# HG changeset patch # User Dremov Kirill (Nokia-D-MSW/Tampere) # Date 1273841244 -10800 # Node ID 98ccebc37403bec230b34c96b15710b92439f87c # Parent 2a9601315dfc8c75033c6fe959be00d6e824c002 Revision: v2.1.24 Kit: 201019 diff -r 2a9601315dfc -r 98ccebc37403 build/Makefile.project --- a/build/Makefile.project Mon May 03 12:27:20 2010 +0300 +++ b/build/Makefile.project Fri May 14 15:47:24 2010 +0300 @@ -166,16 +166,6 @@ PROJECT_DEFINES += RD_JAVA_NGA_ENABLED endif -# Uiaccelerator AlfDrawer is supported since 9.2 -ifndef RD_JAVA_S60_RELEASE_5_0 - ifneq ($(wildcard $(EPOCROOT)epoc32/include/platform/mw/alf/alfdrawer.h),) - RD_JAVA_UI_ALFDRAWER_ENABLED = 1 - endif -endif -ifdef RD_JAVA_UI_ALFDRAWER_ENABLED - PROJECT_DEFINES += RD_JAVA_UI_ALFDRAWER_ENABLED -endif - # Check if USIF is supported ifneq ($(wildcard $(EPOCROOT:\=/)epoc32/include/mw/usif/scr/scr.h),) RD_JAVA_USIF_ENABLED = 1 @@ -188,7 +178,7 @@ # and disables application registrations to AppArc. PROJECT_DEFINES += RD_JAVA_USIF_APP_REG # Following flag enables application notifications to AppArc. - #PROJECT_DEFINES += RD_JAVA_USIF_NOTIFY_APP_ARC + PROJECT_DEFINES += RD_JAVA_USIF_NOTIFY_APP_ARC endif # Java proximity Listener support exsist in 9.2 only(can not be used if 5.0 untill IAD dependecy mentioned) diff -r 2a9601315dfc -r 98ccebc37403 build/buildutils/checkjavapackages.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/build/buildutils/checkjavapackages.py Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +# All rights reserved. +# This component and the accompanying materials are made available +# under the terms of "Eclipse Public License v1.0" +# which accompanies this distribution, and is available +# at the URL "http://www.eclipse.org/legal/epl-v10.html". +# +# Initial Contributors: +# Nokia Corporation - initial contribution. +# +# Contributors: +# +# Description: +# Checks that all the java source files declare a package and that +# the directory within a java source file is located corresponds +# properly to the package. + +import sys, os, re + + +def main(): + + files = [] + + # Create a reg exp matching to "package x.y.z;" with whitespace ignored + regex = re.compile("\\s*package\\s*([\\w.]*);.*", re.IGNORECASE) + + def visitFun(arg, dirname, names): + + # Skip SVN directories + if dirname.find("\\.svn") != -1: + return names + + for f in names: + if not f.endswith(".java"): + continue + + try: + fname = dirname + "\\" + f + file = open(fname) + + package = None + line = file.readline() + while line != "": + result = regex.match(line) + if result != None: + package = result.group(1) + break; + line = file.readline() + + if package != None: + expectedDir = package.replace(".", "\\"); + if not dirname.endswith(expectedDir): + print "Wrong directory:", fname + ", package", package + else: + print "Package statement missing:", fname + + + file.close() + + except IOError: + print "Error reading the file " + fname + + os.path.walk(sys.argv[1], visitFun, files) + + +if __name__ == "__main__": + main() diff -r 2a9601315dfc -r 98ccebc37403 build/buildutils/checkwarnings.py --- a/build/buildutils/checkwarnings.py Mon May 03 12:27:20 2010 +0300 +++ b/build/buildutils/checkwarnings.py Fri May 14 15:47:24 2010 +0300 @@ -33,7 +33,7 @@ # Constants for matching warnings related to deprecation deprecatedStart = "warning: preprocessor #warning directive" - deprecatedSecondLine = "warning: #warning This header file has been deprecated. Will be removed in one of the next SDK releases." + deprecatedSecondLine = "warning: #warning This header file" deprecatedOptionalThirdLine = "warning: (included from:" deprecatedOptionalRest = "warning: " diff -r 2a9601315dfc -r 98ccebc37403 build/buildutils/distribution.policy.s60.configuration.txt --- a/build/buildutils/distribution.policy.s60.configuration.txt Mon May 03 12:27:20 2010 +0300 +++ b/build/buildutils/distribution.policy.s60.configuration.txt Fri May 14 15:47:24 2010 +0300 @@ -18,6 +18,7 @@ /swt/mobile/internal : 7 /internal : 1 /releng : 1 +ROOT/tools : 1 ROOT/javacommons/jvms/j9/s60 : 810 /midprms : 102 /webservices/javasrc : 102 diff -r 2a9601315dfc -r 98ccebc37403 build/buildutils/extractJavaLocFiles_qt.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/build/buildutils/extractJavaLocFiles_qt.py Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,129 @@ +# +# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +# All rights reserved. +# This component and the accompanying materials are made available +# under the terms of "Eclipse Public License v1.0" +# which accompanies this distribution, and is available +# at the URL "http://www.eclipse.org/legal/epl-v10.html". +# +# Initial Contributors: +# Nokia Corporation - initial contribution. +# +# Contributors: +# +# Description: +# +#!/usr/bin/python +# +# This script creates java specific loc zip files from S60 loc zip files +# and also creates a "resources.jar" file where all the java loc files +# are collected. +# +# Usage: extractJavaLocFiles_qt.py +# +# Script reads S60 loc zip files from directory and writes +# "resources.jar" to directory. +# +# This script uses external "jar" command for handling zip files and +# thus is not optimized for speed. +# + +import os, re, shutil, sys, glob, codecs +import traceback +import xml.etree.ElementTree as et +from optparse import OptionParser + +# Base names for java loc files. +JAVA_LOC_FILES = [ + 'javafileconnection', + 'javainstallation', + 'javasensor', + 'javassl', + 'javausermessages', + 'javaapplicationsettings', + 'javaruntimeapplicationsettings' + ] + +# Path for java loc files inside RESOURCES_FILE. +RESOURCES_PATH = os.path.join("resources", "com", "nokia", "mj", "impl") + +def main(): + parser = OptionParser( + usage = "Usage: %prog [args] ") + (opts, args) = parser.parse_args() + + try: + inputDir = args[0] + outputDir = args[1] + resourcesFilename = os.path.join(outputDir, args[2]) + + # Use temporary directory + tmpDir = "tmpdir" + if os.path.exists(tmpDir): + shutil.rmtree(tmpDir) + locDir = os.path.join(tmpDir, RESOURCES_PATH) + os.makedirs(locDir) + + print "Processing loc files from %s to %s" % (inputDir, resourcesFilename) + locFileCount = 0; + + # Go through all Java loc file names, converting the .ts to .loc + for name in JAVA_LOC_FILES: + + # Find all existing ts-files + for ts in glob.glob("%s/%s_*.ts" % (inputDir, name)): + path, filename = os.path.split(ts) + base, ext = os.path.splitext(filename) + loc = os.path.join(locDir, base + ".loc") + print "Converting %s" % ts + writeLoc(loc, readTs(ts)) + locFileCount = locFileCount + 1 + + # Update the target jar with loc-files + if os.path.isfile(resourcesFilename): + os.system("jar ufM " + resourcesFilename + " -C " + tmpDir + " .") + else: + os.system("jar cfM " + resourcesFilename + " -C " + tmpDir + " .") + + print "Processed %d loc files" % (locFileCount) + shutil.rmtree(tmpDir) + + except: + print "Usage: %s " % sys.argv[0] + traceback.print_exc() + sys.exit(1) + +def readTs(filename): + messages = [] + tree = et.parse(filename).getroot() + for message in tree.find("context").findall("message"): + id = message.get("id") + translation = message.find("translation") + + # Sanity check - we have no good plurality support for qt-localisation + if translation.find("numerusform") != None: + raise Exception("Conversion error at %s / %s: numerus form (qt plurality) is not supported" % (filename, id)) + + lengthvariant = translation.find("lengthvariant") + if lengthvariant != None: + text = lengthvariant.text + else: + text = translation.text + + # Sanity check - no newlines in text allowed + if "\n" in text: + raise Exception("Conversion error in %s / %s: newline found" % (filename, id)) + + messages.append((id, text)) + + return messages + +def writeLoc(filename, messages): + loc = codecs.open(filename, "w", "UTF-8") + loc.write(u"CHARACTER_SET UTF8\n") + for id, message in messages: + loc.write(u'#define %s "%s"\n' % (id, message)) + loc.close() + +if __name__ == "__main__": + main() diff -r 2a9601315dfc -r 98ccebc37403 build/loc/01.zip Binary file build/loc/01.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/02.zip Binary file build/loc/02.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/03.zip Binary file build/loc/03.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/04.zip Binary file build/loc/04.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/05.zip Binary file build/loc/05.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/06.zip Binary file build/loc/06.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/07.zip Binary file build/loc/07.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/08.zip Binary file build/loc/08.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/09.zip Binary file build/loc/09.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/10.zip Binary file build/loc/10.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/102.zip Binary file build/loc/102.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/103.zip Binary file build/loc/103.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/129.zip Binary file build/loc/129.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/13.zip Binary file build/loc/13.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/14.zip Binary file build/loc/14.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/14346.zip Binary file build/loc/14346.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/14387.zip Binary file build/loc/14387.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/14412.zip Binary file build/loc/14412.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/14419.zip Binary file build/loc/14419.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/15.zip Binary file build/loc/15.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/157.zip Binary file build/loc/157.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/158.zip Binary file build/loc/158.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/159.zip Binary file build/loc/159.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/16.zip Binary file build/loc/16.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/160.zip Binary file build/loc/160.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/161.zip Binary file build/loc/161.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/17.zip Binary file build/loc/17.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/18.zip Binary file build/loc/18.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/230.zip Binary file build/loc/230.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/25.zip Binary file build/loc/25.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/26.zip Binary file build/loc/26.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/27.zip Binary file build/loc/27.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/28.zip Binary file build/loc/28.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/29.zip Binary file build/loc/29.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/30.zip Binary file build/loc/30.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/31.zip Binary file build/loc/31.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/32.zip Binary file build/loc/32.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/326.zip Binary file build/loc/326.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/327.zip Binary file build/loc/327.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/33.zip Binary file build/loc/33.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/37.zip Binary file build/loc/37.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/39.zip Binary file build/loc/39.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/42.zip Binary file build/loc/42.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/44.zip Binary file build/loc/44.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/45.zip Binary file build/loc/45.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/49.zip Binary file build/loc/49.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/50.zip Binary file build/loc/50.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/51.zip Binary file build/loc/51.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/54.zip Binary file build/loc/54.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/57.zip Binary file build/loc/57.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/58.zip Binary file build/loc/58.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/59.zip Binary file build/loc/59.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/65.zip Binary file build/loc/65.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/67.zip Binary file build/loc/67.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/68.zip Binary file build/loc/68.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/70.zip Binary file build/loc/70.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/76.zip Binary file build/loc/76.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/78.zip Binary file build/loc/78.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/79.zip Binary file build/loc/79.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/83.zip Binary file build/loc/83.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/93.zip Binary file build/loc/93.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/94.zip Binary file build/loc/94.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/96.zip Binary file build/loc/96.zip has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/resources.jar Binary file build/loc/resources.jar has changed diff -r 2a9601315dfc -r 98ccebc37403 build/loc/resources_qt.jar Binary file build/loc/resources_qt.jar has changed diff -r 2a9601315dfc -r 98ccebc37403 build/makefile.javaversion --- a/build/makefile.javaversion Mon May 03 12:27:20 2010 +0300 +++ b/build/makefile.javaversion Fri May 14 15:47:24 2010 +0300 @@ -1,6 +1,6 @@ # Set Java version (must be dot separated, without spaces) ifdef RD_JAVA_S60_RELEASE_5_0_IAD - JAVA_VERSION = 2.1.22 + JAVA_VERSION = 2.1.24 else - JAVA_VERSION = 2.1.22 + JAVA_VERSION = 2.1.24 endif diff -r 2a9601315dfc -r 98ccebc37403 build/symbian_uids.pri --- a/build/symbian_uids.pri Mon May 03 12:27:20 2010 +0300 +++ b/build/symbian_uids.pri Fri May 14 15:47:24 2010 +0300 @@ -29,6 +29,10 @@ } +contains(TEMPLATE,lib):isEmpty(TARGET.UID3):contains(PROJECT_DEFINES,RD_JAVA_S60_RELEASE_10_1) { + contains(TARGET, javacentrep): TARGET.UID3 = 0x2002DCE1 +} + contains(TEMPLATE,lib):isEmpty(TARGET.UID3) { contains(TARGET, eswt): TARGET.UID3 = 0x2002DC93 # On >= 9.2 only @@ -109,7 +113,6 @@ contains(TARGET, javaapplicationsettingsview): TARGET.UID3 = 0x2002DCDF contains(TARGET, javabroadcast): TARGET.UID3 = 0x2002DCE0 contains(TARGET, javastarter): TARGET.UID3 = 0x2002E6A7 -# Free 0x2002DCE1 contains(TARGET, openlcdui): TARGET.UID3 = 0x2002DCE2 contains(TARGET, tckrunner): TARGET.UID3 = 0x2002DCE3 diff -r 2a9601315dfc -r 98ccebc37403 build/templates/10.1.layers.sysdef.xml --- a/build/templates/10.1.layers.sysdef.xml Mon May 03 12:27:20 2010 +0300 +++ b/build/templates/10.1.layers.sysdef.xml Fri May 14 15:47:24 2010 +0300 @@ -12,12 +12,26 @@ qmakeArgs="-r" filter="!sf_build" /> + + + + + + + + + diff -r 2a9601315dfc -r 98ccebc37403 build/templates/9.2.layers.sysdef.xml --- a/build/templates/9.2.layers.sysdef.xml Mon May 03 12:27:20 2010 +0300 +++ b/build/templates/9.2.layers.sysdef.xml Fri May 14 15:47:24 2010 +0300 @@ -9,11 +9,23 @@ - + + + + + + + + + + diff -r 2a9601315dfc -r 98ccebc37403 build/utilities.xml --- a/build/utilities.xml Mon May 03 12:27:20 2010 +0300 +++ b/build/utilities.xml Fri May 14 15:47:24 2010 +0300 @@ -316,6 +316,10 @@ debug="${javac.debug.on}" debuglevel="lines,vars,source" bootclasspath="${bcp}:${int.bcp}:${platform.api.jar}:${public.api.jar}${eswt.jar}"> + + + + diff -r 2a9601315dfc -r 98ccebc37403 inc/build_defines.hrh --- a/inc/build_defines.hrh Mon May 03 12:27:20 2010 +0300 +++ b/inc/build_defines.hrh Fri May 14 15:47:24 2010 +0300 @@ -15,7 +15,7 @@ * */ -#define RD_JAVA_VERSION 2,1,22 +#define RD_JAVA_VERSION 2,1,24 #define RD_JAVA_SYMBIAN_TARGET #define RD_JAVA_S60_RELEASE_10_1 #define RD_JAVA_S60_RELEASE_10_1_ONWARDS @@ -26,9 +26,9 @@ #define RD_JAVA_EPOCALLOWDLLDATA_FIX #define RD_JAVA_HTTP_EMC_ENABLED #define RD_JAVA_NGA_ENABLED -#define RD_JAVA_UI_ALFDRAWER_ENABLED #define SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK #define RD_JAVA_USIF_APP_REG +#define RD_JAVA_USIF_NOTIFY_APP_ARC #define RD_JAVA_PROXIMITY_LISTENER_ENABLED #define RD_JAVA_OPENC_BETA_PATCH #define OPENLCDUI_ENABLED diff -r 2a9601315dfc -r 98ccebc37403 inc/build_defines.pri --- a/inc/build_defines.pri Mon May 03 12:27:20 2010 +0300 +++ b/inc/build_defines.pri Fri May 14 15:47:24 2010 +0300 @@ -13,4 +13,4 @@ # # Description: Generated file - do not edit manually # -PROJECT_DEFINES *= RD_JAVA_SYMBIAN_TARGET RD_JAVA_S60_RELEASE_10_1 RD_JAVA_S60_RELEASE_10_1_ONWARDS RD_JAVA_S60_RELEASE_9_2_ONWARDS RD_JAVA_S60_RELEASE_5_0_ONWARDS RD_JAVA_UI_QT RD_JAVA_STDCPPV5 RD_JAVA_EPOCALLOWDLLDATA_FIX RD_JAVA_HTTP_EMC_ENABLED RD_JAVA_NGA_ENABLED RD_JAVA_UI_ALFDRAWER_ENABLED SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK RD_JAVA_USIF_APP_REG RD_JAVA_PROXIMITY_LISTENER_ENABLED RD_JAVA_OPENC_BETA_PATCH OPENLCDUI_ENABLED RD_JAVA_OPENLCDUI_ENABLED RD_JAVA_INSTALLERUI_ENABLED RD_JAVA_PREWARM RD_JAVA_ADVANCED_TACTILE_FEEDBACK RD_JAVA_APPLICATION_SETTINGS_QT RD_JAVA_MIDPRMS_DB +PROJECT_DEFINES *= RD_JAVA_SYMBIAN_TARGET RD_JAVA_S60_RELEASE_10_1 RD_JAVA_S60_RELEASE_10_1_ONWARDS RD_JAVA_S60_RELEASE_9_2_ONWARDS RD_JAVA_S60_RELEASE_5_0_ONWARDS RD_JAVA_UI_QT RD_JAVA_STDCPPV5 RD_JAVA_EPOCALLOWDLLDATA_FIX RD_JAVA_HTTP_EMC_ENABLED RD_JAVA_NGA_ENABLED SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK RD_JAVA_USIF_APP_REG RD_JAVA_USIF_NOTIFY_APP_ARC RD_JAVA_PROXIMITY_LISTENER_ENABLED RD_JAVA_OPENC_BETA_PATCH OPENLCDUI_ENABLED RD_JAVA_OPENLCDUI_ENABLED RD_JAVA_INSTALLERUI_ENABLED RD_JAVA_PREWARM RD_JAVA_ADVANCED_TACTILE_FEEDBACK RD_JAVA_APPLICATION_SETTINGS_QT RD_JAVA_MIDPRMS_DB diff -r 2a9601315dfc -r 98ccebc37403 inc/java.txt --- a/inc/java.txt Mon May 03 12:27:20 2010 +0300 +++ b/inc/java.txt Fri May 14 15:47:24 2010 +0300 @@ -1,1 +1,1 @@ -2.1.22 +2.1.24 diff -r 2a9601315dfc -r 98ccebc37403 inc/project_defines.hrh --- a/inc/project_defines.hrh Mon May 03 12:27:20 2010 +0300 +++ b/inc/project_defines.hrh Fri May 14 15:47:24 2010 +0300 @@ -25,9 +25,9 @@ MACRO RD_JAVA_EPOCALLOWDLLDATA_FIX MACRO RD_JAVA_HTTP_EMC_ENABLED MACRO RD_JAVA_NGA_ENABLED -MACRO RD_JAVA_UI_ALFDRAWER_ENABLED MACRO SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK MACRO RD_JAVA_USIF_APP_REG +MACRO RD_JAVA_USIF_NOTIFY_APP_ARC MACRO RD_JAVA_PROXIMITY_LISTENER_ENABLED MACRO RD_JAVA_OPENC_BETA_PATCH MACRO OPENLCDUI_ENABLED diff -r 2a9601315dfc -r 98ccebc37403 java_stubs/javaregistry/clientserver/client/inc/javaregconverter.h --- a/java_stubs/javaregistry/clientserver/client/inc/javaregconverter.h Mon May 03 12:27:20 2010 +0300 +++ b/java_stubs/javaregistry/clientserver/client/inc/javaregconverter.h Fri May 14 15:47:24 2010 +0300 @@ -209,7 +209,7 @@ * @param aCertChains [out] The method converts the unicode descriptors * into this RPointerArray. */ - IMPORT_C static void JavaRegConverter::GetUnicodeDescriptorsL( + IMPORT_C static void GetUnicodeDescriptorsL( const TDesC& aValue, RPointerArray& aDescriptors); /** @@ -224,7 +224,7 @@ * @param aDes [out] Descriptor parameter, storing, and the returning * the certificate chains. */ - IMPORT_C static void JavaRegConverter::StoreUnicodeDescriptorsL( + IMPORT_C static void StoreUnicodeDescriptorsL( const RPointerArray& aValue, HBufC*& aDes); }; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/fileutils/javasrc/com/nokia/mj/impl/fileutils/FileUtility.java --- a/javacommons/fileutils/javasrc/com/nokia/mj/impl/fileutils/FileUtility.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/fileutils/javasrc/com/nokia/mj/impl/fileutils/FileUtility.java Fri May 14 15:47:24 2010 +0300 @@ -1289,6 +1289,35 @@ return _delete(iTarget.getFullPath()); } + + /** + * Deletes the file or directory denoted by this pathname. If this pathname + * denotes a directory, then the directory must be empty in order to be + * deleted. Deletes the file or directory even if it is marked as read-only. + *

+ * All open input and output streams are automatically flushed and closed. + * Attempts to further use those streams result in an IOException. The + * FileUtility instance object remains available for use. + * + * @return true if and only if the file or directory is successfully + * deleted; false otherwise + * @throws SecurityException + * if access was denied to the file/directory + */ + public boolean forceDelete() throws SecurityException + { + + // Close input and output Streams if created. + // Found in StreamConnectionBase + + if (iStreamHandler != null) + { + iStreamHandler.closeInputStreams(); + iStreamHandler.closeOutputStreams(); + } + + return _delete(iTarget.getFullPath()); + } /** * Renames the selected file or directory to a new name in the same diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc.linux/com/nokia/mj/impl/file/FileAccessHelper.java --- a/javacommons/gcfprotocols/file/javasrc.linux/com/nokia/mj/impl/file/FileAccessHelper.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc.linux/com/nokia/mj/impl/file/FileAccessHelper.java Fri May 14 15:47:24 2010 +0300 @@ -25,8 +25,7 @@ */ public class FileAccessHelper implements FileConstants { - public static boolean accessAllowed(String aPath, String aIntent, - String aDomain, boolean aIsOpening) + public static boolean accessAllowed(String aPath, String aDomain) { return true; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileAccessHelper.java --- a/javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileAccessHelper.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileAccessHelper.java Fri May 14 15:47:24 2010 +0300 @@ -20,6 +20,9 @@ import java.util.Hashtable; import java.util.Vector; import com.nokia.mj.impl.rt.support.ApplicationInfo; +import com.nokia.mj.impl.fileutils.DriveInfo; +import com.nokia.mj.impl.fileutils.DriveUtilities; + public class FileAccessHelper implements FileConstants { @@ -32,35 +35,14 @@ private static String[] iRestrictedPathList; private static String[] iForbiddenPathList; - static - { - // Populate forbidden path list. - Vector forbidden = FileSystemUtils.getForbiddenPaths(); - iForbiddenPathList = new String[forbidden.size()]; - for (int index = 0; index < forbidden.size(); index++) - { - iForbiddenPathList[index] = (String) forbidden.elementAt(index); - } - - // Populate restricted path list. - Vector restricted = FileSystemUtils.getRestrictedPaths(); - iRestrictedPathList = new String[restricted.size() + 1]; - for (int index = 0; index < restricted.size(); index++) - { - iRestrictedPathList[index] = (String) restricted.elementAt(index); - } - // Add midlet's private directory also to restricted path list. - iRestrictedPathList[restricted.size()] = FileSystemUtils - .getAppPrivateDir(); - } + // getMidpRoot get the midp private directory such as "/private/102033E6" + private static String iMidpRoot = FileSystemUtils.getMidpRoot().toLowerCase(); /** * Checks to see if the application has access to a specific path. * * @param aPath * path which the application is trying to access. - * @param aIntent - * mode in which the application wants to access the target. * @param aDomain * domain of the application * @param aIsOpening @@ -68,358 +50,33 @@ * connection. * @return true in case access is allowed. False otherwise */ - public static boolean accessAllowed(String aPath, String aIntent, - String aDomain, boolean aIsOpening) + public static boolean accessAllowed(String aPath, String aDomain) { FileLogger.Log("FileAccessHelper.accessAllowed: Checking access: \n"); + + if(aPath.endsWith("/") == false) + aPath += "/"; if (isHomeDir(aPath)) { return true; } - if (isForbidden(aPath)) - { - return false; - } - - if (isIllegalAccessToRestrictedDir(aPath, aIntent, aIsOpening, aDomain)) - { - return false; - } - - if (aDomain.equals(ApplicationInfo.MANUFACTURER_DOMAIN)) - { - return manufacturerDomainChecks(aPath, aIntent, aIsOpening); - } - else - { - return otherDomainChecks(aPath, aIntent, aIsOpening); - } - } - - /** - * To be used in case of list. If list is done on a directory that is equal - * to, or higher in path hierarchy than one of the restricted paths, then we - * need to check for access for all files, if not, then no need. - */ - public static boolean isDirRestricted(String aPath) - { - for (int index = 0; index < iRestrictedPathList.length; index++) - { - int matchResult = matchPaths(aPath, iRestrictedPathList[index]); - if ((matchResult != PATHS_NO_MATCH) - && (matchResult != PATH_BELOWIN_HIERARCHY)) - { - return true; - } - } - return false; - } - - /** - * Checks to see if the path being accessed in forbidden. - * - * @param aPath - * path being accessed - * @return true in case the path is forbidden, false otherwise - */ - private static boolean isForbidden(String aPath) - { - for (int index = 0; index < iForbiddenPathList.length; index++) + // The basic assumption for this check is + // always drive name is a single character. + if (aPath.substring(2).toLowerCase().startsWith(iMidpRoot)) { - int matchPathResult = matchPaths(aPath, iForbiddenPathList[index]); - - // Forbidden paths should match exactly or should be such that the - // path must be lower in hierarchy. - // Example: e:/system is forbidden, e:/ is not. - // e:/system is forbidden, e:/system/dir is also forbidden - if ((matchPathResult == PATHS_EQUAL) - || (matchPathResult == PATH_BELOWIN_HIERARCHY)) - { - return true; - } - } - return false; - } - - /** - * Checks if the access to restricted paths is being made in correct intent - * based on the domain. - * - * @param aPath - * path of the file/directory being accessed - * @param aIntent - * intent with which it is being accessed (read or write) - * @param aOpening - * set to true in case it is being used by Connector.open or - * setFileConnection. Both are considered as open and not as - * acutal read or write operations. - * @param aDomain - * domain of the application. - * @return true in case there is an access violation, false if the access is - * allowed. - */ - public static boolean isIllegalAccessToRestrictedDir(String aPath, - String aIntent, boolean aOpening, String aDomain) - { - for (int index = 0; index < iRestrictedPathList.length; index++) - { - int matchResult = matchPaths(aPath, iRestrictedPathList[index]); - if ((matchResult != PATHS_NO_MATCH) - && (matchResult != PATH_BELOWIN_HIERARCHY)) - { - if (aIntent.equals(INTENT_WRITE) - || aIntent.equals(INTENT_READ_WRITE)) - { - if (!aOpening) - { - return true; - } - } - } - } - return false; - } - - /** - * Performs manufacturer domain specific checks. Manufacturer domain apps - * are not allowed to access any path in C:/private apart from its private - * directory. Other checks are forbidden directories and restricted paths. - * This is done before (accessAllowed()) So, no need to check once again. - * - * @param aPath - * path which is being accessed - * @param aIntent - * intent with which access is being made. read, write - * @param aIsOpening - * true in case its an open operation (open, setFileConnection) - * @return true in case access is allowed. false otherwise. - */ - public static boolean manufacturerDomainChecks(String aPath, - String aIntent, boolean aIsOpening) - { - // Check if it is private directory. - if (aPath.indexOf(PATH_PRIVATE) == 3) - { - if (matchPaths(aPath, FileSystemUtils.getAppPrivateDir()) == PATHS_NO_MATCH) + // Allowed only for Manufacturer domain. + if (aDomain.equals(ApplicationInfo.MANUFACTURER_DOMAIN) == false) { return false; } - } - return true; - } - - /** - * Performs domains other than manufacturer domain. - * - * @param aPath - * path which is being accessed - * @param aIntent - * intent with which access is being made. read, write - * @param aIsOpening - * true in case its an open operation (open, setFileConnection) - * @return true in case access is allowed. false otherwise. - */ - private static boolean otherDomainChecks(String aPath, String aIntent, - boolean aIsOpening) - { - if (aPath.length() < 3) - { - // Path will be valid. This will be only in case file:///c: is given - aPath += "/"; - } - - String rom = FileSystemUtils.getRomDrive().toLowerCase() - .substring(0, 2); - String temp = FileSystemUtils.getTemporaryDrive().toLowerCase() - .substring(0, 2); - - if (aPath.toLowerCase().startsWith(rom) - || aPath.toLowerCase().startsWith(temp)) - { - return false; - } - - // Other domains can access only below restricted paths or - // in other drives. - for (int index = 0; index < iRestrictedPathList.length; index++) - { - int matchResult = matchPaths(aPath, iRestrictedPathList[index]); - - if ((matchResult != PATH_BELOWIN_HIERARCHY) - && (matchResult != PATHS_NO_MATCH)) - { - if ((!aIntent.equals(INTENT_READ)) && (!aIsOpening)) - { - // Anything other than read operation on par or above - // restricted path hierarchy is not allowed when not opening - return false; - } - } - } - - if (partialMatchWithRestrictedPaths(aPath)) - { - return false; + } return true; } - private static boolean partialMatchWithRestrictedPaths(String aPath) - { - String path1 = aPath; - boolean initialNoMatch = true; - - // Partial match is only when path is not a substring initially, - // but when stripped, becomes a substring of one of the restricted paths - for (int index = 0; index < iRestrictedPathList.length; index++) - { - int matchResult = matchPaths(aPath, iRestrictedPathList[index]); - if (matchResult == PATH_BELOWIN_HIERARCHY - || matchResult == PATH_ABOVEIN_HIERARCHY - || matchResult == PATHS_EQUAL) - { - return false; - } - } - - if (path1.length() > 3) - { - path1 = path1.substring(0, path1.lastIndexOf('/')); - } - - // path1 is stripped to know in case the file is being created inside - // root. - while (path1.length() > 3) - { - for (int index = 0; index < iRestrictedPathList.length; index++) - { - if (iRestrictedPathList[index].toLowerCase().startsWith( - path1.toLowerCase())) - { - return true; - } - } - path1 = path1.substring(0, path1.lastIndexOf('/')); - } - - // C:/data/somefile should be matched with c:/data/images,c:/data/videos - // and must return true but c:/data or c:/ must not return as true - return false; - } - - /** - * Resolves a path to a one of the following categories: - * - *

-     * PUBLIC_DIRS - C:/Data/Images
-     *               C:/Data/Videos
-     *               C:/Data/Graphics
-     *               C:/Data/Sounds
-     *               C:/Data/Music
-     *               C:/Data/Recordings and all files therein
-     * HOME_DIR - App's private directory
-     * PRIVATE_USER_FILES - All files and directories higher in path hierarchy
-     *                      of PUBLIC_DIRS
-     * SYSTEM_FILES - Z drive
-     * 
- * - * @param aPath - * path that has to be mapped to a particular category. - * @return category of the path specified.
One of the following: - * SYSTEM_FILES, PRIVATE_USER_FILES, PUBLIC_DIRS, HOME_DIR - */ - public static String getCategory(String aPath) - { - FileLogger.Log("+ FileAccessHelper: getCategory: " + aPath); - // SYSTEM_FILES, PRIVATE_USER_FILES, PUBLIC_DIRS, HOME_DIR - if (aPath.equals(SYSTEM_FILES) || aPath.equals(PRIVATE_USER_FILES) - || aPath.equals(PUBLIC_DIRS) || aPath.equals(HOME_DIR) - || aPath.equals(RESTRICTED_PUBLIC_FILES)) - { - // if it is already mapped - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + aPath); - return aPath; - } - - if (aPath.equals("")) - { - // Used in case of FileSystemRegistry - return PUBLIC_DIRS; - } - - // First check for Home directory. Restricted paths list contains - // app's private directory too. - if (isHomeDir(aPath)) - { - return HOME_DIR; - } - - int matchResult = PATHS_NO_MATCH; - // Paths below restricted paths in hierarchy are part of Public files - // Paths above in hierarchy are part of private used files. - for (int index = 0; index < iRestrictedPathList.length; index++) - { - matchResult = matchPaths(aPath, iRestrictedPathList[index]); - if (PATH_BELOWIN_HIERARCHY == matchResult) - { - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + PUBLIC_DIRS); - return PUBLIC_DIRS; - } - - if (PATHS_EQUAL == matchResult) - { - return PUBLIC_DIRS; - } - - // Do we need this at all? Restricted PUBLIC Files can be removed - if (PATH_ABOVEIN_HIERARCHY == matchResult) - { - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + PUBLIC_DIRS); - return PUBLIC_DIRS; - } - } - - String rom = FileSystemUtils.getRomDrive().toLowerCase() - .substring(0, 2); - String temp = FileSystemUtils.getTemporaryDrive().toLowerCase() - .substring(0, 2); - - if (aPath.toLowerCase().startsWith(rom) - || aPath.toLowerCase().startsWith(temp)) - { - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + SYSTEM_FILES); - return SYSTEM_FILES; - - } - else if (aPath.toLowerCase().startsWith( - FileSystemUtils.getDefaultRoot().toLowerCase())) - { - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + RESTRICTED_PUBLIC_FILES); - // It is however known that the default root of the device can - // change. - return RESTRICTED_PUBLIC_FILES; - } - else if ((aPath.toLowerCase().indexOf(PATH_PRIVATE) == 3) - || (aPath.toLowerCase().indexOf(PATH_SYSTEM) == 3)) - { - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + SYSTEM_FILES); - return SYSTEM_FILES; - } - - FileLogger.Log("- FileAccessHelper: getCategory: returning: " - + PUBLIC_DIRS); - return PUBLIC_DIRS; - } - /** * Checks to see if the specified path is same as application's private * directory. @@ -427,90 +84,12 @@ private static boolean isHomeDir(String aPath) { String appPrivateDir = FileSystemUtils.getAppPrivateDir(); - if (aPath.equalsIgnoreCase(appPrivateDir)) - { - return true; - } - if (aPath.startsWith(appPrivateDir)) + + if (aPath.toLowerCase().startsWith(appPrivateDir.toLowerCase())) { return true; } return false; } - - /** - * Checks to see if a file/directory can be created within the specidied - * path. - * - * @param aPath - * directory within which the application intends to create a - * file. - * @param aDomain - * domain of the application - * @return true in case access is allowed, false otherwise. - */ - public static boolean isCreateAllowedWithinDir(String aPath, String aDomain) - { - if (aDomain.equals(ApplicationInfo.MANUFACTURER_DOMAIN)) - { - return true; - } - - boolean allowed = false; - - if (!aPath.startsWith(FileSystemUtils.getDefaultRoot())) - { - return true; - } - - for (int index = 0; index < iRestrictedPathList.length; index++) - { - String path = iRestrictedPathList[index]; - int matchResult = matchPaths(aPath, path); - // Domains other than manufacturer are allowed to create content - // only within restricted directories. - if ((PATHS_EQUAL == matchResult) - || (PATH_BELOWIN_HIERARCHY == matchResult)) - { - allowed = true; - break; - } - } - return allowed; - } - - /** - * Tries to match paths. Returns how "path2" is related to "path1". Checks if - * the path is above or below in path hierarchy. Also checks to see if paths - * are same or are totally different. - */ - private static int matchPaths(String aPath1, String aPath2) - { - // Strip trailing slash in case its present. - String path1 = aPath1.endsWith("/") ? aPath1.substring(0, aPath1 - .length() - 1) : aPath1; - - String path2 = aPath2.endsWith("/") ? aPath2.substring(0, aPath2 - .length() - 1) : aPath2; - - // In case both paths are the same. - if (path1.equalsIgnoreCase(path2)) - { - return PATHS_EQUAL; - } - - // Check if path1 is higher in path hierarchy - if (path2.toLowerCase().startsWith(path1.toLowerCase())) - { - return PATH_ABOVEIN_HIERARCHY; - } - - if (path1.toLowerCase().startsWith(path2.toLowerCase())) - { - return PATH_BELOWIN_HIERARCHY; - } - - return PATHS_NO_MATCH; - } } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileSystemUtils.java --- a/javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileSystemUtils.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc.s60/com/nokia/mj/impl/file/FileSystemUtils.java Fri May 14 15:47:24 2010 +0300 @@ -87,11 +87,7 @@ for (int index = 0; index < drives.length; index++) { String toAdd = drives[index].iRootPath.replace('\\', '/'); - if (FileAccessHelper.accessAllowed(toAdd, - FileConstants.INTENT_READ, getProtectionDomain(), false)) - { - roots.addElement(toAdd); - } + roots.addElement(toAdd); } return roots; } @@ -222,11 +218,7 @@ for (int index = 0; index < drives.length; index++) { String toAdd = drives[index].iRootPath.replace('\\', '/'); - if (FileAccessHelper.accessAllowed(toAdd, - FileConstants.INTENT_READ, getProtectionDomain(), false)) - { - roots.addElement(drives[index]); - } + roots.addElement(drives[index]); } Vector rootNames = new Vector(); @@ -327,36 +319,6 @@ return FileConnectionTexts.get(propKey); } - public static Vector getForbiddenPaths() - { - String pathString = _getForbiddenPaths(); - String[] pathArray = Tokenizer.split(pathString, "*"); - Vector paths = new Vector(); - - for (int index = 0; index < pathArray.length - 1; index++) - { - String toAdd = pathArray[index]; - toAdd = toAdd.replace('\\', '/'); - paths.addElement(toAdd); - } - return paths; - } - - public static Vector getRestrictedPaths() - { - String pathString = _getRestrictedPaths(); - String[] pathArray = Tokenizer.split(pathString, "*"); - Vector paths = new Vector(); - - for (int index = 0; index < pathArray.length - 1; index++) - { - String toAdd = pathArray[index]; - toAdd = toAdd.replace('\\', '/'); - paths.addElement(toAdd); - } - return paths; - } - public static String getAppPrivateDir() { String appPrivateDir = iAppInfo.getRootPath(); @@ -365,6 +327,14 @@ return appPrivateDir; } + public static String getMidpRoot() + { + String midpRoot = _getMidpRoot(); + + midpRoot = midpRoot.replace('\\', '/'); + return midpRoot; + } + private static native String _getMemoryCardDrivePath(); private static native String _getTemporaryDrivePath(); @@ -375,7 +345,5 @@ private static native String _getPathOfProperty(int value, boolean addRoot); - private static native String _getForbiddenPaths(); - - private static native String _getRestrictedPaths(); + private static native String _getMidpRoot(); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileConnectionImpl.java --- a/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileConnectionImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileConnectionImpl.java Fri May 14 15:47:24 2010 +0300 @@ -96,7 +96,7 @@ } // Check access. - checkAccess(actual, aMode, true); + checkAccess(actual); // Go ahead to prompt the user checkSecurityPermission(actual, aMode); @@ -175,22 +175,6 @@ } } - /** - * Checks access to a specified path given its absolute path and the mode in - * which the connection has been opened. - * - * @param aAbsolutePath - * path of the connection - * @param aMode - * mode in which the connection has been opened. - * @throws SecurityException - * in case access was allowed for the application for the given - * intent and target. - */ - private static void checkAccess(String aAbsolutePath, int aMode) - { - checkAccess(aAbsolutePath, aMode, false); - } /** * Checks access to a specified path given its absolute path and the mode in @@ -198,37 +182,15 @@ * * @param aAbsolutePath * path of the connection - * @param aMode - * mode in which the connection has been opened. - * @param aIsOpening - * specifies if the access check is being made on a method that - * is considered as open operation (setFileConnection and - * Connector.open) * @throws SecurityException * in case access was allowed for the application for the given * intent and target. */ - private static void checkAccess(String aAbsolutePath, int aMode, - boolean aIsOpening) + private static void checkAccess(String aAbsolutePath) { - FileLogger.Log("FileConnectionImpl: Check Access to " + aAbsolutePath - + " in " + aMode + " mode"); - - String modeString; - switch (aMode) - { - case Connector.READ: - modeString = FileAccessHelper.INTENT_READ; - break; - case Connector.WRITE: - modeString = FileAccessHelper.INTENT_WRITE; - break; - default: - modeString = FileAccessHelper.INTENT_READ_WRITE; - } - - if (!(FileAccessHelper.accessAllowed(aAbsolutePath, modeString, - FileSystemUtils.getProtectionDomain(), aIsOpening))) + FileLogger.Log("FileConnectionImpl: Check Access to " + aAbsolutePath ); + + if (!FileAccessHelper.accessAllowed(aAbsolutePath,FileSystemUtils.getProtectionDomain())) { // Access to the specified path not allowed. // Throw Security Exception @@ -257,15 +219,6 @@ String domain = FileSystemUtils.getProtectionDomain(); - // We need to check if we have access to base directory and not the file - // itself :-) - if (!FileAccessHelper.isCreateAllowedWithinDir(iFileUtility.getPath(), - domain)) - { - throw new SecurityException("Permission denied: " - + iFileUtility.getAbsolutePath()); - } - if (!iFileUtility.createNewFile()) { FileLogger.WLog("FileConnectionImpl: File Creation failed. " @@ -284,7 +237,7 @@ checkConnection(); checkConnectionMode(Connector.READ); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); if (!iFileUtility.rename(aName)) { @@ -313,7 +266,7 @@ { checkConnection(); checkConnectionMode(Connector.READ); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); FileLogger.Log("FileConnectionImpl: mkdir(): " + iFileUtility.getAbsolutePath()); @@ -333,7 +286,7 @@ { checkConnection(); checkConnectionMode(Connector.READ); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); FileLogger.Log("FileConnectionImpl: delete(): " + iFileUtility.getAbsolutePath()); @@ -489,7 +442,7 @@ public void setReadable(boolean aReadable) throws IOException { checkConnection(); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); checkConnectionMode(Connector.READ); iFileUtility.setReadable(aReadable); } @@ -500,7 +453,7 @@ public void setWritable(boolean aWritable) throws IOException { checkConnection(); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); checkConnectionMode(Connector.READ); iFileUtility.setWritable(aWritable); } @@ -511,7 +464,7 @@ public void setHidden(boolean aHidden) throws IOException { checkConnection(); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); checkConnectionMode(Connector.READ); iFileUtility.setHidden(aHidden); } @@ -552,7 +505,6 @@ String domain = FileSystemUtils.getProtectionDomain(); // Check if read access is allowed to all contents in the list. - boolean accessCheckNeeded = FileAccessHelper.isDirRestricted(parent); boolean accessAllowed = true; for (int index = 0; index < fileList.length; index++) @@ -562,12 +514,8 @@ if (FileUtility.matchString(filter.toLowerCase(), fileList[index])) { // If it passes the filter, check if midlet has access. - // if check access is true, then accessAllowed is not checked. - if (accessCheckNeeded) - { - accessAllowed = FileAccessHelper.accessAllowed(fullPath, - FileConstants.INTENT_READ, domain, true); - } + accessAllowed = FileAccessHelper.accessAllowed(fullPath, + domain); if (accessAllowed) { @@ -585,7 +533,7 @@ { checkConnection(); checkConnectionMode(Connector.READ); - checkAccess(iFileUtility.getAbsolutePath(), Connector.WRITE); + checkAccess(iFileUtility.getAbsolutePath()); iFileUtility.truncate(aByteOffset); } @@ -654,7 +602,7 @@ // See if access is allowed. True because setting to new target is // as good as opening. - checkAccess(tempTarget.getAbsolutePath(), iMode, true); + checkAccess(tempTarget.getAbsolutePath()); checkSecurityPermission(tempTarget.getAbsolutePath(), iMode); // if we reach here, it is fine :-) @@ -701,7 +649,7 @@ // See if access is allowed. True because setting to new target is // as good as opening. - checkAccess(tempTarget.getAbsolutePath(), iMode, true); + checkAccess(tempTarget.getAbsolutePath()); checkSecurityPermission(tempTarget.getAbsolutePath(), iMode); // If no exception is thrown, its safe to set connection diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileInternalPermission.java --- a/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileInternalPermission.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileInternalPermission.java Fri May 14 15:47:24 2010 +0300 @@ -86,24 +86,7 @@ if (PermissionBase.matchActions(per.getActions(), intent)) { - if (getTarget().equals("*")) - { - // IN case all are allowed. - return true; - } - - if (this.targetName.equalsIgnoreCase(per.getTarget())) - { - return true; - } - else - { - return getCategory().equals(per.getCategory()); - } - } - else - { - return false; + return true; } } @@ -165,11 +148,6 @@ return null; } - public String getCategory() - { - return FileAccessHelper.getCategory(targetName); - } - public String getTarget() { return targetName; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileSystemRegistryImpl.java --- a/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileSystemRegistryImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/javasrc/com/nokia/mj/impl/file/FileSystemRegistryImpl.java Fri May 14 15:47:24 2010 +0300 @@ -72,12 +72,7 @@ for (int index = 0; index < rootVector.size(); index++) { - if (FileAccessHelper.accessAllowed( - (String) rootVector.elementAt(index), - FileConstants.INTENT_READ, domain, false)) - { retValue.addElement(rootVector.elementAt(index)); - } } FileLogger.Log("<-- FileSystemRegistry.listRoots()"); diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/file/src.s60/filesystemutilsjni.cpp --- a/javacommons/gcfprotocols/file/src.s60/filesystemutilsjni.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/file/src.s60/filesystemutilsjni.cpp Fri May 14 15:47:24 2010 +0300 @@ -23,6 +23,7 @@ #include "javasymbianoslayer.h" #include "s60commonutils.h" #include "logger.h" +#include "javaoslayer.h" #include "systempropertyprovider.h" #include "com_nokia_mj_impl_file_FileSystemUtils.h" @@ -108,48 +109,14 @@ /* * Class: com_nokia_mj_impl_file_FileSystemUtils - * Method: _getForbiddenPaths + * Method: _getMidpRoot * Signature: ()Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_com_nokia_mj_impl_file_FileSystemUtils__1getForbiddenPaths -(JNIEnv *aJni, jclass) +JNIEXPORT jstring JNICALL Java_com_nokia_mj_impl_file_FileSystemUtils__1getMidpRoot +(JNIEnv *aEnv, jclass) { - JELOG2(EJavaFile); - jstring str = 0; - HBufC* names = 0; - - SystemPropertyProvider::GetForbiddenPaths(names); - TPtrC namePtr(names->Des()); - if (0 != names) - { - str = S60CommonUtils::NativeToJavaString(*aJni, namePtr); - delete names; - } - return str; -} + std::string path; + java::util::JavaOsLayer::getMidpRoot(path); -/* - * Class: com_nokia_mj_impl_file_FileSystemUtils - * Method: _getRestrictedPaths - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_com_nokia_mj_impl_file_FileSystemUtils__1getRestrictedPaths -(JNIEnv *aJni, jclass) -{ - JELOG2(EJavaFile); - jstring str = 0; - HBufC* names = 0; - - TRAPD(err, SystemPropertyProvider::GetRestrictedPathsL(names)); - - if (KErrNone == err) - { - TPtrC namePtr(names->Des()); - if (0 != names) - { - str = S60CommonUtils::NativeToJavaString(*aJni, namePtr); - delete names; - } - } - return str; + return aEnv->NewStringUTF((const char*)(path.c_str())); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/inc.s60/nativehttpsession.h --- a/javacommons/gcfprotocols/http/inc.s60/nativehttpsession.h Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/inc.s60/nativehttpsession.h Fri May 14 15:47:24 2010 +0300 @@ -42,7 +42,7 @@ void doReadCallback(TInt aStatus,jobject &aPeer); void vmAttached(); - ~NativeHttpSession(); + private: NativeHttpSession(); @@ -51,7 +51,7 @@ private: TInt ExecuteCreateHttpSessionL(int aSelf, TInt aType, TInt aAPNId, TInt* apnerr); - void ExecuteCloseHttpSessionL(int aSelf); + private: HttpSessionClient* iHttpSessionClient; TInt iSuiteId; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/javasrc.s60/com/nokia/mj/impl/http/HttpConnectionNative.java --- a/javacommons/gcfprotocols/http/javasrc.s60/com/nokia/mj/impl/http/HttpConnectionNative.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/javasrc.s60/com/nokia/mj/impl/http/HttpConnectionNative.java Fri May 14 15:47:24 2010 +0300 @@ -194,8 +194,7 @@ iTransactionBlock = new BlockingOperation(); iNativeDataReadyForRead = new BlockingOperation(); iNativeDataReadyForRead.setResult(BlockingOperation.BLOCKED); - iFinalizer = registerForFinalization(); - setShutdownListener(); + iFinalizer = registerForFinalization(); Logger.LOG(Logger.ESOCKET, Logger.EInfo, "- HttpConnectionNative new "); ApplicationInfo appInfo = ApplicationInfo.getInstance(); @@ -245,65 +244,19 @@ }; } - /** - * Registers for shutdown listener - */ - private void setShutdownListener() - { - // if shutdown for first connection has been called, then dont delete - // session again - if (iIsSessionDeleted == true) - return; - - iIsSessionDeleted = true; - - // Get the instance of ApplicationUtils. - ApplicationUtils appUtils = ApplicationUtils.getInstance(); - - // Get the name of the application. - appUtils.addShutdownListener(new ShutdownListener() - { - public void shuttingDown() - { - Logger.LOG(Logger.ESOCKET, Logger.EInfo, - "++HttpConnectionNative::shuttingDown ,this = " + this); - try - { - // Do cleaning... - close(); - } - catch (IOException ex) - { - // catch the exception and call dispose - } - - if (iNativeHttpSessionHandle != 0) - { - _dispose(iNativeHttpSessionHandle); - iNativeHttpSessionHandle = 0; - } - } - - }); - } public void doFinalize() { Logger.LOG(Logger.ESOCKET, Logger.EInfo, "++HttpConnectionNative::doFinalize "); - // if finalization for first connection has been called, then dont - // delete session again - if (iIsSessionDeleted == true) - return; - - iIsSessionDeleted = true; - - if (iNativeHttpSessionHandle != 0) + try { - _dispose(iNativeHttpSessionHandle); - iNativeHttpSessionHandle = 0; + close(); } - + catch(Exception e) + { + + } Logger.LOG(Logger.ESOCKET, Logger.EInfo, "--HttpConnectionNative::doFinalize "); } @@ -920,6 +873,7 @@ case CONNECTED: case REQUEST_HEADERS_SENT: ensureResponse(); + break; default: // No-op @@ -1350,7 +1304,6 @@ private native String[] _getResponse(int aNativeTransactionHande); private native int _getBytes(int aNativeTransactionHande, byte[] aBuffer, int aLength); - private native void _dispose(int iNativeHttpSessionHandle); private native void _closeTransaction(int aNativeTransactionHande); private native int _available(int aNativeTransactionHande); private native String _getUserAgentHeaderValue(boolean aMidpRuntime); diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/src.s60/chttptransactionclient.cpp --- a/javacommons/gcfprotocols/http/src.s60/chttptransactionclient.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/src.s60/chttptransactionclient.cpp Fri May 14 15:47:24 2010 +0300 @@ -295,25 +295,6 @@ { TInt err = headers.GetRawField(fieldNameStr,rawFldPtr); - // Work around for DRM download -// RStringF contentType = strP.StringF(HTTP::EContentType,RHTTPSession::GetTable()); -// if (fieldNameStr == contentType) -// { -// LOG(ESOCKET,EInfo,"content type header is present"); -// TInt index = rawFldPtr.Match(KDRMHeader1); -// // LOG1(ESOCKET,EInfo,"rawFldPtr = %s ",rawFldPtr.str()); -// LOG1(ESOCKET,EInfo,"index of drm header is = %d",index); -// if(index == 0) -// { -// iDrmDownload = true; -// } -// else -// { -// index = rawFldPtr.Match(KDRMHeader2); -// if(index == 0) -// iDrmDownload = true; -// } -// } if (err==KErrNone) { rawFieldLength += fieldNameStr.DesC().Length(); @@ -332,11 +313,7 @@ while (!it.AtEnd()); } -// RHTTPResponse CHttpTransactionClient::GetResponseL() -// { -// LOG(ESOCKET,EInfo,"CHttpTransactionClient::GetResponseL"); -// return iTransaction.Response(); -// } + /* * Returns the total number of bytes read into the buffer, * or -1 if there is no more data because the end of the stream @@ -738,7 +715,6 @@ void CHttpTransactionClient::CloseTransaction() { - //__ASSERT_DEBUGCOMP(iJavaWaitingOnCallBack==EFalse, User::Panic(_L("Http Java Waiting on notification"), KErrGeneral )); LOG(ESOCKET,EInfo,"CHttpTransactionClient::CloseTransaction + "); iClosing=ETrue; if (!iReleasedData) diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/src.s60/nativehttpsession.cpp --- a/javacommons/gcfprotocols/http/src.s60/nativehttpsession.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/src.s60/nativehttpsession.cpp Fri May 14 15:47:24 2010 +0300 @@ -40,37 +40,6 @@ } -NativeHttpSession::~NativeHttpSession() -{ - JELOG2(ESOCKET); - - //delete iHttpSessionClient; - TInt handle = reinterpret_cast(this); - - CallMethod(this, &NativeHttpSession::ExecuteCloseHttpSessionL,handle, this); - - if (iMonitor != NULL) - iMonitor->wait(); - - iHttpSessionClient = NULL; - stopServer(); - - delete iMonitor; - iMonitor = NULL; - -} - -void NativeHttpSession::ExecuteCloseHttpSessionL(int /*aSelfhandle*/) -{ - if (iHttpSessionClient !=NULL) - { - delete iHttpSessionClient; - iHttpSessionClient = NULL; - } - - iMonitor->notify(); - -} /** * This uses the TConstructor class to ensure safe construction of the CJavaEventSource * subclass, and then returns the Java handle to the object directly, hence the @@ -80,20 +49,10 @@ TInt NativeHttpSession::NewL(JNIEnv& aJni, jobject aPeer,/* TJavaEventServer aServer,*/ TInt aType, TInt aAPNId, TInt * aErr, TInt * apnerr) { NativeHttpSession* self = new(ELeave) NativeHttpSession(); - // Cleanup the event source object if a leave occurs during construction: - //TConstructor selfCleanup(self, aJni); -// FeatureManager::InitializeLibL(); - // TBool isSupported = false; //FeatureManager::FeatureSupported( KFeatureIdJavaApiEnhancementsIap );//KFeatureIdJavaAPIEnhancementsIAP -// FeatureManager::UnInitializeLib(); - // if( isSupported ) - // { + *aErr = self->ConstructL(aJni, aPeer /* aServer*/, aType, aAPNId, apnerr); LOG1(ESOCKET,EInfo,"NativeHttpSession::NewL - aErr : %d",*aErr); - // } - //else - // { - // self->ConstructL(aJni, aPeer, /*aServer,*/ aType, -1 ); - // } + self->attachToVm(aJni,aPeer); // Pop the cleanup of the object and create a handle: return reinterpret_cast(self); //selfCleanup.GetHandle(); @@ -111,28 +70,11 @@ iReadCallbackMethodID = NULL; iReadCallbackMethodID = mJniEnv->GetMethodID(httpNativeClass, "dataReadyForReadCallBack", "(I)V"); - // mJniEnv->CallVoidMethod(mJavaPeerObject,iSubmitCallbackMethodID,1); - - /* httpNativeClass = mJniEnv->FindClass("com/nokia/mj/impl/gcf/protocol/http/Protocol"); - if ( httpNativeClass == NULL ) - { - LOG(ESOCKET,EInfo,"+httpNativeClass is null"); - } - iSubmitCallbackMethodID = NULL; - iSubmitCallbackMethodID = mJniEnv->GetMethodID( httpNativeClass, "temp", "(I)V" ); - if ( iSubmitCallbackMethodID == NULL ) - { - LOG(ESOCKET,EInfo,"+iMethodID is NULL"); - } - mJniEnv->CallVoidMethod(mJavaPeerObject,iSubmitCallbackMethodID,1);*/ LOG(ESOCKET,EInfo,"-vmAttached"); } TInt NativeHttpSession::ConstructL(JNIEnv& /*aJni*/, jobject /*aPeer*/,/* TJavaEventServer aServer, */ TInt aType, TInt aAPNId, TInt * apnerr) { -// CJavaEventSourceBase::ConstructL(aJni, aPeer, aServer); - //iSuiteId = aSuiteId; - TInt err; TInt handle = reinterpret_cast(this); CallMethodL(err, this, &NativeHttpSession::ExecuteCreateHttpSessionL,handle, aType, aAPNId,apnerr, this); @@ -148,9 +90,6 @@ HBufC* t1 = S60CommonUtils::wstringToDes(uri2.c_str()); HBufC* t2 = S60CommonUtils::wstringToDes(req2.c_str()); - // RJString uri( *aJni, aUri ); - // RJString reqMethod( *aJni, aRequestMethod ); - //TInt handle= NativeHttpTransaction::NewL(*aJni,aPeer, Server(), *iHttpSessionClient, (const TDesC*)&uri, (const TDesC*)&reqMethod); TInt handle= NativeHttpTransaction::NewL(*aJni,aPeer,/* NULL, */*iHttpSessionClient, (const TDesC*)t1, (const TDesC*)t2,this); return handle; } @@ -178,27 +117,34 @@ return err; } -//RHTTPSession& NativeHttpSession::Session() -// { -// return iHttpSessionClient->Session(); -// } - - - - void NativeHttpSession::doSubmitCallback(TInt aStatus,jobject &aPeer) { - LOG(ESOCKET,EInfo,"+doSubmitCallback1"); - //mJniEnv->CallVoidMethod(mJavaPeerObject,iSubmitCallbackMethodID,aStatus); - mJniEnv->CallVoidMethod(aPeer,iSubmitCallbackMethodID,aStatus); + LOG(ESOCKET,EInfo,"+doSubmitCallback1"); + jobject localPeerObject = mJniEnv->NewLocalRef(aPeer); + if(localPeerObject) + { + // java side peer object may be GC'ed when this call is being made. + mJniEnv->CallVoidMethod(aPeer,iSubmitCallbackMethodID,aStatus); + } + else + { + ELOG(ESOCKET,"NativeHttpSession::doSubmitCallback: Error!! java peer object not found "); + } LOG(ESOCKET,EInfo,"-doSubmitCallback1"); } void NativeHttpSession::doReadCallback(TInt aStatus,jobject &aPeer) { LOG(ESOCKET,EInfo,"+doReadCallback1"); -// mJniEnv->CallVoidMethod(mJavaPeerObject,iReadCallbackMethodID,aStatus); - mJniEnv->CallVoidMethod(aPeer,iReadCallbackMethodID,aStatus); + jobject localPeerObject = mJniEnv->NewLocalRef(aPeer); + if(localPeerObject) + { + mJniEnv->CallVoidMethod(aPeer,iReadCallbackMethodID,aStatus); + } + else + { + ELOG(ESOCKET,"NativeHttpSession::doReadCallback: Error!! java peer object not found "); + } LOG(ESOCKET,EInfo,"-doReadCallback1"); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/src.s60/nativehttptraansaction.cpp --- a/javacommons/gcfprotocols/http/src.s60/nativehttptraansaction.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/src.s60/nativehttptraansaction.cpp Fri May 14 15:47:24 2010 +0300 @@ -57,7 +57,7 @@ NativeHttpTransaction::NativeHttpTransaction(HttpSessionClient& aSession, FunctionServer* aFuncServer) :iSessionClient(aSession) //, java::util::FunctionServer("MyhttpServer2") { - // createServerToNewThread(); + iFuncServer = aFuncServer; } @@ -72,8 +72,7 @@ { NativeHttpTransaction* self = new(ELeave) NativeHttpTransaction(aSession,aFuncServer); - // Cleanup the event source object if a leave occurs during construction: - //TConstructor selfCleanup(self, aJni); + self->ConstructL(aJni, aPeer, /*aServer, */ aUri, aRequestMethod); @@ -86,36 +85,17 @@ { - // iJniPeer = aJni.NewWeakGlobalRef(aPeer); iJniPeer = aJni.NewWeakGlobalRef(aPeer); -// CJavaEventSourceBase::ConstructL(aJni, aPeer, aServer); - //Set up the Java Call Backs HttpConnectionNative - /* - jclass httpNativeClass = aJni.FindClass( "com/nokia/mj/impl/http/HttpConnectionNative" ); - if ( httpNativeClass == NULL ) - { - User::Leave( KErrGeneral ); - } - iTransactionCallbackMethod = aJni.GetMethodID( httpNativeClass, "transactionSubmitCallback", "(I)V" ); - if ( iTransactionCallbackMethod == NULL ) - { - User::Leave( KErrGeneral ); - } - iNotifyDataReadyForReadMethod = aJni.GetMethodID( httpNativeClass, "dataReadyForReadCallBack", "(I)V" ); - if ( iNotifyDataReadyForReadMethod == NULL ) - { - User::Leave( KErrGeneral ); - } - */ + // iFuncServer->attachToVm(aJni, aPeer); int handle = reinterpret_cast(this); int urihandle = reinterpret_cast(aUri); int methodhandle = reinterpret_cast(aRequestMethod); //open the transaction - //User::LeaveIfError(ExecuteTrap(&NativeHttpTransaction::ExecuteCreateTransactionL, this , aUri , aRequestMethod)); + CallMethodL(this, &NativeHttpTransaction::ExecuteCreateTransactionL,handle,urihandle , methodhandle, iFuncServer); - //ExecuteCreateTransactionL( this , aUri , aRequestMethod); + } void NativeHttpTransaction::ExecuteCreateTransactionL(int aSelfhandle, int aUrihandle, int aMethodhandle) @@ -135,8 +115,7 @@ RPointerArray rawHeaderArray; CleanupStack::PushL(TCleanupItem(CleanUpResetAndDestroy,&rawHeaderArray)); iJniObject = aJni; - //iJniPeer = aPeer; - //iFuncServer->attachToVm(*aJni, *aPeer); + if (aHeaders!=NULL) { @@ -188,13 +167,13 @@ postBuf = NULL; } -// ExecuteSubmitL( this, &rawHeaderArray , postBuf); + CleanupStack::PopAndDestroy();//rawHeaderArray; } void NativeHttpTransaction::ExecuteSubmitL(int aSelfhandle , int aRawHeadershandle , int aPostBufhandle, int aResponseTimeout) { - //RPointerArray* aRawHeaders; + NativeHttpTransaction *aSelf = reinterpret_cast(aSelfhandle); RPointerArray* aRawHeaders = reinterpret_cast*>(aRawHeadershandle); HBufC8* aPostBuf = reinterpret_cast(aPostBufhandle); @@ -207,12 +186,12 @@ jobjectArray objArray=NULL; RPointerArray rawHeaders(KResponseGranularity); CleanupStack::PushL(TCleanupItem(CleanUpResetAndDestroy,&rawHeaders)); - //User::LeaveIfError(ExecuteTrap(&NativeHttpTransaction::ExecuteGetResponseL, this, &rawHeaders)); + int handle = reinterpret_cast(this); int arrayhandle = reinterpret_cast(&rawHeaders); CallMethodL(this, &NativeHttpTransaction::ExecuteGetResponseL,handle,arrayhandle , iFuncServer); - //ExecuteGetResponseL( this, &rawHeaders); + const TInt headerCount = rawHeaders.Count(); if (headerCount>KErrNone) { @@ -253,7 +232,7 @@ */ TInt NativeHttpTransaction::ReadBytes(TUint8* aBytes, TInt aLength) { - //return Execute(&NativeHttpTransaction::ExecuteReadBytes, this, aBytes , aLength); + int handle = reinterpret_cast(this); int uinthandle = reinterpret_cast(aBytes); @@ -261,7 +240,7 @@ CallMethod(ret,this, &NativeHttpTransaction::ExecuteReadBytes,handle,uinthandle,aLength,iFuncServer); return ret; - //return ExecuteReadBytes( this, aBytes , aLength); + } TInt NativeHttpTransaction::ExecuteReadBytes(int aSelfhandle, int aByteshandle, TInt aLength) @@ -277,26 +256,10 @@ { LOG(ESOCKET,EInfo,"+NativeHttpTransaction::SubmitComplete"); -// jclass httpNativeClass = NULL; -// httpNativeClass = iJniObject->FindClass("com/nokia/mj/impl/http/HttpConnectionNative"); -// jmethodID iMethodID = NULL; -// iMethodID = iJniObject->GetMethodID( httpNativeClass, "transactionSubmitCallback", "(I)V" ); -// if ( httpNativeClass == NULL ) -// { -// LOG(ESOCKET,EInfo,"+httpNativeClass is null"); -// } -// if ( iMethodID == NULL ) -// { -// LOG(ESOCKET,EInfo,"+iMethodID is NULL"); -// } - /* if ( iJniPeer == NULL ) - { - LOG(ESOCKET,EInfo,"+iJniPeer is null"); - }*/ + NativeHttpSession* session = reinterpret_cast(iFuncServer); session->doSubmitCallback(aStatus,iJniPeer); - // PostEvent(new (ELeave) CHttpTransactionEvent(iTransactionCallbackMethod, aStatus ),CJavaEventBase::ENotifyPriority); LOG(ESOCKET,EInfo,"-NativeHttpTransaction::SubmitComplete"); } @@ -304,17 +267,9 @@ { LOG(ESOCKET,EInfo,"+NativeHttpTransaction::DataReadyForRead"); -// jclass httpNativeClass = NULL; -// httpNativeClass = iJniObject->FindClass("com/nokia/mj/impl/http/HttpConnectionNative"); -// jmethodID iMethodReadCallBackID = NULL; -// iMethodReadCallBackID = iJniObject->GetMethodID( httpNativeClass, "dataReadyForReadCallBack", "(I)V" ); -// -// iFuncServer->mJniEnv->CallVoidMethod(mJavaPeerObject,iMethodReadCallBackID,1); - NativeHttpSession* session = reinterpret_cast(iFuncServer); session->doReadCallback(aStatus,iJniPeer); - //PostEvent(new (ELeave) CHttpTransactionEvent(iNotifyDataReadyForReadMethod, aStatus ),CJavaEventBase::ENotifyPriority); LOG(ESOCKET,EInfo,"-NativeHttpTransaction::DataReadyForRead"); } @@ -327,11 +282,9 @@ void NativeHttpTransaction::Dispose() { LOG(ESOCKET,EInfo,"+NativeHttpTransaction::Dispose()"); - //iFuncServer->stopServer(); CloseTransaction(); delete iTransactionClient; iTransactionClient=NULL; -// iFuncServer->detachFromVm(); LOG(ESOCKET,EInfo,"-NativeHttpTransaction::Dispose()"); } @@ -339,10 +292,8 @@ void NativeHttpTransaction::CloseTransaction() { - //ExecuteV(&NativeHttpTransaction::ExecuteCloseTransaction, this); int handle = reinterpret_cast(this); CallMethod(this, &NativeHttpTransaction::ExecuteCloseTransaction,handle,iFuncServer); - //ExecuteCloseTransaction( this); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/http/src.s60/nativetransaction.cpp --- a/javacommons/gcfprotocols/http/src.s60/nativetransaction.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/http/src.s60/nativetransaction.cpp Fri May 14 15:47:24 2010 +0300 @@ -18,7 +18,13 @@ #include #include + +#ifdef RD_JAVA_S60_RELEASE_10_1_ONWARDS +#include +#else #include +#endif + #include "com_nokia_mj_impl_http_HttpConnectionNative.h" #include "nativehttptransaction.h" #include "nativehttpsession.h" @@ -54,16 +60,6 @@ return handle; } -JNIEXPORT void JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1dispose( - JNIEnv*, - jobject, - jint aNativeHttpSessionHandle) -{ - LOG(ESOCKET,EInfo,"http jni _dispose()"); - NativeHttpSession* session = reinterpret_cast(aNativeHttpSessionHandle); - delete session; -} - JNIEXPORT void JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1closeTransaction( JNIEnv* aJni, jobject aPeer, @@ -72,8 +68,16 @@ NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); tran->iJniPeer = aJni->NewWeakGlobalRef(aPeer); - - tran->Dispose(); + try + { + tran->Dispose(); + } + catch(...) + { + // function server usage may throw an exception. + // ignore, called when transcation is closed + ELOG(ESOCKET,"Http JNI Error, exception caught!: _closeTransaction"); + } delete tran; } @@ -84,10 +88,21 @@ jstring aUri, jstring aRequestMethod) { + LOG(ESOCKET,EInfo,"http jni _createNativeTransaction()"); NativeHttpSession* session = reinterpret_cast(aNativeHttpSession); //tran->iJniPeer = aJni->NewGlobalRef(aPeer); - TRAPD(handle, handle = session->CreateTransactionL(aJni, aPeer , aUri, aRequestMethod);); - return handle; + try + { + TRAPD(handle, handle = session->CreateTransactionL(aJni, aPeer , aUri, aRequestMethod);); + return handle; + } + catch(...) + { + // function server usage may throw an exception. + ELOG(ESOCKET,"Http JNI Error, exception caught!: _createTransaction"); + return -1; + } + } JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1submitTransaction( @@ -99,11 +114,20 @@ jint aPostDataLength, jint aResponseTimeout) { + LOG(ESOCKET,EInfo,"http jni _submitTransaction"); NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); int respTimeOut = aResponseTimeout; tran->iJniPeer = aJni->NewWeakGlobalRef(aPeer); - TRAPD(err,tran->SubmitL(aJni, &aPeer,aHeaders, aPostData, aPostDataLength, respTimeOut)); - return err; + try + { + TRAPD(err,tran->SubmitL(aJni, &aPeer,aHeaders, aPostData, aPostDataLength, respTimeOut)); + return err; + } + catch(...) + { + ELOG(ESOCKET,"Http JNI Error, exception caught!: _submitTransaction"); + return -1; + } } JNIEXPORT jobjectArray JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1getResponse( @@ -111,18 +135,24 @@ jobject aPeer, jint aNativeHttpTransaction) { + LOG(ESOCKET,EInfo,"http jni _getResponse"); jobjectArray rawHeaders=NULL; -// java::util::Monitor *iMonitor2; -// iMonitor2 = java::util::Monitor::createMonitor(); -// iMonitor2->wait(); - NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); tran->iJniPeer = aJni->NewWeakGlobalRef(aPeer); - TRAPD(err, rawHeaders = tran->GetResponseL(aJni)); - if (err!=KErrNone) + try { - rawHeaders=NULL; - } + TRAPD(err, rawHeaders = tran->GetResponseL(aJni)); + if (err!=KErrNone) + { + rawHeaders=NULL; + } + } + catch(...) + { + rawHeaders=NULL; + ELOG(ESOCKET,"Http JNI Error, exception caught!: _getResponse"); + + } return rawHeaders; } @@ -134,20 +164,27 @@ jbyteArray aBytes, jint aLength) { + LOG(ESOCKET,EInfo,"http jni _getBytes"); jbyte* bytes = aEnv->GetByteArrayElements(aBytes, NULL); - if (bytes == NULL) { return -1; } - - NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); - tran->iJniPeer = aEnv->NewWeakGlobalRef(aPeer); - TInt length = tran->ReadBytes(reinterpret_cast(bytes), aLength); - - aEnv->ReleaseByteArrayElements(aBytes, bytes, NULL); - return length; + try + { + NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); + tran->iJniPeer = aEnv->NewWeakGlobalRef(aPeer); + TInt length = tran->ReadBytes(reinterpret_cast(bytes), aLength); + + aEnv->ReleaseByteArrayElements(aBytes, bytes, NULL); + return length; + } + catch(...) + { + ELOG(ESOCKET,"Http JNI Error, exception caught!: _getBytes"); + return -1; + } } JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1available( @@ -157,7 +194,15 @@ { NativeHttpTransaction* tran = reinterpret_cast(aNativeHttpTransaction); tran->iJniPeer = aJni->NewWeakGlobalRef(aPeer); - return tran->Available(); + try + { + return tran->Available(); + } + catch(...) + { + ELOG(ESOCKET,"Http JNI Error, exception caught!: _available"); + return -1; + } } JNIEXPORT jstring JNICALL Java_com_nokia_mj_impl_http_HttpConnectionNative__1getUserAgentHeaderValue( diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/secureconnection/inc.s60/nativecertificatemanager.h --- a/javacommons/gcfprotocols/secureconnection/inc.s60/nativecertificatemanager.h Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/secureconnection/inc.s60/nativecertificatemanager.h Fri May 14 15:47:24 2010 +0300 @@ -45,7 +45,6 @@ class CX500DistinguishedName; class CX520AttributeTypeAndValue; class CPKCS10Request; -class MPKIDialog; class CCMSIssuerAndSerialNumber; using namespace java::util; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/secureconnection/src.linux/dummy.txt diff -r 2a9601315dfc -r 98ccebc37403 javacommons/gcfprotocols/socket/socket/src.linux/socketlocalhostinfo.cpp --- a/javacommons/gcfprotocols/socket/socket/src.linux/socketlocalhostinfo.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/gcfprotocols/socket/socket/src.linux/socketlocalhostinfo.cpp Fri May 14 15:47:24 2010 +0300 @@ -20,6 +20,7 @@ #include #include #include +#include #include "socketlocalhostinfo.h" #include "logger.h" diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/att_manufacturer.txt --- a/javacommons/security/data/att_manufacturer.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/att_manufacturer.txt Fri May 14 15:47:24 2010 +0300 @@ -33,4 +33,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/att_operator.txt --- a/javacommons/security/data/att_operator.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/att_operator.txt Fri May 14 15:47:24 2010 +0300 @@ -1,19 +1,18 @@ domain Operator; -grant user "Net Access" session,blanket,oneshot,no { +grant user "Net Access" blanket,session,oneshot,no { permission javax.microedition.io.HttpProtocolPermission "http://*"; permission javax.microedition.io.HttpsProtocolPermission "https://*"; +} +grant user "Low Level Net Access" blanket,session,oneshot,no { permission javax.microedition.io.DatagramProtocolPermission "datagram://*"; permission javax.microedition.io.DatagramProtocolPermission "datagram://"; permission javax.microedition.io.SSLProtocolPermission "ssl://*"; -} - -grant user "Low Level Net Access" session,blanket,oneshot,no { permission javax.microedition.io.SocketProtocolPermission "socket://*"; permission javax.microedition.io.SocketProtocolPermission "socket://"; permission javax.microedition.io.Connector.rtsp "*"; } -grant user "Local Connectivity" session,blanket,oneshot,no { +grant user "Local Connectivity" blanket,session,oneshot,no { permission javax.microedition.io.CommProtocolPermission "comm:*"; permission javax.microedition.io.Connector.obex.server "*" "server"; permission javax.microedition.io.Connector.obex.client "*" "client"; @@ -21,43 +20,34 @@ permission javax.microedition.io.Connector.bluetooth.client "*" "client"; } -grant user "Read User Data Access" session,blanket,oneshot,no { +grant user "Read User Data Access" blanket,session,oneshot,no { permission javax.microedition.io.FileProtocolPermission "*" "read"; permission javax.microedition.pim.ContactList "pim://*" "read_contacts"; permission javax.microedition.pim.EventList "pim://*" "read_events"; permission javax.microedition.pim.ToDoList "pim://*" "read_todos"; } -grant user "Write User Data Access" session,blanket,oneshot,no { +grant user "Write User Data Access" blanket,session,oneshot,no { permission javax.microedition.io.FileProtocolPermission "*" "write"; permission javax.microedition.pim.ContactList "pim://*" "write_contacts"; permission javax.microedition.pim.EventList "pim://*" "write_events"; permission javax.microedition.pim.ToDoList "pim://*" "write_todos"; } -grant user "Messaging" session,blanket,oneshot,no { +grant user "Messaging" blanket,session,oneshot,no { permission javax.microedition.io.Connector.sms "sms://*" "send"; permission javax.microedition.io.Connector.mms "mms://*" "send"; } -grant user "Multimedia Recording" session,blanket,oneshot,no { +grant user "Multimedia Recording" blanket,session,oneshot,no { permission javax.microedition.media.control.RecordControl "*" "record"; permission javax.microedition.media.control.VideoControl.getSnapshot "*" "snapshot"; } -grant user "Application Auto Invocation" session,blanket,oneshot,no { +grant user "Application Auto Invocation" blanket,session,oneshot,no { permission javax.microedition.io.PushRegistryPermission "*" "staticregistration,dynamicregistration,autoinvocation"; } -grant user "Location" session,blanket,oneshot,no { - permission javax.microedition.location.LocationPermission "location://*" "position,orientation"; - permission javax.microedition.location.LocationPermission "landmarks://*" "read,write,category,management"; -} - -grant user "Restricted API Extensions" session,blanket,oneshot,no { - permission javax.microedition.PropertyPermission "mobinfo.imsi" "read"; -} - grant allowed { permission javax.microedition.io.Connector.sms "sms://*" "open,receive"; permission javax.microedition.io.Connector.mms "mms://*" "open,receive"; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/att_operatorextra.txt --- a/javacommons/security/data/att_operatorextra.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/att_operatorextra.txt Fri May 14 15:47:24 2010 +0300 @@ -33,4 +33,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/att_trustedthirdparty.txt --- a/javacommons/security/data/att_trustedthirdparty.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/att_trustedthirdparty.txt Fri May 14 15:47:24 2010 +0300 @@ -2,9 +2,6 @@ grant user "Net Access" session,oneshot,no { permission javax.microedition.io.HttpProtocolPermission "http://*"; permission javax.microedition.io.HttpsProtocolPermission "https://*"; - permission javax.microedition.io.DatagramProtocolPermission "datagram://*"; - permission javax.microedition.io.DatagramProtocolPermission "datagram://"; - permission javax.microedition.io.SSLProtocolPermission "ssl://*"; } grant user "Local Connectivity" session,oneshot,no { diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/att_untrusted.txt --- a/javacommons/security/data/att_untrusted.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/att_untrusted.txt Fri May 14 15:47:24 2010 +0300 @@ -2,7 +2,4 @@ grant user "Net Access" oneshot,no { permission javax.microedition.io.HttpProtocolPermission "http://*"; permission javax.microedition.io.HttpsProtocolPermission "https://*"; - permission javax.microedition.io.DatagramProtocolPermission "datagram://*"; - permission javax.microedition.io.DatagramProtocolPermission "datagram://"; - permission javax.microedition.io.SSLProtocolPermission "ssl://*"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/msa_manufacturer.txt --- a/javacommons/security/data/msa_manufacturer.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/msa_manufacturer.txt Fri May 14 15:47:24 2010 +0300 @@ -34,4 +34,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/msa_operator.txt --- a/javacommons/security/data/msa_operator.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/msa_operator.txt Fri May 14 15:47:24 2010 +0300 @@ -34,4 +34,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/msa_trustedthirdparty.txt --- a/javacommons/security/data/msa_trustedthirdparty.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/msa_trustedthirdparty.txt Fri May 14 15:47:24 2010 +0300 @@ -67,3 +67,6 @@ permission javax.microedition.io.Connector.mms "mms://*" "open,receive"; permission javax.microedition.io.Connector.cbs "cbs://*" "open,receive"; } +grant assigned { + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; +} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/msa_untrusted.txt --- a/javacommons/security/data/msa_untrusted.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/msa_untrusted.txt Fri May 14 15:47:24 2010 +0300 @@ -60,3 +60,6 @@ permission javax.microedition.io.Connector.mms "mms://*" "open,receive"; permission javax.microedition.io.Connector.cbs "cbs://*" "open,receive"; } +grant assigned { + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; +} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/s60_manufacturer.txt --- a/javacommons/security/data/s60_manufacturer.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/s60_manufacturer.txt Fri May 14 15:47:24 2010 +0300 @@ -34,4 +34,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/s60_operator.txt --- a/javacommons/security/data/s60_operator.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/s60_operator.txt Fri May 14 15:47:24 2010 +0300 @@ -34,4 +34,5 @@ grant assigned { permission javax.microedition.PropertyPermission "mobinfo.msisdn" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/s60_trustedthirdparty.txt --- a/javacommons/security/data/s60_trustedthirdparty.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/s60_trustedthirdparty.txt Fri May 14 15:47:24 2010 +0300 @@ -68,3 +68,6 @@ permission javax.microedition.io.Connector.mms "mms://*" "open,receive"; permission javax.microedition.io.Connector.cbs "cbs://*" "open,receive"; } +grant assigned { + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; +} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/data/s60_untrusted.txt --- a/javacommons/security/data/s60_untrusted.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/data/s60_untrusted.txt Fri May 14 15:47:24 2010 +0300 @@ -37,7 +37,7 @@ permission javax.microedition.io.Connector.mms "mms://*" "send"; } -grant user "Multimedia Recording" oneshot,session,no { +grant user "Multimedia Recording" oneshot,session,blanket,no { permission javax.microedition.media.control.RecordControl "*" "record"; permission javax.microedition.media.control.VideoControl.getSnapshot "*" "snapshot"; } @@ -60,3 +60,6 @@ permission javax.microedition.io.Connector.mms "mms://*" "open,receive"; permission javax.microedition.io.Connector.cbs "cbs://*" "open,receive"; } +grant assigned { + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; +} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/javasrc.cdc/com/nokia/mj/impl/security/midp/authorization/PermissionGranter.java --- a/javacommons/security/javasrc.cdc/com/nokia/mj/impl/security/midp/authorization/PermissionGranter.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/javasrc.cdc/com/nokia/mj/impl/security/midp/authorization/PermissionGranter.java Fri May 14 15:47:24 2010 +0300 @@ -345,7 +345,8 @@ boolean permissions_from_mutually_exclusive_list_2 = false; boolean permissions_from_sensitive_combination_list_1 = false; boolean permissions_from_sensitive_combination_list_2 = false; - String blanketPermissionsDetails = "settings_inst_query_perm_sec"; + boolean local_connectivity = false; + boolean net_access = false; Vector blanketPermissions = new Vector(); for (int i=0; i #include -#ifndef RD_JAVA_S60_RELEASE_5_0_IAD #include -#endif #include #include @@ -49,9 +47,7 @@ //_LIT(KMIDP2TrustRoot, "J2ME MIDP2 Trust Root"); _LIT(KMIDP2TrustRoot, "Java Trust Root"); -#ifndef RD_JAVA_S60_RELEASE_5_0_IAD _LIT(KJavaUserMessagesResourceFileName, "javausermessages.rsc"); -#endif //_LIT( KRuntimeSecPolicyResourceFileName, "z:midp2runtimesecuritypolicy.rsc" ); //const TUid KCertManUIViewTrustJavaInstallingId = { 0x101F9B28 }; @@ -177,6 +173,10 @@ SendDisableMsg(status); return; + case EPreDeleting: + SendDeleteMsg(status); + return; + default: //Do nothing. break; @@ -230,7 +230,6 @@ */ void CJavaCertStoreImpl::Remove(const CCTCertInfo& aCertInfo,TRequestStatus& aStatus) { - aStatus = KRequestPending; TRequestStatus* pRequestStatus = &aStatus; @@ -252,24 +251,10 @@ User::RequestComplete(pRequestStatus,KErrArgument); return; } - - CommsMessage commsMsg; - commsMsg.setReceiver(IPC_ADDRESS_JAVA_CAPTAIN_C); - commsMsg.setSender(IPC_ADDRESS_JAVA_CAPTAIN_C); - commsMsg.setModuleId(PLUGIN_ID_JAVA_CERT_STORE_EXTENSION_C); - commsMsg.setMessageId(JAVA_CERT_STORE_MSG_ID_REQUEST); - commsMsg << JAVA_CERT_STORE_OPERATION_DELETE_CERT; - commsMsg << certData->mId; - int err = mComms.send(commsMsg); - if (0 != err) - { - std::string errTxt("Sending a comms request failed: "); - errTxt.append(java::util::JavaCommonUtils::intToString(err)); - ELOG1(EJavaSecurity, "ERROR!!! %s",errTxt.c_str()); - User::RequestComplete(pRequestStatus,KErrCommsBreak); - } - certData->mDeleted = ETrue; - User::RequestComplete(pRequestStatus,KErrNone); + + mState = EPreDeleting; + mTempCertData = certData; + HandleDeleteDisableQuery(aStatus, false /* disableCertQuery */); } /** @@ -330,7 +315,7 @@ #else mState = state; mTempCertData = certData; - HandleDisableQuery(aStatus); + HandleDeleteDisableQuery(aStatus, true /* disableCertQuery */); #endif return; } @@ -832,6 +817,32 @@ /** * */ +TBool CJavaCertStoreImpl::SendDeleteCommsMsg(const std::string& aId, + TRequestStatus* aRequestStatus) +{ + CommsMessage commsMsg; + commsMsg.setReceiver(IPC_ADDRESS_JAVA_CAPTAIN_C); + commsMsg.setSender(IPC_ADDRESS_JAVA_CAPTAIN_C); + commsMsg.setModuleId(PLUGIN_ID_JAVA_CERT_STORE_EXTENSION_C); + commsMsg.setMessageId(JAVA_CERT_STORE_MSG_ID_REQUEST); + commsMsg << JAVA_CERT_STORE_OPERATION_DELETE_CERT; + commsMsg << aId; + int err = mComms.send(commsMsg); + if (0 != err) + { + std::string errTxt("Sending a comms request failed: "); + errTxt.append(java::util::JavaCommonUtils::intToString(err)); + ELOG1(EJavaSecurity, "ERROR!!! %s",errTxt.c_str()); + User::RequestComplete(aRequestStatus,KErrCommsBreak); + return EFalse; + } + + return ETrue; +} + +/** + * + */ TBool CJavaCertStoreImpl::CheckCapability(const TCapability& aCapability,TRequestStatus* aRequestStatus) { RThread thread; @@ -847,10 +858,19 @@ /** * */ -void CJavaCertStoreImpl::HandleDisableQuery(TRequestStatus &aRequestStatus) +void CJavaCertStoreImpl::HandleDeleteDisableQuery(TRequestStatus &aRequestStatus, bool disableCertQuery) { - - TRAPD(leaveStatus,ShowQueryL()); + TInt leaveStatus = KErrNone; + if (disableCertQuery) + { +#ifndef RD_JAVA_S60_RELEASE_5_0_IAD + TRAP(leaveStatus,ShowQueryL(R_JAVA_SECUR_CERT_DISABLING)); +#endif + } + else + { + TRAP(leaveStatus,ShowQueryL(R_JAVA_SECUR_CERT_DELETING)); + } if (KErrNone == leaveStatus) { mClientStatus = &aRequestStatus; @@ -866,21 +886,16 @@ /** * */ -void CJavaCertStoreImpl::ShowQueryL() +void CJavaCertStoreImpl::ShowQueryL(TInt resourceId) { - -#ifndef RD_JAVA_S60_RELEASE_5_0_IAD - TFileName resourceFileName = java::util::S60CommonUtils::ResourceLanguageFileNameL( KJavaUserMessagesResourceFileName); std::auto_ptr reader(CStringResourceReader::NewL(resourceFileName)); - std::auto_ptr queryPrompt(reader->ReadResourceString(R_JAVA_SECUR_CERT_DISABLING).AllocL()); + std::auto_ptr queryPrompt(reader->ReadResourceString(resourceId).AllocL()); mQuery.reset(CAknGlobalConfirmationQuery::NewL()); mQuery->ShowConfirmationQueryL(iStatus,queryPrompt->Des(),R_AVKON_SOFTKEYS_OK_CANCEL); - -#endif } /** @@ -903,6 +918,23 @@ /** * */ +void CJavaCertStoreImpl::SendDeleteMsg(TInt aStatus) +{ + + mState = EInitial; + delete mQuery.release(); + mState = EInitial; + if (EAknSoftkeyOk != aStatus) + { + User::RequestComplete(mClientStatus,KErrCancel); + return; + } + HandleSendingDeleteMsg(mClientStatus,*mTempCertData); +} + +/** + * + */ void CJavaCertStoreImpl::HandleSendingEnableDisableMsg(TRequestStatus* aRequestStatus, TState aState,CJavaCertData& aCertDataObj) { @@ -926,6 +958,25 @@ User::RequestComplete(aRequestStatus,KErrNone); } +/** + * + */ +void CJavaCertStoreImpl::HandleSendingDeleteMsg(TRequestStatus* aRequestStatus, + CJavaCertData& aCertDataObj) +{ + + TBool flag = SendDeleteCommsMsg(aCertDataObj.mId,aRequestStatus); + if (!flag) + { + //SendDeleteCommsMsg() operation calls RequestComplete() + //operation in the error situation. + return; + } + aCertDataObj.mDeleted = ETrue; + + User::RequestComplete(aRequestStatus,KErrNone); +} + ///////////////////////////////////////////////////////////////////////////////// // // IMPLEMENTATION OF CJavaCertData CLASS diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/javaunicertstoreplugin/src.s60/javacertstoreimpl.h --- a/javacommons/security/javaunicertstoreplugin/src.s60/javacertstoreimpl.h Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/javaunicertstoreplugin/src.s60/javacertstoreimpl.h Fri May 14 15:47:24 2010 +0300 @@ -129,7 +129,8 @@ EInitial, EListing, EPreDisabling, - EPreEnabling + EPreEnabling, + EPreDeleting }; //Datamembers. @@ -159,12 +160,17 @@ TBool SendDisableEnableCommsMsg(const std::string& aId, TState aState, TRequestStatus* aRequestStatus); + TBool SendDeleteCommsMsg(const std::string& aId, + TRequestStatus* aRequestStatus); TBool CheckCapability(const TCapability& aCapability,TRequestStatus* aRequestStatus); - void HandleDisableQuery(TRequestStatus &aRequestStatus); - void ShowQueryL(); + void HandleDeleteDisableQuery(TRequestStatus &aRequestStatus, bool disableCertQuery); + void ShowQueryL(TInt resourceId); void SendDisableMsg(TInt aStatus); + void SendDeleteMsg(TInt aStatus); void HandleSendingEnableDisableMsg(TRequestStatus* aRequestStatus, TState aState,CJavaCertData& aCertDataObj); + void HandleSendingDeleteMsg(TRequestStatus* aRequestStatus, + CJavaCertData& aCertDataObj); //Not implemented. CJavaCertStoreImpl(const CJavaCertStoreImpl &x); diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/src/utils/storagehandler.cpp --- a/javacommons/security/src/utils/storagehandler.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/src/utils/storagehandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -86,7 +86,6 @@ std::string& aChain) { int i = 1; - wstring chain = L""; bool foundPart = true; const wstring attrPrefix = L"MIDlet-Certificate-"; JavaStorageEntry attr; @@ -119,7 +118,9 @@ if (entryFinder != (*appIter).end()) { - chain.append((*entryFinder).entryValue()); + char* tmp = JavaCommonUtils::wstringToUtf8((*entryFinder).entryValue()); + aChain.append(JavaCommonUtils::base64decode(tmp)); + delete [] tmp; } found = true; @@ -135,11 +136,8 @@ i++; } while (foundPart); +} - char* tempStr = JavaCommonUtils::wstringToUtf8(chain); - aChain.append(tempStr); - delete [] tempStr; -} void StorageHandler::findEntry(const JavaStorageApplicationList_t& queryResult, const std::wstring& eName, std::wstring& eValue) diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/build/build.xml --- a/javacommons/security/tsrc/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -50,6 +50,7 @@ + @@ -100,7 +101,7 @@ - + @@ -135,6 +136,7 @@ + @@ -204,6 +206,18 @@ + + + + @@ -211,10 +225,8 @@ - + - - @@ -225,10 +237,8 @@ - + - - @@ -250,7 +260,7 @@ - + diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/data/policies/all.txt --- a/javacommons/security/tsrc/data/policies/all.txt Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/data/policies/all.txt Fri May 14 15:47:24 2010 +0300 @@ -3,4 +3,5 @@ grant assigned { permission java.util.PropertyPermission "microedition.*" "read"; permission javax.microedition.PropertyPermission "mobinfo.publicinfo" "read"; + permission javax.microedition.PropertyPermission "mobinfo.cellid" "read"; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/OMJSecurityTests.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/OMJSecurityTests.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/OMJSecurityTests.java Fri May 14 15:47:24 2010 +0300 @@ -174,7 +174,7 @@ { // prepare the storage data allAttributes = new Hashtable(); - SecurityAttributes securityAttributes; + SecurityAttributes securityAttributes = new SecurityAttributes(); String appName = "OMJSecurityTests"; ac = AccessControllerFactoryImpl.getAccessController(appUID, appName); AuthenticationCredentials[] credentials; @@ -190,7 +190,6 @@ allAttributes.put(MIDP_PROFILE_ATTRIBUTE_NAME,new Attribute("",MIDP2)); allAttributes.put(AuthenticationAttribute.MAIN_ATTRIBUTE_PREFIX + "1-1", new Attribute("", "MIICWDCCAcECBEhQwA0wDQYJKoZIhvcNAQEEBQAwczELMAkGA1UEBhMCZmkxEjAQBgNVBAgTCVBpcmthbm1hYTEQMA4GA1UEBxMHVGFtcGVyZTEOMAwGA1UEChMFTm9raWExDTALBgNVBAsTBEphdmExHzAdBgNVBAMMFkpQX0RldmljZV9NYW51ZmFjdHVyZXIwHhcNMDgwNjEyMDYxOTU3WhcNMTgwNjEwMDYxOTU3WjBzMQswCQYDVQQGEwJmaTESMBAGA1UECBMJUGlya2FubWFhMRAwDgYDVQQHEwdUYW1wZXJlMQ4wDAYDVQQKEwVOb2tpYTENMAsGA1UECxMESmF2YTEfMB0GA1UEAwwWSlBfRGV2aWNlX01hbnVmYWN0dXJlcjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApi3ipIPj8O33/rZre1euh7Itd9d6ZVf2mvQ/tLpHEsFJe5XLOsVViMvFskhhKUzmDsRbP4J03L6827/vEDIi/1i8kJGLaoFqJYaLGFWI2Zmxlj6aJV8cfZyOjmQPWJn1IDEe1ZAWbvMSp8xibWRsCLNEGKIkxQvAr/QDK/6iS+kCAwEAATANBgkqhkiG9w0BAQQFAAOBgQCDXt6klAs6yKvdTab3D2wkdoi3Lu4YFsMgLexJOu5HhAUJ/9VYO+Q2+mjd95MRsTa5rWQ2Jjvhn57Z3z/KBOwfHbymmNtMk6Gl14H0vQRoHa31jh3mTuAy5KotDVthaDp30aOizk473NU68wY1WdP4gFk5ZhrpNea9q3st13BxIQ==")); allAttributes.put(AuthenticationAttribute.SECOND_LEGACY_ATTRIBUTE_NAME ,new Attribute("", "IcANmLKiOJQF8ABCNDj1PNNH/O8v9jfCVuiGBVm8enXDkM/gLwPjrC65sDKpOCHPqssUlHzjmVN5b9g8aRs4jxUOXNt2b732J7NSIPh97vw/WrP/KHdiooi/1KFUyklMyokK9ZrIv+GW1ttLCfKbuFupT9zmPAmWJQpnuD7J6sE=")); - securityAttributes = new SecurityAttributes(); securityAttributes.addDescriptorAttributes(allAttributes); credentials = authenticationModule.authenticateJad(appUID,null,securityAttributes.getAuthenticationAttributes()); permissionGranter.grantJadPermissions(appUID, null, securityAttributes.getPermissionAttributes(), credentials); @@ -741,6 +740,7 @@ UserSecuritySettings.SESSION_INTERACTION_MODE})), new PolicyBasedPermissionImpl("java.util.PropertyPermission", "microedition.*", "read", null), new PolicyBasedPermissionImpl(p4.getName(), "mobinfo.publicinfo", "read", null), + new PolicyBasedPermissionImpl(p4.getName(), "mobinfo.cellid", "read", null), new PolicyBasedPermissionImpl("com.nokia.ext2.internal.Ext2Perm", "ext2.target4", "ext2.action4", null), })); // getBlanketPermissions: while installing V1 the permissions are not put to blanket, while installing V2 there are some blanket permissions returned @@ -952,7 +952,7 @@ permissionGranter.grantJarPermissions(session, appUID, null, securityAttributes.getPermissionAttributes()); permissionGranter.getBlanketPermissions(appUID); assertTrue(permissionGranter.getBlanketPermissionsDetails(appUID) == null); - // getBlanketPermissionsDetails for Net Access, Read User Data -> net details + // getBlanketPermissionsDetails for Multimedia, Local Connectivity -> privacy details permissionGranter.removeSecurityData(session, appUID); storage.removeAuthenticationStorageData(appUID); permissionGranter.removeSecurityData(session, appUID); @@ -963,21 +963,22 @@ allAttributes.put(AuthenticationAttribute.MAIN_ATTRIBUTE_PREFIX + "1-1", new Attribute("","cert1")); allAttributes.put(AuthenticationAttribute.MAIN_ATTRIBUTE_PREFIX + "1-2", new Attribute("","cert2")); allAttributes.put(AuthenticationAttribute.SECOND_LEGACY_ATTRIBUTE_NAME, new Attribute("","signature")); - allAttributes.put(PermissionAttribute.MANDATORY_LEGACY_ATTRIBUTE_NAME, new Attribute("","javax.microedition.io.Connector.http,javax.microedition.io.Connector.file.read")); + allAttributes.put(PermissionAttribute.MANDATORY_LEGACY_ATTRIBUTE_NAME, new Attribute("","javax.microedition.media.control.RecordControl,javax.microedition.io.Connector.bluetooth.client")); securityAttributes.addDescriptorAttributes(allAttributes); authCredentials = new AuthenticationCredentials[1]; authCredentials[0] = new AuthenticationCredentials("IdentifiedThirdParty", "ITDP"); permissionGranter.grantJadPermissions(appUID, null, securityAttributes.getPermissionAttributes(), authCredentials); allAttributes.clear(); allAttributes.put(MIDP_PROFILE_ATTRIBUTE_NAME,new Attribute("",MIDP2)); - allAttributes.put(PermissionAttribute.MANDATORY_LEGACY_ATTRIBUTE_NAME, new Attribute("","javax.microedition.io.Connector.http,javax.microedition.io.Connector.file.read")); + allAttributes.put(PermissionAttribute.MANDATORY_LEGACY_ATTRIBUTE_NAME, new Attribute("","javax.microedition.media.control.RecordControl,javax.microedition.io.Connector.bluetooth.client")); securityAttributes.addManifestAttributes(allAttributes); permissionGranter.grantJarPermissions(session, appUID, null, securityAttributes.getPermissionAttributes()); permissionGranter.getBlanketPermissions(appUID); - assertTrue("qtn_java_settings_inst_query_perm_net".equals(permissionGranter.getBlanketPermissionsDetails(appUID)) - || "Allowing these permissions may result in compromised privacy or increased network usage costs.".equals( - permissionGranter.getBlanketPermissionsDetails(appUID))); - // getBlanketPermissionsDetails for Messaging. Multimedia -> privacy details + String blanketDetails = permissionGranter.getBlanketPermissionsDetails(appUID); + assertTrue("qtn_java_settings_inst_query_perm_sec".equals(blanketDetails) + || "Allowing these permissions may result in compromised privacy".equals( + blanketDetails)); + // getBlanketPermissionsDetails for Messaging, Multimedia -> net details permissionGranter.removeSecurityData(session, appUID); storage.removeAuthenticationStorageData(appUID); permissionGranter.removeSecurityData(session, appUID); @@ -999,9 +1000,10 @@ securityAttributes.addManifestAttributes(allAttributes); permissionGranter.grantJarPermissions(session, appUID, null, securityAttributes.getPermissionAttributes()); permissionGranter.getBlanketPermissions(appUID); - assertTrue("qtn_java_settings_inst_query_perm_sec".equals(permissionGranter.getBlanketPermissionsDetails(appUID)) - || "Allowing these permissions may result in compromised privacy.".equals( - permissionGranter.getBlanketPermissionsDetails(appUID))); + blanketDetails = permissionGranter.getBlanketPermissionsDetails(appUID); + assertTrue("qtn_java_settings_inst_query_perm_net".equals(blanketDetails) + || "Allowing these permissions may result in compromised privacy or increased network usage costs".equals( + blanketDetails)); } private void upgradeTests(boolean legacySuites) diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/InteractiveAccessControllerTests.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/InteractiveAccessControllerTests.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/InteractiveAccessControllerTests.java Fri May 14 15:47:24 2010 +0300 @@ -35,7 +35,6 @@ import com.nokia.mj.impl.security.midp.common.AuthenticationAttribute; import com.nokia.mj.impl.security.midp.common.MIDPPermission; import com.nokia.mj.impl.security.midp.common.PermissionMappingTable; -import com.nokia.mj.impl.security.midp.common.TestPermissionMappingTable; import com.nokia.mj.impl.utils.Attribute; import com.nokia.mj.impl.security.utils.*; import java.security.*; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionGranterTests.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionGranterTests.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionGranterTests.java Fri May 14 15:47:24 2010 +0300 @@ -42,7 +42,6 @@ import com.nokia.mj.impl.utils.OtaStatusCode; import com.nokia.mj.impl.utils.Attribute; import com.nokia.mj.impl.security.midp.common.PermissionMappingTable; -import com.nokia.mj.impl.security.midp.common.TestPermissionMappingTable; import j2meunit.framework.Test; import j2meunit.framework.TestCase; @@ -1087,9 +1086,10 @@ private static MIDPPermission[] getDefaultPermissions() { - MIDPPermission[] defaultPerms = new MIDPPermission[2]; + MIDPPermission[] defaultPerms = new MIDPPermission[3]; defaultPerms[0] = new MIDPPermission("java.util.PropertyPermission", "microedition.*", "read"); defaultPerms[1] = new MIDPPermission("javax.microedition.PropertyPermission", "mobinfo.publicinfo", "read"); + defaultPerms[2] = new MIDPPermission("javax.microedition.PropertyPermission", "mobinfo.cellid", "read"); return defaultPerms; } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionMappingTable.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionMappingTable.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/PermissionMappingTable.java Fri May 14 15:47:24 2010 +0300 @@ -17,6 +17,8 @@ package com.nokia.mj.impl.security.midp.common; +import com.nokia.mj.impl.security.midp.authorization.TestPermissionMappingTable; + import java.util.Hashtable; import java.util.Enumeration; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/SecurityPolicyModuleTests.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/SecurityPolicyModuleTests.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/SecurityPolicyModuleTests.java Fri May 14 15:47:24 2010 +0300 @@ -87,6 +87,7 @@ new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.imsi","read",null), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.msisdn","read",null), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.publicinfo","read",null), + new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.cellid","read",null), }; static final SecurityPolicyPermission[] OPERATOR_PERMS = { @@ -138,6 +139,7 @@ new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.imsi","read",null), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.msisdn","read",null), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.publicinfo","read",null), + new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.cellid","read",null), }; static final SecurityPolicyPermission[] IDENTIFIED_THIRD_PARTY_PERMS = { @@ -260,6 +262,7 @@ new SecurityPolicyPermissionSettings("Net Access",UserSecuritySettings.SESSION_INTERACTION_MODE, new int[]{UserSecuritySettings.BLANKET_INTERACTION_MODE,UserSecuritySettings.ONESHOT_INTERACTION_MODE,UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE})), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.publicinfo","read",null), + new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.cellid","read",null), }; static final SecurityPolicyPermission[] UNIDENTIFIED_THIRD_PARTY_PERMS = { @@ -368,14 +371,15 @@ new int[]{UserSecuritySettings.ONESHOT_INTERACTION_MODE,UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE})), new SecurityPolicyPermission(getPermissionName("javax.microedition.media.control.RecordControl"),"*", "record", new SecurityPolicyPermissionSettings("Multimedia Recording",UserSecuritySettings.ONESHOT_INTERACTION_MODE, - new int[]{UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE,UserSecuritySettings.ONESHOT_INTERACTION_MODE})), + new int[]{UserSecuritySettings.BLANKET_INTERACTION_MODE,UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE,UserSecuritySettings.ONESHOT_INTERACTION_MODE})), new SecurityPolicyPermission(getPermissionName("javax.microedition.media.control.VideoControl.getSnapshot"),"*", "snapshot", new SecurityPolicyPermissionSettings("Multimedia Recording",UserSecuritySettings.ONESHOT_INTERACTION_MODE, - new int[]{UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE,UserSecuritySettings.ONESHOT_INTERACTION_MODE})), + new int[]{UserSecuritySettings.BLANKET_INTERACTION_MODE,UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE,UserSecuritySettings.ONESHOT_INTERACTION_MODE})), new SecurityPolicyPermission(getPermissionName("javax.microedition.io.Connector.rtsp"),"*", null, new SecurityPolicyPermissionSettings("Net Access",UserSecuritySettings.SESSION_INTERACTION_MODE, new int[]{UserSecuritySettings.ONESHOT_INTERACTION_MODE,UserSecuritySettings.NO_INTERACTION_MODE,UserSecuritySettings.SESSION_INTERACTION_MODE})), new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.publicinfo","read",null), + new SecurityPolicyPermission(getPermissionName("javax.microedition.PropertyPermission"),"mobinfo.cellid","read",null), }; // Begin j2meunit test framework setup diff -r 2a9601315dfc -r 98ccebc37403 javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/TestPermissionMappingTable.java --- a/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/TestPermissionMappingTable.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/security/tsrc/javasrc/com/nokia/mj/impl/security/midp/authorization/TestPermissionMappingTable.java Fri May 14 15:47:24 2010 +0300 @@ -15,10 +15,11 @@ * */ -package com.nokia.mj.impl.security.midp.common; +package com.nokia.mj.impl.security.midp.authorization; import java.util.Hashtable; import java.util.Enumeration; +import com.nokia.mj.impl.security.midp.common.*; /** * Mapping between named permissions and class named permissions diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/functionserver/src/functionserver.cpp --- a/javacommons/utils/functionserver/src/functionserver.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/functionserver/src/functionserver.cpp Fri May 14 15:47:24 2010 +0300 @@ -62,16 +62,24 @@ JELOG2(EUtils); ScopedLock lock(mMutex); - mServerTerminating = true; - if (!mConnectedToClient) + if (mOsServer != 0) { - mClient.connect(*mOsServer); - mConnectedToClient = true; + + mServerTerminating = true; + if (!mConnectedToClient) + { + mClient.connect(*mOsServer); + mConnectedToClient = true; + } + + mClient.sendCloseMessage(this); + mClient.Close(); + mMonitor->wait(); } - - mClient.sendCloseMessage(this); - mClient.Close(); - mMonitor->wait(); + else + { + ELOG(EUtils,"FunctionServer::stopServer() called when there was no server running"); + } } @@ -335,10 +343,18 @@ JELOG2(EUtils); // See stopServerInsideServerThread operation. // ScopedLock lock(mMutex); - if (mServerTerminating) + if (mServerTerminating || mOsServer == 0) { std::string message = "Trying to execute code in non-existing FS: "; message.append(mServerName); + if (mServerTerminating) + { + message.append(" server closing."); + } + else + { + message.append(" server not created."); + } ELOG1(EUtils,"%s", message.c_str()); throw ExceptionBase(message, __FILE__, __FUNCTION__, __LINE__); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/functionserver/src/methodcall.cpp --- a/javacommons/utils/functionserver/src/methodcall.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/functionserver/src/methodcall.cpp Fri May 14 15:47:24 2010 +0300 @@ -34,7 +34,16 @@ OS_EXPORT void MethodCaller::ExecuteLeavingFunctorL(const Functor& functor, java::util::FunctionServer* functionServer, int* /*res*/) { JELOG2(EUtils); - int error = functionServer->executeInServerThread(functor); + int error = KErrNone; + try + { + error = functionServer->executeInServerThread(functor); + } + catch (std::exception&) + { + error = KErrServerTerminated; + } + if (error) // Do not use LeaveIfError(), we want to handle positive error codes as well { User::Leave(error); diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/functionserver/tsrc/build/testfunctionserver.pro --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javacommons/utils/functionserver/tsrc/build/testfunctionserver.pro Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +# +# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +# All rights reserved. +# This component and the accompanying materials are made available +# under the terms of "Eclipse Public License v1.0" +# which accompanies this distribution, and is available +# at the URL "http://www.eclipse.org/legal/epl-v10.html". +# +# Initial Contributors: +# Nokia Corporation - initial contribution. +# +# Contributors: +# +# Description: +# + +TEMPLATE=app +TARGET=testfunctionserver +CONFIG += omj no_icon stl +CONFIG -= qt + +LIBS += -lCppUTest + +INCLUDEPATH += ../../../../../tools/cpputest/include/CppUTest + +INCLUDEPATH += ../../../../../tools/cpputest/include/Platforms/Symbian +TARGET.CAPABILITY = all -tcb + +include(../../../../../build/omj.pri) diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/functionserver/tsrc/src/alltests.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javacommons/utils/functionserver/tsrc/src/alltests.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AllTests +* +*/ + +#include "Platform.h" +#include "CommandLineTestRunner.h" + +int main(int ac, char** av) +{ + return CommandLineTestRunner::RunAllTests(ac, av); +} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/functionserver/tsrc/src/testfunctionserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javacommons/utils/functionserver/tsrc/src/testfunctionserver.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,2186 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Tests for function server +* +*/ + +#include "functionserver.h" +#include "fs_methodcall.h" + +#include "TestHarness.h" +#include "exceptionbase.h" +#include "logger.h" +using namespace java::util; + +int sIvokedMethod = -1; +int sA = -1; +int sB = -1; +int sC = -1; +int sD = -1; +int sE = -1; +int sF = -1; +int sG = -1; +int sH = -1; +int sI = -1; +int sIndex = 0; +int sServerSideInitCalled = false; +int sServerSideCleanCalled = false; +int sStartServerCalled = false; + +void localMethod() +{sIvokedMethod = 1;} +void localMethod1(int a) + {sIvokedMethod = 2; sA = a;} +void localMethod2(int a, int b) + {sIvokedMethod = 3; sA = a; sB = b;} +void localMethod3(int a, int b, int c) + {sIvokedMethod = 4; sA = a; sB = b; sC = c;} +void localMethod4(int a, int b, int c, int d) + {sIvokedMethod = 5; sA = a; sB = b; sC = c; sD = d;} +void localMethod5(int a, int b, int c, int d, int e) + {sIvokedMethod = 6; sA = a; sB = b; sC = c; sD = d; sE = e;} +void localMethod6(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 7; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} +void localMethod7(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 8; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} +void localMethod8(int a, int b, int c, int d, int e, int f, int g, int h) + {sIvokedMethod = 9; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h;} +void localMethod9(int a, int b, int c, int d, int e, int f, int g, int h, int i) + {sIvokedMethod = 10; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h; sI = i;} + +int localMethodR() + {sIvokedMethod = 11;return sIvokedMethod;} +int localMethodR1(int a) + {sIvokedMethod = 12; sA = a;return sIvokedMethod;} +int localMethodR2(int a, int b) + {sIvokedMethod = 13; sA = a; sB = b;return sIvokedMethod;} +int localMethodR3(int a, int b, int c) + {sIvokedMethod = 14; sA = a; sB = b; sC = c;return sIvokedMethod;} +int localMethodR4(int a, int b, int c, int d) + {sIvokedMethod = 15; sA = a; sB = b; sC = c; sD = d;return sIvokedMethod;} +int localMethodR5(int a, int b, int c, int d, int e) + {sIvokedMethod = 16; sA = a; sB = b; sC = c; sD = d; sE = e;return sIvokedMethod;} +int localMethodR6(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 17; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;return sIvokedMethod;} +int localMethodR7(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 18; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;return sIvokedMethod;} +int localMethodR8(int a, int b, int c, int d, int e, int f, int g, int h) + {sIvokedMethod = 19; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h;return sIvokedMethod;} +int localMethodR9(int a, int b, int c, int d, int e, int f, int g, int h, int i) + {sIvokedMethod = 20; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h; sI = i;return sIvokedMethod;} + +void localMethodTL() + {sIvokedMethod = 21; } +void localMethodT1L(int a) + {sIvokedMethod = 22; sA = a;} +void localMethodT2L(int a, int b) + {sIvokedMethod = 23; sA = a; sB = b;} +void localMethodT3L(int a, int b, int c) + {sIvokedMethod = 24; sA = a; sB = b; sC = c;} +void localMethodT4L(int a, int b, int c, int d) + {sIvokedMethod = 25; sA = a; sB = b; sC = c; sD = d;} +void localMethodT5L(int a, int b, int c, int d, int e) + {sIvokedMethod = 26; sA = a; sB = b; sC = c; sD = d; sE = e;} +void localMethodT6L(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 27; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} +void localMethodT7L(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 28; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} +void localMethodT8L(int a, int b, int c, int d, int e, int f, int g, int h) + {sIvokedMethod = 29; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h;} +void localMethodT9L(int a, int b, int c, int d, int e, int f, int g, int h, int i) + {sIvokedMethod = 30; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h; sI = i;} + +void localLeavingMethodTL() + {sIvokedMethod = 31; User::Leave(-sIvokedMethod);} +void localLeavingMethodT1L(int a) + {sIvokedMethod = 32; sA = a;User::Leave(-sIvokedMethod);} +void localLeavingMethodT2L(int a, int b) + {sIvokedMethod = 33; sA = a; sB = b;User::Leave(-sIvokedMethod);} +void localLeavingMethodT3L(int a, int b, int c) + {sIvokedMethod = 34; sA = a; sB = b; sC = c;User::Leave(-sIvokedMethod);} +void localLeavingMethodT4L(int a, int b, int c, int d) + {sIvokedMethod = 35; sA = a; sB = b; sC = c; sD = d;User::Leave(-sIvokedMethod);} +void localLeavingMethodT5L(int a, int b, int c, int d, int e) + {sIvokedMethod = 36; sA = a; sB = b; sC = c; sD = d; sE = e;User::Leave(-sIvokedMethod);} +void localLeavingMethodT6L(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 37; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;User::Leave(-sIvokedMethod);} +void localLeavingMethodT7L(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 38; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;User::Leave(-sIvokedMethod);} +void localLeavingMethodT8L(int a, int b, int c, int d, int e, int f, int g, int h) + {sIvokedMethod = 39; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h;User::Leave(-sIvokedMethod);} +void localLeavingMethodT9L(int a, int b, int c, int d, int e, int f, int g, int h, int i) + {sIvokedMethod = 40; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g; sH = h; sI = i;User::Leave(-sIvokedMethod);} + + +class TestClass +{ +public: + void classMethod() + {sIvokedMethod = 41;} + void classMethod1(int a) + {sIvokedMethod = 42; sA = a;} + void classMethod2(int a, int b) + {sIvokedMethod = 43; sA = a; sB = b;} + void classMethod3(int a, int b, int c) + {sIvokedMethod = 44; sA = a; sB = b; sC = c;} + void classMethod4(int a, int b, int c, int d) + {sIvokedMethod = 45; sA = a; sB = b; sC = c; sD = d;} + void classMethod5(int a, int b, int c, int d, int e) + {sIvokedMethod = 46; sA = a; sB = b; sC = c; sD = d; sE = e;} + void classMethod6(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 47; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} + void classMethod7(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 48; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} + + int classMethodR() + {sIvokedMethod = 51;return sIvokedMethod;} + int classMethodR1(int a) + {sIvokedMethod = 52; sA = a;return sIvokedMethod;} + int classMethodR2(int a, int b) + {sIvokedMethod = 53; sA = a; sB = b;return sIvokedMethod;} + int classMethodR3(int a, int b, int c) + {sIvokedMethod = 54; sA = a; sB = b; sC = c;return sIvokedMethod;} + int classMethodR4(int a, int b, int c, int d) + {sIvokedMethod = 55; sA = a; sB = b; sC = c; sD = d;return sIvokedMethod;} + int classMethodR5(int a, int b, int c, int d, int e) + {sIvokedMethod = 56; sA = a; sB = b; sC = c; sD = d; sE = e;return sIvokedMethod;} + int classMethodR6(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 57; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;return sIvokedMethod;} + int classMethodR7(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 58; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;return sIvokedMethod;} + + void classMethodL() + {sIvokedMethod = 61;} + void classMethodL1(int a) + {sIvokedMethod = 62; sA = a;} + void classMethodL2(int a, int b) + {sIvokedMethod = 63; sA = a; sB = b;} + void classMethodL3(int a, int b, int c) + {sIvokedMethod = 64; sA = a; sB = b; sC = c;} + void classMethodL4(int a, int b, int c, int d) + {sIvokedMethod = 65; sA = a; sB = b; sC = c; sD = d;} + void classMethodL5(int a, int b, int c, int d, int e) + {sIvokedMethod = 66; sA = a; sB = b; sC = c; sD = d; sE = e;} + void classMethodL6(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 67; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} + void classMethodL7(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 68; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} + + void classMethodWithLeaveL() + {sIvokedMethod = 71;User::Leave(-sIvokedMethod);} + void classMethodWithLeave1L(int a) + {sIvokedMethod = 72; sA = a;User::Leave(-sIvokedMethod);} + void classMethodWithLeave2L(int a, int b) + {sIvokedMethod = 73; sA = a; sB = b;User::Leave(-sIvokedMethod);} + void classMethodWithLeave3L(int a, int b, int c) + {sIvokedMethod = 74; sA = a; sB = b; sC = c;User::Leave(-sIvokedMethod);} + void classMethodWithLeave4L(int a, int b, int c, int d) + {sIvokedMethod = 75; sA = a; sB = b; sC = c; sD = d;User::Leave(-sIvokedMethod);} + void classMethodWithLeave5L(int a, int b, int c, int d, int e) + {sIvokedMethod = 76; sA = a; sB = b; sC = c; sD = d; sE = e;User::Leave(-sIvokedMethod);} + void classMethodWithLeave6L(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 77; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;User::Leave(-sIvokedMethod);} + void classMethodWithLeave7L(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 78; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;User::Leave(-sIvokedMethod);} + + int classMethodRL() + {sIvokedMethod = 81;return sIvokedMethod;} + int classMethodR1L(int a) + {sIvokedMethod = 82; sA = a;return sIvokedMethod;} + int classMethodR2L(int a, int b) + {sIvokedMethod = 83; sA = a; sB = b;return sIvokedMethod;} + int classMethodR3L(int a, int b, int c) + {sIvokedMethod = 84; sA = a; sB = b; sC = c;return sIvokedMethod;} + int classMethodR4L(int a, int b, int c, int d) + {sIvokedMethod = 85; sA = a; sB = b; sC = c; sD = d;return sIvokedMethod;} + int classMethodR5L(int a, int b, int c, int d, int e) + {sIvokedMethod = 86; sA = a; sB = b; sC = c; sD = d; sE = e;return sIvokedMethod;} + int classMethodR6L(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 87; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;return sIvokedMethod;} + int classMethodR7L(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 88; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;return sIvokedMethod;} + + int classMethodWithLeaveRL() + {sIvokedMethod = 91;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR1L(int a) + {sIvokedMethod = 92; sA = a;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR2L(int a, int b) + {sIvokedMethod = 93; sA = a; sB = b;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR3L(int a, int b, int c) + {sIvokedMethod = 94; sA = a; sB = b; sC = c;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR4L(int a, int b, int c, int d) + {sIvokedMethod = 95; sA = a; sB = b; sC = c; sD = d;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR5L(int a, int b, int c, int d, int e) + {sIvokedMethod = 96; sA = a; sB = b; sC = c; sD = d; sE = e;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR6L(int a, int b, int c, int d, int e, int f) + {sIvokedMethod = 97; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveR7L(int a, int b, int c, int d, int e, int f, int g) + {sIvokedMethod = 98; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;User::Leave(-sIvokedMethod);return 0;} + + + + void classMethodC() const + {sIvokedMethod = 101;} + void classMethodC1(int a) const + {sIvokedMethod = 102; sA = a;} + void classMethodC2(int a, int b) const + {sIvokedMethod = 103; sA = a; sB = b;} + void classMethodC3(int a, int b, int c) const + {sIvokedMethod = 104; sA = a; sB = b; sC = c;} + void classMethodC4(int a, int b, int c, int d) const + {sIvokedMethod = 105; sA = a; sB = b; sC = c; sD = d;} + void classMethodC5(int a, int b, int c, int d, int e) const + {sIvokedMethod = 106; sA = a; sB = b; sC = c; sD = d; sE = e;} + void classMethodC6(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 107; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} + void classMethodC7(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 108; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} + + int classMethodRC() const + {sIvokedMethod = 111;return sIvokedMethod;} + int classMethodRC1(int a) const + {sIvokedMethod = 112; sA = a;return sIvokedMethod;} + int classMethodRC2(int a, int b) const + {sIvokedMethod = 113; sA = a; sB = b;return sIvokedMethod;} + int classMethodRC3(int a, int b, int c) const + {sIvokedMethod = 114; sA = a; sB = b; sC = c;return sIvokedMethod;} + int classMethodRC4(int a, int b, int c, int d) const + {sIvokedMethod = 115; sA = a; sB = b; sC = c; sD = d;return sIvokedMethod;} + int classMethodRC5(int a, int b, int c, int d, int e) const + {sIvokedMethod = 116; sA = a; sB = b; sC = c; sD = d; sE = e;return sIvokedMethod;} + int classMethodRC6(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 117; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;return sIvokedMethod;} + int classMethodRC7(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 118; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;return sIvokedMethod;} + + void classMethodCL() const + {sIvokedMethod = 121;} + void classMethodC1L(int a) const + {sIvokedMethod = 122; sA = a;} + void classMethodC2L(int a, int b) const + {sIvokedMethod = 123; sA = a; sB = b;} + void classMethodC3L(int a, int b, int c) const + {sIvokedMethod = 124; sA = a; sB = b; sC = c;} + void classMethodC4L(int a, int b, int c, int d) const + {sIvokedMethod = 125; sA = a; sB = b; sC = c; sD = d;} + void classMethodC5L(int a, int b, int c, int d, int e) const + {sIvokedMethod = 126; sA = a; sB = b; sC = c; sD = d; sE = e;} + void classMethodC6L(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 127; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;} + void classMethodC7L(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 128; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;} + + void classMethodWithLeaveCL() const + {sIvokedMethod = 131;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC1L(int a) const + {sIvokedMethod = 132; sA = a;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC2L(int a, int b) const + {sIvokedMethod = 133; sA = a; sB = b;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC3L(int a, int b, int c) const + {sIvokedMethod = 134; sA = a; sB = b; sC = c;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC4L(int a, int b, int c, int d) const + {sIvokedMethod = 135; sA = a; sB = b; sC = c; sD = d;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC5L(int a, int b, int c, int d, int e) const + {sIvokedMethod = 136; sA = a; sB = b; sC = c; sD = d; sE = e;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC6L(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 137; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;User::Leave(-sIvokedMethod);} + void classMethodWithLeaveC7L(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 138; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;User::Leave(-sIvokedMethod);} + + int classMethodRCL() const + {sIvokedMethod = 141;return sIvokedMethod;} + int classMethodRC1L(int a) const + {sIvokedMethod = 142; sA = a;return sIvokedMethod;} + int classMethodRC2L(int a, int b) const + {sIvokedMethod = 143; sA = a; sB = b;return sIvokedMethod;} + int classMethodRC3L(int a, int b, int c) const + {sIvokedMethod = 144; sA = a; sB = b; sC = c;return sIvokedMethod;} + int classMethodRC4L(int a, int b, int c, int d) const + {sIvokedMethod = 145; sA = a; sB = b; sC = c; sD = d;return sIvokedMethod;} + int classMethodRC5L(int a, int b, int c, int d, int e) const + {sIvokedMethod = 146; sA = a; sB = b; sC = c; sD = d; sE = e;return sIvokedMethod;} + int classMethodRC6L(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 147; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;return sIvokedMethod;} + int classMethodRC7L(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 148; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;return sIvokedMethod;} + + int classMethodWithLeaveRCL() const + {sIvokedMethod = 151;User::Leave(-sIvokedMethod); return 0;} + int classMethodWithLeaveRC1L(int a) const + {sIvokedMethod = 152; sA = a;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC2L(int a, int b) const + {sIvokedMethod = 153; sA = a; sB = b;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC3L(int a, int b, int c) const + {sIvokedMethod = 154; sA = a; sB = b; sC = c;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC4L(int a, int b, int c, int d) const + {sIvokedMethod = 155; sA = a; sB = b; sC = c; sD = d;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC5L(int a, int b, int c, int d, int e) const + {sIvokedMethod = 156; sA = a; sB = b; sC = c; sD = d; sE = e;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC6L(int a, int b, int c, int d, int e, int f) const + {sIvokedMethod = 157; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f;User::Leave(-sIvokedMethod);return 0;} + int classMethodWithLeaveRC7L(int a, int b, int c, int d, int e, int f, int g) const + {sIvokedMethod = 158; sA = a; sB = b; sC = c; sD = d; sE = e; sF = f; sG = g;User::Leave(-sIvokedMethod);return 0;} +}; + + +class MyFunctionServer: public java::util::FunctionServer +{ +public: + + MyFunctionServer() : + java::util::FunctionServer("JavaTestFunctionServer") + { + } + + virtual void doServerSideInit() + { + java::util::FunctionServer::doServerSideInit(); + sServerSideInitCalled = ++sIndex; + } + virtual void doServerSideClean() + { + sServerSideCleanCalled = ++sIndex; + } + virtual void startServer() + { + sStartServerCalled = ++sIndex; + java::util::FunctionServer::startServer(); + } +}; +class MyFunctionServer2 +{ + int a; +}; + +TEST_GROUP(TestFuncServerInit) +{ + TEST_SETUP() + { + sIvokedMethod = -1; + sA = -1; + sB = -1; + sC = -1; + sD = -1; + sE = -1; + sF = -1; + sG = -1; + sH = -1; + sI = -1; + sServerSideInitCalled = 0; + sServerSideCleanCalled = 0; + sStartServerCalled = 0; + sIndex = 0; + } + + TEST_TEARDOWN() + { + } +}; + + +TEST(TestFuncServerInit, startAndStop) +{ + MyFunctionServer* fserver = new MyFunctionServer(); + try + { + fserver->createServerToNewThread(); + fserver->stopServer(); + delete fserver; + fserver = 0; + } + catch(...) + { + FAIL("Unexpected exp in startAndStop\n"); + } + + CHECK(sServerSideInitCalled == 1); + CHECK(sStartServerCalled == 2); + CHECK(sServerSideCleanCalled == 3); +} + + + + + + + +TEST_GROUP(TestFuncServerNotOpened) +{ + MyFunctionServer* fserver; + TestClass* clazz; + int a; + int b; + int c; + int d; + int e; + int f; + int g; + int h; + int i; + + TEST_SETUP() + { + fserver = new MyFunctionServer(); + + sServerSideInitCalled = 0; + sServerSideCleanCalled = 0; + sStartServerCalled = 0; + sIndex = 0; + sIvokedMethod = -1; + sA = -1; + sB = -1; + sC = -1; + sD = -1; + sE = -1; + sF = -1; + sG = -1; + sH = -1; + sI = -1; + a = -1; + b = -1; + c = -1; + d = -1; + e = -1; + f = -1; + g = -1; + h = -1; + i = -1; + } + + TEST_TEARDOWN() + { + CHECK(sA == a); + CHECK(sB == b); + CHECK(sC == c); + CHECK(sD == d); + CHECK(sE == e); + CHECK(sF == f); + CHECK(sG == g); + CHECK(sH == h); + CHECK(sI == i); + delete fserver; + fserver = 0; + } +}; + + +TEST(TestFuncServerNotOpened, closeWithoutOpen) +{ + try + { + fserver->stopServer(); + + } + catch(...) + { + FAIL("UNexpected exp in closeWithoutOpen\n"); + } + CHECK(sServerSideInitCalled == 0); + CHECK(sStartServerCalled == 0); + CHECK(sServerSideCleanCalled == 0); +} + + +TEST(TestFuncServerNotOpened, sendWithoutOpen) +{ + try + { + CallMethod(localMethod, fserver); + } + catch (ExceptionBase& e) + { + CHECK(e.toString().find("Trying to execute code in non-existing FS: ") != std::string::npos) + CHECK(e.toString().find(" server not created.") != std::string::npos) + } + catch(...) + { + FAIL("UNexpected exp in closeWithoutOpen\n"); + } + CHECK(sIvokedMethod == -1); + CHECK(sServerSideInitCalled == 0); + CHECK(sStartServerCalled == 0); + CHECK(sServerSideCleanCalled == 0); +} + + +TEST(TestFuncServerNotOpened, sendWithoutOpenL) +{ + try + { + TRAPD(err, CallMethodL(localLeavingMethodTL, fserver)); + CHECK(err == KErrServerTerminated); + } + catch(...) + { + FAIL("UNexpected exp in closeWithoutOpen\n"); + } + CHECK(sIvokedMethod == -1); + CHECK(sServerSideInitCalled == 0); + CHECK(sStartServerCalled == 0); + CHECK(sServerSideCleanCalled == 0); +} + + +TEST(TestFuncServerNotOpened, sendAfterClose) +{ + try + { + fserver->createServerToNewThread(); + fserver->stopServer(); + CallMethod(localMethod, fserver); + } + catch (ExceptionBase& e) + { + CHECK(e.toString().find("Trying to execute code in non-existing FS: ") != std::string::npos) + CHECK(e.toString().find(" server closing.") != std::string::npos) + } + catch(...) + { + FAIL("UNexpected exp in closeWithoutOpen\n"); + } + CHECK(sIvokedMethod == -1); +} + +TEST(TestFuncServerNotOpened, sendAfterCloseL) +{ + try + { + fserver->createServerToNewThread(); + fserver->stopServer(); + TRAPD(err, CallMethodL(localLeavingMethodTL, fserver)); + CHECK(err == KErrServerTerminated); + } + catch(...) + { + FAIL("UNexpected exp in closeWithoutOpen\n"); + } + CHECK(sIvokedMethod == -1); +} + + + + + + + + + + + +TEST_GROUP(TestFuncServer) +{ + MyFunctionServer* fserver; + TestClass* clazz; + int a; + int b; + int c; + int d; + int e; + int f; + int g; + int h; + int i; + + TEST_SETUP() + { + fserver = new MyFunctionServer(); + clazz = new TestClass(); + + sServerSideInitCalled = 0; + sServerSideCleanCalled = 0; + sStartServerCalled = 0; + sIndex = 0; + fserver->createServerToNewThread(); + sIvokedMethod = -1; + sA = -1; + sB = -1; + sC = -1; + sD = -1; + sE = -1; + sF = -1; + sG = -1; + sH = -1; + sI = -1; + a = -1; + b = -1; + c = -1; + d = -1; + e = -1; + f = -1; + g = -1; + h = -1; + i = -1; + } + + TEST_TEARDOWN() + { + CHECK(sA == a); + CHECK(sB == b); + CHECK(sC == c); + CHECK(sD == d); + CHECK(sE == e); + CHECK(sF == f); + CHECK(sG == g); + CHECK(sH == h); + CHECK(sI == i); + delete clazz; + fserver->stopServer(); + delete fserver; + fserver = 0; + CHECK(sServerSideInitCalled == 1); + CHECK(sStartServerCalled == 2); + CHECK(sServerSideCleanCalled == 3); + } +}; + +// Calling local void methods. +TEST(TestFuncServer, localVoid0) +{ + CallMethod(localMethod, fserver); + CHECK(sIvokedMethod == 1); +} + +TEST(TestFuncServer, localVoid1) +{ + a = 1; + CallMethod(localMethod1, a, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid2) +{ + a = 2; + b = a + 1; + CallMethod(localMethod2, a, b, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid3) +{ + a = 3; + b = a + 1; + c = b + 1; + CallMethod(localMethod3, a, b, c, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid4) +{ + a = 4; + b = a + 1; + c = b + 1; + d = c + 1; + CallMethod(localMethod4, a, b, c, d, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid5) +{ + a = 5; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + CallMethod(localMethod5, a, b, c, d, e, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid6) +{ + a = 6; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + CallMethod(localMethod6, a, b, c, d, e, f, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid7) +{ + a = 7; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + CallMethod(localMethod7, a, b, c, d, e, f, g, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid8) +{ + a = 8; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + CallMethod(localMethod8, a, b, c, d, e, f, g, h, fserver); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localVoid9) +{ + a = 9; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + i = h + 1; + CallMethod(localMethod9, a, b, c, d, e, f, g, h, i, fserver); + CHECK(sIvokedMethod == a + 1); +} + + +// Calling methods that returns something. + +TEST(TestFuncServer, localReturn) +{ + int res = CallMethod(localMethodR, fserver); + CHECK(res == 11); + CHECK(sIvokedMethod == 11); +} + +TEST(TestFuncServer, localReturn1) +{ + a = 11; + int res = CallMethod(localMethodR1, a, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn2) +{ + a = 12; + b = a + 1; + int res = CallMethod(localMethodR2, a, b, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn3) +{ + a = 13; + b = a + 1; + c = b + 1; + int res = CallMethod(localMethodR3, a, b, c, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn4) +{ + a = 14; + b = a + 1; + c = b + 1; + d = c + 1; + int res = CallMethod(localMethodR4, a, b, c, d, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn5) +{ + a = 15; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res = CallMethod(localMethodR5, a, b, c, d, e, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn6) +{ + a = 16; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res = CallMethod(localMethodR6, a, b, c, d, e, f, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn7) +{ + a = 17; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res = CallMethod(localMethodR7, a, b, c, d, e, f, g, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn8) +{ + a = 18; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + int res = CallMethod(localMethodR8, a, b, c, d, e, f, g, h, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localReturn9) +{ + a = 19; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + i = h + 1; + int res = CallMethod(localMethodR9, a, b, c, d, e, f, g, h, i, fserver); + CHECK(res == a + 1); + CHECK(sIvokedMethod == a + 1); +} + + +// Calling methods through TRAP. + +TEST(TestFuncServer, localTrap0) +{ + int res = CallMethodTrap(localMethodTL, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == 21); +} + +TEST(TestFuncServer, localTrap1) +{ + a = 21; + int res = CallMethodTrap(localMethodT1L, a, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap2) +{ + a = 22; + b = a + 1; + int res = CallMethodTrap(localMethodT2L, a, b, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap3) +{ + a = 23; + b = a + 1; + c = b + 1; + int res = CallMethodTrap(localMethodT3L, a, b, c, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap4) +{ + a = 24; + b = a + 1; + c = b + 1; + d = c + 1; + int res = CallMethodTrap(localMethodT4L, a, b, c, d, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap5) +{ + a = 25; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res = CallMethodTrap(localMethodT5L, a, b, c, d, e, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap6) +{ + a = 26; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res = CallMethodTrap(localMethodT6L, a, b, c, d, e, f, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap7) +{ + a = 27; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res = CallMethodTrap(localMethodT7L, a, b, c, d, e, f, g, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap8) +{ + a = 28; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + int res = CallMethodTrap(localMethodT8L, a, b, c, d, e, f, g, h, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrap9) +{ + a = 29; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + i = h + 1; + int res = CallMethodTrap(localMethodT9L, a, b, c, d, e, f, g, h, i, fserver); + CHECK(res == 0); + CHECK(sIvokedMethod == a + 1); +} + +// Calling methods through TRAP. The method will leave. +TEST(TestFuncServer, localTrapWithLeave) +{ + int res = CallMethodTrap(localLeavingMethodTL, fserver); + CHECK(res == -31); + CHECK(sIvokedMethod == 31); +} + +TEST(TestFuncServer, localTrapWithLeave1) +{ + a = 31; + int res = CallMethodTrap(localLeavingMethodT1L, a, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave2) +{ + a = 32; + b = a + 1; + int res = CallMethodTrap(localLeavingMethodT2L, a, b, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave3) +{ + a = 33; + b = a + 1; + c = b + 1; + int res = CallMethodTrap(localLeavingMethodT3L, a, b, c, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave4) +{ + a = 34; + b = a + 1; + c = b + 1; + d = c + 1; + int res = CallMethodTrap(localLeavingMethodT4L, a, b, c, d, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave5) +{ + a = 35; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res = CallMethodTrap(localLeavingMethodT5L, a, b, c, d, e, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + + +TEST(TestFuncServer, localTrapWithLeave6) +{ + a = 36; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res = CallMethodTrap(localLeavingMethodT6L, a, b, c, d, e, f, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave7) +{ + a = 37; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res = CallMethodTrap(localLeavingMethodT7L, a, b, c, d, e, f, g, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave8) +{ + a = 38; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + int res = CallMethodTrap(localLeavingMethodT8L, a, b, c, d, e, f, g, h, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, localTrapWithLeave9) +{ + a = 39; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + h = g + 1; + i = h + 1; + int res = CallMethodTrap(localLeavingMethodT9L, a, b, c, d, e, f, g, h, i, fserver); + CHECK(res == -(a + 1)); + CHECK(sIvokedMethod == a + 1); +} + + +// Testing non-const void methods from a class. + +TEST(TestFuncServer, classVoid0) +{ + CallMethod( clazz, TestClass::classMethod, fserver ); + CHECK(sIvokedMethod == 41); +} + +TEST(TestFuncServer, classVoid1) +{ + a = 41; + CallMethod( clazz, TestClass::classMethod1, a, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid2) +{ + a = 42; + b = a + 1; + CallMethod( clazz, TestClass::classMethod2, a, b, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid3) +{ + a = 43; + b = a + 1; + c = b + 1; + CallMethod( clazz, TestClass::classMethod3, a, b, c, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid4) +{ + a = 44; + b = a + 1; + c = b + 1; + d = c + 1; + CallMethod( clazz, TestClass::classMethod4, a, b, c, d, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid5) +{ + a = 45; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + CallMethod( clazz, TestClass::classMethod5, a, b, c, d, e, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid6) +{ + a = 46; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + CallMethod( clazz, TestClass::classMethod6, a, b, c, d, e, f, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +TEST(TestFuncServer, classVoid7) +{ + a = 47; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + CallMethod( clazz, TestClass::classMethod7, a, b, c, d, e, f, g, fserver ); + CHECK(sIvokedMethod == a + 1); +} + +// Testing non-const methods from a class that returns a value. + +TEST(TestFuncServer, classReturn0) +{ + int res; + CallMethod(res, clazz, TestClass::classMethodR, fserver ); + CHECK(sIvokedMethod == 51); + CHECK(res == 51); + +} +TEST(TestFuncServer, classReturn1) +{ + a = 51; + int res; + CallMethod(res, clazz, TestClass::classMethodR1, a, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn2) +{ + a = 52; + b = a + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR2, a, b, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn3) +{ + a = 53; + b = a + 1; + c = b + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR3, a, b, c, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn4) +{ + a = 54; + b = a + 1; + c = b + 1; + d = c + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR4, a, b, c, d, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn5) +{ + a = 55; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR5, a, b, c, d, e, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn6) +{ + a = 56; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR6, a, b, c, d, e, f, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturn7) +{ + a = 57; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodR7, a, b, c, d, e, f, g, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} + +// Testing non-const void leaving methods from a class. Leave is not happening. + +TEST(TestFuncServer, classVoidL0) +{ + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL, fserver )); + CHECK(sIvokedMethod == 61); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL1) +{ + a = 61; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL1, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL2) +{ + a = 62; + b = a + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL2, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL3) +{ + a = 63; + b = a + 1; + c = b + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL3, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL4) +{ + a = 64; + b = a + 1; + c = b + 1; + d = c + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL4, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL5) +{ + a = 65; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL5, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL6) +{ + a = 66; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL6, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidL7) +{ + a = 67; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodL7, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} + +// Testing non-const void leaving methods from a class. Leave is happening. +TEST(TestFuncServer, classVoidLeavingL0) +{ + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveL, fserver )); + CHECK(sIvokedMethod == 71); + CHECK(res == -71); + +} +TEST(TestFuncServer, classVoidLeavingL1) +{ + a = 71; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL2) +{ + a = 72; + b = a + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL3) +{ + a = 73; + b = a + 1; + c = b + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL4) +{ + a = 74; + b = a + 1; + c = b + 1; + d = c + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL5) +{ + a = 75; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL6) +{ + a = 76; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingL7) +{ + a = 77; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeave7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} + +// Testing non-const value returning leaving methods from a class. Leave is not happening. + +TEST(TestFuncServer, classReturnL0) +{ + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRL, fserver )); + CHECK(sIvokedMethod == 81); + CHECK(res == 81); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL1) +{ + a = 81; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL2) +{ + a = 82; + b = a + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL3) +{ + a = 83; + b = a + 1; + c = b + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL4) +{ + a = 84; + b = a + 1; + c = b + 1; + d = c + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL5) +{ + a = 85; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL6) +{ + a = 86; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnL7) +{ + a = 87; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodR7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} + +// Testing non-const value returning leaving methods from a class. Leave is happening. + + +TEST(TestFuncServer, classReturnLeaveL0) +{ + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRL, fserver )); + CHECK(sIvokedMethod == 91); + CHECK(leaveRes == -91); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL1) +{ + a = 91; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL2) +{ + a = 92; + b = a + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL3) +{ + a = 93; + b = a + 1; + c = b + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL4) +{ + a = 94; + b = a + 1; + c = b + 1; + d = c + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL5) +{ + a = 95; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL6) +{ + a = 96; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} +TEST(TestFuncServer, classReturnLeaveL7) +{ + a = 97; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res=123; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveR7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 123); +} + +// Testing const void methods from a class. + +TEST(TestFuncServer, classVoidC0) +{ + CallMethod( clazz, TestClass::classMethodC, fserver ); + CHECK(sIvokedMethod == 101); + +} +TEST(TestFuncServer, classVoidC1) +{ + a = 101; + CallMethod( clazz, TestClass::classMethodC1, a, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC2) +{ + a = 102; + b = a + 1; + CallMethod( clazz, TestClass::classMethodC2, a, b, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC3) +{ + a = 103; + b = a + 1; + c = b + 1; + CallMethod( clazz, TestClass::classMethodC3, a, b, c, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC4) +{ + a = 104; + b = a + 1; + c = b + 1; + d = c + 1; + CallMethod( clazz, TestClass::classMethodC4, a, b, c, d, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC5) +{ + a = 105; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + CallMethod( clazz, TestClass::classMethodC5, a, b, c, d, e, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC6) +{ + a = 106; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + CallMethod( clazz, TestClass::classMethodC6, a, b, c, d, e, f, fserver ); + CHECK(sIvokedMethod == a + 1); + +} +TEST(TestFuncServer, classVoidC7) +{ + a = 107; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + CallMethod( clazz, TestClass::classMethodC7, a, b, c, d, e, f, g, fserver ); + CHECK(sIvokedMethod == a + 1); + +} + +// Testing const methods from a class retruning a value. + +TEST(TestFuncServer, classReturnC0) +{ + int res; + CallMethod(res, clazz, TestClass::classMethodRC, fserver ); + CHECK(sIvokedMethod == 111); + CHECK(res == 111); + +} +TEST(TestFuncServer, classReturnC1) +{ + a = 111; + int res; + CallMethod(res, clazz, TestClass::classMethodRC1, a, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC2) +{ + a = 112; + b = a + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC2, a, b, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC3) +{ + a = 113; + b = a + 1; + c = b + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC3, a, b, c, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC4) +{ + a = 114; + b = a + 1; + c = b + 1; + d = c + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC4, a, b, c, d, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC5) +{ + a = 115; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC5, a, b, c, d, e, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC6) +{ + a = 116; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC6, a, b, c, d, e, f, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} +TEST(TestFuncServer, classReturnC7) +{ + a = 117; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res; + CallMethod(res, clazz, TestClass::classMethodRC7, a, b, c, d, e, f, g, fserver ); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + +} + +// Testing const leaving void methods from a class. No leave. + + +TEST(TestFuncServer, classVoidCL0) +{ + TRAPD(res, CallMethodL(clazz, TestClass::classMethodCL, fserver )); + CHECK(sIvokedMethod == 121); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL1) +{ + a = 121; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL2) +{ + a = 122; + b = a + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL3) +{ + a = 123; + b = a + 1; + c = b + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL4) +{ + a = 124; + b = a + 1; + c = b + 1; + d = c + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL5) +{ + a = 125; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL6) +{ + a = 126; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} +TEST(TestFuncServer, classVoidCL7) +{ + a = 127; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodC7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == 0); + +} + + + +// Testing const leaving void methods from a class. Leaving. + + +TEST(TestFuncServer, classVoidLeavingCL0) +{ + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveCL, fserver )); + CHECK(sIvokedMethod == 131); + CHECK(res == -131); + +} +TEST(TestFuncServer, classVoidLeavingCL1) +{ + a = 131; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL2) +{ + a = 132; + b = a + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL3) +{ + a = 133; + b = a + 1; + c = b + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL4) +{ + a = 134; + b = a + 1; + c = b + 1; + d = c + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL5) +{ + a = 135; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL6) +{ + a = 136; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} +TEST(TestFuncServer, classVoidLeavingCL7) +{ + a = 137; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + TRAPD(res, CallMethodL(clazz, TestClass::classMethodWithLeaveC7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == -(a + 1)); + +} + + + +// Testing const leaving value returning methods from a class. Not leaving. +TEST(TestFuncServer, classReturnLC0) +{ + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRCL, fserver )); + CHECK(sIvokedMethod == 141); + CHECK(res == 141); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC1) +{ + a = 141; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC2) +{ + a = 142; + b = a + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC3) +{ + a = 143; + b = a + 1; + c = b + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC4) +{ + a = 144; + b = a + 1; + c = b + 1; + d = c + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC5) +{ + a = 145; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC6) +{ + a = 146; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} +TEST(TestFuncServer, classReturnLC7) +{ + a = 147; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodRC7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(res == a + 1); + CHECK(leaveRes == 0); +} + +// Testing const leaving value returning methods from a class. Leaving. + +TEST(TestFuncServer, classReturnLeaveCL0) +{ + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRCL, fserver )); + CHECK(sIvokedMethod == 151); + CHECK(leaveRes == -151); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL1) +{ + a = 151; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC1L, a, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL2) +{ + a = 152; + b = a + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC2L, a, b, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL3) +{ + a = 153; + b = a + 1; + c = b + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC3L, a, b, c, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL4) +{ + a = 154; + b = a + 1; + c = b + 1; + d = c + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC4L, a, b, c, d, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL5) +{ + a = 155; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC5L, a, b, c, d, e, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL6) +{ + a = 156; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC6L, a, b, c, d, e, f, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} +TEST(TestFuncServer, classReturnLeaveCL7) +{ + a = 157; + b = a + 1; + c = b + 1; + d = c + 1; + e = d + 1; + f = e + 1; + g = f + 1; + int res=456; + TRAPD(leaveRes, CallMethodL(res, clazz, TestClass::classMethodWithLeaveRC7L, a, b, c, d, e, f, g, fserver )); + CHECK(sIvokedMethod == a + 1); + CHECK(leaveRes == -(a + 1)); + CHECK(res == 456); +} + diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/inc/javainifileutils.h --- a/javacommons/utils/inc/javainifileutils.h Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/inc/javainifileutils.h Fri May 14 15:47:24 2010 +0300 @@ -65,7 +65,7 @@ private: static FileContent readFileContent(bool create=false); static void writeFileContent(const char* content); - static char* getPosition(FileContent& content, const std::string& property); + static const char* getPosition(FileContent& content, const std::string& property); }; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/inc/logger.h --- a/javacommons/utils/inc/logger.h Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/inc/logger.h Fri May 14 15:47:24 2010 +0300 @@ -115,6 +115,7 @@ EDebugApi, // =34 EJavaAppMngrPlugin, // =35 EJavaBroadcast, // =36 + EJavaAMMS, // =37 // add id of new components here }; @@ -171,6 +172,7 @@ {"JavaDebugApi.log", "[JavaDebugApi]"}, // EDebugApi {"JavaAppMngrPlugin.log","[JavaAppMngrPlugin]"}, // EJavaAppMngrPlugin {"JavaBroadcast.log", "[JavaBroadcast]"}, // EJavaBroadcast + {"JavaMMAPI.log", "[ MMAPPI ]"}, // EJavaAMMS // add new component file name and nickname here }; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUi.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUi.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUi.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -21,16 +21,12 @@ import com.nokia.mj.impl.utils.Logger; /** - * Base class for any UI interfaces. - * - * @author Nokia Corporation - * @version $Rev: 0 $ + * Base class for RuntimeUI implementation. */ public class RuntimeUi { /** Id for the log file where log entries are written. */ - private static final int LOG_ID = Logger.EJavaRuntime; - //private static final int LOG_ID = Logger.EJavaInstaller; + protected static int iLogId = Logger.EJavaRuntime; /** Identified flag. */ private boolean iIdentified = false; @@ -111,7 +107,7 @@ */ protected static void log(String aMsg) { - Logger.ILOG(LOG_ID, "RuntimeUi: " + aMsg); + Logger.ILOG(iLogId, "RuntimeUi: " + aMsg); } /** @@ -122,6 +118,6 @@ */ protected static void logError(String aMsg, Throwable aThrowable) { - Logger.ELOG(LOG_ID, "RuntimeUi: " + aMsg, aThrowable); + Logger.ELOG(iLogId, "RuntimeUi: " + aMsg, aThrowable); } } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUiFactory.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUiFactory.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/javasrc/com/nokia/mj/impl/rt/ui/RuntimeUiFactory.java Fri May 14 15:47:24 2010 +0300 @@ -21,9 +21,6 @@ /** * Factory for RuntimeUI interfaces. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class RuntimeUiFactory { diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfo.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfo.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,98 +0,0 @@ -/* -* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ - - -package com.nokia.mj.impl.runtime.rtport; - -/** - * Interface for getting runtime information. - * - * @see RuntimeInfoFactory - */ -public interface RuntimeInfo -{ - /** - * Defined constant for manufacturer domain - */ - final String MANUFACTURER_DOMAIN = "MFD"; - - /** - * Defined constant for identified third party domain - */ - final String IDENTIFIED_THIRD_PARTY_DOMAIN = "ITPD"; - /** - * Defined constant for operator domain - */ - final String OPERATOR_DOMAIN = "OPD"; - - /** - * Defined constant for unidentified third party domain - */ - final String UNIDENTIFIED_THIRD_PARTY_DOMAIN = "UTPD"; - - /** - * Gets the UI toolkit register for this runtime environment - */ - public UiToolkitRegister getUiToolkitRegister(); - - /** - * Returns object representing current application of the caller. The - * meaning of "current application" is specific to the runtime used - * (e.g. MIDlets, OSGi). - * - * The object has correct hashCode and equals method implementations to - * support usage as Hashtable key. The Id returned for different - * applications is unique within the same JVM process. - * - * The caller should not keep reference to the value after the application - * has been closed. - * - * @return Object representing current application - */ - public Object getApplicationId(); - - /** - * Returns the UID of the caller, or -1 if no UID is associated. - * - * @return UID of the caller, or -1 if no UID is associated - */ - public int getApplicationUid(); - - /** - * Returns protection domain of current application as String. - * - * Currently there are four defined domains - * - * @see #MANUFACTURER_DOMAIN - * @see #IDENTIFIED_THIRD_PARTY_DOMAIN - * @see #OPERATOR_DOMAIN - * @see #UNIDENTIFIED_THIRD_PARTY_DOMAIN - * - * @return protection domain as String - */ - public String getApplicationDomain(); - - /** - * Notifies the runtime that exit command has been received. - * It is runtime's responsibility to ensure that the application - * exits surely. - * - * @param aUid UID of the application to be closed. - */ - public void notifyExitCmd(int aUid); - -} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfoFactory.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfoFactory.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,47 +0,0 @@ -/* -* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ - - -package com.nokia.mj.impl.runtime.rtport; - -/** - * Factory to get the RuntimeInfo implementation. - * - * The RuntimeInfo implementation class is searched and dynamically loaded - * based on the value of "nokia.rt.port" system property. - * - * The class named "com.nokia.mj.impl.runtime.rtport..RuntimeInfoImpl" - * is tried to be loaded first, and if that is not found the value is tried to - * be used as a full class name. - * - * If the system property does not exist, then the default value "midp" is used. - */ -public class RuntimeInfoFactory -{ - /** RuntimeInfo instance */ - private static RuntimeInfo sInstance = new RuntimeInfoImpl(); - - /** - * Returns the RuntimeInfo - * - * @return RuntimeInfo - */ - public static RuntimeInfo getRuntimeInfo() - { - return sInstance; - } -} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfoImpl.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/RuntimeInfoImpl.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -/* -* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ - - -package com.nokia.mj.impl.runtime.rtport; - -import com.nokia.mj.impl.rt.support.ApplicationInfo; -import com.nokia.mj.impl.rt.support.ApplicationUtils; - -import com.nokia.mj.impl.utils.Logger; -import com.nokia.mj.impl.utils.Uid; - -public class RuntimeInfoImpl implements RuntimeInfo -{ - - UiToolkitRegisterImpl tk = new UiToolkitRegisterImpl(); - - public UiToolkitRegister getUiToolkitRegister() - { - return tk; - } - - public Object getApplicationId() - { -// return ApplicationInfo.getInstance().getName(); - return this; - } - - public int getApplicationUid() - { - try - { - String u = ApplicationInfo.getInstance().getUid().getStringValue(); - return Integer.parseInt(u.substring(1,u.length()-1), 16); - } - catch (Throwable t) - { - } - return 0x2001843A; // The JavaInstaller uid. - } - - public String getApplicationDomain() - { - try - { - return ApplicationInfo.getInstance().getProtectionDomain(); - } - catch (Throwable t) - { - } - return RuntimeInfo.MANUFACTURER_DOMAIN; - } - - public void notifyExitCmd(int aUid) - { - try - { - ApplicationUtils.getInstance().notifyExitCmd(); - } - catch (Throwable t) - { - Logger.ELOG(Logger.EUtils, - "RuntimeInfoImpl.notifyExitCmd(): Failed", - t); - } - } -} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/UiToolkitRegister.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/UiToolkitRegister.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* -* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ - - -package com.nokia.mj.impl.runtime.rtport; - -/** - * Common interface to UI Toolkit Register implementations. - */ -public interface UiToolkitRegister -{ - /** - * Registers given UI toolkit for current application. - * - * @param toolkitId ID of the toolkit - * @throws RuntimeException if given toolkit cannot be registered - * for current application. - */ - public void registerUiToolkit(String toolkitId); - - /** - * Clears the registered UI toolkit associated with current application. - * - * After this it is possible to register another UI toolkit. - * It is OK to call this even if a toolkit has not been registered. - * - * @param toolkitId ID of the toolkit to unregister - */ - public void unregisterUiToolkit(String toolkitId); - - /** - * Provides the names of the registered allowed toolkits. - * - * @return IDs of the allowed UI toolkits, or empty array if no toolkit - * has not yet been registered. - */ - public String[] getRegisteredUiToolkits(); - - /** - * Returns true if UI toolkit is foreground. - * - * @return true if toolkit is foreground. If toolkit has not set the value, - * false is returned. - */ - public boolean isToolkitForeground(); - - /** - * Changes the value to be returned from isToolkitForeground. - * - * @param foreground true if switched to foreground - */ - public void setToolkitForeground(boolean foreground); -} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/UiToolkitRegisterImpl.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/runtime/rtport/UiToolkitRegisterImpl.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -/* -* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ - - -package com.nokia.mj.impl.runtime.rtport; - -import com.nokia.mj.impl.rt.legacy.LegacySupport; - -/** - * Common interface to UI Toolkit Register implementations. - */ -public class UiToolkitRegisterImpl implements UiToolkitRegister -{ - private String mRegisteredToolkit; - private String[] mRegisteredToolkits; - - public void registerUiToolkit(String toolkitId) - { - if (mRegisteredToolkit != null) - { - throw new RuntimeException("Could not register toolkit: "+toolkitId); - } - mRegisteredToolkit = toolkitId; - mRegisteredToolkits = new String[1]; - mRegisteredToolkits[0] = mRegisteredToolkit; - } - - public void unregisterUiToolkit(String toolkitId) - { - if (mRegisteredToolkit != null && mRegisteredToolkit.equals(toolkitId)) - { - mRegisteredToolkit = null; - mRegisteredToolkits = null; - } - } - - public String[] getRegisteredUiToolkits() - { - if (mRegisteredToolkits == null) - { - return new String[0]; - } - return mRegisteredToolkits; - } - - /** - * Returns true if UI toolkit is foreground. - * - * @return true if toolkit is foreground. If toolkit has not set the value, - * false is returned. - */ - public boolean isToolkitForeground() - { - return false; - } - - /** - * Changes the value to be returned from isToolkitForeground. - * - * @param foreground true if switched to foreground - */ - public void setToolkitForeground(boolean foreground) - { - // Stop the start screen if exists. - } -} diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/utils/Base64.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Base64.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Base64.java Fri May 14 15:47:24 2010 +0300 @@ -17,6 +17,10 @@ package com.nokia.mj.impl.utils; +/** + * Base64 utility class originated from the public domain: + * see http://iharder.sourceforge.net/current/java/base64/ + */ public class Base64 { private final static byte[] ENCODE_ALPHABET = diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/utils/Formatter.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Formatter.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Formatter.java Fri May 14 15:47:24 2010 +0300 @@ -299,7 +299,7 @@ /** * Replace first occurrence of the string pattern in the replaced field. - * Replace only [NN] defined amount of characters. + * Replace [N...N] defined amount of characters. * * @param pattern string to search for * @param replacement string to replace patterns @@ -310,11 +310,10 @@ private boolean replaceWithMax(String pattern, String replacement, int maxIndex) { boolean result = false; - int closingIndex = maxIndex + pattern.length() + 3; + int closingIndex = replaced.indexOf("]", maxIndex + pattern.length()); - // Check format [NN] comply. If not skip. - if (replaced.length() > closingIndex - && replaced.charAt(closingIndex) == ']') + // Check format [N...N] comply. If not skip. + if (closingIndex > 0) { try { @@ -328,7 +327,7 @@ replaced = replaced.substring(0, maxIndex) + replacement.substring(0, maxLen) + - replaced.substring(maxIndex + pattern.length() + 4); + replaced.substring(closingIndex + 1); result = true; } catch (NumberFormatException nfe) diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/javasrc/com/nokia/mj/impl/utils/Logger.java --- a/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Logger.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/javasrc/com/nokia/mj/impl/utils/Logger.java Fri May 14 15:47:24 2010 +0300 @@ -80,6 +80,7 @@ public static final int EDebugApi = 34; public static final int EJavaAppMngrPlugin = 35; public static final int EJavaBroadcast = 36; + public static final int EJavaAMMS = 37; // add name of new components here @@ -136,6 +137,7 @@ false, //EDebugApi = 34; false, //EJavaAppMngrPlugin = 35; false, //EJavaBroadcast = 36; + false, //EJavaAMMS = 37; // add new components here }; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/src.s60/javaoslayer.cpp --- a/javacommons/utils/src.s60/javaoslayer.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/src.s60/javaoslayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -359,8 +359,10 @@ { std::string errorMsg("Cannot read ROM ODC files: "); errorMsg.append(strerror(errno)); + errorMsg.append(" : dir: "); + errorMsg.append(aDirPath.c_str()); ELOG(EUtils, errorMsg.c_str()); - throw ExceptionBase(errorMsg, __FILE__, __FUNCTION__, __LINE__); + // Suppres error if no Java at all on device ROM. } struct dirent* pDirEnt = readdir(pDIR); diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/src.s60/properties.cpp --- a/javacommons/utils/src.s60/properties.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/src.s60/properties.cpp Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2009-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -15,7 +15,6 @@ * */ - #include #include #include @@ -24,19 +23,6 @@ #include #include -#ifdef RD_JAVA_UI_QT - -#include - -#else // RD_JAVA_UI_QT - -#include -#include -#include -#include - -#endif // RD_JAVA_UI_QT - #include "javaenvinfo.h" #include "commonproperties.h" #include "javacommonutils.h" @@ -46,14 +32,6 @@ using namespace java::util; -jstring getS60LocaleL(JNIEnv* env); - -#ifndef RD_JAVA_UI_QT - -HBufC* getS60LocaleTempImplL(); - -#endif // RD_JAVA_UI_QT - HBufC* MicroEditionPlatformL(); TInt getHardwareVersionL(TDes& aHardwareType); @@ -64,57 +42,244 @@ _LIT(KMicroeditionPlatformVersion, "sw_platform_version="); _LIT(KMicroeditionPlatformJavaVersion, "java_build_version="); +_LIT(KMicroeditionLocaleAfrikaans, "af-ZA"); +_LIT(KMicroeditionLocaleAlbanian, "sq-SQ"); +_LIT(KMicroeditionLocaleArabic, "ar"); +_LIT(KMicroeditionLocaleBasque, "eu"); +_LIT(KMicroeditionLocaleIndonesian, "id-ID"); +_LIT(KMicroeditionLocaleMalay, "ms-MY"); +_LIT(KMicroeditionLocaleBulgarian, "bg-BG"); +_LIT(KMicroeditionLocaleCatalan, "ca"); +_LIT(KMicroeditionLocalePrcChinese, "zh-CN"); +_LIT(KMicroeditionLocaleHongKongChinese, "zh-HK"); +_LIT(KMicroeditionLocaleTaiwanChinese, "zh-TW"); +_LIT(KMicroeditionLocaleCroatian, "hr-HR"); +_LIT(KMicroeditionLocaleCzech, "cs-CZ"); +_LIT(KMicroeditionLocaleDanish, "da-DK"); +_LIT(KMicroeditionLocaleDutch, "nl-NL"); +_LIT(KMicroeditionLocaleEnglish, "en"); +_LIT(KMicroeditionLocaleAmerican, "en-US"); +_LIT(KMicroeditionLocaleEstonian, "et-EE"); +_LIT(KMicroeditionLocaleFarsi, "fa"); +_LIT(KMicroeditionLocaleFinnish, "fi-FI"); +_LIT(KMicroeditionLocaleFrench, "fr"); +_LIT(KMicroeditionLocaleCanadianFrench, "fr-CA"); +_LIT(KMicroeditionLocaleGalician, "gl"); +_LIT(KMicroeditionLocaleGerman, "de"); +_LIT(KMicroeditionLocaleGreek, "el-GR"); +_LIT(KMicroeditionLocaleHebrew, "he-IL"); +_LIT(KMicroeditionLocaleHindi, "hi-IN"); +_LIT(KMicroeditionLocaleMarathi, "mr-IN"); +_LIT(KMicroeditionLocaleHungarian, "hu-HU"); +_LIT(KMicroeditionLocaleIcelandic, "is-IS"); +_LIT(KMicroeditionLocaleItalian, "it"); +_LIT(KMicroeditionLocaleJapanese, "ja-JP"); +_LIT(KMicroeditionLocaleKorean, "ko-KR"); +_LIT(KMicroeditionLocaleLatvian, "lv-LV"); +_LIT(KMicroeditionLocaleLithuanian, "lt-LT"); +_LIT(KMicroeditionLocaleNorwegian, "no-NO"); +_LIT(KMicroeditionLocalePolish, "pl-PL"); +_LIT(KMicroeditionLocalePortuguese, "pt-PT"); +_LIT(KMicroeditionLocaleBrazilianPortuguese, "pt-BR"); +_LIT(KMicroeditionLocaleRomanian, "ro-RO"); +_LIT(KMicroeditionLocaleRussian, "ru-RU"); +_LIT(KMicroeditionLocaleSerbian, "sr-YU"); +_LIT(KMicroeditionLocaleSlovak, "sk-SK"); +_LIT(KMicroeditionLocaleSlovenian, "sl-SI"); +_LIT(KMicroeditionLocaleSpanish, "es-ES"); +_LIT(KMicroeditionLocaleLatinAmericanSpanish, "es-US"); +_LIT(KMicroeditionLocaleSwahili, "sw"); +_LIT(KMicroeditionLocaleSwedish, "sv"); +_LIT(KMicroeditionLocaleTagalog, "tl-PH"); +_LIT(KMicroeditionLocaleThai, "th-TH"); +_LIT(KMicroeditionLocaleTurkish, "tr-TR"); +_LIT(KMicroeditionLocaleUkrainian, "uk-UA"); +_LIT(KMicroeditionLocaleUrdu, "ur"); +_LIT(KMicroeditionLocaleVietnamese, "vi-VN"); +_LIT(KMicroeditionLocaleZulu, "zu"); + jstring java::util::getLocaleImpl(JNIEnv* env) { JELOG2(EUtils); -#ifdef RD_JAVA_UI_QT + // microedition.locale + switch (User::Language()) { + case ELangAfrikaans: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleAfrikaans); + case ELangAlbanian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleAlbanian); + + case ELangArabic: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleArabic); + +#if defined (__S60_50__) + case 327: // Indonesian in Asia-Pacific regions = 327 +#else + case ELangIndonesian_Apac: +#endif + + case ELangIndonesian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleIndonesian); - QString localeName = QLocale::system().name(); + case ELangMalay_Apac: + case ELangMalay: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleMalay); + + case ELangBasque: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleBasque); + + case ELangBulgarian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleBulgarian); + + case ELangCatalan: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleCatalan); + + case ELangPrcChinese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocalePrcChinese); + + case ELangHongKongChinese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleHongKongChinese); + + case ELangTaiwanChinese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleTaiwanChinese); - jstring loc = env->NewString(localeName.utf16(), localeName.size()); - if (!loc) - { - std::bad_alloc(); - } - return loc; + case ELangCroatian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleCroatian); + + case ELangCzech: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleCzech); + + case ELangDanish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleDanish); + + case ELangDutch: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleDutch); + + case ELangEnglish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleEnglish); + + case ELangAmerican: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleAmerican); + + case ELangEstonian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleEstonian); + + case ELangFarsi: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleFarsi); + + case ELangFinnish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleFinnish); + + case ELangFrench: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleFrench); + + case ELangCanadianFrench: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleCanadianFrench); + + case ELangGalician: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleGalician); + + case ELangGerman: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleGerman); + + case ELangGreek: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleGreek); + + case ELangHebrew: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleHebrew); -#else // RD_JAVA_UI_QT - jstring loc = 0; - HBufC* buf = 0; - bool usingTempSolution = false; - TRAPD(err, buf = AknLangUtils::DisplayLanguageTagL()); - if (buf == 0 && err == KErrNotSupported) - { - //At the moment DisplayLanguageTagL must be called from - //UI thread. Once this is fixed by the Avkon, we must - //use temporary solution. - usingTempSolution = true; - TRAP(err, buf = getS60LocaleTempImplL()); + case ELangHindi: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleHindi); + + case ELangHungarian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleHungarian); + + case ELangIcelandic: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleIcelandic); + + case ELangItalian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleItalian); + + case ELangJapanese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleJapanese); + + case ELangKorean: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleKorean); + + case ELangLatvian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleLatvian); + + case ELangLithuanian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleLithuanian); + + case ELangMarathi: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleMarathi); + + case ELangNorwegian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleNorwegian); + + case ELangPolish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocalePolish); + + case ELangPortuguese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocalePortuguese); + + case ELangBrazilianPortuguese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleBrazilianPortuguese); + + case ELangRomanian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleRomanian); + + case ELangRussian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleRussian); + + case ELangSerbian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSerbian); + + case ELangSlovak: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSlovak); + + case ELangSlovenian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSlovenian); + + case ELangSpanish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSpanish); + + case ELangLatinAmericanSpanish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleLatinAmericanSpanish); + + case ELangSwahili: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSwahili); + + case ELangSwedish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleSwedish); + + case ELangTagalog: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleTagalog); + + case ELangThai: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleThai); + + case ELangTurkish: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleTurkish); + + case ELangUkrainian: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleUkrainian); + + case ELangUrdu: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleUrdu); + + case ELangVietnamese: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleVietnamese); + + case ELangZulu: + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleZulu); } - if (buf == 0) - { - std::string errorStr = "Could not solve locale when using "; - if (usingTempSolution) - { - errorStr.append("temp"); - } - else - { - errorStr.append("original"); - } - errorStr.append(" solution. Leave code = "); - errorStr.append(JavaCommonUtils::intToString(err)); - throw ExceptionBase(errorStr, - __FILE__,__FUNCTION__,__LINE__); - } - const jchar* stringPtr = buf->Ptr(); - const jsize stringLength = buf->Length(); - loc = env->NewString(stringPtr, stringLength); - delete buf; - return loc; -#endif // RD_JAVA_UI_QT + // According to MIDP2.0 spec the locale property, if not null, MUST + // consist of the language and MAY optionally also contain the country + // code, and variant separated by - + return S60CommonUtils::NativeToJavaString(*env, KMicroeditionLocaleEnglish); } jstring java::util::getPlatformImpl(JNIEnv* aEnv) @@ -133,31 +298,6 @@ return platform; } -#ifndef RD_JAVA_UI_QT - -HBufC* getS60LocaleTempImplL() -{ - JELOG2(EUtils); - _LIT(KFileName, "z:\\resource\\avkon.rsc"); - TFileName fileName(KFileName); - RFs iRFs; - CleanupClosePushL(iRFs); - User::LeaveIfError(iRFs.Connect()); - BaflUtils::NearestLanguageFile(iRFs, fileName); - RResourceFile resourceFile; - CleanupClosePushL(resourceFile); - resourceFile.OpenL(iRFs, fileName); - resourceFile.ConfirmSignatureL(0); - HBufC8* textBuf8 = resourceFile.AllocReadLC(R_QTN_LANGUAGE_RFC3066_TAG); - const TPtrC16 ptrBuf8((TText16*) textBuf8->Ptr(), (textBuf8->Length() + 1) >> 1); - HBufC16* tag = ptrBuf8.AllocL(); - CleanupStack::PopAndDestroy(3); - return tag; - -} - -#endif // RD_JAVA_UI_QT - HBufC* GetPlatformVersionL() { VersionInfo::TPlatformVersion platformVersion; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/src/javainifileutils.cpp --- a/javacommons/utils/src/javainifileutils.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/src/javainifileutils.cpp Fri May 14 15:47:24 2010 +0300 @@ -19,8 +19,8 @@ #include #include #include - #include +#include #include "logger.h" #include "javainifileutils.h" @@ -118,12 +118,12 @@ #endif // RD_JAVA_INI_FILE_ACCESS_IN_USE -char* JavaIniFileUtils::getPosition(FileContent& content, const std::string& property) +const char* JavaIniFileUtils::getPosition(FileContent& content, const std::string& property) { const char* data = content.getContent(); if (data) { - char* position = strstr(data, property.c_str()); + const char* position = strstr(data, property.c_str()); if (position) { position += property.length()+2; diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/src/monitor.cpp --- a/javacommons/utils/src/monitor.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/src/monitor.cpp Fri May 14 15:47:24 2010 +0300 @@ -97,7 +97,7 @@ currentTimeVal.tv_usec * 1000 + (timeOut % 1000) * 1000 * 1000; int err = pthread_cond_timedwait(&mCondVar, &mMutex, &timeOutTime); - if (err != ETIMEDOUT) + if (err != 0 && err != ETIMEDOUT) { ELOG1(EUtils, "Monitor: Timed wait failed, err = %d", err); } diff -r 2a9601315dfc -r 98ccebc37403 javacommons/utils/tsrc/localisation/javasrc/com/nokia/mj/test/utils/LocalisationTest.java --- a/javacommons/utils/tsrc/localisation/javasrc/com/nokia/mj/test/utils/LocalisationTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javacommons/utils/tsrc/localisation/javasrc/com/nokia/mj/test/utils/LocalisationTest.java Fri May 14 15:47:24 2010 +0300 @@ -180,14 +180,14 @@ "Test %U[20", new Formatter("Test %U[20").arg("testMyTest").toString()); - // Test %U[300] Skip + // Test %U[300] assertEquals( - "Test %U[300]", + "Test testMyTest", new Formatter("Test %U[300]").arg("testMyTest").toString()); - // Test %U[8] Skip + // Test %U[8] assertEquals( - "Test %U[8]", + "Test testMyTe", new Formatter("Test %U[8]").arg("testMyTest").toString()); // Test Max is higher than actual string. Expected output: whole string no padding. diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/bluetooth/bluetoothcommons/build/javabluetoothcommons.pro --- a/javaextensions/bluetooth/bluetoothcommons/build/javabluetoothcommons.pro Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/bluetooth/bluetoothcommons/build/javabluetoothcommons.pro Fri May 14 15:47:24 2010 +0300 @@ -26,7 +26,7 @@ SOURCES += ../bluetoothplatformcontrol/src.s60/*.cpp } -LIBS += -lsdpdatabase -lbtengsettings -lbtnotif -lbluetooth -lbtmanclient \ +LIBS += -lsdpdatabase -lbtengsettings -lbluetooth -lbtmanclient \ -lbtdevice -ljavacomms -ljavafileutils -lesock diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/bluetooth/bluetoothcommons/inc.s60/bluetoothclientconnection.h --- a/javaextensions/bluetooth/bluetoothcommons/inc.s60/bluetoothclientconnection.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/bluetooth/bluetoothcommons/inc.s60/bluetoothclientconnection.h Fri May 14 15:47:24 2010 +0300 @@ -73,8 +73,8 @@ * connection open, all we do here is to add the object to Active Scheduler. */ OS_IMPORT - void BluetoothClientConnection::initialize(int protocol, - TInt64 aRemoteAddr, int aReceiveMtu, int aTransmitMtu); + void initialize(int protocol, TInt64 aRemoteAddr, + int aReceiveMtu, int aTransmitMtu); /** * Used to Initialize the protocol specific options of the Bluetooth Socket. diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/broadcast_stub/build/build.xml --- a/javaextensions/broadcast_stub/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/broadcast_stub/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -43,6 +43,9 @@ javax/microedition/broadcast/connection/BroadcastConnectionListener.class, javax/microedition/broadcast/connection/BroadcastDatagramConnection.class, javax/microedition/broadcast/connection/BroadcastFileConnection.class, + javax/microedition/broadcast/control/NTPTimeControl.class, + javax/microedition/broadcast/control/TimeShiftControl.class, + javax/microedition/broadcast/control/TimerEventsControl.class, javax/microedition/broadcast/esg/Attribute.class, javax/microedition/broadcast/esg/BooleanAttribute.class, javax/microedition/broadcast/esg/CommonMetadataSet.class, diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/broadcast_stub/build/javabroadcast.pro --- a/javaextensions/broadcast_stub/build/javabroadcast.pro Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/broadcast_stub/build/javabroadcast.pro Fri May 14 15:47:24 2010 +0300 @@ -16,7 +16,7 @@ TARGET=javabroadcast TEMPLATE=lib -CONFIG += omj java javaonly +CONFIG += omj java javaonly stl CONFIG -= qt include(../../../build/omj.pri) diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/iapinfo/javasrc.s60/com/nokia/mid/iapinfo/IAPInfoImpl.java --- a/javaextensions/iapinfo/javasrc.s60/com/nokia/mid/iapinfo/IAPInfoImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/iapinfo/javasrc.s60/com/nokia/mid/iapinfo/IAPInfoImpl.java Fri May 14 15:47:24 2010 +0300 @@ -31,8 +31,6 @@ /** * Implementation class of the APNInfo interface - * - * @version 0.1 First version of the implementation. */ class IAPInfoImpl extends IAPInfo { diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/common/inc/cleanupresetanddestroy.h --- a/javaextensions/location/common/inc/cleanupresetanddestroy.h Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,114 +0,0 @@ -/* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: Cleanup Stack "reset and destroy" push operation. - * -*/ - - -#ifndef CLEANUPRESETANDDESTROY_H -#define CLEANUPRESETANDDESTROY_H - -// INCLUDE FILES -#include - -/** - * An operation for pushing objects to cleanup stack with \c TCleanupItems - * that will perform a \c ResetAndDestroy() operation on the pushed object - * if a leave occurs. - * - * Note that the object itself will not be deleted. - * - * @par Example: - * Here is an example of using \c CleanupResetAndDestroy with a dynamically - * allocated \c RPointerArray. \c RPointerArray clears its contents with a - * \cResetAndDestroy() operation. - * @code - * - * // A function which creates a pointer array with couple of initialized - * // CThings. The function must return a pointer to the pointer array, - * // because the array has to be allocated dynamically. CThing is some - * // simple CBase-derived class. - * - * RPointerArray< CThing >* CreateThingArrayL( ) - * { - * // Create an array of pointers to CThings with granularity of 4 - * - * RPointerArray< CThing >* things = - * new( ELeave ) RPointerArray< CThing >( 4 ); - * - * // Push pointer to the array to the cleanup stack; then push reference - * // to the array and a ResetAndDestroy operation to the cleanup stack. - * - * // (Note that order of these operations matters: the ResetAndDestroy - * // operation must be performed before the array itself is deleted.) - * - * CleanupStack::PushL( things ); - * CleanupResetAndDestroyPushL( *things ); - * - * // Add couple of CThings with magic numbers to the array. - * // If any of the NewL() operations leaves, the array will be cleared - * // with ResetAndDestroy() and the array itself will destroyed. - * - * User::LeaveIfError( things->Append( CThing::NewL( 7 ) ) ); - * User::LeaveIfError( things->Append( CThing::NewL( 96 ) ) ); - * User::LeaveIfError( things->Append( CThing::NewL( 999 ) ) ); - * - * // Pop the array reference with ResetAndDestroy from cleanup stack; - * // then pop the pointer to the array itself. - * - * CleanupStack::Pop(); // *things - * CleanupStack::Pop(); // things - * - * // Now we're ready to return the results (a pointer to the array) - * return things; - * } - * - * @endcode - */ -template -inline void CleanupResetAndDestroyPushL(T& aRef); - -/** - * See \ref CleanupResetAndDestroyPushL() documentation. - */ -template -class CleanupResetAndDestroy -{ -public: - inline static void PushL(T& aRef); - -private: - static void ResetAndDestroy(TAny *aPtr); -}; - -template -inline void CleanupResetAndDestroy::PushL(T& aRef) -{ - CleanupStack::PushL(TCleanupItem(&ResetAndDestroy, &aRef)); -} - -template -void CleanupResetAndDestroy::ResetAndDestroy(TAny *aPtr) -{ - static_cast(aPtr)->ResetAndDestroy(); -} - -template -inline void CleanupResetAndDestroyPushL(T& aRef) -{ - CleanupResetAndDestroy::PushL(aRef); -} - -#endif // CLEANUPRESETANDDESTROY_H -// End of File diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/common/src/lapijnicommon.cpp --- a/javaextensions/location/common/src/lapijnicommon.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/common/src/lapijnicommon.cpp Fri May 14 15:47:24 2010 +0300 @@ -19,7 +19,7 @@ // INTERNAL INCLUDES #include "lapijnicommon.h" #include "clapilandmark.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "lapipanics.h" #include "jstringutils.h" #include "s60commonutils.h" diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/landmarks/src/clapilandmarkstore.cpp --- a/javaextensions/location/landmarks/src/clapilandmarkstore.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/landmarks/src/clapilandmarkstore.cpp Fri May 14 15:47:24 2010 +0300 @@ -23,7 +23,7 @@ #include "clapilandmarksearchfactory.h" #include "clapilandmark.h" #include "tlapisearchcriteria.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "lapipanics.h" #include "logger.h" diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/landmarks/src/landmark.cpp --- a/javaextensions/location/landmarks/src/landmark.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/landmarks/src/landmark.cpp Fri May 14 15:47:24 2010 +0300 @@ -24,7 +24,7 @@ #include "logger.h" #include "clapilandmark.h" #include "clapiaddressinfo.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "locationfunctionserver.h" using namespace java::location; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/orientation/inc/corientation.h --- a/javaextensions/location/orientation/inc/corientation.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/orientation/inc/corientation.h Fri May 14 15:47:24 2010 +0300 @@ -34,7 +34,7 @@ { namespace location { - +// re arrange this header file to have more readable format class COrientation: public CBase, public MSensrvDataListener { public: @@ -44,6 +44,9 @@ // Channel Info TSensrvChannelInfo ichannelInfo; + + // Location Function Server + LocationFunctionServer* mFunctionServer; public: // Constructors and destructor @@ -79,13 +82,9 @@ /** * Opens the Channel and Starts the Data Listening - * @return Error number which indicates either sucess or failure + * @return */ - TInt GetOrientationL(); - -public: - // Location Function Server - LocationFunctionServer* mFunctionServer; + void GetOrientationL(); private: // new methods @@ -93,7 +92,7 @@ /** * Opens the the Channel */ - TInt OpenChannel(); + void OpenChannelL(); /** * Creates the Channel Finder @@ -108,13 +107,10 @@ /** * Checks the hardware caliberation */ - TInt CheckCalibration(); + void CheckCalibrationL(); private: - // JNI Environment Data - JNIEnv* mJni; - jobject mPeer; jclass iOrientationClass; // Azimuth Data Callback JNI Method ID diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/orientation/src/corientation.cpp --- a/javaextensions/location/orientation/src/corientation.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/orientation/src/corientation.cpp Fri May 14 15:47:24 2010 +0300 @@ -48,7 +48,6 @@ // void COrientation::NewL(TInt* aHandle) { - // CallMethodL(new(ELeave) COrientation(), aserver); COrientation* self = new(ELeave) COrientation(); *aHandle = reinterpret_cast(self); } @@ -59,7 +58,7 @@ // COrientation::~COrientation() { - if (iXYZChannel) + if (iXYZChannel) { delete iXYZChannel; iXYZChannel = NULL; @@ -79,105 +78,58 @@ // COrientation::GetOrientation // --------------------------------------------------------------------------- // -TInt COrientation::GetOrientationL() +void COrientation::GetOrientationL() { - mJni = mFunctionServer->getValidJniEnv(); - mPeer = mFunctionServer->getPeer(); - + iOrientationClass = - mJni->FindClass("javax/microedition/location/Orientation"); + (mFunctionServer->getValidJniEnv())->FindClass( + "javax/microedition/location/Orientation"); //Get Method ID of Azimuth Data Callback - mAzimuthDataMethod = mJni->GetStaticMethodID(iOrientationClass, - "AzimuthDataCallBack", - "(I)V"); + mAzimuthDataMethod = (mFunctionServer->getValidJniEnv())->GetStaticMethodID( + iOrientationClass, + "AzimuthDataCallBack", + "(I)V"); //Check if all the JNI inits have succeeded if (NULL == mAzimuthDataMethod) { - return KErrGeneral; + User::Leave( KErrGeneral); } - TInt Err = KErrNone; - TInt result = this->OpenChannel(); - - if (result == KErrNone) - { - TInt CalibErr = CheckCalibration(); - - if (CalibErr < KErrNone) - { - return CalibErr; - } + OpenChannelL(); - TRAP(Err, iXYZChannel->StartDataListeningL(this, 1, 1, 0)); + CheckCalibrationL(); - if (Err == KErrNotFound) - { - return Err; - } - else if (Err == KErrAlreadyExists) - { - return Err; - } - } + iXYZChannel->StartDataListeningL(this, 1, 1, 0); - return result; } // --------------------------------------------------------------------------- // COrientation::OpenChannel // --------------------------------------------------------------------------- // -TInt COrientation::OpenChannel() +void COrientation::OpenChannelL() { - TInt ChnlFindErr = 0; - TRAP(ChnlFindErr, this->CreateChannelFinderL()); - - if (ChnlFindErr < 0) - { - return ChnlFindErr; - } + CreateChannelFinderL(); iChannelInfoList.Reset(); - TInt FindErr = 0; - TRAP(FindErr, iChannelFinder->FindChannelsL(iChannelInfoList, - ichannelInfo)); - - if (FindErr < KErrNone) + iChannelFinder->FindChannelsL(iChannelInfoList, + ichannelInfo); + + if (iChannelInfoList.Count() != 1) { - return FindErr; - } - - else if (iChannelInfoList.Count() != 1) - { - return ERROR; + User::Leave( ERROR); } else { - TInt SensChanlErr = 0; - TRAP(SensChanlErr, this->CreateSensorChannelL()); - - if (SensChanlErr < 0) - { - return SensChanlErr; - } - - TInt err = 0; - TRAP(err, iXYZChannel->OpenChannelL()); + + CreateSensorChannelL(); - if (err == KErrNotFound) - { - return err; - } - else if (err == KErrAlreadyExists) - { - return err; - } + iXYZChannel->OpenChannelL(); + } - - return KErrNone; } // --------------------------------------------------------------------------- @@ -207,9 +159,8 @@ iXYZChannel->StopDataListening(); iXYZChannel->CloseChannel(); - mJni = mFunctionServer->getValidJniEnv(); - - (*mJni).CallStaticVoidMethod(iOrientationClass, mAzimuthDataMethod, err); + (mFunctionServer->getValidJniEnv())->CallStaticVoidMethod( + iOrientationClass, mAzimuthDataMethod, err); } } @@ -227,12 +178,12 @@ iXYZChannel->StopDataListening(); iXYZChannel->CloseChannel(); - mJni = mFunctionServer->getValidJniEnv(); - if (info.iChannelType == KSensrvChannelTypeIdMagneticNorthData) { - (*mJni).CallStaticVoidMethod(iOrientationClass, - mAzimuthDataMethod, aError); + (mFunctionServer->getValidJniEnv())->CallStaticVoidMethod( + iOrientationClass, + mAzimuthDataMethod, + aError); } } @@ -281,28 +232,21 @@ // COrientation::CheckCalibration // --------------------------------------------------------------------------- // -TInt COrientation::CheckCalibration() +void COrientation::CheckCalibrationL() { TSensrvProperty property; TInt value(0); TInt maxValue(0); - TInt LeaveError(KErrNone); - TRAP(LeaveError, iXYZChannel->GetPropertyL(KSensrvPropCalibrationLevel, - KSensrvItemIndexNone, property)); - - if (LeaveError < KErrNone) - { - return LeaveError; - } + iXYZChannel->GetPropertyL(KSensrvPropCalibrationLevel, + KSensrvItemIndexNone, property); property.GetValue(value); property.GetMaxValue(maxValue); if (value != maxValue) { - return CALIBRATIONERROR; + User::Leave( CALIBRATIONERROR); } - return KErrNone; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/location/orientation/src/orientation.cpp --- a/javaextensions/location/orientation/src/orientation.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/location/orientation/src/orientation.cpp Fri May 14 15:47:24 2010 +0300 @@ -73,14 +73,9 @@ KSensrvChannelTypeIdMagneticNorthData; Orientation->mFunctionServer = server; - TInt error = KErrNone; - TRAPD(err,CallMethodL(error, Orientation,&COrientation::GetOrientationL,server)); - if (error < KErrNone) - { - err = error; - } - + TRAPD(err,CallMethodL( Orientation,&COrientation::GetOrientationL,server)); + return err; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/midppush/pushcontroller/src/pushserverconnpluginmanager.cpp --- a/javaextensions/midppush/pushcontroller/src/pushserverconnpluginmanager.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/midppush/pushcontroller/src/pushserverconnpluginmanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -367,7 +367,7 @@ std::string dllNameStr(PREFIX_OF_SRV_CONN_PLUGIN); dllNameStr.append(schemeStr); dllNameStr.append(SUFFIX_OF_SRV_CONN_PLUGIN); - WLOG1(EJavaPush,"Name of the loaded dll: %s",dllNameStr.c_str()); + ILOG1(EJavaPush,"Name of the loaded dll: %s",dllNameStr.c_str()); return dllNameStr; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoPermission.java --- a/javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoPermission.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoPermission.java Fri May 14 15:47:24 2010 +0300 @@ -27,6 +27,7 @@ // the known target names private static final String IMSI_TARGET_NAME = "mobinfo.imsi"; private static final String MSISDN_TARGET_NAME = "mobinfo.msisdn"; + private static final String CELLID_TARGET_NAME = "mobinfo.cellid"; private static final String PUBLIC_INFO_TARGET_NAME = "mobinfo.publicinfo"; private String iTarget = null; @@ -38,6 +39,7 @@ // figure out the target if (IMSI_TARGET_NAME.equals(aUri) || MSISDN_TARGET_NAME.equals(aUri) + || CELLID_TARGET_NAME.equals(aUri) || PUBLIC_INFO_TARGET_NAME.equals(aUri)) { // aUri contains a known target name -> save it as such @@ -56,6 +58,10 @@ { iTarget = MSISDN_TARGET_NAME; } + else if (MobileInfoProperties.CELLID.equals(aUri)) + { + iTarget = CELLID_TARGET_NAME; + } else { iTarget = PUBLIC_INFO_TARGET_NAME; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoProperties.java --- a/javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoProperties.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/mobinfo/javasrc.s60/com/nokia/mj/impl/properties/mobinfo/MobileInfoProperties.java Fri May 14 15:47:24 2010 +0300 @@ -67,7 +67,7 @@ private static final String EMAIL_SEND_SETTINGS = "com.nokia.mid.settings.email-send-protocol"; - private static final String CELLID = "com.nokia.mid.cellid"; + static final String CELLID = "com.nokia.mid.cellid"; static final String MSISDN = "com.nokia.mid.msisdn"; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/inc.s60/cpimagnlistadapter.h --- a/javaextensions/pim/agnadapter/inc.s60/cpimagnlistadapter.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/inc.s60/cpimagnlistadapter.h Fri May 14 15:47:24 2010 +0300 @@ -225,8 +225,7 @@ GetExternalItemModificationsByEntryTypeL( CCalEntry::TType aEntryType); - void CPIMAgnListAdapter::DoExternalItemModificationsByEntryTypeL( - CCalEntry::TType aEntryType); + void DoExternalItemModificationsByEntryTypeL(CCalEntry::TType aEntryType); /** * Fetches a CAgnEntry from the native Agenda Model. @@ -268,7 +267,8 @@ * * @param aEntryType Entry type for change callbacks (ToDo/Event/all). */ - void ConstructL(MCalChangeCallBack::TChangeEntryType aEntryType); + void ConstructL(MCalChangeCallBack::TChangeEntryType aEntryType, + CCalSession* aCalSession); void DoClose(); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/inc.s60/cpimeventadapteraccess.h --- a/javaextensions/pim/agnadapter/inc.s60/cpimeventadapteraccess.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/inc.s60/cpimeventadapteraccess.h Fri May 14 15:47:24 2010 +0300 @@ -73,13 +73,17 @@ MPIMLocalizationData** aRetLocalizationData); TBool OpenEventListL( - const TDesC* aListName, + CCalSession* aCalSession, + + const TDesC* aListName, MPIMEventAdapterManager** aRetAdapterManager, MPIMEventListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData); TBool OpenToDoListL( - const TDesC* aListName, + CCalSession* aCalSession, + + const TDesC* aListName, MPIMToDoAdapterManager** aRetAdapterManager, MPIMToDoListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/inc.s60/cpimeventlistadapter.h --- a/javaextensions/pim/agnadapter/inc.s60/cpimeventlistadapter.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/inc.s60/cpimeventlistadapter.h Fri May 14 15:47:24 2010 +0300 @@ -27,6 +27,7 @@ // FORWARD DECLARATIONS class MPIMEventItem; class CPIMAgnEventAdapter; +class CCalSession; // CLASS DECLARATION @@ -47,7 +48,8 @@ static CPIMEventListAdapter* NewL( CCalEntry::TType aEntryType, CPIMAgnEventAdapter* aEventAdapter, - java::util::FunctionServer* aFuncServer); + java::util::FunctionServer* aFuncServer, + CCalSession *aCalSession); /** * Destructor. @@ -137,8 +139,7 @@ */ void CreateEventItemL(MPIMEventItem& aEventItem); - void CPIMEventListAdapter::DoCreateEventItemL( - MPIMEventItem& aEventItem); + void DoCreateEventItemL(MPIMEventItem& aEventItem); /** * Reads an existing event item from the Agenda File. @@ -163,8 +164,7 @@ */ void ReadEventItemL(MPIMEventItem& aEventItem); - void CPIMEventListAdapter::DoReadEventItemL( - MPIMEventItem& aEventItem); + void DoReadEventItemL(MPIMEventItem& aEventItem); /** * Writes an existing event item to the native Agenda File. @@ -190,8 +190,7 @@ */ void WriteEventItemL(MPIMEventItem& aEventItem); - void CPIMEventListAdapter::DoWriteEventItemL( - MPIMEventItem& aEventItem); + void DoWriteEventItemL(MPIMEventItem& aEventItem); /** * Removes an existing event from the native Agenda File. @@ -211,8 +210,7 @@ */ void RemoveEventItemL(TPIMItemID aItemID); - void CPIMEventListAdapter::DoRemoveEventItemL( - TPIMItemID aItemID); + void DoRemoveEventItemL(TPIMItemID aItemID); protected: @@ -226,7 +224,9 @@ */ void ConstructL( CCalEntry::TType aEntryType, - CPIMAgnEventAdapter* aEventAdapter); + + CPIMAgnEventAdapter* aEventAdapter, + TInt aCalSessionInt); private: // Member data diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/inc.s60/cpimtodoadapteraccess.h --- a/javaextensions/pim/agnadapter/inc.s60/cpimtodoadapteraccess.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/inc.s60/cpimtodoadapteraccess.h Fri May 14 15:47:24 2010 +0300 @@ -67,13 +67,17 @@ MPIMLocalizationData** aRetLocalizationData); TBool OpenEventListL( - const TDesC* aListName, + CCalSession* aCalSession, + + const TDesC* aListName, MPIMEventAdapterManager** aRetAdapterManager, MPIMEventListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData); TBool OpenToDoListL( - const TDesC* aListName, + CCalSession* aCalSession, + + const TDesC* aListName, MPIMToDoAdapterManager** aRetAdapterManager, MPIMToDoListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/inc.s60/cpimtodolistadapter.h --- a/javaextensions/pim/agnadapter/inc.s60/cpimtodolistadapter.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/inc.s60/cpimtodolistadapter.h Fri May 14 15:47:24 2010 +0300 @@ -44,7 +44,8 @@ /** * Two-phased constructor. */ - static CPIMToDoListAdapter* NewL(java::util::FunctionServer* aFuncServer); + static CPIMToDoListAdapter* NewL(java::util::FunctionServer* aFuncServer, + CCalSession *aCalSession); /** * Destructor. @@ -134,8 +135,7 @@ */ void CreateToDoItemL(MPIMToDoItem& aToDoItem); - void CPIMToDoListAdapter::DoCreateToDoItemL( - MPIMToDoItem& aToDoItem); + void DoCreateToDoItemL(MPIMToDoItem& aToDoItem); /** * Reads an existing To-Do item from the Agenda File. @@ -160,8 +160,7 @@ */ void ReadToDoItemL(MPIMToDoItem& aToDoItem); - void CPIMToDoListAdapter::DoReadToDoItemL( - MPIMToDoItem& aToDoItem); + void DoReadToDoItemL(MPIMToDoItem& aToDoItem); /** * Writes an existing To-Do item to the native Agenda File. @@ -187,8 +186,7 @@ */ void WriteToDoItemL(MPIMToDoItem& aToDoItem); - void CPIMToDoListAdapter::DoWriteToDoItemL( - MPIMToDoItem& aToDoItem); + void DoWriteToDoItemL(MPIMToDoItem& aToDoItem); /** * Removes an existing To-Do from the native Agenda File. @@ -208,8 +206,7 @@ */ void RemoveToDoItemL(TPIMItemID aItemID); - void CPIMToDoListAdapter::DoRemoveToDoItemL( - TPIMItemID aItemID); + void DoRemoveToDoItemL(TPIMItemID aItemID); protected: @@ -221,7 +218,7 @@ /** * By default Symbian 2nd phase constructor is private. */ - void ConstructL(); + void ConstructL(TInt aCalSessionInt ); private: // Member data diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/src.s60/cpimagnlistadapter.cpp --- a/javaextensions/pim/agnadapter/src.s60/cpimagnlistadapter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/src.s60/cpimagnlistadapter.cpp Fri May 14 15:47:24 2010 +0300 @@ -19,7 +19,7 @@ // INCLUDE FILES #include "cpimagnlistadapter.h" #include "mpimitemdata.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "cpimagnserverwait.h" #include "logger.h" @@ -54,13 +54,15 @@ // ----------------------------------------------------------------------------- // void CPIMAgnListAdapter::ConstructL( - MCalChangeCallBack::TChangeEntryType aEntryType) -{ + + MCalChangeCallBack::TChangeEntryType aEntryType, + CCalSession* aCalSession) + { JELOG2(EPim); - iServerWait = CPIMAgnServerWait::NewL(); - iCalSession = CCalSession::NewL(); - iCalSession->OpenL(iCalSession->DefaultFileNameL()); - iCalEntryView = CCalEntryView::NewL(*iCalSession, *iServerWait); + + iServerWait = CPIMAgnServerWait::NewL(); + iCalSession = aCalSession; + iCalEntryView = CCalEntryView::NewL(*iCalSession, *iServerWait); iServerWait->WaitCompleteL(KServerMaxWait); iCalSession->StartChangeNotification(this, aEntryType, ETrue, // include undated ToDos, if ToDos are observed @@ -285,10 +287,9 @@ void CPIMAgnListAdapter::CloseAgendaSession() { JELOG2(EPim); + iCalSession->StopChangeNotification(); delete iCalEntryView; - iCalEntryView = NULL; - - delete iCalSession; + iCalEntryView = NULL; iCalSession = NULL; iChangesRead = ETrue; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/src.s60/cpimeventadapteraccess.cpp --- a/javaextensions/pim/agnadapter/src.s60/cpimeventadapteraccess.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/src.s60/cpimeventadapteraccess.cpp Fri May 14 15:47:24 2010 +0300 @@ -139,7 +139,8 @@ return EFalse; } -TBool CPIMEventAdapterAccess::OpenEventListL(const TDesC* aListName, +TBool CPIMEventAdapterAccess::OpenEventListL(CCalSession* aCalSession, + const TDesC* aListName, MPIMEventAdapterManager** aRetAdapterManager, MPIMEventListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData) @@ -181,9 +182,9 @@ CPIMAgnApptAdapter* adapter = CPIMAgnApptAdapter::NewL(iFuncServer); CleanupStack::PushL(adapter); - listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EAppt, adapter, - iFuncServer); - + listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EAppt,adapter, + iFuncServer, aCalSession); + CleanupStack::Pop(adapter); CleanupStack::Pop(adapterManager); @@ -200,8 +201,8 @@ CPIMAgnMemoAdapter* adapter = CPIMAgnMemoAdapter::NewL(iFuncServer); CleanupStack::PushL(adapter); - listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EEvent, adapter, - iFuncServer); + listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EEvent,adapter, + iFuncServer, aCalSession); CleanupStack::Pop(adapter); CleanupStack::Pop(adapterManager); @@ -219,8 +220,8 @@ CPIMAgnAnnivAdapter* adapter = CPIMAgnAnnivAdapter::NewL(iFuncServer); CleanupStack::PushL(adapter); - listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EAnniv, adapter, - iFuncServer); + listAdapter = CPIMEventListAdapter::NewL(CCalEntry::EAnniv,adapter, + iFuncServer, aCalSession); CleanupStack::Pop(adapter); CleanupStack::Pop(adapterManager); @@ -244,9 +245,11 @@ return ETrue; } -TBool CPIMEventAdapterAccess::OpenToDoListL(const TDesC* /*aListName*/, +TBool CPIMEventAdapterAccess::OpenToDoListL(CCalSession* /*aCalSession*/, + const TDesC* /*aListName*/, MPIMToDoAdapterManager** /*aRetAdapterManager*/, - MPIMToDoListAdapter** /*aRetListAdapter*/, MPIMLocalizationData** /*aRetLocalizationData*/) + MPIMToDoListAdapter** /*aRetListAdapter*/, + MPIMLocalizationData** /*aRetLocalizationData*/) { JELOG2(EPim); // no ToDo lists diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/src.s60/cpimeventlistadapter.cpp --- a/javaextensions/pim/agnadapter/src.s60/cpimeventlistadapter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/src.s60/cpimeventlistadapter.cpp Fri May 14 15:47:24 2010 +0300 @@ -48,11 +48,14 @@ // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // -void CPIMEventListAdapter::ConstructL(CCalEntry::TType aEntryType, - CPIMAgnEventAdapter* aEventAdapter) -{ +void CPIMEventListAdapter::ConstructL(CCalEntry::TType aEntryType, + + CPIMAgnEventAdapter* aEventAdapter, + TInt aCalSessionInt) + { JELOG2(EPim); - CPIMAgnListAdapter::ConstructL(MCalChangeCallBack::EChangeEntryEvent); + CCalSession* calSession = reinterpret_cast (aCalSessionInt); + CPIMAgnListAdapter::ConstructL(MCalChangeCallBack::EChangeEntryEvent, calSession); iEntryType = aEntryType; iAgnAdapter = aEventAdapter; } @@ -62,15 +65,19 @@ // Two-phased constructor. // ----------------------------------------------------------------------------- // -CPIMEventListAdapter* CPIMEventListAdapter::NewL(CCalEntry::TType aEntryType, - CPIMAgnEventAdapter* aEventAdapter, java::util::FunctionServer* aFuncServer) -{ +CPIMEventListAdapter* CPIMEventListAdapter::NewL(CCalEntry::TType aEntryType, + CPIMAgnEventAdapter* aEventAdapter, + java::util::FunctionServer* aFuncServer, CCalSession *aCalSession + ) + { JELOG2(EPim); CPIMEventListAdapter* self = new(ELeave) CPIMEventListAdapter(aFuncServer); CleanupStack::PushL(self); + TInt calSessionInt = reinterpret_cast (aCalSession); CallMethodL(self, &CPIMEventListAdapter::ConstructL, aEntryType, - aEventAdapter, self->iFuncServer); - CleanupStack::Pop(self); + aEventAdapter, calSessionInt,self->iFuncServer); + + CleanupStack::Pop( self ); return self; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/src.s60/cpimtodoadapteraccess.cpp --- a/javaextensions/pim/agnadapter/src.s60/cpimtodoadapteraccess.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/src.s60/cpimtodoadapteraccess.cpp Fri May 14 15:47:24 2010 +0300 @@ -106,16 +106,20 @@ return EFalse; } -TBool CPIMToDoAdapterAccess::OpenEventListL(const TDesC* /*aListName*/, +TBool CPIMToDoAdapterAccess::OpenEventListL(CCalSession* /*aCalSession*/, + const TDesC* /*aListName*/, MPIMEventAdapterManager** /*aRetAdapterManager*/, - MPIMEventListAdapter** /*aRetListAdapter*/, MPIMLocalizationData** /*aRetLocalizationData*/) + MPIMEventListAdapter** /*aRetListAdapter*/, + MPIMLocalizationData** /*aRetLocalizationData*/ + ) { JELOG2(EPim); // no Event lists return EFalse; } -TBool CPIMToDoAdapterAccess::OpenToDoListL(const TDesC* aListName, +TBool CPIMToDoAdapterAccess::OpenToDoListL(CCalSession* aCalSession, + const TDesC* aListName, MPIMToDoAdapterManager** aRetAdapterManager, MPIMToDoListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData) @@ -136,7 +140,7 @@ (*iToDoListNames)[0]); CleanupDeletePushL(adapterManager); - MPIMToDoListAdapter* listAdapter = CPIMToDoListAdapter::NewL(iFuncServer); + MPIMToDoListAdapter* listAdapter = CPIMToDoListAdapter::NewL(iFuncServer, aCalSession); CleanupStack::Pop(adapterManager); MPIMLocalizationData* localizationData = iToDoLocalizationData; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/agnadapter/src.s60/cpimtodolistadapter.cpp --- a/javaextensions/pim/agnadapter/src.s60/cpimtodolistadapter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/agnadapter/src.s60/cpimtodolistadapter.cpp Fri May 14 15:47:24 2010 +0300 @@ -49,10 +49,11 @@ // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // -void CPIMToDoListAdapter::ConstructL() -{ +void CPIMToDoListAdapter::ConstructL(TInt aCalSessionInt) + { JELOG2(EPim); - CPIMAgnListAdapter::ConstructL(MCalChangeCallBack::EChangeEntryTodo); + CCalSession* calSession = reinterpret_cast (aCalSessionInt); + CPIMAgnListAdapter::ConstructL(MCalChangeCallBack::EChangeEntryTodo, calSession); iAgnToDoAdapter = CPIMAgnToDoAdapter::NewL(iFuncServer); } @@ -61,14 +62,15 @@ // Two-phased constructor. // ----------------------------------------------------------------------------- // -CPIMToDoListAdapter* CPIMToDoListAdapter::NewL( - java::util::FunctionServer* aFuncServer) -{ +CPIMToDoListAdapter* CPIMToDoListAdapter::NewL(java::util::FunctionServer* aFuncServer, +CCalSession *aCalSession) + { JELOG2(EPim); CPIMToDoListAdapter* self = new(ELeave) CPIMToDoListAdapter(aFuncServer); CleanupStack::PushL(self); - CallMethodL(self, &CPIMToDoListAdapter::ConstructL, self->iFuncServer); - CleanupStack::Pop(self); + TInt calSessionInt = reinterpret_cast (aCalSession); + CallMethodL(self, &CPIMToDoListAdapter::ConstructL,calSessionInt,self->iFuncServer); + CleanupStack::Pop( self ); return self; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/cntadapter/inc.s60/cpimcmadapteraccess.h --- a/javaextensions/pim/cntadapter/inc.s60/cpimcmadapteraccess.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/cntadapter/inc.s60/cpimcmadapteraccess.h Fri May 14 15:47:24 2010 +0300 @@ -26,6 +26,7 @@ // FORWARD DECLARATIONS class MPIMLocalizationManager; class MPIMLocalizationData; +class CCalSession; // CLASS DECLARATION /** @@ -63,12 +64,14 @@ MPIMLocalizationData** aRetLocalizationData); TBool OpenEventListL( + CCalSession* aCalSession, const TDesC* aListName, MPIMEventAdapterManager** aRetAdapterManager, MPIMEventListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData); TBool OpenToDoListL( + CCalSession* aCalSession, const TDesC* aListName, MPIMToDoAdapterManager** aRetAdapterManager, MPIMToDoListAdapter** aRetListAdapter, diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/cntadapter/inc.s60/cpimcontactlistadapter.h --- a/javaextensions/pim/cntadapter/inc.s60/cpimcontactlistadapter.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/cntadapter/inc.s60/cpimcontactlistadapter.h Fri May 14 15:47:24 2010 +0300 @@ -195,7 +195,7 @@ */ void Close(); - void CPIMContactListAdapter::DoClose(); + void DoClose(); public: // MPIMContactListAdapter @@ -223,8 +223,7 @@ */ void CreateContactItemL(MPIMContactItem& aContactItem); - void CPIMContactListAdapter::DoCreateContactItemL( - MPIMContactItem& aContactItem); + void DoCreateContactItemL(MPIMContactItem& aContactItem); /** * Reads an existing contact item from the native database. @@ -249,8 +248,7 @@ */ void ReadContactItemL(MPIMContactItem& aContactItem); - void CPIMContactListAdapter::DoCallReadContactItemL( - MPIMContactItem& aContactItem); + void DoCallReadContactItemL(MPIMContactItem& aContactItem); /** * Reads an existing contact item from the native database @@ -271,11 +269,9 @@ * native database. * @li Other - The list adapter is non-functional. */ - void ReadMinimalContactItemL( - MPIMContactItem& aContactItem); + void ReadMinimalContactItemL(MPIMContactItem& aContactItem); - void CPIMContactListAdapter::DoCallReadMinimalContactItemL( - MPIMContactItem& aContactItem); + void DoCallReadMinimalContactItemL(MPIMContactItem& aContactItem); /** * Reads an existing contact item from the native database @@ -315,7 +311,7 @@ void ReadContactFieldL(MPIMContactItem& aContactItem, TPIMContactField aContactField); - void CPIMContactListAdapter::DoReadContactFieldL( + void DoReadContactFieldL( MPIMContactItem& aContactItem, TPIMContactField aContactField); @@ -343,8 +339,7 @@ */ void WriteContactItemL(MPIMContactItem& aContactItem); - void CPIMContactListAdapter::DoWriteContactItemL( - MPIMContactItem& aContactItem); + void DoWriteContactItemL(MPIMContactItem& aContactItem); /** * Removes an existing contact from the native database. @@ -415,7 +410,7 @@ * @param aContactItemViewDef View definition which is used for * reading the contact item from the database */ - void CPIMContactListAdapter::DoReadContactItemL( + void DoReadContactItemL( MPIMContactItem& aContactItem, const CContactItemViewDef& aContactItemViewDef); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/cntadapter/src.s60/cpimcmadapteraccess.cpp --- a/javaextensions/pim/cntadapter/src.s60/cpimcmadapteraccess.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/cntadapter/src.s60/cpimcmadapteraccess.cpp Fri May 14 15:47:24 2010 +0300 @@ -75,16 +75,16 @@ return ETrue; } -TBool CPIMCMAdapterAccess::OpenEventListL(const TDesC* /*aListName*/, +TBool CPIMCMAdapterAccess::OpenEventListL(CCalSession* /*aCalSession*/, const TDesC* /*aListName*/, MPIMEventAdapterManager** /*aRetAdapterManager*/, - MPIMEventListAdapter** /*aRetListAdapter*/, MPIMLocalizationData** /*aRetLocalizationData */) + MPIMEventListAdapter** /*aRetListAdapter*/, MPIMLocalizationData** /*aRetLocalizationData*/ ) { JELOG2(EPim); // no Event lists return EFalse; } -TBool CPIMCMAdapterAccess::OpenToDoListL(const TDesC* /*aListName*/, +TBool CPIMCMAdapterAccess::OpenToDoListL(CCalSession* /*aCalSession*/, const TDesC* /*aListName*/, MPIMToDoAdapterManager** /*aRetAdapterManager*/, MPIMToDoListAdapter** /*aRetListAdapter*/, MPIMLocalizationData** /*aRetLocalizationData */) { diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/common/inc.s60/mpimadapteraccess.h --- a/javaextensions/pim/common/inc.s60/mpimadapteraccess.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/common/inc.s60/mpimadapteraccess.h Fri May 14 15:47:24 2010 +0300 @@ -31,6 +31,7 @@ class MPIMToDoAdapterManager; class MPIMToDoListAdapter; class MPIMLocalizationData; +class CCalSession; // CLASS DECLARATION @@ -129,7 +130,8 @@ * @li \c KErrNotFound - The native database does not exist any more. * @li Other - The system is non-functional. */ - virtual TBool OpenEventListL(const TDesC* aListName, + virtual TBool OpenEventListL(CCalSession* aCalSession, + const TDesC* aListName, MPIMEventAdapterManager** aRetAdapterManager, MPIMEventListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData) = 0; @@ -163,7 +165,8 @@ * @li \c KErrNotFound - The native database does not exist any more. * @li Other - The system is non-functional. */ - virtual TBool OpenToDoListL(const TDesC* aListName, + virtual TBool OpenToDoListL(CCalSession* aCalSession, + const TDesC* aListName, MPIMToDoAdapterManager** aRetAdapterManager, MPIMToDoListAdapter** aRetListAdapter, MPIMLocalizationData** aRetLocalizationData) = 0; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/inc.s60/cleanupresetanddestroy.h --- a/javaextensions/pim/framework/inc.s60/cleanupresetanddestroy.h Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,114 +0,0 @@ -/* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: Cleanup Stack "reset and destroy" push operation. - * -*/ - - -#ifndef CLEANUPRESETANDDESTROY_H -#define CLEANUPRESETANDDESTROY_H - -// INCLUDE FILES -#include - -/** - * An operation for pushing objects to cleanup stack with \c TCleanupItems - * that will perform a \c ResetAndDestroy() operation on the pushed object - * if a leave occurs. - * - * Note that the object itself will not be deleted. - * - * @par Example: - * Here is an example of using \c CleanupResetAndDestroy with a dynamically - * allocated \c RPointerArray. \c RPointerArray clears its contents with a - * \cResetAndDestroy() operation. - * @code - * - * // A function which creates a pointer array with couple of initialized - * // CThings. The function must return a pointer to the pointer array, - * // because the array has to be allocated dynamically. CThing is some - * // simple CBase-derived class. - * - * RPointerArray< CThing >* CreateThingArrayL( ) - * { - * // Create an array of pointers to CThings with granularity of 4 - * - * RPointerArray< CThing >* things = - * new( ELeave ) RPointerArray< CThing >( 4 ); - * - * // Push pointer to the array to the cleanup stack; then push reference - * // to the array and a ResetAndDestroy operation to the cleanup stack. - * - * // (Note that order of these operations matters: the ResetAndDestroy - * // operation must be performed before the array itself is deleted.) - * - * CleanupStack::PushL( things ); - * CleanupResetAndDestroyPushL( *things ); - * - * // Add couple of CThings with magic numbers to the array. - * // If any of the NewL() operations leaves, the array will be cleared - * // with ResetAndDestroy() and the array itself will destroyed. - * - * User::LeaveIfError( things->Append( CThing::NewL( 7 ) ) ); - * User::LeaveIfError( things->Append( CThing::NewL( 96 ) ) ); - * User::LeaveIfError( things->Append( CThing::NewL( 999 ) ) ); - * - * // Pop the array reference with ResetAndDestroy from cleanup stack - * // then pop the pointer to the array itself. - * - * CleanupStack::Pop(); // *things - * CleanupStack::Pop(); // things - * - * // Now we're ready to return the results (a pointer to the array) - * return things; - * } - * - * @endcode - */ -template -inline void CleanupResetAndDestroyPushL(T& aRef); - -/** - * See \ref CleanupResetAndDestroyPushL() documentation. - */ -template -class CleanupResetAndDestroy -{ -public: - inline static void PushL(T& aRef); - -private: - static void ResetAndDestroy(TAny *aPtr); -}; - -template -inline void CleanupResetAndDestroy::PushL(T& aRef) -{ - CleanupStack::PushL(TCleanupItem(&ResetAndDestroy, &aRef)); -} - -template -void CleanupResetAndDestroy::ResetAndDestroy(TAny *aPtr) -{ - static_cast(aPtr)->ResetAndDestroy(); -} - -template -inline void CleanupResetAndDestroyPushL(T& aRef) -{ - CleanupResetAndDestroy::PushL(aRef); -} - -#endif // CLEANUPRESETANDDESTROY_H -// End of File diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/inc.s60/cpimmanager.h --- a/javaextensions/pim/framework/inc.s60/cpimmanager.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/framework/inc.s60/cpimmanager.h Fri May 14 15:47:24 2010 +0300 @@ -43,6 +43,7 @@ class CPIMEventValidator; class CPIMToDoValidator; class MPIMAdapterAccess; +class CCalSession; // CLASS DECLARATION @@ -77,7 +78,7 @@ * Destructor. */ virtual ~CPIMManager(); - + void DeleteSessions(); public: // New functions /** @@ -200,13 +201,13 @@ CPIMToDoList* DoOpenToDoListL( const TDesC* aListName); - CDesCArray* CPIMManager::DoListPimListsL( + CDesCArray* DoListPimListsL( const TPIMListType& aPimListType); - pimbaselist* CPIMManager::DoOpenPimListL( + pimbaselist* DoOpenPimListL( const TPIMListType& aPimListType, const TDesC* aPimListName); - + void CreateCalSessionL(); void dispose(); private: // Constructors @@ -240,6 +241,13 @@ /** Owned. */ CPIMToDoValidator* iToDoValidator; + RLibrary iLocalizationLibrary; + + + /** Session to calendar server. Owned. */ + CCalSession* iCalSession; + + }; diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/src.s60/cpimeventlist.cpp --- a/javaextensions/pim/framework/src.s60/cpimeventlist.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/framework/src.s60/cpimeventlist.cpp Fri May 14 15:47:24 2010 +0300 @@ -29,7 +29,7 @@ #include "pimjnitools.h" #include "pimutils.h" #include "s60commonutils.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "logger.h" CPIMEventList::CPIMEventList(const CPIMEventValidator& aValidator) : diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/src.s60/cpimlist.cpp --- a/javaextensions/pim/framework/src.s60/cpimlist.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/framework/src.s60/cpimlist.cpp Fri May 14 15:47:24 2010 +0300 @@ -25,7 +25,7 @@ #include "cpimitem.h" #include "cpimitemmatcher.h" #include "cpimstringmatcher.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "pimexternalchanges.h" #include "pimpanics.h" #include "pimjnitools.h" @@ -927,9 +927,9 @@ User::LeaveIfError(newAndRemovedItems->Append( tempRemovedItems[i])); } - + CleanupStack::Pop(newAndRemovedItems); CleanupStack::Pop(); // newAndRemovedItems cleanup close - CleanupStack::Pop(newAndRemovedItems); + CleanupStack::PopAndDestroy(); // tempRemovedItems cleanup close CleanupStack::PopAndDestroy(); // tempNewItems cleanup close @@ -1187,6 +1187,7 @@ CleanupStack::Pop(newItem); // Add to list of new items + CleanupClosePushL(aTempNewItems); TInt errAddToNewItems = aTempNewItems.Append(newItem); if (errAddToNewItems != KErrNone) { @@ -1194,6 +1195,7 @@ delete newItem; User::Leave(errAddToNewItems); } + CleanupStack::Pop(&aTempNewItems); } void CPIMList::HandleItemChangeModifiedL(CPIMItem& aModifiedItem) @@ -1224,6 +1226,7 @@ RPointerArray& aTempRemovedItems) { JELOG2(EPim); + CleanupClosePushL(aTempRemovedItems); CPIMItem* removedItem = iItems[aRemovedItemIndex]; // Add to list of removed items @@ -1237,6 +1240,7 @@ // Remove from item list and remove adapter association iItems.Remove(aRemovedItemIndex); removedItem->RemoveAdapterAssociation(); + CleanupStack::Pop(&aTempRemovedItems); } void CPIMList::RefreshModifiedItemsL() diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/src.s60/cpimmanager.cpp --- a/javaextensions/pim/framework/src.s60/cpimmanager.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/framework/src.s60/cpimmanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -20,6 +20,7 @@ #include "cpimmanager.h" #include #include +#include #include "pimcommon.h" #include "mpimcontactadaptermanager.h" #include "mpimeventadaptermanager.h" @@ -44,9 +45,14 @@ #include "pimjnitools.h" #include "pimutils.h" #include "jstringutils.h" +#include "fs_methodcall.h" #include "logger.h" #include "cpimlocalizationmanager.h" +#include "s60commonutils.h" + + + // CONSTANTS /** @@ -74,7 +80,23 @@ = (MPIMLocalizationManager*)(CPIMLocalizationManager::NewL()); createServerToNewThread(); -} + CallMethodL(this, &CPIMManager::CreateCalSessionL, this); + } + +void CPIMManager::CreateCalSessionL() + { + iCalSession = CCalSession::NewL(); + TRAPD(err, iCalSession->OpenL(iCalSession->DefaultFileNameL())); + if ( KErrNotFound == err) + { + iCalSession->CreateCalFileL(iCalSession->DefaultFileNameL()); + iCalSession->OpenL(iCalSession->DefaultFileNameL()); + } + else + { + User::LeaveIfError(err); + } + } pimbasemanager* pimbasemanager::getInstance() { @@ -134,10 +156,17 @@ iContactValidator = NULL; delete iEventValidator; iEventValidator = NULL; - delete iToDoValidator; + delete iToDoValidator; + CallMethod(this, &CPIMManager::DeleteSessions, this); + iToDoValidator = NULL; stopServer(); } +void CPIMManager::DeleteSessions() + { + delete iCalSession; + iCalSession = NULL; + } void CPIMManager::dispose() { @@ -335,12 +364,11 @@ MPIMEventAdapterManager* eventAdapterManager = NULL; MPIMEventListAdapter* eventListAdapter = NULL; - MPIMLocalizationData* localizationData = NULL; - + MPIMLocalizationData* localizationData = NULL; const TInt n = iAdapterAccesses.Count(); for (TInt i = 0; i < n; i++) { - if (iAdapterAccesses[i]->OpenEventListL(aListName, + if (iAdapterAccesses[i]->OpenEventListL(iCalSession,aListName, &eventAdapterManager, &eventListAdapter, &localizationData)) { // got one @@ -369,12 +397,11 @@ MPIMToDoAdapterManager* toDoAdapterManager = NULL; MPIMToDoListAdapter* toDoListAdapter = NULL; - MPIMLocalizationData* localizationData = NULL; - + MPIMLocalizationData* localizationData = NULL; const TInt n = iAdapterAccesses.Count(); for (TInt i = 0; i < n; i++) { - if (iAdapterAccesses[i]->OpenToDoListL(aListName, &toDoAdapterManager, + if (iAdapterAccesses[i]->OpenToDoListL(iCalSession,aListName, &toDoAdapterManager, &toDoListAdapter, &localizationData)) { // got one diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/framework/src.s60/cpimtodolist.cpp --- a/javaextensions/pim/framework/src.s60/cpimtodolist.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/framework/src.s60/cpimtodolist.cpp Fri May 14 15:47:24 2010 +0300 @@ -24,7 +24,7 @@ #include "cpimtodoitem.h" #include "mpimadaptermanager.h" #include "pimtodo.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "pimjnitools.h" #include "pimutils.h" #include "s60commonutils.h" diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/versit/src.s60/cpimcalendarconverter.cpp --- a/javaextensions/pim/versit/src.s60/cpimcalendarconverter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/versit/src.s60/cpimcalendarconverter.cpp Fri May 14 15:47:24 2010 +0300 @@ -30,7 +30,7 @@ #include "cpimeventpropertyconverter.h" #include "fs_methodcall.h" #include "logger.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" // EXTERNAL INCLUDES #include @@ -242,7 +242,7 @@ RPointerArray& aItemArray) { JELOG2(EPim); - CleanupResetAndDestroyPushL(aItemArray); + CPIMEventItem* item = CPIMEventItem::NewLC(iEventValidator); TPIMDate alarm(TInt64(0)); // We don't take the ownership of the propertyArray, so the properties @@ -269,6 +269,7 @@ item->addInt(EPIMEventAlarm, KPIMAttrNone, interval.Int()); } } + CleanupClosePushL(aItemArray); User::LeaveIfError(aItemArray.Append(item)); CleanupStack::Pop(item); // item CleanupStack::Pop(&aItemArray); @@ -283,7 +284,7 @@ RPointerArray& aItemArray) { JELOG2(EPim); - CleanupResetAndDestroyPushL(aItemArray); + CPIMToDoItem* item = CPIMToDoItem::NewLC(iToDoValidator); TPIMDate alarm(TInt64(0)); // We don't take the ownership of the propertyArray, so the properties @@ -318,6 +319,7 @@ { item->AddBooleanL(EPIMToDoCompleted, KPIMAttrNone, ETrue); } + CleanupClosePushL(aItemArray); User::LeaveIfError(aItemArray.Append(item)); CleanupStack::Pop(item); // item CleanupStack::Pop(&aItemArray); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/versit/src.s60/cpimcardconverter.cpp --- a/javaextensions/pim/versit/src.s60/cpimcardconverter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/versit/src.s60/cpimcardconverter.cpp Fri May 14 15:47:24 2010 +0300 @@ -26,7 +26,7 @@ #include "cpimcardpropertyconverter.h" #include "fs_methodcall.h" #include "logger.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include // ============================ MEMBER FUNCTIONS =============================== @@ -131,7 +131,7 @@ CArrayPtrFlat& aParserArray) // contained vCards here { JELOG2(EPim); - CleanupResetAndDestroyPushL(aItemArray); + CleanupClosePushL(aItemArray); CPIMContactItem* item = CPIMContactItem::NewLC(iContactValidator); // We don't take the ownership of the propertyArray, so the properties // are deleted when the parser is diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/versit/src.s60/cpimeventpropertyconverter.cpp --- a/javaextensions/pim/versit/src.s60/cpimeventpropertyconverter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/versit/src.s60/cpimeventpropertyconverter.cpp Fri May 14 15:47:24 2010 +0300 @@ -27,7 +27,7 @@ #include "cpimitem.h" #include "cpimeventitem.h" #include "mpimrepeatruledata.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "logger.h" // EXTERNAL INCLUDES diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/pim/versit/src.s60/cpimversit.cpp --- a/javaextensions/pim/versit/src.s60/cpimversit.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/pim/versit/src.s60/cpimversit.cpp Fri May 14 15:47:24 2010 +0300 @@ -22,7 +22,7 @@ #include "cpimcardconverter.h" #include "cpimcalendarconverter.h" #include "cpimitem.h" -#include "cleanupresetanddestroy.h" +#include "javasymbianoslayer.h" #include "logger.h" #include // RBufWriteStream #include diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/satsa/apdu/src.s60/cstsace.h --- a/javaextensions/satsa/apdu/src.s60/cstsace.h Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/satsa/apdu/src.s60/cstsace.h Fri May 14 15:47:24 2010 +0300 @@ -24,7 +24,7 @@ #include "cstsprincipal.h" #include "cstsapdumaskpermission.h" #include "cstsuserauth.h" -#include "stscommon.h" +#include "javasymbianoslayer.h" namespace java { diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/satsa/framework/inc/stscommon.h --- a/javaextensions/satsa/framework/inc/stscommon.h Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: - * -*/ - - -#ifndef STSCOMMON_H -#define STSCOMMON_H - -// Enables pushing a call to ResetAndDestroy into cleanup stack - -template -class CleanupResetAndDestroy -{ -public: - inline static void PushL(T& aRef); -private: - static void ResetAndDestroy(TAny *aPtr); -}; -template -inline void CleanupResetAndDestroyPushL(T& aRef); -template -inline void CleanupResetAndDestroy::PushL(T& aRef) -{ - CleanupStack::PushL(TCleanupItem(&ResetAndDestroy, &aRef)); -} -template -void CleanupResetAndDestroy::ResetAndDestroy(TAny *aPtr) -{ - (STATIC_CAST(T*,aPtr))->ResetAndDestroy(); -} -template -inline void CleanupResetAndDestroyPushL(T& aRef) -{ - CleanupResetAndDestroy::PushL(aRef); -} - -#endif // STSCOMMON_H diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/satsa/pki/src.s60/tstsdistinguishednameconverter.cpp --- a/javaextensions/satsa/pki/src.s60/tstsdistinguishednameconverter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/satsa/pki/src.s60/tstsdistinguishednameconverter.cpp Fri May 14 15:47:24 2010 +0300 @@ -20,7 +20,7 @@ // INCLUDE FILES #include "tstsdistinguishednameconverter.h" #include "tstscharactersetconverter.h" -#include "stscommon.h" // for CleanupResetAndDestroy +#include "javasymbianoslayer.h" // for CleanupResetAndDestroy #include "stspkiconstants.h" // for error constants #include #include diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/subsystem.mk --- a/javaextensions/subsystem.mk Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/subsystem.mk Fri May 14 15:47:24 2010 +0300 @@ -26,7 +26,13 @@ location/build \ sensor/build -SYMBIAN_ONLY = pim wma bluetooth satsa/build location/build sensor/build iapinfo/build mobinfo/build globalindicators/build comm/build +ifeq ($(UI),AVKON) +# Broadcast stub is available for now only on AVKON environments (where also MMAPI exists) +COMPONENTS += \ + broadcast_stub/build +endif + +SYMBIAN_ONLY = pim wma bluetooth satsa/build location/build sensor/build iapinfo/build mobinfo/build globalindicators/build comm/build broadcast_stub/build LINUX_ONLY = diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSBinaryMessageImpl.java --- a/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSBinaryMessageImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSBinaryMessageImpl.java Fri May 14 15:47:24 2010 +0300 @@ -37,16 +37,13 @@ * @returns null if not supported * @see */ - public String getPayloadTextData() + String getPayloadTextData() { return null; } - /** - *Refer About this in JSR-205(Wireless Messaging API 2.0)specification - */ - public byte[] getPayloadBinaryData() + byte[] getPayloadBinaryData() { return getPayloadData(); } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSMessageImpl.java --- a/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSMessageImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSMessageImpl.java Fri May 14 15:47:24 2010 +0300 @@ -74,8 +74,8 @@ public abstract int getType(); - public abstract String getPayloadTextData(); + abstract String getPayloadTextData(); - public abstract byte[] getPayloadBinaryData(); + abstract byte[] getPayloadBinaryData(); } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSTextMessageImpl.java --- a/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSTextMessageImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/javasrc/com/nokia/mj/impl/sms/SMSTextMessageImpl.java Fri May 14 15:47:24 2010 +0300 @@ -37,7 +37,7 @@ * @return Returns the message payload data as a String * or null if it is not set */ - public String getPayloadTextData() + String getPayloadTextData() { return getPayloadText(); } @@ -45,7 +45,7 @@ * Method to get the message payload Data * @returns null if it is not supported */ - public byte[] getPayloadBinaryData() + byte[] getPayloadBinaryData() { return null; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/pushplugin/cbs/src.s60/cbsserverconnection.cpp --- a/javaextensions/wma/sms_cbs/pushplugin/cbs/src.s60/cbsserverconnection.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/pushplugin/cbs/src.s60/cbsserverconnection.cpp Fri May 14 15:47:24 2010 +0300 @@ -287,11 +287,12 @@ JELOG2(EWMA); TCBSParametersBuf cbsParametersBuf; std::wstring path; + char* messagePath =0; path += mMessageStoreDirName; try { path += JavaCommonUtils::intToWstring(mFirstMessageInStore); - char* messagePath = JavaCommonUtils::wstringToUtf8(path); + messagePath = JavaCommonUtils::wstringToUtf8(path); // Read the CBS file contents readStream.exceptions(std::ifstream::failbit|std::ifstream::badbit); @@ -313,12 +314,14 @@ catch (std::ifstream::failure e) { ELOG(EWMA,"CBS : Exception while opening/reading file"); + delete[] messagePath; readStream.exceptions(std::ofstream::goodbit); readStream.close(); return KErrGeneral; } catch (ExceptionBase ex) { + delete[] messagePath; return KErrGeneral; } return KErrNone; @@ -689,6 +692,7 @@ catch (std::ofstream::failure e) { ELOG(EWMA,"CBS : Exception while creating/writing file"); + delete[] messagePath; writeStream.exceptions(std::ofstream::goodbit); writeStream.close(); User::Leave(KErrGeneral); diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/pushplugin/sms/src.s60/smsserverconnection.cpp --- a/javaextensions/wma/sms_cbs/pushplugin/sms/src.s60/smsserverconnection.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/pushplugin/sms/src.s60/smsserverconnection.cpp Fri May 14 15:47:24 2010 +0300 @@ -65,7 +65,7 @@ { JELOG2(EWMA); // As per internal spec the message store should be removed only when - // Application is unintalled / UnRegistered from push + // Application is uninstalled / UnRegistered from push removeDir(mMessageStoreDirName); delete mMessage; delete mFilterDes; @@ -109,7 +109,9 @@ if (0 == mMessage) { CSmsBuffer* smsBuffer = CSmsBuffer::NewL(); + CleanupStack::PushL(smsBuffer); mMessage = CSmsMessage::NewL(mFs, CSmsPDU::ESmsDeliver, smsBuffer); + CleanupStack::Pop(smsBuffer); } error = pthread_mutex_init(&mMutex, 0); if (error == 0) @@ -152,7 +154,6 @@ { error = pthread_create(&mThreadId, NULL, SmsServerConnection::listenThread, this); - mOpenMonitor->wait(); } } } @@ -163,6 +164,7 @@ throw PushException(COMMON_SRV_CONN_PLUGIN_ERROR,errTxt,__FILE__, __FUNCTION__,__LINE__); } + mOpenMonitor->wait(); if (mMessagesOnStore > 0) { mListener->msgArrived(); @@ -328,6 +330,7 @@ mSocket.CancelIoctl(); mSocket.Close(); mSocketServer.Close(); + mSocketServerOpened = EFalse; } TInt SmsServerConnection::RunError(TInt aError) @@ -347,12 +350,13 @@ JELOG2(EWMA); std::wstring path; path += mMessageStoreDirName; + char* messagePath =0; // Read the SMS file contents readStream.exceptions(std::ifstream::failbit|std::ifstream::badbit); try { path += JavaCommonUtils::intToWstring(mFirstMessageInStore); - char* messagePath = JavaCommonUtils::wstringToUtf8(path); + messagePath = JavaCommonUtils::wstringToUtf8(path); readStream.open(messagePath, std::ios::in | std::ios::binary); readStream.read((char*) aSmsBuf.Ptr(), mSmsParameters.Size()); readStream.read((char*)(aSmsBuf().mData).Ptr(), aSmsBuf().mDataSize * 2); @@ -364,11 +368,13 @@ catch (std::ifstream::failure e) { ELOG(EWMA,"SMS : Exception while opening/reading file"); + delete[] messagePath; readStream.close(); return KErrGeneral; } catch (ExceptionBase ex) { + delete[] messagePath; return KErrGeneral; } return KErrNone; @@ -443,6 +449,7 @@ catch (std::ofstream::failure e) { ELOG(EWMA,"SMS : Exception while creating/writing file"); + delete[] messagePath; writeStream.close(); User::Leave(KErrGeneral); } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/pushplugin/src/serverconnectionbase.cpp --- a/javaextensions/wma/sms_cbs/pushplugin/src/serverconnectionbase.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/pushplugin/src/serverconnectionbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -133,7 +133,16 @@ { path += std::wstring(tok); path += L"\\"; - char *dirName = JavaCommonUtils::wstringToUtf8(path); + char *dirName =0; + try + { + dirName = JavaCommonUtils::wstringToUtf8(path); + } + catch (ExceptionBase ex) + { + delete[] stringToTokenize; + return -1; + } if (ableToOpen) { if (0 != lstat(dirName, &temp)) @@ -169,10 +178,11 @@ JELOG2(EWMA); std::wstring path1; path1 += aDirPath; + char* path =0; int error = 0; try { - char* path = JavaCommonUtils::wstringToUtf8(path1); + path = JavaCommonUtils::wstringToUtf8(path1); LOG1(EWMA, EInfo, "WMA : Removing Message Store %s",path); struct stat temp; if (0 != lstat(path, &temp)) @@ -211,7 +221,9 @@ } catch (ExceptionBase ex) { + delete[] path; ELOG(EWMA,"WMA : Cought an exception while removing Dir"); + return -1; } return error; } diff -r 2a9601315dfc -r 98ccebc37403 javaextensions/wma/sms_cbs/src.s60/csmsplatformservices60impl.cpp --- a/javaextensions/wma/sms_cbs/src.s60/csmsplatformservices60impl.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaextensions/wma/sms_cbs/src.s60/csmsplatformservices60impl.cpp Fri May 14 15:47:24 2010 +0300 @@ -166,13 +166,16 @@ TRAPD(error, { HBufC* smsData = convertToDes(aData,aMsgType,aLength); + CleanupStack::PushL(smsData); std::auto_ptr smsAddress(stringToDes(aHostAddress)); // The sms message takes ownership of the buffer CSmsBuffer* buffer = CSmsBuffer::NewL(); + CleanupStack::PushL(buffer); delete mSendMessage; mSendMessage = 0; RFs fileServer; mSendMessage = CSmsMessage::NewL(fileServer,CSmsPDU::ESmsSubmit,buffer); + CleanupStack::Pop(buffer); if (smsAddress->Length()> 0) { // set the destination address @@ -212,7 +215,7 @@ numberOfSegments = (int)mSendMessage->NumMessagePDUsL(); LOG2(EWMA, EInfo,"SMS :number of segments %d data length %d", numberOfSegments, aLength); - delete smsData; + CleanupStack::PopAndDestroy(smsData); }); return (error == KErrNone)? numberOfSegments : error; } @@ -234,6 +237,7 @@ TInt nonConvertibleCharacters; CCnvCharacterSetConverter* cConverter = CCnvCharacterSetConverter::NewL(); + CleanupStack::PushL(cConverter); CCnvCharacterSetConverter::TAvailability cnvAvailable = cConverter->PrepareToConvertToOrFromL( KCharacterSetIdentifierSms7Bit, aFs); @@ -266,8 +270,7 @@ } (isGSM7Convertible)?msgEncoding = TSmsDataCodingScheme::ESmsAlphabet7Bit :msgEncoding = TSmsDataCodingScheme::ESmsAlphabetUCS2; - delete cConverter; - cConverter = 0; + CleanupStack::PopAndDestroy(cConverter); } else { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaappschemeplugin/inc/javaapphandler.h --- a/javamanager/javaappschemeplugin/inc/javaapphandler.h Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaappschemeplugin/inc/javaapphandler.h Fri May 14 15:47:24 2010 +0300 @@ -20,9 +20,16 @@ #define JAVAAPPHANDLER_H // INCLUDES + +#ifdef RD_JAVA_S60_RELEASE_10_1_ONWARDS +#include +#else #include +#endif + #include + namespace java { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javacaptain/extensionplugins/javacertstore/src.linux/metadatafilehandler.cpp --- a/javamanager/javacaptain/extensionplugins/javacertstore/src.linux/metadatafilehandler.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javacaptain/extensionplugins/javacertstore/src.linux/metadatafilehandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -15,6 +15,7 @@ * */ +#include #include "metadatafilehandler.h" diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javacaptain/extensionplugins/scrupdater/build/javacaptain_ext_scrupdater.pro --- a/javamanager/javacaptain/extensionplugins/scrupdater/build/javacaptain_ext_scrupdater.pro Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javacaptain/extensionplugins/scrupdater/build/javacaptain_ext_scrupdater.pro Fri May 14 15:47:24 2010 +0300 @@ -20,6 +20,6 @@ CONFIG -= qt -LIBS += -lapgrfx -ljavacomms -ljavastorage -lscrclient - +LIBS += -lapgrfx -ljavacomms -ljavastorage -lscrclient -lefsrv + include(../../../../../build/omj.pri) diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javacaptain/extensionplugins/scrupdater/src.s60/scrupdater.cpp --- a/javamanager/javacaptain/extensionplugins/scrupdater/src.s60/scrupdater.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javacaptain/extensionplugins/scrupdater/src.s60/scrupdater.cpp Fri May 14 15:47:24 2010 +0300 @@ -20,9 +20,6 @@ #include #include #include -#include -#include -#include #include "javaprocessconstants.h" #include "javasymbianoslayer.h" diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javacaptain/src/main.cpp --- a/javamanager/javacaptain/src/main.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javacaptain/src/main.cpp Fri May 14 15:47:24 2010 +0300 @@ -21,6 +21,7 @@ #include "signalhandler.h" #endif /* __SYMBIAN32__ */ +#include #include #include #include diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java Fri May 14 15:47:24 2010 +0300 @@ -37,10 +37,6 @@ * * startSession() must be called before the other methods of this * class can be used. - * - * - * @author Nokia Corporation - * @version $Rev: 10289 $ */ public final class ApplicationRegistrator { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java Fri May 14 15:47:24 2010 +0300 @@ -48,12 +48,16 @@ private String iGlobalComponentId = null; /** Component name (i.e. suite name). */ private String iComponentName = null; - /** Array of pplication names. */ + /** Application names. */ private String[] iApplicationNames = null; + /** Applications icons. */ + private String[] iApplicationIcons = null; /** Component initial size. */ private int iComponentSize = 0; - /** Component icon path. */ - private String iComponentIconPath = null; + /** Icon dir. */ + private String iIconDir = null; + /** Component icon. */ + private String iComponentIcon = null; /*** ----------------------------- PUBLIC ------------------------------ */ @@ -79,15 +83,17 @@ */ public void notifyStart( int aOperation, String aGlobalComponentId, String aComponentName, - String[] aApplicationNames, int aComponentSize, - String aComponentIconPath) + String[] aApplicationNames, String[] aApplicationIcons, + int aComponentSize, String aIconDir, String aComponentIcon) { iOperation = aOperation; iGlobalComponentId = aGlobalComponentId; iComponentName = aComponentName; iApplicationNames = aApplicationNames; + iApplicationIcons = aApplicationIcons; iComponentSize = aComponentSize; - iComponentIconPath = aComponentIconPath; + iIconDir = aIconDir; + iComponentIcon = aComponentIcon; } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java Fri May 14 15:47:24 2010 +0300 @@ -25,9 +25,6 @@ /** * Fetches product program/operator specific customizable settings. * In Linux platform some of these are fetched from ??? - * - * @author Nokia Corporation - * @version $Rev: 10289 $ */ public final class CustomisationProperties extends CustomisationPropertiesBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java Fri May 14 15:47:24 2010 +0300 @@ -26,9 +26,6 @@ * JadJarMatcher offers services for finding Jar when Jad filename is known, * and finding Jad when Jar filename is known. JadJarMatcher only searches * files from local folders. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public final class JadJarMatcher extends JadJarMatcherBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java Fri May 14 15:47:24 2010 +0300 @@ -29,9 +29,7 @@ * installed / uninstalled or installation / uninstallation * is rolled back. Linux specific implementation. * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ - " @see JsrPluginNotifierBase + * @see JsrPluginNotifierBase */ public final class JsrPluginNotifier extends JsrPluginNotifierBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/utils/SysUtil.java --- a/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/utils/SysUtil.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.linux/com/nokia/mj/impl/installer/utils/SysUtil.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * SysUtil provides system utility services. - * - * @author Nokia Corporation - * @version $Rev: 10289 $ */ public final class SysUtil { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistrator.java Fri May 14 15:47:24 2010 +0300 @@ -31,9 +31,6 @@ * This version registers MIDlet to Symbian AppArc. * startSession() must be called before the other methods of this * class can be used. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public final class ApplicationRegistrator { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifNotifier.java Fri May 14 15:47:24 2010 +0300 @@ -48,12 +48,20 @@ private String iGlobalComponentId = null; /** Component name (i.e. suite name). */ private String iComponentName = null; - /** Array of pplication names. */ + /** Application names. */ private String[] iApplicationNames = null; + /** Applications icons. */ + private String[] iApplicationIcons = null; /** Component initial size. */ private int iComponentSize = 0; - /** Component icon path. */ - private String iComponentIconPath = null; + /** Icon dir. */ + private String iIconDir = null; + /** Component icon. */ + private String iComponentIcon = null; + + /** Sending progress notifications is only allowed between start + * and end notifications. */ + private boolean iNotifyProgressAllowed = false; /** Native object handle. */ private int iHandle = 0; @@ -83,15 +91,17 @@ */ public void notifyStart( int aOperation, String aGlobalComponentId, String aComponentName, - String[] aApplicationNames, int aComponentSize, - String aComponentIconPath) + String[] aApplicationNames, String[] aApplicationIcons, + int aComponentSize, String aIconDir, String aComponentIcon) { iOperation = aOperation; iGlobalComponentId = aGlobalComponentId; iComponentName = aComponentName; iApplicationNames = aApplicationNames; + iApplicationIcons = aApplicationIcons; iComponentSize = aComponentSize; - iComponentIconPath = aComponentIconPath; + iIconDir = aIconDir; + iComponentIcon = aComponentIcon; if (iHandle == 0) { @@ -99,8 +109,9 @@ "SifNotifier.notifyStart: notifier has not been initialized"); } int ret = _notifyStart( - iHandle, aGlobalComponentId, aComponentName, aApplicationNames, - aComponentSize, aComponentIconPath); + iHandle, aGlobalComponentId, aComponentName, + aApplicationNames, aApplicationIcons, + aComponentSize, aIconDir, aComponentIcon); if (ret < 0) { Log.logError("Notifying SIF start failed with code " + ret + @@ -108,6 +119,7 @@ InstallerException.internalError( "Notifying SIF start failed with code " + ret); } + iNotifyProgressAllowed = true; } /** @@ -123,6 +135,7 @@ InstallerException.internalError( "SifNotifier.notifyEnd: notifier has not been initialized"); } + iNotifyProgressAllowed = false; int ret = _notifyEnd( iHandle, iGlobalComponentId, aErrCategory, aErrCode, aErrMsg, aErrMsgDetails); @@ -146,6 +159,10 @@ */ public void notifyProgress(int aSubOperation, int aCurrent, int aTotal) { + if (!iNotifyProgressAllowed) + { + return; + } if (iHandle == 0) { InstallerException.internalError( @@ -240,15 +257,17 @@ * @param aGlobalComponentId * @param aComponentName * @param aApplicationNames + * @param aApplicationIcons * @param aComponentSize - * @param aComponentIconPath + * @param aIconDir + * @param aComponentIcon * @return Symbian error code (negative number) if operation fails, * otherwise 0 */ private static native int _notifyStart( int aHandle, String aGlobalComponentId, String aComponentName, - String[] aApplicationNames, int aComponentSize, - String aComponentIconPath); + String[] aApplicationNames, String[] aApplicationIcons, + int aComponentSize, String aIconDir, String aComponentIcon); /** * Notifies SIF about installation/uinstallation completion. diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifRegistrator.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifRegistrator.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/applicationregistrator/SifRegistrator.java Fri May 14 15:47:24 2010 +0300 @@ -654,7 +654,11 @@ { groupName = ""; // default installation group } - String iconFilename = aSuiteInfo.getRegisteredIconPath(aIndex); + String iconFilename = null; + if (!appInfo.getUseDefaultIcon()) + { + iconFilename = aSuiteInfo.getRegisteredIconPath(aIndex); + } Log.log("SifRegistrator iconFilename " + aIndex + ": " + iconFilename); int numberOfIcons = 1; // Initalize localized names for the application. @@ -736,7 +740,7 @@ { if (aSuite.getComponentId() == null) { - Log.logWarning( + Log.log( "SifRegistrator.registerLocalizedComponentName: cid not present in suite"); return; } @@ -749,7 +753,7 @@ (ApplicationInfo)aSuite.getApplications().elementAt(aIndex); if (app.getComponentId() == null) { - Log.logWarning( + Log.log( "SifRegistrator.registerLocalizedComponentName: cid not present in app"); return; } @@ -785,7 +789,7 @@ { if (aSuite.getComponentId() == null) { - Log.logWarning( + Log.log( "SifRegistrator.registerLocalizedProperties: cid not present in suite"); return; } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/customisationproperties/CustomisationProperties.java Fri May 14 15:47:24 2010 +0300 @@ -32,9 +32,6 @@ * Fetches product program/operator specific customizable settings. * In S60 platform some of these are fetched from central repository, * rest are asked from S60 ApplicationShell - * - * @author Nokia Corporation - * @version $Rev: 9381 $ */ public final class CustomisationProperties extends CustomisationPropertiesBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcher.java Fri May 14 15:47:24 2010 +0300 @@ -29,9 +29,6 @@ * JadJarMatcher offers services for finding Jar when Jad filename is known, * and finding Jad when Jar filename is known. JadJarMatcher only searches * files from local folders. - * - * @author Nokia Corporation - * @version $Rev: 9457 $ */ public final class JadJarMatcher extends JadJarMatcherBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifier.java Fri May 14 15:47:24 2010 +0300 @@ -28,9 +28,7 @@ * installed / uninstalled or installation / uninstallation * is rolled back. * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ - " @see JsrPluginNotifierBase + * @see JsrPluginNotifierBase */ public final class JsrPluginNotifier extends JsrPluginNotifierBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/utils/SysUtil.java --- a/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/utils/SysUtil.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc.s60/com/nokia/mj/impl/installer/utils/SysUtil.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * SysUtil provides system utility services. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public final class SysUtil { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallationNotifier.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallationNotifier.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallationNotifier.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -89,7 +89,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.started threw exception", t); + Log.logError( + "InstallationNotifier: InstallerUi.started threw exception", t); } } } @@ -132,7 +133,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.ended threw exception", t); + Log.logError( + "InstallationNotifier: InstallerUi.ended threw exception", t); } } if (iSifNotifier != null) @@ -180,7 +182,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.error threw exception", t); + Log.logError( + "InstallationNotifier: InstallerUi.error threw exception", t); } } } @@ -269,7 +272,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.updateProgress threw exception", t); + Log.logError( + "InstallationNotifier: InstallerUi.updateProgress threw exception", t); } } if (iSifNotifier != null) @@ -283,7 +287,8 @@ } catch (Throwable t) { - Log.logError("SifNotifier.notifyProgress threw exception", t); + Log.logError( + "InstallationNotifier: SifNotifier.notifyProgress threw exception", t); } } } @@ -373,7 +378,8 @@ } catch (Exception ex) { - Log.logError("Deleting property failed", ex); + Log.logError( + "InstallationNotifier: Deleting property failed", ex); } } } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/Installer.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/Installer.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/Installer.java Fri May 14 15:47:24 2010 +0300 @@ -70,9 +70,6 @@ * JavaInstaller main class. JavaInstaller can be started either with * #main(String[]) or #mainWithResult(String[]) methods. Negative return * values indicate that execution has failed. - * - * @author Nokia Corporation - * @version $Rev: 10413 $ */ public class Installer { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallerResultMessage.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallerResultMessage.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/InstallerResultMessage.java Fri May 14 15:47:24 2010 +0300 @@ -238,11 +238,19 @@ */ public void send(int[] aEndpoints) throws InstallerException { + InstallerException installerException = null; if (aEndpoints != null) { - for (int i = 0; i < aEndpoints.length; i++) + try { - send(aEndpoints[i]); + for (int i = 0; i < aEndpoints.length; i++) + { + send(aEndpoints[i]); + } + } + catch (InstallerException ie) + { + installerException = ie; } } if (iSifNotifier != null) @@ -267,6 +275,10 @@ Log.logError("InstallerResultMessage: SifNotifier.notifyEnd failed", t); } } + if (installerException != null) + { + throw installerException; + } } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/applicationregistrator/AppRegInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/applicationregistrator/AppRegInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/applicationregistrator/AppRegInfo.java Fri May 14 15:47:24 2010 +0300 @@ -24,9 +24,6 @@ /** * Contains all information needed to register Java application to * any platform. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public final class AppRegInfo { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesBase.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesBase.java Fri May 14 15:47:24 2010 +0300 @@ -24,9 +24,6 @@ /** * Fetches product program/operator specific customizable settings. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public class CustomisationPropertiesBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadInfo.java Fri May 14 15:47:24 2010 +0300 @@ -26,9 +26,6 @@ /** * DownloadInfo contains information of one file download. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ public class DownloadInfo { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadListener.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/DownloadListener.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ * Downloader will notify DownloadListener about download progress. * Note that Downloader will ignore all exceptions thrown from * DownloadListener callback methods. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ public interface DownloadListener { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/Downloader.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/Downloader.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/Downloader.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -40,9 +40,6 @@ * Each Downloader instance downloads one file at a time in * a separate thread. Parallel downloads are possible with * multiple Downloader instances. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ abstract public class Downloader implements Runnable { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfDownloader.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfDownloader.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfDownloader.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -28,9 +28,6 @@ /** * GcfDownloader implements Downloader using MIDP GCF classes. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ public class GcfDownloader extends Downloader { @@ -104,8 +101,20 @@ { // Open connection. String url = getUrlWithAccessPoint(iDlInfo.getUrl(), iIap, iSnap); - Log.log("GcfDownloader: opening " + url); - HttpConnection connection = (HttpConnection)Connector.open(url); + HttpConnection connection = null; + synchronized (this) + { + if (iState != STATE_DOWNLOADING) + { + Log.log("GcfDownloader: download cancelled before connection opening"); + return; + } + // Download may not be stopped during connection opening, + // so open connection inside synchronization block. + Log.logInfoPrd("GcfDownloader: opening " + url); + connection = (HttpConnection)Connector.open(url); + Log.logInfoPrd("GcfDownloader: connection opened"); + } if (iAuthorizationHeader != null) { connection.setRequestProperty("Authorization", @@ -120,8 +129,8 @@ // Get response code and message. int status = connection.getResponseCode(); - Log.log("GcfDownloader: got HTTP status: " + status + - " " + connection.getResponseMessage()); + Log.logInfoPrd("GcfDownloader: got HTTP status: " + status + + " " + connection.getResponseMessage()); // Check if HTTP redirect is needed. String location = connection.getHeaderField("Location"); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfNotificationPoster.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfNotificationPoster.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/GcfNotificationPoster.java Fri May 14 15:47:24 2010 +0300 @@ -30,9 +30,6 @@ /** * GcfNotificationPoster implements NotificationPoster using * MIDP GCF classes. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ public class GcfNotificationPoster extends NotificationPoster { @@ -98,8 +95,19 @@ String url = getUrlWithTimeout( GcfDownloader.getUrlWithAccessPoint( aOtaStatusNotification.getUrl(), iIap, iSnap), 60); - Log.logInfoPrd("GcfNotificationPoster: opening " + url); - HttpConnection connection = (HttpConnection)Connector.open(url); + HttpConnection connection = null; + synchronized (this) + { + if (iState != STATE_POSTING) + { + throw new IOException("Posting cancelled before connection opening"); + } + // Posting may not be stopped during connection opening, + // so open connection inside synchronization block. + Log.logInfoPrd("GcfNotificationPoster: opening " + url); + connection = (HttpConnection)Connector.open(url); + Log.logInfoPrd("GcfNotificationPoster: connection opened"); + } connection.setRequestMethod(connection.POST); // we will post content connection.setRequestProperty("Content-Type", CONTENT_TYPE); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/NotificationPoster.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/NotificationPoster.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/downloader/NotificationPoster.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -30,9 +30,6 @@ * NotificationPoster takes care of posting OTA status notifcations. * It uses a separate thread for posting pending notifications. * HTTP authentication is not supported for the OTA status notifications. - * - * @author Nokia Corporation - * @version $Rev: 0 $ $Date$ */ abstract public class NotificationPoster implements Runnable { @@ -104,6 +101,7 @@ } try { + iState = STATE_POSTING; doPost(aOtaStatusNotification, null); } catch (Throwable t) @@ -116,6 +114,12 @@ (System.currentTimeMillis()); iOtaStatusHandler.addNotification(aOtaStatusNotification); } + finally + { + // Notify that waitForCompletion() can proceed. + iState = STATE_STOPPED; + this.notify(); + } } /** @@ -255,7 +259,6 @@ iState = STATE_STOPPED; this.notify(); } - } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeEngine.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeEngine.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeEngine.java Fri May 14 15:47:24 2010 +0300 @@ -26,9 +26,6 @@ /** * Execution engine. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public final class ExeEngine { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeProgressListener.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeProgressListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeProgressListener.java Fri May 14 15:47:24 2010 +0300 @@ -20,9 +20,6 @@ /** * Execution engine progress listener interface. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public interface ExeProgressListener { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeStep.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeStep.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeStep.java Fri May 14 15:47:24 2010 +0300 @@ -20,9 +20,6 @@ /** * Base class for execution steps. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public class ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeTable.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeTable.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/exetable/ExeTable.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ /** * Execution table contains the steps to be executed in execution engine. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public final class ExeTable { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/integrityservice/FileOps.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/integrityservice/FileOps.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/integrityservice/FileOps.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -111,7 +111,7 @@ result = copy(aFrom, aTo); if (result) { - result = fromFile.delete(); + result = fromFile.forceDelete(); if (!result) { Log.logError("FileOps.move: delete failed: " + aFrom); @@ -144,7 +144,7 @@ } else { - result = file.delete(); + result = file.forceDelete(); } if (!result) { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/FileList.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/FileList.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/FileList.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ /** * FileList is a holder for a list of file related information. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class FileList { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarFile.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarFile.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarFile.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ /** * JadJarFile contains names of Jad and Jar files and attributes from them. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public class JadJarFile { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcherBase.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcherBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jadjarmatcher/JadJarMatcherBase.java Fri May 14 15:47:24 2010 +0300 @@ -38,9 +38,6 @@ * JadJarMatcher offers services for finding Jar when Jad filename is known, * and finding Jad when Jar filename is known. JadJarMatcher only searches * files from local folders. - * - * @author Nokia Corporation - * @version $Rev: 9457 $ */ public class JadJarMatcherBase { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtension.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtension.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtension.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ * JSR Installer Plugin interface. All Java Installer * JSR plugins must implement this interface and have * constructor that accepts empty argument list. - * - * @author Nokia Corporation - * @version $Rev: 9337 $ $Date: 2010-01-14 14:27:46 +0200 (Thu, 14 Jan 2010) $ * @see JsrPluginNotifier */ public interface InstallerExtension diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtensionInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtensionInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/InstallerExtensionInfo.java Fri May 14 15:47:24 2010 +0300 @@ -25,9 +25,6 @@ /** * Information passed to JSR plugins when installing or uninstalling * Java applications - * - * @author Nokia Corporation - * @version $Rev: 10381 $ $Date: 2010-04-06 15:34:34 +0300 (Tue, 06 Apr 2010) $ * @see JsrPluginNotifier */ public final class InstallerExtensionInfo diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CheckDiskSpace.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CheckDiskSpace.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CheckDiskSpace.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -66,6 +66,7 @@ Log.log("Choosing default installation drive"); Vector drives = new Vector(); SysUtil.getUserVisibleDrives(drives); + logDrives("User visible drives:", drives); if (ball.iOldSuite == null || !SysUtil.isDrivePresent(ball.iInstallationDrive)) { @@ -131,6 +132,7 @@ Vector aDrives, int aSizeInBytes) { sortDrives(aDrives); + logDrives("Sorted drives:", aDrives); for (int i = 0; i < aDrives.size(); i++) { DriveInfo drive = (DriveInfo)aDrives.elementAt(i); @@ -163,14 +165,16 @@ */ private static void sortDrives(Vector aDrives) { - for (int i = 1; i < aDrives.size(); i++) + for (int i = 0; i < aDrives.size(); i++) { - for (int j = 0; j < i; j++) + for (int j = i+1; j < aDrives.size(); j++) { - DriveInfo d1 = (DriveInfo)aDrives.elementAt(j); - DriveInfo d2 = (DriveInfo)aDrives.elementAt(i); + DriveInfo d1 = (DriveInfo)aDrives.elementAt(i); + DriveInfo d2 = (DriveInfo)aDrives.elementAt(j); if (hasHigherPriority(d1, d2)) { + Log.log(d1.getNumber() + " < " + d2.getNumber() + + ", swap [" + i + "] and [" + j + "]"); aDrives.removeElementAt(j); aDrives.insertElementAt(d2, i); } @@ -193,6 +197,23 @@ } /** + * Logs list of drives to info log. + */ + private static void logDrives(String aMsg, Vector aDrives) + { + StringBuffer sortedDrives = new StringBuffer(); + for (int i = 0; i < aDrives.size(); i++) + { + DriveInfo drive = (DriveInfo)aDrives.elementAt(i); + sortedDrives.append(" ").append(drive.getNumber()) + .append(" (").append(drive.getDriveType()) + .append(", ").append(drive.getFreeSpace()).append(")"); + + } + Log.log(aMsg + sortedDrives); + } + + /** * Returns the installation drive the user has chosen last. * If user selection is not available, returns -1. */ diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConfirmInstallation.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConfirmInstallation.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConfirmInstallation.java Fri May 14 15:47:24 2010 +0300 @@ -40,9 +40,6 @@ /** * ConfirmInstallation shows installation confirmation dialog to user. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class ConfirmInstallation extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConvertIcons.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConvertIcons.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/ConvertIcons.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -53,9 +53,6 @@ * sets path to the converted and renamed icon to suite and application * icons. [This must be done in S60 because icon cannot be registered * into AppArc unless it can be opened in write mode and it has unique name.] - * - * @author Nokia Corporation - * @version $Rev: 2259 $ $Date: 2008-09-19 12:27:49 +0300 (Fri, 19 Sep 2008) $ */ public class ConvertIcons extends ExeStep { @@ -161,12 +158,14 @@ { // Set suite icon ball.iSuite.setConvertedIconPath(defaultIcon); + ball.iSuite.setUseDefaultIcon(true); // Set application icons for (int i = 0; i < newApps.size(); i++) { - ((ApplicationInfo)newApps.elementAt(i)).setConvertedIconPath( - defaultIcon); + ApplicationInfo app = (ApplicationInfo)newApps.elementAt(i); + app.setConvertedIconPath(defaultIcon); + app.setUseDefaultIcon(true); } } else @@ -224,6 +223,7 @@ else { ball.iSuite.setConvertedIconPath(defaultIcon); + ball.iSuite.setUseDefaultIcon(true); // Cannot use suite icon file suiteIconFile = ""; } @@ -231,6 +231,7 @@ else { ball.iSuite.setConvertedIconPath(defaultIcon); + ball.iSuite.setUseDefaultIcon(true); } // The icon of the application can be specified in two attributes. @@ -289,6 +290,7 @@ { // use default icon newApp.setConvertedIconPath(defaultIcon); + newApp.setUseDefaultIcon(true); } } else @@ -362,6 +364,7 @@ // use default icon ball.log("Using default icon for midlet number " + (i+1)); newApp.setConvertedIconPath(defaultIcon); + newApp.setUseDefaultIcon(true); } } } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CopyAppFiles.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CopyAppFiles.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/CopyAppFiles.java Fri May 14 15:47:24 2010 +0300 @@ -222,6 +222,10 @@ for (int i = 0; i < apps.size(); i++) { appInfo = (ApplicationInfo)apps.elementAt(i); + if (appInfo.getUseDefaultIcon()) + { + continue; + } iconFilename = aBall.iSuite.getRegisteredIconPath(i); iconDir = FileUtils.getParent(iconFilename); if (!FileUtils.exists(iconDir)) diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DlListener.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DlListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DlListener.java Fri May 14 15:47:24 2010 +0300 @@ -56,7 +56,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.started threw exception", t); + Log.logError( + "DlListener: InstallerUi.started threw exception", t); } } } @@ -74,7 +75,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.updateProgress threw exception", t); + Log.logError( + "DlListener: InstallerUi.updateProgress threw exception", t); } } if (iBall.iSifNotifier != null) @@ -90,7 +92,8 @@ } catch (Throwable t) { - Log.logError("SifNotifier.notifyProgress threw exception", t); + Log.logError( + "DlListener: SifNotifier.notifyProgress threw exception", t); } } } @@ -107,7 +110,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.ended threw exception", t); + Log.logError( + "DlListener: InstallerUi.ended threw exception", t); } } if (iBall != null) @@ -145,7 +149,8 @@ } catch (Throwable t) { - Log.logError("InstallerUi.getUsernamePassword threw exception", t); + Log.logError( + "DlListener: InstallerUi.getUsernamePassword threw exception", t); } } return result; diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJad.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJad.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJad.java Fri May 14 15:47:24 2010 +0300 @@ -31,9 +31,6 @@ * This is mostly used in Linux platform because in S60 platform * either jad or Jar is already present in the device when * installation is started. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class DownloadJad extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJar.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJar.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/DownloadJar.java Fri May 14 15:47:24 2010 +0300 @@ -31,9 +31,6 @@ /** * Installation step DownloadJar takes care of downloading Jar file. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class DownloadJar extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/HandleCustomAttributes.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/HandleCustomAttributes.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/HandleCustomAttributes.java Fri May 14 15:47:24 2010 +0300 @@ -74,14 +74,7 @@ } else { - Log.logError("Invalid " + attrName + " value " + attrValue); - throw new InvalidAttributeException - (InstallerErrorMessage.INST_CORRUPT_PKG, null, - InstallerDetailedErrorMessage.ATTR_UNSUPPORTED, - new String[] { attrName }, - (aBall.attributeExistsInJad(attrName)? - OtaStatusCode.INVALID_DESCRIPTOR: - OtaStatusCode.INVALID_JAR)); + Log.logWarning("Invalid " + attrName + " value " + attrValue); } } } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/InstallBall.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/InstallBall.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/InstallBall.java Fri May 14 15:47:24 2010 +0300 @@ -289,6 +289,20 @@ super.checkForCancel(); if (isCancelled()) { + if (iDownloader != null) + { + try + { + Log.log("checkForCancel: User cancelled, stopping downloader..."); + iDownloader.stop(); + iDownloader = null; + Log.log("checkForCancel: Downloader stopped"); + } + catch (Throwable t) + { + Log.logWarning("checkForCancel: Stopping downloader failed", t); + } + } throw new InstallerException (InstallerErrorMessage.INST_CANCEL, null, InstallerDetailedErrorMessage.NO_MSG, null, diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/NotifyJsrPlugins.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/NotifyJsrPlugins.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/NotifyJsrPlugins.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * MIDP installation step NotifyJsrPlugins. * Added to MIDP2 Install table in com.nokia.mj.impl.installer.Installer - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public class NotifyJsrPlugins extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/OcspListener.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/OcspListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/OcspListener.java Fri May 14 15:47:24 2010 +0300 @@ -72,7 +72,8 @@ } catch (Throwable t) { - Log.logError("Exception from InstallerUi.setOcspIndicator", t); + Log.logError( + "OcspListener: Exception from InstallerUi.setOcspIndicator", t); } } if (iBall.iSifNotifier != null) @@ -85,7 +86,8 @@ } catch (Throwable t) { - Log.logError("SifNotifier.notifyProgress threw exception", t); + Log.logError( + "OcspListener: SifNotifier.notifyProgress threw exception", t); } } } @@ -101,7 +103,8 @@ } catch (Throwable t) { - Log.logError("Exception from InstallerUi.setOcspIndicator", t); + Log.logError( + "OcspListener: Exception from InstallerUi.setOcspIndicator", t); } } if (iBall.iSifNotifier != null) @@ -114,7 +117,8 @@ } catch (Throwable t) { - Log.logError("SifNotifier.notifyProgress threw exception", t); + Log.logError( + "OcspListener: SifNotifier.notifyProgress threw exception", t); } } // Notify InstallBall so that WaitForOcsp step can proceed. @@ -123,7 +127,8 @@ } else { - Log.logError("OcspListener.ocspEvent: Unknown event: " + aEventId); + Log.logError( + "OcspListener.ocspEvent: Unknown event: " + aEventId); } } } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/RegisterApplication.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/RegisterApplication.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/RegisterApplication.java Fri May 14 15:47:24 2010 +0300 @@ -31,9 +31,6 @@ /** * MIDP installation step RegisterApplication. * Added to MIDP2 Install table in com.nokia.mj.impl.installer.Installer - * - * @author Nokia Corporation - * @version $Rev: 9375 $ $Date: 2010-01-18 12:54:40 +0200 (Mon, 18 Jan 2010) $ */ public class RegisterApplication extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendInstallerResultMessage.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendInstallerResultMessage.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendInstallerResultMessage.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Installation step for sending InstallerResultMessage. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class SendInstallerResultMessage extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendOtaStatus.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendOtaStatus.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/SendOtaStatus.java Fri May 14 15:47:24 2010 +0300 @@ -35,9 +35,6 @@ * Installation step for sending OTA status notifications. * This is the first and the last step in installation execution table. * This execution step may not throw any exceptions. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class SendOtaStatus extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/StartProgressNotifications.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/StartProgressNotifications.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/StartProgressNotifications.java Fri May 14 15:47:24 2010 +0300 @@ -22,6 +22,8 @@ import com.nokia.mj.impl.installer.exetable.ExeBall; import com.nokia.mj.impl.installer.exetable.ExeStep; import com.nokia.mj.impl.installer.storagehandler.ApplicationInfo; +import com.nokia.mj.impl.installer.utils.FileRoots; +import com.nokia.mj.impl.installer.utils.FileUtils; import com.nokia.mj.impl.installer.utils.InstallerException; import com.nokia.mj.impl.installer.utils.Log; @@ -53,6 +55,11 @@ // Init application names array. Vector appNamesVector = ball.iSuite.getApplications(); + if (ball.iOldSuite != null) + { + // In update get the names of previously installed applications. + appNamesVector = ball.iOldSuite.getApplications(); + } String[] appNames = new String[appNamesVector.size()]; for (int i = 0; i < appNamesVector.size(); i++) { @@ -60,9 +67,26 @@ ((ApplicationInfo)appNamesVector.elementAt(i)).getName(); } - // Use default icon for now. - String componentIconPath = - ball.iApplicationRegistrator.getDefaultIconPath(); + // Initialize icon filenames and icon dir. + String iconDir = null; + String componentIcon = null; + String[] appIcons = null; + if (ball.iOldSuite != null) + { + // In update get the icons of previously installed applications. + iconDir = FileRoots.getRegisteredIconDir( + FileUtils.getDrive(ball.iOldSuite.getRootDir())) + + ball.iOldSuite.getUid().toString(); + appIcons = ball.iOldSuite.getRegisteredAppIcons(); + if (appIcons != null) + { + for (int i = 0; i < appIcons.length; i++) + { + Log.log("Old app icon " + appIcons[i] + + " for "+ appNames[i] + " from " + iconDir); + } + } + } try { @@ -70,8 +94,8 @@ (ball.iOldSuite != null? ball.iSifNotifier.OP_UPDATE: ball.iSifNotifier.OP_INSTALL), ball.iSuite.getGlobalId(), ball.iSuite.getName(), - appNames, ball.iSuite.calculateInitialSize(), - componentIconPath); + appNames, appIcons, ball.iSuite.calculateInitialSize(), + iconDir, componentIcon); } catch (Throwable t) { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForDownload.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForDownload.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForDownload.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Installation step WaitForDownload blocks and waits until * donwload gets completed. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class WaitForDownload extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForLaunchAppQuery.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForLaunchAppQuery.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForLaunchAppQuery.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Installation step which waits until user has * answered to launch application query. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class WaitForLaunchAppQuery extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForOcsp.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForOcsp.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/install/steps/WaitForOcsp.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Installation step WaitForOcsp blocks and waits until * certificate validation (OCSP) has been completed. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class WaitForOcsp extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/CheckUninstallationAllowed.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/CheckUninstallationAllowed.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/CheckUninstallationAllowed.java Fri May 14 15:47:24 2010 +0300 @@ -33,9 +33,6 @@ /** * Check if uninstallation is allowed from Nokia-MIDlet-Block-Uninstall * attribute and protection domain. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class CheckUninstallationAllowed extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/ConfirmUninstallation.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/ConfirmUninstallation.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/ConfirmUninstallation.java Fri May 14 15:47:24 2010 +0300 @@ -38,9 +38,6 @@ /** * ConfirmUninstallation shows uninstallation confirmation dialog to user. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class ConfirmUninstallation extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/NotifyJsrPlugins.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/NotifyJsrPlugins.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/NotifyJsrPlugins.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * MIDP uninstallation step NotifyJsrPlugins. * Added to MIDP2 Uninstall table in com.nokia.mj.impl.installer.Installer - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public class NotifyJsrPlugins extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/RemoveSecurityData.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/RemoveSecurityData.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/RemoveSecurityData.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Removes application's security data from storage. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class RemoveSecurityData extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendInstallerResultMessage.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendInstallerResultMessage.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendInstallerResultMessage.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * Installation step for sending InstallerResultMessage. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class SendInstallerResultMessage extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendOtaStatus.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendOtaStatus.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/SendOtaStatus.java Fri May 14 15:47:24 2010 +0300 @@ -32,9 +32,6 @@ * Uninstallation step for sending OTA status notifications. * This is the first and the last step in uninstallation execution table. * This execution step may not throw any exceptions. - * - * @author Nokia Corporation - * @version $Rev: $ $Date: $ */ public class SendOtaStatus extends ExeStep { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/StartProgressNotifications.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/StartProgressNotifications.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/midp2/uninstall/steps/StartProgressNotifications.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,14 @@ import com.nokia.mj.impl.installer.exetable.ExeBall; import com.nokia.mj.impl.installer.exetable.ExeStep; import com.nokia.mj.impl.installer.storagehandler.ApplicationInfo; +import com.nokia.mj.impl.installer.utils.FileRoots; +import com.nokia.mj.impl.installer.utils.FileUtils; import com.nokia.mj.impl.installer.utils.InstallerException; import com.nokia.mj.impl.installer.utils.Log; +import com.nokia.mj.impl.utils.Uid; +import java.io.IOException; +import java.util.Enumeration; import java.util.Vector; public class StartProgressNotifications extends ExeStep @@ -60,17 +65,28 @@ ((ApplicationInfo)appNamesVector.elementAt(i)).getName(); } - // Use default icon for now. - String componentIconPath = - ball.iApplicationRegistrator.getDefaultIconPath(); + // Initialize icon filenames and icon dir. + String iconDir = FileRoots.getRegisteredIconDir( + FileUtils.getDrive(ball.iSuite.getRootDir())) + + ball.iSuite.getUid().toString(); + String componentIcon = null; + String[] appIcons = ball.iSuite.getRegisteredAppIcons(); + if (appIcons != null) + { + for (int i = 0; i < appIcons.length; i++) + { + Log.log("App icon " + appIcons[i] + + " for "+ appNames[i] + " from " + iconDir); + } + } try { ball.iSifNotifier.notifyStart( ball.iSifNotifier.OP_UNINSTALL, ball.iSuite.getGlobalId(), ball.iSuite.getName(), - appNames, ball.iSuite.calculateInitialSize(), - componentIconPath); + appNames, appIcons, ball.iSuite.calculateInitialSize(), + iconDir, componentIcon); } catch (Throwable t) { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/ApplicationInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/ApplicationInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/ApplicationInfo.java Fri May 14 15:47:24 2010 +0300 @@ -1,5 +1,5 @@ /* -* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" @@ -36,6 +36,8 @@ private String iMainClass = null; private int iAutoStart = AUTOSTART_FALSE; + /** Flag telling if default icon should be used. */ + private boolean iUseDefaultIcon = false; /** Filename for converted icon. This member is not saved into storage. */ private String iConvertedIconPath = null; @@ -155,6 +157,22 @@ } /** + * Returns true if default icon should be used, false otherwise. + */ + public boolean getUseDefaultIcon() + { + return iUseDefaultIcon; + } + + /** + * Set flag telling if default icon should be used. + */ + public void setUseDefaultIcon(boolean aUseDefaultIcon) + { + iUseDefaultIcon = aUseDefaultIcon; + } + + /** * Get icon path for converted icon. */ public String getConvertedIconPath() diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusHandler.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusHandler.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusHandler.java Fri May 14 15:47:24 2010 +0300 @@ -44,9 +44,6 @@ * Because JavaStorage limits the number of concurrent sessions to * one for each database, the OtaStatusHandler uses a separate * JavaOtaStorage database for storing the OTA status notifications. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public class OtaStatusHandler { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusNotification.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusNotification.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/OtaStatusNotification.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * OtaStatusNotification contains information of one Ota status * notification that needs to be sent. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ $Date: 2009-12-07 18:36:08 +0200 (Mon, 07 Dec 2009) $ */ public class OtaStatusNotification { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/SuiteInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/SuiteInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/storagehandler/SuiteInfo.java Fri May 14 15:47:24 2010 +0300 @@ -18,13 +18,16 @@ package com.nokia.mj.impl.installer.storagehandler; +import com.nokia.mj.impl.fileutils.FileUtility; import com.nokia.mj.impl.installer.utils.ComponentId; import com.nokia.mj.impl.installer.utils.FileRoots; import com.nokia.mj.impl.installer.utils.FileUtils; +import com.nokia.mj.impl.installer.utils.Log; import com.nokia.mj.impl.utils.Attribute; import com.nokia.mj.impl.utils.Uid; import com.nokia.mj.impl.utils.Version; +import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; @@ -71,6 +74,8 @@ // Flag telling if application suite is trusted private boolean iTrusted = false; + /** Flag telling if default icon should be used. */ + private boolean iUseDefaultIcon = false; /** Filename for converted icon. This member is not saved into storage. */ private String iConvertedIconPath = null; /** Application installation group. This member is not saved into storage. */ @@ -384,8 +389,7 @@ } /** - * Get icon path for converted icon for speccified - * application in the suite. + * Get registered icon path for specified application in the suite. */ public String getRegisteredIconPath(int aAppIndex) { @@ -407,6 +411,56 @@ } /** + * Get names of application icon files from the directory where + * icons registered to the platform are. This method finds filenames + * from the disk, so it can only be used for a suite that has been + * installed. + */ + public String[] getRegisteredAppIcons() + { + String iconDirName = + FileRoots.getRegisteredIconDir(FileUtils.getDrive(getRootDir())) + + getUid().toString(); + Vector filenames = new Vector(); + try + { + FileUtility iconDir = new FileUtility(iconDirName); + if (iconDir.exists()) + { + Enumeration e = iconDir.list(); + while (e.hasMoreElements()) + { + String filename = (String)e.nextElement(); + filenames.addElement(filename); + } + } + } + catch (IOException ioe) + { + Log.logWarning( + "Cannot list application icons from " + iconDirName, ioe); + return null; + } + Uid[] appUids = getApplicationUids(); + String[] appIcons = new String[appUids.length]; + String filename = null; + for (int i = 0; i < appUids.length; i++) + { + appIcons[i] = null; + for (int j = 0; j < filenames.size(); j++) + { + filename = (String)filenames.elementAt(j); + if (filename.startsWith(appUids[i].toString())) + { + appIcons[i] = filename; + break; + } + } + } + return appIcons; + } + + /** * Tells if application suite is trusted. * * @return true if suite is trusted, false otherwise @@ -417,6 +471,22 @@ } /** + * Returns true if default icon should be used, false otherwise. + */ + public boolean getUseDefaultIcon() + { + return iUseDefaultIcon; + } + + /** + * Set flag telling if default icon should be used. + */ + public void setUseDefaultIcon(boolean aUseDefaultIcon) + { + iUseDefaultIcon = aUseDefaultIcon; + } + + /** * Get icon path for converted icon. */ public String getConvertedIconPath() diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/utils/DriveInfo.java --- a/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/utils/DriveInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/javasrc/com/nokia/mj/impl/installer/utils/DriveInfo.java Fri May 14 15:47:24 2010 +0300 @@ -23,9 +23,6 @@ /** * Contains all information about a device drive needed by UI. - * - * @author Nokia Corporation - * @version $Rev: 2572 $ */ public final class DriveInfo { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/src.s60/applicationregistrator/applicationregistrator.cpp --- a/javamanager/javainstaller/installer/src.s60/applicationregistrator/applicationregistrator.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/src.s60/applicationregistrator/applicationregistrator.cpp Fri May 14 15:47:24 2010 +0300 @@ -129,8 +129,8 @@ return err; } -#if 1 -//#ifndef RD_JAVA_USIF_APP_REG +//#if 1 +#ifndef RD_JAVA_USIF_APP_REG // Delete any pending (un)registrations (possible if // e.g. device rebooted before commit). // This call does nothing if there is no pending registrations. @@ -169,8 +169,8 @@ * @param[in] aBackground * @return 0 if registration succeeded or Symbian error code */ -#if 0 -//#ifdef RD_JAVA_USIF_APP_REG +//#if 0 +#ifdef RD_JAVA_USIF_APP_REG JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_ApplicationRegistrator__1registerApplication (JNIEnv */*aEnv*/, jclass /*aClass*/, jint /*aSessionHandle*/, jint /*aUid*/, jstring /*aGroupName*/, jstring /*aMIDletName*/, jstring /*aTargetDrive*/, jstring /*aIconFileName*/, @@ -486,8 +486,8 @@ * @param[in] aUid The Uid of the application to be unregistered.. * @return 0 if unregistration succeeded or Symbian error code */ -#if 0 -//#ifdef RD_JAVA_USIF_APP_REG +//#if 0 +#ifdef RD_JAVA_USIF_APP_REG JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_ApplicationRegistrator__1unregisterApplication (JNIEnv *, jclass, jint /*aSessionHandle*/, jint /*aUid*/) { @@ -520,14 +520,15 @@ JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_ApplicationRegistrator__1commitSession (JNIEnv *, jclass, jint aSessionHandle, jboolean aSynchronous) { + (void)aSynchronous; // suppress compilation warning about unused argument // Convert session handle to pointer. RApaLsSession *pApaSession = reinterpret_cast(aSessionHandle<<2); TInt err = KErrNone; -#if 1 -//#ifndef RD_JAVA_USIF_APP_REG +//#if 1 +#ifndef RD_JAVA_USIF_APP_REG if (aSynchronous) { // Make synchronous commit @@ -585,8 +586,8 @@ reinterpret_cast(aSessionHandle<<2); TInt err = KErrNone; -#if 1 -//#ifndef RD_JAVA_USIF_APP_REG +//#if 1 +#ifndef RD_JAVA_USIF_APP_REG err = pApaSession->RollbackNonNativeApplicationsUpdates(); #endif // RD_JAVA_USIF_APP_REG pApaSession->Close(); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/src.s60/applicationregistrator/sifnotifier.cpp --- a/javamanager/javainstaller/installer/src.s60/applicationregistrator/sifnotifier.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/src.s60/applicationregistrator/sifnotifier.cpp Fri May 14 15:47:24 2010 +0300 @@ -42,6 +42,8 @@ IMPORT_C HBufC* CreateHBufCFromJavaStringLC(JNIEnv* aEnv, jstring aString); +// String to be used for icon filenames when icon is not present. +_LIT(KNoIconFilename, ""); /* * Class: com_nokia_mj_impl_installer_applicationregistrator_SifNotifier @@ -61,13 +63,17 @@ void NotifyStartL( JNIEnv *aEnv, CPublishSifOperationInfo *aNotifier, jstring aGlobalComponentId, jstring aComponentName, - jobjectArray aApplicationNames, jint aComponentSize, - jstring aComponentIconPath) + jobjectArray aApplicationNames, jobjectArray aApplicationIcons, + jint aComponentSize, jstring aIconDir, jstring /*aComponentIcon*/) { __UHEAP_MARK; HBufC *globalComponentId = CreateHBufCFromJavaStringLC(aEnv, aGlobalComponentId); HBufC *componentName = CreateHBufCFromJavaStringLC(aEnv, aComponentName); - HBufC *componentIconPath = CreateHBufCFromJavaStringLC(aEnv, aComponentIconPath); + HBufC *iconDir = NULL; + if (NULL != aIconDir) + { + iconDir = CreateHBufCFromJavaStringLC(aEnv, aIconDir); + } RPointerArray applicationNames; CleanupResetAndDestroyPushL(applicationNames); @@ -77,16 +83,39 @@ TInt appsCount = aEnv->GetArrayLength(aApplicationNames); for (TInt i = 0; i < appsCount; i++) { - HBufC *appName = CreateHBufCFromJavaStringLC( - aEnv, (jstring)aEnv->GetObjectArrayElement(aApplicationNames, i)); + HBufC *appName = + CreateHBufCFromJavaStringLC( + aEnv, (jstring)aEnv->GetObjectArrayElement(aApplicationNames, i)); applicationNames.AppendL(appName); CleanupStack::Pop(appName); } + if (NULL != aApplicationIcons) + { + appsCount = aEnv->GetArrayLength(aApplicationIcons); + for (TInt i = 0; i < appsCount; i++) + { + jstring tmpAppIcon = + (jstring)aEnv->GetObjectArrayElement(aApplicationIcons, i); + if (NULL != tmpAppIcon) + { + HBufC *appIcon = CreateHBufCFromJavaStringLC(aEnv, tmpAppIcon); + applicationIcons.AppendL(appIcon); + CleanupStack::Pop(appIcon); + } + else + { + // Add a string indicating that icon is not available + // for this application. + applicationIcons.AppendL(KNoIconFilename().AllocL()); + } + } + } - CSifOperationStartData *startData = CSifOperationStartData::NewLC( - *globalComponentId, *componentName, applicationNames, applicationIcons, - aComponentSize, /*aIconPath=*/ *componentIconPath, - /*aComponentIcon=*/ KNullDesC(), Usif::KSoftwareTypeJava); + CSifOperationStartData *startData = + CSifOperationStartData::NewLC( + *globalComponentId, *componentName, applicationNames, applicationIcons, + aComponentSize, /*aIconPath=*/ (NULL != aIconDir? *iconDir: KNullDesC()), + /*aComponentIcon=*/ KNullDesC(), Usif::KSoftwareTypeJava); User::LeaveIfError(aNotifier->PublishStart(*startData)); @@ -95,7 +124,10 @@ CleanupStack::PopAndDestroy(&applicationIcons); CleanupStack::PopAndDestroy(&applicationNames); - CleanupStack::PopAndDestroy(componentIconPath); + if (NULL != aIconDir) + { + CleanupStack::PopAndDestroy(iconDir); + } CleanupStack::PopAndDestroy(componentName); CleanupStack::PopAndDestroy(globalComponentId); __UHEAP_MARKEND; @@ -108,14 +140,15 @@ */ JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_SifNotifier__1notifyStart (JNIEnv *aEnv, jclass, jint aHandle, jstring aGlobalComponentId, - jstring aComponentName, jobjectArray aApplicationNames, jint aComponentSize, - jstring aComponentIconPath) + jstring aComponentName, jobjectArray aApplicationNames, + jobjectArray aApplicationIcons, jint aComponentSize, + jstring aIconDir, jstring aComponentIcon) { CPublishSifOperationInfo *pNotifier = reinterpret_cast(aHandle<<2); TRAPD(err, NotifyStartL(aEnv, pNotifier, aGlobalComponentId, aComponentName, - aApplicationNames, aComponentSize, - aComponentIconPath)); + aApplicationNames, aApplicationIcons, + aComponentSize, aIconDir, aComponentIcon)); return err; } @@ -272,7 +305,7 @@ * Signature: (IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;I)I */ JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_SifNotifier__1notifyStart -(JNIEnv *, jclass, jint, jstring, jstring, jobjectArray, jint, jstring) +(JNIEnv *, jclass, jint, jstring, jstring, jobjectArray, jobjectArray, jint, jstring, jstring) { LOG(EJavaInstaller, EInfo, "SifNotifier.notifyStart"); return KErrNone; @@ -286,6 +319,8 @@ JNIEXPORT jint JNICALL Java_com_nokia_mj_impl_installer_applicationregistrator_SifNotifier__1notifyEnd (JNIEnv *, jclass, jint, jstring, jint aErrCategory, jint aErrCode, jstring, jstring) { + (void)aErrCategory; // suppress compilation warning about unused argument + (void)aErrCode; // suppress compilation warning about unused argument LOG2(EJavaInstaller, EInfo, "SifNotifier.notifyEnd: errCategory=%d, errCode=%d", aErrCategory, aErrCode); @@ -301,6 +336,10 @@ (JNIEnv *, jclass, jint, jstring, jint aOperation, jint aSubOperation, jint aCurrent, jint aTotal) { + (void)aOperation; // suppress compilation warning about unused argument + (void)aSubOperation; // suppress compilation warning about unused argument + (void)aCurrent; // suppress compilation warning about unused argument + (void)aTotal; // suppress compilation warning about unused argument LOG4(EJavaInstaller, EInfo, "SifNotifier.notifyProgress: op=%d, subop=%d, current=%d, total=%d", aOperation, aSubOperation, aCurrent, aTotal); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/src.s60/applicationregistrator/sifregistrator.cpp --- a/javamanager/javainstaller/installer/src.s60/applicationregistrator/sifregistrator.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/src.s60/applicationregistrator/sifregistrator.cpp Fri May 14 15:47:24 2010 +0300 @@ -628,22 +628,23 @@ RDesWriteStream writeStream(opaqueDataBuf); writeStream.WriteInt32L(aAppUid); writeStream.CommitL(); - COpaqueData *opaqueData = - COpaqueData::NewLC(opaqueDataBuf, KUnspecifiedLocale); + COpaqueData *opaqueData = COpaqueData::NewLC(opaqueDataBuf, KNonLocalized); opaqueDataArray.AppendL(opaqueData); CleanupStack::Pop(opaqueData); RPointerArray localizableAppInfoList; CleanupResetAndDestroyPushL(localizableAppInfoList); // Add non-localized application name (caption) and icon. - CCaptionAndIconInfo *captionAndIconInfo = CCaptionAndIconInfo::NewLC( - /*aCaption=*/ *caption, - /*aIconFileName=*/ *iconFilename, - /*aNumOfAppIcons=*/ numberOfAppIcons); - CLocalizableAppInfo *locAppInfo = CLocalizableAppInfo::NewLC( - /*aShortCaption=*/ KNullDesC, /*aApplicationLanguage=*/ KNonLocalized, - /*aGroupName=*/ KNullDesC, /*aCaptionAndIconInfo=*/ captionAndIconInfo, - /*aViewDataList=*/ viewDataList); + CCaptionAndIconInfo *captionAndIconInfo = + CCaptionAndIconInfo::NewLC( + /*aCaption=*/ *caption, + /*aIconFileName=*/ (NULL != aIconFilename? *iconFilename: KNullDesC()), + /*aNumOfAppIcons=*/ numberOfAppIcons); + CLocalizableAppInfo *locAppInfo = + CLocalizableAppInfo::NewLC( + /*aShortCaption=*/ KNullDesC, /*aApplicationLanguage=*/ KNonLocalized, + /*aGroupName=*/ KNullDesC, /*aCaptionAndIconInfo=*/ captionAndIconInfo, + /*aViewDataList=*/ viewDataList); localizableAppInfoList.AppendL(locAppInfo); CleanupStack::Pop(locAppInfo); CleanupStack::Pop(captionAndIconInfo); @@ -659,8 +660,9 @@ for (TInt i = 0; i < langCount; i++) { TLanguage tmpLanguage = (TLanguage)languages[i]; - HBufC *tmpCaption = CreateHBufCFromJavaStringLC( - aEnv, (jstring)aEnv->GetObjectArrayElement(aAppNames, i)); + HBufC *tmpCaption = + CreateHBufCFromJavaStringLC( + aEnv, (jstring)aEnv->GetObjectArrayElement(aAppNames, i)); captionsArray.AppendL(tmpCaption); CleanupStack::Pop(tmpCaption); //LOG1(EJavaInstaller, EInfo, diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistratorTest.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistratorTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/applicationregistrator/ApplicationRegistratorTest.java Fri May 14 15:47:24 2010 +0300 @@ -30,9 +30,6 @@ /** * ApplicationRegistrator unit tests. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public class ApplicationRegistratorTest extends TestCase implements InstallerMain { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesTest.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/customisationproperties/CustomisationPropertiesTest.java Fri May 14 15:47:24 2010 +0300 @@ -33,9 +33,6 @@ /** * ApplicationRegistrator unit tests. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public class CustomisationPropertiesTest extends TestCase implements InstallerMain { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/BadTestPlugin.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/BadTestPlugin.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/BadTestPlugin.java Fri May 14 15:47:24 2010 +0300 @@ -23,8 +23,6 @@ * This plugin does not implement InstallerExtension interface although * it has all the correct functions. * - * @author Nokia Corporation - * @version $Rev: 9336 $ $Date: 2010-01-14 14:18:29 +0200 (Thu, 14 Jan 2010) $ * @see InstallerExtension */ public class BadTestPlugin diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifierTest.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifierTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/JsrPluginNotifierTest.java Fri May 14 15:47:24 2010 +0300 @@ -37,9 +37,6 @@ /** * ApplicationRegistrator unit tests. - * - * @author Nokia Corporation - * @version $Rev: 9041 $ */ public class JsrPluginNotifierTest extends TestCase implements InstallerMain { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin.java Fri May 14 15:47:24 2010 +0300 @@ -21,8 +21,6 @@ /** * Installer Jsr plugin just for test purposes. * - * @author Nokia Corporation - * @version $Rev: 9336 $ $Date: 2010-01-14 14:18:29 +0200 (Thu, 14 Jan 2010) $ * @see InstallerExtension */ public class TestPlugin implements InstallerExtension diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin2.java --- a/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin2.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installer/tsrc/javasrc/com/nokia/mj/impl/installer/jsrpluginnotifier/TestPlugin2.java Fri May 14 15:47:24 2010 +0300 @@ -21,8 +21,6 @@ /** * Installer Jsr plugin just for test purposes. * - * @author Nokia Corporation - * @version $Rev: 9336 $ $Date: 2010-01-14 14:18:29 +0200 (Thu, 14 Jan 2010) $ * @see InstallerExtension */ public class TestPlugin2 implements InstallerExtension diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/InstallerUi.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/InstallerUi.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/InstallerUi.java Fri May 14 15:47:24 2010 +0300 @@ -372,17 +372,21 @@ } /** + * Hides or unhides InstallerUi. + */ + public void hide(boolean aHide) + { + } + + /** * Writes an info log entry to JavaInstaller log. * * @param aMsg message to be logged */ public static void log(String aMsg) { - if (Logger.Activated[Logger.EJavaInstaller]) - { - String msg = iThisClassName + ": " + aMsg; - Logger.LOG(Logger.EJavaInstaller, Logger.EInfo, msg); - } + String msg = iThisClassName + ": " + aMsg; + Logger.ILOG(Logger.EJavaInstaller, msg); } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallDetailsView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallDetailsView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallDetailsView.java Fri May 14 15:47:24 2010 +0300 @@ -258,9 +258,6 @@ addSoftKeyListenerFor(certLink); } } - /* - // Uncomment this to enable "application not certified" - // warning in installation details view. else { // Add not certified application link. @@ -281,7 +278,6 @@ certLink.setLayoutData(gridData); addSoftKeyListenerFor(certLink); } - */ } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallerUiEswt.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallerUiEswt.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/InstallerUiEswt.java Fri May 14 15:47:24 2010 +0300 @@ -56,9 +56,6 @@ /** * JavaInstaller eSWT UI. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class InstallerUiEswt extends InstallerUi { @@ -663,7 +660,7 @@ { return; } - if (iDlProgressView != null) + if (iDlProgressView != null && !iDlProgressView.isDisposed()) { iDlProgressView.dispose(); iDlProgressView = null; diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/MinimalUi.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/MinimalUi.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/MinimalUi.java Fri May 14 15:47:24 2010 +0300 @@ -28,9 +28,6 @@ /** * Minimal UI for JavaInstaller. This UI will only show simplified * confirmation dialogs using RuntimeUi. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class MinimalUi extends InstallerUi { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/PermissionDetailsView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/PermissionDetailsView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/PermissionDetailsView.java Fri May 14 15:47:24 2010 +0300 @@ -77,7 +77,6 @@ } } - /* // Add permissions details message. if (iPermissionInfo.getPermissionsDetails() != null) { @@ -86,7 +85,6 @@ iPermissionInfo.getPermissionsDetails(), horizontalSpan, labelStyle); } - */ } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/ViewBase.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/ViewBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt/ViewBase.java Fri May 14 15:47:24 2010 +0300 @@ -174,8 +174,11 @@ { public void run() { - log(className + ": disposing view container"); - iContainer.dispose(); + if (!isDisposed()) + { + log(className + ": disposing view container"); + iContainer.dispose(); + } } }); } @@ -212,11 +215,14 @@ } } // UI updates must be executed in UI thread. - iParent.getDisplay().syncExec - (new Runnable() + iParent.getDisplay().syncExec(new Runnable() { public void run() { + if (isDisposed()) + { + return; + } if (iVisible) { updateSize(); @@ -421,10 +427,10 @@ { Label label = createLabel((Image)null, 1, SWT.NONE); Image securityIcon = null; - if (iInstallerUi instanceof InstallerUiEswt) + if (iInstallerUi != null) { - securityIcon = ((InstallerUiEswt)iInstallerUi).getSecurityIcon - (getDisplay(), aIdentified); + securityIcon = iInstallerUi.getSecurityIcon( + getDisplay(), aIdentified); } if (securityIcon != null) { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/CertificateDetailsView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/CertificateDetailsView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/CertificateDetailsView.java Fri May 14 15:47:24 2010 +0300 @@ -81,6 +81,17 @@ horizontalSpan, labelStyle); detailsLabel.setFont(iInstallerUi.getBoldFont()); + // Add domain category label. + createLabel("", horizontalSpan, labelStyle); + Label domainLabel = createLabel( + InstallerUiTexts.get( + InstallerUiTexts.DOMAIN, + new String[] { + InstallerUiTexts.get(InstallerUiTexts.DOMAIN_UTP) + }), + horizontalSpan, labelStyle); + createLabel("", horizontalSpan, labelStyle); + // Add warning label. Label warningLabel = createLabel( InstallerUiTexts.get(InstallerUiTexts.NOT_CERTIFIED_WARNING), diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ConfirmationViewBase.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ConfirmationViewBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ConfirmationViewBase.java Fri May 14 15:47:24 2010 +0300 @@ -57,15 +57,15 @@ } /** Constructor */ - protected ConfirmationViewBase(InstallerUiEswt aInstaller, Composite aParent, int aColumns) + protected ConfirmationViewBase(InstallerUiEswt aInstallerUi, Composite aParent, int aColumns) { - this(aInstaller, aParent, aColumns, false); + this(aInstallerUi, aParent, aColumns, false); } /** Constructor */ - protected ConfirmationViewBase(InstallerUiEswt aInstaller, Composite aParent, int aColumns, boolean aScrollable) + protected ConfirmationViewBase(InstallerUiEswt aInstallerUi, Composite aParent, int aColumns, boolean aScrollable) { - super(aInstaller, aParent, aColumns, aScrollable); + super(aInstallerUi, aParent, aColumns, aScrollable); } /** diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ErrorDetailsView.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ErrorDetailsView.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.mj.impl.installer.ui.eswt2; + +import com.nokia.mj.impl.utils.exception.ExceptionBase; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; + +/** + * Displays error message details. + */ +public class ErrorDetailsView extends ConfirmationViewBase +{ + private ExceptionBase iException = null; + + /** Constructor */ + protected ErrorDetailsView() + { + super(); + } + + /** Constructor */ + protected ErrorDetailsView(InstallerUiEswt aInstallerUi, Composite aParent) + { + super(aInstallerUi, aParent, 8); + setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALL_FAILED)); + setCommands(InstallerUiTexts.get(InstallerUiTexts.OK), null); + } + + /** + * Synchoronous method for displaying error message details. + */ + public boolean error(ExceptionBase aException) + { + iException = aException; + boolean result = confirm(); + if (result) + { + log("ErrorDetailsView confirmed"); + } + else + { + log("ErrorDetailsView cancelled"); + } + return result; + } + + /** + * This method is called once before view is opened. + */ + protected void createView() + { + // Add title. + //String title = InstallerUiTexts.get(InstallerUiTexts.INSTALL_FAILED); + String title = "Installation failed"; + if (iInstallerUi.getInstallInfo() != null) + { + if (iInstallerUi.getInstallInfo().getOldVersion() != null) + { + title = "Update failed"; + } + Label titleLabel = createLabel(title, getColumns() - 1, SWT.WRAP); + titleLabel.setFont(iInstallerUi.getBoldFont()); + // Add security icon. + iCertificates = iInstallerUi.getInstallInfo().getCertificates(); + createSecurityButton(); + } + else + { + Label titleLabel = createLabel(title, getColumns(), SWT.WRAP); + titleLabel.setFont(iInstallerUi.getBoldFont()); + } + + int horizontalSpan = getColumns(); + int labelStyle = SWT.WRAP; + + // Begin widgets creation. + Label errorLabel = createLabel( + iException.getDetailedMessage(), horizontalSpan, labelStyle); + // End of widgets creation. + } + + /** + * This method is called after user has answered + * to confirmation. + * Inheriting class must implement this method. + */ + protected void getDataFromView() + { + // nop + } + + /** + * Returns SWT style for this view. + */ + protected int getStyle() + { + return SWT.V_SCROLL; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ErrorView.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ErrorView.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.mj.impl.installer.ui.eswt2; + +import com.nokia.mj.impl.utils.exception.ExceptionBase; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; + +/** + * Displays error message. + */ +public class ErrorView extends ConfirmationViewBase +{ + private ExceptionBase iException = null; + + /** Constructor */ + protected ErrorView() + { + super(); + } + + /** Constructor */ + protected ErrorView(InstallerUiEswt aInstallerUi, Composite aParent) + { + super(aInstallerUi, aParent, 8); + setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALL_FAILED)); + setCommands("Show", + InstallerUiTexts.get(InstallerUiTexts.CLOSE)); + } + + /** + * Synchoronous method for displaying error message. + */ + public boolean error(ExceptionBase aException) + { + iException = aException; + boolean result = confirm(); + if (result) + { + log("ErrorView confirmed"); + } + else + { + log("ErrorView cancelled"); + } + return result; + } + + /** + * This method is called once before view is opened. + */ + protected void createView() + { + // Add header. + //String title = InstallerUiTexts.get(InstallerUiTexts.INSTALL_FAILED); + String title = "Installation failed"; + if (iInstallerUi.getInstallInfo() != null) + { + if (iInstallerUi.getInstallInfo().getOldVersion() != null) + { + title = "Update failed"; + } + addHeader(title, iInstallerUi.getInstallInfo(), null); + } + else + { + Label titleLabel = createLabel(title, getColumns(), SWT.WRAP); + titleLabel.setFont(iInstallerUi.getBoldFont()); + } + + int horizontalSpan = getColumns(); + int labelStyle = SWT.WRAP; + + // Begin widgets creation. + Label errorLabel = createLabel( + iException.getShortMessage(), horizontalSpan, labelStyle); + // End of widgets creation. + + if (iInstallerUi.getInstallInfo() != null) + { + // After other widgets have been added, add content to + // application info Composite. + addAppInfo(iInstallerUi.getInstallInfo(), true); + } + } + + /** + * This method is called after user has answered + * to confirmation. + * Inheriting class must implement this method. + */ + protected void getDataFromView() + { + // nop + } + + /** + * Returns SWT style for this view. + */ + protected int getStyle() + { + return SWT.V_SCROLL; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallConfirmationView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallConfirmationView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallConfirmationView.java Fri May 14 15:47:24 2010 +0300 @@ -55,9 +55,10 @@ } /** Constructor */ - protected InstallConfirmationView(InstallerUiEswt aInstaller, Composite aParent) + protected InstallConfirmationView( + InstallerUiEswt aInstallerUi, Composite aParent) { - super(aInstaller, aParent, 8); + super(aInstallerUi, aParent, 8); setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALL)); setCommands(InstallerUiTexts.get(InstallerUiTexts.OK), InstallerUiTexts.get(InstallerUiTexts.CANCEL)); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerRuntimeUi.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerRuntimeUi.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.mj.impl.installer.ui.eswt2; + +import com.nokia.mj.impl.rt.ui.ConfirmData; +import com.nokia.mj.impl.rt.ui.RuntimeUi; +import com.nokia.mj.impl.utils.exception.ExceptionBase; +import com.nokia.mj.impl.utils.exception.InstallerExceptionBase; +import com.nokia.mj.impl.utils.Logger; + +/** + * Implementation for JavaInstaller specific RuntimeUI. + */ +public class InstallerRuntimeUi extends RuntimeUi +{ + private static InstallerUiEswt iInstallerUi = null; + + /** + * Initializes static members of this class. + */ + static void init(InstallerUiEswt aInstallerUi) + { + iInstallerUi = aInstallerUi; + iLogId = Logger.EJavaInstaller; + } + + /** + * Constructor + */ + public InstallerRuntimeUi() + { + super(); + } + + /** + * Seeks confirmation from the user. + * + * @param aAppName the name of the application on behalf of which the + * confirmation is requested + * @param aConfirmData the data to be confirmed. Unless the user has + * canceled the confirmation, this data will be filled + * in with user's answer upon return + * @return true if the user has answered, false if the user has + * canceled the confirmation + */ + public boolean confirm(String aAppName, ConfirmData aConfirmData) + { + boolean result = super.confirm(aAppName, aConfirmData); + if (iInstallerUi != null) + { + result = iInstallerUi.confirm(aAppName, aConfirmData); + } + return result; + } + + /** + * Notifies the user that an error has occurred. + * This method must return quickly. + * + * @param aAppName the name of the application which generated the error + * situation + * @param aException exception indicating the error reason + */ + public void error(String aAppName, ExceptionBase aException) + { + super.error(aAppName, aException); + if (iInstallerUi != null && + aException instanceof InstallerExceptionBase) + { + iInstallerUi.error((InstallerExceptionBase)aException); + } + else + { + logError("Unexpected exception from " + aAppName, aException); + } + } +} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiEswt.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiEswt.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiEswt.java Fri May 14 15:47:24 2010 +0300 @@ -28,6 +28,7 @@ import com.nokia.mj.impl.installer.ui.PermissionInfo; import com.nokia.mj.impl.installer.ui.UninstallInfo; import com.nokia.mj.impl.installer.ui.eswt.MinimalUi; +import com.nokia.mj.impl.rt.ui.ConfirmData; import com.nokia.mj.impl.rt.ui.RuntimeUi; import com.nokia.mj.impl.rt.ui.RuntimeUiFactory; import com.nokia.mj.impl.utils.ResourceUtil; @@ -58,9 +59,6 @@ /** * JavaInstaller eSWT UI. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class InstallerUiEswt extends InstallerUi { @@ -78,6 +76,9 @@ private PermissionConfirmationView iPermissionConfirmationView = null; private UsernamePasswordView iUsernamePasswordView = null; private LaunchAppQueryView iLaunchAppQueryView = null; + private ErrorView iErrorView = null; + private ErrorDetailsView iErrorDetailsView = null; + private RuntimeConfirmationView iRuntimeConfirmationView = null; /** Synchronization object for waiting for the UI initialization. */ private Object iInitWaitObject = new Object(); /** Synchronization object for waiting for the UI termination. */ @@ -131,6 +132,7 @@ { super.init(aMode, aListener); StartUpTrace.doTrace("InstallerUiEswt init"); + InstallerRuntimeUi.init(this); // Create a hashtable for icons. iImageTable = new Hashtable(); // Create a new thread to be the UI main thread. @@ -271,6 +273,18 @@ { iLaunchAppQueryView.confirmCancel(); } + if (iErrorView != null) + { + iErrorView.confirmCancel(); + } + if (iErrorDetailsView != null) + { + iErrorDetailsView.confirmCancel(); + } + if (iRuntimeConfirmationView != null) + { + iRuntimeConfirmationView.confirmCancel(); + } // Remove download progress bar if it visible. if (iDlProgressView != null && !iDlProgressView.isDisposed()) { @@ -686,7 +700,7 @@ { return; } - if (iDlProgressView != null) + if (iDlProgressView != null && !iDlProgressView.isDisposed()) { iDlProgressView.dispose(); iDlProgressView = null; @@ -803,7 +817,6 @@ /** * Notify user that an error has occurred. - * This method must return quickly. * * @param aInstallerException exception indicating the error reason */ @@ -812,17 +825,59 @@ super.error(aInstallerException); waitForUi(); - // InstallerUi does not have to be ready as long as - // RuntimeUi is used to display error messages. - //if (!isUiReady()) { - // return; - //} + if (!isUiReady()) { + showRuntimeUiError(aInstallerException); + return; + } + + // Use ErrorView to display error message. + if (iErrorView == null) + { + final Display display = iParent.getDisplay(); + final InstallerUiEswt self = this; + display.syncExec(new Runnable() + { + public void run() + { + iErrorView = new ErrorView(self, iDialog); + } + }); + } + boolean result = iErrorView.error(aInstallerException); + iErrorView.dispose(); + iErrorView = null; + if (result) + { + // Display error details. + if (iErrorDetailsView == null) + { + final Display display = iParent.getDisplay(); + final InstallerUiEswt self = this; + display.syncExec(new Runnable() + { + public void run() + { + iErrorDetailsView = new ErrorDetailsView(self, iDialog); + } + }); + } + result = iErrorDetailsView.error(aInstallerException); + iErrorDetailsView.dispose(); + iErrorDetailsView = null; + } + } + + /** + * Notify user that an error has occurred using RuntimeUI. + * + * @param aInstallerException exception indicating the error reason + */ + private void showRuntimeUiError(InstallerExceptionBase aInstallerException) + { boolean identified = false; - //String tmpAppName = null; if (iInstallInfo != null) { - //tmpAppName = iInstallInfo.getName(); if (iInstallInfo.getCertificates() != null) { identified = true; @@ -830,7 +885,6 @@ } else if (iUninstallInfo != null) { - //tmpAppName = iUninstallInfo.getName(); if (iUninstallInfo.getCertificates() != null) { identified = true; @@ -853,67 +907,50 @@ { iProgressView.setVisible(false); } - // Use RuntimeUi to display error message. + // Use RuntimeUi to display uninstallation error message. RuntimeUi runtimeUi = RuntimeUiFactory.getRuntimeUi(identified); runtimeUi.error(tmpTitle, aInstallerException); runtimeUi.destroy(); + } - /* - // Display error message using eSWT MessageBox. - final String appName = tmpAppName; - final String title = tmpTitle; - final String shortMsg = aInstallerException.getShortMessage(); - final String detailedMsg = aInstallerException.getDetailedMessage(); - // UI updates must be executed in UI thread. - iParent.getDisplay().syncExec - (new Runnable() { - public void run() { - if (detailedMsg == null || detailedMsg.length() == 0) { - // No detailed msg, display only short msg. - MessageBox messageBox = new MessageBox - (iParent, SWT.ICON_ERROR | SWT.OK); - messageBox.setText(title); - messageBox.setMessage - (getMessage(title, appName, shortMsg, false)); - messageBox.open(); - } else { - // Display both short and detailed msgs. - MessageBox messageBox = new MessageBox - (iParent, SWT.ICON_ERROR | SWT.YES | SWT.NO); - messageBox.setText(title); - messageBox.setMessage - (getMessage(title, appName, shortMsg, true)); - int answer = messageBox.open(); - if ((answer & SWT.YES) != 0) { - // User wants to see details, display them. - messageBox = new MessageBox - (iParent, SWT.ICON_ERROR | SWT.OK); - messageBox.setText(title); - messageBox.setMessage - (getMessage(title, appName, detailedMsg, false)); - messageBox.open(); - } - } - } - private String getMessage(String aTitle, String aAppName, - String aMsg, boolean aDetailsQuery) { - //String result = aTitle + "\n\n"; - String result = ""; - if (aAppName == null) { - result += aMsg; - } else { - result += aAppName + "\n\n" + aMsg; - } - if (aDetailsQuery) { - result += "\n\n"; - result += InstallerUiTexts.get - (InstallerUiTexts.DETAILS_QUERY); - } - return result; - } - }); + /** + * Seeks confirmation from the user. + * + * @param aAppName the name of the application on behalf of which the + * confirmation is requested + * @param aConfirmData the data to be confirmed. Unless the user has + * canceled the confirmation, this data will be filled + * in with user's answer upon return + * @return true if the user has answered, false if the user has + * canceled the confirmation + */ + public boolean confirm(String aAppName, ConfirmData aConfirmData) + { + waitForUi(); + if (!isUiReady()) { + return true; + } - */ + if (iRuntimeConfirmationView == null) + { + final Display display = iParent.getDisplay(); + final InstallerUiEswt self = this; + final String appName = aAppName; + final ConfirmData confirmData = aConfirmData; + display.syncExec(new Runnable() + { + public void run() + { + iRuntimeConfirmationView = new RuntimeConfirmationView( + self, iDialog, appName, confirmData); + } + }); + } + boolean result = iRuntimeConfirmationView.confirm(); + iRuntimeConfirmationView.dispose(); + iRuntimeConfirmationView = null; + log("Runtime confirmation returns " + result); + return result; } /** @@ -1020,7 +1057,7 @@ /** * Hides or unhides InstallerUi. */ - protected void hide(boolean aHide) + public void hide(boolean aHide) { iParent.setMinimized(aHide); } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiTexts.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiTexts.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/InstallerUiTexts.java Fri May 14 15:47:24 2010 +0300 @@ -24,9 +24,6 @@ /** * Class defining InstallerUi texts. - * - * @author Nokia Corporation - * @version 1.0 */ public class InstallerUiTexts { @@ -40,6 +37,7 @@ public static final String INSTALL = "progress"; public static final String UNINSTALL = "uninstalling_progress"; public static final String START = "start"; + public static final String SHOW = "show"; public static final String CLOSE = "close"; public static final String INSTALL_QUERY = "query"; public static final String UPDATE_QUERY = "update_query"; diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/LaunchAppQueryView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/LaunchAppQueryView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/LaunchAppQueryView.java Fri May 14 15:47:24 2010 +0300 @@ -41,9 +41,10 @@ } /** Constructor */ - protected LaunchAppQueryView(InstallerUiEswt aInstaller, Composite aParent) + protected LaunchAppQueryView( + InstallerUiEswt aInstallerUi, Composite aParent) { - super(aInstaller, aParent, 8); + super(aInstallerUi, aParent, 8); setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALLATION_COMPLETE)); setCommands("Show", //InstallerUiTexts.get(InstallerUiTexts.SHOW), InstallerUiTexts.get(InstallerUiTexts.CLOSE)); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionConfirmationView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionConfirmationView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionConfirmationView.java Fri May 14 15:47:24 2010 +0300 @@ -59,9 +59,10 @@ } /** Constructor */ - protected PermissionConfirmationView(InstallerUiEswt aInstaller, Composite aParent) + protected PermissionConfirmationView( + InstallerUiEswt aInstallerUi, Composite aParent) { - super(aInstaller, aParent, 8, true); + super(aInstallerUi, aParent, 8, true); setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALL)); setCommands(null, null); } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionDetailsView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionDetailsView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/PermissionDetailsView.java Fri May 14 15:47:24 2010 +0300 @@ -39,11 +39,11 @@ } /** Constructor */ - protected PermissionDetailsView(InstallerUiEswt aInstaller, Composite aParent, - String aTitle, - PermissionInfo aPermissionInfo) + protected PermissionDetailsView( + InstallerUiEswt aInstallerUi, Composite aParent, + String aTitle, PermissionInfo aPermissionInfo) { - super(aInstaller, aParent, 1, true); + super(aInstallerUi, aParent, 1, true); iPermissionInfo = aPermissionInfo; setTitle(aTitle); setCommands(null, InstallerUiTexts.get(InstallerUiTexts.OK)); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ProgressView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ProgressView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ProgressView.java Fri May 14 15:47:24 2010 +0300 @@ -58,29 +58,29 @@ } /** Constructor */ - protected ProgressView(InstallerUiEswt aInstaller, Composite aParent) + protected ProgressView(InstallerUiEswt aInstallerUi, Composite aParent) { - this(aInstaller, aParent, ""); + this(aInstallerUi, aParent, ""); } /** Constructor */ - protected ProgressView(InstallerUiEswt aInstaller, Composite aParent, String aMsg) + protected ProgressView(InstallerUiEswt aInstallerUi, Composite aParent, String aMsg) { - this(aInstaller, aParent, aMsg, false); + this(aInstallerUi, aParent, aMsg, false); } /** Constructor */ - protected ProgressView(InstallerUiEswt aInstaller, Composite aParent, String aMsg, + protected ProgressView(InstallerUiEswt aInstallerUi, Composite aParent, String aMsg, boolean aIndeterminate) { - super(aInstaller, aParent, 8); + super(aInstallerUi, aParent, 8); iMsg = aMsg; // Add header. if (iInstallerUi != null && iInstallerUi.getInstallInfo() != null) { // Add header. - addHeader(aMsg, iInstallerUi.getInstallInfo(), null); + addHeader(aMsg, iInstallerUi.getInstallInfo(), null, false); } else { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/RuntimeConfirmationView.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/RuntimeConfirmationView.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,181 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.mj.impl.installer.ui.eswt2; + +import com.nokia.mj.impl.rt.ui.ConfirmData; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; + +/** + * Displays error message. + */ +public class RuntimeConfirmationView extends ConfirmationViewBase +{ + private String iAppName = null; + private ConfirmData iConfirmData = null; + private Button[] iAnswerButtons = null; + + /** Constructor */ + protected RuntimeConfirmationView() + { + super(); + } + + /** Constructor */ + protected RuntimeConfirmationView(InstallerUiEswt aInstallerUi, + Composite aParent, String aAppName, + ConfirmData aConfirmData) + { + super(aInstallerUi, aParent, 8); + iAppName = aAppName; + iConfirmData = aConfirmData; + setTitle(InstallerUiTexts.get(InstallerUiTexts.INSTALL_FAILED)); + String[] answerOptions = iConfirmData.getAnswerOptions(); + switch (answerOptions.length) + { + case 1: setCommands(answerOptions[0], null); break; + case 2: setCommands(answerOptions[0], answerOptions[1]); break; + default: setCommands(null, null); break; + } + } + + /** + * This method is called once before view is opened. + */ + protected void createView() + { + // Add title. + if (iInstallerUi.getInstallInfo() != null) + { + Label titleLabel = createLabel(iAppName, getColumns() - 1, SWT.WRAP); + titleLabel.setFont(iInstallerUi.getBoldFont()); + // Add security icon. + iCertificates = iInstallerUi.getInstallInfo().getCertificates(); + createSecurityButton(); + } + else + { + Label titleLabel = createLabel(iAppName, getColumns(), SWT.WRAP); + titleLabel.setFont(iInstallerUi.getBoldFont()); + } + + GridData gridData = null; + int horizontalSpan = getColumns(); + int labelStyle = SWT.WRAP; + + // Begin widgets creation. + + // Add question label. + Label errorLabel = createLabel( + iConfirmData.getQuestion(), horizontalSpan, labelStyle); + + + // Add user answer buttons. + String[] answerOptions = iConfirmData.getAnswerOptions(); + if (answerOptions.length > 2) + { + iAnswerButtons = new Button[answerOptions.length]; + for (int i = 0; i < iAnswerButtons.length; i++) + { + final int answerIndex = i; + iAnswerButtons[i] = new Button(getComposite(), SWT.PUSH); + iAnswerButtons[i].setText(answerOptions[i]); + gridData = new GridData(GridData.FILL_HORIZONTAL); + gridData.horizontalSpan = horizontalSpan; + iAnswerButtons[i].setLayoutData(gridData); + iAnswerButtons[i].addDisposeListener(new DisposeListener () + { + public void widgetDisposed(DisposeEvent aEvent) + { + answer(answerIndex); + } + }); + iAnswerButtons[i].addSelectionListener(new SelectionListener () + { + public void widgetDefaultSelected(SelectionEvent aEvent) + { + widgetSelected(aEvent); + } + public void widgetSelected(SelectionEvent aEvent) + { + answer(answerIndex); + } + }); + } + // Set the default answer option. + iParent.setDefaultButton( + iAnswerButtons[iConfirmData.getAnswerSuggestion()]); + iAnswerButtons[iConfirmData.getAnswerSuggestion()].setFocus(); + } + + // End of widgets creation. + } + + /** + * This method is called when user answers to the dialog. + */ + protected void answer(int aAnswerIndex) + { + iConfirmData.setAnswer(aAnswerIndex); + super.confirmOk(); + } + + /** + * This method is called when user accepts the dialog. + */ + protected void confirmOk() + { + iConfirmData.setAnswer(0); + super.confirmOk(); + } + + /** + * This method is called when user cancels the dialog. + */ + protected void confirmCancel() + { + iConfirmData.setAnswer(1); + super.confirmCancel(); + } + + /** + * This method is called after user has answered + * to confirmation. + */ + protected void getDataFromView() + { + // nop + } + + /** + * Returns SWT style for this view. + */ + protected int getStyle() + { + return SWT.V_SCROLL; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UninstallConfirmationView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UninstallConfirmationView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UninstallConfirmationView.java Fri May 14 15:47:24 2010 +0300 @@ -46,9 +46,10 @@ } /** Constructor */ - protected UninstallConfirmationView(InstallerUiEswt aInstaller, Composite aParent) + protected UninstallConfirmationView( + InstallerUiEswt aInstallerUi, Composite aParent) { - super(aInstaller, aParent, 8); + super(aInstallerUi, aParent, 8); setTitle(InstallerUiTexts.get(InstallerUiTexts.UNINSTALL)); setCommands(InstallerUiTexts.get(InstallerUiTexts.OK), InstallerUiTexts.get(InstallerUiTexts.CANCEL)); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UsernamePasswordView.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UsernamePasswordView.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/UsernamePasswordView.java Fri May 14 15:47:24 2010 +0300 @@ -18,6 +18,7 @@ package com.nokia.mj.impl.installer.ui.eswt2; +import org.eclipse.ercp.swt.mobile.Screen; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; @@ -44,9 +45,10 @@ } /** Constructor */ - protected UsernamePasswordView(InstallerUiEswt aInstaller, Composite aParent) + protected UsernamePasswordView( + InstallerUiEswt aInstallerUi, Composite aParent) { - super(aInstaller, aParent, 1); + super(aInstallerUi, aParent, 1); setTitle(InstallerUiTexts.get(InstallerUiTexts.CONNECT_TO)); setCommands(InstallerUiTexts.get(InstallerUiTexts.OK), InstallerUiTexts.get(InstallerUiTexts.CANCEL)); @@ -86,8 +88,11 @@ } iUrl = aUrl; + // UsernamePasswordView is always displayed in portrait mode. + //forceScreenOrientation(Screen.PORTRAIT); // Use confirm() from super class to display the view. boolean confirmation = confirm(); + //forceScreenOrientation(SWT.DEFAULT); // And return the result to the client. String[] result = null; diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ViewBase.java --- a/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ViewBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javainstaller/installerui/javasrc/com/nokia/mj/impl/installer/ui/eswt2/ViewBase.java Fri May 14 15:47:24 2010 +0300 @@ -25,6 +25,8 @@ import java.io.InputStream; +import org.eclipse.ercp.swt.mobile.MobileDevice; +import org.eclipse.ercp.swt.mobile.Screen; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionEvent; @@ -75,7 +77,7 @@ /** Certificate details view. */ private CertificateDetailsView iCertificateDetailsView = null; /** Certificates for this application. */ - private SigningCertificate[] iCertificates = null; + protected SigningCertificate[] iCertificates = null; /** Constructor */ protected ViewBase() @@ -83,15 +85,15 @@ } /** Constructor */ - protected ViewBase(InstallerUiEswt aInstaller, Composite aParent, int aColumns) + protected ViewBase(InstallerUiEswt aInstallerUi, Composite aParent, int aColumns) { - this(aInstaller, aParent, aColumns, false); + this(aInstallerUi, aParent, aColumns, false); } /** Constructor */ - protected ViewBase(InstallerUiEswt aInstaller, Composite aParent, int aColumns, boolean aScrollable) + protected ViewBase(InstallerUiEswt aInstallerUi, Composite aParent, int aColumns, boolean aScrollable) { - iInstallerUi = aInstaller; + iInstallerUi = aInstallerUi; // Each view gets a shell to be used as a parameter. iParent = (Shell)aParent; @@ -229,8 +231,11 @@ { public void run() { - log(className + ": disposing view container"); - iContainer.dispose(); + if (!isDisposed()) + { + log(className + ": disposing view container"); + iContainer.dispose(); + } } }); } @@ -267,11 +272,14 @@ } } // UI updates must be executed in UI thread. - iParent.getDisplay().syncExec - (new Runnable() + iParent.getDisplay().syncExec(new Runnable() { public void run() { + if (isDisposed()) + { + return; + } if (iVisible) { updateSize(); @@ -386,6 +394,20 @@ } /** + * Forces screen orientation. Valid values are + * Screen.PORTRAIT, Screen.LANDSCAPE, and SWT.DEFAULT. + */ + protected void forceScreenOrientation(int aOrientation) + { + Screen[] screens = MobileDevice.getMobileDevice().getScreens(); + for (int i = 0; i < screens.length; i++) + { + screens[i].setOrientation(aOrientation); + } + log(this.toString() + ": screen orientation set to " + aOrientation); + } + + /** * Returns true if the View should have focus after it has been opened. */ protected boolean forceFocusToView() @@ -412,11 +434,21 @@ } /** - * Adds header used in installation and uninstallation views. + * Adds header used in installation views. */ protected void addHeader( String aTitle, InstallInfo aInstallInfo, UninstallInfo aUninstallInfo) { + addHeader(aTitle, aInstallInfo, aUninstallInfo, true); + } + + /** + * Adds header used in installation views. + */ + protected void addHeader( + String aTitle, InstallInfo aInstallInfo, UninstallInfo aUninstallInfo, + boolean aSecurityButton) + { // Add title. String title = "Install?"; if (aInstallInfo != null) @@ -435,8 +467,16 @@ Label titleLabel = createLabel(aTitle, getColumns() - 1, SWT.WRAP); titleLabel.setFont(iInstallerUi.getBoldFont()); - // Add security icon. - createSecurityButton(); + if (aSecurityButton) + { + // Add security icon. + createSecurityButton(); + } + else + { + // Add security icon. + createSecurityLabel(iCertificates != null); + } // Add suite icon. InputStream iconInputStream = null; @@ -628,10 +668,10 @@ { Label label = createLabel((Image)null, 1, SWT.NONE); Image securityIcon = null; - if (iInstallerUi instanceof InstallerUiEswt) + if (iInstallerUi != null) { - securityIcon = ((InstallerUiEswt)iInstallerUi).getSecurityIcon - (getDisplay(), aIdentified); + securityIcon = iInstallerUi.getSecurityIcon( + getDisplay(), aIdentified); } if (securityIcon != null) { @@ -654,11 +694,10 @@ gridData.verticalAlignment = SWT.CENTER; button.setLayoutData(gridData); Image securityIcon = null; - if (iInstallerUi instanceof InstallerUiEswt) + if (iInstallerUi != null) { - securityIcon = - ((InstallerUiEswt)iInstallerUi).getSecurityIcon( - getDisplay(), iCertificates != null); + securityIcon = iInstallerUi.getSecurityIcon( + getDisplay(), iCertificates != null); } if (securityIcon != null) { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/org/eclipse/swt/custom/ScrolledComposite.java --- a/javamanager/javainstaller/installerui/javasrc/org/eclipse/swt/custom/ScrolledComposite.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,764 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.swt.custom; - -import org.eclipse.swt.*; -import org.eclipse.swt.events.*; -import org.eclipse.swt.graphics.*; -import org.eclipse.swt.widgets.*; - -/** - * A ScrolledComposite provides scrollbars and will scroll its content when the user - * uses the scrollbars. - * - * - *

There are two ways to use the ScrolledComposite: - * - *

- * 1) Set the size of the control that is being scrolled and the ScrolledComposite - * will show scrollbars when the contained control can not be fully seen. - * - * 2) The second way imitates the way a browser would work. Set the minimum size of - * the control and the ScrolledComposite will show scroll bars if the visible area is - * less than the minimum size of the control and it will expand the size of the control - * if the visible area is greater than the minimum size. This requires invoking - * both setMinWidth(), setMinHeight() and setExpandHorizontal(), setExpandVertical(). - * - *

- * public static void main (String [] args) {
- *      Display display = new Display ();
- *      Color red = display.getSystemColor(SWT.COLOR_RED);
- *      Color blue = display.getSystemColor(SWT.COLOR_BLUE);
- *      Shell shell = new Shell (display);
- *      shell.setLayout(new FillLayout());
- *
- *      // set the size of the scrolled content - method 1
- *      final ScrolledComposite sc1 = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- *      final Composite c1 = new Composite(sc1, SWT.NONE);
- *      sc1.setContent(c1);
- *      c1.setBackground(red);
- *      GridLayout layout = new GridLayout();
- *      layout.numColumns = 4;
- *      c1.setLayout(layout);
- *      Button b1 = new Button (c1, SWT.PUSH);
- *      b1.setText("first button");
- *      c1.setSize(c1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- *
- *      // set the minimum width and height of the scrolled content - method 2
- *      final ScrolledComposite sc2 = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- *      sc2.setExpandHorizontal(true);
- *      sc2.setExpandVertical(true);
- *      final Composite c2 = new Composite(sc2, SWT.NONE);
- *      sc2.setContent(c2);
- *      c2.setBackground(blue);
- *      layout = new GridLayout();
- *      layout.numColumns = 4;
- *      c2.setLayout(layout);
- *      Button b2 = new Button (c2, SWT.PUSH);
- *      b2.setText("first button");
- *      sc2.setMinSize(c2.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- *
- *      Button add = new Button (shell, SWT.PUSH);
- *      add.setText("add children");
- *      final int[] index = new int[]{0};
- *      add.addListener(SWT.Selection, new Listener() {
- *          public void handleEvent(Event e) {
- *              index[0]++;
- *              Button button = new Button(c1, SWT.PUSH);
- *              button.setText("button "+index[0]);
- *              // reset size of content so children can be seen - method 1
- *              c1.setSize(c1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- *              c1.layout();
- *
- *              button = new Button(c2, SWT.PUSH);
- *              button.setText("button "+index[0]);
- *              // reset the minimum width and height so children can be seen - method 2
- *              sc2.setMinSize(c2.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- *              c2.layout();
- *          }
- *      });
- *
- *      shell.open ();
- *      while (!shell.isDisposed ()) {
- *          if (!display.readAndDispatch ()) display.sleep ();
- *      }
- *      display.dispose ();
- * }
- * 
- * - *
- *
Styles:
H_SCROLL, V_SCROLL - *
- * - * @see ScrolledComposite snippets - * @see Sample code and further information - */ -public class ScrolledComposite extends Composite -{ - - Control content; - Listener contentListener; - Listener filter; - - int minHeight = 0; - int minWidth = 0; - boolean expandHorizontal = false; - boolean expandVertical = false; - boolean alwaysShowScroll = false; - boolean showFocusedControl = false; - - /** - * Constructs a new instance of this class given its parent - * and a style value describing its behavior and appearance. - *

- * The style value is either one of the style constants defined in - * class SWT which is applicable to instances of this - * class, or must be built by bitwise OR'ing together - * (that is, using the int "|" operator) two or more - * of those SWT style constants. The class description - * lists the style constants that are applicable to the class. - * Style bits are also inherited from superclasses. - *

- * - * @param parent a widget which will be the parent of the new instance (cannot be null) - * @param style the style of widget to construct - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the parent is null
  • - *
- * @exception SWTException
    - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent
  • - *
- * - * @see SWT#H_SCROLL - * @see SWT#V_SCROLL - * @see #getStyle() - */ - public ScrolledComposite(Composite parent, int style) - { - super(parent, checkStyle(style)); - super.setLayout(new ScrolledCompositeLayout()); - ScrollBar hBar = getHorizontalBar(); - if (hBar != null) - { - hBar.setVisible(false); - hBar.addListener(SWT.Selection, new Listener() - { - public void handleEvent(Event e) - { - hScroll(); - } - }); - } - - ScrollBar vBar = getVerticalBar(); - if (vBar != null) - { - vBar.setVisible(false); - vBar.addListener(SWT.Selection, new Listener() - { - public void handleEvent(Event e) - { - vScroll(); - } - }); - } - - contentListener = new Listener() - { - public void handleEvent(Event e) - { - if (e.type != SWT.Resize) return; - layout(false); - } - }; - - filter = new Listener() - { - public void handleEvent(Event event) - { - if (event.widget instanceof Control) - { - Control control = (Control) event.widget; - if (contains(control)) showControl(control); - } - } - }; - - addDisposeListener(new DisposeListener() - { - public void widgetDisposed(DisposeEvent e) - { - getDisplay().removeFilter(SWT.FocusIn, filter); - } - }); - } - - static int checkStyle(int style) - { - int mask = SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; - return style & mask; - } - - boolean contains(Control control) - { - if (control == null || control.isDisposed()) return false; - - Composite parent = control.getParent(); - while (parent != null && !(parent instanceof Shell)) - { - if (this == parent) return true; - parent = parent.getParent(); - } - return false; - } - - /** - * Returns the Always Show Scrollbars flag. True if the scrollbars are - * always shown even if they are not required. False if the scrollbars are only - * visible when some part of the composite needs to be scrolled to be seen. - * The H_SCROLL and V_SCROLL style bits are also required to enable scrollbars in the - * horizontal and vertical directions. - * - * @return the Always Show Scrollbars flag value - */ - public boolean getAlwaysShowScrollBars() - { - //checkWidget(); - return alwaysShowScroll; - } - - /** - * Returns true if the content control - * will be expanded to fill available horizontal space. - * - * @return the receiver's horizontal expansion state - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.2 - */ - public boolean getExpandHorizontal() - { - checkWidget(); - return expandHorizontal; - } - - /** - * Returns true if the content control - * will be expanded to fill available vertical space. - * - * @return the receiver's vertical expansion state - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.2 - */ - public boolean getExpandVertical() - { - checkWidget(); - return expandVertical; - } - - /** - * Returns the minimum width of the content control. - * - * @return the minimum width - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.2 - */ - public int getMinWidth() - { - checkWidget(); - return minWidth; - } - - /** - * Returns the minimum height of the content control. - * - * @return the minimum height - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.2 - */ - public int getMinHeight() - { - checkWidget(); - return minHeight; - } - - /** - * Get the content that is being scrolled. - * - * @return the control displayed in the content area - */ - public Control getContent() - { - //checkWidget(); - return content; - } - - /** - * Returns true if the receiver automatically scrolls to a focused child control - * to make it visible. Otherwise, returns false. - * - * @return a boolean indicating whether focused child controls are automatically scrolled into the viewport - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.4 - */ - public boolean getShowFocusedControl() - { - checkWidget(); - return showFocusedControl; - } - - void hScroll() - { - if (content == null) return; - Point location = content.getLocation(); - ScrollBar hBar = getHorizontalBar(); - int hSelection = hBar.getSelection(); - content.setLocation(-hSelection, location.y); - } - boolean needHScroll(Rectangle contentRect, boolean vVisible) - { - ScrollBar hBar = getHorizontalBar(); - if (hBar == null) return false; - - Rectangle hostRect = getBounds(); - int border = getBorderWidth(); - hostRect.width -= 2*border; - ScrollBar vBar = getVerticalBar(); - if (vVisible && vBar != null) hostRect.width -= vBar.getSize().x; - - if (!expandHorizontal && contentRect.width > hostRect.width) return true; - if (expandHorizontal && minWidth > hostRect.width) return true; - return false; - } - - boolean needVScroll(Rectangle contentRect, boolean hVisible) - { - ScrollBar vBar = getVerticalBar(); - if (vBar == null) return false; - - Rectangle hostRect = getBounds(); - int border = getBorderWidth(); - hostRect.height -= 2*border; - ScrollBar hBar = getHorizontalBar(); - if (hVisible && hBar != null) hostRect.height -= hBar.getSize().y; - - if (!expandVertical && contentRect.height > hostRect.height) return true; - if (expandVertical && minHeight > hostRect.height) return true; - return false; - } - - /** - * Return the point in the content that currently appears in the top left - * corner of the scrolled composite. - * - * @return the point in the content that currently appears in the top left - * corner of the scrolled composite. If no content has been set, this returns - * (0, 0). - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 2.0 - */ - public Point getOrigin() - { - checkWidget(); - if (content == null) return new Point(0, 0); - Point location = content.getLocation(); - return new Point(-location.x, -location.y); - } - /** - * Scrolls the content so that the specified point in the content is in the top - * left corner. If no content has been set, nothing will occur. - * - * Negative values will be ignored. Values greater than the maximum scroll - * distance will result in scrolling to the end of the scrollbar. - * - * @param origin the point on the content to appear in the top left corner - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
  • ERROR_INVALID_ARGUMENT - value of origin is outside of content - *
- * @since 2.0 - */ - public void setOrigin(Point origin) - { - setOrigin(origin.x, origin.y); - } - /** - * Scrolls the content so that the specified point in the content is in the top - * left corner. If no content has been set, nothing will occur. - * - * Negative values will be ignored. Values greater than the maximum scroll - * distance will result in scrolling to the end of the scrollbar. - * - * @param x the x coordinate of the content to appear in the top left corner - * - * @param y the y coordinate of the content to appear in the top left corner - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 2.0 - */ - public void setOrigin(int x, int y) - { - checkWidget(); - if (content == null) return; - ScrollBar hBar = getHorizontalBar(); - if (hBar != null) - { - hBar.setSelection(x); - x = -hBar.getSelection(); - } - else - { - x = 0; - } - ScrollBar vBar = getVerticalBar(); - if (vBar != null) - { - vBar.setSelection(y); - y = -vBar.getSelection(); - } - else - { - y = 0; - } - content.setLocation(x, y); - } - /** - * Set the Always Show Scrollbars flag. True if the scrollbars are - * always shown even if they are not required. False if the scrollbars are only - * visible when some part of the composite needs to be scrolled to be seen. - * The H_SCROLL and V_SCROLL style bits are also required to enable scrollbars in the - * horizontal and vertical directions. - * - * @param show true to show the scrollbars even when not required, false to show scrollbars only when required - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setAlwaysShowScrollBars(boolean show) - { - checkWidget(); - if (show == alwaysShowScroll) return; - alwaysShowScroll = show; - ScrollBar hBar = getHorizontalBar(); - if (hBar != null && alwaysShowScroll) hBar.setVisible(true); - ScrollBar vBar = getVerticalBar(); - if (vBar != null && alwaysShowScroll) vBar.setVisible(true); - layout(false); - } - - /** - * Set the content that will be scrolled. - * - * @param content the control to be displayed in the content area - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setContent(Control content) - { - checkWidget(); - if (this.content != null && !this.content.isDisposed()) - { - this.content.removeListener(SWT.Resize, contentListener); - this.content.setBounds(new Rectangle(-200, -200, 0, 0)); - } - - this.content = content; - ScrollBar vBar = getVerticalBar(); - ScrollBar hBar = getHorizontalBar(); - if (this.content != null) - { - if (vBar != null) - { - vBar.setMaximum(0); - vBar.setThumb(0); - vBar.setSelection(0); - } - if (hBar != null) - { - hBar.setMaximum(0); - hBar.setThumb(0); - hBar.setSelection(0); - } - content.setLocation(0, 0); - layout(false); - this.content.addListener(SWT.Resize, contentListener); - } - else - { - if (hBar != null) hBar.setVisible(alwaysShowScroll); - if (vBar != null) vBar.setVisible(alwaysShowScroll); - } - } - /** - * Configure the ScrolledComposite to resize the content object to be as wide as the - * ScrolledComposite when the width of the ScrolledComposite is greater than the - * minimum width specified in setMinWidth. If the ScrolledComposite is less than the - * minimum width, the content will not be resized and instead the horizontal scroll bar will be - * used to view the entire width. - * If expand is false, this behaviour is turned off. By default, this behaviour is turned off. - * - * @param expand true to expand the content control to fill available horizontal space - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setExpandHorizontal(boolean expand) - { - checkWidget(); - if (expand == expandHorizontal) return; - expandHorizontal = expand; - layout(false); - } - /** - * Configure the ScrolledComposite to resize the content object to be as tall as the - * ScrolledComposite when the height of the ScrolledComposite is greater than the - * minimum height specified in setMinHeight. If the ScrolledComposite is less than the - * minimum height, the content will not be resized and instead the vertical scroll bar will be - * used to view the entire height. - * If expand is false, this behaviour is turned off. By default, this behaviour is turned off. - * - * @param expand true to expand the content control to fill available vertical space - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setExpandVertical(boolean expand) - { - checkWidget(); - if (expand == expandVertical) return; - expandVertical = expand; - layout(false); - } - /** - * Sets the layout which is associated with the receiver to be - * the argument which may be null. - *

- * Note: No Layout can be set on this Control because it already - * manages the size and position of its children. - *

- * - * @param layout the receiver's new layout or null - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setLayout(Layout layout) - { - checkWidget(); - return; - } - /** - * Specify the minimum height at which the ScrolledComposite will begin scrolling the - * content with the vertical scroll bar. This value is only relevant if - * setExpandVertical(true) has been set. - * - * @param height the minimum height or 0 for default height - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setMinHeight(int height) - { - setMinSize(minWidth, height); - } - /** - * Specify the minimum width and height at which the ScrolledComposite will begin scrolling the - * content with the horizontal scroll bar. This value is only relevant if - * setExpandHorizontal(true) and setExpandVertical(true) have been set. - * - * @param size the minimum size or null for the default size - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setMinSize(Point size) - { - if (size == null) - { - setMinSize(0, 0); - } - else - { - setMinSize(size.x, size.y); - } - } - /** - * Specify the minimum width and height at which the ScrolledComposite will begin scrolling the - * content with the horizontal scroll bar. This value is only relevant if - * setExpandHorizontal(true) and setExpandVertical(true) have been set. - * - * @param width the minimum width or 0 for default width - * @param height the minimum height or 0 for default height - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setMinSize(int width, int height) - { - checkWidget(); - if (width == minWidth && height == minHeight) return; - minWidth = Math.max(0, width); - minHeight = Math.max(0, height); - layout(false); - } - /** - * Specify the minimum width at which the ScrolledComposite will begin scrolling the - * content with the horizontal scroll bar. This value is only relevant if - * setExpandHorizontal(true) has been set. - * - * @param width the minimum width or 0 for default width - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- */ - public void setMinWidth(int width) - { - setMinSize(width, minHeight); - } - - /** - * Configure the receiver to automatically scroll to a focused child control - * to make it visible. - * - * If show is false, show a focused control is off. - * By default, show a focused control is off. - * - * @param show true to show a focused control. - * - * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.4 - */ - public void setShowFocusedControl(boolean show) - { - checkWidget(); - if (showFocusedControl == show) return; - Display display = getDisplay(); - display.removeFilter(SWT.FocusIn, filter); - showFocusedControl = show; - if (!showFocusedControl) return; - display.addFilter(SWT.FocusIn, filter); - Control control = display.getFocusControl(); - if (contains(control)) showControl(control); - } - - /** - * Scrolls the content of the receiver so that the control is visible. - * - * @param control the control to be shown - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the control is null
  • - *
  • ERROR_INVALID_ARGUMENT - if the control has been disposed
  • - *
- * @exception SWTException
    - *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • - *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • - *
- * - * @since 3.4 - */ - public void showControl(Control control) - { - checkWidget(); - if (control == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (control.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (!contains(control)) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - - Rectangle itemRect = getDisplay().map(control.getParent(), this, control.getBounds()); - Rectangle area = getClientArea(); - Point origin = getOrigin(); - if (itemRect.x < 0) - { - origin.x = Math.max(0, origin.x + itemRect.x); - } - else - { - if (area.width < itemRect.x + itemRect.width) origin.x = Math.max(0, origin.x + itemRect.x + Math.min(itemRect.width, area.width) - area.width); - } - if (itemRect.y < 0) - { - origin.y = Math.max(0, origin.y + itemRect.y); - } - else - { - if (area.height < itemRect.y + itemRect.height) origin.y = Math.max(0, origin.y + itemRect.y + Math.min(itemRect.height, area.height) - area.height); - } - setOrigin(origin); - } - - void vScroll() - { - if (content == null) return; - Point location = content.getLocation(); - ScrollBar vBar = getVerticalBar(); - int vSelection = vBar.getSelection(); - content.setLocation(location.x, -vSelection); - } -} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javainstaller/installerui/javasrc/org/eclipse/swt/custom/ScrolledCompositeLayout.java --- a/javamanager/javainstaller/installerui/javasrc/org/eclipse/swt/custom/ScrolledCompositeLayout.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.swt.custom; - -import org.eclipse.swt.*; -import org.eclipse.swt.graphics.*; -import org.eclipse.swt.widgets.*; - -/** - * This class provides the layout for ScrolledComposite - * - * @see ScrolledComposite - */ -class ScrolledCompositeLayout extends Layout -{ - - boolean inLayout = false; - static final int DEFAULT_WIDTH = 64; - static final int DEFAULT_HEIGHT = 64; - - protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) - { - ScrolledComposite sc = (ScrolledComposite)composite; - Point size = new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT); - if (sc.content != null) - { - Point preferredSize = sc.content.computeSize(wHint, hHint, flushCache); - Point currentSize = sc.content.getSize(); - size.x = sc.getExpandHorizontal() ? preferredSize.x : currentSize.x; - size.y = sc.getExpandVertical() ? preferredSize.y : currentSize.y; - } - size.x = Math.max(size.x, sc.minWidth); - size.y = Math.max(size.y, sc.minHeight); - if (wHint != SWT.DEFAULT) size.x = wHint; - if (hHint != SWT.DEFAULT) size.y = hHint; - return size; - } - - protected boolean flushCache(Control control) - { - return true; - } - - protected void layout(Composite composite, boolean flushCache) - { - if (inLayout) return; - ScrolledComposite sc = (ScrolledComposite)composite; - if (sc.content == null) return; - ScrollBar hBar = sc.getHorizontalBar(); - ScrollBar vBar = sc.getVerticalBar(); - if (hBar != null) - { - if (hBar.getSize().y >= sc.getSize().y) - { - return; - } - } - if (vBar != null) - { - if (vBar.getSize().x >= sc.getSize().x) - { - return; - } - } - inLayout = true; - Rectangle contentRect = sc.content.getBounds(); - if (!sc.alwaysShowScroll) - { - boolean hVisible = sc.needHScroll(contentRect, false); - boolean vVisible = sc.needVScroll(contentRect, hVisible); - if (!hVisible && vVisible) hVisible = sc.needHScroll(contentRect, vVisible); - if (hBar != null) hBar.setVisible(hVisible); - if (vBar != null) vBar.setVisible(vVisible); - } - Rectangle hostRect = sc.getClientArea(); - if (sc.expandHorizontal) - { - contentRect.width = Math.max(sc.minWidth, hostRect.width); - } - if (sc.expandVertical) - { - contentRect.height = Math.max(sc.minHeight, hostRect.height); - } - - if (hBar != null) - { - hBar.setMaximum(contentRect.width); - hBar.setThumb(Math.min(contentRect.width, hostRect.width)); - int hPage = contentRect.width - hostRect.width; - int hSelection = hBar.getSelection(); - if (hSelection >= hPage) - { - if (hPage <= 0) - { - hSelection = 0; - hBar.setSelection(0); - } - contentRect.x = -hSelection; - } - } - - if (vBar != null) - { - vBar.setMaximum(contentRect.height); - vBar.setThumb(Math.min(contentRect.height, hostRect.height)); - int vPage = contentRect.height - hostRect.height; - int vSelection = vBar.getSelection(); - if (vSelection >= vPage) - { - if (vPage <= 0) - { - vSelection = 0; - vBar.setSelection(0); - } - contentRect.y = -vSelection; - } - } - - sc.content.setBounds(contentRect); - inLayout = false; - } -} diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/client/src/javaregistry.cpp --- a/javamanager/javaregistry/client/src/javaregistry.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/client/src/javaregistry.cpp Fri May 14 15:47:24 2010 +0300 @@ -35,7 +35,6 @@ EXPORT_C CJavaRegistry* CJavaRegistry::NewL() { JELOG2(EJavaStorage); - LOG(EJavaStorage, EInfo, "CJavaRegistry::NewL"); CJavaRegistry* self = CJavaRegistry::NewLC(); CleanupStack::Pop(self); @@ -49,7 +48,6 @@ EXPORT_C CJavaRegistry* CJavaRegistry::NewLC() { JELOG2(EJavaStorage); - LOG(EJavaStorage, EInfo, "CJavaRegistry::NewLC"); CJavaRegistry* self = new(ELeave) CJavaRegistry(); CleanupStack::PushL(self); @@ -96,7 +94,7 @@ JELOG2(EJavaStorage); if (0 == aUid.iUid) { - WLOG(EJavaStorage, + ILOG(EJavaStorage, "Can't find entry for uid 0, returning NULL."); return NULL; } @@ -106,7 +104,7 @@ if (writableEntry == NULL) { - WLOG(EJavaStorage, + ILOG(EJavaStorage, "Can't find entry for the given uid, returning NULL."); return NULL; } @@ -124,7 +122,7 @@ regEntry = new(ELeave) CJavaRegistryPackageEntry(writablePackageEntry); // pointer ownership passed over - LOG(EJavaStorage, EInfo, "PackageEntry created"); + ILOG(EJavaStorage, "PackageEntry created"); } else if (EGeneralApplication <= entryType) { @@ -134,7 +132,7 @@ regEntry = new(ELeave) CJavaRegistryApplicationEntry(writableAppEntry); // pointer ownership passed over - LOG(EJavaStorage, EInfo, "ApplicationEntry created"); + ILOG(EJavaStorage, "ApplicationEntry created"); } else { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/client/src/javaregistrypackageentry.cpp --- a/javamanager/javaregistry/client/src/javaregistrypackageentry.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/client/src/javaregistrypackageentry.cpp Fri May 14 15:47:24 2010 +0300 @@ -103,7 +103,7 @@ if (writeableEntry == NULL) { - WLOG(EJavaStorage, + ILOG(EJavaStorage, "Can't find entry for the given uid, returning NULL."); return NULL; } @@ -119,14 +119,14 @@ entry = new(ELeave) CJavaRegistryPackageEntry( (CWriteableJavaRegistryPackageEntry*) writeableEntry); - LOG(EJavaStorage, EInfo, "PackageEntry created"); + ILOG(EJavaStorage, "PackageEntry created"); } else if (EGeneralApplication <= entryType) { entry = new(ELeave) CJavaRegistryApplicationEntry ((CWriteableJavaRegistryApplicationEntry*) writeableEntry); - LOG(EJavaStorage, EInfo, "ApplicationEntry created"); + ILOG(EJavaStorage, "ApplicationEntry created"); } else { @@ -167,14 +167,14 @@ entry = new(ELeave) CJavaRegistryPackageEntry( (CWriteableJavaRegistryPackageEntry*) writeableEntry); - LOG(EJavaStorage, EInfo, "PackageEntry created"); + ILOG(EJavaStorage, "PackageEntry created"); } else if (EGeneralApplication <= entryType) { entry = new(ELeave) CJavaRegistryApplicationEntry ((CWriteableJavaRegistryApplicationEntry*) writeableEntry); - LOG(EJavaStorage, EInfo, "ApplicationEntry created"); + ILOG(EJavaStorage, "ApplicationEntry created"); } else { diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/client/src/writeablejavaregistryentry.cpp --- a/javamanager/javaregistry/client/src/writeablejavaregistryentry.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/client/src/writeablejavaregistryentry.cpp Fri May 14 15:47:24 2010 +0300 @@ -517,7 +517,7 @@ { if ((*iter).size() > 0) { - string decoded = JavaCommonUtils::base64decode((*iter)); + string decoded = (*iter); HBufC8* decodedBuf = HBufC8::New(decoded.size()); TPtr8 decodedBufPtr(decodedBuf->Des()); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/legacy/server/inc/javaregconverter.h --- a/javamanager/javaregistry/legacy/server/inc/javaregconverter.h Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/legacy/server/inc/javaregconverter.h Fri May 14 15:47:24 2010 +0300 @@ -209,7 +209,7 @@ * @param aCertChains [out] The method converts the unicode descriptors * into this RPointerArray. */ - static void JavaRegConverter::GetUnicodeDescriptorsL( + static void GetUnicodeDescriptorsL( const TDesC& aValue, RPointerArray& aDescriptors); /** @@ -224,7 +224,7 @@ * @param aDes [out] Descriptor parameter, storing, and the returning * the certificate chains. */ - static void JavaRegConverter::StoreUnicodeDescriptorsL( + static void StoreUnicodeDescriptorsL( const RPointerArray& aValue, HBufC*& aDes); }; diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/legacy/server/inc/javaregserver.h --- a/javamanager/javaregistry/legacy/server/inc/javaregserver.h Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/legacy/server/inc/javaregserver.h Fri May 14 15:47:24 2010 +0300 @@ -95,7 +95,7 @@ * @param aUid uid of the required entry * @param[out] aProperties entry are read in this parameter */ - void CJavaRegServer::GetEntryL( + void GetEntryL( TUid aUid, CJavaPropertyArray*& aProperties, TBool aAllEntries = EFalse); diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/legacy/server/src/javaregconverter.cpp --- a/javamanager/javaregistry/legacy/server/src/javaregconverter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/legacy/server/src/javaregconverter.cpp Fri May 14 15:47:24 2010 +0300 @@ -21,6 +21,7 @@ #include #include "javaregconverter.h" #include "javaregproperty.h" +#include "javasymbianoslayer.h" #include "logger.h" using namespace Java::Manager::Registry; @@ -262,6 +263,7 @@ const TDesC& aValue, RPointerArray& aDescriptors) { + CleanupResetAndDestroyPushL(aDescriptors); // If method leaves this will clean leaked memory TInt32 count; HBufC8* buf = HBufC8::NewLC(aValue.Length()); @@ -283,6 +285,7 @@ CleanupStack::PopAndDestroy(&stream); CleanupStack::PopAndDestroy(buf); + CleanupStack::Pop(&aDescriptors); } // --------------------------------------------------------------------------- diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javaregistry/legacy/server/src/javaregstore.cpp --- a/javamanager/javaregistry/legacy/server/src/javaregstore.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javaregistry/legacy/server/src/javaregstore.cpp Fri May 14 15:47:24 2010 +0300 @@ -17,7 +17,7 @@ #include - +#include #include "driveutilities.h" #include "javaattributes.h" #include "javacommonutils.h" diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javasettings/appmngrplugin/inc/appmngr2midletsettingscontainer.h --- a/javamanager/javasettings/appmngrplugin/inc/appmngr2midletsettingscontainer.h Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javasettings/appmngrplugin/inc/appmngr2midletsettingscontainer.h Fri May 14 15:47:24 2010 +0300 @@ -44,8 +44,7 @@ /** * C++ constructor. */ - CAppMngr2MidletSettingsContainer::CAppMngr2MidletSettingsContainer( - CAppMngr2MidletSettingsView& aView); + CAppMngr2MidletSettingsContainer(CAppMngr2MidletSettingsView& aView); /** * EPOC default constructor. diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javasettings/appmngrplugin/src/appmngr2midletruntime.cpp --- a/javamanager/javasettings/appmngrplugin/src/appmngr2midletruntime.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javasettings/appmngrplugin/src/appmngr2midletruntime.cpp Fri May 14 15:47:24 2010 +0300 @@ -205,7 +205,7 @@ //CleanupStack::PushL(entry); // Entry ownership is taken. - TRAP_IGNORE(GetInstalledAppL(aApps, aFsSession, entry)); + GetInstalledAppL(aApps, aFsSession, entry); //CleanupStack::Pop(aEntry); } diff -r 2a9601315dfc -r 98ccebc37403 javamanager/javasettings/appsettingsview_qt/src/javaapplicationsettingsview_p.cpp --- a/javamanager/javasettings/appsettingsview_qt/src/javaapplicationsettingsview_p.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javamanager/javasettings/appsettingsview_qt/src/javaapplicationsettingsview_p.cpp Fri May 14 15:47:24 2010 +0300 @@ -446,7 +446,8 @@ == HbDataFormModelItem::ComboBoxItem) { HbComboBox * comboBox = static_cast( - mainForm->dataFormViewItem(dataItemIndex)->dataItemContentWidget()); + (qobject_cast + (mainForm->itemByIndex(dataItemIndex)))->dataItemContentWidget()); // add the extra settings values for (int i=0; idataFormViewItem( - model->indexFromItem(item)); + + HbDataFormViewItem * viewItem = qobject_cast (mainForm->itemByIndex( + model->indexFromItem(item))); if (viewItem) { return static_cast(viewItem->dataItemContentWidget()); diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/installer/starterdll/src/main.cpp --- a/javaruntimes/installer/starterdll/src/main.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/installer/starterdll/src/main.cpp Fri May 14 15:47:24 2010 +0300 @@ -361,10 +361,21 @@ } #ifdef RD_JAVA_INSTALLERUI_ENABLED +#if 0 // Disable 10.1 JavaInstallerUi +//#ifdef RD_JAVA_S60_RELEASE_10_1_ONWARDS + jvm->appendSystemProperty( + L"-Dcom.nokia.mj.impl.installer.ui=" + L"com.nokia.mj.impl.installer.ui.eswt2.InstallerUiEswt"); + // Replace RuntimeUi with installer specific implementation. + jvm->appendSystemProperty( + L"-Dcom.nokia.mj.impl.rt.ui=" + L"com.nokia.mj.impl.installer.ui.eswt2.InstallerRuntimeUi"); +#else jvm->appendSystemProperty( L"-Dcom.nokia.mj.impl.installer.ui=" L"com.nokia.mj.impl.installer.ui.eswt.InstallerUiEswt"); -#endif +#endif // RD_JAVA_S60_RELEASE_10_1_ONWARDS +#endif // RD_JAVA_INSTALLERUI_ENABLED std::wstring extendedBootClassPath; // This call is platform dependent. diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationInfoImpl.java --- a/javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationInfoImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationInfoImpl.java Fri May 14 15:47:24 2010 +0300 @@ -23,11 +23,8 @@ import com.nokia.mj.impl.rt.support.ApplicationInfo; /** - * A Main runtime specific implemetation of ApplicationInfo class of the + * A Main runtime specific implementation of ApplicationInfo class of the * runtime support API. - * - * @author Nokia Corporation - * @version $Rev$ */ public class ApplicationInfoImpl extends ApplicationInfo diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationUtilsImpl.java --- a/javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationUtilsImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc.cdc/com/nokia/mj/impl/rt/main/ApplicationUtilsImpl.java Fri May 14 15:47:24 2010 +0300 @@ -29,11 +29,8 @@ /** - * A Main runtime specific implemetation of ApplicationUtils class of the + * A Main runtime specific implementation of ApplicationUtils class of the * runtime support API. - * - * @author Nokia Corporation - * @version $Rev$ */ public class ApplicationUtilsImpl extends ApplicationUtils diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationInfoImpl.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationInfoImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationInfoImpl.java Fri May 14 15:47:24 2010 +0300 @@ -21,11 +21,8 @@ import com.nokia.mj.impl.rt.support.ApplicationInfo; /** - * A MIDP runtime specific implemetation of ApplicationInfo class of the + * A MIDP runtime specific implementation of ApplicationInfo class of the * runtime support API. - * - * @author Nokia Corporation - * @version $Rev$ */ public class ApplicationInfoImpl extends ApplicationInfo diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationUtilsImpl.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationUtilsImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/ApplicationUtilsImpl.java Fri May 14 15:47:24 2010 +0300 @@ -29,11 +29,8 @@ /** - * A MIDP runtime specific implemetation of ApplicationUtils class of the + * A MIDP runtime specific implementation of ApplicationUtils class of the * runtime support API. - * - * @author Nokia Corporation - * @version $Rev$ */ public class ApplicationUtilsImpl extends ApplicationUtils @@ -49,7 +46,14 @@ */ public static void doShutdownImpl() { - ((ApplicationUtilsImpl)sInstance).doShutdown(); + try + { + ((ApplicationUtilsImpl)sInstance).doShutdown(); + } + catch (Throwable t) + { + Log.logE("Error in doShutdownImpl: " , t); + } } public static void setStandAloneMode() diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/DrmUtil.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/DrmUtil.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/DrmUtil.java Fri May 14 15:47:24 2010 +0300 @@ -18,10 +18,7 @@ package com.nokia.mj.impl.rt.midp; /** - * A utility class for consuming DTM rights. - * - * @author Nokia Corporation - * @version $Rev$ + * A utility class for consuming DRM rights. */ final class DrmUtil { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/LifeCycleTask.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/LifeCycleTask.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/LifeCycleTask.java Fri May 14 15:47:24 2010 +0300 @@ -23,9 +23,6 @@ /** * A class to be used to state change request to the state machine of the * MIDP runtime life cycle. - * - * @author Nokia Corporation - * @version $Rev$ */ class LifeCycleTask extends Task diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Log.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Log.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Log.java Fri May 14 15:47:24 2010 +0300 @@ -21,9 +21,6 @@ /** * A utility class for logging. - * - * @author Nokia Corporation - * @version $Rev$ */ @@ -41,7 +38,7 @@ */ public static void logI(String msg) { - Logger.ILOG(COMPONENT_ID, msg); + Logger.ILOG(COMPONENT_ID, Thread.currentThread().getName() + ": " +msg); } /** diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Main.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Main.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/Main.java Fri May 14 15:47:24 2010 +0300 @@ -24,9 +24,6 @@ /** * A Main entry class of the MIDP runtime. - * - * @author Nokia Corporation - * @version $Rev$ */ public final class Main { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MainArgs.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MainArgs.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MainArgs.java Fri May 14 15:47:24 2010 +0300 @@ -25,9 +25,6 @@ * MIDP runtime. It is assumed that the arguments are provided so that * there is always a key starting with '-' available and after that the * value. Keys without value are not supported. - * - * @author Nokia Corporation - * @version $Rev$ */ public final class MainArgs { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MemoryLogger.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MemoryLogger.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MemoryLogger.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * A class for storing the heap usage to a file after fixed time period. - * - * @author Nokia Corporation - * @version $Rev$ */ public class MemoryLogger extends Thread { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletApplicationBase.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletApplicationBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletApplicationBase.java Fri May 14 15:47:24 2010 +0300 @@ -44,9 +44,6 @@ * MIDlet instance. During the construction of this class it will give a * reference to this to the MIDP life cycle, which will store the refernce in * order to delegate calls to MIDlet. - * - * @author Nokia Corporation - * @version $Rev$ */ public abstract class MidletApplicationBase { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletInfo.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletInfo.java Fri May 14 15:47:24 2010 +0300 @@ -28,9 +28,6 @@ * A class for caching important MIDlet specific data. This data * is used mostly to serve the ApplicationInfo APIs, but to some extent * this data is used by the life cycle. - * - * @author Nokia Corporation - * @version $Rev$ */ final class MidletInfo { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletLifeCycle.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletLifeCycle.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidletLifeCycle.java Fri May 14 15:47:24 2010 +0300 @@ -80,9 +80,6 @@ * that will fail if any of the started Java threads dont stop as a result of * shut down notifications. That is considered a failure in the shut down phase * and the Java Captain will terminate forcefully the process. - * - * @author Nokia Corporation - * @version $Rev$ */ final class MidletLifeCycle { @@ -100,8 +97,7 @@ private static final int RESUMING = 0x100; /** - * A singleton instance of the life cycle. It is singleton for provoding - * easy access to all other classes of the MIDP runtime. + * A singleton instance of the life cycle. */ private static MidletLifeCycle mInstance = new MidletLifeCycle(); @@ -251,11 +247,6 @@ { mRuntimeErrDialog.showDialog(); } - if (Log.mOn) Log.logI("Sending close indication to runtime starter."); - _closeInd(mNativeRuntimeStarterHandle); - - if (Log.mOn) Log.logI("Sending shutdown notifications to listeners."); - ApplicationUtilsImpl.doShutdownImpl(); if (!mStandAlone) { @@ -267,7 +258,14 @@ mMidpcomms = null; } - if (Log.mOn) Log.logI("Short pause before closing dispatchers."); + if (Log.mOn) Log.logI("Sending shutdown notifications to listeners."); + ApplicationUtilsImpl.doShutdownImpl(); + + if (Log.mOn) Log.logI("Sending close indication to runtime starter."); + _closeInd(mNativeRuntimeStarterHandle); + + + if (Log.mOn) Log.logI("Short pause before closing LegacySupport."); try { Thread.sleep(200); @@ -276,7 +274,7 @@ { } - if (Log.mOn) Log.logI("Closing dispatchers."); + if (Log.mOn) Log.logI("Closing LegacySupport."); LegacySupport.close(); // Setting state to closed. @@ -602,7 +600,7 @@ /** * Handles the start request task. Allowed to be called only from * startStateMachine() method. The only intention of this method is - * to diminish the switch case clause in the diminish startStateMachine() + * to diminish the switch case clause in the startStateMachine() * method. * @param subTask The sub task provided by the task setter. */ @@ -610,8 +608,8 @@ { if (Log.mOn) Log.logI("MidletLifeCycle.handleStartRequest(), subTask: " + subTask); - if (mState == POST_INIT_DONE || (mState == PRE_INIT_DONE && - subTask == LifeCycleTask.PRE_WARM_START)) + if ((mState == POST_INIT_DONE && subTask != LifeCycleTask.PRE_WARM_START) || + (mState == PRE_INIT_DONE && subTask == LifeCycleTask.PRE_WARM_START)) { if (subTask == LifeCycleTask.NORMAL_START) { @@ -781,6 +779,10 @@ // Check if there are add-on JSRs. ExtensionUtil.handleExtensions(); } + else + { + ApplicationUtilsImpl.setStandAloneMode(); + } mTaskQueue = new TaskQueue(); @@ -919,10 +921,6 @@ _setUids(mMidletUid.toString(), ApplicationInfoImpl.getMidletInfo().getSuiteUid().toString(), mNativeRuntimeStarterHandle); - // The Jvm doesn't know about MIDlet class path - need to set it. - String classPath = ApplicationInfoImpl.getMidletInfo().getClassPath(); - if (Log.mOn) Log.logI(" Adding to classpath: "+classPath); - JvmInternal.appendToClassPath(classPath); } private void doPostInit() @@ -946,6 +944,11 @@ // API works ok, the setMidletInfo must be called before // starting the UI. CoreUi.createUi(mMidletUid, mBackGroundStart); + + // The Jvm doesn't know about MIDlet class path - need to set it. + String classPath = ApplicationInfoImpl.getMidletInfo().getClassPath(); + if (Log.mOn) Log.logI(" Adding to classpath: "+classPath); + JvmInternal.appendToClassPath(classPath); } if (!mStandAlone) { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidpComms.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidpComms.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/MidpComms.java Fri May 14 15:47:24 2010 +0300 @@ -27,9 +27,6 @@ /** * A class for Comms connection towards Java Captain. This class is used to * send and receive messages to/from Java Captain. - * - * @author Nokia Corporation - * @version $Rev$ */ final class MidpComms implements CommsListener diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/RuntimeErrorDialog.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/RuntimeErrorDialog.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/RuntimeErrorDialog.java Fri May 14 15:47:24 2010 +0300 @@ -40,9 +40,6 @@ * that may be shown in the error cases: Some thread doesn't catch exception, * application start up fails by throwing some exception or DRM rights has been * expired. - * - * @author Nokia Corporation - * @version $Rev$ */ final class RuntimeErrorDialog extends ErrorMessageBase diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/SaMidletInfoProvider.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/SaMidletInfoProvider.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/SaMidletInfoProvider.java Fri May 14 15:47:24 2010 +0300 @@ -36,9 +36,6 @@ /** * A utility class for reading the standalone MIDlet specfic data from Jar and * Jad file (if Jad provided). - * - * @author Nokia Corporation - * @version $Rev$ */ final class SaMidletInfoProvider { @@ -91,7 +88,6 @@ try { InputStream is = midletInfo.getClass().getResourceAsStream("/META-INF/MANIFEST.MF"); - Log.logE("MIKKO is = " + is); jarAttributes = ManifestReader.getAttributes(is); is.close(); is = null; diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StartupException.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StartupException.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StartupException.java Fri May 14 15:47:24 2010 +0300 @@ -25,9 +25,6 @@ * an error or the MIDlet start up denied by the user (e.g. auto invocation). * If it is denied by the user, then this exception is not considered as an * error. - * - * @author Nokia Corporation - * @version $Rev$ */ final class StartupException extends RuntimeException { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StorageAccessor.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StorageAccessor.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/midp/StorageAccessor.java Fri May 14 15:47:24 2010 +0300 @@ -34,9 +34,6 @@ * created in setMidletStartArguments() is reused in setMidletAttributes() * method and then closed. If this scenario changes, then the close must * be done also in setMidletStartArguments() method. - * - * @author Nokia Corporation - * @version $Rev$ */ final class StorageAccessor { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/utils/ExtensionUtil.java --- a/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/utils/ExtensionUtil.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/com/nokia/mj/impl/rt/utils/ExtensionUtil.java Fri May 14 15:47:24 2010 +0300 @@ -55,9 +55,6 @@ * The J9 JVM is not able to read the system properties from the odc * file added to boot classpath. This class provides utility for reading * the system properties from the odc files. - * - * @author Nokia Corporation - * @version $Rev$ */ public final class ExtensionUtil diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDlet.java --- a/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDlet.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDlet.java Fri May 14 15:47:24 2010 +0300 @@ -36,9 +36,6 @@ /** * A class to be extended by the MIDlet applcation. See MIDP spec for * further details. - * - * @author Nokia Corporation - * @version $Rev$ */ public abstract class MIDlet { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDletStateChangeException.java --- a/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDletStateChangeException.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MIDletStateChangeException.java Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,6 @@ * An exception for the MIDlet to inform that it doesn't want to do the state * change requested by the life cycle. * @see MIDP spec for further details. - * - * @author Nokia Corporation - * @version $Rev$ */ public class MIDletStateChangeException extends Exception { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MidletApplication.java --- a/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MidletApplication.java Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/javasrc/javax/microedition/midlet/MidletApplication.java Fri May 14 15:47:24 2010 +0300 @@ -24,8 +24,6 @@ * A package private class in javax.microedition.midlet package for * accessing protected abstract methods of MIDlet class. * @see com.nokia.mj.impl.rt.midp.MidletApplicationBase. - * @author Nokia Corporation - * @version $Rev$ */ final class MidletApplication extends MidletApplicationBase { diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtime/src.s60/platformrequesthandler.cpp --- a/javaruntimes/midp/runtime/src.s60/platformrequesthandler.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtime/src.s60/platformrequesthandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -17,7 +17,13 @@ #include -#include // SchemeHandler + +#ifdef RD_JAVA_S60_RELEASE_10_1_ONWARDS +#include +#else +#include +#endif + #include // for RApaLsSession #include #include diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtimestarter/src.linux/dummy.txt diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtimestarter/src.s60/dummy.txt diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtimestarter/src/midpruntimestarter.cpp --- a/javaruntimes/midp/runtimestarter/src/midpruntimestarter.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtimestarter/src/midpruntimestarter.cpp Fri May 14 15:47:24 2010 +0300 @@ -23,6 +23,10 @@ #include #include +#ifndef __SYMBIAN32__ +#include +#endif // __SYMBIAN32__ + #include "midpruntimestarter.h" #include "applicationinfosetter.h" #include "runtimeexception.h" @@ -59,7 +63,7 @@ MidpRuntimeStarter::MidpRuntimeStarter(): mMidletInfo(new MidletInfo()), // codescanner::nonleavenew - mRuntimeState(Constructed) + mRuntimeState(Constructed), mShudownOk(false) { JELOG2(EJavaRuntime); } @@ -236,6 +240,14 @@ } CoreUi::releaseUi(coreUiLoader); + // Close the thread that ensures the exit. + if (mExitMonitor.get()) + { + mShudownOk = true; + LOG(EJavaRuntime, EInfo, "Notifying exit thread."); + mExitMonitor->notify(); + } + return status; } @@ -489,14 +501,47 @@ } } + +void* MidpRuntimeStarter::ensureExit(void* ptr) +{ + JELOG2(EUtils); +#ifdef __SYMBIAN32__ + RThread().SetPriority(EPriorityMore); +#endif // __SYMBIAN32__ + MidpRuntimeStarter* starter = reinterpret_cast(ptr); + LOG(EJavaRuntime, EInfo, "Starting to wait for the shutdown."); + const int waitTime = 1000; // 1 second. + starter->mExitMonitor->wait(waitTime); + LOG(EJavaRuntime, EInfo, "woke up from monitor."); + if (!starter->mShudownOk) + { + LOG(EJavaRuntime, EInfo, "Killing process."); +#ifdef __SYMBIAN32__ + RProcess().Kill(0); +#else + kill(getpid(), SIGTERM); +#endif // __SYMBIAN32__ + } + LOG(EJavaRuntime, EInfo, "Clean exit."); + return 0; +} + void MidpRuntimeStarter::closeRuntimeInd() { JELOG2(EJavaRuntime); LOG(EJavaRuntime, EInfo, "Starter got close indication from JVM"); + + // Create a thread for ensure the exit of the process, if something goes + // wrong. + pthread_t tid; + mExitMonitor.reset(Monitor::createMonitor()); + pthread_create(&tid, 0, ensureExit, this); + if (mMidletInfo->mPushStart) { closePush(); } + } void MidpRuntimeStarter::setUids(const Uid& midletUid, const Uid& midletSuiteUid) diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/midp/runtimestarter/src/midpruntimestarter.h --- a/javaruntimes/midp/runtimestarter/src/midpruntimestarter.h Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/midp/runtimestarter/src/midpruntimestarter.h Fri May 14 15:47:24 2010 +0300 @@ -280,6 +280,13 @@ private: // Methods /** + * A thread entry point for a thread that ensure that the runtime process + * will be exited if something goes wrong in shutdown sequence. + * @param ptr A pointer to MidpRuntimeStarter. + */ + static void* ensureExit(void* ptr); + + /** * Parses the arguments provided by Java Captain when creating the * process. The argument interpretations are stored into a member variable * mMidletInfo for easy future access. Any Unknown argument @@ -445,6 +452,11 @@ std::auto_ptr mMonitor; /** + * A lock for exit case. + */ + std::auto_ptr mExitMonitor; + + /** * A library loader for push case. */ std::auto_ptr mPushLib; @@ -454,6 +466,11 @@ */ std::wstring mPushAdditionalInfo; + /** + * Did the shutdown go ok. + */ + bool mShudownOk; + }; } // end namespace runtime diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/standalone/src/javastarterimpl.cpp --- a/javaruntimes/standalone/src/javastarterimpl.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/standalone/src/javastarterimpl.cpp Fri May 14 15:47:24 2010 +0300 @@ -233,7 +233,7 @@ #ifndef RD_JAVA_UI_QT // In Java 2.x we are using legacy UI. - mJvmStarter->appendSystemProperty(L"-Dcom.nokia.legacy.support=symbian"); + mJvmStarter->appendSystemProperty(L"-Dcom.nokia.legacy.support=LegacySymbian"); #endif //RD_JAVA_HYBRID int result = mJvmStarter->startJvm(); @@ -460,11 +460,6 @@ #ifdef __SYMBIAN32__ TUidToUid(RProcess().Type()[2], mAppUid); LOG1(EJavaRuntime, EInfo, "PROCESS UID %S", mAppUid.toString().c_str()); - -// TUid tuid = uidType[1]; - TUid tuid(TUid::Uid(0x10005902)); -// TUidToUid(tuid, mAppUid); -// LOG1(EJavaRuntime, EInfo, "TEMP UID %S", mAppUid.toString().c_str()); #else // __SYMBIAN32__ // mAppUid = Uid(L"java_standalone"); diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/standalone/tsrc/build/javatest.pro --- a/javaruntimes/standalone/tsrc/build/javatest.pro Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/standalone/tsrc/build/javatest.pro Fri May 14 15:47:24 2010 +0300 @@ -15,7 +15,7 @@ # TEMPLATE=app -TARGET=javastandalone +TARGET=javatest CONFIG += omj no_icon stl CONFIG -= qt diff -r 2a9601315dfc -r 98ccebc37403 javaruntimes/starterutils/src.s60/j9starters60.cpp --- a/javaruntimes/starterutils/src.s60/j9starters60.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javaruntimes/starterutils/src.s60/j9starters60.cpp Fri May 14 15:47:24 2010 +0300 @@ -192,7 +192,6 @@ mJvmArgs.push_back(stackSizeStr); } -// #define RD_JAVA_VM_EXT_ODC_FEATURE_IN_USE void J9StarterS60::setInternalOdcFiles() { JELOG2(EJavaRuntime); diff -r 2a9601315dfc -r 98ccebc37403 javatools/javasecuritycustomization/policyeditor/lib/readme.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javatools/javasecuritycustomization/policyeditor/lib/readme.txt Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,4 @@ +Policyeditor is a tool for customizing jrt security policy. The tool needs some classes from jrt binaries. +The required classes are generated when compiling jrt/javacommons/security component. +This folder is the placeholder for the required jrt classes. + \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_akn/build/build.xml --- a/javauis/amms_akn/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/amms_akn/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -52,6 +52,10 @@ com.nokia.amms.ModuleBase"/> + + + + audio.samplerates=8000 16000 diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_akn/src_tuner/javasrc/com/symbian/midp/runtime/properties/Property_tuner_modulations.java --- a/javauis/amms_akn/src_tuner/javasrc/com/symbian/midp/runtime/properties/Property_tuner_modulations.java Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,29 +0,0 @@ -/* -* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: Implements tuner.modulations property -* -*/ - -package com.symbian.midp.runtime.properties; - -import com.symbian.midp.runtime.PropertyHandler; - -public final class Property_tuner_modulations - implements PropertyHandler -{ - public String getProperty() - { - return "fm"; - } -} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammsaudio3dcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammsaudio3dcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for 3D audio controls +* +*/ + + +#ifndef CAMMSAUDIO3DCONTROLGROUP_H +#define CAMMSAUDIO3DCONTROLGROUP_H + +// INCLUDES +#include +#include "cammscontrolgroup.h" + +// CLASS DECLARATION + +/** + * Group for 3D audio controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSAudio3DControlGroup): public CAMMSControlGroup +{ +public: // Constructors and destructor + + /** + * Destructor. + */ + ~CAMMSAudio3DControlGroup(); + +protected: // New functions + + /** + * Update the controls depending on commit mode + * + * @param aCommit variable id that need to be commited + */ + void UpdateL(TInt aCommit); + + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + virtual void CommitL(TInt aCommit) = 0; + +public: // From MAMMSControlGroup + /** + * Sets the mode of the CommitControl. + * + * @param aMode commit mode + */ + void SetModeL(TCommitMode aMode); + + /** + * Commit all the controls in the group + * in immediate mode commits, in deferred mode marks what variables + * need to be commited later + */ + void CommitGroupL(); + +protected: + /** + * Constructor. + * + * @param aName The name of the corresponding amms control + * @param aControlType Special AMMS type of the Control + */ + CAMMSAudio3DControlGroup( + const TDesC& aName, + TAMMSControlTypes aControlType = EAMMSBaseControl); + + /** + * Symbian 2nd phase constructor. + */ + void ConstructL(); + +protected: // Data + + // Commit mode + TCommitMode iCommitMode; + +private: // Data + + // bit field of variables that have to be commited + // (used in CommitL()) + TInt iCommit; +}; + +#endif // CAMMSAUDIO3DCONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammscommitcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammscommitcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,107 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for commit controls +* +*/ + + +#ifndef CAMMSCOMMITCONTROLGROUP_H +#define CAMMSCOMMITCONTROLGROUP_H + +// INCLUDES +#include +#include "cammsaudio3dcontrolgroup.h" +#include "cammsmodulecontainer.h" +#include "cammsmodule.h" + +// FORWARD DECLARATIONS +class CAMMSModule; + +// CONSTANTS +_LIT(KAMMSCommitControlClassName, ".amms.control.audio3d.CommitControl"); +_LIT(KAMMSCommitControl, "CommitControl"); + +// CLASS DECLARATION +/** + * Group for commit controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSCommitControlGroup): public CAMMSAudio3DControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSCommitControlGroup* NewLC( + CAMMSModule& aSpectator, + CAMMSModuleContainer& aSoundSource3Ds); + + /** + * Destructor. + */ + ~CAMMSCommitControlGroup(); + +public: // New functions + + /** + * Transfers all the pending parameters to the audio processing system + * for all ControlGroups in this controllable + */ + void CommitAllControlsL(); + + /** + * Sets the mode of the CommitControl + * + * @param aDeferred deferred mode flag + */ + void SetDeferredL(TBool aDeferred); + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + void CommitL(TInt aCommit); + +private: + /** + * C++ default constructor. + */ + CAMMSCommitControlGroup( + CAMMSModule& aSpectator, + CAMMSModuleContainer& aSoundSource3Ds); + +private: // Data + // Reference to spectator, owned by GlobalManager + CAMMSModule& iSpectator; + + // Reference to sound source 3Ds, owned by GlobalManager + CAMMSModuleContainer& iSoundSource3Ds; + +}; + +#endif // CAMMSCOMMITCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammsdistanceattenuationcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammsdistanceattenuationcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,162 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for distance attenuation controls +* +*/ + + +#ifndef CAMMSDISTANCEATTENUATIONCONTROLGROUP_H +#define CAMMSDISTANCEATTENUATIONCONTROLGROUP_H + +// INCLUDES +#include +#include "cammsaudio3dcontrolgroup.h" + +// CONSTANTS +_LIT(KAMMSDistanceAttenuationClassName, + ".amms.control.audio3d.DistanceAttenuationControl"); + +// FORWARD DECLARATIONS +class CAMMSBaseDistanceAttenuationControl; + +// CLASS DECLARATION +/** + * Group for distance attenuation controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSDistanceAttenuationControlGroup): public CAMMSAudio3DControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSDistanceAttenuationControlGroup* NewLC(); + + /** + * Destructor. + */ + ~CAMMSDistanceAttenuationControlGroup(); + +public: // New functions + + /** + * Returns the maximum distance. At the maximum distance, the gain does + * not decrease any more. The exact behavior of the gain at distances + * beyond the maximum distance depends on the value of muteAfterMax + * + * @return the maximum distance + */ + TInt32 MaxDistance() const; + + /** + * Returns the distance where the source is loudest. + * + * @return the minimum distance + */ + TInt32 MinDistance() const; + + /** + * Returns how the distance gain behaves for distances beyond the + * maximum distance. + * + * @return true if beyond the maximum distance the source is silent, + * or false if beyond the maximum distance the source's gain is held + * constant at the level at the maximum distance + */ + TBool MuteAfterMax() const; + + /** + * Returns the rolloff factor for the distance gain. + * + * @return the rolloff factor as an exponent specified in thousandths + */ + TUint32 RolloffFactor() const; + + /** + * Sets all the 3D audio distance attenuation parameters simultaneously + * + * @param aMinDistance the minimum distance, below which the + * distance gain is clipped to its maximum + * value of 1.0 + * @param aMaxDistance the maximum distance, beyond which the + * distance gain does not decrease any more + * @param aMuteAfterMax a boolean determining how the distance + * gain behaves at distances greater than + * maxDistance + * @param aRolloffFactor the rolloff factor + */ + void SetParametersL(TInt32 aMinDistance, TInt32 aMaxDistance, + TBool aMuteAfterMax, TUint32 aRolloffFactor); + +private: // New functions + /** + * Gets and casts a control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSBaseDistanceAttenuationControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + virtual void CommitL(TInt aCommit); + + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer* aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSDistanceAttenuationControlGroup(); + +private: // Data + + class TVariables + { + public: + + TInt32 iMinDistance; + TInt32 iMaxDistance; + TBool iMuteAfterMax; + TUint32 iRolloffFactor; + }; + + TVariables iCommited; // holder for variables after commit + TVariables iUncommited; // holder for variables before commit + + enum TCommit { EDistance = 1 }; +}; + +#endif // CAMMSDISTANCEATTENUATIONCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammsdopplercontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammsdopplercontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,157 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for Doppler controls +* +*/ + + +#ifndef CAMMSDOPPLERCONTROLGROUP_H +#define CAMMSDOPPLERCONTROLGROUP_H + +// INCLUDES +#include +#include "cammsaudio3dcontrolgroup.h" +#include "ammsconstants.h" + +// FORWARD DECLARATIONS +class CAMMSDopplerControl; + +// CONSTANTS +_LIT(KAMMSDopplerControl, "DopplerControl"); +_LIT(KAMMSDopplerControlClassName, ".amms.control.audio3d.DopplerControl"); + +// CLASS DECLARATION +/** + * Group for Doppler controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSDopplerControlGroup): public CAMMSAudio3DControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSDopplerControlGroup* NewLC( + TAMMSControlTypes aControlType); + + /** + * Destructor. + */ + ~CAMMSDopplerControlGroup(); + +public: // New functions + /** + * Returns the current velocity, used in calculations for the Doppler + * effect + * + * @param aVelocity the current velocity + */ + void VelocityCartesianL(TInt aVelocity[ KAMMSVectorComponents ]); + + /** + * Returns whether this Doppler effect is currently active. + * + * @return the enabled state of the control + */ + TBool Enabled(); + + /** + * Specifies if this Doppler effect is active or ignored. + * + * @param aEnabled new enabled state + */ + void SetEnabledL(TBool aEnabled); + + /** + * Sets the velocity, used in calculations for the Doppler effect. + * + * @param aX the x component of the new velocity + * @param aY the y component of the new velocity + * @param aZ the z component of the new velocity + */ + void SetVelocityCartesianL(TInt aX, TInt aY, TInt aZ); + + /** + * Sets the velocity, used in calculations for the Doppler effect. + * + * @param aAzimuth the azimuth angle of the new velocity in degrees + * @param aElevation the elevation angle of the new velocity in degrees + * @param aRadius the magnitude of the new velocity + */ + void SetVelocitySphericalL(TInt aAzimuth, TInt aElevation, TInt aRadius); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSDopplerControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + virtual void CommitL(TInt aCommit); + + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSDopplerControlGroup(TAMMSControlTypes aControlType); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + class TVariables + { + public: + + TInt iVelocity[ KAMMSVectorComponents ]; + TBool iEnabled; + }; + + TVariables iCommited; // holder for variables after commit + TVariables iUncommited; // holder for variables before commit + + enum TCommit { EEnabled = 1, EVelocity = 2 }; +}; + +#endif // CAMMSDOPPLERCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammslocationcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammslocationcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,136 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for location controls +* +*/ + + +#ifndef CAMMSLOCATIONCONTROLGROUP_H +#define CAMMSLOCATIONCONTROLGROUP_H + +// INCLUDES +#include +#include "cammsaudio3dcontrolgroup.h" +#include "ammsconstants.h" + +// CONSTANTS +_LIT(KAMMSLocationControl, "LocationControl"); +_LIT(KAMMSLocationControlClassName, ".amms.control.audio3d.LocationControl"); + +// FORWARD DECLARATIONS +class CAMMSLocationControl; + +// CLASS DECLARATION +/** + * Group for location controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSLocationControlGroup): public CAMMSAudio3DControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSLocationControlGroup* NewLC( + TAMMSControlTypes aControlType); + + /** + * Destructor. + */ + ~CAMMSLocationControlGroup(); + +public: // New functions + /** + * Gets the coordinates of the current location + * + * @param aLocation the current location + */ + void CartesianL(TInt aLocation[ KAMMSVectorComponents ]); + + /** + * Moves the object to the new location + * + * @param aX the x component of the new location + * @param aY the y component of the new location + * @param aZ the z component of the new location + */ + void SetCartesianL(TInt aX, TInt aY, TInt aZ); + + /** + * Moves the object to the new location + * + * @param aAzimuth the azimuth angle of the new location in degrees + * @param aElevation the elevation angle of the new location in degrees + * @param aRadius the magnitude of the new location + */ + void SetSphericalL(TInt aAzimuth, TInt aElevation, TInt aRadius); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSLocationControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + virtual void CommitL(TInt aCommit); + + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSLocationControlGroup(TAMMSControlTypes aControlType); + +private: // Data + + class TVariables + { + public: + + TInt iLocation[ KAMMSVectorComponents ]; + }; + + TVariables iCommited; // holder for variables after commit + TVariables iUncommited; // holder for variables before commit + + enum TCommit { ELocation = 1 }; +}; + +#endif // CAMMSLOCATIONCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/inc/cammsorientationcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/inc/cammsorientationcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,237 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for orientation controls +* +*/ + + +#ifndef CAMMSORIENTATIONCONTROLGROUP_H +#define CAMMSORIENTATIONCONTROLGROUP_H + +// INCLUDES +#include +#include "cammsaudio3dcontrolgroup.h" +#include "ammsconstants.h" + +// CONSTANTS +_LIT(KAMMSOrientationControlClassName, + ".amms.control.audio3d.OrientationControl"); + +// FORWARD DECLARATIONS +class CAMMSOrientationControl; + + +// CLASS DECLARATION +/** + * Group for location controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSOrientationControlGroup): public CAMMSAudio3DControlGroup +{ +private: + + class TVariables + { + public: + + TInt iOrientation[ KAMMSTwoVectorComponents ]; + TBool iOrientationVector; + }; + +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSOrientationControlGroup* NewLC(); + + /** + * Destructor. + */ + ~CAMMSOrientationControlGroup(); + +public: // New functions + /** + * Gets the orientation of the object using two vectors. + * + * Sets the location using cartesian right-handed coordinates that are + * relative to the origin. The measures are defined in units specified + * by GlobalManager.getUnitsPerMeter(). + * Referenced memory of the arguments will contain the coordinate values. + * + * @param aOrientation the current orientation + */ + void OrientationVectorsL(TInt aOrientation[ KAMMSTwoVectorComponents ]); + + /** + * Turns the object to the new orientation. + * + * The new orientation is given using rotation angles. A zero vector + * corresponds to the orientation pointing directly towards the negative + * Z-axis. Orientation is applied in the following order: heading, + * pitch, and roll. Therefore, notice that heading turns the X-axis and + * therefore affects the pitch, and similarly heading and pitch turn the + * Z-axis and therefore affect the roll. + * + * @param aHeading The rotation around the Y-axis in degrees. + * @param aPitch The rotation around the X-axis in degrees. + * @param aRoll The rotation around the Z-axis in degrees. + */ + void SetOrientationL(TInt aHeading, TInt aPitch, TInt aRoll); + + /** + * Turns the object to the new orientation. + * + * The orientation is specified using two vectors, one specifying the + * direction of the front vector of the object in world coordinates, and + * another specifying the "above" vector of the object. The right and up + * vectors of the object are calculated by first normalizing both source + * vectors, then calculating the right vector as the cross product of the + * "above" vector and the front vector, and the up vector as a cross + * product of the front and right vectors. + * + * Because both vectors are normalized, they may be of any length. + * + * @param aFrontVector X, Y and Z value of Front vector + * @param aAboveVector X, Y and Z value of Above vector + * + * @par Leaving: + * @li \c KErrArgument - In case any of the parameters is a zero vector + * or they are parallel to each other or any of the parameters' lenghts + * is not three. In that case, the orientation of the object remains + * unchanged. + */ + void SetOrientationVectorsL( + TInt aFrontVector[ KAMMSVectorComponents ], + TInt aAboveVector[ KAMMSVectorComponents ]); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSOrientationControl* TypeSafeControl(TInt aIndex) const; + + /** + * Creates "up" vector by applying cross product operation to + * "front" and "above" vectors. + * + * @param aVariables Used orientation parameters. + * @param aUpVector Returned "up" vector. + */ + static void GetUpVectorL(TVariables& aVariables, + TInt aUpVector[ KAMMSVectorComponents ]); + + /** + * Converts orientation from vectors to angles. + * + * NOTE: THIS FUNCTION SHOULD BE REMOVED WHEN EFFECT API FIX IS AVAILABLE! + * (it is possible to set an orientation as vectors). + * + * @param aVariables Used orientation parameters. + * @param aSphericalOrientation Result vector. + */ + static void ConvertOrientationToAnglesL( + TVariables& aVariables, + TInt aSphericalOrientation[ KAMMSVectorComponents ]); + + /** + * Calculates how much the given vector should be rotated around the + * given rotation vector so that the value of the specified vector + * component is maximized. + * + * NOTE: THIS FUNCTION SHOULD BE REMOVED WHEN EFFECT API FIX IS AVAILABLE! + * + * @param aVector Vector thats components are investigated. + * @param aRotationAxelVector Vector for the rotation axel. + * @param aMaximizeComponent Index of the vector component to be + * maximized. + * @return An angle that the vector should be rotated. + */ + static TReal CalculatePartialRotationL( + TReal aVector[ KAMMSVectorComponents ], + TReal aRotationAxelVector[ KAMMSVectorComponents ], + TInt aMaximizeComponent); + + /** + * Checks whether two given vectors are similar according to the given + * maximum error percentage. The function compares each component in + * aA to the corresponding component in aB. + * + * NOTE: THIS FUNCTION SHOULD BE REMOVED WHEN EFFECT API FIX IS AVAILABLE! + * + * @param aA A vector + * @param aB A vector + * @param aMaxComponentErrorPercentage Maximum error percentage between + * a component in aA and the corresponding component in aB + * @return ETrue if difference between each component pair is lower + * than the given error, else ETrue is returned + */ + static TBool AreVectorsSimilar(TReal aA[ KAMMSVectorComponents ], + TReal aB[ KAMMSVectorComponents ], + TInt aMaxComponentErrorPercentage); + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Transfers all the pending parameters to the audio processing system. + * + * @param aCommit variable id that need to be commited + */ + virtual void CommitL(TInt aCommit); + + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer* aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSOrientationControlGroup(); + +private: // Data + + enum TOrientationIndex { EFrontX = 0, + EFrontY = 1, + EFrontZ = 2, + EAboveX = 3, + EAboveY = 4, + EAboveZ = 5, + EHeading = 0, + EPitch = 1, + ERoll = 2 }; + + TVariables iCommited; // holder for variables after commit + TVariables iUncommited; // holder for variables before commit + + enum TCommit { EOrientation = 1 }; +}; + +#endif // CAMMSORIENTATIONCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammsaudio3dcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammsaudio3dcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,109 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for 3D audio controls +* +*/ + + +// INCLUDE FILES +#include "cammsaudio3dcontrolgroup.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSAudio3DControlGroup::~CAMMSAudio3DControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudio3DControlGroup::UpdateL +// Update the controls depending on commit mode +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudio3DControlGroup::UpdateL(TInt aCommit) +{ + // Add new variables that have to be committed to member variable. + iCommit |= aCommit; + + if (iCommitMode == EImmediate) + { + // Commit new values, and remove them from the member variable. + CommitL(aCommit); + iCommit &= ~aCommit; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudio3DControlGroup::SetModeL +// Sets the mode of the CommitControl. +// Can be called only from CAMMSCommitControlGroup +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudio3DControlGroup::SetModeL(TCommitMode aMode) +{ + // When switching back from the deferred mode to the immediate mode + // (setDeferred(false)) all the pending parameters from the buffer are + // transmitted to the audio processing system automatically. + if (aMode == EImmediate) + { + CommitL(iCommit); + iCommit = 0; + } + iCommitMode = aMode; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudio3DControlGroup::CommitGroupL +// Commits all the controls in the group +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudio3DControlGroup::CommitGroupL() +{ + // In case the mode is changed to EImmediate in the middle of commit process, + // SetModeL method is implemented so that it takes care of all pending + // parameter committing. + if (iCommitMode == EDeferred) + { + CommitL(iCommit); + iCommit = 0; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudio3DControlGroup::CAMMSAudio3DControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSAudio3DControlGroup::CAMMSAudio3DControlGroup( + const TDesC& aName, + TAMMSControlTypes aControlType) : + CAMMSControlGroup(aName, aControlType) +{ + // default values + iCommitMode = EImmediate; + iCommit = 0; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudio3DControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSAudio3DControlGroup::ConstructL() +{ + CAMMSControlGroup::ConstructL(); +} + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammscommitcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammscommitcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for commit controls +* +*/ + + +// INCLUDE FILES + +#include +#include "cammscommitcontrolgroup.h" +#include "cammsmodule.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSCommitControlGroup* CAMMSCommitControlGroup::NewLC( + CAMMSModule& aSpectator, + CAMMSModuleContainer& aSoundSource3Ds) +{ + CAMMSCommitControlGroup* self = new(ELeave) CAMMSCommitControlGroup( + aSpectator, + aSoundSource3Ds); + + CleanupStack::PushL(self); + // calls base class ConstructL + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSCommitControlGroup::~CAMMSCommitControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::CommitAllControlsL +// Transfers all the pending parameters to the audio processing system +// for all ControlGroups in this controllable +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSCommitControlGroup::CommitAllControlsL() +{ + TInt groupAmount = 0; + + // Go through every module in SoundSource3D + TInt moduleAmount = iSoundSource3Ds.Count(); + for (TInt i = 0; i < moduleAmount; i++) + { + CAMMSModule* module = iSoundSource3Ds.At(i); + + // Go through every ControlGroup in Module + groupAmount = module->Count(); + for (TInt j = 0; j < groupAmount; j++) + { + MAMMSControlGroup* group = module->At(j); + group->CommitGroupL(); + } + } + + // And finally go through every ControlGroup in Spectator + groupAmount = iSpectator.Count(); + for (TInt i = 0; i < groupAmount; i++) + { + MAMMSControlGroup* group = iSpectator.At(i); + group->CommitGroupL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::SetDeferredL +// Sets the mode of the CommitControl +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSCommitControlGroup::SetDeferredL(TBool aDeferred) +{ + TInt groupAmount = 0; + TCommitMode mode = (aDeferred ? EDeferred : EImmediate); + + // Go through every module in SoundSource3D + TInt moduleAmount = iSoundSource3Ds.Count(); + for (TInt i = 0; i < moduleAmount; i++) + { + CAMMSModule* module = iSoundSource3Ds.At(i); + + // Go through every ControlGroup in Module + groupAmount = module->Count(); + for (TInt j = 0; j < groupAmount; j++) + { + MAMMSControlGroup* group = module->At(j); + group->SetModeL(mode); + } + } + + // And finally go through every ControlGroup in Spectator + groupAmount = iSpectator.Count(); + for (TInt i = 0; i < groupAmount; i++) + { + MAMMSControlGroup* group = iSpectator.At(i); + group->SetModeL(mode); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSCommitControlGroup::ClassName() +{ + return KAMMSCommitControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::CommitL +// Transfers all the pending parameters to the audio processing system. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSCommitControlGroup::CommitL(TInt /*aCommit*/) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSCommitControlGroup::CAMMSCommitControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSCommitControlGroup::CAMMSCommitControlGroup( + CAMMSModule& aSpectator, + CAMMSModuleContainer& aSoundSource3Ds): +// CommitControlGroup has no associated amms controls therefore +// the name passed as a parameter to the constructor is KNullDesC +// CHANGED for now, passing actual name here even no associated Controls. + CAMMSAudio3DControlGroup(KAMMSCommitControl), + iSpectator(aSpectator), + iSoundSource3Ds(aSoundSource3Ds) +{ +} + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammsdistanceattenuationcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammsdistanceattenuationcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,193 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for distance attenuation controls +* +*/ + + +// INCLUDE FILES + +#include "cammsdistanceattenuationcontrolgroup.h" +#include "cammsbasedistanceattenuationcontrol.h" + +// CONSTANTS +static const TInt KAMMSMinDistance = 1000; +static const TInt KAMMSRolloffFactor = 1000; + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSDistanceAttenuationControlGroup* +CAMMSDistanceAttenuationControlGroup::NewLC() +{ + CAMMSDistanceAttenuationControlGroup* self = + new(ELeave) CAMMSDistanceAttenuationControlGroup; + + CleanupStack::PushL(self); + // calls base class ConstructL + self->ConstructL(); + + return self; +} + +//Destructor +CAMMSDistanceAttenuationControlGroup::~CAMMSDistanceAttenuationControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::MaxDistance +// Returns the maximum distance. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt32 CAMMSDistanceAttenuationControlGroup::MaxDistance() const +{ + return iCommited.iMaxDistance; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::MinDistance +// Returns the distance where the source is loudest. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt32 CAMMSDistanceAttenuationControlGroup::MinDistance() const +{ + return iCommited.iMinDistance; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::MuteAfterMax +// Returns how the distance gain behaves for distances beyond +// the maximum distance. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TBool CAMMSDistanceAttenuationControlGroup::MuteAfterMax() const +{ + return iCommited.iMuteAfterMax; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::RolloffFactor +// Returns the rolloff factor for the distance gain. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TUint32 CAMMSDistanceAttenuationControlGroup::RolloffFactor() const +{ + return iCommited.iRolloffFactor; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::SetParametersL +// Sets all the 3D audio distance attenuation parameters simultaneously +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDistanceAttenuationControlGroup::SetParametersL( + TInt32 aMinDistance, + TInt32 aMaxDistance, + TBool aMuteAfterMax, + TUint32 aRolloffFactor) +{ + // temporary values, moved to the commited variables in CommitL() method + iUncommited.iMinDistance = aMinDistance; + iUncommited.iMaxDistance = aMaxDistance; + iUncommited.iMuteAfterMax = aMuteAfterMax; + iUncommited.iRolloffFactor = aRolloffFactor; + + UpdateL(EDistance); +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::TypeSafeControl +// Get and cast a control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSBaseDistanceAttenuationControl* +CAMMSDistanceAttenuationControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSDistanceAttenuationControlGroup::ClassName() +{ + return KAMMSDistanceAttenuationClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::CommitL +// Transfers all the pending parameters to the audio processing system. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDistanceAttenuationControlGroup::CommitL(TInt aCommit) +{ + if (aCommit & EDistance) + { + TInt controls = ControlCount(); + for (TInt i = 0; i < controls; i++) + { + TypeSafeControl(i)->SetParametersL( + iUncommited.iMinDistance, + iUncommited.iMaxDistance, + iUncommited.iMuteAfterMax, + iUncommited.iRolloffFactor); + } + iCommited = iUncommited; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDistanceAttenuationControlGroup::NotifyPlayerAddedL( + CMMAPlayer* aPlayer, + CMMAControl* aControl) +{ + CAMMSAudio3DControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSBaseDistanceAttenuationControl* control = + static_cast(aControl); + + // set the current parameters + control->SetParametersL( + iCommited.iMinDistance, + iCommited.iMaxDistance, + iCommited.iMuteAfterMax, + iCommited.iRolloffFactor); +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControlGroup::CAMMSDistanceAttenuationControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSDistanceAttenuationControlGroup::CAMMSDistanceAttenuationControlGroup() + : CAMMSAudio3DControlGroup(KAMMSBaseDistanceAttenuationControl) +{ + iCommited.iMinDistance = KAMMSMinDistance; + iCommited.iMaxDistance = KMaxTInt; + iCommited.iMuteAfterMax = ETrue; + iCommited.iRolloffFactor = KAMMSRolloffFactor; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammsdopplercontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammsdopplercontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,237 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for Doppler controls +* +*/ + + +// INCLUDE FILES + +#include "cammsdopplercontrolgroup.h" +#include "cammsdopplercontrol.h" +#include "ammsutil.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSDopplerControlGroup* CAMMSDopplerControlGroup::NewLC( + TAMMSControlTypes aControlType) +{ + CAMMSDopplerControlGroup* self = new(ELeave) CAMMSDopplerControlGroup( + aControlType); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSDopplerControlGroup::~CAMMSDopplerControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::VelocityCartesianL +// Returns the current velocity, used in calculations for the Doppler effect +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::VelocityCartesianL( + TInt aVelocity[ KAMMSVectorComponents ]) +{ + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + aVelocity[ i ] = iCommited.iVelocity[ i ]; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::Enabled +// Returns whether this Doppler effect is currently active. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TBool CAMMSDopplerControlGroup::Enabled() +{ + return iCommited.iEnabled; +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::SetEnabledL +// Specifies if this Doppler effect is active or ignored. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::SetEnabledL(TBool aEnabled) +{ + // If the DopplerControl was fetched from the Spectator, + // this method has no effect. So only disable the value for SoundSource3D. + if (aEnabled || + (!aEnabled && iControlType == EAMMSSoundSource3DControl)) + { + iUncommited.iEnabled = aEnabled; + UpdateL(EEnabled); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::SetVelocityCartesianL +// Sets the velocity, used in calculations for the Doppler effect. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::SetVelocityCartesianL( + TInt aX, + TInt aY, + TInt aZ) +{ + iUncommited.iVelocity[ EComponentX ] = aX; + iUncommited.iVelocity[ EComponentY ] = aY; + iUncommited.iVelocity[ EComponentZ ] = aZ; + + UpdateL(EVelocity); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::SetVelocitySphericalL +// Sets the velocity, used in calculations for the Doppler effect. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::SetVelocitySphericalL( + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + TInt sphericalVector[] = { aAzimuth, aElevation, aRadius }; + + // Convert to cartesian. + AMMSUtil::FromSphericalToCartesianL(sphericalVector, + iUncommited.iVelocity); + + UpdateL(EVelocity); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSDopplerControl* +CAMMSDopplerControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSDopplerControlGroup::ClassName() +{ + return KAMMSDopplerControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::CommitL +// Transfers all the pending parameters to the audio processing system. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::CommitL(TInt aCommit) +{ + TInt controls = ControlCount(); + + // first commit enabled state + if (aCommit & EEnabled) + { + for (TInt i = 0; i < controls; i++) + { + CAMMSDopplerControl* control = TypeSafeControl(i); + control->SetEnabledL(iUncommited.iEnabled); + } + iCommited.iEnabled = iUncommited.iEnabled; + } + + // then commit velocity + if (aCommit & EVelocity) + { + for (TInt i = 0; i < controls; i++) + { + CAMMSDopplerControl* control = TypeSafeControl(i); + + control->SetVelocityCartesianL( + iUncommited.iVelocity[ EComponentX ], + iUncommited.iVelocity[ EComponentY ], + iUncommited.iVelocity[ EComponentZ ]); + } + + // Change uncommited velocity to commited + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + iCommited.iVelocity[ i ] = iUncommited.iVelocity[ i ]; + } + } +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSDopplerControlGroup::NotifyPlayerAddedL( + CMMAPlayer* aPlayer, + CMMAControl* aControl) +{ + CAMMSAudio3DControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSDopplerControl* control = + static_cast(aControl); + + // set the current parameters + + control->SetVelocityCartesianL( + iCommited.iVelocity[ EComponentX ], + iCommited.iVelocity[ EComponentY ], + iCommited.iVelocity[ EComponentZ ]); + + control->SetEnabledL(iCommited.iEnabled); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::CAMMSDopplerControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSDopplerControlGroup::CAMMSDopplerControlGroup( + TAMMSControlTypes aControlType): + CAMMSAudio3DControlGroup(KAMMSDopplerControl, aControlType) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +inline void CAMMSDopplerControlGroup::ConstructL() +{ + CAMMSAudio3DControlGroup::ConstructL(); + + // The default value for Spectator's DopplerControl is true + // (the default value for SoundSource3D's DopplerControl is false) + if (iControlType == EAMMSSpectatorControl) + { + SetEnabledL(ETrue); + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammslocationcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammslocationcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,175 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for location controls +* +*/ + + +// INCLUDE FILES + +#include "cammslocationcontrolgroup.h" +#include "cammslocationcontrol.h" +#include "ammsutil.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSLocationControlGroup* CAMMSLocationControlGroup::NewLC( + TAMMSControlTypes aControlType) +{ + CAMMSLocationControlGroup* self = new(ELeave) CAMMSLocationControlGroup( + aControlType); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; + +} + +// Destructor +CAMMSLocationControlGroup::~CAMMSLocationControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::Cartesian +// Gets the coordinates of the current location +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSLocationControlGroup::CartesianL( + TInt aLocation[ KAMMSVectorComponents ]) +{ + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + aLocation[ i ] = iCommited.iLocation[ i ]; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::SetCartesianL +// Moves the object to the new location +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSLocationControlGroup::SetCartesianL(TInt aX, TInt aY, TInt aZ) +{ + iUncommited.iLocation[ EComponentX ] = aX; + iUncommited.iLocation[ EComponentY ] = aY; + iUncommited.iLocation[ EComponentZ ] = aZ; + + UpdateL(ELocation); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::SetSphericalL +// Moves the object to the new location +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSLocationControlGroup::SetSphericalL( + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + __ASSERT_DEBUG(aRadius >= 0, User::Invariant()); + + TInt sphericalVector[] = { aAzimuth, aElevation, aRadius }; + + // Convert to cartesian. + AMMSUtil::FromSphericalToCartesianL(sphericalVector, + iUncommited.iLocation); + + UpdateL(ELocation); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSLocationControl* +CAMMSLocationControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSLocationControlGroup::ClassName() +{ + return KAMMSLocationControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::CommitL +// Transfers all the pending parameters to the audio processing system. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSLocationControlGroup::CommitL(TInt aCommit) +{ + if (aCommit & ELocation) + { + TInt controls = ControlCount(); + for (TInt i = 0; i < controls; i++) + { + CAMMSLocationControl* control = TypeSafeControl(i); + + control->SetLocationCartesianL( + iUncommited.iLocation[ EComponentX ], + iUncommited.iLocation[ EComponentY ], + iUncommited.iLocation[ EComponentZ ]); + } + + iCommited = iUncommited; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSLocationControlGroup::NotifyPlayerAddedL( + CMMAPlayer* aPlayer, + CMMAControl* aControl) +{ + CAMMSAudio3DControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSLocationControl* control = + static_cast(aControl); + + // set the current parameters + control->SetLocationCartesianL( + iCommited.iLocation[ EComponentX ], + iCommited.iLocation[ EComponentY ], + iCommited.iLocation[ EComponentZ ]); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControlGroup::CAMMSLocationControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSLocationControlGroup::CAMMSLocationControlGroup( + TAMMSControlTypes aControlType): + CAMMSAudio3DControlGroup(KAMMSLocationControl, aControlType) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audio3D/src/cammsorientationcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audio3D/src/cammsorientationcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,600 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for orientation controls +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cammsorientationcontrolgroup.h" +#include "cammsorientationcontrol.h" +#include "ammsutil.h" + + +// CONSTANTS +namespace +{ +// since orientation vectors consist of integers rather than real values, +// normalized vectors have to be multiplied by a large constant to keep +// adequate precision +const TInt KAMMSAxisMultiplier = 1000; + +// Some calculations are done with real values and then rounded to integers. +// Rounding may cause loss of precision. KAMMSMaxOrientationErrorPercentage +// tells how much error (in percentages) is acceptable when rounding values. +const TInt KAMMSMaxOrientationErrorPercentage = 5; +} + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSOrientationControlGroup* CAMMSOrientationControlGroup::NewLC() +{ + CAMMSOrientationControlGroup* self = + new(ELeave) CAMMSOrientationControlGroup; + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; + +} + +// Destructor +CAMMSOrientationControlGroup::~CAMMSOrientationControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::OrientationVectorsL +// Gets the orientation of the object using two vectors +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::OrientationVectorsL( + TInt aOrientation[ KAMMSTwoVectorComponents ]) +{ + // If the orientation was set by using "front" and "above" vectors, + // return "front" and "up" vectors. + if (iCommited.iOrientationVector) + { + // Get "up" vector. + TInt upVector[ KAMMSVectorComponents ]; + GetUpVectorL(iCommited, upVector); + + // Return the "front" and "up" vectors. + for (TInt i = 0; i < KAMMSVectorComponents; i ++) + { + aOrientation[ i ] = iCommited.iOrientation[ i ]; + aOrientation[ i + KAMMSVectorComponents ] = upVector[ i ]; + } + } + // If the orientation was set by using angles, convert set angles + // to "front" and "up" vectors. + else + { + // Start rotation from these axis vectors. + TReal xAxisVector[ KAMMSVectorComponents ] = { 1, 0, 0 }; + TReal yAxisVector[ KAMMSVectorComponents ] = { 0, 1, 0 }; + TReal zAxisVector[ KAMMSVectorComponents ] = { 0, 0, 1 }; + + // Result axis vectors after rotation. + TReal xAxisVector2[ KAMMSVectorComponents ]; + TReal yAxisVector2[ KAMMSVectorComponents ]; + TReal zAxisVector2[ KAMMSVectorComponents ]; + + // rotate round y axis + AMMSUtil::RotateVectorL(zAxisVector, yAxisVector, + iCommited.iOrientation[ EHeading ], zAxisVector2); + AMMSUtil::RotateVectorL(xAxisVector, yAxisVector, + iCommited.iOrientation[ EHeading ], xAxisVector2); + + // rotate round x axis + AMMSUtil::RotateVectorL(yAxisVector, xAxisVector2, + iCommited.iOrientation[ EPitch ], yAxisVector2); + AMMSUtil::RotateVectorL(zAxisVector2, xAxisVector2, + iCommited.iOrientation[ EPitch ], zAxisVector); + + // rotate round z axis + AMMSUtil::RotateVectorL(yAxisVector2, zAxisVector, + iCommited.iOrientation[ ERoll ], yAxisVector); + + // round and save "front" vector to the given parameter + TReal roundedValue; + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + User::LeaveIfError(Math::Round(roundedValue, zAxisVector[ i ] * // CSI: 2 Wrong index means implementation error # + KAMMSAxisMultiplier, 0)); + // "front" vector is opposite to z-axis + aOrientation[ i ] = -(TInt)roundedValue; // CSI: 2 Wrong index means implementation error # + } + + // round and save "up" vector to the given parameter + for (TInt e = 0; e < KAMMSVectorComponents; e++) + { + User::LeaveIfError(Math::Round(roundedValue, yAxisVector[ e ] * // CSI: 2 Wrong index means implementation error # + KAMMSAxisMultiplier, 0)); + aOrientation[ e + KAMMSVectorComponents ] = (TInt)roundedValue; // CSI: 2 Wrong index means implementation error # + } + } +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::SetOrientationL +// Turns the object to the new orientation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::SetOrientationL( + TInt aHeading, + TInt aPitch, + TInt aRoll) +{ + iUncommited.iOrientation[ EHeading ] = aHeading; + iUncommited.iOrientation[ EPitch ] = aPitch; + iUncommited.iOrientation[ ERoll ] = aRoll; + iUncommited.iOrientationVector = EFalse; + + UpdateL(EOrientation); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::SetOrientationVectorsL +// Turns the object to the new orientation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::SetOrientationVectorsL( + TInt aFrontVector[ KAMMSVectorComponents ], + TInt aAboveVector[ KAMMSVectorComponents ]) +{ + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + iUncommited.iOrientation[ i ] = aFrontVector[ i ]; + iUncommited.iOrientation[ i + KAMMSVectorComponents ] = + aAboveVector[ i ]; + } + iUncommited.iOrientationVector = ETrue; + + UpdateL(EOrientation); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSOrientationControl* +CAMMSOrientationControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::GetUpVectorL +// Calculates and returns "up" vector by using "front" and "above" vectors. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::GetUpVectorL( + TVariables& aVariables, + TInt aUpVector[ KAMMSVectorComponents ]) +{ + __ASSERT_DEBUG(aVariables.iOrientationVector, User::Invariant()); + + // Calculate first "right" vector and then "up" vector. + // The "right" vector is calculated as cross product of the "front" + // and "above" vectors. + // The "up" vector is calculated as cross product of the "right" + // and "front" vectors. + + TReal frontVector[ KAMMSVectorComponents ] = + { + aVariables.iOrientation[ EFrontX ], + aVariables.iOrientation[ EFrontY ], + aVariables.iOrientation[ EFrontZ ] + }; + + TReal aboveVector[ KAMMSVectorComponents ] = + { + aVariables.iOrientation[ EAboveX ], + aVariables.iOrientation[ EAboveY ], + aVariables.iOrientation[ EAboveZ ] + }; + + TReal rightVector[ KAMMSVectorComponents ]; + + TReal vectorLength = Min(AMMSUtil::VectorLengthL(frontVector), + (TReal)KMaxTInt); + + // Perform cross product with unit vectors. + AMMSUtil::ConvertToUnitVectorL(frontVector); + AMMSUtil::ConvertToUnitVectorL(aboveVector); + + TReal upVector[ KAMMSVectorComponents ]; + + AMMSUtil::CrossProduct(frontVector, aboveVector, rightVector); + AMMSUtil::CrossProduct(rightVector, frontVector, upVector); + + AMMSUtil::ConvertToUnitVectorL(upVector); + + // Multiply the unit vector so that the result "up" vector has the same + // length as the "front" vector. + + AMMSUtil::MultiplyVector(upVector, vectorLength); + + // Round the vector. + AMMSUtil::RoundVectorL(upVector, aUpVector); + + // Check the rounding error. If it is too high, multiply the original + // vector before rounding. + if (!AMMSUtil::AreVectorsSimilar(upVector, + aUpVector, + KAMMSMaxOrientationErrorPercentage)) + { + AMMSUtil::MultiplyVector(upVector, (TReal)KAMMSAxisMultiplier); + + // Accept this multiplied vector only if it can be fit into TInt. + if ((AMMSUtil::MinVectorComponent(upVector) >= KMinTInt) && + (AMMSUtil::MaxVectorComponent(upVector) <= KMaxTInt)) + { + AMMSUtil::RoundVectorL(upVector, aUpVector); + } + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::ConvertOrientationToAnglesL +// Converts orientation from vectors to angles. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::ConvertOrientationToAnglesL( + TVariables& aVariables, + TInt aSphericalOrientation[ KAMMSVectorComponents ]) +{ + // Get vector for y-axis. + TInt temp[ KAMMSVectorComponents ]; + GetUpVectorL(aVariables, temp); + TReal yAxisVector[] = { temp[ EComponentX ], temp[ EComponentY ], + temp[ EComponentZ ] + }; + + AMMSUtil::ConvertToUnitVectorL(yAxisVector); + + + // Get vector for z-axis. + TReal frontVector[] = + { + aVariables.iOrientation[ EFrontX ], + aVariables.iOrientation[ EFrontY ], + aVariables.iOrientation[ EFrontZ ] + }; + + // Z-axis is opposite to the front vector. + AMMSUtil::ConvertToUnitVectorL(frontVector); + TReal zAxisVector[ KAMMSVectorComponents ] = + { + -frontVector[ EFrontX ], + -frontVector[ EFrontY ], + -frontVector[ EFrontZ ] + }; + + + // Calculate orientation vector for the x-axis. + // The vector is calculated as cross product of the y- + // and z-axis vectors. + TReal xAxisVector[ KAMMSVectorComponents ]; + + AMMSUtil::CrossProduct(yAxisVector, zAxisVector, xAxisVector); + AMMSUtil::ConvertToUnitVectorL(xAxisVector); + + + // First rotate the object coordinate axels so that the object y-axel is + // parallel to the global y-axis (this gives us roll and pitch angles). + // Then rotate the object coordinate axels so that x- and z-axels are + // parallel to the global x- and z-axels, respectively (this gives the + // heading). + + + // Calculate how much the axels should be rotated round the z-axis. + TReal rotateRollDeg = CalculatePartialRotationL(yAxisVector, zAxisVector, EComponentY); + + AMMSUtil::RotateVectorL(xAxisVector, zAxisVector, rotateRollDeg, xAxisVector); + AMMSUtil::RotateVectorL(yAxisVector, zAxisVector, rotateRollDeg, yAxisVector); + + + // Calculate how much the axels should be rotated round the x-axis. + TReal rotatePitchDeg = CalculatePartialRotationL(yAxisVector, xAxisVector, EComponentY); + + AMMSUtil::RotateVectorL(yAxisVector, xAxisVector, rotatePitchDeg, yAxisVector); + AMMSUtil::RotateVectorL(zAxisVector, xAxisVector, rotatePitchDeg, zAxisVector); + + // Calculate how much the axels should be rotated round the y-axis. + TReal rotateHeadingDeg = CalculatePartialRotationL(xAxisVector, yAxisVector, EComponentX); + + TReal resultAngles[] = { -rotateHeadingDeg, + -rotatePitchDeg, + -rotateRollDeg + }; + + AMMSUtil::RoundVectorL(resultAngles, aSphericalOrientation); +} + + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::CalculatePartialRotationL +// Calculates how much the given vector should be rotated around the given +// rotation vector so that the value of the specified vector component is +// maximized. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TReal CAMMSOrientationControlGroup::CalculatePartialRotationL( + TReal aVector[ KAMMSVectorComponents ], + TReal aRotationAxelVector[ KAMMSVectorComponents ], + TInt aMaximizeComponent) +{ + __ASSERT_DEBUG((aMaximizeComponent >= EComponentX) && + (aMaximizeComponent <= EComponentZ), + User::Invariant()); + + TReal x = aRotationAxelVector[ EComponentX ]; + TReal y = aRotationAxelVector[ EComponentY ]; + TReal z = aRotationAxelVector[ EComponentZ ]; + + // calculate the length of the axis vector + TReal lengthSquare = x * x + y * y + z * z; + TReal length; + User::LeaveIfError(Math::Sqrt(length, lengthSquare)); + + // check that the vector is long enough + __ASSERT_DEBUG(length > 0, User::Invariant()); + + + // Find out the components that are tried to set 0. + TInt zeroComponents[ KAMMSVectorComponents - 1 ]; + TInt counter = 0; + + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + if (i != aMaximizeComponent) + { + zeroComponents[ counter ] = i; + counter++; + } + } + + // normalize the axis vector + x = x / length; + y = y / length; + z = z / length; + + // calculate some help variables + TReal xx = x * x; + TReal yy = y * y; + TReal zz = z * z; + + TReal x2 = aVector[ EComponentX ]; + TReal y2 = aVector[ EComponentY ]; + TReal z2 = aVector[ EComponentZ ]; + + TReal xx2 = x * x2; + TReal yy2 = y * y2; + TReal zz2 = z * z2; + + TReal xxx2 = xx * x2; + TReal yyy2 = yy * y2; + TReal zzz2 = zz * z2; + + TReal constants[] = + { + xxx2 + x *(yy2 + zz2), + yyy2 + y *(xx2 + zz2), + zzz2 + z *(xx2 + yy2) + }; + + TReal cosMultipliers[] = + { + constants[ EComponentX ] - x2, + constants[ EComponentY ] - y2, + constants[ EComponentZ ] - z2 + }; + + TReal sinMultipliers[] = + { + z * y2 - y * z2, + x * z2 - z * x2, + y * x2 - x * y2 + }; + + // The angles where some component of the vector is zero. + TReal zeroAngles[ 4 ]; // CSI: 47 Two components may have zero points in 4 angles. # + TInt angleCounter = 0; + + // Find rotation angles that makes (at least) one of the vector components + // to be 0 (however, dismiss the component to be maximized). + for (int i = 0; i < KAMMSVectorComponents - 1; i++) + { + TInt componentIndex = zeroComponents[ i ]; + + TReal cosMultiplier = cosMultipliers[ componentIndex ]; + TReal sinMultiplier = sinMultipliers[ componentIndex ]; + + TReal angleDeg = 0; + + // If both multipliers are zero, this vector is parallel or opposite + // to the target vector. Thus, no need to calculate the angle. + if ((cosMultiplier != 0) || + (sinMultiplier != 0)) + { + // Calculate the angle that makes this vector element to be 0. + TReal temp = cosMultiplier * cosMultiplier + + sinMultiplier * sinMultiplier; + + TReal divider = 0; + User::LeaveIfError(Math::Sqrt(divider, temp)); + + TReal arcTan = 0; + User::LeaveIfError( + Math::ATan(arcTan, sinMultiplier, cosMultiplier)); + + TReal arcCos = 0; + User::LeaveIfError(Math::ACos( + arcCos, constants[ i ] / divider)); // CSI: 2 Wrong index means implementation error # + + TReal angleRad = arcCos + arcTan; + + // Save the angle in degrees. + angleDeg = angleRad * 180 / KPi; // CSI: 47 Value 180 means 180 degrees # + } + + zeroAngles[ angleCounter ] = angleDeg; + + zeroAngles[ angleCounter + 1 ] = angleDeg + 180; // CSI: 47 Save also the opposite direction (+ 180 degrees) # + + angleCounter += 2; // CSI: 47 Two angles have been found # + } + + + // Find the angle that gives the maximum value for the component + // to be maximized. + TReal maxValue = -0xFFFF; + TInt maxIndex = KErrNotFound; + + for (TInt i = 0; i < angleCounter; i++) + { + // Rotate the original vector. + TReal rotatedVector[ KAMMSVectorComponents ]; + + AMMSUtil::RotateVectorL(aVector, aRotationAxelVector, + zeroAngles[ i ], rotatedVector); // CSI: 2 Wrong index means implementation error # + + // Check the value of the component that should be maximized. + TReal value = rotatedVector[ aMaximizeComponent ]; + + if (value > maxValue) + { + maxValue = value; + maxIndex = i; + } + } + + return zeroAngles[ maxIndex ]; +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSOrientationControlGroup::ClassName() +{ + return KAMMSOrientationControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::CommitL +// Transfers all the pending parameters to the audio processing system. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::CommitL(TInt aCommit) +{ + if (aCommit & EOrientation) + { + TInt controls = ControlCount(); + + if (controls > 0) + { + TInt angleVector[] = + { + iUncommited.iOrientation[ EHeading ], + iUncommited.iOrientation[ EPitch ], + iUncommited.iOrientation[ ERoll ] + }; + + // If the orientation was given in vectors, convert + // the vectors to angles because at the moment the Effect API + // can handle only angles. + if (iUncommited.iOrientationVector) + { + ConvertOrientationToAnglesL(iUncommited, angleVector); + } + + for (TInt i = 0; i < controls; i++) + { + CAMMSOrientationControl* control = TypeSafeControl(i); + + control->SetOrientationL( + angleVector[ EHeading ], + angleVector[ EPitch ], + angleVector[ ERoll ]); + } + } + + iCommited = iUncommited; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSOrientationControlGroup::NotifyPlayerAddedL( + CMMAPlayer* aPlayer, + CMMAControl* aControl) +{ + CAMMSAudio3DControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSOrientationControl* control = + static_cast(aControl); + + // set the current parameters + if (iCommited.iOrientationVector) + { + TInt angleVector[ KAMMSVectorComponents ]; + + ConvertOrientationToAnglesL(iCommited, angleVector); + + control->SetOrientationL( + angleVector[ EHeading ], + angleVector[ EPitch ], + angleVector[ ERoll ]); + } + else + { + control->SetOrientationL( + iCommited.iOrientation[ EHeading ], + iCommited.iOrientation[ EPitch ], + iCommited.iOrientation[ ERoll ]); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControlGroup::CAMMSOrientationControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSOrientationControlGroup::CAMMSOrientationControlGroup() + : CAMMSAudio3DControlGroup(KAMMSOrientationControl) +{ + // Default orientation is: + // heading = 0 + // pitch = 0 + // roll = 0 + iCommited.iOrientationVector = EFalse; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/inc/cammsaudiovirtualizercontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/inc/cammsaudiovirtualizercontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,120 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb controls +* +*/ + + +#ifndef CAMMSAUDIOVIRTUALIZERCONTROLGROUP_H +#define CAMMSAUDIOVIRTUALIZERCONTROLGROUP_H + +// INCLUDES +#include +#include "cammseffectcontrolgroup.h" + +// CONSTANTS +_LIT(KAMMSAudioVirtualizerControlClassName, + ".amms.control.audioeffect.AudioVirtualizerControl"); + +// FORWARD DECLARATIONS +class CAMMSAudioVirtualizerControl; +class CStereoWideningUtility; + + +// CLASS DECLARATION +/** + * Group for audio virtualizer controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSAudioVirtualizerControlGroup): + public CAMMSEffectControlGroup +{ +public: // Constructors and destructor + /** + * Two-phased constructor. + */ + static CAMMSAudioVirtualizerControlGroup* NewLC(); + + /** + * destructor + */ + ~CAMMSAudioVirtualizerControlGroup(); + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: // Functions from base classes + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + + /** + * Called when the current preset changes + */ + void PresetChangedL(); + + /** + * Finish initialization (after the 1st player is added) + */ + void InitializeL(); + + /** + * Creates utilities that can be used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utility already exists. + */ + void PrepareEmptyGroupUtilitiesL(); + + /** + * Deletes utilities that are used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utilities have already been deleted. + */ + void DeleteEmptyGroupUtilities(); + + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + void GetPresetNamesL(CDesCArray& aPresetNames); + +private: + /** + * C++ default constructor. + */ + CAMMSAudioVirtualizerControlGroup(); + + /** + * Symbian 2nd phase constructor. + */ + void ConstructL(); + +private: // data + + // Needed to get preset names when the group has no controls. + CStereoWideningUtility* iEmptyStereoWideningUtility; // Owned. + +}; + +#endif // CAMMSAUDIOVIRTUALIZERCONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/inc/cammseffectcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/inc/cammseffectcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,238 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +#ifndef CAMMSEFFECTCONTROLGROUP_H +#define CAMMSEFFECTCONTROLGROUP_H + +// INCLUDES +#include +#include +#include // MMdaAudioPlayerCallback +#include "cammscontrolgroup.h" + +// CONSTANTS +// Used to get preset names and data when the group is empty. +_LIT(KAMMSEmptyGroupSoundPath, "Z:\\System\\Sounds\\Digital\\CamcorderJavaStart.wav"); +const TInt KAMMSMaxPresetNameLength = 32; +const TInt KAMMSPresetGranularity = 5; + +// FORWARD DECLARATIONS +class CAMMSEffectControl; + + +// CLASS DECLARATION + +/** + * Group for effect controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSEffectControlGroup) + : public CAMMSControlGroup, public MMdaAudioPlayerCallback +{ +public: // Enumerations + + enum TEffectScope { + EScopeLiveOnly = 1, + EScopeRecordOnly = 2, + EScopeLiveAndRecord = 3 }; + +public: // Constructors and destructor + /** + * Destructor. + */ + ~CAMMSEffectControlGroup(); + +public: // New functions + + /** + * Gets the current preset. + * + * @return the current preset + */ + void GetPresetL(TDes& aPreset); + + /** + * Gets the available preset names + * + * @return all the available current presets + */ + const CDesCArray& PresetNamesL(); + + /** + * Returns the scope in which the effect is present. + * + * @return SCOPE_LIVE_ONLY, SCOPE_RECORD_ONLY or SCOPE_LIVE_AND_RECORD + */ + TEffectScope Scope(); + + /** + * Returns true if the effect is enabled and false otherwise. + * + * @return true=enable, false=disable + */ + TBool Enabled(); + + /** + * Returns the current enforced setting of the effect. + * + * @return true if the effect is an enforced effect, false if not + */ + TBool Enforced(); + + /** + * Enables/disables the effect. + * + * @param aEnabled true=enabled, false=disabled + */ + void SetEnabledL(TBool aEnabled); + + /** + * Enforces the effect to be in use. + * + * @param aEnforced true if the effect is essential and cannot + * be dropped, false if the effect can be dropped + * if the system runs out of resources. + */ + void SetEnforcedL(TBool aEnforced); + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Sets the scope of the effect. + * + * @param aScope SCOPE_LIVE_ONLY, SCOPE_RECORD_ONLY or + * SCOPE_LIVE_AND_RECORD. + */ + void SetScopeL(TEffectScope aScope); + +public: // From MMdaAudioPlayerCallback + + /** + * Called when file KAMMSEmptyGroupSoundPath has been opened. + */ + void MapcInitComplete(TInt aError, + const TTimeIntervalMicroSeconds& aDuration); + + /** + * Called when KAMMSEmptyGroupSoundPath has been played, + * no implementation needed in this class. + */ + void MapcPlayComplete(TInt aError); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSEffectControl* TypeSafeControl(TInt aIndex) const; + +protected: // New functions + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer* aPlayer, CMMAControl* aControl); + + /** + * Called when the current preset changes + */ + virtual void PresetChangedL(); + + /* + * Finish initialization (after the 1st player is added) + */ + virtual void InitializeL(); + + /** + * Creates utilities that can be used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utility already exists. + */ + virtual void PrepareEmptyGroupUtilitiesL(); + + /** + * Deletes utilities that are used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utilities have already been deleted. + */ + virtual void DeleteEmptyGroupUtilities(); + + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + virtual void GetPresetNamesL(CDesCArray& aPresetNames) = 0; + +protected: + /** + * C++ default constructor. + */ + CAMMSEffectControlGroup(const TDesC& aName); + +protected: + /** + * 2nd phase constructor. + */ + void BaseConstructL(); + +protected: // data + + // Available preset names, owned + CDesCArrayFlat* iPresetNames; + + // Index of the current preset or -1 if no preset is set + TInt iPresetIndex; + + TBool iInitialized; // Flag to store whether effect is initialized + + // Used to get preset names and data when the group is empty + // (there are no controls in the group, and thus, no actual + // control can be used for that purpose). + CMdaAudioPlayerUtility* iEmptyPlayerUtility; // Owned. + +private: //data + + TEffectScope iScope; // Scope of the effect + TBool iEnabled; // Flag to store whether effect is enabled + TBool iEnforced; // Flag to store whether effect is enforced + + // Flag to store whether enforce was set before the group was initialized + TBool iInitialEnforceSet; + // Flag to store whether scope was set before the group was initialized + TBool iInitialScopeSet; + + // Used to wait for opening KAMMSEmptyGroupSoundPath. + CActiveSchedulerWait* iActiveSchedulerWait; // Owned. + + // Error code occured when creating a player for empty group. + TInt iEmptyPlayerUtilityError; + +}; + +#endif // CAMMSEFFECTCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/inc/cammsequalizercontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/inc/cammsequalizercontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,259 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for equalizer controls +* +*/ + + +#ifndef CAMMSEQUALIZERCONTROLGROUP_H +#define CAMMSEQUALIZERCONTROLGROUP_H + +// INCLUDES +#include +#include "cammseffectcontrolgroup.h" +#include + +// CONSTANTS +_LIT(KAMMSEqualizerControlClassName, + ".amms.control.audioeffect.EqualizerControl"); + + +// FORWARD DECLARATIONS +class CAMMSBaseEqualizerControl; +class CAudioEqualizerUtility; + + +// CLASS DECLARATION +/** + * Group for equalizer controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSEqualizerControlGroup): public CAMMSEffectControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSEqualizerControlGroup* NewLC(); + + /** + * Destructor. + */ + ~CAMMSEqualizerControlGroup(); + +public: // New functions + /** + * Gets the band that has the most effect on the given frequency + * + * @param aFrequency The frequency in milliHertz which is + * to be equalized via the returned band + * + * @return The frequency band that has most effect on the given + * frequency or -1 if no band has effect on the given frequency + */ + TInt Band(TInt aFrequency); + + /** + * Gets the gain set for the given equalizer band. + * + * @param aBand The frequency band whose gain is asked. + * @param aBandLevel The returned level for the given band in millibels. + * + */ + void GetBandLevelL(TInt aBand, TInt& aBandLevel); + + /** + * Gets the bass level. + * + * @return The current level that is set to the bass band. If the + * bass level cannot been defined EqualizerControl.UNDEFINED will + * be returned + */ + TInt Bass(); + + /** + * Gets the center frequency of the given band + * + * @param aBand The frequency band whose center frequency + * is asked. + * @param aCenterFreq The returned center frequency in milliHertz. + */ + void GetCenterFreqL(TInt aBand, TInt& aCenterFreq); + + /** + * Returns the maximum band level supported + * + * @return the maximum band level supported + */ + TInt MaxBandLevel(); + + /** + * Returns the minimum band level supported. + * + * @return the minimum band level supported. + */ + TInt MinBandLevel(); + + /** + * Gets the number of frequency bands that the equalizer supports. + * + * @return the number of frequency bands that the equalizer supports. + */ + TInt NumberOfBands(); + + /** + * Gets the treble level. + * + * @return The current level that is set to the treble band. If the + * treble level cannot been defined EqualizerControl.UNDEFINED will + * be returned + */ + TInt Treble(); + + /** + * Sets the given equalizer band to the given gain value. + * + * @param aLevel The new gain in millibels that will be set to the + * given band + * @param aBand The frequency band that will have the new gain + */ + void SetBandLevelL(TInt aLevel, TInt aBand); + + /** + * Sets the bass level using a linear point scale with values between + * 0 and 100: a value of 0 applies the maximum available attenuation + * to frequencies in the bass band; a value of 50 gives a flat + * equalization of the bass band; and a value of 100 applies the + * maximum available amplification to frequencies in the bass band. + * + * @param aLevel The new level on a linear point scale that will + * be set to the bass band + * @param aSetLevel Returned level that was actually set + */ + void SetBassL(TInt aLevel, TInt& aSetLevel); + + /** + * Sets the treble level using a linear point scale with values between + * 0 and 100: a value of 0 applies the maximum available attenuation to + * frequencies in the treble band; a value of 50 gives a flat + * equalization of the treble band; and a value of 100 applies the + * maximum available amplification to frequencies in the treble band + * + * @param aLevel The new level on a linear point scale that will + * be set to the treble band + * + * @param aSetLevel Returned level that was actually set + */ + void SetTrebleL(TInt aLevel, TInt& aSetLevel); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSBaseEqualizerControl* TypeSafeControl(TInt aIndex) const; + + /** + * Checks whether the band index is between 0 and number of bands -1. + * Function leaves with KErrArgument if the band is not between the + * limits. + */ + void CheckBandIndexL(TInt aBand) const; + + /** + * Gets bands corresponding to the given preset index. + * The data is obtained from controls (or from empty group utility, if the + * group has no controls). + * @param aPresetIndex Index of the preset whose bands are asked + * @param aBands Returned bands + */ + void GetPresetBandsL(TUint aPresetIndex, + RArray< TEfAudioEqualizerBand >& aBands); + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: // Functions from base classes + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + + /** + * Called when the current preset changes + */ + void PresetChangedL(); + + /** + * Finish initialization (after the 1st player is added) + */ + void InitializeL(); + + /** + * Creates utilities that can be used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utility already exists. + */ + void PrepareEmptyGroupUtilitiesL(); + + /** + * Deletes utilities that are used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utilities have already been deleted. + */ + void DeleteEmptyGroupUtilities(); + + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + void GetPresetNamesL(CDesCArray& aPresetNames); + +protected: + /** + * C++ default constructor. + */ + CAMMSEqualizerControlGroup(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // data + + // Needed to get preset names when the group has no controls. + CAudioEqualizerUtility* iEmptyAudioEqualizerUtility; // Owned. + + RArray< TEfAudioEqualizerBand > iBands; + TInt iBass; // bass level + TInt iTreble; // treble level + TInt iMaxBandLevel; + TInt iMinBandLevel; +}; + +#endif // CAMMSEQUALIZERCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/inc/cammsreverbcontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/inc/cammsreverbcontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,173 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb controls +* +*/ + + +#ifndef CAMMSREVERBCONTROLGROUP_H +#define CAMMSREVERBCONTROLGROUP_H + +// INCLUDES +#include +#include "cammseffectcontrolgroup.h" +#include + +// CONSTANTS +_LIT(KAMMSReverbControlClassName, ".amms.control.audioeffect.ReverbControl"); + +// FORWARD DECLARATIONS +class CAMMSBaseReverbControl; +class CEnvironmentalReverbUtility; + + +// CLASS DECLARATION +/** + * Group for reverb controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSReverbControlGroup): public CAMMSEffectControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSReverbControlGroup* NewLC(); + + /** + * destructor + */ + ~CAMMSReverbControlGroup(); + +public: // New functions + + /** + * Gets the gain level of the reverberation + * + * @return the gain level of the reverberation + */ + TInt ReverbLevel(); + + /** + * Gets the reverberation time, as set either explicitly via + * setReverbTime or implicitly via setPreset (whichever was called last). + * + * @return the reverberation time + */ + TInt ReverbTime(); + + /** + * Sets the gain level of the reverberation + * + * @param the gain level of the reverberation to be set + */ + void SetReverbLevelL(TInt aLevel); + + /** + * Sets the reverberation time of the reverb + * + * @param the reverberation time to be set + */ + void SetReverbTimeL(TInt aTime); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSBaseReverbControl* TypeSafeControl(TInt aIndex) const; + + /** + * Gets reverb data for the given preset index from the central + * repository. + * @param aPresetIndex Index of the preset whose reverb is asked. + * @param aReverbData Returned data. + */ + void GetReverbDataFromCenRepL(TUint aPresetIndex, + TEfEnvReverbDataPckg& aReverbData); + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + + /** + * Called when the current preset changes + */ + void PresetChangedL(); + + /** + * Finish initialization (after the 1st player is added) + */ + void InitializeL(); + + /** + * Creates utilities that can be used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utility already exists. + */ + void PrepareEmptyGroupUtilitiesL(); + + /** + * Deletes utilities that are used to obtain preset names + * and preset data (needed when the group has no controls). + * Does nothing if the utilities have already been deleted. + */ + void DeleteEmptyGroupUtilities(); + + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + void GetPresetNamesL(CDesCArray& aPresetNames); + +protected: + /** + * C++ default constructor. + */ + CAMMSReverbControlGroup(); + + /** + * Symbian 2nd phase constructor. + */ + void ConstructL(); + +protected: // data + + // Needed to get preset names when the group has no controls. + CEnvironmentalReverbUtility* iEmptyEnvironmentalReverbUtility; // Owned. + + TInt iReverbLevel; + TInt iReverbTime; + TInt iReverbMinLevel; + TInt iReverbMaxLevel; + +}; + +#endif // CAMMSREVERBCONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/inc/cammsreverbsourcecontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/inc/cammsreverbsourcecontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb source controls +* +*/ + + +#ifndef CAMMSREVERBSOURCECONTROLGROUP_H +#define CAMMSREVERBSOURCECONTROLGROUP_H + +// INCLUDES +#include +#include "cammscontrolgroup.h" + +// CONSTANTS +_LIT(KAMMSReverbSourceControlClassName, + ".amms.control.audioeffect.ReverbSourceControl"); + +// FORWARD DECLARATIONS +class CAMMSBaseReverbSourceControl; + + +// CLASS DECLARATION +/** + * Group for reverb controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSReverbSourceControlGroup): public CAMMSControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSReverbSourceControlGroup* NewLC(); + + /** + * destructor + */ + ~CAMMSReverbSourceControlGroup(); + +public: // New functions + + /** + * Gets the gain level of the reverberation + * + * @return the gain level of the reverberation + */ + TInt RoomLevel(); + + /** + * Sets the gain level of the reverberation + * + * @param the gain level of the reverberation to be set + */ + void SetRoomLevelL(TInt aLevel); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSBaseReverbSourceControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: // Functions from base classes + + /** + * Called by PlayerAddedL when new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer* aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSReverbSourceControlGroup(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // data + + // the actual room level for this control group + TInt iRoomLevel; + +}; + +#endif // CAMMSREVERBSOURCECONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/src/cammsaudiovirtualizercontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/src/cammsaudiovirtualizercontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,187 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb controls +* +*/ + + +// INCLUDE FILES +#include +#include +#include +#include "cammsaudiovirtualizercontrolgroup.h" +#include "cammsaudiovirtualizercontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioVirtualizerControlGroup* CAMMSAudioVirtualizerControlGroup::NewLC() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::NewLC +"); + + CAMMSAudioVirtualizerControlGroup* self = + new(ELeave) CAMMSAudioVirtualizerControlGroup; + + CleanupStack::PushL(self); + self->BaseConstructL(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::NewLC -"); + + return self; +} + +// Destructor +CAMMSAudioVirtualizerControlGroup::~CAMMSAudioVirtualizerControlGroup() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::~ +"); + + delete iEmptyStereoWideningUtility; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::~ -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSAudioVirtualizerControlGroup::ClassName() +{ + return KAMMSAudioVirtualizerControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + CAMMSEffectControlGroup::NotifyPlayerAddedL(aPlayer, aControl); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::PresetChangedL +// Called when the current preset changes +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::PresetChangedL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::InitializeL +// Finish initialization (after the 1st player is added) +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::InitializeL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::PrepareEmptyGroupUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::PrepareEmptyGroupUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::PrepareEmptyGroupUtilitiesL +"); + + if (!iEmptyStereoWideningUtility) + { + CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL(); + + iEmptyStereoWideningUtility = + CStereoWideningUtility::NewL(*iEmptyPlayerUtility); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::PrepareEmptyGroupUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::DeleteEmptyGroupUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::DeleteEmptyGroupUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::DeleteEmptyGroupUtilities +"); + + if (iEmptyPlayerUtility) + { + delete iEmptyStereoWideningUtility; + iEmptyStereoWideningUtility = NULL; + + CAMMSEffectControlGroup::DeleteEmptyGroupUtilities(); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::DeleteEmptyGroupUtilities -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::GetPresetNamesL +"); + + // Create empty group utilities for getting preset names. + PrepareEmptyGroupUtilitiesL(); + + TArray< TEfStereoWideningUtilityPreset > presetNames = + iEmptyStereoWideningUtility->Presets(); + + + TInt presetCount = presetNames.Count(); + + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + + + // Delete empty group utilities in order to save memory. + DeleteEmptyGroupUtilities(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControlGroup::GetPresetNamesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::CAMMSAudioVirtualizerControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioVirtualizerControlGroup::CAMMSAudioVirtualizerControlGroup() + : CAMMSEffectControlGroup(KAMMSAudioVirtualizerControl) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControlGroup::ConstructL() +{ + CAMMSEffectControlGroup::BaseConstructL(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/src/cammseffectcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/src/cammseffectcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,436 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +// INCLUDE FILES +#include +#include "cammseffectcontrolgroup.h" +#include "cammseffectcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSEffectControlGroup::~CAMMSEffectControlGroup() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::~ +"); + + delete iPresetNames; + delete iActiveSchedulerWait; + + if (iEmptyPlayerUtility) + { + iEmptyPlayerUtility->Close(); + delete iEmptyPlayerUtility; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::~ -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::PresetL +// Gets the current preset. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::GetPresetL(TDes& aPreset) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::GetPresetL +"); + + // Return KNullDesC if no preset is set. + if (iPresetIndex >= 0) + { + aPreset = (*iPresetNames)[ iPresetIndex ]; // CSI: 2 Wrong index means implementation error # + } + else + { + aPreset = KNullDesC; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::GetPresetL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::PresetNamesL +// Gets the available preset names +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const CDesCArray& CAMMSEffectControlGroup::PresetNamesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::PresetNamesL"); + + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::Scope +// Returns the scope in which the effect is present. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSEffectControlGroup::TEffectScope CAMMSEffectControlGroup::Scope() +{ + return iScope; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::Enabled +// Returns true if the effect is enabled and false otherwise. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TBool CAMMSEffectControlGroup::Enabled() +{ + return iEnabled; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::EnforcedL +// Returns the current enforced setting of the effect. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TBool CAMMSEffectControlGroup::Enforced() +{ + return iEnforced; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::SetEnabledL +// Enables/disables the effect. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::SetEnabledL(TBool aEnabled) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetEnabledL +"); + + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetEnabledL(aEnabled); + } + + iEnabled = aEnabled; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetEnabledL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::SetEnforcedL +// Enforces the effect to be in use. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::SetEnforcedL(TBool aEnforced) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetEnforcedL +"); + + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetEnforcedL(aEnforced); + } + + iEnforced = aEnforced; + + // remember that enforce was set when the group was not yet initialized + if (!iInitialized) + { + iInitialEnforceSet = ETrue; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetEnforcedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::SetPresetL +// Sets the effect according to the given preset. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::SetPresetL(const TDesC& aPreset) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetPresetL +"); + + // Leave if the given preset does not exist. + TInt presetIndex = -1; + if (!(iPresetNames->Find(aPreset, presetIndex) == 0)) + { + User::Leave(KErrNotFound); + } + + // Set new preset to the controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetPresetL(aPreset); + } + + // Change preset. + iPresetIndex = presetIndex; + + // Announce a preset change. + PresetChangedL(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetPresetL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::SetScopeL +// Sets the scope of the effect. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::SetScopeL(TEffectScope aScope) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetScopeL +"); + + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetScopeL(aScope); + } + + iScope = aScope; + + // remember that scope was set when the group was not yet initialized + if (!iInitialized) + { + iInitialScopeSet = ETrue; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::SetScopeL -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::MapcInitComplete +// Called when file KAMMSEmptyGroupSoundPath has been opened. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::MapcInitComplete(TInt aError, + const TTimeIntervalMicroSeconds& /*aDuration*/) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::MapcInitComplete +"); + + __ASSERT_DEBUG(iActiveSchedulerWait->IsStarted(), User::Invariant()); + + iEmptyPlayerUtilityError = aError; + + // Stop waiting in PrepareEmptyGroupUtilityL() function. + iActiveSchedulerWait->AsyncStop(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::MapcInitComplete -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::MapcPlayComplete +// Called when KAMMSEmptyGroupSoundPath has been played. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::MapcPlayComplete(TInt /*aError*/) +{ + // No implementation needed. +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSEffectControl* +CAMMSEffectControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::NotifyPlayerAddedL +"); + + CAMMSControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSEffectControl* control = + static_cast(aControl); + + // set current preset if any + if (iPresetIndex >= 0) + { + control->SetPresetL((*iPresetNames)[ iPresetIndex ]); // CSI: 2 Wrong index means implementation error # + } + + // handle default values if this is the first control added into empty and + // uninitialized group + if (!iInitialized) + { + + InitializeL(); + + // if parameters, whose default values are not known, have not been set, + // ask them from the first control added to the empty group + if (!iInitialEnforceSet) + { + + iEnforced = control->Enforced(); + + } + + if (!iInitialScopeSet) + { + + iScope = (TEffectScope) control->Scope(); + + } + + iInitialized = ETrue; + } + + // set current parameters + + control->SetEnabledL(iEnabled); + + control->SetEnforcedL(iEnforced); + + control->SetScopeL(iScope); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::NotifyPlayerAddedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::PresetChangedL +// Called when the current preset changes +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::PresetChangedL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::InitializeL +// Finish initialization (after the 1st player is added) +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::InitializeL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL +// Creates an utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL +"); + + if (!iEmptyPlayerUtility) + { + iEmptyPlayerUtility = CMdaAudioPlayerUtility::NewL(*this, + EMdaPriorityMin, EMdaPriorityPreferenceNone); + + iEmptyPlayerUtility->OpenFileL(KAMMSEmptyGroupSoundPath); + + __ASSERT_DEBUG(!iActiveSchedulerWait->IsStarted(), User::Invariant()); + + // Wait until MapcInitComplete() has been called. + iActiveSchedulerWait->Start(); // CSI: 10 iActiveSchedulerWait cannot be started, also checked in debug build # + + ELOG1( EJavaAMMS, + "AMMS::CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL, err=%d", + iEmptyPlayerUtilityError); + + // Leave if file opening returned an error. + User::LeaveIfError(iEmptyPlayerUtilityError); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::DeleteEmptyGroupUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::DeleteEmptyGroupUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::DeleteEmptyGroupUtilities +"); + + if (iEmptyPlayerUtility) + { + iEmptyPlayerUtility->Close(); + + delete iEmptyPlayerUtility; + iEmptyPlayerUtility = NULL; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::DeleteEmptyGroupUtilities -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::CAMMSEffectControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSEffectControlGroup::CAMMSEffectControlGroup(const TDesC& aName) : + CAMMSControlGroup(aName) +{ + iScope = CAMMSEffectControlGroup::EScopeLiveOnly; + iEnabled = EFalse; + iEnforced = ETrue; + iPresetIndex = -1; // no preset set +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEffectControlGroup::BaseConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::BaseConstructL +"); + + CAMMSControlGroup::ConstructL(); + + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; + iPresetNames = new(ELeave)CDesCArrayFlat(KAMMSPresetGranularity); + + // If the Effect API implementation does not support the effect, + // the function leaves with KErrNotSupported. The leaving can be ignored + // in this case, the result is that the list of supported presets + // remain empty. + TRAPD(err, GetPresetNamesL(*iPresetNames)); + + ELOG1( EJavaAMMS, "AMMS::CAMMSEffectControlGroup::BaseConstructL, err %d", err); + + // In case of an error, delete possible utilities to save memory. + if (err != KErrNone) + { + DeleteEmptyGroupUtilities(); + } + + // Leave if some error occured (other than KErrNotSupported). + if ((err != KErrNone) && (err != KErrNotSupported)) + { + User::Leave(err); + } + + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControlGroup::BaseConstructL -"); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/src/cammsequalizercontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/src/cammsequalizercontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,617 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for equalizer controls +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "cammsequalizercontrolgroup.h" +#include "cammsbaseequalizercontrol.h" + +// CONSTANTS +namespace +{ +const TInt KAMMSDefaultEqualizerLevel = 0; +const TInt KAMMSDefaultEqualizerMaxLevel = 1200; +const TInt KAMMSDefaultEqualizerMinLevel = -1200; +const TInt KAMMSDefaultEqualizerTrebleAndBassLevel = 50; +const TInt KAMMSUndefinedTrebleOrBass = -1004; +const TInt KAMMSKilo = 1000; // e.g. 1Hz = 1000 mHz +} + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEqualizerControlGroup* CAMMSEqualizerControlGroup::NewLC() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::NewLC +"); + + CAMMSEqualizerControlGroup* self = + new(ELeave) CAMMSEqualizerControlGroup; + + CleanupStack::PushL(self); + self->ConstructL(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::NewLC -"); + + return self; +} + +// Destructor +CAMMSEqualizerControlGroup::~CAMMSEqualizerControlGroup() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::~ +"); + + delete iEmptyAudioEqualizerUtility; + + iBands.Close(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::~ -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::Band +// Gets the band that has the most effect on the given frequency +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::Band(TInt aFrequency) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::Band +"); + + // Check whether bands have effect on the given frequency. + if ((aFrequency <= 0) || + (aFrequency > KAMMSHalfOfSamplingFrequency)) // 24000000 milliHertz + { + return -1; // no effect on the frequency. Frequency 0 goes here too. + } + + TInt bandCount = iBands.Count(); + if (bandCount == 0) + { + return 0; // if the number of the bands is zero, return band zero. + } + + // Effect API uses hertzes whereas AMMS uses millihertzes. + TInt frequencyInHertzes = aFrequency / KAMMSKilo; + + // Find the first band whose cross-over frequency is greater than the + // given frequency (the band has effect on the given frequency). + TInt i = 0; + for (i = 0; i < bandCount; i++) + { + if (iBands[ i ].iCrossoverFrequency >= frequencyInHertzes) + { + return i; + } + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::Band -"); + + // If the given frequency if bigger than any cross-over frequency, + // return the last band. + return (bandCount - 1); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::GetBandLevelL +// Gets the gain set for the given equalizer band. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::GetBandLevelL(TInt aBand, TInt& aBandLevel) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetBandLevelL +"); + + CheckBandIndexL(aBand); + + aBandLevel = iBands[ aBand ].iBandLevel; // CSI: 2 Index checked above # + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetBandLevelL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::Bass +// Gets the bass level. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::Bass() +{ + return iBass; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::GetCenterFreqL +// Gets the center frequency of the given band +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::GetCenterFreqL(TInt aBand, TInt& aCenterFreq) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetCenterFreqL +"); + + CheckBandIndexL(aBand); + + // Effect API uses hertzes whereas AMMS uses millihertzes. + aCenterFreq = iBands[ aBand ].iCenterFrequency * KAMMSKilo; // CSI: 2 Index checked above # + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetCenterFreqL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::MaxBandLevel +// Returns the maximum band level supported +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::MaxBandLevel() +{ + return iMaxBandLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::MinBandLevel +// Returns the minimum band level supported. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::MinBandLevel() +{ + return iMinBandLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::NumberOfBands +// Gets the number of frequency bands that the equalizer supports. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::NumberOfBands() +{ + return iBands.Count(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::Treble +// Gets the treble level. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEqualizerControlGroup::Treble() +{ + return iTreble; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::SetBandLevelL +// Sets the given equalizer band to the given gain value. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::SetBandLevelL(TInt aLevel, TInt aBand) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetBandLevelL +"); + + // check given parameters + CheckBandIndexL(aBand); + + if (aLevel < iMinBandLevel || aLevel > iMaxBandLevel) + { + User::Leave(KErrArgument); + } + + // Set new level to controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetBandLevelL(aLevel, aBand); + } + + iBands[ aBand ].iBandLevel = aLevel; // CSI: 2 Index checked above # + + // remove current preset since it is not valid any more + iPresetIndex = -1; + + iTreble = KAMMSUndefinedTrebleOrBass; + iBass = KAMMSUndefinedTrebleOrBass; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetBandLevelL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::SetBassL +// Sets the bass level +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::SetBassL(TInt aLevel, TInt& aSetLevel) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetBassL +"); + + __ASSERT_DEBUG((aLevel >= iMinBandLevel) && + (aLevel <= iMaxBandLevel), User::Invariant()); + + // Set the bass band (first band) to the given percentage of the valid range + // between MinBandLevel and MaxBandLevel. + TInt newBandLevel = iMinBandLevel + aLevel * + (iMaxBandLevel - iMinBandLevel) / 100; // CSI: 47 Value 100 means 100% here # + + // Set new value to bass band (band 0) if band count > 0 + if (iBands.Count() > 0) + { + // Set new bass (band 0) to controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetBandLevelL(newBandLevel, 0); + } + + iBands[ 0 ].iBandLevel = newBandLevel; + } + + // remove the current preset since it is not valid any more + iPresetIndex = -1; + + iBass = aLevel; + + aSetLevel = iBass; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetBassL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::SetTrebleL +// Sets the treble level +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::SetTrebleL(TInt aLevel, TInt& aSetLevel) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetTrebleL +"); + + __ASSERT_DEBUG((aLevel >= iMinBandLevel) && + (aLevel <= iMaxBandLevel), User::Invariant()); + + TInt bands = iBands.Count(); + // Set new values to treble bands if there is at least two bands. + if (bands > 1) + { + // Treble affects to two bands. + TInt trebleIndex1 = bands - 1; // CSI: 47 Last band # + TInt trebleIndex2 = bands - 2; // CSI: 47 Second last band # + + // Set the highest band with 100% weight of the given percentage + // of the valid range between MinBandLevel and MaxBandLevel. + TInt newBandLevel1 = iMinBandLevel + + aLevel * (iMaxBandLevel - iMinBandLevel) / 100; // CSI: 47 Value 100 means 100% # + + // The treble affects 50% to the next highest band. + TInt newBandLevel2 = KAMMSDefaultEqualizerLevel + + (newBandLevel1 - KAMMSDefaultEqualizerLevel) / 2; // CSI: 47 Divided by 2 is the same as 50% # + + // Set new treble level to controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetBandLevelL(newBandLevel1, trebleIndex1); + TypeSafeControl(i)->SetBandLevelL(newBandLevel2, trebleIndex2); + } + + iBands[ trebleIndex1 ].iBandLevel = newBandLevel1; + iBands[ trebleIndex2 ].iBandLevel = newBandLevel2; + } + + // remove the current preset since it is not valid any more + iPresetIndex = -1; + + iTreble = aLevel; + + aSetLevel = iTreble; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::SetTrebleL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSBaseEqualizerControl* +CAMMSEqualizerControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::CheckBandIndexL +// Checks whether the band index is between 0 and number of bands -1. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::CheckBandIndexL(TInt aBand) const +{ + if (aBand < 0 || aBand >= iBands.Count()) + { + User::Leave(KErrArgument); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::GetPresetBandsL +// Gets bands corresponding to the given preset index. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::GetPresetBandsL(TUint /*aPresetIndex*/, + RArray< TEfAudioEqualizerBand >& aBands) +{ + aBands.Reset(); + + TInt count = ControlCount(); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetPresetBandsL, controls=%d", + count); + + // Get data of each band from a control. If there is no controls in the + // group, get the data from the empty group utility. + if (count > 0) + { + CAMMSBaseEqualizerControl* control = + CAMMSEqualizerControlGroup::TypeSafeControl(0); + + TInt bands = control->NumberOfBands(); + + for (TInt i = 0; i < bands; i++) + { + TEfAudioEqualizerBand band; + + band.iBandLevel = control->BandLevelL(i); + band.iBandWidth = control->BandWidth(i); + band.iCenterFrequency = control->CenterFrequency(i); + band.iCrossoverFrequency = control->CrossoverFrequency(i); + + aBands.AppendL(band); + } + } + else + { + // Create empty group utilities for getting preset data. + PrepareEmptyGroupUtilitiesL(); + + CAudioEqualizer& audioEffect = iEmptyAudioEqualizerUtility->Equalizer(); + TInt bands = audioEffect.NumberOfBands(); + + for (TInt i = 0; i < bands; i++) + { + TEfAudioEqualizerBand band; + + // Band 0 in JSR-234 equals Band 1 in Effect API + TUint8 bandId = (TUint8)(i + KAMMSBandOffset); + + band.iBandLevel = audioEffect.BandLevel(bandId); + band.iBandWidth = audioEffect.BandWidth(bandId); + band.iCenterFrequency = audioEffect.CenterFrequency(bandId); + band.iCrossoverFrequency = audioEffect.CrossoverFrequency(bandId); + + aBands.AppendL(band); + } + + // Delete empty group utilities in order to save memory. + DeleteEmptyGroupUtilities(); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetPresetBandsL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSEqualizerControlGroup::ClassName() +{ + return KAMMSEqualizerControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::NotifyPlayerAddedL +"); + + CAMMSEffectControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSBaseEqualizerControl* control = + static_cast(aControl); + + // if preset was not set into the new control by the main class, + // set bands, treble, and bass manually + if (iPresetIndex < 0) + { + TInt bands = iBands.Count(); + + // set current band levels + for (TInt i = 0; i < bands; i++) + { + control->SetBandLevelL(iBands[ i ].iBandLevel, i); + } + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::NotifyPlayerAddedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::PresetChangedL +// Called when the current preset changes +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::PresetChangedL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::PresetChangedL +"); + + // Invalidate bass and treble levels + iBass = KAMMSUndefinedTrebleOrBass; + iTreble = KAMMSUndefinedTrebleOrBass; + + // Get band data from controls (or from empty group utility, if the + // group has no controls). + GetPresetBandsL(iPresetIndex, iBands); // index limits already checked + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::PresetChangedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::InitializeL +// Finish initialization (after the 1st player is added) +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::InitializeL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::InitializeL +"); + + CAMMSBaseEqualizerControl* control = TypeSafeControl(0); + + iMaxBandLevel = control->MaxBandLevel(); + iMinBandLevel = control->MinBandLevel(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::InitializeL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::PrepareEmptyGroupUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::PrepareEmptyGroupUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::PrepareEmptyGroupUtilitiesL +"); + + if (!iEmptyAudioEqualizerUtility) + { + CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL(); + + iEmptyAudioEqualizerUtility = + CAudioEqualizerUtility::NewL(*iEmptyPlayerUtility); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::PrepareEmptyGroupUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::DeleteEmptyGroupUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::DeleteEmptyGroupUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::DeleteEmptyGroupUtilities +"); + + if (iEmptyPlayerUtility) + { + delete iEmptyAudioEqualizerUtility; + iEmptyAudioEqualizerUtility = NULL; + + CAMMSEffectControlGroup::DeleteEmptyGroupUtilities(); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::DeleteEmptyGroupUtilities -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetPresetNamesL +"); + + // Create empty group utilities for getting preset names. + PrepareEmptyGroupUtilitiesL(); + + TArray< TEfAudioEqualizerUtilityPreset > presetNames = + iEmptyAudioEqualizerUtility->Presets(); + + + TInt presetCount = presetNames.Count(); + + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + + // Delete empty group utilities in order to save memory. + DeleteEmptyGroupUtilities(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::GetPresetNamesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::CAMMSEqualizerControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSEqualizerControlGroup::CAMMSEqualizerControlGroup() + : CAMMSEffectControlGroup(KAMMSBaseEqualizerControl) +{ + iMaxBandLevel = KAMMSDefaultEqualizerMaxLevel; + iMinBandLevel = KAMMSDefaultEqualizerMinLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControlGroup::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::ConstructL +"); + + CAMMSEffectControlGroup::BaseConstructL(); + + // Get band data from empty group utility. + // If the Effect API implementation does not support the effect, + // the function leaves with KErrNotSupported. The leaving can be ignored + // in this case, the result is that the list of supported presets + // remain empty. + TRAPD(err, GetPresetBandsL(0, iBands)); + + ELOG1( EJavaAMMS, "AMMS::CAMMSEqualizerControlGroup::ConstructL, err %d", err); + + // In case of an error, delete possible utilities to save memory. + if (err != KErrNone) + { + DeleteEmptyGroupUtilities(); + } + + // Ignore the error so that using MMA and AMMS is possible. + // Only successfully read bands are visible for the user. + + + TInt bands = iBands.Count(); + + // Set default band levels. + for (TInt i = 0; i < bands; i++) + { + iBands[ i ].iBandLevel = KAMMSDefaultEqualizerLevel; + } + + // Set default values for Bass and Treble. Value 50 means flat equalization. + iBass = KAMMSDefaultEqualizerTrebleAndBassLevel; + iTreble = KAMMSDefaultEqualizerTrebleAndBassLevel; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControlGroup::ConstructL -"); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/src/cammsreverbcontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/src/cammsreverbcontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,355 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb controls +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "cammsreverbcontrolgroup.h" +#include "cammsbasereverbcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSReverbControlGroup* CAMMSReverbControlGroup::NewLC() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::NewLC +"); + + CAMMSReverbControlGroup* self = new(ELeave) CAMMSReverbControlGroup; + + CleanupStack::PushL(self); + self->ConstructL(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::NewLC -"); + + return self; +} + +// Destructor +CAMMSReverbControlGroup::~CAMMSReverbControlGroup() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::~"); + + delete iEmptyEnvironmentalReverbUtility; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::ReverbLevel +// Gets the gain level of the reverberation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSReverbControlGroup::ReverbLevel() +{ + return iReverbLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::ReverbTime +// Gets the reverberation time, as set either explicitly via +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSReverbControlGroup::ReverbTime() +{ + return iReverbTime; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::SetReverbLevelL +// Sets the gain level of the reverberation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::SetReverbLevelL(TInt aLevel) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::SetReverbLevelL"); + + __ASSERT_DEBUG(aLevel <= 0, User::Invariant()); + + // Set the level between the accepted limits [iReverbMinLevel, + // iReverbMaxLevel]. + TInt reverbLevel = Min(aLevel, iReverbMaxLevel); + reverbLevel = Max(reverbLevel, iReverbMinLevel); + + // Set reverb level to the controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetReverbLevelL(reverbLevel); + } + + // Invalidate current preset and save the new reverb level + iPresetIndex = -1; + iReverbLevel = reverbLevel; + + LOG4( EJavaMMAPI, EInfo, "CAMMSReverbControlGroup::SetReverbLevelL, levels: %d, %d, %d %d", + aLevel, iReverbMinLevel, iReverbMaxLevel, reverbLevel); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::SetReverbTimeL +// Sets the reverberation time of the reverb +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::SetReverbTimeL(TInt aTime) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::SetReverbTimeL +"); + + __ASSERT_DEBUG(aTime >= 0, User::Invariant()); + + // Set reverb time to controls. + TInt count = ControlCount(); + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetReverbTimeL(aTime); + } + + // Invalidate current preset and save new reverb time + iPresetIndex = -1; + iReverbTime = aTime; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::SetReverbTimeL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSBaseReverbControl* +CAMMSReverbControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSReverbControlGroup::ClassName() +{ + return KAMMSReverbControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::NotifyPlayerAddedL +"); + + CAMMSEffectControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSBaseReverbControl* control = + static_cast(aControl); + + // if the preset is not valid, set reverb level and time to the added + // control + if (iPresetIndex < 0) + { + control->SetReverbLevelL(iReverbLevel); + control->SetReverbTimeL(iReverbTime); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::NotifyPlayerAddedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::PresetChangedL +// Called when the current preset changes +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::PresetChangedL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PresetChangedL +"); + + TInt count = ControlCount(); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PresetChangedL, controls=%d", + count); + + // Ask preset data from the first control if exists. If not, ask the + // data from the empty group utility. + if (count > 0) + { + CAMMSBaseReverbControl* control = TypeSafeControl(0); + + iReverbTime = control->ReverbTime(); + iReverbLevel = control->ReverbLevel(); + iReverbMinLevel = control->MinReverbLevel(); + iReverbMaxLevel = control->MaxReverbLevel(); + } + else + { + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PresetChangedL, index=%d", + iPresetIndex); + + __ASSERT_DEBUG(iPresetIndex >= 0, User::Invariant()); + + // Create empty group utilities for getting preset data. + PrepareEmptyGroupUtilitiesL(); + + // Set the preset to the empty group utility. + iEmptyEnvironmentalReverbUtility->GetPresetL(iPresetIndex); + + CEnvironmentalReverb& audioEffect = + iEmptyEnvironmentalReverbUtility->EnvironmentalReverb(); + + + iReverbTime = audioEffect.DecayTime(); + iReverbLevel = + audioEffect.ReflectionsLevel() + audioEffect.RoomLevel(); + + TInt32 minLevel; + TInt32 maxLevel; + audioEffect.ReverbLevelRange(minLevel, maxLevel); + + iReverbMinLevel = minLevel; + iReverbMaxLevel = maxLevel; + + // Delete empty group utilities in order to save memory. + DeleteEmptyGroupUtilities(); + } + + LOG4( EJavaAMMS, EInfo, "CAMMSReverbControlGroup::PresetChangedL, values: %d, %d, %d %d", + iReverbTime, iReverbLevel, iReverbMinLevel, iReverbMaxLevel); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PresetChangedL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::InitializeL +// Finish initialization (after the 1st player is added) +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::InitializeL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::PrepareEmptyGroupUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::PrepareEmptyGroupUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PrepareEmptyGroupUtilitiesL +"); + + if (!iEmptyEnvironmentalReverbUtility) + { + CAMMSEffectControlGroup::PrepareEmptyGroupUtilitiesL(); + + iEmptyEnvironmentalReverbUtility = + CEnvironmentalReverbUtility::NewL(*iEmptyPlayerUtility); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::PrepareEmptyGroupUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::DeleteEmptyGroupUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::DeleteEmptyGroupUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::DeleteEmptyGroupUtilities +"); + + if (iEmptyPlayerUtility) + { + delete iEmptyEnvironmentalReverbUtility; + iEmptyEnvironmentalReverbUtility = NULL; + + CAMMSEffectControlGroup::DeleteEmptyGroupUtilities(); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::DeleteEmptyGroupUtilities -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::GetPresetNamesL +"); + + // Create empty group utilities for getting preset names. + PrepareEmptyGroupUtilitiesL(); + + TArray< TEfEnvironmentalReverbUtilityPreset > presetNames = + iEmptyEnvironmentalReverbUtility->Presets(); + + + TInt presetCount = presetNames.Count(); + + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + + // Delete empty group utilities in order to save memory. + DeleteEmptyGroupUtilities(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::GetPresetNamesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::CAMMSReverbControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSReverbControlGroup::CAMMSReverbControlGroup() + : CAMMSEffectControlGroup(KAMMSBaseReverbControl) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSReverbControlGroup::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::ConstructL +"); + + CAMMSEffectControlGroup::BaseConstructL(); + + TRAPD(err, SetPresetL(KAMMSBaseDefaultReverbPreset)); + + // The following code prevents build warning. + if (err != KErrNone) + { + ELOG1( EJavaAMMS, "AMMS::CAMMSReverbControlGroup::ConstructL, err %d", err); + } + + // Ignore the error so that using MMA and AMMS is possible. + // Error is visible so that "smallroom" preset is not activated. + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControlGroup::ConstructL -"); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/audioeffect/src/cammsreverbsourcecontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/audioeffect/src/cammsreverbsourcecontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,132 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for reverb source controls +* +*/ + + +// INCLUDE FILES +#include "cammsreverbsourcecontrolgroup.h" +#include "cammsbasereverbsourcecontrol.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSReverbSourceControlGroup* CAMMSReverbSourceControlGroup::NewLC() +{ + CAMMSReverbSourceControlGroup* self = + new(ELeave) CAMMSReverbSourceControlGroup; + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSReverbSourceControlGroup::~CAMMSReverbSourceControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::RoomLevel +// Gets the gain level of the reverberation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSReverbSourceControlGroup::RoomLevel() +{ + return iRoomLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::SetRoomLevelL +// Sets the gain level of the reverberation +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbSourceControlGroup::SetRoomLevelL(TInt aLevel) +{ + // Set room level to controls. + TInt count = ControlCount(); + + for (TInt i = 0; i < count; i++) + { + TypeSafeControl(i)->SetRoomLevelL(aLevel); + } + + iRoomLevel = aLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSBaseReverbSourceControl* +CAMMSReverbSourceControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast< CAMMSBaseReverbSourceControl* >(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSReverbSourceControlGroup::ClassName() +{ + return KAMMSReverbSourceControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::NotifyPlayerAddedL +// Called by PlayerRemoved when new player is added. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSReverbSourceControlGroup::NotifyPlayerAddedL( + CMMAPlayer* aPlayer, + CMMAControl* aControl) +{ + CAMMSControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSBaseReverbSourceControl* control = + static_cast(aControl); + + // set the current parameters + control->SetRoomLevelL(iRoomLevel); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::CAMMSReverbSourceControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSReverbSourceControlGroup::CAMMSReverbSourceControlGroup() + : CAMMSControlGroup(KAMMSBaseReverbSourceControl), + iRoomLevel(0) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControlGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSReverbSourceControlGroup::ConstructL() +{ + CAMMSControlGroup::ConstructL(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/inc/cammspancontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/inc/cammspancontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,111 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for panning controls +* +*/ + + +#ifndef CAMMSPANCONTROLGROUP_H +#define CAMMSPANCONTROLGROUP_H + +// INCLUDES +#include +#include "cammscontrolgroup.h" + +// CONSTANTS +_LIT(KAMMSPanControlClassName, ".amms.control.PanControl"); + +// FORWARD DECLARATIONS +class CAMMSPanControl; + +// CLASS DECLARATION + +/** + * Group for panning controls + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSPanControlGroup): public CAMMSControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSPanControlGroup* NewLC(); + + /** + * Destructor. + */ + ~CAMMSPanControlGroup(); + +public: // New functions + + /** + * Gets the current panning set. + * + * @return The current panning. + */ + TInt Pan(); + + /** + * Sets the panning using a linear point scale with values between -100 + * and 100. 0 represents panning for both channels, -100 full panning to + * the left and 100 full panning to the right. If the given panning + * value is less than -100 or greater than 100, the panning will be set + * to -100 or 100, respectively. + * + * @param aPan The new panning to be set. + * @param aSetPan Returned pan that has been set. + */ + void SetPanL(TInt aPan, TInt& aSetPan); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSPanControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base classes + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: + /* + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + */ + CAMMSPanControlGroup(); + +private: //Data + + // the actual volume for this control group + TInt iPan; +}; + +#endif // CAMMSPANCONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/inc/cammsvolumecontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/inc/cammsvolumecontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for volume controls +* +*/ + + +#ifndef CAMMSVOLUMECONTROLGROUP_H +#define CAMMSVOLUMECONTROLGROUP_H + +// INCLUDES +#include +#include "cammscontrolgroup.h" + +// FORWARD DECLARATIONS +class CAMMSVolumeControl; + +// CONSTANTS +_LIT(KAMMSVolumeControlClassName, ".amms.control.VolumeControl"); + +// CLASS DECLARATION + +/** + * Group for volume controls. + * This volume control group can be used with many CAMMSVolumeControl + * instances. Controls that belong to this group are identified with + * aClassName parameter given to the NewL / NewLC method. + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSVolumeControlGroup): public CAMMSControlGroup +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aControlName Class name that identifies controls + * belonging tothis control group. + */ + static CAMMSVolumeControlGroup* NewLC(const TDesC& aControlName); + + /** + * Destructor. + */ + ~CAMMSVolumeControlGroup(); + +public: // New functions + /** + * Sets the current volume. + * + * @param aVolume Volume to be set. + */ + void SetVolumeL(TInt aVolume); + +private: // New functions + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + CAMMSVolumeControl* TypeSafeControl(TInt aIndex) const; + +public: // Functions from base class + /** + * Returns class name that identifies this control group. + * + * @return Control group name. + */ + const TDesC16& ClassName(); + +protected: // From + /** + * Called by when a new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + void NotifyPlayerAddedL(CMMAPlayer *aPlayer, CMMAControl* aControl); + +private: + /** + * C++ default constructor. + * @param aControlName Class name that identifies controls + * belonging tothis control group. + */ + CAMMSVolumeControlGroup(const TDesC& aControlName); + +protected: //Data + + TInt iVolume; +}; + +#endif // CAMMSVOLUMECONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/src/cammspancontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/src/cammspancontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for panning controls +* +*/ + + +// INCLUDE FILES +#include "cammspancontrolgroup.h" +#include "cammspancontrol.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPanControlGroup* CAMMSPanControlGroup::NewLC() +{ + CAMMSPanControlGroup* self = new(ELeave) CAMMSPanControlGroup; + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; + +} + +// Destructor. +CAMMSPanControlGroup::~CAMMSPanControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::Pan +// Gets the current panning set. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSPanControlGroup::Pan() +{ + return iPan; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::SetPanL +// Sets the panning value +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPanControlGroup::SetPanL(TInt aPan, TInt& aSetPan) +{ + TInt groups = ControlCount(); + TInt retVal = aPan; + + for (TInt i = 0; i < groups; i++) + { + retVal = TypeSafeControl(i)->SetPanL(aPan); + } + + iPan = retVal; + + aSetPan = retVal; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSPanControl* CAMMSPanControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSPanControlGroup::ClassName() +{ + return KAMMSPanControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPanControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + CAMMSControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSPanControl* control = static_cast(aControl); + + // set the current parameters + control->SetPanL(iPan); +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControlGroup::CAMMSPanControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPanControlGroup::CAMMSPanControlGroup() + : CAMMSControlGroup(KAMMSPanControl) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/ammscontrol/src/cammsvolumecontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/ammscontrol/src/cammsvolumecontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,112 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for volume controls +* +*/ + + +// INCLUDE FILES +#include "cammsvolumecontrolgroup.h" +#include "cammsvolumecontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSVolumeControlGroup* CAMMSVolumeControlGroup::NewLC(const TDesC& aControlName) +{ + CAMMSVolumeControlGroup* self = new(ELeave) CAMMSVolumeControlGroup( + aControlName); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSVolumeControlGroup::~CAMMSVolumeControlGroup() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlGroup::SetVolumeL +// Sets the current volume set. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSVolumeControlGroup::SetVolumeL(TInt aVolume) +{ + TInt controls = ControlCount(); + for (TInt i = 0; i < controls; i++) + { + TypeSafeControl(i)->SetVolumeL(aVolume); + } + + iVolume = aVolume; +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlGroup::TypeSafeControl +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSVolumeControl* +CAMMSVolumeControlGroup::TypeSafeControl(TInt aIndex) const +{ + return static_cast< CAMMSVolumeControl* >(Control(aIndex)); +} + +// ----------------------------------------------------------------------------- +// TDesC16& CAMMSVolumeControlGroup::ClassName +// Returns class name that identifies this control group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +const TDesC16& CAMMSVolumeControlGroup::ClassName() +{ + return KAMMSVolumeControlClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlGroup::NotifyPlayerAddedL +// Called by when a new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSVolumeControlGroup::NotifyPlayerAddedL( + CMMAPlayer *aPlayer, + CMMAControl* aControl) +{ + CAMMSControlGroup::NotifyPlayerAddedL(aPlayer, aControl); + + CAMMSVolumeControl* control = + static_cast< CAMMSVolumeControl* >(aControl); + + // set the current parameters + control->SetVolumeL(iVolume); +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlGroup::CAMMSVolumeControlGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSVolumeControlGroup::CAMMSVolumeControlGroup(const TDesC& aControlName) + : CAMMSControlGroup(aControlName) +{ + iVolume = KAMMSMAXVolume; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/build/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + audio.samplerates=8000 16000 + audio3d.simultaneouslocations=4 + microedition.amms.version=1.1 + supports.mediacapabilities=music audio3d + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/build/bwins/javaammsu.def --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/build/bwins/javaammsu.def Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,4 @@ +EXPORTS + ?jni_lookup@@YAP6AXXZPBD@Z @ 1 NONAME ; void (*)(void) jni_lookup(char const *) + ?NewL@CTimeOutTimer@@SAPAV1@HAAVMTimeOutNotify@@@Z @ 2 NONAME ; class CTimeOutTimer * CTimeOutTimer::NewL(int, class MTimeOutNotify &) + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/build/eabi/javaammsu.def --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/build/eabi/javaammsu.def Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,6 @@ +EXPORTS + _Z10jni_lookupPKc @ 1 NONAME + _ZN13CTimeOutTimer4NewLEiR14MTimeOutNotify @ 2 NONAME + _ZTI13CTimeOutTimer @ 3 NONAME + _ZTV13CTimeOutTimer @ 4 NONAME + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/build/javaamms.pro --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/build/javaamms.pro Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,107 @@ +# +# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +# All rights reserved. +# This component and the accompanying materials are made available +# under the terms of "Eclipse Public License v1.0" +# which accompanies this distribution, and is available +# at the URL "http://www.eclipse.org/legal/epl-v10.html". +# +# Initial Contributors: +# Nokia Corporation - initial contribution. +# +# Contributors: +# +# Description: +# + +TARGET=javaamms +TEMPLATE=lib +CONFIG += omj java stl + +include(../../../inc/build_defines.pri) + +DEFINES += RD_JAVA_VOLUME_CONTROL +DEFINES += RD_JAVA_OMA_DRM_V2 +DEFINES += __JAVA_JSR234_TUNER + + +INCLUDEPATH += /epoc32/include/mmf/common \ + /epoc32/include/caf \ + ../ammscontrol/inc \ + ../ammscontrol/audio3D/inc \ + ../ammscontrol/audioeffect/inc \ + ../mmacontrol/inc \ + ../module/inc \ + ../src_tuner/native/external_include \ + ../src_tuner/native/inc \ + ../ammscontrol/inc \ + ../../mmapi_qt/baseline/inc \ + ../../mmapi_qt/utils/inc \ + /epoc32/include/mw/Qt + + +SOURCES += ../ammscontrol/src/*.cpp \ + ../ammscontrol/audio3D/src/*.cpp \ + ../ammscontrol/audioeffect/src/*.cpp \ + ../jni/src/*.cpp \ + ../mmacontrol/src/*.cpp \ + ../module/src/*.cpp \ + ../../mmapi_qt/utils/src/*.cpp + +contains(PROJECT_DEFINES,RD_JAVA_HTTP_EMC_ENABLED) { + INCLUDEPATH += ../../mmapi_qt/baseline/inc.emc \ + ../mmacontrol/inc.emc \ + + SOURCES += ../mmacontrol/src.emc/*.cpp + + + LIBS += -lEnhancedMediaClient \ + -lmmfdevsound +} +else{ + INCLUDEPATH += ../../mmapi_qt/baseline/inc.mmf \ + ../mmacontrol/inc.mmf \ + + SOURCES += ../mmacontrol/src.mmf/*.cpp + +} + +contains(PROJECT_DEFINES,RD_JAVA_NGA_ENABLED) { + INCLUDEPATH += ../../mmapi_qt/baseline/inc.nga +} +else { + INCLUDEPATH += ../../mmapi_qt/baseline/inc.dsa +} + + +LIBS += -lAudioEqualizerEffect \ + -lAudioEqualizerUtility \ + -lCustomCommandUtility \ + -lDistanceAttenuationEffect \ + -lDopplerBase \ + -lEnvironmentalReverbEffect \ + -lEnvironmentalReverbUtility \ + -lListenerDopplerEffect \ + -lListenerLocationEffect \ + -lListenerOrientationEffect \ + -lLocationBase \ + -lMediaClientAudio \ + -lOrientationBase \ + -lRoomLevelEffect \ + -lSourceDopplerEffect \ + -lSourceLocationEffect \ + -lStereoWideningEffect \ + -lStereoWideningUtility \ + -lbafl \ + -lcentralrepository \ + -lestor \ + -leuser \ + -lflogger \ + -ljavamobilemedia \ + -lmidiclient \ + -lmmfcontrollerframework \ + -lmmfstandardcustomcommands \ + -laudiooutputrouting \ + -laccmonitor + +include(../../../build/omj.pri) diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/AMMSError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/AMMSError.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms; + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.NativeError; + +/** + * This class contains general helper methods for error conversion + * between native side and java side. + */ +public final class AMMSError +{ + /** + * Private, because this class is not intended to be constructed. + */ + private AMMSError() + { + } + + /** + * This method throws IllegalStateException if error code is + * KErrNotReady (-18) + * + * @param aNativeErrorCode Native error code. + */ + static public void checkIllegalState(int aNativeErrorCode) + { + if (aNativeErrorCode == NativeError.KErrNotReady) + { + throw new IllegalStateException(); + } + } + + /** + * This method throws MediaException if checked native error + * code is below KErrNone. + * @param aNativeErrorCode Native error code. + */ + static public void checkMediaException(int aNativeErrorCode) + throws MediaException + { + NativeError.checkOOMOnly(aNativeErrorCode); + if (aNativeErrorCode < NativeError.KErrNone) + { + throw new MediaException(); + } + } + /** + * @param aObject Object to be checked. + */ + static public void checkArgument(Object aObject) + { + if (aObject == null) + { + throw new IllegalArgumentException(); + } + } + + /** + * Checks for basic native error codes that map to standard Java + * exceptions and throws the exception if the error code matches. + * Otherwise throws basic Error class. + * @param aNativeErrorCode Native error code. + */ + static public void check(int aNativeErrorCode) + { + NativeError.check(aNativeErrorCode); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/AMMSPlugin.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/AMMSPlugin.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Adds PriorityControl when a player is created. +* +*/ + +package com.nokia.amms; + +import com.nokia.amms.control.PriorityControl; +import com.nokia.mid.impl.media.AudioOutputControl; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.PlayerImpl; +import com.nokia.microedition.media.PlugIn; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.NativeError; +import javax.microedition.media.MediaException; +import javax.microedition.media.protocol.DataSource; +import java.io.IOException; + + +// CLASS DEFINITION +/** + * MMA Manager calls AMMSPlugin class when a new player is created. + * The plugin adds PriorityControl to the created player. + */ +public class AMMSPlugin implements PlugIn +{ + private final String PRIORITY_CONTROL = + "javax.microedition.amms.control.PriorityControl"; + private final String AUDIO_OUTPUT_CONTROL = + "com.nokia.mid.media.AudioOutputControl"; + + /** + * Default constructor. + */ + public AMMSPlugin() + { + } + + /** + * From PlugIn. Empty implementation. + */ + public String[] getSupportedContentTypes(String aProtocol) + { + return new String[ 0 ]; + } + + /** + * From PlugIn. Empty implementation. + */ + public String[] getSupportedProtocols(String aContentType) + { + return new String[ 0 ]; + } + + /** + * From PlugIn. Empty implementation. + */ + public InternalPlayer createPlayer(DataSource aDataSource) + throws MediaException, IOException + { + return null; + } + + /** + * From PlugIn. + */ + public void preparePlayer(InternalPlayer aPlayer) throws MediaException + { + // Do not add PriorityControl if the player is not derived from + // PlayerImpl (because native player handle is needed). + if (aPlayer instanceof PlayerImpl) + { + PlayerImpl player = (PlayerImpl)aPlayer; + + int eventSource = ManagerImpl.getEventSource(); + createAndAddPriorityControlToPlayer(eventSource, player); + createAndAddAudioOutputControlToPlayer(eventSource, player); + } + + } + /** + * Create and add priority control to player + */ + public void createAndAddPriorityControlToPlayer(int eventSource, PlayerImpl aPlayer) + { + // Create native PriorityControl and add it to the native player. + int nativePriorityControl = _createNativePriorityControl( + eventSource, aPlayer.getPlayerHandle()); + + NativeError.check(nativePriorityControl); + + + // Create java side control. + PriorityControl priorityControl = new PriorityControl(aPlayer); + priorityControl.initControl(eventSource, nativePriorityControl, + null); // This control does not belong to any module. + + aPlayer.addControl(priorityControl, PRIORITY_CONTROL); + } + /** + * Create and add AudioOutput control to player + */ + public void createAndAddAudioOutputControlToPlayer(int eventSource, PlayerImpl aPlayer) + { + // Create native AudioOutputControl and add it to the native player. + int nativeAudioOutputControl = _createNativeAudioOutputControl( + eventSource, aPlayer.getPlayerHandle()); + NativeError.check(nativeAudioOutputControl); + + + // Create java side control. + AudioOutputControl audioOutputControl = new AudioOutputControl(aPlayer); + audioOutputControl.initControl(eventSource, nativeAudioOutputControl, + null); // This control does not belong to any module. + audioOutputControl.SetAudioOutputToNative(); + aPlayer.addControl(audioOutputControl, AUDIO_OUTPUT_CONTROL); + } + + /** + * Creates native PriorityControl and adds it + */ + private static native int _createNativePriorityControl( + int aEventSource, int aPlayerHandle); + /** + * Creates native AudioOutputControl and adds it + */ + private static native int _createNativeAudioOutputControl( + int aEventSource, int aPlayerHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/ControlContainer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/ControlContainer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,293 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Container for controls. +* +*/ + +package com.nokia.amms; + +import javax.microedition.media.Control; +import javax.microedition.media.Controllable; +import com.nokia.amms.ModuleBase; +import com.nokia.amms.control.ControlImpl; +import com.nokia.mj.impl.utils.Logger; +import java.util.Hashtable; +import java.util.Enumeration; + +/** + * ControlContainer class creates java control objects according to a classname + * which is got from native control object. Created controls are accessible + * through Controllable interface which is implemented in this class. + */ +public class ControlContainer implements Controllable +{ + /** + * Default control package. Used when getting control with + * getControl method which appends default control package if package is + * not specified. + */ + static final String CONTROL_DEFAULT_PACKAGE = + "javax.microedition.media.control."; + + /** + * Package where control implementation are. + */ + static final String PRIVATE_PACKAGE = "com.nokia"; + + /** + * Hashtable containing controls identified with a full package name. + * All control names starts with iDefaultPackage. + */ + private final Hashtable iControls = new Hashtable(); + + /** + * Creates new ControlContainer. + */ + private ControlContainer() + { + } + + /** + * Create new ControlContainer and populates the controls. + * + * @param aDefaultPackege Default control package. Used when getting control + * with getControl method which appends default control package if package + * is not specified. + * @param aEventSourceHandle Handle to native event source. + * @param aNativeHandle Handle to native control source. + * @param aModule Module where the controls belong to. + */ + public static final ControlContainer populateControls( + int aEventSourceHandle, + int aNativeHandle, + ModuleBase aModule) + { + ControlContainer container = new ControlContainer(); + + // Get amount of controls in native object. + int controlCount = _getControlsCount(aEventSourceHandle, + aNativeHandle); + + // Create java object for each native objects. + for (int i = 0; i < controlCount; i++) + { + // Get handle to native object at index i + int controlHandle = _getControlHandle(aEventSourceHandle, + aNativeHandle, + i); + + // Get controls class name which will be used to create java object + String className = _getControlClassName(aEventSourceHandle, + controlHandle); + + // create java instance + Control control = createControl(className, + controlHandle, + aEventSourceHandle, + aModule); + + // Add package if it does not exists + if (className.indexOf('.') < 0) + { + className = CONTROL_DEFAULT_PACKAGE + className; + } + container.iControls.put(className, control); + } + + // population succeed, return created collection + return container; + } + + /** + * Implements method defined in javax.microedition.media.Controllable. + * + * @see javax.microedition.media.Controllable + * @param aControlType the class name of the Control. The class name should + * be given either as the fully-qualified name of the class; or if the + * package of the class is not given, the package + * javax.microedition.media.control is assumed. + * @return the object that implements the control, or null. + */ + public Control getControl(String aControlType) + { + if (aControlType == null) + { + Logger.ELOG(Logger.EJavaMMAPI, + "ControlContainer::getControl parameter was null"); + throw new IllegalArgumentException("argument was null"); + } + + String controlType = aControlType; + + // check if package name exists + if (controlType.indexOf(".") == -1) + { + // add package name + controlType = CONTROL_DEFAULT_PACKAGE + aControlType; + } + Control control = (Control)iControls.get(controlType); + + // If control does not exists with default name, check if there is + // is a control with same type ( extends the given class name ). + if (control == null) + { + try + { + // try to create class for control + Class controlClass = Class.forName(controlType); + + Enumeration elements = iControls.elements(); + + // search if any control is same type that requested control + while (elements.hasMoreElements() && + control == null) + { + Control tmpControl = (Control)elements.nextElement(); + if (controlClass.isInstance(tmpControl)) + { + // control is found + control = tmpControl; + } + } + } + catch (ClassNotFoundException cnfe) // the class could not be found + { + // Exception is ignored and null is returned from this method + Logger.ELOG(Logger.EJavaMMAPI, + "ControlContainer::getControl ", + cnfe); + } + catch (Error e) // the function failed for any other reason. + { + // Error is ignored and null is returned from this method + Logger.ELOG(Logger.EJavaMMAPI, + "ControlContainer::getControl ", + e); + } + } + return control; + } + + /** + * Implements method defined in javax.microedition.media.Controllable. + * + * @see javax.microedition.media.Controllable + * @return the collection of Control objects. + */ + public Control[] getControls() + { + Control[] controls = new Control[ iControls.size()]; + Enumeration elements = iControls.elements(); + int i = 0; + // Put all controls to array + while (elements.hasMoreElements()) + { + controls[ i ] = (Control)elements.nextElement(); + i++; + } + return controls; + } + + /** + * Invalidates the controls stored in this container. + * After this using controls in Java side will throw + * RuntimeException. + */ + public void invalidateControls() + { + Enumeration elements = iControls.elements(); + + while (elements.hasMoreElements()) + { + // All controls are instances of ControlImpl class. + ControlImpl control = (ControlImpl)elements.nextElement(); + control.invalidateControl(); + } + } + + /** + * Creates new Control instance. + * All control classes must be in iPrivatePackage package and + * extend the ControlImpl base class. Created control is initialized + * with native control handle and eventsource handle. + * + * @param aClassName Control's class name without the package. + * @param aControlHandle Handle to native control. + * @param aModule Module where the control belongs to. + * @return created control + */ + static private final Control createControl(String aClassName, + int aControlHandle, + int aEventSourceHandle, + ModuleBase aModule) + { + ControlImpl control = null; + + // Try to make control instance. If instantion fails, it is an internal + // error and can only occur in development time. + try + { + Class controlClass = + Class.forName(PRIVATE_PACKAGE + + aClassName); + control = (ControlImpl)controlClass.newInstance(); + control.initControl(aEventSourceHandle, aControlHandle, aModule); + } + catch (InstantiationException ie) + { + throw new OutOfMemoryError(ie.getMessage()); + } + catch (IllegalAccessException iae) + { + throw new OutOfMemoryError(iae.getMessage()); + } + catch (ClassNotFoundException cnfe) + { + throw new OutOfMemoryError(cnfe.getMessage()); + } + return control; + } + + + /** + * Return the amount of controls in native control source. + * + * @param aEventSourceHandle Handle to native event source. + * @param aNativeHandle Handle to native control source object. + */ + private static native int _getControlsCount(int aEventSourceHandle, + int aNativeHandle); + + /** + * Return native handle to control at specified index. + * + * @param aEventSourceHandle Handle to native event source. + * @param aNativeHandle Handle to native control source object. + * @param aControlIndex Control's index. + */ + private static native int _getControlHandle(int aEventSourceHandle, + int aNativeHandle, + int aControlIndex); + /** + * Returns the control class name that can be used to instantiate Java + * object. + * + * @param aEventSourceHandle Handle to native event source. + * @param aControlHandle Handle to native control. + */ + private static native String _getControlClassName(int aEventSourceHandle, + int aControlHandle); + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/EffectModuleImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/EffectModuleImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms; + +import javax.microedition.amms.EffectModule; +import javax.microedition.media.Control; + +/** + * EffectModuleImpl provides functionality defined in EffectModule. + * This class is used through EffectModule interface which implements the + * Module interface and does not define any new methods. Methods defined in + * Module are implemented in ModuleBase class. + * Can be accessed only from com.nokia.amms package. + */ +class EffectModuleImpl extends ModuleBase + implements EffectModule +{ + /** + * Constructs new EffectModuleImpl instance. + * Package private. + * @param aEventSourceHandle Handle to event source. + * @param aNativeHandle Handle to corresponding native object. + * @param aManagerHandle Handle to native global manager. + */ + EffectModuleImpl(int aEventSourceHandle, + int aNativeHandle, + int aManagerHandle) + { + super(aEventSourceHandle, + aNativeHandle, + aManagerHandle); + } + + /** + * Obtain the object that implements the specified Control interface. + * + * @see javax.microedition.media.Controllable + * @param aControlType the class name of the Control. The class name should + * be given either as the fully-qualified name of the class; or if the + * package of the class is not given, the package + * javax.microedition.media.control is assumed. + * @return the object that implements the control, or null if no objects + * implement the control or if there is no players in the module. + */ + public Control getControl(String aControlType) + { + if (iPlayers.size() > 0) + { + // Delegate to ControlContainer + return iControls.getControl(aControlType); + } + // An EffectModule, that has no Players attached to it, does not + // provide any Controls. + else + { + return null; + } + } + + /** + * Obtain the collection of Controls. + * + * @see javax.microedition.media.Controllable + * @return the collection of Control objects or a zero length array if + * there is no controls or players in the module. + */ + public Control[] getControls() + { + if (iPlayers.size() > 0) + { + // Delegate to ControlContainer + return iControls.getControls(); + } + // An EffectModule, that has no Players attached to it, does not + // provide any Controls. + else + { + return new Control[ 0 ]; + } + + + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/GlobalManagerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/GlobalManagerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,372 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.amms; + +import javax.microedition.media.MediaException; +import javax.microedition.amms.EffectModule; +import javax.microedition.amms.SoundSource3D; +import javax.microedition.amms.MediaProcessor; +import javax.microedition.media.Manager; +import java.util.Vector; + +/** + * GlobalManager implementation used by + * javax.microedition.amms.GlobalManager. + */ +public class GlobalManagerImpl extends ModuleBase +{ + /** + * There is no supported media processor input types. + */ + private static final String[] SUPPORTED_MEDIA_PROCESSOR_INPUT_TYPES = + new String[ 0 ]; + + // Constants needed when getting supported player content types. + private static final String AUDIO_STRING = "audio"; + private static final String VIDEO_STRING = "video"; + private static final String CAPTURE_STRING = "capture"; + private static final String DEVICE_STRING = "device"; + private static final String PROTOCOL_SEPARATOR = "://"; + private static final char MEDIA_SEPARATOR = '/'; + + /** + * Singleton instance. + */ + static private GlobalManagerImpl iInstance; + + /** + * Implements Spectator functionality. + */ + private SpectatorImpl iSpectator; + + /** + * Private constructor not to allow direct construction, because + * this class is singleton. + */ + private GlobalManagerImpl(int aEventSourceHandle) + { + com.nokia.mj.impl.rt.support.Jvm.loadSystemLibrary("javaamms"); + + iEventSourceHandle = aEventSourceHandle; + + // Create native instance + iModuleHandle = _createGlobalManager(iEventSourceHandle); + + + if (iModuleHandle < 0) + { + // Could not create native object + throw new OutOfMemoryError(); + } + } + + /** + * Creates static GlobalManagerImpl instance. Instance can be obtained + * with getInstance method. + * @param aEventSourceHandle Handle to native event source. + */ + public static void invoke(int aEventSourceHandle) + { + // create static instance + iInstance = new GlobalManagerImpl(aEventSourceHandle); + } + + /** + * Returns static GlobalManagerImpl instance. This method will be called + * from GlobalManager's static block when it is loaded for the first time. + * @return GlobalManagerImpl instance + */ + public static GlobalManagerImpl getInstance() + { + if (iInstance == null) + { + // GlobalManagerImpl is not initialized because iInstance is null. + // Invoke MMA1.1 by calling one of Manager's static methods. + // MMA will invoke its invoke listener that will result a call to + // GlobalManagerImpl::invoke method which creates static global + // manager instance. + Manager.getSystemTimeBase(); + } + + // if spectator isn't null init is already called + if (iInstance.iSpectator == null) + { + iInstance.init(); + } + return iInstance; + } + + /** + * Finalizes GlobalManagerImpl's initialization. + * This method creates native global controls and corresponding Java + * controls. + */ + private void init() + { + // Initialize native global manager instance. + int err = _init(iInstance.iEventSourceHandle, + iInstance.iModuleHandle); + + + // Initialize super class which will add global controls + init(iEventSourceHandle, iModuleHandle); + + if (err < 0) + { + // Init failed. AMMS functionality cannot be used. + throw new OutOfMemoryError(); + } + int handle = _createSpectator(iEventSourceHandle, iModuleHandle); + if (handle < 0) + { + // Could not create native object + throw new OutOfMemoryError(); + } + + // Create Java object for native spectator + iSpectator = new SpectatorImpl(iEventSourceHandle, handle); + } + + /** + * Creates an EffectModule. + * + * @throws MediaException if creation of EffectModule + * is not supported. + * @return An EffectModule object that may be used to group + * Players. + */ + public EffectModule createEffectModule() throws MediaException + { + int handle = _createEffectModule(iEventSourceHandle, iModuleHandle); + if (handle < 0) + { + throw new MediaException(); + } + return new EffectModuleImpl(iEventSourceHandle, + handle, + iModuleHandle); + } + + /** + * Creates a SoundSource3D. + * + * @throws MediaException if creation of SoundSource3D + * is not supported. + * @return A SoundSource3D object that represents + * a virtual sound source and that may be used to group + * Players. + */ + public SoundSource3D createSoundSource3D() throws MediaException + { + int handle = _createSoundSource3D(iEventSourceHandle, iModuleHandle); + if (handle < 0) + { + throw new MediaException(); + } + return new SoundSource3DImpl(iEventSourceHandle, + handle, + iModuleHandle); + } + + /** + * Gets the supported player content types that can be added + * to a SoundSource3D. + * {@link javax.microedition.amms.control.AudioFormatControl} + * specifies constants for content types commonly used with + * SoundSource3D. + * + * @return a list of content types that can be used to create + * Players supported by SoundSource3D + * (e.g. "audio/midi") and of device and capture locators that can + * be used to create Players supported by + * SoundSource3D (e.g. "capture://radio") + */ + public String[] getSupportedSoundSource3DPlayerTypes() + { + Vector resultVector = new Vector(); + + // Get content types (e.g. audio/midi) + playerTypes(null, resultVector); + + // Get device locators (e.g. "device://video) + playerTypes(DEVICE_STRING, resultVector); + + + // Convert the vector to string array. + + int resultLength = resultVector.size(); + + String[] result = new String[ resultLength ]; + + for (int i = 0; i < resultLength; i++) + { + result[ i ] = (String)resultVector.elementAt(i); + } + + return result; + } + + /** + * Returns player types that supports the given protocol. + * @param aProtocol Protocol (e.g. capture) or null if all protocols are used. + * @param aResultVector Vector where the result is stored. + */ + private void playerTypes(String aProtocol, Vector aResultVector) + { + String[] contentTypes = Manager.getSupportedContentTypes(aProtocol); + + int contents = contentTypes.length; + + for (int i = 0; i < contents; i++) + { + String contentType = contentTypes[ i ]; + + // Select those types that are supported by AMMS. + if (contentType.startsWith(AUDIO_STRING + MEDIA_SEPARATOR) || + contentType.startsWith(VIDEO_STRING + MEDIA_SEPARATOR)) + { + String playerType = contentType; + + // Add the protocol string if a specific one is used. + if (aProtocol != null) + { + int endIndex = contentType.indexOf(MEDIA_SEPARATOR); + if (endIndex >= 0) + { + contentType = contentType.substring(0, endIndex); + } + + playerType = aProtocol + PROTOCOL_SEPARATOR + contentType; + } + + // Add the type to the vector. + if (!aResultVector.contains(playerType)) + { + aResultVector.addElement(playerType); + } + } + } + } + + /** + * Gets the Spectator, which represents the listener + * in the virtual acoustical space. + * + * @return the Spectator, which represents the listener + * in the virtual acoustical space + */ + public SpectatorImpl getSpectator() + { + return iSpectator; + } + + /** + * Creates a MediaProcessor object. Content type is passed + * as a MIME type as specified in javax.microedition.media.Manager. + * {@link FormatControl}, + * {@link javax.microedition.amms.control.ContainerFormatControl}, + * {@link javax.microedition.amms.control.VideoFormatControl}, + * {@link javax.microedition.amms.control.AudioFormatControl} + * and {@link javax.microedition.amms.control.ImageFormatControl} specify + * constants for a set of commonly used content types. + * + * + * @param contentType the content type of the source data to be processed. + * @throws MediaException if a MediaProcessor could + * not be created for the given content type. + * @return An instance of MediaProcessor + */ + public MediaProcessor createMediaProcessor(String aContentType) + throws MediaException + { + // MediaProcessor is not supported. + throw new MediaException(); + } + + /** + * Obtain the handle of the GlobalManager. + * + * @return the module handle. + */ + public static int getHandle() + { + if (iInstance == null) + { + // GlobalManagerImpl is not initialized because iInstance is null. + // Invoke MMA1.1 by calling one of Manager's static methods. + // MMA will invoke its invoke listener that will result a call to + // GlobalManagerImpl::invoke method which creates static global + // manager instance. + Manager.getSystemTimeBase(); + } + + return iInstance.iModuleHandle; + } + + /** + * Gets the supported MediaProcessor input content types. + * + * @return Supported MediaProcessor input content types. + */ + public String[] getSupportedMediaProcessorInputTypes() + { + return SUPPORTED_MEDIA_PROCESSOR_INPUT_TYPES; + } + + /** + * @param aEventSourceHandle Handle to native event source. + * @return Handle to native object or an error code. + */ + private static native int _createGlobalManager(int aEventSourceHandle); + + /** + * Initializes native object. + * + * @param aEventSourceHandle Handle to native event source. + * @param aGlobalManagerHandle Handle to native global manager. + * @return 0 if success or an error code. + */ + private static native int _init(int aEventSourceHandle, + int aGlobalManagerHandle); + + /** + * @param aEventSourceHandle Handle to native event source. + * @param aGlobalManagerHandle Handle to native global manager. + * @return Handle to native object or an error code. + */ + private static native int _createEffectModule(int aEventSourceHandle, + int aGlobalManagerHandle); + + /** + * @param aEventSourceHandle Handle to native event source. + * @param aGlobalManagerHandle Handle to native global manager. + * @return Handle to native object or an error code. + */ + private static native int _createSoundSource3D(int aEventSourceHandle, + int aGlobalManagerHandle); + + /** + * @param aEventSourceHandle Handle to native event source. + * @param aGlobalManagerHandle Handle to native global manager. + * @return Handle to native object or an error code. + */ + private static native int _createSpectator(int aEventSourceHandle, + int aGlobalManagerHandle); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/MMAInvokeListenerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/MMAInvokeListenerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is invoked when MMA event source is created. +* +*/ + +package com.nokia.amms; + +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.MMAInvokeListener; + +/** + * This class will be created and invoked when MMA event source is created. + */ +public class MMAInvokeListenerImpl implements MMAInvokeListener +{ + /** + * Public empty constructor to used from MMA. + */ + public MMAInvokeListenerImpl() + { + } + + /** + * From MMAInvokeListener. Invokes GlobalManager and adds AMMSPlugin to + * the MMA Manager. + * @param aEventSourceHandle Handle to native MMA event source. + */ + public void notifyInvoke(int aEventSourceHandle) + { + // Create GlobalManagerImpl static instance. + GlobalManagerImpl.invoke(aEventSourceHandle); + + // Add AMMSPlugin to MMA Manager. The plugin is called every time + // a player is created. + ManagerImpl.getInstance().addPlugIn(new AMMSPlugin()); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/ModuleBase.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/ModuleBase.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,400 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for modules. +* +*/ + +package com.nokia.amms; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Player; +import javax.microedition.media.PlayerListener; +import javax.microedition.media.Control; +import com.nokia.microedition.media.PlayerImpl; + +import com.nokia.microedition.media.NativeError; +import java.util.Vector; +import com.nokia.mj.impl.rt.support.Finalizer; + +/** + * Base class for all modules. + */ +public class ModuleBase implements PlayerListener +{ + /** + * Player is already in some other module. + */ + private static final int PLAYER_ALREADY_IN_MODULE = -123; + private static final int MIXING_NOT_SUPPORTED = -1234; + + /** + * Current implementation does not support midi channels in modules. + */ + private static final String MIDI_CHANNELS_NOT_SUPPORTED = + "Adding MIDI channels is not supported."; + + /** + * Contains all controls in the module. Package private. + */ + ControlContainer iControls; + + /** + * Handle to native implemantation. Package private. + */ + int iModuleHandle; + + /** + * Handle to native event source. Package private. + */ + int iEventSourceHandle; + + /** + * Handle to native global mabager. Package private. + * Used to dispose native module. + */ + int iManagerHandle; + + /** + * Java-side players. Package private. + */ + Vector iPlayers = new Vector(); + + private Finalizer mFinalizer; + + /** + * Constructs new Module base. Package private. + * Module is registered for the finalization. + * + * @param aEventSourceHandle Handle to event source. + * @param aModuleHandle Handle to corresponding native object. + * @param aManagerHandle Handle to native global manager. + * @param aMana + */ + ModuleBase(int aEventSourceHandle, + int aModuleHandle, + int aManagerHandle) + { + // registeredFinalize() method is called when this class is finalized. + mFinalizer = new Finalizer() + { + public void finalizeImpl() + { + doFinalize(); + } + }; + + iManagerHandle = aManagerHandle; + + init(aEventSourceHandle, + aModuleHandle); + } + + /** + * Constructs new Module base. Package private. + * Module is not registered for the finalization. + */ + ModuleBase() + { + } + + /** + * Initialises module base. This method must be called before module can be + * used. Package private. + * + * @param aEventSourceHandle Handle to event source. + * @param aModuleHandle Handle to corresponding native object. + */ + final void init(int aEventSourceHandle, + int aModuleHandle) + { + iEventSourceHandle = aEventSourceHandle; + iModuleHandle = aModuleHandle; + + iControls = ControlContainer.populateControls( + iEventSourceHandle, + iModuleHandle, + this); + } + + private void doFinalize() + { + if (mFinalizer != null) + { + registeredFinalize(); + mFinalizer = null; + } + } + + /** + * This method is called when garbage collector finalizes this object. + */ + void registeredFinalize() + { + iControls.invalidateControls(); + + _dispose(iManagerHandle, + iModuleHandle); + } + + /** + *

Adds an individual MIDI channel of a MIDI Player + * to the module.

+ * + *

If the played MIDI file or MIDI stream contains information + * that is contradictory + * to what is specified via this Module the behavior + * will be implementation specific.

+ * + * @param player The MIDI Player whose channel is to be added. + * @param channel The channel of the given Player to be added. + * The range is 0-15. + * + * @throws MediaException if adding of channels is not supported. + * @throws IllegalArgumentException if the player is not a MIDI player or the player is null + * or if the player is already part of the module. + * @throws IllegalArgumentException if channel > 15 or channel < 0. + * @throws IllegalStateException if some Player + * in the Module tree is not in + * UNREALIZED or REALIZED state. + */ + public void addMIDIChannel(Player aPlayer, int aChannel) + throws MediaException + { + // Midi channels are not supported modules. + throw new MediaException(MIDI_CHANNELS_NOT_SUPPORTED); + } + + /** + * Removes a MIDI channel from the module. + * + * All channels can be removed at once by {@link #removePlayer removePlayer} + * + * @param player The MIDI Player whose channel is to be removed. + * @param channel The channel of the given MIDI Player + * to be removed. + * @throws IllegalArgumentException if the given channel is + * not part of the Module or if the player is null. + * @throws IllegalStateException if some Player + * in the Module tree is not in + * UNREALIZED or REALIZED state + */ + public void removeMIDIChannel(Player aPlayer, int aChannel) + { + // Midi channels are not supported modules. + throw new IllegalArgumentException(MIDI_CHANNELS_NOT_SUPPORTED); + } + + /** + * Adds a Player to the module. + * @param player The Player to be added. + * @throws IllegalArgumentException if the player is null or + * if the player or some channels of + * the player already belong to the module. + * @throws MediaException if the player cannot be added. + * @throws IllegalStateException if some Player + * in the Module tree is not in + * UNREALIZED or REALIZED state. + */ + public void addPlayer(Player aPlayer) throws MediaException + { + if (aPlayer == null) + { + throw new IllegalArgumentException("Player is null."); + } + if (!(aPlayer instanceof PlayerImpl)) + { + throw new MediaException("Player is not supported."); + } + + // It is not reasonable to add a player that is in CLOSED state. + if (aPlayer.getState() == Player.CLOSED) + { + throw new IllegalStateException("Cannot add Player while it is in CLOSED state."); + } + + int playerHandle = ((PlayerImpl)aPlayer).getPlayerHandle(); + + int err = _addPlayer(iEventSourceHandle, + iModuleHandle, + playerHandle); + + // Throw IllegalArgumentException if the player or some channels of + // the player already belong to the module. + if (err == NativeError.KErrArgument) + { + throw new IllegalArgumentException("Player already belongs to the module."); + } + + // Throw IllegalStateException if some Player in the Module + // (or the player to be added) is in PREFETCHED or STARTED state + if (err == NativeError.KErrNotReady) + { + throw new IllegalStateException("Cannot Add Player while any player in the module is in PREFETCHED or STARTED state"); + } + + // Throw MediaException if the player already exists in some + // other module. + if (err == PLAYER_ALREADY_IN_MODULE) + { + throw new MediaException("Player already in other module."); + } + + // Throw MediaException if audio mixing is not supported (emulator). + if (err == MIXING_NOT_SUPPORTED) + { + throw new MediaException("Mixing is not supported in emulator."); + } + + // Throw MediaException if the player cannot be added. + if (err < 0) + { + throw new MediaException(NativeError.errorMessage(err)); + } + + iPlayers.addElement(aPlayer); + aPlayer.addPlayerListener(this); + } + + /** + * Removes a Player or all channels of a Player + * from the module. + * @param player The Player to be removed. + * @throws IllegalArgumentException if player is not part of + * the + * module or if player is null. + * @throws IllegalStateException if some Player + * in the Module tree is not in + * UNREALIZED or REALIZED state. + */ + public void removePlayer(Player aPlayer) + { + // Throw IllegalArgumentException if the player is null, incorrect + // type, or does not belong to the module. + if (aPlayer == null) + { + throw new IllegalArgumentException("Player is null."); + } + if (!(aPlayer instanceof PlayerImpl)) + { + throw new IllegalArgumentException("Not supported player."); + } + + // If the player is in CLOSED state, the native side player is + // already removed and destroyed. + if (aPlayer.getState() != Player.CLOSED) + { + // The player list does not contain CLOSED players, thus do not + // check the existence for these players. + if (!iPlayers.contains(aPlayer)) + { + throw new IllegalArgumentException( + "Player does not belong to the module."); + } + + int playerHandle = ((PlayerImpl)aPlayer).getPlayerHandle(); + + int err = _removePlayer(iEventSourceHandle, + iModuleHandle, + playerHandle); + + if (err == NativeError.KErrNotReady) + { + throw new IllegalStateException( + "Cannot remove Player while any player in the module is in PREFETCHED or STARTED state"); + } + + NativeError.check(err); + + aPlayer.removePlayerListener(this); + } + + iPlayers.removeElement(aPlayer); + } + + /** + * Obtain the object that implements the specified Control interface. + * + * @see javax.microedition.media.Controllable + * @param aControlType the class name of the Control. The class name should + * be given either as the fully-qualified name of the class; or if the + * package of the class is not given, the package + * javax.microedition.media.control is assumed. + * @return the object that implements the control, or null. + */ + public Control getControl(String aControlType) + { + // Delegate to ControlContainer + return iControls.getControl(aControlType); + } + + /** + * Obtain the collection of Controls. + * + * @see javax.microedition.media.Controllable + * @return the collection of Control objects. + */ + public Control[] getControls() + { + // Delegate to ControlContainer + return iControls.getControls(); + } + + /** + * From PlayerListener. + */ + public void playerUpdate(Player aPlayer, String aEvent, Object aEventData) + { + // Remove the player from the vector in order to allow + // the garbage collector to dispose the player. + if (aEvent == PlayerListener.CLOSED) + { + iPlayers.removeElement(aPlayer); + } + } + + /** + * Removes a Player from module. + * (The function is protected to allow inherited modules to remove + * CLOSED players which is not possible by removePlayer() function). + * + * @param aEventSourceHandle Handle to native event source. + * @param aModuleHandle Handle to native module object. + * @param aPlayerHandle Handle to native player object. + * @return Negative value if player does not exist in the module. + */ + static native protected int _removePlayer(int aEventSourceHandle, + int aModuleHandle, + int aPlayerHandle); + + /** + * Adds a Player to module. + * + * @param aEventSourceHandle Handle to native event source. + * @param aModuleHandle Handle to native module object. + * @param aPlayerHandle Handle to native player object. + * @return Error code + */ + static native private int _addPlayer(int aEventSourceHandle, + int aModuleHandle, + int aPlayerHandle); + + /** + * Disposes native module. + * + * @param aManagerHandle Handle to native global manager. + * @param aModuleHandle Handle to native module object. + */ + static native private void _dispose(int aManagerHandle, + int aModuleHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/SoundSource3DImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/SoundSource3DImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms; + +import javax.microedition.amms.SoundSource3D; + +/** + * SoundSource3DImpl provides functionality defined in SoundSource3D. + * This class is used through SoundSource3D interface which implements the + * Module interface and does not define any new methods. Methods defined in + * Module are implemented in ModuleBase class. + * Can be accessed only from com.nokia.amms package. + */ +class SoundSource3DImpl extends ModuleBase + implements SoundSource3D +{ + /** + * Constructs new EffectModuleImpl instance. + * Package private. + * @param aEventSourceHandle Handle to event source. + * @param aNativeHandle Handle to corresponding native object. + * @param aManagerHandle Handle to native global manager. + */ + SoundSource3DImpl(int aEventSourceHandle, + int aNativeHandle, + int aManagerHandle) + { + super(aEventSourceHandle, + aNativeHandle, + aManagerHandle); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/SpectatorImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/SpectatorImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms; + +import javax.microedition.media.Controllable; + +/** + * SpectatorImpl provides functionality defined in Spectator class. + * This class is used through Controllable interface which methods are + * implemented in ModuleBase. + */ +class SpectatorImpl extends ModuleBase implements Controllable +{ + /** + * Constructs new SpectatorImpl instance. + * @param aEventSourceHandle Handle to event source. + * @param aNativeHandle Handle to corresponding native object. + */ + SpectatorImpl(int aEventSourceHandle, + int aNativeHandle) + { + // use empty constructor which don't register this object for + // finalization. Finalization is not needed because spectator's + // is singleton class in the global manager. + init(aEventSourceHandle, + aNativeHandle); + } + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/ControlImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/ControlImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for all AMMS controls. +* +*/ + +package com.nokia.amms.control; + +import javax.microedition.media.Control; +import com.nokia.amms.ModuleBase; +import com.nokia.mj.impl.utils.Logger; + + +/** + * Base class for all AMMS controls. + */ +public class ControlImpl implements Control +{ + protected int iControlHandle; + protected int iEventSource; + // Module that owns this control. Storing the reference to the module + // will prevent the garbage collector from deleting the module if some + // controls are still used. + protected ModuleBase iModule; + + protected static final int NO_ERROR = 0; + protected static final int NOT_READY = -18; + protected static final int NOT_FOUND = -1; + protected static final int NOT_SUPPORTED = -5; + + /** + * Constructor + */ + protected ControlImpl() + { + } + + /** + * Initializes control with event source and native implementation handles. + * @param aEventSource Handle to native event source. + * @param aControl Handle to native control implementation. + * @param aModule Module that owns this control. + */ + public void initControl(int aEventSource, + int aControlHandle, + ModuleBase aModule) + { + iEventSource = aEventSource; + iControlHandle = aControlHandle; + iModule = aModule; + + Logger.LOG(Logger.EJavaMMAPI, + Logger.EInfo, + "created: " + toString() + " handle = " + aControlHandle); + } + + /** + * Invalidates the control. Using this control after invalidating + * throws a RuntimeException. + */ + public void invalidateControl() + { + iControlHandle = 0; + } + + + public void checkValid() + { + if ((iEventSource == 0) || (iControlHandle == 0)) + { + throw new IllegalStateException("Control creation failed"); + } + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/EffectControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/EffectControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,229 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for Effect controls +* +*/ + +package com.nokia.amms.control; + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.NativeError; + +public class EffectControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.EffectControl +{ + /** + * Constructor + */ + public EffectControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setEnabled(boolean aEnable) + { + checkValid(); + + int err = _setEnabled(iEventSource, iControlHandle, aEnable); + + if (err == NOT_READY) + { + throw new IllegalStateException( + "Enabling effect failed: Symbian OS error " + err); + } + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isEnabled() + { + checkValid(); + + // must ask the actual value from the native side + // because the effect can be dropped (if it's not enforced) + + int err = _isEnabled(iEventSource, iControlHandle); + NativeError.check(err); + + return err != 0; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setScope(int aScope) throws MediaException + { + checkValid(); + + String KScopeNotSupported = "Only SCOPE_LIVE_ONLY scope is supported"; + + // Only SCOPE_LIVE_ONLY is supported at the moment. + if (aScope != SCOPE_LIVE_ONLY) + { + throw new MediaException(KScopeNotSupported); + } + + int err = _setScope(iEventSource, iControlHandle, aScope); + if (err < NO_ERROR) + { + if (err == NOT_READY) + { + throw new IllegalStateException( + "Setting scope failed: Symbian OS error " + err); + } + else if (err == NOT_SUPPORTED) + { + throw new MediaException(KScopeNotSupported); + } + else + { + NativeError.check(err); + } + } + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getScope() + { + checkValid(); + + int err = _getScope(iEventSource, iControlHandle); + NativeError.check(err); + + return err; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setEnforced(boolean aEnforced) + { + checkValid(); + + int err = _setEnforced(iEventSource, iControlHandle, aEnforced); + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isEnforced() + { + checkValid(); + + int err = _isEnforced(iEventSource, iControlHandle); + NativeError.check(err); + + return err != 0; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setPreset(String aPreset) + { + checkValid(); + + if (aPreset == null) + { + throw new IllegalArgumentException("Preset is null"); + } + + int err = _setPreset(iEventSource, iControlHandle, aPreset); + + if (err == NOT_FOUND) + { + throw new IllegalArgumentException("Preset is not available"); + } + else + { + NativeError.check(err); + } + } + + /** + * Please refer to JSR 234 for more details. + */ + public String getPreset() + { + checkValid(); + + String[] preset = new String[1]; + int err = _getPreset(iEventSource, iControlHandle, preset); + if (err < NO_ERROR) + { + throw new IllegalStateException(); + } + + return preset[0]; + } + + /** + * Please refer to JSR 234 for more details. + */ + public String[] getPresetNames() + { + checkValid(); + + String[] presets = _getPresetNames(iEventSource, iControlHandle); + + // native function must not return null, unless an error occures. If + // there is no supported types zero length array will be returned. + if (presets == null) + { + throw new OutOfMemoryError(); + } + return presets; + } + + // native methods + private static native int _setEnabled( + int aEventSource, + int aControlHandle, + boolean aEnable); + private static native int _isEnabled( + int aEventSource, + int aControlHandle); + private static native int _setScope( + int aEventSource, + int aControlHandle, + int aScope); + private static native int _getScope( + int aEventSource, + int aControlHandle); + private static native int _setEnforced( + int aEventSource, + int aControlHandle, + boolean aEnforced); + private static native int _isEnforced( + int aEventSource, + int aControlHandle); + private static native int _setPreset( + int aEventSource, + int aControlHandle, + String aPreset); + private static native int _getPreset( + int aEventSource, + int aControlHandle, + String[] aPreset); + private static native String[] _getPresetNames( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/PanControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/PanControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control; + +import com.nokia.microedition.media.NativeError; + +public class PanControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.PanControl +{ + private static final int MIN_PAN = -100; + private static final int MAX_PAN = 100; + + /** + * Constructor + */ + public PanControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public int setPan(int aPan) + { + checkValid(); + + int pan = aPan; + // Panning value that is out of range is set to the valid range. + if (pan < MIN_PAN) + { + pan = MIN_PAN; + } + if (pan > MAX_PAN) + { + pan = MAX_PAN; + } + + // SetBalance method in native side returns a system wide error code. + int[] error = new int[ 1 ]; + int value = _setPan(iEventSource, iControlHandle, pan, error); + NativeError.check(error[ 0 ]); + + return value; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getPan() + { + checkValid(); + + int value = _getPan(iEventSource, iControlHandle); + // GetBalance method in native would return a system wide error code, + // but the panning value is just instead queried from the control group. + + return value; + } + + // native methods + private static native int _setPan( + int aEventSource, + int aControlHandle, + int aPan, + int[] aError); + private static native int _getPan( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/PriorityControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/PriorityControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for adjusting player priorities. +* +*/ + +package com.nokia.amms.control; + +import com.nokia.microedition.media.NativeError; +import javax.microedition.media.Player; + +/** + * Control for adjusting player priorities. + */ +public class PriorityControl + extends ControlImpl + implements javax.microedition.amms.control.PriorityControl +{ + private static final int MIN_PRIORITY = 0; + private static final int MAX_PRIORITY = 100; + + // The player owning this control. + private Player iPlayer; + + + /** + * Constructor + */ + public PriorityControl(Player aPlayer) + { + iPlayer = aPlayer; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setPriority(int aPriority) + { + checkValid(); + + int priority = aPriority; + // Panning value that is out of range is set to the valid range. + if (aPriority < MIN_PRIORITY || + aPriority > MAX_PRIORITY) + { + throw new IllegalArgumentException( + "Priority must be between 0 and 100"); + } + + // Priority setting in native side returns a system wide error code. + int error = _setPriority(iEventSource, iControlHandle, aPriority); + NativeError.check(error); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getPriority() + { + checkValid(); + + int value = _getPriority(iEventSource, iControlHandle); + + return value; + } + + public void checkValid() + { + super.checkValid(); + + if (iPlayer.getState() == Player.CLOSED) + { + throw new IllegalStateException("Player is closed."); + } + } + + // native methods + private static native int _setPriority( + int aEventSource, + int aControlHandle, + int aPriority); + private static native int _getPriority( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/VolumeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/VolumeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.amms.control; + +import com.nokia.amms.AMMSError; + +public class VolumeControl extends ControlImpl + implements javax.microedition.media.control.VolumeControl +{ + private static final int MAX_VOLUME = 100; + private int iLevel = MAX_VOLUME; + private boolean iMuted = false; + + /** + * Constructor + */ + public VolumeControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isMuted() + { + checkValid(); + return iMuted; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getLevel() + { + checkValid(); + return iLevel; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int setLevel(int aLevel) + { + checkValid(); + int level = aLevel; + + // Set level to between 0 and 100 + if (level < 0) + { + level = 0; + } + else if (level > MAX_VOLUME) + { + level = MAX_VOLUME; + } + + if (!iMuted) + { + AMMSError.check(_setLevel(iEventSource, + iControlHandle, + level)); + } + iLevel = level; + return level; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setMute(boolean aMuted) + { + checkValid(); + + // Check if mute status is changed + if (aMuted != iMuted) + { + iMuted = aMuted; + + int level = iLevel; + + // If mute is on set volume to 0, otherwise set to level set before + if (iMuted) + { + level = 0; + } + + AMMSError.check(_setLevel(iEventSource, + iControlHandle, + level)); + } + } + + /** + * @param aEventSourceHandle Handle to native event source. + * @param aControlHandle Handle to native control. + * @param aLevel New volume level. + */ + private static native int _setLevel(int aEventSourceHandle, + int aControlHandle, + int aLevel); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/CommitControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/CommitControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audio3d; + +import com.nokia.microedition.media.NativeError; + +/** + * Please refer to JSR 234 for more details. + */ +public class CommitControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audio3d.CommitControl +{ + // data + private boolean iIsDeferred = false; + + /** + * Constructor + */ + public CommitControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setDeferred(boolean aDeferred) + { + checkValid(); + + int err = _setDeferred(iEventSource, iControlHandle, aDeferred); + + // check error + NativeError.check(err); + + iIsDeferred = aDeferred; + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isDeferred() + { + checkValid(); + + return iIsDeferred; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void commit() + { + checkValid(); + + int err = _commit(iEventSource, iControlHandle); + + // check error + NativeError.check(err); + } + + // native function + private static native int _setDeferred(int aEventSource, int aControlHandle, boolean aDeferred); + private static native int _commit(int aEventSource, int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/DistanceAttenuationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/DistanceAttenuationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,133 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audio3d; + +import com.nokia.microedition.media.NativeError; + +public class DistanceAttenuationControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audio3d.DistanceAttenuationControl +{ + private static final int MIN_MINIMUM_DISTANCE = 1; + private static final int MIN_MAXIMUM_DISTANCE = 1; + private static final int MIN_ROLLOF_FACTOR = 0; + /** + * Constructor + */ + public DistanceAttenuationControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setParameters(int aMinDistance, + int aMaxDistance, + boolean aMuteAfterMax, + int aRolloffFactor) + { + checkValid(); + + if (aMaxDistance <= aMinDistance) + { + throw new IllegalArgumentException("maxDistance must be equal or greater than minDistance"); + } + if (aMinDistance < MIN_MINIMUM_DISTANCE) + { + throw new IllegalArgumentException("minDistance must be greater than zero"); + } + if (aMaxDistance < MIN_MAXIMUM_DISTANCE) + { + throw new IllegalArgumentException("maxDistance must be greater than zero"); + } + if (aRolloffFactor < MIN_ROLLOF_FACTOR) + { + throw new IllegalArgumentException("rolloffFactor cannot be less than zero"); + } + + int err = _setParameters(iEventSource, iControlHandle, + aMinDistance, aMaxDistance, aMuteAfterMax, aRolloffFactor); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinDistance() + { + checkValid(); + + // have to ask the native control because of commiting + return _getMinDistance(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxDistance() + { + checkValid(); + + // have to ask the native control because of commiting + return _getMaxDistance(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean getMuteAfterMax() + { + checkValid(); + + // have to ask the native control because of commiting + return _getMuteAfterMax(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getRolloffFactor() + { + checkValid(); + + // have to ask the native control because of commiting + return _getRolloffFactor(iEventSource, iControlHandle); + } + + // native functions + private static native int _setParameters( + int aEventSource, + int aControlHandle, + int aMinDistance, + int aMaxDistance, + boolean aMuteAfterMax, + int aRolloffFactor); + private static native int _getMaxDistance( + int aEventSource, + int aControlHandle); + private static native int _getMinDistance( + int aEventSource, + int aControlHandle); + private static native boolean _getMuteAfterMax( + int aEventSource, + int aControlHandle); + private static native int _getRolloffFactor( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/DopplerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/DopplerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audio3d; + +import com.nokia.microedition.media.NativeError; + +public class DopplerControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audio3d.DopplerControl +{ + /** + * Constructor + */ + public DopplerControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isEnabled() + { + checkValid(); + + // have to ask the native control because of commiting + return _isEnabled(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getVelocityCartesian() + { + checkValid(); + + int[] error = new int[ 1 ]; + // have to ask the native control because of commiting + int[] velocity = _getVelocityCartesian(iEventSource, + iControlHandle, + error); + if (velocity == null) + { + // couldn't allocate memory + throw new OutOfMemoryError("Unable to obatin velocity."); + } + + NativeError.check(error[ 0 ]); + + return velocity; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setEnabled(boolean aDopplerEnabled) + { + checkValid(); + + int err = _setEnabled(iEventSource, iControlHandle, aDopplerEnabled); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setVelocityCartesian(int aX, int aY, int aZ) + { + checkValid(); + + int err = _setVelocityCartesian(iEventSource, iControlHandle, aX, aY, aZ); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setVelocitySpherical(int aAzimuth, int aElevation, int aRadius) + { + checkValid(); + + int err = _setVelocitySpherical( + iEventSource, + iControlHandle, + aAzimuth, + aElevation, + aRadius); + + NativeError.check(err); + } + + private static native boolean _isEnabled( + int aEventSource, + int aControlHandle); + private static native int[] _getVelocityCartesian( + int aEventSource, + int aControlHandle, + int[] aError); + private static native int _setEnabled( + int aEventSource, + int aControlHandle, + boolean dopplerEnabled); + private static native int _setVelocityCartesian( + int aEventSource, + int aControlHandle, + int x, + int y, + int z); + private static native int _setVelocitySpherical( + int aEventSource, + int aControlHandle, + int azimuth, + int elevation, + int radius); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/LocationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/LocationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audio3d; + +import com.nokia.microedition.media.NativeError; + +public class LocationControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audio3d.LocationControl +{ + private static final int MIN_RADIUS = 0; + + /** + * Constructor + */ + public LocationControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setCartesian(int aX, int aY, int aZ) + { + checkValid(); + + int err = _setCartesian(iEventSource, iControlHandle, aX, aY, aZ); + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setSpherical(int aAzimuth, int aElevation, int aRadius) + { + checkValid(); + + if (aRadius < MIN_RADIUS) + { + throw new IllegalArgumentException("Radius cannot be less than zero"); + } + + int err = _setSpherical( + iEventSource, + iControlHandle, + aAzimuth, + aElevation, + aRadius); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getCartesian() + { + checkValid(); + + int[] error = new int[ 1 ]; + int[] location = _getCartesian(iEventSource, iControlHandle, error); + if (location == null) + { + throw new OutOfMemoryError("Unable to obtain coordinates"); + } + + NativeError.check(error[ 0 ]); + + return location; + } + + private static native int[] _getCartesian( + int aEventSource, + int aControlHandle, + int[] aError); + private static native int _setCartesian( + int aEventSource, + int aControlHandle, + int x, + int y, + int z); + private static native int _setSpherical( + int aEventSource, + int aControlHandle, + int azimuth, + int elevation, + int radius); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/OrientationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audio3d/OrientationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,162 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audio3d; + +import com.nokia.microedition.media.NativeError; + +public class OrientationControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audio3d.OrientationControl +{ + private static final int REQUIRED_VECTOR_SIZE = 3; + private static final int COMPONENT_X = 0; + private static final int COMPONENT_Y = 1; + private static final int COMPONENT_Z = 2; + + /** + * Constructor + */ + public OrientationControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setOrientation(int aHeading, int aPitch, int aRoll) + { + checkValid(); + + int err = _setOrientation( + iEventSource, + iControlHandle, + aHeading, + aPitch, + aRoll); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setOrientation(int[] aFrontVector, int[] aAboveVector) + throws IllegalArgumentException + { + checkValid(); + + if ((aFrontVector == null) || + (aAboveVector == null)) + { + throw new IllegalArgumentException("Argument is null"); + } + + if ((aFrontVector.length < REQUIRED_VECTOR_SIZE) || + (aAboveVector.length < REQUIRED_VECTOR_SIZE) || + (aFrontVector.length > REQUIRED_VECTOR_SIZE) || + (aAboveVector.length > REQUIRED_VECTOR_SIZE)) + { + throw new IllegalArgumentException("Required orientation vector size is 3"); + } + + // Vector is a zero vector if all the components are zero + if (((aFrontVector[ COMPONENT_X ] == 0) && + (aFrontVector[ COMPONENT_Y ] == 0) && + (aFrontVector[ COMPONENT_Z ] == 0)) || + ((aAboveVector[ COMPONENT_X ] == 0) && + (aAboveVector[ COMPONENT_Y ] == 0) && + (aAboveVector[ COMPONENT_Z ] == 0))) + { + throw new IllegalArgumentException("Orientation vector cannot be a zero vector"); + } + + // Two vectors are parallel if their cross product is zero vector. + // Cross product of vectors a1*i + a2*j + a3*k and b1*i + b2*j + b3*k : + // (a2*b3 - a3*b2)i + (a3*b1 - a1*b3)j + (a1*b2 - a2*b1)k + if (( + (aFrontVector[ COMPONENT_Y ] * aAboveVector[ COMPONENT_Z ]) - + (aFrontVector[ COMPONENT_Z ] * aAboveVector[ COMPONENT_Y ]) == 0 + ) + && + ( + (aFrontVector[ COMPONENT_Z ] * aAboveVector[ COMPONENT_X ]) - + (aFrontVector[ COMPONENT_X ] * aAboveVector[ COMPONENT_Z ]) == 0 + ) + && + ( + (aFrontVector[ COMPONENT_X ] * aAboveVector[ COMPONENT_Y ]) - + (aFrontVector[ COMPONENT_Y ] * aAboveVector[ COMPONENT_X ]) == 0 + )) + { + throw new IllegalArgumentException("Orientation vectors cannot be parallel"); + } + + int err = _setOrientationVectors( + iEventSource, + iControlHandle, + aFrontVector, + aAboveVector); + + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getOrientationVectors() + { + checkValid(); + + int[] error = new int[ 1 ]; + + int[] orientation = _getOrientationVectors( + iEventSource, + iControlHandle, + error); + + if (error[ 0 ] != NativeError.KErrNone) + { + throw new OutOfMemoryError("Obtaining orientation vectors failed: Symbian OS error " + + error[ 0 ]); + } + + if (orientation == null) + { + throw new OutOfMemoryError("Unable to obtain orientation vectors"); + } + return orientation; + } + + private static native int _setOrientation( + int aEventSource, + int aControlHandle, + int heading, + int pitch, + int roll); + + private static native int _setOrientationVectors( + int aEventSource, + int aControlHandle, + int[] frontVector, + int[] aboveVector); + + private static native int[] _getOrientationVectors( + int aEventSource, + int aControlHandle, + int[] error); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/AudioVirtualizerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/AudioVirtualizerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audioeffect; + +public class AudioVirtualizerControl + extends com.nokia.amms.control.EffectControl + implements javax.microedition.amms.control.audioeffect.AudioVirtualizerControl +{ + /** + * Constructor + */ + public AudioVirtualizerControl() + { + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/EqualizerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/EqualizerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,218 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audioeffect; + +import com.nokia.microedition.media.NativeError; + +public class EqualizerControl + extends com.nokia.amms.control.EffectControl + implements javax.microedition.amms.control.audioeffect.EqualizerControl +{ + private static final int MAX_LEVEL = 100; + private static final int MIN_LEVEL = 0; + + /** + * Constructor + */ + public EqualizerControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinBandLevel() + { + checkValid(); + + return _getMinBandLevel(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxBandLevel() + { + checkValid(); + + return _getMaxBandLevel(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setBandLevel(int aLevel, int aBand) + throws IllegalArgumentException + { + checkValid(); + + int err = _setBandLevel(iEventSource, iControlHandle, aLevel, aBand); + + // throws IllegalArgumentException on KErrArgument + NativeError.check(err); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getBandLevel(int aBand) throws IllegalArgumentException + { + checkValid(); + + int[] level = new int[ 1 ]; + + int error = _getBandLevel(iEventSource, iControlHandle, aBand, level); + + // throws IllegalArgumentException on KErrArgument + NativeError.check(error); + + return level[ 0 ]; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getNumberOfBands() + { + checkValid(); + + return _getNumberOfBands(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getCenterFreq(int aBand) throws IllegalArgumentException + { + checkValid(); + + int err = _getCenterFreq(iEventSource, iControlHandle, aBand); + NativeError.check(err); + + return err; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getBand(int aFrequency) + { + checkValid(); + + int band = _getBand(iEventSource, iControlHandle, aFrequency); + + return band; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int setBass(int aLevel) throws IllegalArgumentException + { + checkValid(); + + if (aLevel < MIN_LEVEL || aLevel > MAX_LEVEL) + { + throw new IllegalArgumentException("Bass level out of range"); + } + + int err = _setBass(iEventSource, iControlHandle, aLevel); + NativeError.check(err); + + return err; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int setTreble(int aLevel) throws IllegalArgumentException + { + checkValid(); + + if (aLevel < MIN_LEVEL || aLevel > MAX_LEVEL) + { + throw new IllegalArgumentException("Treble level out of range"); + } + + int err = _setTreble(iEventSource, iControlHandle, aLevel); + NativeError.check(err); + return err; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getBass() + { + checkValid(); + + return _getBass(iEventSource, iControlHandle); + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getTreble() + { + checkValid(); + + return _getTreble(iEventSource, iControlHandle); + } + + private static native int _getMinBandLevel( + int iEventSource, + int iControlHandle); + private static native int _getMaxBandLevel( + int iEventSource, + int iControlHandle); + private static native int _setBandLevel( + int iEventSource, + int iControlHandle, + int level, + int band); + private static native int _getBandLevel( + int iEventSource, + int iControlHandle, + int band, + int[] level); + private static native int _getCenterFreq( + int iEventSource, + int iControlHandle, + int band); + private static native int _getBand( + int iEventSource, + int iControlHandle, + int frequency); + private static native int _setBass( + int iEventSource, + int iControlHandle, + int level); + private static native int _setTreble( + int iEventSource, + int iControlHandle, + int level); + private static native int _getBass( + int iEventSource, + int iControlHandle); + private static native int _getTreble( + int iEventSource, + int iControlHandle); + private static native int _getNumberOfBands( + int iEventSource, + int iControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/ReverbControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/ReverbControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,133 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audioeffect; + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.NativeError; + +public class ReverbControl + extends com.nokia.amms.control.EffectControl + implements javax.microedition.amms.control.audioeffect.ReverbControl +{ + private static final int MAX_REVERB_LEVEL = 0; + private static final int MIN_REVERB_TIME = 0; + + /** + * Constructor + */ + public ReverbControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public int setReverbLevel(int aLevel) throws IllegalArgumentException + { + checkValid(); + + if (aLevel > MAX_REVERB_LEVEL) + { + throw new IllegalArgumentException("Reverb level cannot be greater than zero."); + } + + int err[] = new int[ 1 ]; + int setLevel = _setReverbLevel(iEventSource, + iControlHandle, + aLevel, + err); + NativeError.check(err[ 0 ]); + + return setLevel; + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getReverbLevel() + { + checkValid(); + + int level = _getReverbLevel(iEventSource, iControlHandle); + + return level; + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setReverbTime(int aTime) + throws IllegalArgumentException, MediaException + { + checkValid(); + + if (aTime < MIN_REVERB_TIME) + { + throw new IllegalArgumentException("Reverb time cannot be less than zero"); + } + + int err = _setReverbTime(iEventSource, iControlHandle, aTime); + if (err < NO_ERROR) + { + if (err == NOT_READY) + { + NativeError.check(err); + } + else + { + throw new MediaException( + "Setting reverb time failed: Symbian OS error " + err); + } + } + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getReverbTime() throws javax.microedition.media.MediaException + { + checkValid(); + + int time = _getReverbTime(iEventSource, iControlHandle); + + if (time == NOT_SUPPORTED) + { + throw new MediaException( + "Obtaining reverb time failed: Symbian OS error " + time); + } + + return time; + } + + // native methods + private static native int _setReverbLevel( + int aEventSource, + int aControlHandle, + int aLevel, + int aError[]); + private static native int _getReverbLevel( + int aEventSource, + int aControlHandle); + private static native int _setReverbTime( + int aEventSource, + int aControlHandle, + int aTime); + private static native int _getReverbTime( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/ReverbSourceControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/amms/control/audioeffect/ReverbSourceControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.amms.control.audioeffect; + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.NativeError; + +public class ReverbSourceControl + extends com.nokia.amms.control.ControlImpl + implements javax.microedition.amms.control.audioeffect.ReverbSourceControl +{ + + /** + * Constructor + */ + public ReverbSourceControl() + { + } + + /** + * Please refer to JSR 234 for more details. + */ + public void setRoomLevel(int aLevel) + throws IllegalArgumentException, MediaException + { + checkValid(); + + if ((aLevel > 0) && + (aLevel != DISCONNECT)) + { + throw new IllegalArgumentException("Room level must be less than zero"); + } + + int level = aLevel; + int err = _setRoomLevel(iEventSource, iControlHandle, level); + + if (err < NO_ERROR) + { + if (err == NOT_READY) + { + NativeError.check(err); + } + else + { + throw new MediaException( + "Room level cannot be set: Symbian OS error " + err); + } + } + } + + /** + * Please refer to JSR 234 for more details. + */ + public int getRoomLevel() + { + checkValid(); + + return _getRoomLevel(iEventSource, iControlHandle); + } + + // native methods + private static native int _setRoomLevel( + int aEventSource, + int aControlHandle, + int aLevel); + + private static native int _getRoomLevel( + int aEventSource, + int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/mid/impl/media/AudioOutput.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/mid/impl/media/AudioOutput.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for routing the player's audio output. +* +*/ +package com.nokia.mid.impl.media; +//AudioOutput Class which has info regarding the Output mode and device type +public class AudioOutput implements com.nokia.mid.media.AudioOutput +{ + //Constructor + public AudioOutput(int mode) + { + outputmode = mode; + } + //public + public int getActiveOutputMode() + { + return outputmode; + } + public int[] getOutputDevices() + { + return null; + } + //package access + void setOutputMode(int mode) + { + outputmode = mode; + } + + //private + private int outputmode; + + +} + + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/mid/impl/media/AudioOutputControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/mid/impl/media/AudioOutputControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,135 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for routing the player's audio output. +* +*/ +package com.nokia.mid.impl.media; + +import com.nokia.microedition.media.NativeError; +import javax.microedition.media.Player; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.*; +import com.nokia.mid.impl.media.AudioOutput; + +/** + * Control for adjusting player's Audio output routing. Note : This doesn't have any interface defined in javax.microediton.amms.control package + * as its internal to nokia + */ +public class AudioOutputControl + extends com.nokia.amms.control.ControlImpl + implements com.nokia.mid.media.AudioOutputControl +{ + // The player owning this control. + private Player iPlayer; + private AudioOutput audioOutputObj; + /** + * Constructor + */ + public AudioOutputControl(Player aPlayer) + { + iPlayer = aPlayer; + } + + public void SetAudioOutputToNative() + { + // Create an AudioOutput object and pass it to native + audioOutputObj = new AudioOutput(AudioOutputControl.DEFAULT); + setAudioOutputObject(audioOutputObj); + } + /** + * Sets the new mode. + * Throws IllegalArgumentException if the argument is invalid + * @param mode The new Output mode to be set. + */ + public int setOutputMode(int mode) + { + checkValid(); + int value = _setOutputMode(iEventSource, iControlHandle, mode); + NativeError.check(value); + return value; + } + + /** + * Gets the previous set mode by user. + * + * @return The last set user mode . + */ + public int getOutputMode() + { + checkValid(); + int value = _getOutputMode(iEventSource, iControlHandle); + return value; + } + + /** + * Gets the actual routing at that time. + * @return The current preference. + */ + + public com.nokia.mid.media.AudioOutput getCurrent() + { + checkValid(); + int value = _getCurrent(iEventSource, iControlHandle); + NativeError.check(value); + return audioOutputObj; + } + + /** + * @return all the available output modes. + */ + public int[] getAvailableOutputModes() + { + checkValid(); + int[] availableOutputModes = { DEFAULT, ALL, NONE, PRIVATE, PUBLIC }; + return availableOutputModes; + } + + + public void checkValid() + { + super.checkValid(); + + if (iPlayer.getState() == Player.CLOSED) + { + throw new IllegalStateException("Closed player"); + } + } + /** + * pass the AudioOutput object to native + */ + public void setAudioOutputObject(AudioOutput obj) + { + checkValid(); + int value = _setAudioOutputObject(iEventSource, iControlHandle, obj); + NativeError.check(value); + } + + + // native methods + private static native int _setOutputMode( + int aEventSource, + int aControlHandle, + int aMode); + private static native int _getOutputMode( + int aEventSource, + int aControlHandle); + private static native int _getCurrent( + int aEventSource, + int aControlHandle); + private static native int _setAudioOutputObject( + int aEventSource, int aControlHandle, + AudioOutput audioOutputObj); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/mid/media/AudioOutput.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/mid/media/AudioOutput.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for routing the player's audio output. +* +*/ + +package com.nokia.mid.media; + +/** + * AudioOutput + * Encapsulates current audio output mode and output device(s) used. + *

+ *

+ * @since 1.4 + *

+ */ +public interface AudioOutput +{ + /** + * Get active output mode. + *

+ * The different modes are defined in AudioOutputControl class. + * + * @return The current audio output mode or -1 if unable to determine + * + * @exception SecurityException with message "Permission denied" if the + * called does not have permission to set the audio routing. + */ + public int getActiveOutputMode(); + + /** + * Get supported output devices + *

+ * returns array of audio output device types if it is supported + * otherwise returns "null" + */ + public int[] getOutputDevices(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/com/nokia/mid/media/AudioOutputControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/com/nokia/mid/media/AudioOutputControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,201 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for routing the player's audio output. +* +*/ + +package com.nokia.mid.media; + +/** + * AudioOutputControl is an interface for setting application + * preferred audio output mode. + *

+ * SYMBIAN SPECIFIC BEHAVIOR:

+ * Audio output mode is within the scope of a player instance and can be set + * when the MIDlet which set the audio routing is finished with the audio + * when the player is in REALIZED, PREFETCHED, STARTED or STOPPED state. + * The preferences are applied or imposed when media is played.

+ * Audio output control is retrieved using 'Player' interface by calling + * Control getControl ( java.lang.string controlType ) + * The control type to be passed as an argument is + * com.nokia.mid.media.AudioOutputControl + *

+ * S40 SPECIFIC BEHAVIOR:

+ * The AudioOutputControl is a Global Control and will effect all players. + * When the MIDlet which set the audio routing is finished with the audio + * change then it must set it back to DEFAULT. + *

+ * Audio output control is retrieved using 'GlobalManager' interface by calling + * Control getControl ( java.lang.string controlType ) + * The control type to be passed as an argument is + * com.nokia.mid.media.AudioOutputControl + *

+ * Code Snippet:
+ *
+ * 1. Getting AudioOutputControl:

+ * In SYMBIAN:

+ * Player p = + * Manager.createPlayer(getClass().getResourceAsStream + * ("nokia_tune.mid"), "audio/midi");
+ * p.realize();
+ * AudioOutputControl iAudioOutputControl= + * (AudioOutputControl)p.getControl("com.nokia.mid.media.AudioOutputControl");
+ * p.addPlayerListener(this);


+ * In S40:

+ * import javax.microedition.amms.*;
+ * iAudioOutputControl = (AudioOutputControl) GlobalManager.getControl("com.nokia.mid.media.AudioOutputControl");
+ *


+ * 2. Setting and getting Audio Output Mode:

+ * 2.1 Setting PRIVATE mode:

+ * iAudioOutputControl.setOutputMode(PRIVATE);

+ * 2.2 Getting Current Mode:

+ * AudioOutput audioOutput = iAudioOutputControl.getCurrent();
+ * int mode = audioOutput.getOutputMode();

+ * 3. Getting notification:

+ * Notifications are supported only on SYMBIAN.
+ * The notification about the preference change is done using + * PlayerListener's playerUpdate() function. + * Whereas, this specific Event type is "com.nokia.audiooutputchange.event" + * and Event data is AudioOutput object.

+ * + * public void playerUpdate(Player aPlayer, String aEvent, Object aEventData){
+ *

if(aEvent.equals("com.nokia.audiooutputchange.event")){
+ *
helloForm.append("com.nokia.audiooutputchange.event");
+ *
// get the mode
+ *
Int mode = ((AudioOutput)aEventData).getActiveOutputMode();
+ *
}

+ * }

+ *

+ *

+ * @since 1.4 + *

+ */ + + +public interface AudioOutputControl extends javax.microedition.media.Control +{ + /** + * The DEFAULT audio output mode. + *

+ * No Preference. The audio routing is restored to the default value. + *

+ * Value 0 is assigned to DEFAULT. + *

+ * SYMBIAN SPECIFIC BEHAVIOR:
+ * Audio is by default routed to loudspeaker. + * Audio output changes dynamically to headset, when headset is connected to + * the device and vice versa. Application is notified about audio output + * change with audio output change event. + *

+ */ + public static final int DEFAULT = 0; + + /** + * The ALL audio output mode. + *

+ * Audio is routed to one public and one private output at the same time. + * The primary output method within public and private outputs is selected + * by the device and can change dynamically when external peripherals are + * connected or disconnected by the user (see "public" and "private" for + * their priorities). + *

+ * Value 1 is assigned to ALL. + */ + public static final int ALL = 1; + + /** + * The NONE audio output mode. + *

+ * Audio is not routed to any output. + *

+ * Value 2 is assigned to NONE. + */ + public static final int NONE = 2; + + /** + * The PRIVATE audio output mode. + *

+ * Audio is routed to earpiece or wired / wireless(BT) headset if connected. + * If there are several private output methods available at the same time + * audio is routed to only one of those selected with following priority + * order 1) wired headset 2) wireless headset 3) earpiece. + *

+ * Value 3 is assigned to PRIVATE. + */ + public static final int PRIVATE = 3; + + /** + * The PUBLIC audio output mode. + *

+ * Audio is routed to loudspeaker, wireless(BT) speakers or TV output. If + * there are several public output methods available at the same time + * audio is routed to only one of those selected with following priority + * order: (1) wired headset 2) Loudspeaker + *

+ * Value 4 is assigned to PUBLIC. + */ + public static final int PUBLIC = 4; + + /** + * Get all supported audio output modes + *

+ * @return The currently supported output modes + *

+ */ + int[] getAvailableOutputModes(); + + /** + * Get the currently set audio output mode. This is the last audioOutputMode + * sent to setOutputMode or DEFAULT if none has been set. + *

+ * This does not return the actual audio output mode of the device. The + * AudioOutput can be used to provide the actual audio output mode. + * + * @return The last audio output mode which was sent to setOutputMode. + */ + int getOutputMode(); + + /** + * returns an AudioOutput object which consists + * Device Type and the mode of the audio output + */ + com.nokia.mid.media.AudioOutput getCurrent(); + + /** + * Sets the preferred audio output mode. + *

+ * + * @return audio output mode set or -1 if unable to set + * + * @exception IllegalArgumentException with message "audio output mode is + * not valid" when the audio output mode is not valid + * + * @exception IllegalStateException with message "Accessory connected" if + * unable to change the audio routing due to an accessory connected + * + * @exception SecurityException with message "Permission denied" if the + * called does not have permission to set the audio routing. + *

+ * SYMBIAN SPECIFIC BEHAVIOR:
+ * This effects only a specific player instance. + * Preference can be set when Player is in REALIZED, PREFETCHED, + * STARTED or STOPPED state. + *

+ * S40 SPECIFIC BEHAVIOR:
+ * This will effect all players + */ + int setOutputMode(int mode); + +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/EffectModule.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/EffectModule.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +/** + * Please refer JSR 234 for more details. + */ +public interface EffectModule extends Module +{ + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/GlobalManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/GlobalManager.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,125 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +import javax.microedition.amms.control.audio3d.LocationControl; +import javax.microedition.amms.control.FormatControl; +import javax.microedition.media.*; + +// Implementation +import com.nokia.amms.GlobalManagerImpl; + +/** + * Please refer JSR 234 for more details. + */ +public class GlobalManager +{ + /** + * Static spectator instance. Returned from getSpectator method. + */ + private static Spectator iSpectator; + + /** + * Implementation. All method calls in this class will be delegated + * GlobalManagerImpl. + */ + private static GlobalManagerImpl iManagerImpl; + + static + { + // Get static instance. + iManagerImpl = GlobalManagerImpl.getInstance(); + + // Spectator delegates all method calls to spectator got from + // GlobalManagerImpl + iSpectator = new Spectator(iManagerImpl.getSpectator()); + } + + /** + * Private not allow construction + */ + private GlobalManager() + { + } + + + /** + * Please refer JSR 234 for more details. + */ + public static Control[] getControls() + { + return iManagerImpl.getControls(); + } + + /** + * Please refer JSR 234 for more details. + */ + public static Control getControl(String aControlType) + { + return iManagerImpl.getControl(aControlType); + } + + /** + * Please refer JSR 234 for more details. + */ + public static EffectModule createEffectModule() throws MediaException + { + return iManagerImpl.createEffectModule(); + } + + /** + * Please refer JSR 234 for more details. + */ + public static SoundSource3D createSoundSource3D() throws MediaException + { + return iManagerImpl.createSoundSource3D(); + } + + /** + * Please refer JSR 234 for more details. + */ + public static String[] getSupportedSoundSource3DPlayerTypes() + { + return iManagerImpl.getSupportedSoundSource3DPlayerTypes(); + } + + /** + * Please refer JSR 234 for more details. + */ + public static Spectator getSpectator() throws MediaException + { + return iSpectator; + } + + /** + * Please refer JSR 234 for more details. + */ + public static MediaProcessor createMediaProcessor(String aContentType) + throws MediaException + { + return iManagerImpl.createMediaProcessor(aContentType); + } + + /** + * Please refer JSR 234 for more details. + */ + public static String[] getSupportedMediaProcessorInputTypes() + { + return iManagerImpl.getSupportedMediaProcessorInputTypes(); + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/MediaProcessor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/MediaProcessor.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +import javax.microedition.media.*; + +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Please refer JSR 234 for more details. + */ +public interface MediaProcessor extends Controllable +{ + + /** + * Please refer JSR 234 for more details. + */ + public final int UNKNOWN = -1; + + /** + * Please refer JSR 234 for more details. + * + */ + public final int UNREALIZED = 100; + + /** + * Please refer JSR 234 for more details. + */ + public final int REALIZED = 200; + + /** + * Please refer JSR 234 for more details. + */ + public final int STARTED = 400; + + /** + * Please refer JSR 234 for more details. + */ + public final int STOPPED = 300; + + + + /** + * Please refer JSR 234 for more details. + * + */ + public void setInput(InputStream input, int length) throws javax.microedition.media.MediaException; + + /** + * Please refer JSR 234 for more details. + * + */ + public void setInput(Object image) throws javax.microedition.media.MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void setOutput(OutputStream output); + + /** + * Please refer JSR 234 for more details. + */ + public void start() throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void stop() throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void complete() throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void abort(); + + /** + * Please refer JSR 234 for more details. + */ + public void addMediaProcessorListener(MediaProcessorListener mediaProcessorListener); + + /** + * Please refer JSR 234 for more details. + */ + public void removeMediaProcessorListener(MediaProcessorListener mediaProcessorListener); + + /** + * Please refer JSR 234 for more details. + */ + public int getProgress(); + + /** + * Please refer JSR 234 for more details. + */ + public int getState(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/MediaProcessorListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/MediaProcessorListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +/** + * Please refer JSR 234 for more details. + */ +public interface MediaProcessorListener +{ + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSOR_REALIZED = "processRealized"; + + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSING_STARTED = "processingStarted"; + + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSING_STOPPED = "processingStopped"; + + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSING_ABORTED = "processingAborted"; + + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSING_COMPLETED = "processingCompleted"; + + /** + * Please refer JSR 234 for more details. + */ + public static final String PROCESSING_ERROR = "processingError"; + + + /** + * Please refer JSR 234 for more details. + */ + public void mediaProcessorUpdate(MediaProcessor processor, String event, Object eventData); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/Module.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/Module.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +import javax.microedition.media.*; + +/** + * Please refer JSR 234 for more details. + */ +public interface Module extends Controllable +{ + + /** + * Please refer JSR 234 for more details. + */ + public void addMIDIChannel(Player player, int channel) + throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void removeMIDIChannel(Player player, int channel); + + /** + * Please refer JSR 234 for more details. + */ + public void addPlayer(Player player) throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public void removePlayer(Player player); + +}; diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/SoundSource3D.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/SoundSource3D.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +/** + * Please refer JSR 234 for more details. + */ +public interface SoundSource3D extends Module +{ + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/Spectator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/Spectator.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms; + +import javax.microedition.media.Controllable; +import javax.microedition.media.Control; +import javax.microedition.amms.control.audio3d.LocationControl; + + +/** + * Please refer JSR 234 for more details. + * + */ +public class Spectator implements Controllable +{ + /** + * All method calls are delegated to this Controllable object + */ + private Controllable iControllable; + + /** + * Package private constructor. Can be used only from GlobalManager. + * @param aControllable Used to delegate all operations. + */ + Spectator(Controllable aControllable) + { + iControllable = aControllable; + } + + /** + * From JSR. This is never called. Added to state that constructor + * is private. + */ + private Spectator() + { + } + + /** + * From JSR + */ + public Control getControl(java.lang.String aControlType) + { + return iControllable.getControl(aControlType); + } + + /** + * From JSR + */ + public Control[] getControls() + { + return iControllable.getControls(); + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/AudioFormatControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/AudioFormatControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,30 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; + +/** + * Please refer JSR 234 for more details. + */ +public interface AudioFormatControl extends FormatControl +{ + + + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/ContainerFormatControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/ContainerFormatControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; + +/** + * Please refer JSR 234 for more details. + */ +public interface ContainerFormatControl extends FormatControl +{ + + /** + * Please refer JSR 234 for more details. + * + */ + void setFormat(String format); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/EffectControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/EffectControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,88 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.*; + +/** + * Please refer JSR 234 for more details. + */ +public interface EffectControl extends javax.microedition.media.Control +{ + + /** + * Please refer JSR 234 for more details. + */ + public static final int SCOPE_LIVE_ONLY = 1; + + /** + * Please refer JSR 234 for more details. + */ + public static final int SCOPE_RECORD_ONLY = 2; + + /** + * Please refer JSR 234 for more details. + */ + public static final int SCOPE_LIVE_AND_RECORD = 3; + + + /** + * Please refer JSR 234 for more details. + */ + public void setEnabled(boolean enable); + + /** + * Please refer JSR 234 for more details. + */ + public boolean isEnabled(); + + /** + * Please refer JSR 234 for more details. + */ + public void setScope(int scope) throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + public int getScope(); + + /** + * Please refer JSR 234 for more details. + */ + public void setEnforced(boolean enforced); + + + /** + * Please refer JSR 234 for more details. + */ + public boolean isEnforced(); + + /** + * Please refer JSR 234 for more details. + */ + void setPreset(String preset); + + /** + * Please refer JSR 234 for more details. + */ + public String getPreset(); + + /** + * Please refer JSR 234 for more details. + */ + public String[] getPresetNames(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/EffectOrderControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/EffectOrderControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer JSR 234 for more details. + */ +public interface EffectOrderControl extends Control +{ + + /** + Please refer JSR 234 for more details. + */ + public int setEffectOrder(EffectControl effect, int order); + + /** + Please refer JSR 234 for more details. + */ + public int getEffectOrder(EffectControl effect); + + /** + * Please refer JSR 234 for more details. + */ + public EffectControl[] getEffectOrders(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/FormatControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/FormatControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,164 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.*; + +/** + * Please refer JSR 234 for more details. + */ +public interface FormatControl extends Control +{ + + /** + * Please refer JSR 234 for more details. + */ + public final static int METADATA_NOT_SUPPORTED = 0; + + /** + * Please refer JSR 234 for more details. + */ + public final static int METADATA_SUPPORTED_FIXED_KEYS = 1; + + /** + * Please refer JSR 234 for more details. + */ + public final static int METADATA_SUPPORTED_FREE_KEYS = 2; + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_BITRATE = "bitrate"; + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_BITRATE_TYPE = "bitrate type"; + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_SAMPLERATE = "sample rate"; + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_FRAMERATE = "frame rate"; + + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_QUALITY = "quality"; + + /** + * Please refer JSR 234 for more details. + */ + public final static String PARAM_VERSION_TYPE = "version type"; + + + + /** + * Please refer JSR 234 for more details. + */ + String[] getSupportedFormats(); + + /** + * Please refer JSR 234 for more details. + */ + String[] getSupportedStrParameters(); + + /** + * Please refer JSR 234 for more details. + */ + String[] getSupportedIntParameters(); + + + /** + * Please refer JSR 234 for more details. + */ + String[] getSupportedStrParameterValues(String parameter); + + + /** + * Please refer JSR 234 for more details. + */ + int[] getSupportedIntParameterRange(String parameter); + + /** + * Please refer JSR 234 for more details. + */ + void setFormat(String format); + + /** + * Please refer JSR 234 for more details. + */ + String getFormat(); + + /** + * Please refer JSR 234 for more details. + */ + int setParameter(String parameter, int value); + + /** + * Please refer JSR 234 for more details. + */ + void setParameter(String parameter, String value); + + + /** + * Please refer JSR 234 for more details. + */ + String getStrParameterValue(String parameter); + + /** + *Please refer JSR 234 for more details. + */ + int getIntParameterValue(String parameter); + + /** + * Please refer JSR 234 for more details. + */ + int getEstimatedBitRate() throws MediaException; + + + /** + * Please refer JSR 234 for more details. + */ + void setMetadata(String key, String value) throws MediaException; + + /** + * Please refer JSR 234 for more details. + */ + String[] getSupportedMetadataKeys(); + + /** + * Please refer JSR 234 for more details. + */ + int getMetadataSupportMode(); + + /** + * Please refer JSR 234 for more details. + */ + void setMetadataOverride(boolean override); + + /** + * Please refer JSR 234 for more details. + */ + boolean getMetadataOverride(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/ImageFormatControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/ImageFormatControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; + +/** + * Please refer JSR 234 for more details. + */ +public interface ImageFormatControl extends FormatControl +{ + + /** + * Please refer JSR 234 for more details. + */ + int getEstimatedImageSize(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/MIDIChannelControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/MIDIChannelControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + + +/** + * Please refer JSR 234 for more details. + */ + +public interface MIDIChannelControl + extends javax.microedition.media.Control +{ + + /** + * Please refer JSR 234 for more details. + */ + Control getChannelControl(java.lang.String controlType, int channel); + + /** + * Please refer JSR 234 for more details. + */ + Control[] getChannelControls(int channel); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/PanControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/PanControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,35 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +/** + * Please refer JSR 234 for more details. + */ + +public interface PanControl extends javax.microedition.media.Control +{ + + /** + * Please refer JSR 234 for more details. + */ + int setPan(int pan); + + /** + * Please refer JSR 234 for more details. + */ + int getPan(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/PriorityControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/PriorityControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +/** +Please refer JSR 234 for more details. +*/ +public interface PriorityControl extends javax.microedition.media.Control +{ + + /** + * Please refer JSR 234 for more details. + */ + public int getPriority(); + + /** + * Please refer JSR 234 for more details. + */ + public void setPriority(int level); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/VideoFormatControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/VideoFormatControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control; + +import javax.microedition.media.MediaException; + +/** + * Please refer JSR 234 for more details. + */ +public interface VideoFormatControl extends FormatControl +{ + + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/CommitControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/CommitControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.media.*; +import javax.microedition.amms.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface CommitControl extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public void setDeferred(boolean deferred); + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isDeferred(); + + /** + * Please refer to JSR 234 for more details. + */ + public void commit(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DirectivityControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DirectivityControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +/** + * Please refer to JSR 234 for more details. + */ + +public interface DirectivityControl extends OrientationControl +{ + + /** + Please refer to JSR 234 for more details. + */ + public void setParameters(int minAngle, + int maxAngle, + int rearLevel); + /** + * Please refer to JSR 234 for more details. + */ + public int[] getParameters(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DistanceAttenuationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DistanceAttenuationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.media.*; +import javax.microedition.amms.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface DistanceAttenuationControl + extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public void setParameters(int minDistance, + int maxDistance, + boolean muteAfterMax, + int rolloffFactor); + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinDistance(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxDistance(); + + /** + * Please refer to JSR 234 for more details. + */ + public boolean getMuteAfterMax(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getRolloffFactor(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DopplerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/DopplerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.media.*; +import javax.microedition.media.control.PitchControl; +import javax.microedition.amms.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface DopplerControl extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public void setEnabled(boolean dopplerEnabled); + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isEnabled(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setVelocityCartesian(int x, int y, int z); + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getVelocityCartesian(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setVelocitySpherical(int azimuth, int elevation, int radius); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/LocationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/LocationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.media.*; + +/** + * + Please refer to JSR 234 for more details. + */ + +public interface LocationControl extends javax.microedition.media.Control +{ + + /** + Please refer to JSR 234 for more details. + */ + public void setCartesian(int x, int y, int z); + + + /** + * Please refer to JSR 234 for more details. + */ + public void setSpherical(int azimuth, int elevation, int radius); + + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getCartesian(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/MacroscopicControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/MacroscopicControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.amms.*; + +/** + * Please refer to JSR 234 for more details. + */ + +public interface MacroscopicControl extends OrientationControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + void setSize(int x, int y, int z); + + /** + * Please refer to JSR 234 for more details. + */ + int[] getSize(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/ObstructionControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/ObstructionControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ObstructionControl extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public void setLevel(int level); + + /** + * Please refer to JSR 234 for more details. + */ + public int getLevel(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setHFLevel(int HFLevel); + + /** + * Please refer to JSR 234 for more details. + */ + public int getHFLevel(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/OrientationControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audio3d/OrientationControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audio3d; + +import javax.microedition.media.*; + +/** + * Please refer to JSR 234 for more details. + */ + +public interface OrientationControl extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public void setOrientation(int heading, int pitch, int roll); + + /** + * Please refer to JSR 234 for more details. + */ + public void setOrientation(int[] frontVector, int[] aboveVector) + throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getOrientationVectors(); + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/AudioVirtualizerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/AudioVirtualizerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,27 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audioeffect; + +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface AudioVirtualizerControl extends EffectControl +{ + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ChorusControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ChorusControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audioeffect; + +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ChorusControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + public int setWetLevel(int level); + + /** + * Please refer to JSR 234 for more details. + * + */ + public int getWetLevel(); + + /** + * Please refer to JSR 234 for more details. + */ + void setModulationRate(int rate); + + /** + * Please refer to JSR 234 for more details. + */ + int getModulationRate(); + + /** + * Please refer to JSR 234 for more details. + */ + int getMinModulationRate(); + + /** + * Please refer to JSR 234 for more details. + */ + int getMaxModulationRate(); + + /** + * Please refer to JSR 234 for more details. + */ + void setModulationDepth(int percentage); + + + /** + * Please refer to JSR 234 for more details. + */ + int getModulationDepth(); + + /** + * Please refer to JSR 234 for more details. + */ + int getMaxModulationDepth(); + + + /** + * Please refer to JSR 234 for more details. + */ + void setAverageDelay(int delay); + + /** + * Please refer to JSR 234 for more details. + */ + int getAverageDelay(); + + + /** + * Please refer to JSR 234 for more details. + */ + int getMaxAverageDelay(); + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/EqualizerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/EqualizerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audioeffect; + +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ + +public interface EqualizerControl + extends EffectControl +{ + + public final int UNDEFINED = -1004; + + + /** + * Please refer to JSR 234 for more details. + */ + int getMinBandLevel(); + + /** + * Please refer to JSR 234 for more details. + */ + int getMaxBandLevel(); + + /** + * Please refer to JSR 234 for more details. + */ + void setBandLevel(int level, int band) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int getBandLevel(int band) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int getNumberOfBands(); + + /** + * Please refer to JSR 234 for more details. + */ + int getCenterFreq(int band) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int getBand(int frequency); + + /** + * Please refer to JSR 234 for more details. + */ + int setBass(int level) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int setTreble(int level) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int getBass(); + + /** + * Please refer to JSR 234 for more details. + */ + int getTreble(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ReverbControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ReverbControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audioeffect; + +import javax.microedition.media.*; +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ReverbControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + int setReverbLevel(int level) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int getReverbLevel(); + + + /** + * Please refer to JSR 234 for more details. + */ + void setReverbTime(int time) throws IllegalArgumentException, + javax.microedition.media.MediaException; + + + /** + * Please refer to JSR 234 for more details. + */ + int getReverbTime() throws + javax.microedition.media.MediaException; + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ReverbSourceControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/audioeffect/ReverbSourceControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.audioeffect; + +import javax.microedition.media.*; +import javax.microedition.media.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ReverbSourceControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final int DISCONNECT = Integer.MAX_VALUE; + + + /** + * Please refer to JSR 234 for more details. + */ + public void setRoomLevel(int level) + throws MediaException; + + + /** + * Please refer to JSR 234 for more details. + */ + public int getRoomLevel(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/CameraControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/CameraControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,111 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + */ +public interface CameraControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int ROTATE_LEFT = 2; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int ROTATE_RIGHT = 3; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int ROTATE_NONE = 1; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int UNKNOWN = -1004; + + /** + * Please refer to JSR 234 for more details. + */ + public int getCameraRotation(); + + + /** + * Please refer to JSR 234 for more details. + */ + public void enableShutterFeedback(boolean enable) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isShutterFeedbackEnabled(); + + /** + * Please refer to JSR 234 for more details. + */ + public String[] getSupportedExposureModes(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setExposureMode(String mode); + + /** + * Please refer to JSR 234 for more details. + */ + public String getExposureMode(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedVideoResolutions(); + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedStillResolutions(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setVideoResolution(int index); + + /** + * Please refer to JSR 234 for more details. + */ + public void setStillResolution(int index); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getVideoResolution(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getStillResolution(); +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/ExposureControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/ExposureControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,130 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + * + + * + * @see CameraControl#setExposureMode + */ +public interface ExposureControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedFStops(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getFStop(); + + + /** + * Please refer to JSR 234 for more details. + */ + public void setFStop(int aperture) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinExposureTime(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxExposureTime(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getExposureTime(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int setExposureTime(int time) throws MediaException; + + + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedISOs(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getISO(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setISO(int iso) throws MediaException; + + + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedExposureCompensations(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getExposureCompensation(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setExposureCompensation(int ec) throws MediaException; + + + /** + * Please refer to JSR 234 for more details. + */ + public int getExposureValue(); + + + + /** + * Please refer to JSR 234 for more details. + */ + public String[] getSupportedLightMeterings(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setLightMetering(String metering); + + /** + * Please refer to JSR 234 for more details. + */ + public String getLightMetering(); + + +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/FlashControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/FlashControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + */ +public interface FlashControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int OFF = 1; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO = 2; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO_WITH_REDEYEREDUCE = 3; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int FORCE = 4; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int FORCE_WITH_REDEYEREDUCE = 5; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int FILLIN = 6; + + /** + * Please refer to JSR 234 for more details. + */ + public int[] getSupportedModes(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setMode(int mode); + + /** + * Please refer to JSR 234 for more details. + */ + public int getMode(); + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isFlashReady(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/FocusControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/FocusControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + */ +public interface FocusControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO = -1000; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO_LOCK = -1005; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int NEXT = -1001; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int PREVIOUS = -1002; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int UNKNOWN = -1004; + + /** + * Please refer to JSR 234 for more details. + */ + public int setFocus(int distance) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public int getFocus(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinFocus(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getFocusSteps(); + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isManualFocusSupported(); + + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isAutoFocusSupported(); + + + /** + * Please refer to JSR 234 for more details. + */ + public boolean isMacroSupported(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setMacro(boolean enable) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public boolean getMacro(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/SnapshotControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/SnapshotControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + */ +public interface SnapshotControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + String SHOOTING_STOPPED = "SHOOTING_STOPPED"; + + /** + * Please refer to JSR 234 for more details. + */ + String STORAGE_ERROR = "STORAGE_ERROR"; + + /** + * Please refer to JSR 234 for more details. + */ + String WAITING_UNFREEZE = "WAITING_UNFREEZE"; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int FREEZE = -2; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int FREEZE_AND_CONFIRM = -1; + + + + /** + * Please refer to JSR 234 for more details. + */ + void setDirectory(String directory); + + /** + * Please refer to JSR 234 for more details. + */ + String getDirectory(); + + /** + * Please refer to JSR 234 for more details. + */ + void setFilePrefix(String prefix); + + /** + * Please refer to JSR 234 for more details. + */ + String getFilePrefix(); + + /** + * Please refer to JSR 234 for more details. + */ + void setFileSuffix(String suffix); + + /** + * Please refer to JSR 234 for more details. + */ + String getFileSuffix(); + + /** + * Please refer to JSR 234 for more details. + */ + void start(int maxShots) throws SecurityException; + + + /** + * Please refer to JSR 234 for more details. + */ + void stop(); + + /** + * Please refer to JSR 234 for more details. + */ + void unfreeze(boolean save); + +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/ZoomControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/camera/ZoomControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.camera; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ZoomControl extends Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int NEXT = -1001; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int PREVIOUS = -1002; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int UNKNOWN = -1004; + + /** + * Please refer to JSR 234 for more details. + */ + public int setOpticalZoom(int level); + + /** + * Please refer to JSR 234 for more details. + */ + public int getOpticalZoom(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxOpticalZoom(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getOpticalZoomLevels(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinFocalLength(); + + /** + * Please refer to JSR 234 for more details. + */ + public int setDigitalZoom(int level); + + /** + * Please refer to JSR 234 for more details. + */ + public int getDigitalZoom(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxDigitalZoom(); + + + /** + * Please refer to JSR 234 for more details. + */ + public int getDigitalZoomLevels(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageEffectControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageEffectControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.imageeffect; + +import javax.microedition.media.MediaException; +import javax.microedition.lcdui.Image; +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ImageEffectControl extends EffectControl +{ + +} + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageTonalityControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageTonalityControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,89 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.imageeffect; + +import javax.microedition.media.MediaException; +import javax.microedition.amms.control.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface ImageTonalityControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO = -1000; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int NEXT = -1001; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int PREVIOUS = -1002; + + /** + * Please refer to JSR 234 for more details. + */ + int setBrightness(int level); + + /** + * Please refer to JSR 234 for more details. + */ + int getBrightness(); + + /** + * Please refer to JSR 234 for more details. + */ + int getBrightnessLevels(); + + + /** + * Please refer to JSR 234 for more details. + */ + int setContrast(int level); + + /** + * Please refer to JSR 234 for more details. + */ + int getContrast(); + + /** + * Please refer to JSR 234 for more details. + */ + int getContrastLevels(); + + /** + * Please refer to JSR 234 for more details. + */ + int setGamma(int level); + + /** + * Please refer to JSR 234 for more details. + */ + int getGamma(); + + /** + * Please refer to JSR 234 for more details. + */ + int getGammaLevels(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageTransformControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/ImageTransformControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.imageeffect; + +import javax.microedition.media.Control; +import javax.microedition.amms.control.*; + +/** + * + * Please refer to JSR 234 for more details. + */ +public interface ImageTransformControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + public int getSourceWidth(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getSourceHeight(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setSourceRect(int x, int y, int width, int height); + + + /** + * Please refer to JSR 234 for more details. + */ + public void setTargetSize(int width, int height, int rotation); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/OverlayControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/OverlayControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.imageeffect; + +import javax.microedition.lcdui.Image; +import javax.microedition.amms.control.*; +import javax.microedition.media.*; + +/** + * Please refer to JSR 234 for more details. + */ +public interface OverlayControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + int insertImage(Object image, int x, int y, int order) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + int insertImage(Object image, int x, int y, int order, int transparentColor) throws IllegalArgumentException; + + /** + * Please refer to JSR 234 for more details. + */ + void removeImage(Object image); + + + /** + * Please refer to JSR 234 for more details. + */ + Object getImage(int order); + + /** + * Please refer to JSR 234 for more details. + */ + int numberOfImages(); + + + + /** + * Please refer to JSR 234 for more details. + * + */ + void clear(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/WhiteBalanceControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/imageeffect/WhiteBalanceControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.imageeffect; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; +import javax.microedition.amms.control.EffectControl; + +/** + * Please refer to JSR 234 for more details. + */ +public interface WhiteBalanceControl extends EffectControl +{ + + /** + * Please refer to JSR 234 for more details. + */ + public final static int AUTO = -1000; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int NEXT = -1001; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int PREVIOUS = -1002; + + /** + * Please refer to JSR 234 for more details. + */ + public final static int UNKNOWN = -1004; + + /** + * Please refer to JSR 234 for more details. + */ + int setColorTemp(int temp); + + /** + * Please refer to JSR 234 for more details. + */ + int getColorTemp(); + + /** + * Please refer to JSR 234 for more details. + */ + int getMinColorTemp(); + + + /** + * Please refer to JSR 234 for more details. + */ + int getMaxColorTemp(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getNumberOfSteps(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/tuner/RDSControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/tuner/RDSControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.tuner; + +import javax.microedition.media.*; + +import java.util.Date; + +/** + * Please refer to JSR 234 for more details. + */ + +public interface RDSControl extends javax.microedition.media.Control +{ + + /** + * Please refer to JSR 234 for more details. + */ + String RDS_NEW_DATA = "RDS_NEW_DATA"; + + /** + * Please refer to JSR 234 for more details. + */ + String RDS_NEW_ALARM = "RDS_ALARM"; + + /** + * Please refer to JSR 234 for more details. + */ + String RADIO_CHANGED = "radio_changed"; + + /** + * Please refer to JSR 234 for more details. + */ + boolean isRDSSignal(); + + /** + * Please refer to JSR 234 for more details. + */ + String getPS(); + + /** + * Please refer to JSR 234 for more details. + */ + String getRT(); + + /** + * Please refer to JSR 234 for more details. + */ + short getPTY(); + + /** + * Please refer to JSR 234 for more details. + */ + String getPTYString(boolean longer); + + /** + * Please refer to JSR 234 for more details. + */ + short getPI(); + + /** + * Please refer to JSR 234 for more details. + */ + int[] getFreqsByPTY(short PTY); + + /** + * Please refer to JSR 234 for more details. + */ + int[][] getFreqsByTA(boolean TA); + + /** + * Please refer to JSR 234 for more details. + */ + String[] getPSByPTY(short PTY); + + /** + * Please refer to JSR 234 for more details. + */ + String[] getPSByTA(boolean TA); + + /** + * Please refer to JSR 234 for more details. + */ + Date getCT(); + + /** + * Please refer to JSR 234 for more details. + */ + boolean getTA(); + + /** + * Please refer to JSR 234 for more details. + */ + boolean getTP(); + + /** + * Please refer to JSR 234 for more details. + */ + void setAutomaticSwitching(boolean automatic) + throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + boolean getAutomaticSwitching(); + + /** + * Please refer to JSR 234 for more details. + */ + void setAutomaticTA(boolean automatic) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + boolean getAutomaticTA(); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/javasrc/javax/microedition/amms/control/tuner/TunerControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/javasrc/javax/microedition/amms/control/tuner/TunerControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,153 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package javax.microedition.amms.control.tuner; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; + +/** + * + * Please refer to JSR 234 for more details. + */ + +public interface TunerControl extends Control +{ + /** + * Please refer to JSR 234 for more details. + */ + public static final int MONO = 1; + + /** + * Please refer to JSR 234 for more details. + */ + public static final int STEREO = 2; + + /** + * Please refer to JSR 234 for more details. + */ + public static final int AUTO = 3; + + /** + * Please refer to JSR 234 for more details. + */ + public static final String MODULATION_FM = "fm"; + + /** + * Please refer to JSR 234 for more details. + */ + public static final String MODULATION_AM = "am"; + + /** + * Please refer to JSR 234 for more details. + */ + public int getMinFreq(String modulation); + + /** + * Please refer to JSR 234 for more details. + */ + public int getMaxFreq(String modulation); + + /** + * Please refer to JSR 234 for more details. + */ + public int setFrequency(int freq, String modulation); + + /** + * Please refer to JSR 234 for more details. + */ + public int getFrequency(); + + /** + * Please refer to JSR 234 for more details. + */ + public int seek(int startFreq, String modulation, boolean upwards) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public boolean getSquelch(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setSquelch(boolean squelch) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public String getModulation(); + + /** + * Please refer to JSR 234 for more details. + */ + public int getSignalStrength() throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public int getStereoMode(); + + /** + * Please refer to JSR 234 for more details. + */ + public void setStereoMode(int mode); + + /** + * Please refer to JSR 234 for more details. + */ + public int getNumberOfPresets(); + + /** + * Please refer to JSR 234 for more details. + */ + public void usePreset(int preset); + + /** + * Please refer to JSR 234 for more details. + */ + public void setPreset(int preset); + + /** + * Please refer to JSR 234 for more details. + */ + public void setPreset(int preset, int freq, String mod, int stereoMode); + + /** + * Please refer to JSR 234 for more details. + */ + public int getPresetFrequency(int preset); + + /** + * Please refer to JSR 234 for more details. + */ + public String getPresetModulation(int preset); + + /** + * Please refer to JSR 234 for more details. + */ + public int getPresetStereoMode(int preset) throws MediaException; + + /** + * Please refer to JSR 234 for more details. + */ + public String getPresetName(int preset); + + /** + * Please refer to JSR 234 for more details. + */ + public void setPresetName(int preset, String name); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/ammsplugin.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/ammsplugin.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Creates CAMMSPriorityControl and adds it to the player. +* +*/ + + +//#include +#include + +#include "com_nokia_amms_AMMSPlugin.h" +#include +#include +#include "cammsprioritycontrol.h" +#include "cammsaudiooutputcontrol.h" + +/** + * Creates CAMMSPriorityControl and adds it to the player. + * Returns the created control through the given parameter. + */ +static void CreatePriorityControlL(CMMAPlayer* aPlayer, + CAMMSPriorityControl** aControl) +{ + LOG( EJavaAMMS, EInfo, "CreatePriorityControlL +"); + + CAMMSPriorityControl* control = CAMMSPriorityControl::NewLC(aPlayer); + + aPlayer->AddControlL(control); + + CleanupStack::Pop(control); + + *aControl = control; + + LOG( EJavaAMMS, EInfo, "CreatePriorityControlL -"); +} + +/** +* Creates CAMMSAudioOutputControl and adds it to the player. +* Returns the created control through the given parameter. +*/ +static void CreateAudioOutputControlL(CMMAPlayer* aPlayer, + CAMMSAudioOutputControl** aControl) +{ + LOG( EJavaAMMS, EInfo, "CreatePriorityControlL +"); + + CAMMSAudioOutputControl* control = CAMMSAudioOutputControl::NewLC(aPlayer); + + aPlayer->AddControlL(control); + + CleanupStack::Pop(control); + + *aControl = control; + + LOG( EJavaAMMS, EInfo, "CAMMSAudioOutputControl -"); +} +/* + * Class: com_nokia_amms_AMMSPlugin + * Method: _createNativePriorityControl + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_AMMSPlugin__1createNativePriorityControl( + JNIEnv*, + jclass, + jint aEventSource, + jint aPlayer) +{ + LOG( EJavaAMMS, EInfo, "AMMS: Java_com_nokia_amms_AMMSPlugin__1createNativePriorityControl + "); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAPlayer* player = reinterpret_cast< CMMAPlayer* >(aPlayer); + + + // Create control and add it to the player. + CAMMSPriorityControl* control = NULL; + + TInt handle = + eventSource->ExecuteTrap(&CreatePriorityControlL, player, &control); + + __ASSERT_DEBUG(control, User::Invariant()); + + if (handle == KErrNone) + { + handle = reinterpret_cast(control); + } + + LOG( EJavaAMMS, EInfo, "AMMS: Java_com_nokia_amms_AMMSPlugin__1createNativePriorityControl - "); + + return handle; +} + +/* +* Class: com_nokia_amms_AMMSPlugin +* Method: _createNativeAudioOutputControl +* +*/ + +JNIEXPORT jint JNICALL Java_com_nokia_amms_AMMSPlugin__1createNativeAudioOutputControl( + JNIEnv*, + jclass, + jint aEventSource, + jint aPlayer) +{ + LOG( EJavaAMMS, EInfo, "AMMS: Java_com_nokia_amms_AMMSPlugin__1createNativeAudioOutputControl + "); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAPlayer* player = reinterpret_cast< CMMAPlayer* >(aPlayer); + + + // Create control and add it to the player. + CAMMSAudioOutputControl* control = NULL; + + TInt handle = + eventSource->ExecuteTrap(&CreateAudioOutputControlL, player, &control); + + __ASSERT_DEBUG(control, User::Invariant()); + + if (handle == KErrNone) + { + handle = reinterpret_cast(control); + } + + LOG( EJavaAMMS, EInfo, "AMMS: Java_com_nokia_amms_AMMSPlugin__1createNativeAudioOutputControl - "); + + return handle; +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/audiooutputcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/audiooutputcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,148 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Creates cammsaudiooutputcontrol. +* +*/ + + +//#include +#include +#include "com_nokia_mid_impl_media_AudioOutputControl.h" +#include +#include "cammsaudiooutputcontrol.h" + +/** +* wrapper for CAMMSAudioOutputControl::GetPreference() +*/ +static TInt GetPreference(CAMMSAudioOutputControl* aControl) +{ + TInt val = aControl->GetAudioOutput(); + return val; +} + +/** +* wrapper for CAMMSAudioOutputControl::SetPreferenceL() +*/ +static TInt SetPreference(CAMMSAudioOutputControl* aControl, TInt aPreference) +{ + return aControl->SetAudioOutput(aPreference); +} + +/** +* wrapper for CAMMSAudioOutputControl::GetCurrent() +*/ +static void GetCurrent(CAMMSAudioOutputControl* aControl) +{ + aControl->GetCurrentPreference(); +} + +/** +* wrapper for CAMMSAudioOutputControl::SetJavaAudioOutputObj() +*/ +static void SetJavaAudioOutputObj(CAMMSAudioOutputControl* aControl,jobject obj) +{ + aControl->SetJavaAudioOutputObject(obj); +} + +/* +* Class: Java_com_nokia_mj_impl_media_AudioOutputControl +* Method: _getOutputMode +* +*/ + +JNIEXPORT jint JNICALL Java_com_nokia_mid_impl_media_AudioOutputControl__1getOutputMode( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + CAMMSAudioOutputControl* control = static_cast< CAMMSAudioOutputControl* >( + reinterpret_cast< CAMMSControl* >(aControl)); + __ASSERT_DEBUG(control, User::Invariant()); + return eventSource->Execute(GetPreference, control); +} + +/* +* Class: Java_com_nokia_mj_impl_media_AudioOutputControl +* Method: _setOutputMode +* +*/ +JNIEXPORT jint JNICALL Java_com_nokia_mid_impl_media_AudioOutputControl__1setOutputMode( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aPreference) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSAudioOutputControl* control = static_cast< CAMMSAudioOutputControl* >( + reinterpret_cast< CAMMSControl* >(aControl)); + __ASSERT_DEBUG(control, User::Invariant()); + TInt error = eventSource->Execute( + &SetPreference, control, (TInt) aPreference); + ELOG1( EJavaAMMS, "AMMS::AudioOutputControl_JNI::setOutputMode = %d", error); + return error; +} + + +/* +* Class: Java_com_nokia_mj_impl_media_AudioOutputControl +* Method: _getCurrent +* +*/ + +JNIEXPORT jint JNICALL Java_com_nokia_mid_impl_media_AudioOutputControl__1getCurrent( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSAudioOutputControl* control = static_cast< CAMMSAudioOutputControl* >( + reinterpret_cast< CAMMSControl* >(aControl)); + __ASSERT_DEBUG(control, User::Invariant()); + TInt err = eventSource->ExecuteTrap(GetCurrent, control); + ELOG1( EJavaAMMS, "AMMS::AudioOutputControl_JNI::getCurrent = %d", err); + return err; +} + + +/* +* Class: com_nokia_mj_impl_media_AudioOutputControl +* Method: _setAudioOutputObject +* Signature: (IILjava/lang/Object;)I +*/ +JNIEXPORT jint JNICALL Java_com_nokia_mid_impl_media_AudioOutputControl__1setAudioOutputObject +(JNIEnv *jni, jclass, jint aEventSource, jint aControl, jobject audioOutputObj) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + CAMMSAudioOutputControl* control = static_cast< CAMMSAudioOutputControl* >( + reinterpret_cast< CAMMSControl* >(aControl)); + __ASSERT_DEBUG(control, User::Invariant()); + jobject obj = jni->NewWeakGlobalRef(audioOutputObj); + TInt err = eventSource->ExecuteTrap(SetJavaAudioOutputObj,control ,obj); + ELOG1( EJavaAMMS, "AMMS::AudioOutputControl_JNI::setAudioOutputObject = %d", err); + return err; +} + + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/commitcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/commitcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_audio3d_CommitControl.h" +#include +#include "cammscommitcontrolgroup.h" + +/** + * wrapper for CAMMSCommitControlGroup::CommitAllControlsL() + */ +static void CommitL(CAMMSCommitControlGroup* aControl) +{ + aControl->CommitAllControlsL(); +} + +/** + * wrapper for CAMMSCommitControlGroup::SetDeferredL() + */ +static void SetDeferredL(CAMMSCommitControlGroup* aControl, TBool aDeferred) +{ + aControl->SetDeferredL(aDeferred); +} + +/* + * Class: com_nokia_amms_control_audio3d_CommitControl + * Method: _commit + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audio3d_CommitControl__1commit( + JNIEnv*, + jclass, + jint aEventSource, + jint aCommitControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSCommitControlGroup* commitControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aCommitControl)); + + TInt error; + error = eventSource->ExecuteTrap(&CommitL, commitControl); + + return error; +} + +/* + * Class: com_nokia_amms_control_audio3d_CommitControl + * Method: _setDeferred + * Signature: (IIZ)V + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audio3d_CommitControl__1setDeferred( + JNIEnv*, + jclass, + jint aEventSource, + jint aCommitControl, + jboolean aDeferred) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSCommitControlGroup* commitControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aCommitControl)); + + TInt error; + error = eventSource->ExecuteTrap(&SetDeferredL, commitControl, + (TBool) aDeferred); + + return error; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/controlcontainer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/controlcontainer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,90 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI file for ControlContainer +* +*/ + + +//#include +#include + +#include "com_nokia_amms_ControlContainer.h" + +#include "cammscontrolgroup.h" +#include "cammsmodule.h" +#include "jstringutils.h" +#include "s60commonutils.h" +using namespace java::util; + +/** + * JNI function. + */ +JNIEXPORT jstring JNICALL Java_com_nokia_amms_ControlContainer__1getControlClassName +(JNIEnv* aJniEnv, + jclass, + jint /*aEventSourceHandle*/, + jint aNativeHandle) +{ + CAMMSControlGroup* controlGroup = + reinterpret_cast< CAMMSControlGroup* >(aNativeHandle); + + LOG1( EJavaAMMS, EInfo, "AMMS::ControlContainer.cpp::getControlClassName name = %S", + controlGroup->ClassName().Ptr()); + + return S60CommonUtils::NativeToJavaString(*aJniEnv, controlGroup->ClassName()); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_ControlContainer__1getControlsCount +(JNIEnv*, + jclass, + jint /*aEventSourceHandle*/, + jint aNativeHandle) +{ + CAMMSModule* module = reinterpret_cast< CAMMSModule* >(aNativeHandle); + + LOG1( EJavaAMMS, EInfo, "AMMS::ControlContainer.cpp::getControlsCount count = %d", + module->Count()); + return module->Count(); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_ControlContainer__1getControlHandle +(JNIEnv*, + jclass, + jint /*aEventSourceHandle*/, + jint aNativeHandle, + jint aIndex) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::ControlContainer.cpp::getControlHandle index = %d", + aIndex); + CAMMSModule* module = reinterpret_cast< CAMMSModule *>(aNativeHandle); + + // Java handles must be created from CBase derived classes. + // Casting here is safe because all groups in the modules are derived from + // CAMMSControlGroup. + CAMMSControlGroup* group = static_cast< CAMMSControlGroup* >( + module->At(aIndex)); // CSI: 1 Wrong index means implementation error # + + return reinterpret_cast(group); +} + +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/distanceattenuationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/distanceattenuationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,197 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI file for DistanceAttenuationControl +* +*/ + + +//#include + +#include "com_nokia_amms_control_audio3d_DistanceAttenuationControl.h" +#include +#include "cammsdistanceattenuationcontrolgroup.h" + +/** + * wrapper for CAMMSDistanceAttenuationControlGroup::MuteAfterMax() + */ +static TBool MuteAfterMax(CAMMSDistanceAttenuationControlGroup* aControl) +{ + return aControl->MuteAfterMax(); +} + +/** + * wrapper for CAMMSDistanceAttenuationControlGroup::MinDistance() + */ +static TInt32 MinDistance(CAMMSDistanceAttenuationControlGroup* aControl) +{ + return aControl->MinDistance(); +} + +/** + * wrapper for CAMMSDistanceAttenuationControlGroup::MaxDistance() + */ +static TInt32 MaxDistance(CAMMSDistanceAttenuationControlGroup* aControl) +{ + return aControl->MaxDistance(); +} + +/** + * wrapper for CAMMSDistanceAttenuationControlGroup::RolloffFactor() + */ +static TUint32 RolloffFactor(CAMMSDistanceAttenuationControlGroup* aControl) +{ + return aControl->RolloffFactor(); +} + +/** + * wrapper for CAMMSDistanceAttenuationControlGroup::SetParametersL() + */ +static void SetParametersL( + CAMMSDistanceAttenuationControlGroup* aControl, + TInt aMinDistance, + TInt aMaxDistance, + TBool aMuteAfterMax, + TInt aRolloffFactor) +{ + aControl->SetParametersL( + aMinDistance, + aMaxDistance, + aMuteAfterMax, + aRolloffFactor); +} + +/* + * Class: com_nokia_amms_control_audio3d_DistanceAttenuationControl + * Method: _getMuteAfterMax + * Signature: (II)Z + */ +JNIEXPORT jboolean JNICALL +Java_com_nokia_amms_control_audio3d_DistanceAttenuationControl__1getMuteAfterMax( + JNIEnv*, + jclass, + jint aEventSource, + jint aDistControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDistanceAttenuationControlGroup* distControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDistControl)); + + return (jboolean) eventSource->Execute(MuteAfterMax, distControl); +} + +/* + * Class: com_nokia_amms_control_audio3d_DistanceAttenuationControl + * Method: _getMinDistance + * Signature: (II)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DistanceAttenuationControl__1getMinDistance( + JNIEnv*, + jclass, + jint aEventSource, + jint aDistControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDistanceAttenuationControlGroup* distControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDistControl)); + + return (jint) eventSource->Execute(MinDistance, distControl); +} + +/* + * Class: com_nokia_amms_control_audio3d_DistanceAttenuationControl + * Method: _getMaxDistance + * Signature: (II)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DistanceAttenuationControl__1getMaxDistance( + JNIEnv*, + jclass, + jint aEventSource, + jint aDistControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDistanceAttenuationControlGroup* distControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDistControl)); + + return (jint) eventSource->Execute(MaxDistance, distControl); +} + +/* + * Class: com_nokia_amms_control_audio3d_DistanceAttenuationControl + * Method: _getRolloffFactor + * Signature: (II)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DistanceAttenuationControl__1getRolloffFactor( + JNIEnv*, + jclass, + jint aEventSource, + jint aDistControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDistanceAttenuationControlGroup* distControl = + static_cast( + reinterpret_cast< CAMMSControlGroup *>(aDistControl)); + + return (jint) eventSource->Execute(RolloffFactor, distControl); +} + +/* + * Class: com_nokia_amms_control_audio3d_DistanceAttenuationControl + * Method: _setParameters + * Signature: (IIIIZI)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DistanceAttenuationControl__1setParameters( + JNIEnv*, + jclass, + jint aEventSource, + jint aDistControl, + jint aMinDistance, + jint aMaxDistance, + jboolean aMuteAfterMax, + jint aRolloffFactor) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDistanceAttenuationControlGroup* distControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDistControl)); + + TInt error; + error = eventSource->ExecuteTrap( + &SetParametersL, + distControl, + (TInt) aMinDistance, + (TInt) aMaxDistance, + (TBool) aMuteAfterMax, + (TInt) aRolloffFactor); + + return error; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/dopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/dopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,225 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI file for DopplerControl +* +*/ + + +//#include + +#include "com_nokia_amms_control_audio3d_DopplerControl.h" +#include +#include "cammsdopplercontrolgroup.h" + +/** + * wrapper for CAMMSDopplerControlGroup::SetEnabledL() + */ +static void SetEnabledL(CAMMSDopplerControlGroup* aControl, TBool aEnabled) +{ + aControl->SetEnabledL(aEnabled); +} + +/** + * wrapper for CAMMSDopplerControlGroup::SetVelocitySphericalL() + */ +static void SetVelocitySphericalL(CAMMSDopplerControlGroup* aControl, + TInt aAzimuth, TInt aElevation, TInt aRadius) +{ + aControl->SetVelocitySphericalL(aAzimuth, aElevation, aRadius); +} + +/** + * wrapper for CAMMSDopplerControlGroup::VelocityCartesian() + */ +static void GetVelocityCartesianL( + CAMMSDopplerControlGroup* aControl, + TInt aVelocity[ KAMMSVectorComponents ]) +{ + aControl->VelocityCartesianL(aVelocity); +} + +/** + * wrapper for CAMMSDopplerControlGroup::Enabled() + */ +static TBool IsEnabled(CAMMSDopplerControlGroup* aControl) +{ + return aControl->Enabled(); +} + +/** + * wrapper for CAMMSDopplerControlGroup::SetVelocityCartesianL() + */ +static void SetVelocityCartesianL( + CAMMSDopplerControlGroup* aControl, + TInt aX, + TInt aY, + TInt aZ) +{ + aControl->SetVelocityCartesianL(aX, aY, aZ); +} + +/* + * Class: com_nokia_amms_control_audio3d_DopplerControl + * Method: _setEnabled + * Signature: (IIZ)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DopplerControl__1setEnabled( + JNIEnv*, + jclass, + jint aEventSource, + jint aDopplerControl, + jboolean aEnabled) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDopplerControlGroup* dopplerControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDopplerControl)); + + TInt error; + error = eventSource->ExecuteTrap( + SetEnabledL, + dopplerControl, + (TBool) aEnabled); + return error; +} + +/* + * Class: com_nokia_amms_control_audio3d_DopplerControl + * Method: _setVelocitySpherical + * Signature: (IIIII)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DopplerControl__1setVelocitySpherical( + JNIEnv*, + jclass, + jint aEventSource, + jint aDopplerControl, + jint aAzimuth, + jint aElevation, + jint aRadius) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDopplerControlGroup* dopplerControl = + static_cast( + reinterpret_cast< CAMMSControlGroup *>(aDopplerControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetVelocitySphericalL, dopplerControl, + (TInt) aAzimuth, (TInt) aElevation, (TInt) aRadius); + + return error; +} + +/* + * Class: com_nokia_amms_control_audio3d_DopplerControl + * Method: _getVelocityCartesian + * Signature: (II)[I + */ +JNIEXPORT jintArray JNICALL +Java_com_nokia_amms_control_audio3d_DopplerControl__1getVelocityCartesian( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aDopplerControl, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSDopplerControlGroup* dopplerControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDopplerControl)); + + TInt velocity[ KAMMSVectorComponents ]; + TInt error = eventSource->ExecuteTrap(GetVelocityCartesianL, + dopplerControl, + velocity); + // allocate new array + jintArray javaArray = aJni->NewIntArray(KAMMSVectorComponents); + if (javaArray) + { + aJni->SetIntArrayRegion( + /*destination*/ javaArray, + /*first*/ 0, + /*count*/ KAMMSVectorComponents, + /*source*/ velocity); + } + + jint javaError[ 1 ] = { error }; + aJni->SetIntArrayRegion(aError, 0, 1, javaError); + + return javaArray; +} + +/* + * Class: com_nokia_amms_control_audio3d_DopplerControl + * Method: _isEnabled + * Signature: (II)Z + */ +JNIEXPORT jboolean JNICALL +Java_com_nokia_amms_control_audio3d_DopplerControl__1isEnabled( + JNIEnv*, + jclass, + jint aEventSource, + jint aDopplerControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDopplerControlGroup* dopplerControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDopplerControl)); + + return (jboolean) eventSource->Execute(IsEnabled, dopplerControl); +} + +/* + * Class: com_nokia_amms_control_audio3d_DopplerControl + * Method: _setVelocityCartesian + * Signature: (IIIII)I + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_DopplerControl__1setVelocityCartesian( + JNIEnv*, + jclass, + jint aEventSource, + jint aDopplerControl, + jint aX, + jint aY, + jint aZ) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSDopplerControlGroup* dopplerControl = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aDopplerControl)); + + TInt error; + error = eventSource->ExecuteTrap( + SetVelocityCartesianL, + dopplerControl, + (TInt) aX, + (TInt) aY, + (TInt) aZ); + + return error; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/effectcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/effectcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,300 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI for EffectControl +* +*/ + + +//#include +#include + +#include "com_nokia_amms_control_EffectControl.h" +#include +#include "cammseffectcontrolgroup.h" +#include "jstringutils.h" +#include "s60commonutils.h" +using namespace java::util; +#include + +/** + * wrapper for CAMMSEffectControlGroup::PresetNamesL() + */ +LOCAL_C void GetPresetNamesL(CAMMSEffectControlGroup* aControl, + JNIEnv* aJni, + jobjectArray* aArray) +{ + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + //aJni = JniEnvWrapper::GetValidJniRef(); + + // Create new java String array and copy values from the values array + *aArray = MMAPIUtils::CopyToNewJavaStringArrayL(*aJni, aControl->PresetNamesL()); +} + +/** + * wrapper for CAMMSEffectControlGroup::PresetL() + */ +static void GetPresetL( + CAMMSEffectControlGroup* aControl, + TDes* aPreset) +{ + aControl->GetPresetL(*aPreset); +} + +/** + * wrapper for CAMMSEffectControlGroup::SetEnabledL() + */ +static void SetEnabledL(CAMMSEffectControlGroup* aControl, TBool aEnabled) +{ + aControl->SetEnabledL(aEnabled); +} + +/** + * wrapper for CAMMSEffectControlGroup::SetScopeL() + */ +static void SetScopeL(CAMMSEffectControlGroup* aControl, TInt aScope) +{ + aControl->SetScopeL((CAMMSEffectControlGroup::TEffectScope) aScope); +} + +/** + * wrapper for CAMMSEffectControlGroup::SetEnforcedL() + */ +static void SetEnforcedL(CAMMSEffectControlGroup* aControl, TBool aEnforced) +{ + aControl->SetEnforcedL(aEnforced); +} + +/** + * wrapper for CAMMSEffectControlGroup::SetPresetL() + */ +static void SetPresetL(CAMMSEffectControlGroup* aControl, TDesC* aPreset) +{ + aControl->SetPresetL(*aPreset); +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _isEnabled + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1isEnabled( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + /*MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource);*/ + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->Enabled(); +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _isEnforced + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1isEnforced( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + /* MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource);*/ + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->Enforced(); +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _getPresetNames + * Signature: (II[Ljava/lang/String;)I + */ +JNIEXPORT jobjectArray JNICALL Java_com_nokia_amms_control_EffectControl__1getPresetNames( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + jobjectArray presetNames = NULL; + + TInt error = eventSource->ExecuteTrap(GetPresetNamesL, + control, + aJni, + &presetNames); + + // If an error happened, return null to Java + if (error != KErrNone) + { + presetNames = NULL; + } + return presetNames; +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _getPreset + * Signature: (II[Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1getPreset( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl, + jobjectArray aPreset) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + TBuf< KAMMSMaxPresetNameLength > preset; + + error = eventSource->ExecuteTrap(GetPresetL, control, (TDes*) &preset); + + if (error == KErrNone) + { + // return NULL if there is no preset set in the native class + if (preset == KNullDesC) + { + aJni->SetObjectArrayElement(aPreset, 0, NULL); + } + else + { + jstring javaStr = S60CommonUtils::NativeToJavaString(*aJni, preset); + if (!javaStr) + { + return KErrNoMemory; + } + + aJni->SetObjectArrayElement(aPreset, 0, javaStr); + } + } + + return error; +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _setScope + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1setScope( + JNIEnv*, jclass, jint aEventSource, jint aControl, jint aScope) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetScopeL, control, aScope); + return error; +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _setEnabled + * Signature: (IIZ)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1setEnabled( + JNIEnv*, jclass, jint aEventSource, jint aControl, jboolean aEnabled) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetEnabledL, control, (TBool) aEnabled); + return error; +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _getScope + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1getScope( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + /*MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource);*/ + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->Scope(); +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _setPreset + * Signature: (IILjava/lang/String;)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1setPreset( + JNIEnv* aJni, jclass, jint aEventSource, jint aControl, jstring aPreset) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + JStringUtils preset(*aJni, aPreset); + error = eventSource->ExecuteTrap(SetPresetL, control, (TDesC*) &preset); + + ELOG1( EJavaAMMS, "AMMS:JNI:EffectControl:setPreset, err=%d", error); + + return error; +} + +/* + * Class: com_nokia_amms_control_EffectControl + * Method: _setEnforced + * Signature: (IIZ)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_EffectControl__1setEnforced( + JNIEnv*, jclass, jint aEventSource, jint aControl, jboolean aEnforced) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSEffectControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + TInt error; + error = eventSource->ExecuteTrap( + SetEnforcedL, + control, + (TBool) aEnforced); + return error; +} + + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/equalizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/equalizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,316 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_audioeffect_EqualizerControl.h" +#include +#include "cammsequalizercontrolgroup.h" + +/** + * wrapper for CAMMSEqualizerControlGroup::GetBandLevelL() + */ +static void GetBandLevelL( + CAMMSEqualizerControlGroup *aControl, + TInt aBand, + TInt *aLevel) +{ + aControl->GetBandLevelL(aBand, *aLevel); +} + +/** + * wrapper for CAMMSEqualizerControlGroup::CenterFreqL() + */ +static void GetCenterFreqL( + CAMMSEqualizerControlGroup *aControl, + TInt aBand, + TInt *aFrequency) +{ + aControl->GetCenterFreqL(aBand, *aFrequency); +} + +/** + * wrapper for CAMMSEqualizerControlGroup::SetBandLevelL() + */ +static void SetBandLevelL( + CAMMSEqualizerControlGroup *aControl, + TInt aLevel, + TInt aBand) +{ + aControl->SetBandLevelL(aLevel, aBand); +} + +/** + * wrapper for CAMMSEqualizerControlGroup::SetBassL() + */ +static void SetBassL(CAMMSEqualizerControlGroup *aControl, TInt *aLevel, TInt *aSetLevel) +{ + aControl->SetBassL(*aLevel, *aSetLevel); +} + +/** + * wrapper for CAMMSEqualizerControlGroup::SetTrebleL() + */ +static void SetTrebleL(CAMMSEqualizerControlGroup *aControl, TInt *aLevel, TInt *aSetLevel) +{ + aControl->SetTrebleL(*aLevel, *aSetLevel); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getBand + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getBand( + JNIEnv*, jclass, jint aEventSource, jint aControl, jint aFrequency) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->Band(aFrequency); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getTreble + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getTreble( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + return control->Treble(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _setBass + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1setBass( + JNIEnv*, jclass, jint aEventSource, jint aControl, jint aLevel) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + TInt level = aLevel; + TInt setLevel; + + error = eventSource->ExecuteTrap(SetBassL, control, &level, &setLevel); + return (error < KErrNone) ? error : setLevel; +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getCenterFreq + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getCenterFreq( + JNIEnv*, jclass, jint aEventSource, jint aControl, jint aBand) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + TInt error; + TInt freq; + + error = eventSource->ExecuteTrap( + GetCenterFreqL, + control, + (TInt) aBand, + &freq); + + return (error < KErrNone) ? error : freq; +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _setBandLevel + * Signature: (IIII)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1setBandLevel( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aLevel, + jint aBand) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap( + SetBandLevelL, + control, + (TInt) aLevel, + (TInt) aBand); + + return error; +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _setTreble + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1setTreble( + JNIEnv*, jclass, jint aEventSource, jint aControl, jint aLevel) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + TInt level = aLevel; + TInt setLevel; + + error = eventSource->ExecuteTrap(SetTrebleL, control, &level, &setLevel); + return (error < KErrNone) ? error : setLevel; +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getNumberOfBands + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getNumberOfBands( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->NumberOfBands(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getMinBandLevel + * Signature: (IILI)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getMinBandLevel( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + + return control->MinBandLevel(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getBass + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getBass( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->Bass(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getMaxBandLevel + * Signature: (IILI)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getMaxBandLevel( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + return control->MaxBandLevel(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_EqualizerControl + * Method: _getBandLevel + * Signature: (IIILI)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_EqualizerControl__1getBandLevel( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl, + jint aBand, + jintArray aLevel) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSEqualizerControlGroup* control = + static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + TInt level; + + error = eventSource->ExecuteTrap( + GetBandLevelL, + control, + (TInt) aBand, + &level); + + if (error == KErrNone) + { + // aLevel is an array of 1 element allocated at the java side + aJni->SetIntArrayRegion( + /*destination*/ aLevel, + /*first*/ 0, + /*count*/ 1, + /*source*/ &level); + } + return error; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/globalmanager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/globalmanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,266 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include +#include + +#include + +#include "com_nokia_amms_GlobalManagerImpl.h" +#include "cammsglobalmanager.h" + +/** + * Creates new CAMMSGlobalManager instance which is added to + * MMAFunctionServer for cleanup. + * @param aHandle will contain handle to created object. + * @param aEventSource MMA event source instance. + */ +LOCAL_C void CreateManagerL(TInt* aHandle, + MMAFunctionServer* aEventSource) +{ + CAMMSGlobalManager* manager = CAMMSGlobalManager::NewLC(); + + // Make Java handle + *aHandle = reinterpret_cast(manager); + + MMAFunctionServer::StaticAddObjectFromHandleL(aEventSource, + *aHandle); + + CleanupStack::Pop(manager); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_GlobalManagerImpl__1createGlobalManager +(JNIEnv*, + jclass, + jint aEventSourceHandle) +{ + LOG( EJavaAMMS, EInfo, "AMMS::GlobalManager.cpp::createGlobalManager +"); + + // Development time check. + __ASSERT_DEBUG(aEventSourceHandle > 0, User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + // handle will be set in CreateManagerL function. + TInt handle = KErrNotReady; + + // Call CreateManagerL. If it leaves handle will not be set + TInt error = eventSource->ExecuteTrap(&CreateManagerL, + &handle, + eventSource); + + if (error != KErrNone) + { + // executed function leaved. Set error to be returned to java. + handle = error; + } + + LOG1( EJavaAMMS, EInfo, "AMMS::GlobalManager.cpp::createGlobalManager return %d", + handle); + + return handle; +} + +/** + * Calls CAMMSGlobalManager::InitL method. + * + * @param aManager CAMMSGlobalManager instance. + * @param aEventSource MMAFunctionServer instance. + */ +LOCAL_C void InitManagerL(CAMMSGlobalManager* aManager, + MMAFunctionServer* aEventSource) +{ + aManager->InitL(aEventSource->Players()); + + // Receive notifications when new players are created or deleted. + aEventSource->SetPlayerInstanceObserver(aManager); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_GlobalManagerImpl__1init +(JNIEnv*, + jclass, + jint aEventSourceHandle, + jint aGlobalManagerHandle) +{ + LOG( EJavaAMMS, EInfo, "AMMS::GlobalManager.cpp::init +"); + + // Development time check. + __ASSERT_DEBUG(aEventSourceHandle > 0 && + aGlobalManagerHandle > 0, User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSGlobalManager* manager = + reinterpret_cast< CAMMSGlobalManager* >(aGlobalManagerHandle); + + // Call InitManagerL. + TInt error = eventSource->ExecuteTrap(&InitManagerL, + manager, + eventSource); + + ELOG1( EJavaAMMS, "AMMS::GlobalManager.cpp::init error code %d", error); + return error; +} + +/** + * Calls CAMMSGlobalManager::CreateSoundSource3DL method. + * @param aManager CAMMSGlobalManager instance. + * @param aHandle will contain handle to created object. + */ +LOCAL_C void CreateSoundSource3DL(CAMMSGlobalManager* aManager, TInt* aHandle) +{ + CAMMSModule* module = aManager->CreateSoundSource3DL(); + + // Make Java handle + *aHandle = reinterpret_cast(module); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_GlobalManagerImpl__1createSoundSource3D +(JNIEnv*, + jclass, + jint aEventSourceHandle, + jint aGlobalManagerHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSGlobalManager* manager = + reinterpret_cast< CAMMSGlobalManager* >(aGlobalManagerHandle); + + // handle will be set in CreateSoundSource3DL function. + TInt handle = KErrNotReady; + + // Call CreateSoundSource3DL. If it leaves handle will not be set + TInt error = eventSource->ExecuteTrap(&CreateSoundSource3DL, + manager, + &handle); + + if (error != KErrNone) + { + // executed function leaved. Set error to be returned to java. + handle = error; + } + ELOG1( EJavaAMMS, "AMMS::GlobalManager.cpp::createSoundSource3D return value %d", + error); + return handle; +} + +/** + * Calls CAMMSGlobalManager::CreateEffectModuleL method. + * @param aManager CAMMSGlobalManager instance. + * @param aHandle will contain handle to created object. + */ +LOCAL_C void CreateEffectModuleL(CAMMSGlobalManager* aManager, TInt* aHandle) +{ + CAMMSModule* module = aManager->CreateEffectModuleL(); + + // Make Java handle + *aHandle = reinterpret_cast(module); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_GlobalManagerImpl__1createEffectModule +(JNIEnv*, + jclass, + jint aEventSourceHandle, + jint aGlobalManagerHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSGlobalManager* manager = + reinterpret_cast< CAMMSGlobalManager* >(aGlobalManagerHandle); + + // handle will be set in CreateEffectModuleL function. + TInt handle = KErrNotReady; + + // Call CreateEffectModuleL. If it leaves handle will not be set + TInt error = eventSource->ExecuteTrap(&CreateEffectModuleL, + manager, + &handle); + + if (error != KErrNone) + { + // executed function leaved. Set error to be returned to java. + handle = error; + } + ELOG1( EJavaAMMS, "AMMS::GlobalManager.cpp::createEffectModule return value %d", + error); + return handle; +} + +/** + * Calls CAMMSGlobalManager::Spectator method. + * @param aManager CAMMSGlobalManager instance. + * @param aHandle will contain handle to created object. + */ +LOCAL_C void CreateSpectatorL(CAMMSGlobalManager* aManager, TInt* aHandle) +{ + CAMMSModule* spectator = aManager->Spectator(); + + // Make Java handle + *aHandle = reinterpret_cast(spectator); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_GlobalManagerImpl__1createSpectator +(JNIEnv*, + jclass, + jint aEventSourceHandle, + jint aGlobalManagerHandle) +{ + LOG( EJavaAMMS, EInfo, "AMMS::GlobalManager.cpp::createSpectator +"); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSGlobalManager* manager = + reinterpret_cast< CAMMSGlobalManager* >(aGlobalManagerHandle); + + // handle will be set in CreateSpectatorL function. + TInt handle = KErrNotReady; + + // Call CreateSpectatorL. If it leaves handle will not be set + TInt error = eventSource->ExecuteTrap(&CreateSpectatorL, + manager, + &handle); + + if (error != KErrNone) + { + // executed function leaved. Set error to be returned to java. + handle = error; + } + LOG1( EJavaAMMS, EInfo, "AMMS::GlobalManager.cpp::createSpectator error code %d", handle); + return handle; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/locationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/locationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,158 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_audio3d_LocationControl.h" +#include +#include "cammslocationcontrolgroup.h" +#include "ammsconstants.h" + +/** + * wrapper for CAMMSLocationControlGroup::Cartesian() + */ +static void GetCartesianL( + CAMMSLocationControlGroup* control, + TInt aLocation[ KAMMSVectorComponents ]) +{ + control->CartesianL(aLocation); +} + +/** + * wrapper for CAMMSLocationControlGroup::SetCartesianL() + */ +static void SetCartesianL( + CAMMSLocationControlGroup* control, + TInt aX, + TInt aY, + TInt aZ) +{ + control->SetCartesianL(aX, aY, aZ); +} + +/** + * wrapper for CAMMSLocationControlGroup::SetSphericalL() + */ +static void SetSphericalL( + CAMMSLocationControlGroup* control, + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + control->SetSphericalL(aAzimuth, aElevation, aRadius); +} + +/* + * Class: com_nokia_amms_control_audio3d_LocationControl + * Method: _setSpherical + * Signature: (IIIII)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audio3d_LocationControl__1setSpherical( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aAzimuth, + jint aElevation, + jint aRadius) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSLocationControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetSphericalL, control, + aAzimuth, aElevation, aRadius); + + return error; +} + +/* + * Class: com_nokia_amms_control_audio3d_LocationControl + * Method: _getCartesian + * Signature: (II)LI + */ +JNIEXPORT jintArray JNICALL Java_com_nokia_amms_control_audio3d_LocationControl__1getCartesian( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSLocationControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt location[ KAMMSVectorComponents ]; + TInt error = eventSource->ExecuteTrap(GetCartesianL, + control, + location); + // allocate new array + jintArray javaArray = aJni->NewIntArray(KAMMSVectorComponents); + if (javaArray) + { + aJni->SetIntArrayRegion( + /*destination*/ javaArray, + /*first*/0, + /*count*/KAMMSVectorComponents, + /*source*/ &location[ 0 ]); + } + + jint javaError[ 1 ] = { error }; + aJni->SetIntArrayRegion(aError, 0, 1, javaError); + + return javaArray; +} + +/* + * Class: com_nokia_amms_control_audio3d_LocationControl + * Method: _setCartesian + * Signature: (IIIII)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audio3d_LocationControl__1setCartesian( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aX, + jint aY, + jint aZ) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSLocationControlGroup* control = static_cast( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap( + SetCartesianL, + control, + aX, + aY, + aZ); + + return error; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/modulebase.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/modulebase.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,124 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +//#include +#include + +#include +#include + +// Generated JNI header. +#include "com_nokia_amms_ModuleBase.h" + +#include "cammsmodule.h" +#include "cammsglobalmanager.h" + +/** + * Calls CAMMSModule::AddPlayerL method. + * @param aModule Module instance. + * @param aPlayer Player to add. + */ +LOCAL_C void AddPlayerL(CAMMSModule* aModule, CMMAPlayer* aPlayer) +{ + aModule->AddPlayerL(aPlayer); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_ModuleBase__1addPlayer +(JNIEnv* /*aJniEnv*/, + jclass, + jint aEventSourceHandle, + jint aModuleHandle, + jint aPlayerHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSModule* module = + reinterpret_cast< CAMMSModule* >(aModuleHandle); + + CMMAPlayer* player = + reinterpret_cast< CMMAPlayer *>(aPlayerHandle); + + // call CAMMSModule::AddPlayerL through local AddPlayerL function. + return eventSource->ExecuteTrap(&AddPlayerL, + module, + player); +} + +/** + * Calls CAMMSModule::RemovePlayerL method. + * @param aModule Module instance. + * @param aPlayer Player to remove. + * @return KErrNotFound if player does not exist in the module. + */ +LOCAL_C TInt RemovePlayer(CAMMSModule* aModule, CMMAPlayer* aPlayer) +{ + return aModule->RemovePlayer(aPlayer); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_ModuleBase__1removePlayer +(JNIEnv* /*aJniEnv*/, + jclass, + jint aEventSourceHandle, + jint aModuleHandle, + jint aPlayerHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CAMMSModule* module = + reinterpret_cast< CAMMSModule *>(aModuleHandle); + + CMMAPlayer* player = + reinterpret_cast< CMMAPlayer *>(aPlayerHandle); + + // call CAMMSModule::RemovePlayerL through local RemovePlayerL function. + return eventSource->Execute(&RemovePlayer, + module, + player); +} + +/** + * JNI function. + */ +JNIEXPORT void JNICALL Java_com_nokia_amms_ModuleBase__1dispose +(JNIEnv*, + jclass, + jint aManagerHandle, + jint aModuleHandle) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::ModuleBase.cpp::finalize %d", aModuleHandle); + + // Module to dispose + CAMMSModule* module = + reinterpret_cast< CAMMSModule* >(aModuleHandle); + + CAMMSGlobalManager* manager = + reinterpret_cast< CAMMSGlobalManager* >(aManagerHandle); + + manager->DisposeModule(module); +} +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/orientationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/orientationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,191 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI file for OrientationControl +* +*/ + + +//#include + +#include "com_nokia_amms_control_audio3d_OrientationControl.h" +#include +#include "cammsorientationcontrolgroup.h" + +/** + * wrapper for CAMMSOrientationControlGroup::OrientationVectors() + */ +static void GetOrientationVectorsL( + CAMMSOrientationControlGroup* control, + TInt aOrientation[ KAMMSTwoVectorComponents ]) +{ + control->OrientationVectorsL(aOrientation); +} + +/** + * wrapper for CAMMSOrientationControlGroup::SetOrientationVectorsL() + */ +static void SetOrientationVectorsL( + CAMMSOrientationControlGroup* control, + TInt aFrontVector[ KAMMSVectorComponents ], + TInt aAboveVector[ KAMMSVectorComponents ]) +{ + control->SetOrientationVectorsL(aFrontVector, aAboveVector); +} + +/** + * wrapper for CAMMSOrientationControlGroup::SetOrientationL() + */ +static void SetOrientationL( + CAMMSOrientationControlGroup* control, + TInt aHeading, + TInt aPitch, + TInt aRoll) +{ + control->SetOrientationL(aHeading, aPitch, aRoll); +} + +/* + * Class: com_nokia_amms_control_audio3d_OrientationControl + * Method: _setOrientation + * Signature: + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_OrientationControl__1setOrientation( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aHeading, + jint aPitch, + jint aRoll) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSOrientationControlGroup* control = + static_cast< CAMMSOrientationControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetOrientationL, control, + aHeading, aPitch, aRoll); + + return error; +} + +/* + * Class: com_nokia_amms_control_audio3d_OrientationControl + * Method: _getOrientationVectros + * Signature: + */ +JNIEXPORT jintArray JNICALL +Java_com_nokia_amms_control_audio3d_OrientationControl__1getOrientationVectors( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSOrientationControlGroup* control = + static_cast< CAMMSOrientationControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt orientation[ KAMMSTwoVectorComponents ]; + TInt error; + error = eventSource->ExecuteTrap( + GetOrientationVectorsL, + control, + orientation); + + // Java side method can not throw exception, store possible error here + // aError is an array of 1 element allocated at the java side + aJni->SetIntArrayRegion( + /*destination*/ aError, + /*first*/ 0, + /*count*/ 1, + /*source*/ &error); + + // allocate new array + jintArray javaArray = aJni->NewIntArray(KAMMSTwoVectorComponents); + + if (javaArray) + { + aJni->SetIntArrayRegion( + /*destination*/ javaArray, + /*first*/0, + /*count*/KAMMSTwoVectorComponents, + /*source*/ &orientation[ 0 ]); + } + + return javaArray; +} + +/* + * Class: com_nokia_amms_control_audio3d_OrientationControl + * Method: _setOrientation + * Signature: + */ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_audio3d_OrientationControl__1setOrientationVectors( + JNIEnv* aJni, + jclass, + jint aEventSource, + jint aControl, + jintArray aFrontVector, + jintArray aAboveVector) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSOrientationControlGroup* control = + static_cast< CAMMSOrientationControlGroup* >( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + TInt i; + + // copy java front vector array to native front vector array + TInt frontVector[ KAMMSVectorComponents ]; + TInt count = aJni->GetArrayLength(aFrontVector); + jint* elements = aJni->GetIntArrayElements(aFrontVector, NULL); + for (i = 0; i < count; i++) + { + frontVector[ i ] = elements[ i ]; + } + aJni->ReleaseIntArrayElements(aFrontVector, elements, 0); + + // copy java above vector array to native above vector array + TInt aboveVector[ KAMMSVectorComponents ]; + count = aJni->GetArrayLength(aAboveVector); + elements = aJni->GetIntArrayElements(aAboveVector, NULL); + for (i = 0; i < count; i++) + { + aboveVector[ i ] = elements[ i ]; + } + aJni->ReleaseIntArrayElements(aAboveVector, elements, 0); + + TInt error; + error = eventSource->ExecuteTrap( + SetOrientationVectorsL, + control, + frontVector, + aboveVector); + + return error; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/pancontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/pancontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_PanControl.h" +#include +#include "cammspancontrolgroup.h" + +/** + * wrapper for CAMMSPanControlGroup::Pan() + */ +static TInt GetPan(CAMMSPanControlGroup* aControl) +{ + return aControl->Pan(); +} + +/** + * wrapper for CAMMSPanControlGroup::SetPanL() + */ +static void SetPanL(CAMMSPanControlGroup* aControl, TInt aPan, TInt *aReturnedPan) +{ + aControl->SetPanL(aPan, *aReturnedPan); +} + +/* + * Class: com_nokia_amms_control_PanControl + * Method: _getPan + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_PanControl__1getPan( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSPanControlGroup* control = static_cast< CAMMSPanControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return eventSource->Execute(GetPan, control); +} + +/* + * Class: com_nokia_amms_control_PanControl + * Method: _setPan + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_PanControl__1setPan( + JNIEnv* aJniEnv, + jclass, + jint aEventSource, + jint aControl, + jint aPan, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSPanControlGroup* control = static_cast< CAMMSPanControlGroup* >( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + TInt error; + TInt aReturnedPan; + error = eventSource->ExecuteTrap(SetPanL, control, (TInt) aPan, &aReturnedPan); + + // the returned pan value is between -100 and 100 (and the error code as well) + jint javaError[ 1 ] = { error }; + aJniEnv->SetIntArrayRegion(aError, 0, 1, javaError); + return aReturnedPan; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/prioritycontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/prioritycontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_PriorityControl.h" +#include +#include "cammsprioritycontrol.h" + +/** + * wrapper for CAMMSPriorityControl::Priority() + */ +static TInt GetPriority(CAMMSPriorityControl* aControl) +{ + return aControl->Priority(); +} + +/** + * wrapper for CAMMSPriorityControl::SetPriorityL() + */ +static void SetPriorityL(CAMMSPriorityControl* aControl, TInt aPriority) +{ + aControl->SetPriorityL(aPriority); +} + +/* + * Class: com_nokia_amms_control_PriorityControl + * Method: _getPriority + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_PriorityControl__1getPriority( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSPriorityControl* control = static_cast< CAMMSPriorityControl* >( + reinterpret_cast< CAMMSControl *>(aControl)); + + return eventSource->Execute(GetPriority, control); +} + +/* + * Class: com_nokia_amms_control_PriorityControl + * Method: _setPriority + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_PriorityControl__1setPriority( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aPriority) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSPriorityControl* control = static_cast< CAMMSPriorityControl* >( + reinterpret_cast< CAMMSControl* >(aControl)); + + TInt error = eventSource->ExecuteTrap( + &SetPriorityL, control, (TInt) aPriority); + + return error; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/reverbcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/reverbcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,134 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_audioeffect_ReverbControl.h" +#include +#include "cammsreverbcontrolgroup.h" + +/** + * wrapper for CAMMSReverbControlGroup::SetReverbLevelL() + */ +static void SetReverbLevelL( + CAMMSReverbControlGroup* aControl, + TInt *aLevel) +{ + aControl->SetReverbLevelL(*aLevel); + *aLevel = aControl->ReverbLevel(); +} + +/** + * wrapper for CAMMSReverbControlGroup::SetReverbLevelL() + */ +static void SetReverbTimeL( + CAMMSReverbControlGroup* aControl, + TInt aTime) +{ + aControl->SetReverbTimeL(aTime); +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbControl + * Method: _getReverbLevel + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbControl__1getReverbLevel( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + CAMMSReverbControlGroup* control = static_cast< CAMMSReverbControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->ReverbLevel(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbControl + * Method: _getReverbTime + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbControl__1getReverbTime( + JNIEnv*, jclass, jint aEventSource, jint aControl) +{ + CAMMSReverbControlGroup* control = static_cast< CAMMSReverbControlGroup* >( + reinterpret_cast< CAMMSControlGroup *>(aControl)); + + return control->ReverbTime(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbControl + * Method: _setReverbTime + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbControl__1setReverbTime( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aTime) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CAMMSReverbControlGroup* control = static_cast< CAMMSReverbControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetReverbTimeL, control, (TInt) aTime); + return error; +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbControl + * Method: _setReverbLevel + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbControl__1setReverbLevel( + JNIEnv* aJniEnv, + jclass, + jint aEventSource, + jint aControl, + jint aLevel, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSReverbControlGroup* control = static_cast< CAMMSReverbControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + TInt level = aLevel; + + error = eventSource->ExecuteTrap( + SetReverbLevelL, + control, + (TInt *) &level); + + jint javaError[ 1 ] = { error }; + aJniEnv->SetIntArrayRegion(aError, 0, 1, javaError); + + return level; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/reverbsourcecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/reverbsourcecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +//#include + +#include "com_nokia_amms_control_audioeffect_ReverbSourceControl.h" +#include +#include "cammsreverbsourcecontrolgroup.h" + + +/** + * wrapper for CAMMSReverbSourceControlGroup::SetRoomLevelL() + */ +static void SetRoomLevelL( + CAMMSReverbSourceControlGroup* aControl, + TInt aLevel) +{ + aControl->SetRoomLevelL(aLevel); +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbSourceControl + * Method: _getRoomLevel + * Signature: + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbSourceControl__1getRoomLevel( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl) +{ + CAMMSReverbSourceControlGroup* control = + static_cast< CAMMSReverbSourceControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + return control->RoomLevel(); +} + +/* + * Class: com_nokia_amms_control_audioeffect_ReverbSourceControl + * Method: _setRoomLevel + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_audioeffect_ReverbSourceControl__1setRoomLevel( + JNIEnv*, + jclass, + jint aEventSource, + jint aControl, + jint aLevel) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CAMMSReverbSourceControlGroup* control = + static_cast< CAMMSReverbSourceControlGroup* >( + reinterpret_cast< CAMMSControlGroup* >(aControl)); + + TInt error; + error = eventSource->ExecuteTrap(SetRoomLevelL, control, (TInt) aLevel); + return error; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/jni/src/volumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/jni/src/volumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +//#include +#include + +#include + +// Generated JNI header. +#include "com_nokia_amms_control_VolumeControl.h" + +#include "cammsvolumecontrolgroup.h" + +/** + * Calls CAMMSVolumeControlGroup::SetLevelL method. + * @param aVolumeControl CAMMSVolumeControlGroup instance. + * @param aLevel Level to set. + */ +LOCAL_C void SetVolumeL(CAMMSVolumeControlGroup* aVolumeControl, TInt aLevel) +{ + aVolumeControl->SetVolumeL(aLevel); +} + +/** + * JNI function. + */ +JNIEXPORT jint JNICALL Java_com_nokia_amms_control_VolumeControl__1setLevel +(JNIEnv* /*aJniEnv*/, + jclass, + jint aEventSourceHandle, + jint aControlHandle, + jint aVolume) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::VolumeControl.cpp::setLevel level = %d", aVolume); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CAMMSVolumeControlGroup* control = + reinterpret_cast< CAMMSVolumeControlGroup* >(aControlHandle); + + // call CAMMSVolumeControlGroup::SetVolumeL through local SetVolumeL function. + return eventSource->ExecuteTrap(&SetVolumeL, + control, + aVolume); +} + +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiodopplercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiodopplercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,109 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an effect called Doppler. +* +*/ + + +#ifndef CAMMSEMCAUDIODOPPLERCONTROL_H +#define CAMMSEMCAUDIODOPPLERCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsdopplercontrol.h" + +#include + +using multimedia :: MSourceDopplerControl; +using multimedia :: KSourceDopplerEffectControl; + + +// CONSTANTS +_LIT(KAMMSEMCAudioDopplerControl, "DopplerControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Doppler Control effect for the Audio source. +* This class delegates Doppler Control effect method calls to +* MEffectControl. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCAudioDopplerControl): public CAMMSDopplerControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + * + */ + static CAMMSEMCAudioDopplerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCAudioDopplerControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCAudioDopplerControl(CMMAPlayer* aPlayer); + + +public: + + void SetEnabledL(TBool aDopplerEnabled); + + TBool Enabled(); + + void SetVelocityCartesianL(TInt aX, TInt aY, TInt aZ); + + void VelocityCartesian(TInt& aX, TInt& aY, TInt& aZ); + + void SetVelocitySphericalL(TInt aAzimuth, TInt aElevation, + TInt aRadius); + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC SourceDoppler Control + */ + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MSourceDopplerControl *iMSourceDopplerControl; +}; + +#endif // CAMMSEMCAUDIODOPPLERCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiolocationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiolocationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +#ifndef CAMMSEMCAUDIOLOCATIONCONTROL_H +#define CAMMSEMCAUDIOLOCATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammslocationcontrol.h" + +#include + +using multimedia :: MSourceLocationControl; +using multimedia :: KSourceLocationEffectControl; + +// CONSTANTS +_LIT(KAMMSEMCAudioLocationControl, "LocationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Location Control effect for the Audio source. +* This class delegates Location Control effect method calls to +* MSourceLocationControl. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCAudioLocationControl): public CAMMSLocationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCAudioLocationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCAudioLocationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCAudioLocationControl(CMMAPlayer* aPlayer); + + +public: + + void SetLocationCartesianL(TInt& aX, TInt& aY, TInt& aZ); + + void LocationCartesian(TInt& aX, TInt& aY, TInt& aZ); + + void SetLocationSphericalL(TInt& aAzimuth, TInt& aElevation, + TInt& aRadius); + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC SourceLocation Control + */ + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MSourceLocationControl *iMSourceLocationControl; +}; + +#endif // CAMMSEMCAUDIOLOCATIONCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiovirtualizercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiovirtualizercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,169 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Virtualizes audio channels. +* +*/ + + +#ifndef CAMMSEMCAUDIOVIRTUALIZERCONTROL_H +#define CAMMSEMCAUDIOVIRTUALIZERCONTROL_H + +// INCLUDES +#include +#include "cammseffectcontrol.h" +#include "cammseffectcontrolgroup.h" +#include +#include +//Utility for getting EnvironmentalPreset +#include "cammsemcaudiovirtualizerenvironmentalpresetutility.h" + + +using multimedia :: KStereoWideningEffectControl; +using multimedia :: MStereoWideningControl; + + +// CONSTANTS +_LIT(KAMMSEMCAudioVirtualizerControl, "AudioVirtualizerControl"); + +// CLASS DECLARATION +/** +* +* Controls for the Audio Virtualizer effect. +* This class delegates Audio Virtualizer effect method calls to +* CStereoWidening. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCAudioVirtualizerControl): public CAMMSEffectControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCAudioVirtualizerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCAudioVirtualizerControl(); + +public: // Functions from base classes + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +public: // overriden virtual functions from CAMMSEffectControl + + + virtual void SetEnforcedL(TBool aEnforced); + + virtual TBool Enforced(); + + virtual void SetScopeL(TInt aScope); + + virtual TInt Scope(); + +protected: + + virtual void ApplySettingsL(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCAudioVirtualizerControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /** Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + TBuf iPresetName; + + /** Index of the current preset */ + TInt iCurrentPreset; + /* AudioVirtualizer utility to get preset and data related to that preset*/ + CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility * iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility; + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC AudioVirtualizer Control + */ + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MStereoWideningControl *iMStereoWideningControl; + + +}; + +#endif // CAMMSEMCAUDIOVIRTUALIZERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiovirtualizerenvironmentalpresetutility.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcaudiovirtualizerenvironmentalpresetutility.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Utility to get the preset and data +* +*/ + + +#ifndef CAMMSEMCAUDIOVIRTUALIZERENVIRONMENTALPRESETUTILITY_H +#define CAMMSEMCAUDIOVIRTUALIZERENVIRONMENTALPRESETUTILITY_H + +// INCLUDES +#include +#include "cammsemcbasemmfdevsound.h" +#include +#include + + +// CLASS DECLARATION + +/** + * @since 5.1 + */ +NONSHARABLE_CLASS(CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility) + : public CAMMSEMCBaseMMFDevSound +{ +public: // destructor + + /** + * Destructor. + */ + ~CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility(); + +public: // New functions + + /** + * Gets the current preset. + * + * @return the current preset + */ + void GetPresetAtIndexL(TDes& aPreset ,TInt iPresetIndex); + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Creates utilities that can be used to obtain CSterioWidening Utility + * and preset data . + * Does nothing if the utility already exists. + */ + virtual void PrepareEmptyStereoWideningUtilitiesL(); + + /** + * Deletes Environmental utilities + * Does nothing if the utilities have already been deleted. + */ + virtual void DeleteEmptyStereoWideningUtilities(); + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + virtual void GetPresetNamesL(CDesCArray& aPresetNames); + + CStereoWidening * GetStereoWideningAtPresetIndexL(TInt iPresetIndex); + +public: + /** + * c++ constructor. + */ + CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility(); + /** + * 2nd phase constructor. + */ + + void ConstructL(); + +protected: // data + + // Available preset names, owned + CDesCArrayFlat* iPresetNames; + // Used to get preset names and data when the group is empty + // (there are no controls in the group, and thus, no actual + // control can be used for that purpose). + CStereoWideningUtility* iEmptyStereoWideningUtility; + +}; + +#endif // CAMMSEMCAUDIOVIRTUALIZERENVIRONMENTALPRESETUTILITY_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcbasemmfdevsound.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcbasemmfdevsound.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Utility to get the preset and data +* +*/ + + +#ifndef CAMMSEMCBASEMMFDEVSOUND_H +#define CAMMSEMCBASEMMFDEVSOUND_H + +// INCLUDES +#include +#include +#include +#include + + +// CLASS DECLARATION + +/** + * Group for effect controls + * + * @since 5.1 + */ +NONSHARABLE_CLASS(CAMMSEMCBaseMMFDevSound) + :public CBase, public MDevSoundObserver +{ +public: // destructor + /** + * Destructor. + */ + virtual ~CAMMSEMCBaseMMFDevSound(); + +public: // From MDevSoundObserver + + // empty implementation for callback methods from MDevSoundObserver + virtual void InitializeComplete(TInt aError); + virtual void BufferToBeFilled(CMMFBuffer* /*aBuffer*/) {} + virtual void PlayError(TInt /*aError*/) {} + + virtual void ToneFinished(TInt /*aError*/) {} + virtual void BufferToBeEmptied(CMMFBuffer* /*aBuffer*/) {} + virtual void RecordError(TInt /*aError*/) {} + virtual void ConvertError(TInt /*aError*/) {} + virtual void DeviceMessage(TUid /*aMessageType*/, + const TDesC8& /*aMsg*/) {} + virtual void SendEventToClient(const TMMFEvent& /*aEvent*/) {} + + +protected: + virtual TInt CreateAndInitializeDevSoundL(); + + /** + * Deletes utilities + * Does nothing if the utilities have already been deleted. + */ + virtual void DeleteDevSound(); + +public: + /** + * c++ constructor. + */ + CAMMSEMCBaseMMFDevSound(); + /** + * 2nd phase constructor. + */ + + void ConstructL(); + +protected: + + CMMFDevSound* iMMFDevSound; + + +private: + // Used to wait for Initializing the iMMFDevSound. + CActiveSchedulerWait* iActiveSchedulerWait; // Owned. + +}; + +#endif // CAMMSEMCBASEMMFDEVSOUND_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcdistanceattenuationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcdistanceattenuationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,128 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + +#ifndef CAMMSEMCDISTANCEATTENUATIONCONTROL_H +#define CAMMSEMCDISTANCEATTENUATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsbasedistanceattenuationcontrol.h" + +#include + +using multimedia :: MDistanceAttenuationControl; +using multimedia :: KDistanceAttenuationEffectControl; + + +// CONSTANTS +_LIT(KAMMSEMCDistanceAttenuationControl, "DistanceAttenuationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Distance Attenuation effect. +* This class delegates Distance Attenuation effect method calls to +* CDistanceAttenuation. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCDistanceAttenuationControl): public CAMMSBaseDistanceAttenuationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCDistanceAttenuationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCDistanceAttenuationControl(); + +public: // Overriden the base class function + + /** + * Sets all the 3D audio distance attenuation parameters simultaneously. + * Distances are specified in units defined by + * "GlobalManager.getUnitsPerMeter()" + * + * @param aMinDistance The minimum distance, below which the distance + * gain is clipped to its maximum value of 1.0. + * @param aMaxDistance The maximum distance, beyond which the distance + * gain does not decrease any more. The exact behaviour of the gain at + * distances beyond the maximum distance depends on the value of the + * muteAfterMax. + * @param aMuteAfterMax A boolean determining how the distance gain + * behaves at distances greater than maxDistance: true if beyond the + * maximum distance the source is silent; false if beyond the maximum + * distance the source's gain is held constant at the level at the + * maximum distance. + * @param aRolloffFactor The rolloff factor, specified in thousandths + * (1000 representing a rolloff factor of 1.0, 2000 representing 2.0 and + * 500 representing 0.5). Higher values cause the distance gain to + * attenuate more quickly. + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aMaxDistance <= \a aMinDistance, + * \a aMinDistance <= 0, \a aMaxDistance <= 0 or \a aRolloffFactor < 0 + */ + void SetParametersL( + TInt aMinDistance, + TInt aMaxDistance, + TBool aMuteAfterMax, + TInt aRolloffFactor); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCDistanceAttenuationControl(CMMAPlayer* aPlayer); + +private: // Data + + CMMAPlayer *iMMAPlayer; + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MDistanceAttenuationControl *iMDistanceAttenuationControl; + +}; + +#endif // CAMMSEMCDISTANCEATTENUATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcequalizercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcequalizercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,256 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +#ifndef CAMMSEMCEQUALIZERCONTROL_H +#define CAMMSEMCEQUALIZERCONTROL_H + +// INCLUDES +#include +#include "cammseffectcontrolgroup.h" +//EMC +#include +#include +#include "cammsbaseequalizercontrol.h" +#include +//Utility for getting EnvironmentalReverb +#include "cammsemcequalizerenvironmentalpresetutility.h" + + +using multimedia :: KEqualizerEffectControl; +using multimedia::MEqualizerControl; + + +// CONSTANTS +_LIT(KAMMSEMCEqualizerControl, "EqualizerControl"); +_LIT(KAMMSEMCDefaultEqualizerPreset, "smallroom"); + +// CLASS DECLARATION + +/** +* +* Controls for the Equalizer effect. +* This class delegates Equalizer effect method calls to CAudioEqualizer. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCEqualizerControl): public CAMMSBaseEqualizerControl +{ +public: + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCEqualizerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCEqualizerControl(); + +public: // New functions + + /** + * Gets the gain set for the given equalizer band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The gain set for the given band in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aBand is out of range. + */ + TInt BandLevelL(TInt aBand); + + /** + * Returns the maximum band level supported. + * + * @return The maximum band level in millibels. + */ + TInt MaxBandLevel(); + + /** + * Returns the minimum band level supported. + * + * @return The minimum band level in millibels. + */ + TInt MinBandLevel(); + + /** + * Returns the band width in Hz for the specified band. + * + * @param aBand The frequency band whose band width is asked. + * The numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @return The band width in Hz for the specified band. + */ + TInt BandWidth(TInt aBand); + + /** + * Returns the center frequency in Hz for a given band. + * + * @param aBand The frequency band whose center frequency + * is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The center frequency in Hz for a given band. + */ + TInt CenterFrequency(TInt aBand); + + /** + * Returns the cross-over frequency between the given frequency + * band (aBand) and the next band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return Crossover frequency. + */ + TInt CrossoverFrequency(TInt aBand); + + /** + * Gets the number of frequency bands that the equalizer supports. + * + * @return The number of frequency bands that the equalizer supports. + */ + TInt NumberOfBands(); + + /** + * Sets the given equalizer band to the given gain value. + * + * @param aLevel The new gain in millibels that will be set to the given + * band. getMinBandLevel() and getMaxBandLevel() will define the maximum + * and minimum values. + * @param aBand The frequency band that will have the new gain. The + * numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @par Leaving: + * @li \c KErrArgument - \a aBand or \a aLevel is out of range. + */ + void SetBandLevelL(TInt aLevel, TInt aBand); + +public: // Functions from base classes + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +public: // override the virtual functions from base class CAMMSEffectControl + + void SetEnforcedL(TBool aEnforced); + TBool Enforced(); + void SetScopeL(TInt aScope); + TInt Scope(); + void ApplySettingsL(); + + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCEqualizerControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /** Native audio equalizer */ + // CAudioEqualizerUtility* iEqualizerUtility; + + /* Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + + TBuf iPresetName; + + /* Index of the current preset */ + TInt iCurrentPreset; + + /* Equalizer utility to get preset and data related to that preset*/ + CAMMSEMCEqualizerEnvironmentalPresetUtility * iAMMSEMCEqualizerEnvironmentalPresetUtility; + + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC Equalizer Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MEqualizerControl *iMEqualizerControl; + +}; + +#endif // CAMMSEMCEQUALIZERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcequalizerenvironmentalpresetutility.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcequalizerenvironmentalpresetutility.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Utility to get the preset and data +* +*/ + + +#ifndef CAMMSEMCEQUALIZERENVIRONMENTALPRESETUTILITY_H +#define CAMMSEMCEQUALIZERENVIRONMENTALPRESETUTILITY_H + +// INCLUDES +#include +#include "cammsemcbasemmfdevsound.h" +#include +#include + +// CLASS DECLARATION + +/** + * Group for effect controls + * + * @since 5.1 + */ +NONSHARABLE_CLASS(CAMMSEMCEqualizerEnvironmentalPresetUtility) + : public CAMMSEMCBaseMMFDevSound +{ +public: // destructor + + /** + * Destructor. + */ + ~CAMMSEMCEqualizerEnvironmentalPresetUtility(); + +public: // New functions + + /** + * Gets the current preset. + * + * @return the current preset + */ + void GetPresetAtIndexL(TDes& aPreset ,TInt iPresetIndex); + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Creates utilities that can be used to obtain CAudioEqualizer Utility + * and preset data . + * Does nothing if the utility already exists. + */ + virtual void PrepareEmptyEqualizerUtilitiesL(); + + /** + * Deletes Environmental utilities + * Does nothing if the utilities have already been deleted. + */ + virtual void DeleteEmptyEqualizerUtilities(); + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + virtual void GetPresetNamesL(CDesCArray& aPresetNames); + + CAudioEqualizer * GetEqualizerAtPresetIndexL(TInt iPresetIndex); + +public: + /** + * c++ constructor. + */ + CAMMSEMCEqualizerEnvironmentalPresetUtility(); + /** + * 2nd phase constructor. + */ + + void ConstructL(); + +protected: // data + + // Available preset names, owned + CDesCArrayFlat* iPresetNames; + // Pointer to the EqualizerUtility + CAudioEqualizerUtility* iEmptyEqualizerUtility; + +}; + +#endif // CAMMSEMCEQUALIZERENVIRONMENTALPRESETUTILITY_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,255 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + + +#ifndef CAMMSEMCREVERBCONTROL_H +#define CAMMSEMCREVERBCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammseffectcontrol.h" +#include "cammseffectcontrolgroup.h" + +//EMC +#include +#include +#include +#include +//Utility for getting EnvironmentalReverb +#include "cammsemcreverbenvironmentalpresetutility.h" + + +using multimedia :: KReverbEffectControl; +using multimedia :: MReverbControl; + +// CONSTANTS +_LIT(KAMMSEMCReverbControl, "ReverbControl"); +_LIT(KAMMSEMCDefaultReverbPreset, "smallroom"); + +// CLASS DECLARATION + +/** +* +* Controls for the Reverb effect. +* This class delegates Reverb effect method calls to CReverb. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCReverbControl): public CAMMSBaseReverbControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCReverbControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCReverbControl(); + +public: // New functions + + /** + * Sets the gain level of the reverberation. The value defines what is + * the relative level of the first reflections compared to the sound + * source without possible distance attenuations, directivities or + * obstructions taken into account. + * + * @param aLevel The new level of the reverberation in millibels. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + TInt SetReverbLevelL(TInt aLevel); + + /** + * Sets the reverberation time of the reverb. The reverberation time is + * the time taken for the reverberant sound to attenuate by 60 dB from + * its initial level. Typical values are in the range from 100 to 20000 + * milliseconds. + * The implementation might not support long reverberation times. + * Therefore, the actual time used might be shorter than the time + * specified with this method. + * + * @param aTime The new reverberation time in milliseconds. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aTime is negative. + * From Java API more leave codes are: + * - java.lang.IllegalArgumentException - when the given time is + * negative + * - javax.microedition.media.MediaException - when the changing of the + * reverb time is not supported + */ + void SetReverbTimeL(TInt aTime); + + /** + * Gets the gain level of the reverberation. + * + * @return The level of the reverberation in millibels. + */ + TInt ReverbLevel(); + + /** + * Gets the reverberation time. + * + * @return The time of the reverberation in milliseconds. + */ + TInt ReverbTime(); + + /** + * Gets the minimum level of the reverberation. + * + * @return The minimum level of the reverberation in millibels. + */ + TInt MinReverbLevel(); + + /** + * Gets the maximum level of the reverberation. + * + * @return The maximum level of the reverberation in millibels. + */ + TInt MaxReverbLevel(); + +public: // Functions from base classes + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +public: // Functions needed by reverb source control + /** + * Returns the Reverb Control. + * CAMMSEMCReverbSourceControl has to use the same instance. + * The function creates the instance if they do not exist yet. + */ + MReverbControl * GetReverbControlL(); + + + /** + * Returns the Current Preset Index. + * CAMMSEMCReverbSourceControl has to use it. + */ + + TInt CurrentPresetIndex(); + +public: // override the virtual functions from base class CAMMSEffectControl + + void SetEnforcedL(TBool aEnforced); + TBool Enforced(); + void SetScopeL(TInt aScope); + TInt Scope(); + void ApplySettingsL(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCReverbControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /* Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + + TBuf iPresetName; + + /* Index of the current preset */ + TInt iCurrentPreset; + + /* Reverb utility to get Environmental Reverb*/ + CAMMSEMCReverbEnvironmentalPresetUtility *iAMMSEMCReverbEnvironmentalPresetUtility; +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC Reverb Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MReverbControl *iMReverbControl; + TInt iEnvReverbLevel; + +}; + +#endif // CAMMSEMCREVERBCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbenvironmentalpresetutility.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbenvironmentalpresetutility.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Utility to get the preset and data +* +*/ + + +#ifndef CAMMSEMCREVERBENVIRONMENTALPRESETUTILITY_H +#define CAMMSEMCREVERBENVIRONMENTALPRESETUTILITY_H + +// INCLUDES +#include +#include "cammsemcbasemmfdevsound.h" +#include +#include + + +// CLASS DECLARATION + +/** + * Group for effect controls + * + * @since 5.1 + */ +NONSHARABLE_CLASS(CAMMSEMCReverbEnvironmentalPresetUtility) + : public CAMMSEMCBaseMMFDevSound +{ +public: // destructor + + /** + * Destructor. + */ + ~CAMMSEMCReverbEnvironmentalPresetUtility(); + +public: // New functions + + /** + * Gets the current preset. + * + * @return the current preset + */ + void GetPresetAtIndexL(TDes& aPreset ,TInt iPresetIndex); + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Creates utilities that can be used to obtain CEnvironmentalReverb Utility + * and preset data . + * Does nothing if the utility already exists. + */ + virtual TInt PrepareEmptyReverbUtilitiesL(); + + /** + * Deletes Environmental utilities + * Does nothing if the utilities have already been deleted. + */ + virtual void DeleteEmptyReverbUtilities(); + /** + * Gets list of preset names available. + * @param aPresetNames Returned preset names + */ + virtual void GetPresetNamesL(CDesCArray& aPresetNames); + + CEnvironmentalReverb * GetEnvironmentalReverbAtPresetIndexL(TInt iPresetIndex); + + CMMFDevSound* MMFDevSound(); + +public: + /** + * c++ constructor. + */ + CAMMSEMCReverbEnvironmentalPresetUtility(); + /** + * 2nd phase constructor. + */ + + void ConstructL(); + +protected: // data + + // Available preset names, owned + CDesCArrayFlat* iPresetNames; + // Used to get preset names and data when the group is empty + // (there are no controls in the group, and thus, no actual + // control can be used for that purpose). + CEnvironmentalReverbUtility* iEmptyEnvironmentalReverbUtility; + +}; + +#endif // CAMMSEMCREVERBENVIRONMENTALPRESETUTILITY_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbsourcecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcreverbsourcecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect reverb source. +* +*/ + + +#ifndef CAMMSEMCREVERBSOURCECONTROL_H +#define CAMMSEMCREVERBSOURCECONTROL_H + +// INCLUDES +#include +#include +#include "cammsbasereverbsourcecontrol.h" +#include +// CONSTANTS +_LIT(KAMMSEMCReverbSourceControl, "ReverbSourceControl"); + +using multimedia::MRoomLevelControl; +using multimedia::KRoomLevelEffectControl; + +// FORWARD DECLARATIONS +class CAMMSBaseReverbControl; + +// CLASS DECLARATION + +/** +* +* Controls for the Reverb Source effect. +* This class delegates Reverb Source effect method calls to CRoomLevel. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCReverbSourceControl): public CAMMSBaseReverbSourceControl /*CAMMSControl*/ +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + * @param aReverbControl Reverb control belonging to aPlayer. + */ + static CAMMSEMCReverbSourceControl* NewLC(CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aBaseReverbControl); + + /** + * Destructor. + */ + ~CAMMSEMCReverbSourceControl(); + +public: // New functions + + /** + * Sets the object specific level for the reverberant sound. + * The default value is 0 meaning the natural room gain (set by + * ReverbControl's presets). + * + * @param aLevel The new level of the reverberation in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + void SetRoomLevelL(TInt aLevel); + +public: // Functions from base classes + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + * @param aReverbControl Reverb control belonging to aPlayer. + */ + CAMMSEMCReverbSourceControl(CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aReverbControl); + +private: // Data + + /** Reverb control belonging to the player */ + CAMMSBaseReverbControl* iBaseReverbControl; + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC ReverbSource Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MRoomLevelControl* iRoomLevelControl; +}; + +#endif // CAMMSEMCREVERBSOURCECONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatordopplercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatordopplercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler of the spectator. +* +*/ + + +#ifndef CAMMSEMCSPECTATORDOPPLERCONTROL_H +#define CAMMSEMCSPECTATORDOPPLERCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsdopplercontrol.h" +#include // from MMAPI + +using multimedia :: MListenerDopplerControl; +using multimedia :: KListenerDopplerEffectControl; + +// CONSTANTS +_LIT(KAMMSEMCListenerDopplerControl, "DopplerControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Doppler Control effect for the Spectator. +* This class delegates Doppler Control effect method calls to +* MListenerDopplerControl. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCSpectatorDopplerControl): public CAMMSDopplerControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCSpectatorDopplerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCSpectatorDopplerControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCSpectatorDopplerControl(CMMAPlayer* aPlayer); + +public: + + void SetEnabledL(TBool aDopplerEnabled); + + TBool Enabled(); + + void SetVelocityCartesianL(TInt aX, TInt aY, TInt aZ); + + void VelocityCartesian(TInt& aX, TInt& aY, TInt& aZ); + + void SetVelocitySphericalL(TInt aAzimuth, TInt aElevation, + TInt aRadius); + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC Spectator Doppler Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MListenerDopplerControl *iMListenerDopplerControl; +}; + +#endif // CAMMSEMCSPECTATORDOPPLERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatorlocationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatorlocationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +#ifndef CAMMSEMCSPECTATORLOCATIONCONTROL_H +#define CAMMSEMCSPECTATORLOCATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammslocationcontrol.h" +#include + +using multimedia :: MListenerLocationControl; +using multimedia :: KListenerLocationEffectControl; + +// CONSTANTS +_LIT(KAMMSEMCSpectatorLocationControl, "LocationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Location Control effect for the Audio source. +* This class delegates Location Control effect method calls to +* MSourceLocationControl. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCSpectatorLocationControl): public CAMMSLocationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCSpectatorLocationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCSpectatorLocationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCSpectatorLocationControl(CMMAPlayer* aPlayer); + + +public: + + void SetLocationCartesianL(TInt& aX, TInt& aY, TInt& aZ); + + void LocationCartesian(TInt& aX, TInt& aY, TInt& aZ); + + void SetLocationSphericalL(TInt& aAzimuth, TInt& aElevation, + TInt& aRadius); + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC Listener Location Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MListenerLocationControl *iMListenerLocationControl; +}; + +#endif // CAMMSEMCSPECTATORLOCATIONCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatororientationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammsemcspectatororientationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,113 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of the spectator. +* +*/ + + +#ifndef CAMMSEMCSPECTATORORIENTATIONCONTROL_H +#define CAMMSEMCSPECTATORORIENTATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsorientationcontrol.h" +#include + +using multimedia :: MListenerOrientationControl; +using multimedia :: KListenerOrientationEffectControl; + +// CONSTANTS +_LIT(KAMMSEMCSpectatorOrientationControl, "OrientationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Orientation Control effect for the Spectator. +* This class delegates Orientation Control effect method calls to +* MListenerOrientationControl. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSEMCSpectatorOrientationControl): public CAMMSOrientationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEMCSpectatorOrientationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEMCSpectatorOrientationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEMCSpectatorOrientationControl(CMMAPlayer* aPlayer); +public: + //base class function overidden + virtual void SetOrientationL(TInt aHeading, TInt aPitch, TInt aRoll); + virtual void SetOrientationL(TInt aFrontX, + TInt aFrontY, + TInt aFrontZ, + TInt aAboveX, + TInt aAboveY, + TInt aAboveZ); + + virtual void OrientationVectors(TInt& aFrontX, + TInt& aFrontY, + TInt& aFrontZ, + TInt& aAboveX, + TInt& aAboveY, + TInt& aAboveZ); + + +private: + + CMMAPlayer *iMMAPlayer; + /** + * EMC Listener Orientation Control + */ + + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MListenerOrientationControl *iMListenerOrientationControl; + +}; + +#endif // CAMMSEMCSPECTATORORIENTATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.emc/cammspancontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.emc/cammspancontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the panning of a Player in the stereo output mix. +* +*/ + + +#ifndef CAMMSPANCONTROL_H +#define CAMMSPANCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammscontrol.h" + +//EMC header +#include +#include +using multimedia :: MBalanceControl; +using multimedia :: KBalanceEffectControl; +// CONSTANTS +_LIT(KAMMSPanControl, "PanControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Panning effect. +* This class delegates Pan effect method calls to CBalance. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSPanControl): public CAMMSControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSPanControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSPanControl(); + +public: // New functions + + /** + * Gets the current panning set. + * + * @return The current balance or panning setting. + */ + TInt PanL(); + + /** + * Sets the panning using a linear point scale with values between -100 + * and 100. 0 represents panning for both channels, -100 full panning to + * the left and 100 full panning to the right. If the given panning + * value is less than -100 or greater than 100, the panning will be set + * to -100 or 100, respectively. + * + * @param aPan The new panning to be set. + * + * @return The panning that was actually set. + */ + TInt SetPanL(TInt aPan); + +public: // Functions from base classes + const TDesC& ClassName() const; + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSPanControl(CMMAPlayer* aPlayer); + + /** + * 2nd phase constructor. + */ + void ConstructL(); + + +private: // Data + + /** Client class to access Audio Play Device functionality, owned */ + RMMFAudioPlayDeviceCustomCommands* iRMMFAudioPlayDeviceCustomCommands; + + /** CMidiClientUtility, not owned. */ + CMidiClientUtility* iMidiClientUtility; +private: + CMMAPlayer *iMMAPlayer; + /** + * EMC Pan Control + */ + CMultimediaFactory* iFactory; + MStreamControl* iStreamControl; + MBalanceControl *iMBalanceControl; +}; + +#endif // CAMMSPANCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc.mmf/cammspancontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc.mmf/cammspancontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,105 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the panning of a Player in the stereo output mix. +* +*/ + + +#ifndef CAMMSPANCONTROL_H +#define CAMMSPANCONTROL_H + +// INCLUDES +#include +#include +#include +#include "CAMMSControl.h" + +// CONSTANTS +_LIT(KAMMSPanControl, "PanControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Panning effect. +* This class delegates Pan effect method calls to CBalance. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSPanControl): public CAMMSControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSPanControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSPanControl(); + +public: // New functions + + /** + * Gets the current panning set. + * + * @return The current balance or panning setting. + */ + TInt PanL(); + + /** + * Sets the panning using a linear point scale with values between -100 + * and 100. 0 represents panning for both channels, -100 full panning to + * the left and 100 full panning to the right. If the given panning + * value is less than -100 or greater than 100, the panning will be set + * to -100 or 100, respectively. + * + * @param aPan The new panning to be set. + * + * @return The panning that was actually set. + */ + TInt SetPanL(TInt aPan); + +public: // Functions from base classes + const TDesC& ClassName() const; + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSPanControl(CMMAPlayer* aPlayer); + + /** + * 2nd phase constructor. + */ + void ConstructL(); + + +private: // Data + + /** Client class to access Audio Play Device functionality, owned */ + RMMFAudioPlayDeviceCustomCommands* iRMMFAudioPlayDeviceCustomCommands; + + /** CMidiClientUtility, not owned. */ + CMidiClientUtility* iMidiClientUtility; +}; + +#endif // CAMMSPANCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsaudiodopplercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsaudiodopplercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,79 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an effect called Doppler. +* +*/ + + +#ifndef CAMMSAUDIODOPPLERCONTROL_H +#define CAMMSAUDIODOPPLERCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsdopplercontrol.h" + +// CONSTANTS +_LIT(KAMMSAudioDopplerControl, "DopplerControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Doppler Control effect for the Audio source. +* This class delegates Doppler Control effect method calls to +* CSourceDoppler. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSAudioDopplerControl): public CAMMSDopplerControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + * + */ + static CAMMSAudioDopplerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSAudioDopplerControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSAudioDopplerControl(CMMAPlayer* aPlayer); +}; + +#endif // CAMMSAUDIODOPPLERCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsaudiolocationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsaudiolocationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +#ifndef CAMMSAUDIOLOCATIONCONTROL_H +#define CAMMSAUDIOLOCATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammslocationcontrol.h" + +// CONSTANTS +_LIT(KAMMSAudioLocationControl, "LocationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Location Control effect for the Audio source. +* This class delegates Location Control effect method calls to +* CSourceLocation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSAudioLocationControl): public CAMMSLocationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSAudioLocationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSAudioLocationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSAudioLocationControl(CMMAPlayer* aPlayer); +}; + +#endif // CAMMSAUDIOLOCATIONCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsaudiooutputcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsaudiooutputcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,178 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the audio output mode. +* +*/ +#ifndef CAMMSAUDIOOUTPUTCONTROL_H +#define CAMMSAUDIOOUTPUTCONTROL_H + +// INCLUDES +#include "cammscontrol.h" +#include +#include +// for audio routing control +#include + +// for audio routing observers +#include +#include +#include + + + + +// CONSTANTS +_LIT(KAMMSAudioOutputControl, "AudioOutputControl"); +// CLASS DECLARATION + +/** +* +* Controls for the Audio Routing. +* This class delegates Audio Routing setting calls to RMMFController. +* +* +* @since X.X +*/ +NONSHARABLE_CLASS(CAMMSAudioOutputControl) + : public CAMMSControl, public MMMAPlayerStateListener ,public MAudioOutputObserver,public MAccMonitorObserver +{ +public: + // Constructors and destructor + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSAudioOutputControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSAudioOutputControl(); + +public: + // New functions + /** + * Sets the AudioOutput. + * + * @param aPreference The new AudioOutput to be set. + */ + TInt SetAudioOutput(TInt aPreference); + + /** + * Gets the Audio Routing preference. + * + * @return The previously set Audio Routing preference. + */ + TInt GetAudioOutput(); + /** + * Reset the AudioOutput java object with changed value of current + */ + void GetCurrentPreference(); + /** + * Gets the Audio Routing preference. + * + * @return The previously set Audio Routing preference. and if not set retruns the device default + */ + + TInt GetCurrentPrefInt(); + /** + * Gets the Audio Routing Device Default. + * + * @returns the device default + */ + TInt GetDeviceDefaultPreference(); + /** + * Create an Observer to get the notification for the Headset state. + * Also initializes iCurrentActualPreference with CAudioOutput::EPrivate if headset is connected. + * @returns the device default + */ + void CreateHeadsetStateObserverL(); + /** + * Actual native control is created using this function + */ + void CreateNativeAudioOutputControlL(); + /** + * seting java object used to send as callback event + */ + void SetJavaAudioOutputObject(jobject object); + /** + * Reset the value of java object with current values + */ + void ResetJavaAudioOutputObject(); + /** + * Check if there is any change in Current output Mode,It sends a event to java + * If there is no change it returns silently + */ + void NotifyJavaOnChange(); + + +public: + // From MMMAPlayerStateListener + void StateChanged(TInt aState); + + +public: + // From MAudioOutputObserver + void DefaultAudioOutputChanged(CAudioOutput& aAudioOutput, CAudioOutput::TAudioOutputPreference aNewDefault); + void DisconnectedL(CAccMonitorInfo *aAccessoryInfo); + void ConnectedL(CAccMonitorInfo* aAccessoryInfo); + void AccMonitorObserverError(TInt aError); + +public: + // Functions from base classes + const TDesC& ClassName() const; + +protected: + // New functions + /** + * @param aAmmsPreference AMMS preference to be set. + */ + TInt SetAudioOutputToMmf(CAudioOutput::TAudioOutputPreference aAmmsPreference); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSAudioOutputControl(CMMAPlayer* aPlayer); + + /** + * Symbian 2nd phase constructor. + */ + void ConstructL(); + +private: + //Data + // Preference visible in AMMS. + CAudioOutput::TAudioOutputPreference iRoutingUserPreference; + // Preference of the device changes by inserting/removing Jack. + CAudioOutput::TAudioOutputPreference iDefaultDevicePreference; + // Preference of the device changes by inserting/removing Jack. + TInt iCurrentPreference; + // owned + CAudioOutput* iAudioOutput; + CMMAPlayer::TPlayerState playerState; + //To get the peripheral attached/detached notification + CAccMonitorInfo* iAccessoryInfo; + RAccMonCapabilityArray capabilityArray; + CAccMonitor *iAccMonitor; + RConnectedAccessories array; + jobject iJavaAudioOutputObj; + JNIEnv* iJni; + +}; + +#endif // CAMMSAUDIOOUTPUTCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsaudioplayerbuilder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsaudioplayerbuilder.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder for adding AMMS audio player controls. +* +*/ + + +#ifndef CAMMSAUDIOPLAYERBUILDER_H +#define CAMMSAUDIOPLAYERBUILDER_H + +// INCLUDES +#include "cammsplayerbuilder.h" + + +// CLASS DECLARATION + +/** +* +* AudioControl player builder. +* This class adds AMMS audio player controls. +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSAudioPlayerBuilder): public CAMMSPlayerBuilder +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSAudioPlayerBuilder* NewLC(); + + /** + * Destructor. + */ + ~CAMMSAudioPlayerBuilder(); + +public: // Funtions from base classes + /** + * Adds the AMMS audio controls to the player + * + * @param aPlayer The Player where the AMMS controls are added + */ + void PreparePlayerL(CMMAPlayer* aPlayer); + +private: + /** + * C++ default constructor. + */ + CAMMSAudioPlayerBuilder(); + +}; + +#endif // CAMMSAUDIOPLAYERBUILDER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsaudiovirtualizercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsaudiovirtualizercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,138 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Virtualizes audio channels. +* +*/ + + +#ifndef CAMMSAUDIOVIRTUALIZERCONTROL_H +#define CAMMSAUDIOVIRTUALIZERCONTROL_H + +// INCLUDES +#include +#include +#include +#include +#include "cammseffectcontrol.h" + +// CONSTANTS +_LIT(KAMMSAudioVirtualizerControl, "AudioVirtualizerControl"); + +// CLASS DECLARATION +/** +* +* Controls for the Audio Virtualizer effect. +* This class delegates Audio Virtualizer effect method calls to +* CStereoWidening. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSAudioVirtualizerControl): public CAMMSEffectControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSAudioVirtualizerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSAudioVirtualizerControl(); + +public: // New functions + +public: // Functions from base classes + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSAudioVirtualizerControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /** Native Stereo Widening Utility */ + CStereoWideningUtility* iStereoWideningUtility; + + /** Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + + /** Index of the current preset */ + TInt iCurrentPreset; + +}; + +#endif // CAMMSAUDIOVIRTUALIZERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsbasedistanceattenuationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsbasedistanceattenuationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + +#ifndef CAMMSBASEDISTANCEATTENUATIONCONTROL_H +#define CAMMSBASEDISTANCEATTENUATIONCONTROL_H + +// INCLUDES +#include +#include "cammscontrol.h" + +// CONSTANTS +_LIT(KAMMSBaseDistanceAttenuationControl, "DistanceAttenuationControl"); + +// CLASS DECLARATION + +/** +* +* Base class for the Distance Attenuation effect. +* This class delegates Distance Attenuation effect method calls to +* to corresponding control. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSBaseDistanceAttenuationControl): public CAMMSControl +{ +public: //destructor + /** + * Destructor. + */ + ~CAMMSBaseDistanceAttenuationControl(); + +public: // New functions + + virtual void SetParametersL( + TInt/* aMinDistance*/, + TInt /*aMaxDistance*/, + TBool /*aMuteAfterMax*/, + TInt /*aRolloffFactor*/) = 0; + +public: + const TDesC& ClassName() const = 0; + +protected: + /** + * C++ default constructor, protected to allow access from derived class + * @param aPlayer Player that has this control. + */ + CAMMSBaseDistanceAttenuationControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSBASEDISTANCEATTENUATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsbaseequalizercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsbaseequalizercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,147 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +#ifndef CAMMSBASEEQUALIZERCONTROL_H +#define CAMMSBASEEQUALIZERCONTROL_H + +// INCLUDES +#include +#include "cammseffectcontrol.h" + +// CONSTANTS +_LIT(KAMMSBaseEqualizerControl, "EqualizerControl"); +const TInt KAMMSHalfOfSamplingFrequency = 24000000; //in milliHertz +const TInt KAMMSBandOffset = 1; // Band 0 in JSR-234 equals Band 1 in Effect API + +// CLASS DECLARATION + +/** +* +* Controls for the Equalizer effect. +* +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSBaseEqualizerControl): public CAMMSEffectControl +{ +public: + /** + * Destructor. + */ + ~CAMMSBaseEqualizerControl(); + +public: // New functions + + /** + * Gets the gain set for the given equalizer band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The gain set for the given band in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aBand is out of range. + */ + virtual TInt BandLevelL(TInt aBand) = 0; + + /** + * Returns the maximum band level supported. + * + * @return The maximum band level in millibels. + */ + virtual TInt MaxBandLevel() = 0; + + /** + * Returns the minimum band level supported. + * + * @return The minimum band level in millibels. + */ + virtual TInt MinBandLevel() = 0; + + /** + * Returns the band width in Hz for the specified band. + * + * @param aBand The frequency band whose band width is asked. + * The numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @return The band width in Hz for the specified band. + */ + virtual TInt BandWidth(TInt aBand) = 0; + + /** + * Returns the center frequency in Hz for a given band. + * + * @param aBand The frequency band whose center frequency + * is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The center frequency in Hz for a given band. + */ + virtual TInt CenterFrequency(TInt aBand) = 0; + + /** + * Returns the cross-over frequency between the given frequency + * band (aBand) and the next band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return Crossover frequency. + */ + virtual TInt CrossoverFrequency(TInt aBand) = 0; + + /** + * Gets the number of frequency bands that the equalizer supports. + * + * @return The number of frequency bands that the equalizer supports. + */ + virtual TInt NumberOfBands() = 0; + + /** + * Sets the given equalizer band to the given gain value. + * + * @param aLevel The new gain in millibels that will be set to the given + * band. getMinBandLevel() and getMaxBandLevel() will define the maximum + * and minimum values. + * @param aBand The frequency band that will have the new gain. The + * numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @par Leaving: + * @li \c KErrArgument - \a aBand or \a aLevel is out of range. + */ + virtual void SetBandLevelL(TInt aLevel, TInt aBand) = 0; + +public: + virtual const TDesC& ClassName() const = 0; + +protected: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSBaseEqualizerControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSBASEEQUALIZERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsbasereverbcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsbasereverbcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + +#ifndef CAMMSBASEREVERBCONTROL_H +#define CAMMSBASEREVERBCONTROL_H + +// INCLUDES +#include +#include +#include +#include +#include "cammseffectcontrol.h" +// only require if platform support EMC +#ifdef RD_JAVA_HTTP_EMC_ENABLED +#include +#endif +// CONSTANTS +_LIT(KAMMSBaseReverbControl, "ReverbControl"); +_LIT(KAMMSBaseDefaultReverbPreset, "smallroom"); + +// only require if platform support EMC +#ifdef RD_JAVA_HTTP_EMC_ENABLED +using multimedia :: MReverbControl; +#endif +// CLASS DECLARATION + +/** +* +* Controls for the Reverb effect. +* This class delegates Reverb effect method calls to CReverb. +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSBaseReverbControl): public CAMMSEffectControl +{ +public: // destructor + + /** + * Destructor. + */ + ~CAMMSBaseReverbControl(); + +public: // New functions + + /** + * Sets the gain level of the reverberation. The value defines what is + * the relative level of the first reflections compared to the sound + * source without possible distance attenuations, directivities or + * obstructions taken into account. + * + * @param aLevel The new level of the reverberation in millibels. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + virtual TInt SetReverbLevelL(TInt aLevel) = 0; + + /** + * Sets the reverberation time of the reverb. The reverberation time is + * the time taken for the reverberant sound to attenuate by 60 dB from + * its initial level. Typical values are in the range from 100 to 20000 + * milliseconds. + * The implementation might not support long reverberation times. + * Therefore, the actual time used might be shorter than the time + * specified with this method. + * + * @param aTime The new reverberation time in milliseconds. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aTime is negative. + * From Java API more leave codes are: + * - java.lang.IllegalArgumentException - when the given time is + * negative + * - javax.microedition.media.MediaException - when the changing of the + * reverb time is not supported + */ + virtual void SetReverbTimeL(TInt aTime) = 0; + + /** + * Gets the gain level of the reverberation. + * + * @return The level of the reverberation in millibels. + */ + virtual TInt ReverbLevel() = 0; + + /** + * Gets the reverberation time. + * + * @return The time of the reverberation in milliseconds. + */ + virtual TInt ReverbTime() = 0; + + /** + * Gets the minimum level of the reverberation. + * + * @return The minimum level of the reverberation in millibels. + */ + virtual TInt MinReverbLevel() = 0; + + /** + * Gets the maximum level of the reverberation. + * + * @return The maximum level of the reverberation in millibels. + */ + virtual TInt MaxReverbLevel() = 0; + + /** + * Gets the current preset index. + * + */ + virtual TInt CurrentPresetIndex() = 0; + +public: + + virtual const TDesC& ClassName() const = 0; + + +public: // Functions needed by reverb source control + + /** + * Returns the environmental reverb utility. + * ReverbSourceControl has to use the same instance. + * The function creates the instance if they do not exist yet. + * + * @param aEnvironmentalReverbUtility Returned utility instance. + */ + virtual void GetEnvironmentalReverbUtilityL( + CEnvironmentalReverbUtility** aEnvironmentalReverbUtility); + // only require if platform support EMC +#ifdef RD_JAVA_HTTP_EMC_ENABLED + virtual MReverbControl* GetReverbControlL(); +#endif +protected: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSBaseReverbControl(CMMAPlayer* aPlayer); + + +}; + +#endif // CAMMSBASEREVERBCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsbasereverbsourcecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsbasereverbsourcecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class behaves like interface of an audio effect reverb source. +* +*/ + + +#ifndef CAMMSBASEREVERBSOURCECONTROL_H +#define CAMMSBASEREVERBSOURCECONTROL_H + +// INCLUDES +#include +#include "cammscontrol.h" + +// CONSTANTS +_LIT(KAMMSBaseReverbSourceControl, "ReverbSourceControl"); + + +// CLASS DECLARATION + +/** +* +* Controls for the Reverb Source effect. +* This class delegates Base class of Reverb Source effect method . +* +* +* @since 5.1 +*/ +NONSHARABLE_CLASS(CAMMSBaseReverbSourceControl): public CAMMSControl +{ +public: + + /** + * Destructor. + */ + ~CAMMSBaseReverbSourceControl(); + +public: + /** + * Sets the object specific level for the reverberant sound. + * The default value is 0 meaning the natural room gain (set by + * ReverbControl's presets). + * + * @param aLevel The new level of the reverberation in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + virtual void SetRoomLevelL(TInt aLevel) = 0; + +public: + + const TDesC& ClassName() const = 0; + +protected: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + * @param aReverbControl Reverb control belonging to aPlayer. + */ + CAMMSBaseReverbSourceControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSBASEREVERBSOURCECONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammscontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammscontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for AMMS controls. +* +*/ + + +#ifndef CAMMSCONTROL_H +#define CAMMSCONTROL_H +// INCLUDES +#include +#include +#include "ammsconstants.h" +// RD_JAVA_HTTP_EMC_ENABLED +#ifdef RD_JAVA_HTTP_EMC_ENABLED +#include "StreamControl.h" +#include "EffectControl.h" +#include "MMControlFactory.h" +using namespace multimedia; +using multimedia ::MStreamControl; +using multimedia ::MEffectControl; +using multimedia ::CMultimediaFactory; +#endif + +// FORWARD DECLARATIONS +class CCustomCommandUtility; +class CMMAPlayer; + +// CLASS DECLARATION + +/** +* +* Base class for AMMS controls. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSControl): public CMMAControl +{ +public: + /** + * Destructor. + */ + virtual ~CAMMSControl(); + +public: // New functions + /** + * Creates the custom command utility. + * @since 3.0 + */ + CCustomCommandUtility* CreateCustomCommandUtilityL(); + + /** + * Prepares the Control by creating the Effect API Control. + */ + virtual void PrepareControlL(); + + /** + * Deallocates the Control by deleting the Effect API Control. + */ + virtual void DeallocateControl(); + +public: // From CMMAControl + + const TDesC& PublicClassName() const; + +protected: + + /** + * C++ default constructor. + * @param aPlayer Player that has this control. + */ + CAMMSControl(CMMAPlayer* aPlayer); + +public: // Data + + /** Type of the Control */ + TAMMSControlTypes iControlType; + +protected: // Data + + CMMAPlayer* iPlayer; // Not owned. +}; + +#endif // CAMMSCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammscustomcommandutility.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammscustomcommandutility.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,99 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Custom command utility class for AMMS custom commands. +* +*/ + + +#ifndef CAMMSCUSTOMCOMMANDUTILITY_H +#define CAMMSCUSTOMCOMMANDUTILITY_H + +// INCLUDES +#include +#include +#include + +// CLASS DECLARATION + +/** +* +* Custom command Utility implementation class. +* This class is used to deliver custom commands to MMFController. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSCustomCommandUtility): public CCustomCommandUtility +{ +public: // Constructors and destructor + /** + * Two-phased constructor. + */ + static CAMMSCustomCommandUtility* NewL( + RMMFController& aMMFController); + + /** + * Two-phased constructor. + */ + static CAMMSCustomCommandUtility* NewLC( + RMMFController& aMMFController); + + /** + * Destructor. + */ + ~CAMMSCustomCommandUtility(); + +public: // New functions + +public: // Functions from base classes + + TInt CustomCommandSync(const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom); + + TInt CustomCommandSync(const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2); + + void CustomCommandAsync(const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom, + TRequestStatus& aStatus); + + void CustomCommandAsync(const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TRequestStatus& aStatus); + +private: + /** + * C++ constructor. + */ + CAMMSCustomCommandUtility(RMMFController& aMMFController); + +private: // Data + + RMMFController& iMMFController; + +}; + +#endif // CAMMSCUSTOMCOMMANDUTILITY_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsdistanceattenuationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsdistanceattenuationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,121 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + +#ifndef CAMMSDISTANCEATTENUATIONCONTROL_H +#define CAMMSDISTANCEATTENUATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsbasedistanceattenuationcontrol.h" + +// CONSTANTS +_LIT(KAMMSDistanceAttenuationControl, "DistanceAttenuationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Distance Attenuation effect. +* This class delegates Distance Attenuation effect method calls to +* CDistanceAttenuation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSDistanceAttenuationControl): public CAMMSBaseDistanceAttenuationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSDistanceAttenuationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSDistanceAttenuationControl(); + +public: // override base class functions + + /** + * Sets all the 3D audio distance attenuation parameters simultaneously. + * Distances are specified in units defined by + * "GlobalManager.getUnitsPerMeter()" + * + * @param aMinDistance The minimum distance, below which the distance + * gain is clipped to its maximum value of 1.0. + * @param aMaxDistance The maximum distance, beyond which the distance + * gain does not decrease any more. The exact behaviour of the gain at + * distances beyond the maximum distance depends on the value of the + * muteAfterMax. + * @param aMuteAfterMax A boolean determining how the distance gain + * behaves at distances greater than maxDistance: true if beyond the + * maximum distance the source is silent; false if beyond the maximum + * distance the source's gain is held constant at the level at the + * maximum distance. + * @param aRolloffFactor The rolloff factor, specified in thousandths + * (1000 representing a rolloff factor of 1.0, 2000 representing 2.0 and + * 500 representing 0.5). Higher values cause the distance gain to + * attenuate more quickly. + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aMaxDistance <= \a aMinDistance, + * \a aMinDistance <= 0, \a aMaxDistance <= 0 or \a aRolloffFactor < 0 + */ + void SetParametersL( + TInt aMinDistance, + TInt aMaxDistance, + TBool aMuteAfterMax, + TInt aRolloffFactor); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSDistanceAttenuationControl(CMMAPlayer* aPlayer); + +private: // Data + + /** Native distance attenuation */ + CDistanceAttenuation* iDistanceAttenuation; + + +}; + +#endif // CAMMSDISTANCEATTENUATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsdopplercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsdopplercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,135 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an effect called Doppler. +* +*/ + + +#ifndef CAMMSDOPPLERCONTROL_H +#define CAMMSDOPPLERCONTROL_H + +// INCLUDES +#include +#include +#include "cammscontrol.h" + +// CLASS DECLARATION + +/** +* +* Controls for the Doppler effect. +* This class delegates Doppler effect method calls to CDoppler. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSDopplerControl): public CAMMSControl +{ +public: // Destructor + /** + * Destructor. + */ + ~CAMMSDopplerControl(); + +public: // New functions + /** + * Specifies if this Doppler effect is active or ignored. In case the + * DopplerControl is fetched from the Spectator, this method does not + * affect anything. + * + * @param aEnabled The boolean specifying if this Doppler effect is to + * be applied. + * + * @par Leaving: + * From Java API there are no leave codes, but the uset EffectControl's + * method leaves with the sama way as in effect control, if: + * - the effect cannot be enabled in this state of the player. + * - enabling is not supported (with the scope set). + */ + virtual void SetEnabledL(TBool aDopplerEnabled); + + /** + * Returns whether this Doppler effect is currently active. + * + * @return The boolean, true if Doppler is being applied. + */ + virtual TBool Enabled(); + + /** + * Sets the velocity, used in calculations for the Doppler effect. + * + * The velocity is specified using right-handed cartesian components in + * units defined by GlobalManager.getUnitsPerMeter(). For example, if + * the x parameter is specified to be 5000 and + * GlobalManager.getUnitsPerMeter() returns 1000 the actual x component + * will be 5 m/s. The same applies to y and z parameters. + * + * @param aX The x-coordinate of the new velocity. + * @param aY The y-coordinate of the new velocity. + * @param aZ The z-coordinate of the new velocity. + * + * @par Leaving: + * @li \c KErrArgument - coordinates are not correct. + */ + virtual void SetVelocityCartesianL(TInt aX, TInt aY, TInt aZ); + + /** + * Returns the current velocity, used in calculations for the Doppler + * effect. The velocity is specified using right-handed cartesian + * components in units defined by GlobalManager.getUnitsPerMeter(). + * The referenced memory of arguments will contain the coordinate values. + * + * @param aX The x-coordinate of the velocity. + * @param aY The y-coordinate of the velocity. + * @param aZ The z-coordinate of the velocity. + */ + virtual void VelocityCartesian(TInt& aX, TInt& aY, TInt& aZ); + + /** + * Sets the velocity, used in calculations for the Doppler effect. + * + * The velocity is specified using spherical components. The radius + * component is specified in units defined by + * GlobalManager.getUnitsPerMeter(). For example, if the radius + * parameter is specified to be 5000 and + * GlobalManager.getUnitsPerMeter() returns 1000 the actual radius + * component will be 5 m/s. + * + * @param aAzimuth The azimuth angle of the new velocity in degrees. + * @param aElevation The elevation angle of the new velocity in degrees. + * @param aRadius The magnitude of the new velocity (namely the speed). + * + * @par Leaving: + * @li \c KErrArgument - coordinates are not correct. + */ + virtual void SetVelocitySphericalL(TInt aAzimuth, TInt aElevation, + TInt aRadius); + +protected: + /** + * C++ default constructor, protected to allow access from derived class + * @param aPlayer Player that has this control. + */ + CAMMSDopplerControl(CMMAPlayer* aPlayer); + + +protected: // Data + + /* Native Doppler effect, set from derived classes */ + CDoppler* iDopplerEffect; +}; + +#endif // CAMMSDOPPLERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammseffectcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammseffectcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,160 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls an abstract filter with various preset settings. +* +*/ + + +#ifndef CAMMSEFFECTCONTROL_H +#define CAMMSEFFECTCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammscontrol.h" + +// CLASS DECLARATION + +/** +* +* Controls for the audio effect control. +* This class delegates Audio Effect method calls to native +* audio effect (created either in CAMMSEqualizerControl or +* in CAMMSReverbControl). +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSEffectControl): public CAMMSControl +{ +public: // Constructors and destructor + /** + * Destructor. + */ + ~CAMMSEffectControl(); + +public: // New functions + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + virtual void SetPresetL(const TDesC& aPreset) = 0; + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + virtual const CDesCArray& PresetNamesL() = 0; + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + virtual const TDesC& PresetL() = 0; + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + virtual void SetEnabledL(TBool aEnable) = 0; + +//Making the following funcitons virtual because of EMC added functionalities + /** + * Enforces the effect to be in use. If this is an EffectControl of a + * MediaProcessor, the enforced setting does not affect in any way. + * + * @param aPreset The boolean value - true if the effect is essential + * and cannot be dropped, false if the effect can be dropped if the + * system runs out of resources. + * + * @par Leaving: + * @li \c KErrArgument - some error happened. + */ + virtual void SetEnforcedL(TBool aEnforced); + + /** + * Returns the current enforced setting of the effect. + * + * @return The boolean, true if the effect is an enforced effect, false + * if not. + */ + virtual TBool Enforced(); + + /** + * Sets the scope of the effect. If this is an EffectControl of the + * MediaProcessor, the scope setting does not affect in anything. + * + * @param aScope SCOPE_LIVE_ONLY, SCOPE_RECORD_ONLY or + * SCOPE_LIVE_AND_RECORD. + * + * @par Leaving: + * From Java API the leave codes are: + * - javax.microedition.media.MediaException - if the given scope is + * not supported + */ + virtual void SetScopeL(TInt aScope); + + /** + * Returns the scope in which the effect is present. + * + * @return SCOPE_LIVE_ONLY, SCOPE_RECORD_ONLY or SCOPE_LIVE_AND_RECORD. + */ + virtual TInt Scope(); + +protected: + /** + * C++ default constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEffectControl(CMMAPlayer* aPlayer); + +protected: + /** + * Apply changed settings if Effect is in enabled state. + */ + virtual void ApplySettingsL(); + +protected: + /** + * By default Symbian 2nd phase constructor is private, + * but allow now the base class to access ConstructL. + */ + void ConstructL(); + +protected: // Data + + /* Native audio effect */ + CAudioEffect* iAudioEffect; + +}; + +#endif // CAMMSEFFECTCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsequalizercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsequalizercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,221 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +#ifndef CAMMSEQUALIZERCONTROL_H +#define CAMMSEQUALIZERCONTROL_H + +// INCLUDES +#include +#include +#include +#include +#include "cammsbaseequalizercontrol.h" + +// CONSTANTS +_LIT(KAMMSEqualizerControl, "EqualizerControl"); + + +// CLASS DECLARATION + +/** +* +* Controls for the Equalizer effect. +* This class delegates Equalizer effect method calls to CAudioEqualizer. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSEqualizerControl): public CAMMSBaseEqualizerControl +{ +public: + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSEqualizerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSEqualizerControl(); + +public: // New functions + + /** + * Gets the gain set for the given equalizer band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The gain set for the given band in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aBand is out of range. + */ + TInt BandLevelL(TInt aBand); + + /** + * Returns the maximum band level supported. + * + * @return The maximum band level in millibels. + */ + TInt MaxBandLevel(); + + /** + * Returns the minimum band level supported. + * + * @return The minimum band level in millibels. + */ + TInt MinBandLevel(); + + /** + * Returns the band width in Hz for the specified band. + * + * @param aBand The frequency band whose band width is asked. + * The numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @return The band width in Hz for the specified band. + */ + TInt BandWidth(TInt aBand); + + /** + * Returns the center frequency in Hz for a given band. + * + * @param aBand The frequency band whose center frequency + * is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return The center frequency in Hz for a given band. + */ + TInt CenterFrequency(TInt aBand); + + /** + * Returns the cross-over frequency between the given frequency + * band (aBand) and the next band. + * + * @param aBand The frequency band whose gain is asked. The numbering of + * the bands starts from 0 and ends at (getNumberOfBands() - 1). + * + * @return Crossover frequency. + */ + TInt CrossoverFrequency(TInt aBand); + + /** + * Gets the number of frequency bands that the equalizer supports. + * + * @return The number of frequency bands that the equalizer supports. + */ + TInt NumberOfBands(); + + /** + * Sets the given equalizer band to the given gain value. + * + * @param aLevel The new gain in millibels that will be set to the given + * band. getMinBandLevel() and getMaxBandLevel() will define the maximum + * and minimum values. + * @param aBand The frequency band that will have the new gain. The + * numbering of the bands starts from 0 and ends at + * (getNumberOfBands() - 1). + * + * @par Leaving: + * @li \c KErrArgument - \a aBand or \a aLevel is out of range. + */ + void SetBandLevelL(TInt aLevel, TInt aBand); + +public: // Functions from base classes + + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSEqualizerControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /** Native audio equalizer */ + CAudioEqualizerUtility* iEqualizerUtility; + + /* Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + + /* Index of the current preset */ + TInt iCurrentPreset; + +}; + +#endif // CAMMSEQUALIZERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammslocationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammslocationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,109 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of an object. +* +*/ + + +#ifndef CAMMSLOCATIONCONTROL_H +#define CAMMSLOCATIONCONTROL_H + +// INCLUDES +#include +#include "cammscontrol.h" + +// CLASS DECLARATION + +/** +* +* Controls for the Location Control effect. +* This class delegates Location Control effect method calls to +* CSourceLocation or CListenerLocation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSLocationControl): public CAMMSControl +{ +public: // Constructors and destructor + /** + * Destructor. + */ + ~CAMMSLocationControl(); + +public: // New functions + /** + * Moves the object to the new location. + * + * Sets the location using cartesian right-handed coordinates that are + * relative to the origin. The measures are defined in units specified + * by GlobalManager.getUnitsPerMeter(). + * + * @param aX The x-coordinate of the new location. + * @param aY The y-coordinate of the new location. + * @param aZ The z-coordinate of the new location. + * + * @par Leaving: + * @li \c KErrArgument - coordinates are not correct. + */ + virtual void SetLocationCartesianL(TInt& aX, TInt& aY, TInt& aZ); + + /** + * Gets the coordinates of the current location. The measures are + * defined in units specified by GlobalManager.getUnitsPerMeter(). . + * + * @param aX The x-coordinate of the location. + * @param aY The y-coordinate of the location. + * @param aZ The z-coordinate of the location. + */ + virtual void LocationCartesian(TInt& aX, TInt& aY, TInt& aZ); + + /** + * Moves the object to the new location. + * + * Sets the new location using spherical coordinates. The negative + * z-axis is the reference. That is, a location where both azimuth and + * elevation are zero, is on the negative z-axis. Radius is defined in + * units specified by GlobalManager.getUnitsPerMeter(). + * + * @param aAzimuth The azimuth angle of the new location in degrees. The + * azimuth is measured from the negative z-axis in the direction of the + * x-axis. + * @param aElevation The elevation angle of the new location in degrees. + * The elevation is measured from the x-z-plane in the direction of the + * y-axis. + * @param aRadius The radius of the new location from the origin. + * + * @par Leaving: + * @li \c KErrArgument - \a aRadius < 0. + */ + virtual void SetLocationSphericalL(TInt& aAzimuth, TInt& aElevation, + TInt& aRadius); + +protected: + /** + * C++ default constructor, protected to allow access from derived class + * @param aPlayer Player that has this control. + */ + CAMMSLocationControl(CMMAPlayer* aPlayer); + +protected: // Data + + /* Native location effect, set from derived classes */ + CLocation* iLocationEffect; +}; + +#endif // CAMMSLOCATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsorientationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsorientationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,134 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of an object. +* +*/ + + +#ifndef CAMMSORIENTATIONCONTROL_H +#define CAMMSORIENTATIONCONTROL_H + +// INCLUDES +#include +#include "cammscontrol.h" + +// CONSTANS +_LIT(KAMMSOrientationControl, "OrientationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Orientation Control effect. +* This class delegates Orientation Control effect method calls to +* CListenerOrientation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSOrientationControl): public CAMMSControl +{ +public: // Constructors and destructor + /** + * Destructor. + */ + ~CAMMSOrientationControl(); + +public: // New functions + /** + * Turns the object to the new orientation. + * + * The new orientation is given using rotation angles. A zero vector + * corresponds to the orientation pointing directly towards the negative + * Z-axis. Orientation is applied in the following order: heading, + * pitch, and roll. Therefore, notice that heading turns the X-axis and + * therefore affects the pitch, and similarly heading and pitch turn the + * Z-axis and therefore affect the roll. + * + * @param aHeading The rotation around the Y-axis in degrees. + * @param aPitch The rotation around the X-axis in degrees. + * @param aRoll The rotation around the Z-axis in degrees. + */ + virtual void SetOrientationL(TInt aHeading, TInt aPitch, TInt aRoll); + + /** + * Turns the object to the new orientation. + * + * The orientation is specified using two vectors, one specifying the + * direction of the front vector of the object in world coordinates, and + * another specifying the "above" vector of the object. The right and up + * vectors of the object are calculated by first normalizing both source + * vectors, then calculating the right vector as the cross product of the + * "above" vector and the front vector, and the up vector as a cross + * product of the front and right vectors. + * + * Because both vectors are normalized, they may be of any length. + * + * @param aFrontX X value of Front vector + * @param aFrontY Y value of Front vector + * @param aFrontZ Z value of Front vector + * @param aAboveX X value of Above vector + * @param aAboveY Y value of Above vector + * @param aAboveZ Z value of Above vector + * + * @par Leaving: + * @li \c KErrArgument - In case any of the parameters is a zero vector + * or they are parallel to each other. + * In that case, the orientation of the object remains unchanged. + */ + virtual void SetOrientationL(TInt aFrontX, + TInt aFrontY, + TInt aFrontZ, + TInt aAboveX, + TInt aAboveY, + TInt aAboveZ); + + /** + * Gets the orientation of the object using two vectors. + * + * Sets the location using cartesian right-handed coordinates that are + * relative to the origin. The measures are defined in units specified + * by GlobalManager.getUnitsPerMeter(). + * Referenced memory of the arguments will contain the coordinate values. + * + * @param aFrontX X value of Front vector + * @param aFrontY Y value of Front vector + * @param aFrontZ Z value of Front vector + * @param aAboveX X value of Above vector + * @param aAboveY Y value of Above vector + * @param aAboveZ Z value of Above vector + */ + virtual void OrientationVectors(TInt& aFrontX, + TInt& aFrontY, + TInt& aFrontZ, + TInt& aAboveX, + TInt& aAboveY, + TInt& aAboveZ); + +protected: + /** + * C++ default constructor, protected to allow access from derived class + * @param aPlayer Player that has this control. + */ + CAMMSOrientationControl(CMMAPlayer* aPlayer); + +protected: // Data + + /* Native orientation effect, set from derived classes */ + COrientation* iOrientationEffect; +}; + +#endif // CAMMSORIENTATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsplayerbuilder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsplayerbuilder.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for AMMS player builders. +* +*/ + + +#ifndef CAMMSPLAYERBUILDER_H +#define CAMMSPLAYERBUILDER_H + +// INCLUDES +#include + +// CLASS DECLARATION + +/** +* +* Base class for AMMS player and control builders. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSPlayerBuilder): public CBase +{ +public: // Constructors and destructor + /** + * Destructor. + */ + ~CAMMSPlayerBuilder(); + +public: // New methods + /** + * Adds the AMMS audio controls to the player + * + * @param aPlayer The MMA Player where the AMMS controls are added + */ + virtual void PreparePlayerL(CMMAPlayer* aPlayer) = 0; + +protected: //Protected so derived classes can access + /** + * C++ default constructor. + */ + CAMMSPlayerBuilder(); +}; + +#endif // CAMMSPLAYERBUILDER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsplayerbuildergroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsplayerbuildergroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder group for adding players. +* +*/ + + +#ifndef CAMMSPLAYERBUILDERGROUP_H +#define CAMMSPLAYERBUILDERGROUP_H + +// INCLUDES +#include "cammsplayerbuilder.h" + +// CLASS DECLARATION + +/** +* +* This class is used to add AMMS audio controls to the player. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSPlayerBuilderGroup): public CAMMSPlayerBuilder +{ +public: // Constructors and destructor + /** + * Two-phased constructor. + */ + static CAMMSPlayerBuilderGroup* NewL(); + + /** + * Two-phased constructor. + */ + static CAMMSPlayerBuilderGroup* NewLC(); + + /** + * Destructor. + */ + ~CAMMSPlayerBuilderGroup(); + +public: // Funtions from base classes + /** + * Adds the AMMS audio controls to the player + * + * @param aPlayer The MMA Player where the AMMS controls are added + */ + virtual void PreparePlayerL(CMMAPlayer* aPlayer); + +public: // New methods + /** + * Adds the AMMS control builder + * + * @param aPlayerBuilder The AMMS player builder + */ + void AddBuilderAndPopL(CAMMSPlayerBuilder* aPlayerBuilder); + +private: + /** + * C++ default constructor. + */ + CAMMSPlayerBuilderGroup(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + CArrayPtrSeg< CAMMSPlayerBuilder >* iPlayerBuilders; // Owned + +}; + +#endif // CAMMSPLAYERBUILDERGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsprioritycontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsprioritycontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,113 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the priority of a Player. +* +*/ + + +#ifndef CAMMSPRIORITYCONTROL_H +#define CAMMSPRIORITYCONTROL_H + +// INCLUDES +#include "cammscontrol.h" +#include + +// CONSTANTS +_LIT(KAMMSPriorityControl, "PriorityControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the priority. +* This class delegates priority setting calls to RMMFController. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSPriorityControl) + : public CAMMSControl, public MMMAPlayerStateListener +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSPriorityControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSPriorityControl(); + +public: // New functions + + /** + * Sets the priority. + * + * @param aPriority The new priority to be set. + */ + void SetPriorityL(TInt aPriority); + + /** + * Gets the priority. + * + * @return The set priority. + */ + TInt Priority(); + +public: // From MMMAPlayerStateListener + + void StateChanged(TInt aState); + +public: // Functions from base classes + + const TDesC& ClassName() const; + +protected: // New functions + + /** + * Scales the given AMMS priority to MMF priority + * and sets it to MMF if the priority has changed. + * @param aAmmsPriority AMMS priority to be set. + */ + void SetPriorityToMmfL(TInt aAmmsPriority); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSPriorityControl(CMMAPlayer* aPlayer); + + /** + * Symbian 2nd phase constructor. + */ + void ConstructL(); + +private: // data + + // Priority cannot be set if player is REALIZED. The priority is set + // when the player is prefetched. + + TInt iVisiblePriority; // Priority visible in AMMS. + + TInt iActualPriority; // Priority set in MMF. + +}; + +#endif // CAMMSPRIORITYCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsreverbcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsreverbcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,219 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + +#ifndef CAMMSREVERBCONTROL_H +#define CAMMSREVERBCONTROL_H + +// INCLUDES +#include +#include +#include +#include +#include "cammseffectcontrol.h" +#include "cammsbasereverbcontrol.h" + +// CONSTANTS +_LIT(KAMMSReverbControl, "ReverbControl"); +_LIT(KAMMSDefaultReverbPreset, "smallroom"); + +// CLASS DECLARATION + +/** +* +* Controls for the Reverb effect. +* This class delegates Reverb effect method calls to CReverb. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSReverbControl): public CAMMSBaseReverbControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSReverbControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSReverbControl(); + +public: // New functions + + /** + * Sets the gain level of the reverberation. The value defines what is + * the relative level of the first reflections compared to the sound + * source without possible distance attenuations, directivities or + * obstructions taken into account. + * + * @param aLevel The new level of the reverberation in millibels. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + TInt SetReverbLevelL(TInt aLevel); + + /** + * Sets the reverberation time of the reverb. The reverberation time is + * the time taken for the reverberant sound to attenuate by 60 dB from + * its initial level. Typical values are in the range from 100 to 20000 + * milliseconds. + * The implementation might not support long reverberation times. + * Therefore, the actual time used might be shorter than the time + * specified with this method. + * + * @param aTime The new reverberation time in milliseconds. + * + * @return The value that was actually set. + * + * @par Leaving: + * @li \c KErrArgument - \a aTime is negative. + * From Java API more leave codes are: + * - java.lang.IllegalArgumentException - when the given time is + * negative + * - javax.microedition.media.MediaException - when the changing of the + * reverb time is not supported + */ + void SetReverbTimeL(TInt aTime); + + /** + * Gets the gain level of the reverberation. + * + * @return The level of the reverberation in millibels. + */ + TInt ReverbLevel(); + + /** + * Gets the reverberation time. + * + * @return The time of the reverberation in milliseconds. + */ + TInt ReverbTime(); + + /** + * Gets the minimum level of the reverberation. + * + * @return The minimum level of the reverberation in millibels. + */ + TInt MinReverbLevel(); + + /** + * Gets the maximum level of the reverberation. + * + * @return The maximum level of the reverberation in millibels. + */ + TInt MaxReverbLevel(); + virtual TInt CurrentPresetIndex(); + +public: // Functions from base classes + /** + * Sets the effect according to the given preset. + * + * @param aPreset The new preset that will be taken into use. + * + * @par Leaving: + * @li \c KErrArgument - \a aPreset is not available or it is null. + */ + void SetPresetL(const TDesC& aPreset); + + /** + * Gets the available preset names. + * + * @return The names of all the available preset modes. + */ + const CDesCArray& PresetNamesL(); + + /** + * Gets the current preset. + * + * @return The preset that is set at the moment. If none of the presets + * is set, null will be returned. + */ + const TDesC& PresetL(); + + /** + * Enables/disables the effect. + * + * @param aEnabled The boolean value, true=enabled, false=disabled. + * + * @par Leaving: + * From Java API the leave codes are: + * - java.lang.IllegalStateException - if the effect cannot be enabled + * in this state of the player. + * - javax.microedition.media.MediaException - if enabling is not + * supported (with the scope set). + */ + void SetEnabledL(TBool aEnable); + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +public: // Functions needed by reverb source control + + /** + * Returns the environmental reverb utility. + * ReverbSourceControl has to use the same instance. + * The function creates the instance if they do not exist yet. + * + * @param aEnvironmentalReverbUtility Returned utility instance. + */ + void GetEnvironmentalReverbUtilityL( + CEnvironmentalReverbUtility** aEnvironmentalReverbUtility); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSReverbControl(CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + + /** Native reverb utility */ + CEnvironmentalReverbUtility* iReverbUtility; + + /* Array for querying the preset names, owned */ + CDesCArray* iPresetNames; + + /* Index of the current preset */ + TInt iCurrentPreset; + +}; + +#endif // CAMMSREVERBCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsreverbsourcecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsreverbsourcecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,112 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect reverb source. +* +*/ + + +#ifndef CAMMSREVERBSOURCECONTROL_H +#define CAMMSREVERBSOURCECONTROL_H + +// INCLUDES +#include +#include +#include +#include +//#include "CAMMSControl.h" +#include "cammsbasereverbsourcecontrol.h" + +// CONSTANTS +_LIT(KAMMSReverbSourceControl, "ReverbSourceControl"); + +// FORWARD DECLARATIONS +class CAMMSBaseReverbControl; + +// CLASS DECLARATION + +/** +* +* Controls for the Reverb Source effect. +* This class delegates Reverb Source effect method calls to CRoomLevel. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSReverbSourceControl): public CAMMSBaseReverbSourceControl //CAMMSControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + * @param aReverbControl Reverb control belonging to aPlayer. + */ + static CAMMSReverbSourceControl* NewLC(CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aReverbControl); + + /** + * Destructor. + */ + ~CAMMSReverbSourceControl(); + +public: // New functions + + /** + * Sets the object specific level for the reverberant sound. + * The default value is 0 meaning the natural room gain (set by + * ReverbControl's presets). + * + * @param aLevel The new level of the reverberation in millibels. + * + * @par Leaving: + * @li \c KErrArgument - \a aLevel is greater than 0 + */ + void SetRoomLevelL(TInt aLevel); + +public: // Functions from base classes + + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + * @param aReverbControl Reverb control belonging to aPlayer. + */ + CAMMSReverbSourceControl(CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aReverbControl); + +private: // Data + + /** Native reverb source */ + CRoomLevel* iReverbSource; + + /** Reverb control belonging to the player */ + CAMMSBaseReverbControl* iReverbControl; + +}; + +#endif // CAMMSREVERBSOURCECONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsspectatordopplercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsspectatordopplercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler of the spectator. +* +*/ + + +#ifndef CAMMSSPECTATORDOPPLERCONTROL_H +#define CAMMSSPECTATORDOPPLERCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsdopplercontrol.h" + +// CONSTANTS +_LIT(KAMMSSpectatorDopplerControl, "DopplerControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Doppler Control effect for the Spectator. +* This class delegates Doppler Control effect method calls to +* CListenerDoppler. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSSpectatorDopplerControl): public CAMMSDopplerControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSSpectatorDopplerControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSSpectatorDopplerControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSSpectatorDopplerControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSSPECTATORDOPPLERCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsspectatorlocationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsspectatorlocationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the spectator. +* +*/ + + +#ifndef CAMMSSPECTATORLOCATIONCONTROL_H +#define CAMMSSPECTATORLOCATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammslocationcontrol.h" + +// CONSTANTS +_LIT(KAMMSSpectatorLocationControl, "LocationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Location Control effect for the Spectator. +* This class delegates Location Control effect method calls to +* CListenerLocation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSSpectatorLocationControl): public CAMMSLocationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSSpectatorLocationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSSpectatorLocationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSSpectatorLocationControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSSPECTATORLOCATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsspectatororientationcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsspectatororientationcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of the spectator. +* +*/ + + +#ifndef CAMMSSPECTATORORIENTATIONCONTROL_H +#define CAMMSSPECTATORORIENTATIONCONTROL_H + +// INCLUDES +#include +#include +#include +#include "cammsorientationcontrol.h" + +// CONSTANTS +_LIT(KAMMSSpectatorOrientationControl, "OrientationControl"); + +// CLASS DECLARATION + +/** +* +* Controls for the Orientation Control effect for the Spectator. +* This class delegates Orientation Control effect method calls to +* CListenerOrientation. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSSpectatorOrientationControl): public CAMMSOrientationControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aPlayer Player that has this control. + */ + static CAMMSSpectatorOrientationControl* NewLC(CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSSpectatorOrientationControl(); + +public: // Functions from base classes + const TDesC& ClassName() const; + + /** + * Prepares the Control. + */ + void PrepareControlL(); + + /** + * Deallocates the Control. + */ + void DeallocateControl(); + +private: + /** + * C++ constructor. + * @param aPlayer Player that has this control. + */ + CAMMSSpectatorOrientationControl(CMMAPlayer* aPlayer); + +}; + +#endif // CAMMSSPECTATORORIENTATIONCONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsvolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsvolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls the volume of a CMMAVolumeControl. +* +*/ + + +#ifndef CAMMSVOLUMECONTROL_H +#define CAMMSVOLUMECONTROL_H + +// INCLUDES +#include +#include "cammscontrol.h" + +// FORWARD DECLARATIONS +class CMMAVolumeControl; + +// CONSTANTS +const TInt KAMMSMAXVolume = 100; + +// CLASS DECLARATION + +/** +* +* Controls the volume of a CMMAVolumeControl. +* This class delegates SetVolumeL method calls to CMMAVolumeControl +* given in constructor. +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSVolumeControl): public CAMMSControl +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * @param aControlName Class name for this control. + * @param aVolumeControl Delegated control. + * @param aPlayer Player that has this control. + */ + static CAMMSVolumeControl* NewLC(const TDesC& aControlName, + CMMAVolumeControl* aVolumeControl, + CMMAPlayer* aPlayer); + + /** + * Destructor. + */ + ~CAMMSVolumeControl(); + +public: // New functions + /** + * Sets the volume.. + * + * @param aVolume The new volume to be set. + */ + void SetVolumeL(TInt aVolume); + +public: // Functions from base classes + const TDesC& ClassName() const; + +private: + /** + * C++ constructor. + * @param aControlName Class name for this control. + * @param aVolumeControl Delegated control. + * @param aPlayer Player that has this control. + */ + CAMMSVolumeControl(const TDesC& aControlName, + CMMAVolumeControl* aVolumeControl, + CMMAPlayer* aPlayer); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // Data + const TDesC& iClassName; + + // Not owned mma volume control. + CMMAVolumeControl* iVolumeControl; + + // Index in iVolumeControl + TInt iControlLevelIndex; +}; + +#endif // CAMMSVOLUMECONTROL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/inc/cammsvolumecontrolbuilder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/inc/cammsvolumecontrolbuilder.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: VolumeControl player builder. +* +*/ + + +#ifndef CAMMSVOLUMECONTROLBUILDER_H +#define CAMMSVOLUMECONTROLBUILDER_H + +// INCLUDES +#include "cammsplayerbuilder.h" + +// CLASS DECLARATION + +/** +* +* VolumeControl player builder. +* This class adds CAMMSVolumeControl to all players that have +* CMMAVolumeControl. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSVolumeControlBuilder): public CAMMSPlayerBuilder +{ +public: // Constructors and destructor + /** + * Two-phased constructor. + */ + static CAMMSVolumeControlBuilder* NewLC(); + + /** + * Destructor. + */ + ~CAMMSVolumeControlBuilder(); + +public: // Funtions from CAMMSPlayerBuilder + void PreparePlayerL(CMMAPlayer* aPlayer); + +private: + /** + * C++ default constructor. + */ + CAMMSVolumeControlBuilder(); +}; + +#endif // CAMMSVOLUMECONTROLBUILDER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsaudioplayerbuilder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsaudioplayerbuilder.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,246 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder for adding AMMS audio player controls. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include +#include "cammsaudioplayerbuilder.h" +#include "cammscustomcommandutility.h" + +//MMF +#include "cammsequalizercontrol.h" +#include "cammsreverbcontrol.h" +#include "cammsreverbsourcecontrol.h" +#include "cammsaudiovirtualizercontrol.h" +#include "cammspancontrol.h" // same header will be used for EMC Control too +#include "cammsdistanceattenuationcontrol.h" +#include "cammsaudiodopplercontrol.h" +#include "cammsspectatordopplercontrol.h" +#include "cammsaudiolocationcontrol.h" +#include "cammsspectatorlocationcontrol.h" +#include "cammsspectatororientationcontrol.h" +#include "cammsvolumecontrol.h" +#include "ammsconstants.h" + + +//EMC +#include +#include "cammsemcaudiodopplercontrol.h" +#include "cammsemcspectatordopplercontrol.h" +#include "cammsemcaudiolocationcontrol.h" +#include "cammsemcspectatorlocationcontrol.h" +#include "cammsemcspectatororientationcontrol.h" +#include "cammsemcdistanceattenuationcontrol.h" +#include "cammsemcreverbcontrol.h" +#include "cammsemcreverbsourcecontrol.h" +#include "cammsemcaudiovirtualizercontrol.h" +#include "cammsemcequalizercontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioPlayerBuilder* CAMMSAudioPlayerBuilder::NewLC() +{ + CAMMSAudioPlayerBuilder* self = new(ELeave) CAMMSAudioPlayerBuilder(); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSAudioPlayerBuilder::~CAMMSAudioPlayerBuilder() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::PreparePlayerL +// Adds the AMMS audio controls to the player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioPlayerBuilder::PreparePlayerL(CMMAPlayer* aPlayer) +{ + const TDesC& playerType = aPlayer->Type(); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL type %S", + playerType.Ptr()); + + if ((playerType != KMMAAudioPlayer) && + (playerType != KMMAMIDIPlayer) && (playerType != KMMAEMCAudioPlayer)) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL, not supported"); + return; + } + + + // Default type for a Control is base Control (=not a derived Control). + // DopplerControl and LocationControl have different Effect API + // implementations and also different corresponding AMMS Controls for + // SoundSource3D and for Spectator, so these Control types need to be + // set accordingly. + // + // CMMAPlayer::AddControlL( CMMAControl* aControl ) adds a new control. + // Ownership of the control is transferred to CMMAPlayer. + // + + // CAMMSPanControl is common class to create control for MMF,MIDI and EMC type of Player,however implementation is different + +#ifndef __WINS__ + // PanControl is not supported in WINSCW builds. + // This is because of limited pan support in DirectX. + CAMMSPanControl* panControl = CAMMSPanControl::NewLC(aPlayer); + aPlayer->AddControlL(panControl); + CleanupStack::Pop(panControl); +#endif // __WINS__ + + + if (playerType != KMMAEMCAudioPlayer) + { + CAMMSAudioDopplerControl* audioDopplerControl = + CAMMSAudioDopplerControl::NewLC(aPlayer); + audioDopplerControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(audioDopplerControl); + CleanupStack::Pop(audioDopplerControl); + + CAMMSSpectatorDopplerControl* spectatorDopplerControl = + CAMMSSpectatorDopplerControl::NewLC(aPlayer); + spectatorDopplerControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(spectatorDopplerControl); + CleanupStack::Pop(spectatorDopplerControl); + + CAMMSAudioLocationControl* audioLocationControl = + CAMMSAudioLocationControl::NewLC(aPlayer); + audioLocationControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(audioLocationControl); + CleanupStack::Pop(audioLocationControl); + + CAMMSSpectatorLocationControl* spectatorLocationControl = + CAMMSSpectatorLocationControl::NewLC(aPlayer); + spectatorLocationControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(spectatorLocationControl); + CleanupStack::Pop(spectatorLocationControl); + + CAMMSSpectatorOrientationControl* spectatorOrientationControl = + CAMMSSpectatorOrientationControl::NewLC(aPlayer); + aPlayer->AddControlL(spectatorOrientationControl); + CleanupStack::Pop(spectatorOrientationControl); + + CAMMSDistanceAttenuationControl* distanceAttenuationControl = + CAMMSDistanceAttenuationControl::NewLC(aPlayer); + aPlayer->AddControlL(distanceAttenuationControl); + CleanupStack::Pop(distanceAttenuationControl); + + CAMMSReverbControl* reverbControl = + CAMMSReverbControl::NewLC(aPlayer); + aPlayer->AddControlL(reverbControl); + CleanupStack::Pop(reverbControl); + + CAMMSReverbSourceControl* reverbSourceControl = + CAMMSReverbSourceControl::NewLC(aPlayer, reverbControl); + aPlayer->AddControlL(reverbSourceControl); + CleanupStack::Pop(reverbSourceControl); + + CAMMSAudioVirtualizerControl* audioVirtualizerControl = + CAMMSAudioVirtualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(audioVirtualizerControl); + CleanupStack::Pop(audioVirtualizerControl); + + CAMMSEqualizerControl* equalizerControl = + CAMMSEqualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(equalizerControl); + CleanupStack::Pop(equalizerControl); + + } + else //EMC Player + { + + CAMMSEMCAudioDopplerControl* emcaudioDopplerControl = + CAMMSEMCAudioDopplerControl::NewLC(aPlayer); + emcaudioDopplerControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(emcaudioDopplerControl); + CleanupStack::Pop(emcaudioDopplerControl); + + CAMMSEMCSpectatorDopplerControl* emcspectatorDopplerControl = + CAMMSEMCSpectatorDopplerControl::NewLC(aPlayer); + emcspectatorDopplerControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(emcspectatorDopplerControl); + CleanupStack::Pop(emcspectatorDopplerControl); + + CAMMSEMCAudioLocationControl* emcaudioLocationControl = + CAMMSEMCAudioLocationControl::NewLC(aPlayer); + emcaudioLocationControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(emcaudioLocationControl); + CleanupStack::Pop(emcaudioLocationControl); + + CAMMSEMCSpectatorLocationControl* emcspectatorLocationControl = + CAMMSEMCSpectatorLocationControl::NewLC(aPlayer); + emcspectatorLocationControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(emcspectatorLocationControl); + CleanupStack::Pop(emcspectatorLocationControl); + + CAMMSEMCSpectatorOrientationControl* emcspectatorOrientationControl = + CAMMSEMCSpectatorOrientationControl::NewLC(aPlayer); + aPlayer->AddControlL(emcspectatorOrientationControl); + CleanupStack::Pop(emcspectatorOrientationControl); + + CAMMSEMCDistanceAttenuationControl* emcdistanceAttenuationControl = + CAMMSEMCDistanceAttenuationControl::NewLC(aPlayer); + aPlayer->AddControlL(emcdistanceAttenuationControl); + CleanupStack::Pop(emcdistanceAttenuationControl); + + CAMMSEMCReverbControl* emcreverbControl = + CAMMSEMCReverbControl::NewLC(aPlayer); + aPlayer->AddControlL(emcreverbControl); + CleanupStack::Pop(emcreverbControl); + + CAMMSEMCReverbSourceControl* emcreverbSourceControl = + CAMMSEMCReverbSourceControl::NewLC(aPlayer, emcreverbControl); + aPlayer->AddControlL(emcreverbSourceControl); + CleanupStack::Pop(emcreverbSourceControl); + + CAMMSEMCAudioVirtualizerControl* emcaudioVirtualizerControl = + CAMMSEMCAudioVirtualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(emcaudioVirtualizerControl); + CleanupStack::Pop(emcaudioVirtualizerControl); + + CAMMSEMCEqualizerControl* emcequalizerControl = + CAMMSEMCEqualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(emcequalizerControl); + CleanupStack::Pop(emcequalizerControl); + + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL add OK"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::CAMMSAudioPlayerBuilder +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioPlayerBuilder::CAMMSAudioPlayerBuilder() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiodopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiodopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,223 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler effect of the SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cammsemcaudiodopplercontrol.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioDopplerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioDopplerControl* CAMMSEMCAudioDopplerControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSEMCAudioDopplerControl* self = + new(ELeave) CAMMSEMCAudioDopplerControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCAudioDopplerControl::~CAMMSEMCAudioDopplerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::~CAMMSEMCAudioDopplerControl"); + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioDopplerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioDopplerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMSourceDopplerControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::PrepareControlL"); + //Create Doppler Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + //Check the state of stream control ,it must be INITIALIZED + TInt state = iStreamControl->GetState(); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::PrepareControlL: Stream state = %d,",state); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KSourceDopplerEffectControl, temp)); + iMSourceDopplerControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMSourceDopplerControl)); + iMSourceDopplerControl->Enable(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioDopplerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioDopplerControl::DeallocateControl() +{ + if (iMSourceDopplerControl) + { + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::DeallocateControl"); + + // Doppler for Audio can be disabled or enabled + if (Enabled()) + { + iMSourceDopplerControl->Disable(); + } + //return the control to factory + MEffectControl* temp = iMSourceDopplerControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMSourceDopplerControl; + iFactory->DeleteEffectControl(tempCtrl); + iMSourceDopplerControl = NULL; + + } + +} + +const TDesC& CAMMSEMCAudioDopplerControl::ClassName() const +{ + return KAMMSEMCAudioDopplerControl; +} + + + +void CAMMSEMCAudioDopplerControl::SetEnabledL(TBool aDopplerEnabled) +{ + + if (aDopplerEnabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::SetEnabledL(true)"); + iMSourceDopplerControl->Enable(); + } + else + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::SetEnabledL(false)"); + iMSourceDopplerControl->Disable(); + } + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCDopplerControl::Enabled +// Returns whether this Doppler effect is currently active. +// ----------------------------------------------------------------------------- +// +TBool CAMMSEMCAudioDopplerControl::Enabled() +{ + TBool temp; + iMSourceDopplerControl->IsEnabled(temp); + return temp; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDopplerControl::SetVelocityCartesianL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioDopplerControl::SetVelocityCartesianL( + TInt aX, + TInt aY, + TInt aZ) +{ + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::SetVelocityCartesianL: X=%d, Y=%d, Z=%d", + aX, aY, aZ); + //Check the state of stream control ,it must be INITIALIZED + TInt state = iStreamControl->GetState(); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::SetVelocityCartesianL: Stream state = %d,",state); + TInt err = iMSourceDopplerControl->SetCartesianVelocity(aX, aY, aZ); + + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCAudioDopplerControl::SetVelocityCartesianL: err = %d,",err); + + + // Apply updated settings to Effect API. + iMSourceDopplerControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDopplerControl::VelocityCartesian +// Returns the current velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioDopplerControl::VelocityCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Get the velocity's cartesian settings + // aX, aY and aZ are velocities in format mm/s + TInt err = iMSourceDopplerControl->CartesianVelocity(aX,aY,aZ); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCAudioDopplerControl::VelocityCartesian: err = %d,",err); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDopplerControl::SetVelocitySphericalL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioDopplerControl::SetVelocitySphericalL( + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + // Parameters are thousandths of radians + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioDopplerControl::SetVelocitySphericalL %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedElevation = (TInt32)(aElevation * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCDopplerControl::SetVelocitySphericalL %d, %d", + convertedAzimuth, convertedElevation); + + TInt err = iMSourceDopplerControl->SetSphericalVelocity( + convertedAzimuth, convertedElevation, aRadius); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCAudioDopplerControl::SetVelocitySphericalL: err = %d,",err); + // Apply updated settings to EMC API. + iMSourceDopplerControl->Apply(); + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioDopplerControl::CAMMSEMCAudioDopplerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioDopplerControl::CAMMSEMCAudioDopplerControl( + CMMAPlayer* aPlayer) + : CAMMSDopplerControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiolocationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiolocationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,188 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cammsemcaudiolocationcontrol.h" + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMinRadius = 0; +#endif // _DEBUG + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioLocationControl* CAMMSEMCAudioLocationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCAudioLocationControl* self = + new(ELeave) CAMMSEMCAudioLocationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCAudioLocationControl::~CAMMSEMCAudioLocationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::~CAMMSEMCAudioLocationControl"); + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioLocationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMSourceLocationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::PrepareControlL"); + //Create Location Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KSourceLocationEffectControl, temp)); + iMSourceLocationControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMSourceLocationControl)); + iMSourceLocationControl->Enable(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioLocationControl::DeallocateControl() +{ + if (iMSourceLocationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::DeallocateControl"); + + // Location for Audio can be disabled or enabled + TRAPD(err,iMSourceLocationControl->Disable()); + if (err != KErrNone) + { + // some EMC Error + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCAudioLocationControl::DeallocateControl err = %d",err); + } + //return the control to factory + MEffectControl* temp = iMSourceLocationControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMSourceLocationControl; + iFactory->DeleteEffectControl(tempCtrl); + iMSourceLocationControl = NULL; + } +} + +const TDesC& CAMMSEMCAudioLocationControl::ClassName() const +{ + return KAMMSEMCAudioLocationControl; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::SetLocationCartesianL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioLocationControl::SetLocationCartesianL( + TInt& aX, + TInt& aY, + TInt& aZ) +{ + // Sets the cartesian coordinates for the source location. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::SetLocationCartesianL: %d, %d, %d", + aX, aY, aZ); + + iMSourceLocationControl->SetLocationCartesian(aX, aY, aZ); + + // Apply updated settings to EMC API. + iMSourceLocationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::LocationCartesian +// Gets the coordinates of the current location. +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioLocationControl::LocationCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Gets the cartesian coordinates for the location of the source position. + // The coordinates of the positions are in millimeters. + iMSourceLocationControl->LocationCartesian(aX, aY, aZ); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::SetLocationSphericalL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioLocationControl::SetLocationSphericalL( + TInt& aAzimuth, + TInt& aElevation, + TInt& aRadius) +{ + // Check in debug build that aRadius is within valid range. + __ASSERT_DEBUG(aRadius >= KAMMSMinRadius, User::Invariant()); + + // Sets the spherical coordinates for the location of the source position. + // The parameters are thousandths of radians + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::SetLocationSphericalL: %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * + KDegToRad * 1000); + + TInt32 convertedElevation = (TInt32)(aElevation * + KDegToRad * 1000); + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioLocationControl::SetLocationSphericalL: %d, %d", + convertedAzimuth, convertedElevation); + + iMSourceLocationControl->SetLocationSpherical( + convertedAzimuth, convertedElevation, (TInt32&)aRadius); + + // Apply updated settings to EMC API. + iMSourceLocationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioLocationControl::CAMMSEMCAudioLocationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioLocationControl::CAMMSEMCAudioLocationControl(CMMAPlayer* aPlayer) + : CAMMSLocationControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiovirtualizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiovirtualizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,324 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Virtualizes audio channels. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsemcaudiovirtualizercontrol.h" + + +// CONSTANTS +const TInt KAMMSEMCDefaultStereoWideningLevel = 100; + +// ============================ MEMBER FUNCTIONS =============================== + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioVirtualizerControl* CAMMSEMCAudioVirtualizerControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCAudioVirtualizerControl* self = + new(ELeave) CAMMSEMCAudioVirtualizerControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSEMCAudioVirtualizerControl::~CAMMSEMCAudioVirtualizerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::~CAMMSEMCAudioVirtualizerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + if (iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility) + delete iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility; + delete iPresetNames; + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::SetPresetL(const TDesC& aPreset) +{ + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::SetPresetL \"%S\"", + aPreset.Ptr()); + CStereoWidening *iStereoWidening = NULL; + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->PrepareEmptyStereoWideningUtilitiesL(); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + TInt presetPosition = 0; + TInt findPreset = iPresetNames->Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + iStereoWidening = iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->GetStereoWideningAtPresetIndexL(presetPosition); + iCurrentPreset = presetPosition; + } + else + { + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->DeleteEmptyStereoWideningUtilities(); + User::Leave(KErrArgument); + } + + if (!iStereoWidening) + { + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->DeleteEmptyStereoWideningUtilities(); + return; + } + //Get all preset data here + TUint8 iStereoWideningLevel = iStereoWidening->StereoWideningLevel(); + // Set all preset data to EMC + iMStereoWideningControl->SetStereoWideningLevel(iStereoWideningLevel); + iMStereoWideningControl->Apply(); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->DeleteEmptyStereoWideningUtilities(); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::SetPresetL \"%S\" GetPresetL OK", + aPreset.Ptr()); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSEMCAudioVirtualizerControl::PresetNamesL() +{ + // Returns an array of all preset names (pre-defined and user-defined). + // The pre-defined presets are in the beginning of the list. + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->PrepareEmptyStereoWideningUtilitiesL(); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->DeleteEmptyStereoWideningUtilities(); + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSEMCAudioVirtualizerControl::PresetL() +{ + //if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + + else + { + // Retrieves a Preset with the given index from the utility class + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->PrepareEmptyStereoWideningUtilitiesL(); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->GetPresetAtIndexL(iPresetName , iCurrentPreset); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->DeleteEmptyStereoWideningUtilities(); + return iPresetName; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect. + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::SetEnabledL(true)."); + iMStereoWideningControl->Enable(); + iMStereoWideningControl->SetStereoWideningLevel(KAMMSEMCDefaultStereoWideningLevel); + iMStereoWideningControl->Apply(); + } + else + { + // Disable the effect + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::SetEnabledL(false)."); + iMStereoWideningControl->Disable(); + } + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMStereoWideningControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::PrepareControlL"); + //Create AudioVirtualizer Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KStereoWideningEffectControl, temp)); + iMStereoWideningControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMStereoWideningControl)); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::DeallocateControl() +{ + + if (iMStereoWideningControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl::DeallocateControl"); + + // StereoWidening for Audio can be disabled or enabled + TRAPD(err,iMStereoWideningControl->Disable()); + if (err != KErrNone) + { + //Some EMC Error + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCAudioVirtualizerControl::DeallocateControl err = %d",err); + } + //return the control to factory + MEffectControl* temp = iMStereoWideningControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMStereoWideningControl; + iFactory->DeleteEffectControl(tempCtrl); + iMStereoWideningControl = NULL; + } +} + +const TDesC& CAMMSEMCAudioVirtualizerControl::ClassName() const +{ + return KAMMSEMCAudioVirtualizerControl; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::SetEnforcedL +// Enforces the effect to be in use. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::SetEnforcedL(TBool aEnforced) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl:SetEnforcedL"); + // Indicate the effect is to be enforced or not. ETrue = Enforced. + + iMStereoWideningControl->Enforce(aEnforced); + + ApplySettingsL(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::Enforced +// Returns the current enforced setting of the effect. +// ----------------------------------------------------------------------------- +// +TBool CAMMSEMCAudioVirtualizerControl::Enforced() +{ + // Returns ETrue if the effect is enforced, EFalse if not enforced. + TBool enforced; + iMStereoWideningControl->IsEnforced(enforced); + return enforced; + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::SetScopeL +// Sets the scope of the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCAudioVirtualizerControl::SetScopeL(TInt aScope) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl:SetScopeL"); + __ASSERT_DEBUG( + (aScope == CAMMSEffectControlGroup::EScopeLiveOnly), + User::Invariant()); + // Just to suppress warning in release build + (void)aScope; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::Scope +// Returns the scope in which the effect is present. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCAudioVirtualizerControl::Scope() +{ + // For now only the (LIVE_ONLY) scope is supported. + return CAMMSEffectControlGroup::EScopeLiveOnly; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::ApplySettingsL +// Apply changed settings if Effect is in enabled state. +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerControl::ApplySettingsL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl:ApplySettingsL called, checking state"); + TBool enabled; + iMStereoWideningControl->IsEnabled(enabled); + if (enabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerControl:ApplySettingsL calling ApplyL"); + iMStereoWideningControl->Apply(); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility = + new(ELeave)CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility; + iAMMSEMCAudioVirtualizerEnvironmentalPresetUtility->ConstructL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::CAMMSEMCAudioVirtualizerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCAudioVirtualizerControl::CAMMSEMCAudioVirtualizerControl( + CMMAPlayer* aPlayer) + : CAMMSEffectControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiovirtualizerenvironmentalpresetutility.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcaudiovirtualizerenvironmentalpresetutility.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,161 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcaudiovirtualizerenvironmentalpresetutility.h" + +const TInt KAMMSEMCPresetGranularity = 5; + + + +// ============================ MEMBER FUNCTIONS =============================== +// Constructors + +CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility:: constructor"); +} + +// Destructor +CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::~CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility() +{ + delete iPresetNames; + if (iEmptyStereoWideningUtility) + { + delete iEmptyStereoWideningUtility; + iEmptyStereoWideningUtility = NULL; + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::~ "); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetAtIndexL +// Gets the current preset. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetAtIndexL(TDes& aPreset ,TInt iIndex) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetAtIndexL +"); + // Return KNullDesC if no preset is set. + if (iIndex >= 0) + { + + TArray< TEfStereoWideningUtilityPreset > presetNames = + iEmptyStereoWideningUtility->Presets(); + aPreset = presetNames[ iIndex ].iPresetName ; + + } + else + { + aPreset = KNullDesC; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetAtIndexL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::PrepareEmptyStereoWideningUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::PrepareEmptyStereoWideningUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::PrepareEmptyStereoWideningUtilitiesL +"); + //Calling base class function to create and initialize the CMMFDevSound + CreateAndInitializeDevSoundL(); + if (!iEmptyStereoWideningUtility) + { + iEmptyStereoWideningUtility = + CStereoWideningUtility::NewL(*iMMFDevSound); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::PrepareEmptyStereoWideningUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::DeleteEmptyStereoWideningUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::DeleteEmptyStereoWideningUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::DeleteEmptyStereoWideningUtilities +"); + + if (iEmptyStereoWideningUtility) + { + delete iEmptyStereoWideningUtility; + iEmptyStereoWideningUtility = NULL; + } + //Calling base class function to delete CMMFDevSound object to free memory + DeleteDevSound(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::DeleteEmptyStereoWideningUtilities -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetNamesL +"); + TArray< TEfStereoWideningUtilityPreset > presetNames = + iEmptyStereoWideningUtility->Presets(); + TInt presetCount = presetNames.Count(); + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetPresetNamesL -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetEnvironmentalStereoWideningAtPresetIndexL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CStereoWidening * CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetStereoWideningAtPresetIndexL(TInt iIndex) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::GetStereoWideningAtPresetIndexL, index=%d", + iIndex); + + __ASSERT_DEBUG(iIndex >= 0, User::Invariant()); + + // Set the preset to the empty Environmental Reverb utility. + iEmptyStereoWideningUtility->GetPresetL(iIndex); + return &(iEmptyStereoWideningUtility->StereoWidening()); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::ConstructL +// Symbian 2nd phase constructor can leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::ConstructL() +{ + iPresetNames = new(ELeave)CDesCArrayFlat(KAMMSEMCPresetGranularity); + CAMMSEMCBaseMMFDevSound ::ConstructL(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCAudioVirtualizerEnvironmentalPresetUtility::ConstructL"); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcbasemmfdevsound.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcbasemmfdevsound.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,125 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcbasemmfdevsound.h" + + +// ============================ MEMBER FUNCTIONS =============================== +// Constructors + +CAMMSEMCBaseMMFDevSound::CAMMSEMCBaseMMFDevSound() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound:: CAMMSEMCBaseMMFDevSound()"); +} + +// Destructor +CAMMSEMCBaseMMFDevSound::~CAMMSEMCBaseMMFDevSound() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::~ +"); + if (iMMFDevSound) + { + delete iMMFDevSound; + iMMFDevSound = NULL; + } + + if (iActiveSchedulerWait) + { + delete iActiveSchedulerWait; + iActiveSchedulerWait = NULL; + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::~ -"); +} + +/****************************************************************************** +* Method Name: CAMMSEMCBaseMMFDevSound::CreateAndInitializeDevSoundL() +******************************************************************************/ +TInt CAMMSEMCBaseMMFDevSound::CreateAndInitializeDevSoundL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::CreateAndInitializeDevSoundL"); + TInt initError; + if (iMMFDevSound) + { + delete iMMFDevSound; + iMMFDevSound = NULL; + } + TRAP(initError, iMMFDevSound = CMMFDevSound::NewL()); + if (initError) + return initError; + + TRAP(initError,iMMFDevSound->InitializeL(*this, EMMFStatePlaying)); + + if (!initError) + { + __ASSERT_DEBUG(!iActiveSchedulerWait->IsStarted(), User::Invariant()); + // Wait until InitializeComplete() has been called. + iActiveSchedulerWait->Start(); // CSI: 10 iActiveSchedulerWait cannot be started, also checked in debug build # + + } + + return initError; +} + +/****************************************************************************** +* Method Name: CAMMSEMCBaseMMFDevSound::DeleteDevSound() +******************************************************************************/ +void CAMMSEMCBaseMMFDevSound::DeleteDevSound() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::DeleteDevSound + "); + if (iMMFDevSound) + { + delete iMMFDevSound; + iMMFDevSound = NULL; + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::DeleteDevSound - "); +} + +/****************************************************************************** +******************************** CALLBACK ************************************ +*******************************************************************************/ + +/****************************************************************************** +* Method Name: CAMMSEMCBaseMMFDevSound::InitializeComplete +* Description: CMMFDevSound callback when Initialization is complete +******************************************************************************/ +void CAMMSEMCBaseMMFDevSound::InitializeComplete(TInt aError) +{ + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCBaseMMFDevSound::InitializeComplete err = %d ",aError); + // Just to suppress warning in release build + (void)aError; + __ASSERT_DEBUG(iActiveSchedulerWait->IsStarted(), User::Invariant()); + // Stop waiting in CreateAndInitializeDevSoundL() function. + iActiveSchedulerWait->AsyncStop(); + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCBaseMMFDevSound::ConstructL +// Symbian 2nd phase constructor can leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCBaseMMFDevSound::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCBaseMMFDevSound::ConstructL "); + // create CActiveSchedulerWait + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcdistanceattenuationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcdistanceattenuationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,168 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsemcdistanceattenuationcontrol.h" + +// CONSTANTS +namespace +{ +const TInt KAMMSRoomRollOffFactor = 0; // The logical default value set to 0 +// Rolloff factor 1000 in AMMS is 100 in EMC API +const TInt KAMMSRolloffDivider = 10; + +#ifdef _DEBUG +const TInt KAMMSMinDistance = 1; +const TInt KAMMSMinRollofFactor = 0; +#endif // _DEBUG +} + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCDistanceAttenuationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCDistanceAttenuationControl* CAMMSEMCDistanceAttenuationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCDistanceAttenuationControl* self = + new(ELeave)CAMMSEMCDistanceAttenuationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCDistanceAttenuationControl::~CAMMSEMCDistanceAttenuationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCDistanceAttenuationControl::~CAMMSEMCDistanceAttenuationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDistanceAttenuationControl::SetParametersL +// Sets all the 3D audio distance attenuation parameters simultaneously. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCDistanceAttenuationControl::SetParametersL( + TInt aMinDistance, + TInt aMaxDistance, + TBool aMuteAfterMax, + TInt aRolloffFactor) +{ + // Check in debug build that parameters are within valid range. + __ASSERT_DEBUG( + (aMaxDistance > aMinDistance) && + (aMinDistance >= KAMMSMinDistance) && + (aMaxDistance >= KAMMSMinDistance) && + (aRolloffFactor >= KAMMSMinRollofFactor), + User::Invariant()); + + // NOTE: Effect API uses hundreths (100 corresponds to 1.00), + // but JSR234 uses thousandths (1000 represents a rolloff factor of 1.0) + // + LOG4( EJavaMMAPI, EInfo, "AMMS::CAMMSEMCDistanceAttenuationControl::SetParametersL %d, %d, %d, %d", + aMinDistance, aMaxDistance, aMuteAfterMax, aRolloffFactor); + + TInt convertedRolloffFactor = aRolloffFactor / KAMMSRolloffDivider; + + iMDistanceAttenuationControl->SetDistanceAttenuation(aMinDistance, aMaxDistance, + aMuteAfterMax, convertedRolloffFactor, KAMMSRoomRollOffFactor); + + // Apply updated settings to EMC API. + iMDistanceAttenuationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDistanceAttenuationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCDistanceAttenuationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMDistanceAttenuationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCDistanceAttenuationControl::PrepareControlL"); + //Create Orientation Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KDistanceAttenuationEffectControl, temp)); + iMDistanceAttenuationControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMDistanceAttenuationControl)); + iMDistanceAttenuationControl->Enable(); + + } + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDistanceAttenuationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCDistanceAttenuationControl::DeallocateControl() +{ + if (iMDistanceAttenuationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCDistanceAttenuationControl::DeallocateControl"); + + // Location for Audio can be disabled or enabled + TRAPD(err,iMDistanceAttenuationControl->Disable()); + if (err != KErrNone) + { + //Some EMC Error + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCDistanceAttenuationControl::DeallocateControl err = %d",err); + } + //return the control to factory + MEffectControl* temp = iMDistanceAttenuationControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMDistanceAttenuationControl; + iFactory->DeleteEffectControl(tempCtrl); + iMDistanceAttenuationControl = NULL; + } +} + +const TDesC& CAMMSEMCDistanceAttenuationControl::ClassName() const +{ + return KAMMSEMCDistanceAttenuationControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCDistanceAttenuationControl::CAMMSEMCDistanceAttenuationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCDistanceAttenuationControl::CAMMSEMCDistanceAttenuationControl( + CMMAPlayer* aPlayer) + : CAMMSBaseDistanceAttenuationControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcequalizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcequalizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,456 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcequalizercontrol.h" + + + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCEqualizerControl* CAMMSEMCEqualizerControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSEMCEqualizerControl* self = + new(ELeave) CAMMSEMCEqualizerControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSEMCEqualizerControl::~CAMMSEMCEqualizerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::~CAMMSEMCEqualizerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + if (iAMMSEMCEqualizerEnvironmentalPresetUtility) + delete iAMMSEMCEqualizerEnvironmentalPresetUtility; + delete iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::BandLevelL +// Gets the gain set for the given equalizer band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::BandLevelL(TInt aBand) +{ + // if aBand is out of range the method must leave with KErrArgument. + + if (aBand < 0 || aBand > (NumberOfBands() - 1)) + { + User::Leave(KErrArgument); + } + // Returns the band level in mB for the specified band + TInt bandlevel; + TInt aNativeBand = aBand + KAMMSBandOffset; + iMEqualizerControl->BandLevel(aNativeBand,bandlevel); + return bandlevel; + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::MaxBandLevel +// Returns the maximum band level supported. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::MaxBandLevel() +{ + // Get the dB range in mB for the equalizer. + TInt min,max; + iMEqualizerControl->DbLevelLimits(min,max); + return max; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::MinBandLevel +// Returns the minimum band level supported. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::MinBandLevel() +{ + // Get the dB range in mB for the equalizer. + TInt min,max; + iMEqualizerControl->DbLevelLimits(min,max); + return min; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::BandWidth +// Returns the band width in Hz for the specified band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::BandWidth(TInt aBand) +{ + TInt bndwdth; + TInt aNativeBand = aBand + KAMMSBandOffset; + iMEqualizerControl->BandWidth(aNativeBand,bndwdth); + return bndwdth; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::CenterFrequency +// Returns the center frequency in Hz for a given band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::CenterFrequency(TInt aBand) +{ + TInt cntrfreq; + TInt aNativeBand = aBand + KAMMSBandOffset; + iMEqualizerControl->CenterFrequency(aNativeBand,cntrfreq); + return cntrfreq; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::CrossoverFrequency +// Returns the cross-over frequency between the given frequency. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::CrossoverFrequency(TInt aBand) +{ + TInt aCrossOverFreq; + TInt aNativeBand = aBand + KAMMSBandOffset; + iMEqualizerControl->CrossoverFrequency(aNativeBand, aCrossOverFreq); + return aCrossOverFreq; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::NumberOfBands +// Gets the number of frequency bands that the equalizer supports. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::NumberOfBands() +{ + // Returns the number of equalizer bands. + // AudioEqualizerBase: TUint8 NumberOfBands() const; + + TInt aNumOfBands; + iMEqualizerControl->NumberOfBands(aNumOfBands); + return aNumOfBands; + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::SetBandLevelL +// Sets the given equalizer band to the given gain value. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::SetBandLevelL( + TInt aLevel, + TInt aBand) +{ + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::SetBandLevelL: level=%d, band=%d", + aLevel, aBand); + // If aBand or aLevel is out of valid range the method must leave + // with KErrArgument. + if (aBand < 0 || + aBand > (NumberOfBands() - 1) || + aLevel < MinBandLevel() || + aLevel > MaxBandLevel()) + { + User::Leave(KErrArgument); + } + TInt aNativeBand = aBand + KAMMSBandOffset; + // Sets the equalizer band level value in mB, ranging from Min to Max + iMEqualizerControl->SetBandLevel(aNativeBand, aLevel); + + ApplySettingsL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::SetPresetL(const TDesC& aPreset) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::SetPresetL \"%S\"", aPreset.Ptr()); + CAudioEqualizer *iAudioEqualizer = NULL; + iAMMSEMCEqualizerEnvironmentalPresetUtility->PrepareEmptyEqualizerUtilitiesL(); + iAMMSEMCEqualizerEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + TInt presetPosition = 0; + TInt findPreset = iPresetNames->Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + iAudioEqualizer = iAMMSEMCEqualizerEnvironmentalPresetUtility->GetEqualizerAtPresetIndexL(presetPosition); + iCurrentPreset = presetPosition; + } + else + { + iAMMSEMCEqualizerEnvironmentalPresetUtility->DeleteEmptyEqualizerUtilities(); + User::Leave(KErrArgument); + } + + if (!iAudioEqualizer) + { + iAMMSEMCEqualizerEnvironmentalPresetUtility->DeleteEmptyEqualizerUtilities(); + return; + } + //Get all preset data here + // For each band of AudioEqualizer get the band level and set it to iMEqualizerControl + + TInt noOfbands = iAudioEqualizer->NumberOfBands(); + + for (TInt i = 0; i < noOfbands; i++) + { + // Band 0 in JSR-234 equals Band 1 in Effect API + TInt aNativeBand = i + KAMMSBandOffset; + TInt iBandLevel = iAudioEqualizer->BandLevel(aNativeBand); + iMEqualizerControl->SetBandLevel(aNativeBand, iBandLevel); + } + + iMEqualizerControl->Apply(); + iAMMSEMCEqualizerEnvironmentalPresetUtility->DeleteEmptyEqualizerUtilities(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSEMCEqualizerControl::PresetNamesL() +{ + // Returns an array of all preset names (pre-defined and user-defined). + // The pre-defined presets are in the beginning of the list. + iAMMSEMCEqualizerEnvironmentalPresetUtility->PrepareEmptyEqualizerUtilitiesL(); + iAMMSEMCEqualizerEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + iAMMSEMCEqualizerEnvironmentalPresetUtility->DeleteEmptyEqualizerUtilities(); + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSEMCEqualizerControl::PresetL() +{//if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + + else + { + // Retrieves a Preset with the given index from the utility class + iAMMSEMCEqualizerEnvironmentalPresetUtility->PrepareEmptyEqualizerUtilitiesL(); // codescanner::leave + iAMMSEMCEqualizerEnvironmentalPresetUtility->GetPresetAtIndexL(iPresetName , iCurrentPreset); // codescanner::leave + iAMMSEMCEqualizerEnvironmentalPresetUtility->DeleteEmptyEqualizerUtilities(); + return iPresetName; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect. + + iMEqualizerControl->Enable(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::SetEnabledL(true), calling Apply"); + iMEqualizerControl->Apply(); + } + else + { + // Disable the effect + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::SetEnabledL(false), calling Disable"); + iMEqualizerControl->Disable(); + iMEqualizerControl->Apply(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMEqualizerControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::PrepareControlL"); + //Create Equalizer Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KEqualizerEffectControl, temp)); + iMEqualizerControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMEqualizerControl)); + iMEqualizerControl->Enable(); + } + + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::DeallocateControl() +{ + if (iMEqualizerControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl::DeallocateControl"); + + // Equalizer for Audio can be disabled or enabled + TRAPD(err,iMEqualizerControl->Disable()); + if (err != KErrNone) + { + //Some EMC Error + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCEqualizerControl::DeallocateControl err = %d",err); + } + //return the control to factory + MEffectControl* temp = iMEqualizerControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMEqualizerControl; + iFactory->DeleteEffectControl(tempCtrl); + iMEqualizerControl = NULL; + } +} + + +const TDesC& CAMMSEMCEqualizerControl::ClassName() const +{ + return KAMMSEMCEqualizerControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::SetEnforcedL +// Enforces the effect to be in use. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::SetEnforcedL(TBool aEnforced) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl:SetEnforcedL"); + // Indicate the effect is to be enforced or not. ETrue = Enforced. + + iMEqualizerControl->Enforce(aEnforced); + + ApplySettingsL(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::Enforced +// Returns the current enforced setting of the effect. +// ----------------------------------------------------------------------------- +// +TBool CAMMSEMCEqualizerControl::Enforced() +{ + // Returns ETrue if the effect is enforced, EFalse if not enforced. + TBool enforced; + iMEqualizerControl->IsEnforced(enforced); + return enforced; + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::SetScopeL +// Sets the scope of the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCEqualizerControl::SetScopeL(TInt aScope) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl:SetScopeL"); + __ASSERT_DEBUG( + (aScope == CAMMSEffectControlGroup::EScopeLiveOnly), + User::Invariant()); + // Just to suppress warning in release build + (void)aScope; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::Scope +// Returns the scope in which the effect is present. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCEqualizerControl::Scope() +{ + // For now only the (LIVE_ONLY) scope is supported. + return CAMMSEffectControlGroup::EScopeLiveOnly; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCAudioVirtualizerControl::ApplySettingsL +// Apply changed settings if Effect is in enabled state. +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerControl::ApplySettingsL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl:ApplySettingsL called, checking state"); + TBool enabled; + iMEqualizerControl->IsEnabled(enabled); + if (enabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerControl:ApplySettingsL calling ApplyL"); + iMEqualizerControl->Apply(); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); + iAMMSEMCEqualizerEnvironmentalPresetUtility = new(ELeave)CAMMSEMCEqualizerEnvironmentalPresetUtility; + iAMMSEMCEqualizerEnvironmentalPresetUtility->ConstructL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerControl::CAMMSEMCEqualizerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCEqualizerControl::CAMMSEMCEqualizerControl(CMMAPlayer* aPlayer) + : CAMMSBaseEqualizerControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcequalizerenvironmentalpresetutility.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcequalizerenvironmentalpresetutility.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,180 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcequalizerenvironmentalpresetutility.h" + +const TInt KAMMSEMCPresetGranularity = 5; + + + +// ============================ MEMBER FUNCTIONS =============================== +// Constructors + +CAMMSEMCEqualizerEnvironmentalPresetUtility::CAMMSEMCEqualizerEnvironmentalPresetUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility:: CAMMSEMCEqualizerEnvironmentalPresetUtility()"); +} + +// Destructor +CAMMSEMCEqualizerEnvironmentalPresetUtility::~CAMMSEMCEqualizerEnvironmentalPresetUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::~ +"); + delete iPresetNames; + if (iEmptyEqualizerUtility) + { + TRAPD(err,iEmptyEqualizerUtility ->DisableEqualizerL()); + if (err) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Utility + // class is already created, that situation can be discarded here. + } + delete iEmptyEqualizerUtility; + iEmptyEqualizerUtility = NULL; + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::~ -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetAtIndexL +// Gets the current preset. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetAtIndexL(TDes& aPreset ,TInt iIndex) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetAtIndexL +"); + // Return KNullDesC if no preset is set. + if (iIndex >= 0) + { + + TArray< TEfAudioEqualizerUtilityPreset > presetNames = + iEmptyEqualizerUtility->Presets(); + aPreset = presetNames[ iIndex ].iPresetName ; + + } + else + { + aPreset = KNullDesC; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetAtIndexL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::PrepareEmptyEqualizerUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerEnvironmentalPresetUtility::PrepareEmptyEqualizerUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::PrepareEmptyEqualizerUtilitiesL +"); + //Calling base class function to create and initialize the CMMFDevSound + CreateAndInitializeDevSoundL(); + if (!iEmptyEqualizerUtility) + { + iEmptyEqualizerUtility = + CAudioEqualizerUtility::NewL(*iMMFDevSound); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::PrepareEmptyEqualizerUtilitiesL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::DeleteEmptyEqualizerUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerEnvironmentalPresetUtility::DeleteEmptyEqualizerUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::DeleteEmptyEqualizerUtilities +"); + + if (iEmptyEqualizerUtility) + { + TRAPD(err,iEmptyEqualizerUtility ->DisableEqualizerL()); + if (err) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Utility + // class is already created, that situation can be discarded here. + } + delete iEmptyEqualizerUtility; + iEmptyEqualizerUtility = NULL; + } + + //Calling base class function to delete CMMFDevSound object to free memory + DeleteDevSound(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::DeleteEmptyEqualizerUtilities -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetNamesL +"); + TArray< TEfAudioEqualizerUtilityPreset > presetNames = + iEmptyEqualizerUtility->Presets(); + TInt presetCount = presetNames.Count(); + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::GetPresetNamesL -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::GetEqualizerAtPresetIndexL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAudioEqualizer * CAMMSEMCEqualizerEnvironmentalPresetUtility::GetEqualizerAtPresetIndexL(TInt iIndex) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::GetEqualizerAtPresetIndexL, index=%d", + iIndex); + + __ASSERT_DEBUG(iIndex >= 0, User::Invariant()); + + // Set the preset to the empty Environmental Equalizer utility. + iEmptyEqualizerUtility->GetPresetL(iIndex); + return &(iEmptyEqualizerUtility->Equalizer()); + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCEqualizerEnvironmentalPresetUtility::ConstructL +// Symbian 2nd phase constructor can leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCEqualizerEnvironmentalPresetUtility::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCEqualizerEnvironmentalPresetUtility::ConstructL"); + iPresetNames = new(ELeave)CDesCArrayFlat(KAMMSEMCPresetGranularity); + CAMMSEMCBaseMMFDevSound ::ConstructL(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,464 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + +// INCLUDE FILES +#include "cammsemcreverbcontrol.h" +#include +#include +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxReverbLevel = 0; +const TInt KAMMSMinReverbTime = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCReverbControl* CAMMSEMCReverbControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSEMCReverbControl* self = new(ELeave) CAMMSEMCReverbControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSEMCReverbControl::~CAMMSEMCReverbControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::~CAMMSEMCReverbControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + if (iAMMSEMCReverbEnvironmentalPresetUtility) + delete iAMMSEMCReverbEnvironmentalPresetUtility; + delete iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::SetReverbLevelL +// Sets the gain level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCReverbControl::SetReverbLevelL(TInt aLevel) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetReverbLevelL: %d", aLevel); + __ASSERT_DEBUG(aLevel <= KAMMSMaxReverbLevel, User::Invariant()); + TInt roomLevel = 0; + iMReverbControl->RoomLevel(roomLevel); + TInt reflectionLevel =0; + iMReverbControl->ReflectionsLevel(reflectionLevel); + TInt tempChange = aLevel - reflectionLevel - roomLevel; + + // Sets the reverb reflections level in mB + iMReverbControl->SetReflectionsLevel(aLevel - roomLevel); + + // Calculate native reverb level. + TInt reverbLevel; + // iMReverbControl->ReverbLevel(reverbLevel); + reverbLevel = iEnvReverbLevel + tempChange; + + // Ensure that the level is within the limits. + + TInt minLevel = 0; + TInt maxLevel = 0; + iMReverbControl->ReverbLevelRange(minLevel, maxLevel); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetReverbLevelL: orig %d", + reverbLevel); + + reverbLevel = Min(reverbLevel, maxLevel); + reverbLevel = Max(reverbLevel, minLevel); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetReverbLevelL: set %d", + reverbLevel); + // Sets the reverb level in mB + iMReverbControl->SetReverbLevel(reverbLevel); + // Apply can be called for Reverb, as it does not internally include EnableL + // unlike in case of Equalizer or StereoWidening + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetReverbLevelL calling ApplyL"); + iMReverbControl->Apply(); + + // Return the value that was used in setting the reverb + return aLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::SetReverbTimeL +// Sets the reverberation time of the reverb. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbControl::SetReverbTimeL(TInt aTime) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetReverbTimeL: %d", aTime); + // Check in debug build that aTime is within valid range. + __ASSERT_DEBUG(aTime >= KAMMSMinReverbTime, User::Invariant()); + iMReverbControl->SetDecayTime(aTime); + iMReverbControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::ReverbLevel +// Gets the gain level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCReverbControl::ReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::ReverbLevel called"); + TInt iReverbLevel; + iMReverbControl->ReverbLevel(iReverbLevel); + return iReverbLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::ReverbTime +// Gets the reverberation time. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCReverbControl::ReverbTime() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::ReverbTime called"); + + TUint iReverbTime; + iMReverbControl->DecayTime(iReverbTime); + return iReverbTime; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::MinReverbLevel +// Gets the minimum level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCReverbControl::MinReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::MinReverbLevel called"); + + TInt minLevel; + TInt maxLevel; + iMReverbControl->ReverbLevelRange( + minLevel, maxLevel); + + return minLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::MaxReverbLevel +// Gets the maximum level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEMCReverbControl::MaxReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::MaxReverbLevel called"); + TInt minLevel; + TInt maxLevel; + iMReverbControl->ReverbLevelRange(minLevel, maxLevel); + return maxLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbControl::SetPresetL(const TDesC& aPreset) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetPresetL \"%S\"", aPreset.Ptr()); + CEnvironmentalReverb *iEnvironmentalReverb = NULL; + User::LeaveIfError(iAMMSEMCReverbEnvironmentalPresetUtility->PrepareEmptyReverbUtilitiesL()); + iAMMSEMCReverbEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + TInt presetPosition = 0; + TInt findPreset = iPresetNames->Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + iEnvironmentalReverb = iAMMSEMCReverbEnvironmentalPresetUtility->GetEnvironmentalReverbAtPresetIndexL(presetPosition); + iCurrentPreset = presetPosition; + } + else + { + iAMMSEMCReverbEnvironmentalPresetUtility->DeleteEmptyReverbUtilities(); + User::Leave(KErrArgument); + } + + if (!iEnvironmentalReverb) + { + iAMMSEMCReverbEnvironmentalPresetUtility->DeleteEmptyReverbUtilities(); + return; + } + //Get all preset data here + + TInt iReverbTime = iEnvironmentalReverb-> DecayTime(); + TInt iReverbLevel = iEnvironmentalReverb->ReflectionsLevel() + iEnvironmentalReverb->RoomLevel(); + iEnvReverbLevel = iEnvironmentalReverb->ReverbLevel(); + TInt roomLevel = iEnvironmentalReverb->RoomLevel(); + TInt reflectionLevel = iEnvironmentalReverb->ReflectionsLevel(); + TUint decayHFRatio = iEnvironmentalReverb->DecayHFRatio(); + TUint density = iEnvironmentalReverb->Density(); + TUint diffusion = iEnvironmentalReverb->Diffusion(); + TUint reflectionsDelay = iEnvironmentalReverb->ReflectionsDelay(); + TUint reverbDelay = iEnvironmentalReverb->ReverbDelay(); + TUint roomHFLevel = iEnvironmentalReverb->RoomHFLevel(); + + // Set all preset data to EMC + TInt err = iMReverbControl->SetDecayTime(iReverbTime); + err = iMReverbControl->SetReverbLevel(iReverbLevel); + err = iMReverbControl->SetRoomLevel(roomLevel); + err = iMReverbControl->SetReflectionsLevel(reflectionLevel); + err = iMReverbControl->SetDecayHFRatio(decayHFRatio); + err = iMReverbControl->SetDensity(density); + err = iMReverbControl->SetDiffusion(diffusion); + err = iMReverbControl->SetReflectionsDelay(reflectionsDelay); + err = iMReverbControl->SetReverbDelay(reverbDelay); + err = iMReverbControl->SetRoomHFLevel(roomHFLevel); + err = iMReverbControl->Apply(); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCReverbControl::SetPresetL iMReverbControl setter func. err = %d",err); + iAMMSEMCReverbEnvironmentalPresetUtility->DeleteEmptyReverbUtilities(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSEMCReverbControl::PresetNamesL() +{ + + //CEnvironmentalReverb *iEnvironmentalReverb = NULL; + iAMMSEMCReverbEnvironmentalPresetUtility->PrepareEmptyReverbUtilitiesL(); + iAMMSEMCReverbEnvironmentalPresetUtility->GetPresetNamesL(*iPresetNames); + iAMMSEMCReverbEnvironmentalPresetUtility->DeleteEmptyReverbUtilities(); + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSEMCReverbControl::PresetL() +{ + //if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + + else + { + // Retrieves a Preset with the given index from the utility class + iAMMSEMCReverbEnvironmentalPresetUtility->PrepareEmptyReverbUtilitiesL(); + iAMMSEMCReverbEnvironmentalPresetUtility->GetPresetAtIndexL(iPresetName , iCurrentPreset); + iAMMSEMCReverbEnvironmentalPresetUtility->DeleteEmptyReverbUtilities(); + return iPresetName; + } + + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetEnabledL(true), calling Enable"); + iMReverbControl->Enable(); + iMReverbControl->Apply(); + } + else + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetEnabledL(false), calling Disable"); + iMReverbControl->Disable(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMReverbControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::PrepareControlL"); + //Create Reverb Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KReverbEffectControl, temp)); + iMReverbControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMReverbControl)); + iMReverbControl->Enable(); + SetPresetL(KAMMSEMCDefaultReverbPreset); + + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbControl::DeallocateControl() +{ + + if (iMReverbControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::DeallocateControl"); + + // Reverb for Audio can be disabled or enabled + TRAPD(err,iMReverbControl->Disable()); + if (err != KErrNone) + { + //Some EMC Error + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCReverbControl::DeallocateControl err = %d",err); + } + //return the control to factory + MEffectControl* temp = iMReverbControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMReverbControl; + iFactory->DeleteEffectControl(tempCtrl); + iMReverbControl = NULL; + + iCurrentPreset = -1; + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::GetReverbControl +// Returns the reverb control. It will be used by CAMMSEMCReverbSourceControl +// ----------------------------------------------------------------------------- +MReverbControl * CAMMSEMCReverbControl::GetReverbControlL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::GetReverbControl"); + + if (! iMReverbControl) + { + PrepareControlL(); // creates the control + } + + return iMReverbControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::CurrentPresetIndex +// Returns the Current Preset Index. It will be used by CAMMSEMCReverbSourceControl +// ----------------------------------------------------------------------------- +TInt CAMMSEMCReverbControl::CurrentPresetIndex() +{ + return iCurrentPreset; +} + +// ----------------------------------------------------------------------------- +// Overriding the base class CAMMSEffectControl function here +//------------------------------------------------------------------------------ + +void CAMMSEMCReverbControl::SetEnforcedL(TBool aEnforced) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetEnforcedL"); + // Indicate the effect is to be enforced or not. ETrue = Enforced. + iMReverbControl->Enforce(aEnforced); + + ApplySettingsL(); + +} +TBool CAMMSEMCReverbControl::Enforced() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::Enforced"); + // Returns ETrue if the effect is enforced, EFalse if not enforced. + TBool enforced; + iMReverbControl->IsEnforced(enforced); + return enforced; + +} +void CAMMSEMCReverbControl::SetScopeL(TInt aScope) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::SetScopeL"); + __ASSERT_DEBUG( + (aScope == CAMMSEffectControlGroup::EScopeLiveOnly), + User::Invariant()); + // Just to suppress warning in release build + (void)aScope; +} +TInt CAMMSEMCReverbControl::Scope() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::Scope"); + // For now only the (LIVE_ONLY) scope is supported. + return CAMMSEffectControlGroup::EScopeLiveOnly; + +} +void CAMMSEMCReverbControl::ApplySettingsL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl::ApplySettingsL"); + TBool enabled; + iMReverbControl->IsEnabled(enabled); + if (enabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbControl:ApplySettingsL calling ApplyL"); + iMReverbControl->Apply(); + } +} + +const TDesC& CAMMSEMCReverbControl::ClassName() const +{ + return KAMMSEMCReverbControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEMCReverbControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); + iAMMSEMCReverbEnvironmentalPresetUtility = new(ELeave) CAMMSEMCReverbEnvironmentalPresetUtility; + iAMMSEMCReverbEnvironmentalPresetUtility->ConstructL(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbControl::CAMMSEMCReverbControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCReverbControl::CAMMSEMCReverbControl(CMMAPlayer* aPlayer) + : CAMMSBaseReverbControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbenvironmentalpresetutility.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbenvironmentalpresetutility.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,177 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Group for effect controls +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcreverbenvironmentalpresetutility.h" + +const TInt KAMMSEMCPresetGranularity = 5; + + + +// ============================ MEMBER FUNCTIONS =============================== +// Constructors + +CAMMSEMCReverbEnvironmentalPresetUtility::CAMMSEMCReverbEnvironmentalPresetUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility:: CAMMSEMCReverbEnvironmentalPresetUtility()"); +} + +// Destructor +CAMMSEMCReverbEnvironmentalPresetUtility::~CAMMSEMCReverbEnvironmentalPresetUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::~ +"); + delete iPresetNames; + + if (iEmptyEnvironmentalReverbUtility) + { + delete iEmptyEnvironmentalReverbUtility; + iEmptyEnvironmentalReverbUtility = NULL; + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::~ -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetAtIndexL +// Gets the current preset. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetAtIndexL(TDes& aPreset ,TInt iIndex) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetAtIndexL +"); + // Return KNullDesC if no preset is set. + if (iIndex >= 0) + { + + TArray< TEfEnvironmentalReverbUtilityPreset > presetNames = + iEmptyEnvironmentalReverbUtility->Presets(); + aPreset = presetNames[ iIndex ].iPresetName ; + + } + else + { + aPreset = KNullDesC; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetAtIndexL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::PrepareEmptyReverbUtilitiesL +// Creates utilities that can be used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSEMCReverbEnvironmentalPresetUtility::PrepareEmptyReverbUtilitiesL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::PrepareEmptyReverbUtilitiesL +"); + //Calling base class function to create and initialize the CMMFDevSound + TInt err = CreateAndInitializeDevSoundL(); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::PrepareEmptyReverbUtilitiesL err = %d",err); + if (!iEmptyEnvironmentalReverbUtility && (err == KErrNone)) + { + iEmptyEnvironmentalReverbUtility = + CEnvironmentalReverbUtility::NewL(*iMMFDevSound); + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::PrepareEmptyReverbUtilitiesL -"); + return err; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::DeleteEmptyReverbUtilities +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCReverbEnvironmentalPresetUtility::DeleteEmptyReverbUtilities() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::DeleteEmptyReverbUtilities +"); + + if (iEmptyEnvironmentalReverbUtility) + { + delete iEmptyEnvironmentalReverbUtility; + iEmptyEnvironmentalReverbUtility = NULL; + } + //Calling base class function to delete CMMFDevSound object to free memory + DeleteDevSound(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::DeleteEmptyReverbUtilities -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::MMFDevSound +// Deletes utilities that are used to obtain preset names and preset data. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CMMFDevSound* CAMMSEMCReverbEnvironmentalPresetUtility::MMFDevSound() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::MMFDevSound "); + return iMMFDevSound; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetNamesL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetNamesL( + CDesCArray& aPresetNames) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetNamesL +"); + TArray< TEfEnvironmentalReverbUtilityPreset > presetNames = + iEmptyEnvironmentalReverbUtility->Presets(); + TInt presetCount = presetNames.Count(); + for (TInt i = 0; i < presetCount; i++) + { + aPresetNames.AppendL(presetNames[ i ].iPresetName); + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::GetPresetNamesL -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::GetEnvironmentalReverbAtPresetIndexL +// Gets list of preset names available. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CEnvironmentalReverb * CAMMSEMCReverbEnvironmentalPresetUtility::GetEnvironmentalReverbAtPresetIndexL(TInt iIndex) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::GetEnvironmentalReverbAtPresetIndexL, index=%d", + iIndex); + + __ASSERT_DEBUG(iIndex >= 0, User::Invariant()); + + // Set the preset to the empty Environmental Reverb utility. + iEmptyEnvironmentalReverbUtility->GetPresetL(iIndex); + return &(iEmptyEnvironmentalReverbUtility->EnvironmentalReverb()); + +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbEnvironmentalPresetUtility::ConstructL +// Symbian 2nd phase constructor can leave. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSEMCReverbEnvironmentalPresetUtility::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbEnvironmentalPresetUtility::ConstructL "); + iPresetNames = new(ELeave)CDesCArrayFlat(KAMMSEMCPresetGranularity); + CAMMSEMCBaseMMFDevSound ::ConstructL(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbsourcecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcreverbsourcecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,208 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect reverb source. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsemcreverbsourcecontrol.h" +#include "cammsbasereverbcontrol.h" +#include "cammsemcreverbcontrol.h" + +// CONSTANTS +const TInt KAMMSDisconnectReverbSource = 2147483647; // From JSR-234 + +#ifdef _DEBUG +const TInt KAMMSMaxRoomLevel = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbSourceControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCReverbSourceControl* CAMMSEMCReverbSourceControl::NewLC( + CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aBaseReverbControl) +{ + CAMMSEMCReverbSourceControl* self = + new(ELeave)CAMMSEMCReverbSourceControl(aPlayer, aBaseReverbControl); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCReverbSourceControl::~CAMMSEMCReverbSourceControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::~CAMMSEMCReverbSourceControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbSourceControl::SetRoomLevelL +// Sets the object specific level for the reverberant sound. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbSourceControl::SetRoomLevelL(TInt aLevel) +{ + LOG1( EJavaAMMS, EInfo, "AMMS:: CAMMSEMCReverbSourceControl::SetRoomLevelL +: %d", aLevel); +// Check in debug build that aLevel is within valid range. + __ASSERT_DEBUG( + (aLevel <= KAMMSMaxRoomLevel) || + (aLevel == KAMMSDisconnectReverbSource), + User::Invariant()); + + // With the JSR-234 value Integer.MIN_VALUE, the reflected sound for the + // given object can be disabled. + if (aLevel == KMinTInt) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL(Integer.MIN_VALUE)"); + aLevel = 0; + } + + // Check the allowed boundaries for room level. + TInt minLevel = 0; + TInt maxLevel = 0; + iRoomLevelControl->LevelRange(minLevel, maxLevel); + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL boundaries %d, %d", + minLevel, maxLevel); + + // Check the state of the effect. If it is in disabled state, enable it. + TBool enabled; + iRoomLevelControl->IsEnabled(enabled); + if (!enabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL calling EnableL"); + iRoomLevelControl->Enable(); + } + + // With the JSR-234 value DISCONNECT, the object can be disconnected + // from the reverb. + if (aLevel == KAMMSDisconnectReverbSource) + { + // Do not call iReverbSource->DisableL(), instead set the room level to + // _minimum_ value (= smallest negative gain -> maximum attenuation). + // The CRoomLevel must also be kept enabled. + aLevel = minLevel; + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL(DISCONNECT) %d", + minLevel); + } + else + { + // Set the room level within allowed boundaries from EMC API + aLevel = Min(aLevel, maxLevel); + aLevel = Max(aLevel, minLevel); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL setting value: %d", aLevel); + } + + // Sets the RoomLevel level, it will leave if aRoomLevel is not within range + // of Min and Max + iRoomLevelControl->SetRoomLevel(aLevel); + + // Apply updated settings to EMC API. + iRoomLevelControl->Apply(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::SetRoomLevelL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbSourceControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbSourceControl::PrepareControlL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::PrepareControlL"); + + if (!iRoomLevelControl) + { + //Create RoomLevel Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KRoomLevelEffectControl, temp)); + iRoomLevelControl = static_cast(temp); + + + //Attach EMC Reverb Control to RoomLevelControl + MReverbControl* reverbControl = iBaseReverbControl->GetReverbControlL(); + iRoomLevelControl->AttachReverb(*reverbControl); + + //Add Effect to Stream Control + User::LeaveIfError(iStreamControl->AddEffect(*iRoomLevelControl)); + } + + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbSourceControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCReverbSourceControl::DeallocateControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCReverbSourceControl::DeallocateControl"); + if (iRoomLevelControl) + { + /* + //idealy reverbControl should be checked for its existance and if it is there ,should be detached from RoomLevelControl. + //But in this case reverbControl is deleted till this position,so need not to do it. + if(reverbControl) + { + iRoomLevelControl->DetachReverb(*reverbControl); + } + */ + iStreamControl->RemoveEffect(*iRoomLevelControl); + MEffectControl* objPtr2 = iRoomLevelControl; + iFactory->DeleteEffectControl(objPtr2); + iRoomLevelControl = NULL; + } + + + + +} + +const TDesC& CAMMSEMCReverbSourceControl::ClassName() const +{ + return KAMMSEMCReverbSourceControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCReverbSourceControl::CAMMSEMCReverbSourceControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCReverbSourceControl::CAMMSEMCReverbSourceControl( + CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aBaseReverbControl) + : CAMMSBaseReverbSourceControl(aPlayer), iBaseReverbControl(aBaseReverbControl) +{ + + iMMAPlayer = aPlayer; + +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatordopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatordopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,212 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler effect of the spectator. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include "cammsemcspectatordopplercontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorDopplerControl* CAMMSEMCSpectatorDopplerControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCSpectatorDopplerControl* self = + new(ELeave)CAMMSEMCSpectatorDopplerControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCSpectatorDopplerControl::~CAMMSEMCSpectatorDopplerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::~CAMMSEMCSpectatorDopplerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorDopplerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMListenerDopplerControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::PrepareControlL"); + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KListenerDopplerEffectControl, temp)); + iMListenerDopplerControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMListenerDopplerControl)); + TInt err = iMListenerDopplerControl->Enable(); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::PrepareControlL: EnableErr = %d", err); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorDopplerControl::DeallocateControl() +{ + if (iMListenerDopplerControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::DeallocateControl"); + + // Doppler for Spectator is always enabled (JSR-234 mandates it) + // so the disabling is needed here + iMListenerDopplerControl->Disable(); + //return the control to factory + MEffectControl* temp = iMListenerDopplerControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMListenerDopplerControl; + iFactory->DeleteEffectControl(tempCtrl); + iMListenerDopplerControl = NULL; + } +} + +const TDesC& CAMMSEMCSpectatorDopplerControl::ClassName() const +{ + return KAMMSEMCListenerDopplerControl; +} + + +void CAMMSEMCSpectatorDopplerControl::SetEnabledL(TBool aDopplerEnabled) +{ + if (aDopplerEnabled) + { + TInt err = iMListenerDopplerControl->Enable(); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::SetEnabledL: Enable err = %d", err); + } + else + { + TInt err = iMListenerDopplerControl->Disable(); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::SetEnabledL: Disable err = %d", err); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::Enabled +// Returns whether this Doppler effect is currently active. +// ----------------------------------------------------------------------------- +// +TBool CAMMSEMCSpectatorDopplerControl::Enabled() +{ + TBool temp; + TInt err = iMListenerDopplerControl->IsEnabled(temp); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::Enabled: err = %d", err); + return temp; +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::SetVelocityCartesianL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorDopplerControl::SetVelocityCartesianL( + TInt aX, + TInt aY, + TInt aZ) +{ + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::SetVelocityCartesianL: X=%d, Y=%d, Z=%d", + aX, aY, aZ); + TInt err = iMListenerDopplerControl->SetCartesianVelocity(aX, aY, aZ); + + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::SetVelocityCartesianL: err = %d", err); + // Apply updated settings + iMListenerDopplerControl->Apply(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::VelocityCartesian +// Returns the current velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorDopplerControl::VelocityCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Get the velocity's cartesian settings + // aX, aY and aZ are velocities in format mm/s + + TInt err = iMListenerDopplerControl->CartesianVelocity(aX,aY,aZ); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::VelocityCartesian: err = %d", err); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::SetVelocitySphericalL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorDopplerControl::SetVelocitySphericalL( + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + // Parameters are thousandths of radians + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::SetVelocitySphericalL %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedElevation = (TInt32)(aElevation * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorDopplerControl::SetVelocitySphericalL %d, %d", + convertedAzimuth, convertedElevation); + + TInt err = iMListenerDopplerControl->SetSphericalVelocity( + convertedAzimuth, convertedElevation, aRadius); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorDopplerControl::SetVelocitySphericalL: err = %d", err); + // Apply updated settings to EMC API. + iMListenerDopplerControl->Apply(); +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorDopplerControl::CAMMSEMCSpectatorDopplerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorDopplerControl::CAMMSEMCSpectatorDopplerControl( + CMMAPlayer* aPlayer) + : CAMMSDopplerControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatorlocationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatorlocationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,184 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cammsemcspectatorlocationcontrol.h" + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMinRadius = 0; +#endif // _DEBUG + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorLocationControl* CAMMSEMCSpectatorLocationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCSpectatorLocationControl* self = + new(ELeave) CAMMSEMCSpectatorLocationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCSpectatorLocationControl::~CAMMSEMCSpectatorLocationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::CAMMSEMCSpectatorLocationControl"); + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorLocationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMListenerLocationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::PrepareControlL"); + //Create Location Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KListenerLocationEffectControl, temp)); + iMListenerLocationControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMListenerLocationControl)); + iMListenerLocationControl->Enable(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorLocationControl::DeallocateControl() +{ + if (iMListenerLocationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::DeallocateControl"); + + // Location for Audio can be disabled or enabled + iMListenerLocationControl->Disable(); + //return the control to factory + MEffectControl* temp = iMListenerLocationControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMListenerLocationControl; + iFactory->DeleteEffectControl(tempCtrl); + iMListenerLocationControl = NULL; + } +} + +const TDesC& CAMMSEMCSpectatorLocationControl::ClassName() const +{ + return KAMMSEMCSpectatorLocationControl; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::SetLocationCartesianL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorLocationControl::SetLocationCartesianL( + TInt& aX, + TInt& aY, + TInt& aZ) +{ + // Sets the cartesian coordinates for the source location. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::SetLocationCartesianL: %d, %d, %d", + aX, aY, aZ); + + iMListenerLocationControl->SetLocationCartesian(aX, aY, aZ); + + // Apply updated settings to EMC API. + iMListenerLocationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::LocationCartesian +// Gets the coordinates of the current location. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorLocationControl::LocationCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Gets the cartesian coordinates for the location of the Listener position. + // The coordinates of the positions are in millimeters. + iMListenerLocationControl->LocationCartesian(aX, aY, aZ); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::SetLocationSphericalL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorLocationControl::SetLocationSphericalL( + TInt& aAzimuth, + TInt& aElevation, + TInt& aRadius) +{ + // Check in debug build that aRadius is within valid range. + __ASSERT_DEBUG(aRadius >= KAMMSMinRadius, User::Invariant()); + + // Sets the spherical coordinates for the location of the source position. + // The parameters are thousandths of radians + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::SetLocationSphericalL: %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * + KDegToRad * 1000); + + TInt32 convertedElevation = (TInt32)(aElevation * + KDegToRad * 1000); + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorLocationControl::SetLocationSphericalL: %d, %d", + convertedAzimuth, convertedElevation); + + iMListenerLocationControl->SetLocationSpherical( + convertedAzimuth, convertedElevation, (TInt32&)aRadius); + + // Apply updated settings to EMC API. + iMListenerLocationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorLocationControl::CAMMSEMCSpectatorLocationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorLocationControl::CAMMSEMCSpectatorLocationControl(CMMAPlayer* aPlayer) + : CAMMSLocationControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatororientationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsemcspectatororientationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,215 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of the spectator. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include "cammsemcspectatororientationcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorOrientationControl* CAMMSEMCSpectatorOrientationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSEMCSpectatorOrientationControl* self = + new(ELeave)CAMMSEMCSpectatorOrientationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSEMCSpectatorOrientationControl::~CAMMSEMCSpectatorOrientationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::~CAMMSEMCSpectatorOrientationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorOrientationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iMListenerOrientationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::PrepareControlL"); + //Create Orientation Effect Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KListenerOrientationEffectControl, temp)); + iMListenerOrientationControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMListenerOrientationControl)); + iMListenerOrientationControl->Enable(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEMCSpectatorOrientationControl::DeallocateControl() +{ + if (iMListenerOrientationControl) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::DeallocateControl"); + + // Orientation for Listener can be disabled or enabled + iMListenerOrientationControl->Disable(); + //return the control to factory + MEffectControl* temp = iMListenerOrientationControl; + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMListenerOrientationControl; + iFactory->DeleteEffectControl(tempCtrl); + iMListenerOrientationControl = NULL; + } +} + +const TDesC& CAMMSEMCSpectatorOrientationControl::ClassName() const +{ + return KAMMSEMCSpectatorOrientationControl; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::SetOrientationL +// Turns the object to the new orientation. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorOrientationControl::SetOrientationL( + TInt aHeading, + TInt aPitch, + TInt aRoll) +{ + // Sets the Heading, Pitch, Roll values for the source/listener orientation. + // Parameters are given in thousandths of radians. + // SourceOrientationBase/ListenerLocationBase : + // + // NOTE: Effect API uses thousandths of radians for all three parameters, + // but JSR234 uses degrees. + // + // From e32Math.h: The multiplying factor to convert degrees to radians. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL: %d, %d, %d", + aHeading, aPitch, aRoll); + + TInt32 convertedHeading = (TInt32)(aHeading * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedPitch = (TInt32)(aPitch * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedRoll = (TInt32)(aRoll * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL: %d, %d, %d", + convertedHeading, convertedPitch, convertedRoll); + + TInt err = iMListenerOrientationControl->SetOrientation( + convertedHeading, convertedPitch, convertedRoll); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL(3 arg.) err = %d",err); + + + // Apply updated settings to EMC API. + iMListenerOrientationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::SetOrientationL +// Turns the object to the new orientation. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorOrientationControl::SetOrientationL( + TInt aFrontX, TInt aFrontY, TInt aFrontZ, + TInt aAboveX, TInt aAboveY, TInt aAboveZ) +{ + // Check in debug build that parameters are not zero vectors. + __ASSERT_DEBUG(((aFrontX != 0) || + (aFrontY != 0) || + (aFrontZ != 0)) && + ((aAboveX != 0) || + (aAboveY != 0) || + (aAboveZ != 0)), + User::Invariant()); + + // Check in debug build that vectors are not parallel. + // Two vectors are parallel if their cross product is zero vector. + // Cross product of vectors a1*i + a2*j + a3*k and b1*i + b2*j + b3*k : + // (a2*b3 - a3*b2)i + (a3*b1 - a1*b3)j + (a1*b2 - a2*b1)k + __ASSERT_DEBUG( + ((aFrontY * aAboveZ) - (aFrontZ * aAboveY) != 0) || + ((aFrontZ * aAboveX) - (aFrontX * aAboveZ) != 0) || + ((aFrontX * aAboveY) - (aFrontY * aAboveX) != 0), + User::Invariant()); + + // Sets the Front and Above vectors for the orientation of the source/listener. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL: Front %d, %d, %d", + aFrontX, aFrontY, aFrontZ); + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL: Above %d, %d, %d", + aAboveX, aAboveY, aAboveZ); + + TInt err = iMListenerOrientationControl->SetOrientationVectors( + (TInt32)aFrontX, (TInt32)aFrontY, (TInt32)aFrontZ, + (TInt32)aAboveX, (TInt32)aAboveY, (TInt32)aAboveZ); + ELOG1( EJavaAMMS, "AMMS::CAMMSEMCSpectatorOrientationControl::SetOrientationL(6 arg.) err = %d",err); + // Apply updated settings to EMC API. + iMListenerOrientationControl->Apply(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::OrientationVectors +// Gets the orientation of the object using two vectors. +// ----------------------------------------------------------------------------- +void CAMMSEMCSpectatorOrientationControl::OrientationVectors( + TInt& aFrontX, TInt& aFrontY, TInt& aFrontZ, + TInt& aAboveX, TInt& aAboveY, TInt& aAboveZ) +{ + // Gets the orientation of the source. + + iMListenerOrientationControl->OrientationVectors( + aFrontX, aFrontY, aFrontZ, aAboveX, aAboveY, aAboveZ); +} + +// ----------------------------------------------------------------------------- +// CAMMSEMCSpectatorOrientationControl::CAMMSEMCSpectatorOrientationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEMCSpectatorOrientationControl::CAMMSEMCSpectatorOrientationControl( + CMMAPlayer* aPlayer) + : CAMMSOrientationControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammspancontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammspancontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,214 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the panning of a Player in the stereo output mix. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include +#include +#include "cammspancontrol.h" + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxPanning = 100; +const TInt KAMMSMinPanning = -100; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPanControl* CAMMSPanControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSPanControl* self = new(ELeave) CAMMSPanControl(aPlayer); + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSPanControl::~CAMMSPanControl() +{ + if (iRMMFAudioPlayDeviceCustomCommands) + { + delete iRMMFAudioPlayDeviceCustomCommands; + iRMMFAudioPlayDeviceCustomCommands = NULL; + } + + // Remove the EMC Pan Control Effect from Stream Control + // Deleted the effect + if (iMBalanceControl) + { + //return the control to factory + MEffectControl* temp = iMBalanceControl; + if (iStreamControl) + iStreamControl->RemoveEffect(*temp); + // Delete the Effect + MEffectControl* tempCtrl = iMBalanceControl; + if (iFactory) + iFactory->DeleteEffectControl(tempCtrl); + iMBalanceControl = NULL; + } + + +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::PanL +// Gets the current panning set. +// ----------------------------------------------------------------------------- +// +TInt CAMMSPanControl::PanL() +{ + TInt balance = KMMFBalanceCenter; + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iMidiClientUtility) + { + // Get the current stereo balance value. + + balance = iMidiClientUtility->GetBalanceL(); + } + else if (iRMMFAudioPlayDeviceCustomCommands) + { + // Gets the balance between the left and right stereo audio channels. + + User::LeaveIfError( + iRMMFAudioPlayDeviceCustomCommands->GetBalance(balance)); + } + else // if EMC Pan Control + { + // Get the balance and set it to balance var. + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::PanL is called for EMC implemented palyer"); + User::LeaveIfError(iMBalanceControl->GetBalance(balance)); + } + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::PanL called, native GetBalance = %d", + balance); + + return balance; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::SetPanL +// Sets the panning using a linear point scale (-100 - +100). +// ----------------------------------------------------------------------------- +// +TInt CAMMSPanControl::SetPanL(TInt aPan) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::SetPanL: Pan = %d", aPan); + + // Check in debug build that aPan is within valid range. + __ASSERT_DEBUG( + (aPan <= KAMMSMaxPanning) && + (aPan >= KAMMSMinPanning), + User::Invariant()); + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iMidiClientUtility) + { + // Set the current stereo balance value. + // Defaults to KMMFBalanceCenter to restore equal left-right balance. + + iMidiClientUtility->SetBalanceL(aPan); + } + else if (iRMMFAudioPlayDeviceCustomCommands) + { + // Sets the balance between the left and right stereo audio channels + // Use a value between KMMFBalanceMaxLeft and KMMFBalanceMaxRight. + // Centre balance can be restored by using KMMFBalanceCenter. + + User::LeaveIfError( + iRMMFAudioPlayDeviceCustomCommands->SetBalance(aPan)); + } + else // EMC Pan Control + { + // Set the Balance using the Pan Control + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::SetPanL: SetBalance()-- EMC "); + User::LeaveIfError(iMBalanceControl->SetBalance(aPan)); + User::LeaveIfError(iMBalanceControl->Apply()); + } + + return PanL(); +} + + +const TDesC& CAMMSPanControl::ClassName() const +{ + return KAMMSPanControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSPanControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::ConstructL"); + + if (iPlayer->Type() == KMMAMIDIPlayer) + { + // In case of CMMAMIDIPlayer use CMidiClientUtility + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + + iMidiClientUtility = mmaMIDIPlayer->MidiClient(); + } + else if (iPlayer->Type() == KMMAEMCAudioPlayer) + { + //Get MMFactory and StreamControl from the player + //Create Pan Control using EMC API. + //Add the control to Stream Control + //Create Balance Control + iStreamControl = (static_cast(iMMAPlayer))->StreamControl(); + iFactory = (static_cast(iMMAPlayer))->MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(iFactory->CreateEffectControl(KBalanceEffectControl, temp)); + iMBalanceControl = static_cast(temp); + User::LeaveIfError(iStreamControl->AddEffect(*iMBalanceControl)); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::ConstructL is called for EMC implemented Player"); + } + else + { + CMMAAudioPlayer* mmaAudioPlayer = + reinterpret_cast< CMMAAudioPlayer* >(iPlayer); + + RMMFController& mmfController = mmaAudioPlayer->Controller(); + + iRMMFAudioPlayDeviceCustomCommands = + new(ELeave) RMMFAudioPlayDeviceCustomCommands(mmfController); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::CAMMSPanControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPanControl::CAMMSPanControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ + iMMAPlayer = aPlayer; +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.emc/cammsprioritycontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.emc/cammsprioritycontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,232 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the priority of a Player. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include +#include "cammsprioritycontrol.h" +#include +#include +#include +#include +#include + + + +const TInt KErrorMessageSize = 32; +_LIT(KErrPriorityError, "AMMS PC error: %d"); + +// Default AMMS priority. +const TInt KAMMSDefaultPriority = 50; + +// Reasonable MMF priorities. +const TInt KAMMSMinMMFPriority = 71; +const TInt KAMMSMaxMMFPriority = 89; + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxPriority = 100; +const TInt KAMMSMinPriority = 0; +#endif // _DEBUG + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPriorityControl* CAMMSPriorityControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSPriorityControl* self = new(ELeave) CAMMSPriorityControl(aPlayer); + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSPriorityControl::~CAMMSPriorityControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::~"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::SetPriorityL +// Sets the priority using a linear point scale between 0 and 100. +// ----------------------------------------------------------------------------- +// +void CAMMSPriorityControl::SetPriorityL(TInt aPriority) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityL %d", aPriority); + + // Check in debug build that aPriority is within valid range. + __ASSERT_DEBUG( + (aPriority <= KAMMSMaxPriority) && + (aPriority >= KAMMSMinPriority), + User::Invariant()); + + // Set a new priority only if it differs from the previous one. + if (aPriority != iVisiblePriority) + { + // Set the new priority to MMF only if the player is PREFETCHED + // (otherwise setting will leave). In other states, the new priority + // will be set when the player state changes to PREFETCHED. + if (iPlayer->State() == CMMAPlayer::EPrefetched) + { + SetPriorityToMmfL(aPriority); + } + + iVisiblePriority = aPriority; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::Priority +// Gets the priority. +// ----------------------------------------------------------------------------- +TInt CAMMSPriorityControl::Priority() +{ + return iVisiblePriority; +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::StateChanged +// Called when player state is changed. +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::StateChanged(TInt aState) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::StateChanged +, state = %d", + aState); + + // If the state was changed to PREFETCHED, set the buffered priority to + // MMF. Set a new priority only if it differs from the previous one. + + if ((aState == CMMAPlayer::EPrefetched) && + (iActualPriority != iVisiblePriority)) + { + TRAPD(err, SetPriorityToMmfL(iVisiblePriority)); + + ELOG1( EJavaAMMS, "AMMS::CAMMSPriorityControl::StateChanged, err = %d", err); + + if (err != KErrNone) + { + TBuf errorMessage; + errorMessage.Format(KErrPriorityError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::StateChanged -"); +} + +const TDesC& CAMMSPriorityControl::ClassName() const +{ + LOG( EJavaAMMS, EInfo, "CAMMSPriorityControl::ClassName"); + + return KAMMSPriorityControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::SetPriorityToMmfL +// Scales the given AMMS priority to MMF priority and sets it to MMF. +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::SetPriorityToMmfL(TInt aAmmsPriority) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL %d", + aAmmsPriority); + + // Scale the AMMS priority value to MMF priority value before setting it. + // The default priority used by MMA is 80. MMF priority can be between + // -100 and 100, but values between 71 and 89 are reasonable ones. + TInt newPriority = KAMMSMinMMFPriority + aAmmsPriority * + (KAMMSMaxMMFPriority - KAMMSMinMMFPriority) / 100; // CSI: 47 100% for scaled value # + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL, newPriority = %d", + newPriority); + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iPlayer->Type() == KMMAMIDIPlayer) + { + // In case of CMMAMIDIPlayer use CMidiClientUtility + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + + CMidiClientUtility* midiClientUtility = mmaMIDIPlayer->MidiClient(); + + midiClientUtility->SetPriorityL(newPriority, + KMMAMIDIPriorityPreference); + } + else if (iPlayer->Type() == KMMAAudioPlayer) + { + CMMAAudioPlayer* mmaAudioPlayer = + reinterpret_cast< CMMAAudioPlayer* >(iPlayer); + + RMMFController& rmmfController = mmaAudioPlayer->Controller(); + + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = newPriority; + + User::LeaveIfError( + rmmfController.SetPrioritySettings(prioritySettings)); + } + else if (iPlayer->Type() == KMMAEMCAudioPlayer) + { + MStreamControl* streamControl = (static_cast(iPlayer))->StreamControl(); + User::LeaveIfError(streamControl->SetPriority(newPriority, KMMAEMCPriorityPreference)); + } + + iActualPriority = aAmmsPriority; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::CAMMSPriorityControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPriorityControl::CAMMSPriorityControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer), + iVisiblePriority(KAMMSDefaultPriority), + iActualPriority(KAMMSDefaultPriority) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::ConstructL +// 2nd phase constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::ConstructL +"); + + iPlayer->AddStateListenerL(this); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::ConstructL -"); +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.mmf/cammsaudioplayerbuilder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.mmf/cammsaudioplayerbuilder.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder for adding AMMS audio player controls. +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "CAMMSAudioPlayerBuilder.h" +#include "CAMMSCustomCommandUtility.h" + +#include "CAMMSEqualizerControl.h" +#include "CAMMSReverbControl.h" +#include "CAMMSReverbSourceControl.h" +#include "CAMMSAudioVirtualizerControl.h" +#include "CAMMSPanControl.h" +#include "CAMMSDistanceAttenuationControl.h" +#include "CAMMSAudioDopplerControl.h" +#include "CAMMSSpectatorDopplerControl.h" +#include "CAMMSAudioLocationControl.h" +#include "CAMMSSpectatorLocationControl.h" +#include "CAMMSSpectatorOrientationControl.h" +#include "CAMMSVolumeControl.h" +#include "AMMSConstants.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioPlayerBuilder* CAMMSAudioPlayerBuilder::NewLC() +{ + CAMMSAudioPlayerBuilder* self = new(ELeave) CAMMSAudioPlayerBuilder(); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSAudioPlayerBuilder::~CAMMSAudioPlayerBuilder() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::PreparePlayerL +// Adds the AMMS audio controls to the player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioPlayerBuilder::PreparePlayerL(CMMAPlayer* aPlayer) +{ + const TDesC& playerType = aPlayer->Type(); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL type %S", + playerType); + + if ((playerType != KMMAAudioPlayer) && + (playerType != KMMAMIDIPlayer)) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL, not supported"); + return; + } + + + // Default type for a Control is base Control (=not a derived Control). + // DopplerControl and LocationControl have different Effect API + // implementations and also different corresponding AMMS Controls for + // SoundSource3D and for Spectator, so these Control types need to be + // set accordingly. + // + // CMMAPlayer::AddControlL( CMMAControl* aControl ) adds a new control. + // Ownership of the control is transferred to CMMAPlayer. + // + +#ifndef __WINS__ + // PanControl is not supported in WINSCW builds. + // This is because of limited pan support in DirectX. + CAMMSPanControl* panControl = CAMMSPanControl::NewLC(aPlayer); + aPlayer->AddControlL(panControl); + CleanupStack::Pop(panControl); +#endif // __WINS__ + + CAMMSEqualizerControl* equalizerControl = + CAMMSEqualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(equalizerControl); + CleanupStack::Pop(equalizerControl); + + CAMMSReverbControl* reverbControl = + CAMMSReverbControl::NewLC(aPlayer); + aPlayer->AddControlL(reverbControl); + CleanupStack::Pop(reverbControl); + + CAMMSAudioVirtualizerControl* audioVirtualizerControl = + CAMMSAudioVirtualizerControl::NewLC(aPlayer); + aPlayer->AddControlL(audioVirtualizerControl); + CleanupStack::Pop(audioVirtualizerControl); + + CAMMSReverbSourceControl* reverbSourceControl = + CAMMSReverbSourceControl::NewLC(aPlayer, reverbControl); + aPlayer->AddControlL(reverbSourceControl); + CleanupStack::Pop(reverbSourceControl); + + CAMMSDistanceAttenuationControl* distanceAttenuationControl = + CAMMSDistanceAttenuationControl::NewLC(aPlayer); + aPlayer->AddControlL(distanceAttenuationControl); + CleanupStack::Pop(distanceAttenuationControl); + + CAMMSAudioDopplerControl* audioDopplerControl = + CAMMSAudioDopplerControl::NewLC(aPlayer); + audioDopplerControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(audioDopplerControl); + CleanupStack::Pop(audioDopplerControl); + + CAMMSSpectatorDopplerControl* spectatorDopplerControl = + CAMMSSpectatorDopplerControl::NewLC(aPlayer); + spectatorDopplerControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(spectatorDopplerControl); + CleanupStack::Pop(spectatorDopplerControl); + + CAMMSAudioLocationControl* audioLocationControl = + CAMMSAudioLocationControl::NewLC(aPlayer); + audioLocationControl->iControlType = EAMMSSoundSource3DControl; + aPlayer->AddControlL(audioLocationControl); + CleanupStack::Pop(audioLocationControl); + + CAMMSSpectatorLocationControl* spectatorLocationControl = + CAMMSSpectatorLocationControl::NewLC(aPlayer); + spectatorLocationControl->iControlType = EAMMSSpectatorControl; + aPlayer->AddControlL(spectatorLocationControl); + CleanupStack::Pop(spectatorLocationControl); + + CAMMSSpectatorOrientationControl* spectatorOrientationControl = + CAMMSSpectatorOrientationControl::NewLC(aPlayer); + aPlayer->AddControlL(spectatorOrientationControl); + CleanupStack::Pop(spectatorOrientationControl); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioPlayerBuilder::PreparePlayerL add OK"); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioPlayerBuilder::CAMMSAudioPlayerBuilder +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioPlayerBuilder::CAMMSAudioPlayerBuilder() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.mmf/cammspancontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.mmf/cammspancontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,164 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the panning of a Player in the stereo output mix. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include +#include "CAMMSPanControl.h" + + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxPanning = 100; +const TInt KAMMSMinPanning = -100; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPanControl* CAMMSPanControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSPanControl* self = new(ELeave) CAMMSPanControl(aPlayer); + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSPanControl::~CAMMSPanControl() +{ + delete iRMMFAudioPlayDeviceCustomCommands; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::PanL +// Gets the current panning set. +// ----------------------------------------------------------------------------- +// +TInt CAMMSPanControl::PanL() +{ + TInt balance = KMMFBalanceCenter; + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iMidiClientUtility) + { + // Get the current stereo balance value. + + balance = iMidiClientUtility->GetBalanceL(); + } + else + { + // Gets the balance between the left and right stereo audio channels. + + User::LeaveIfError( + iRMMFAudioPlayDeviceCustomCommands->GetBalance(balance)); + } + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::PanL called, native GetBalance = %d", + balance); + + return balance; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::SetPanL +// Sets the panning using a linear point scale (-100 - +100). +// ----------------------------------------------------------------------------- +// +TInt CAMMSPanControl::SetPanL(TInt aPan) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::SetPanL: Pan = %d", aPan); + + // Check in debug build that aPan is within valid range. + __ASSERT_DEBUG( + (aPan <= KAMMSMaxPanning) && + (aPan >= KAMMSMinPanning), + User::Invariant()); + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iMidiClientUtility) + { + // Set the current stereo balance value. + // Defaults to KMMFBalanceCenter to restore equal left-right balance. + + iMidiClientUtility->SetBalanceL(aPan); + } + else + { + // Sets the balance between the left and right stereo audio channels + // Use a value between KMMFBalanceMaxLeft and KMMFBalanceMaxRight. + // Centre balance can be restored by using KMMFBalanceCenter. + + User::LeaveIfError( + iRMMFAudioPlayDeviceCustomCommands->SetBalance(aPan)); + } + + return PanL(); +} + + +const TDesC& CAMMSPanControl::ClassName() const +{ + return KAMMSPanControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSPanControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPanControl::ConstructL"); + + if (iPlayer->Type() == KMMAMIDIPlayer) + { + // In case of CMMAMIDIPlayer use CMidiClientUtility + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + + iMidiClientUtility = mmaMIDIPlayer->MidiClient(); + } + else + { + CMMAAudioPlayer* mmaAudioPlayer = + reinterpret_cast< CMMAAudioPlayer* >(iPlayer); + + RMMFController& mmfController = mmaAudioPlayer->Controller(); + + iRMMFAudioPlayDeviceCustomCommands = + new(ELeave) RMMFAudioPlayDeviceCustomCommands(mmfController); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSPanControl::CAMMSPanControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPanControl::CAMMSPanControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src.mmf/cammsprioritycontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src.mmf/cammsprioritycontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,226 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the priority of a Player. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include +#include "CAMMSPriorityControl.h" +#include +#include +#include +#include + + + +const TInt KErrorMessageSize = 32; +_LIT(KErrPriorityError, "AMMS PC error: %d"); + +// Default AMMS priority. +const TInt KAMMSDefaultPriority = 50; + +// Reasonable MMF priorities. +const TInt KAMMSMinMMFPriority = 71; +const TInt KAMMSMaxMMFPriority = 89; + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxPriority = 100; +const TInt KAMMSMinPriority = 0; +#endif // _DEBUG + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPriorityControl* CAMMSPriorityControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSPriorityControl* self = new(ELeave) CAMMSPriorityControl(aPlayer); + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSPriorityControl::~CAMMSPriorityControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::~"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::SetPriorityL +// Sets the priority using a linear point scale between 0 and 100. +// ----------------------------------------------------------------------------- +// +void CAMMSPriorityControl::SetPriorityL(TInt aPriority) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityL %d", aPriority); + + // Check in debug build that aPriority is within valid range. + __ASSERT_DEBUG( + (aPriority <= KAMMSMaxPriority) && + (aPriority >= KAMMSMinPriority), + User::Invariant()); + + // Set a new priority only if it differs from the previous one. + if (aPriority != iVisiblePriority) + { + // Set the new priority to MMF only if the player is PREFETCHED + // (otherwise setting will leave). In other states, the new priority + // will be set when the player state changes to PREFETCHED. + if (iPlayer->State() == CMMAPlayer::EPrefetched) + { + SetPriorityToMmfL(aPriority); + } + + iVisiblePriority = aPriority; + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::Priority +// Gets the priority. +// ----------------------------------------------------------------------------- +TInt CAMMSPriorityControl::Priority() +{ + return iVisiblePriority; +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::StateChanged +// Called when player state is changed. +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::StateChanged(TInt aState) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::StateChanged +, state = %d", + aState); + + // If the state was changed to PREFETCHED, set the buffered priority to + // MMF. Set a new priority only if it differs from the previous one. + + if ((aState == CMMAPlayer::EPrefetched) && + (iActualPriority != iVisiblePriority)) + { + TRAPD(err, SetPriorityToMmfL(iVisiblePriority)); + + ELOG1( EJavaAMMS, "AMMS::CAMMSPriorityControl::StateChanged, err = %d", err); + + if (err != KErrNone) + { + TBuf errorMessage; + errorMessage.Format(KErrPriorityError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } + } + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::StateChanged -"); +} + +const TDesC& CAMMSPriorityControl::ClassName() const +{ + LOG( EJavaAMMS, EInfo, "CAMMSPriorityControl::ClassName"); + + return KAMMSPriorityControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::SetPriorityToMmfL +// Scales the given AMMS priority to MMF priority and sets it to MMF. +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::SetPriorityToMmfL(TInt aAmmsPriority) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL %d", + aAmmsPriority); + + // Scale the AMMS priority value to MMF priority value before setting it. + // The default priority used by MMA is 80. MMF priority can be between + // -100 and 100, but values between 71 and 89 are reasonable ones. + TInt newPriority = KAMMSMinMMFPriority + aAmmsPriority * + (KAMMSMaxMMFPriority - KAMMSMinMMFPriority) / 100; // CSI: 47 100% for scaled value # + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL, newPriority = %d", + newPriority); + + // In case of MIDIPlayer, use CMidiClientUtility, otherwise RMMFController. + if (iPlayer->Type() == KMMAMIDIPlayer) + { + // In case of CMMAMIDIPlayer use CMidiClientUtility + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + + CMidiClientUtility* midiClientUtility = mmaMIDIPlayer->MidiClient(); + + midiClientUtility->SetPriorityL(newPriority, + KMMAMIDIPriorityPreference); + } + else + { + CMMAAudioPlayer* mmaAudioPlayer = + reinterpret_cast< CMMAAudioPlayer* >(iPlayer); + + RMMFController& rmmfController = mmaAudioPlayer->Controller(); + + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = newPriority; + + User::LeaveIfError( + rmmfController.SetPrioritySettings(prioritySettings)); + } + + iActualPriority = aAmmsPriority; + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::SetPriorityToMmfL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSPriorityControl::CAMMSPriorityControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPriorityControl::CAMMSPriorityControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer), + iVisiblePriority(KAMMSDefaultPriority), + iActualPriority(KAMMSDefaultPriority) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::ConstructL +// 2nd phase constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPriorityControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::ConstructL +"); + + iPlayer->AddStateListenerL(this); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSPriorityControl::ConstructL -"); +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsaudiodopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsaudiodopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler effect of the SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsaudiodopplercontrol.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioDopplerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioDopplerControl* CAMMSAudioDopplerControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSAudioDopplerControl* self = + new(ELeave) CAMMSAudioDopplerControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSAudioDopplerControl::~CAMMSAudioDopplerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioDopplerControl::~CAMMSAudioDopplerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete(CAudioEffect*)iDopplerEffect; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioDopplerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioDopplerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iDopplerEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioDopplerControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Set the base class location effect as CSourceDoppler + // Effect API takes the ownership of customCommandUtility. + iDopplerEffect = CSourceDoppler::NewL(customCommandUtility); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioDopplerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioDopplerControl::DeallocateControl() +{ + if (iDopplerEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioDopplerControl::DeallocateControl"); + + // Doppler for Audio can be disabled or enabled + if (Enabled()) + { + TRAPD(err, iDopplerEffect->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling + // ApplyL method without having update rights, but since the + // Effect is already created, that situation can be discarded. + } + } + + // Delete the Effect API class. + delete(CAudioEffect*)iDopplerEffect; + iDopplerEffect = NULL; + } +} + +const TDesC& CAMMSAudioDopplerControl::ClassName() const +{ + return KAMMSAudioDopplerControl; +} + + +// ----------------------------------------------------------------------------- +// CAMMSAudioDopplerControl::CAMMSAudioDopplerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioDopplerControl::CAMMSAudioDopplerControl( + CMMAPlayer* aPlayer) + : CAMMSDopplerControl(aPlayer) +{ +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsaudiolocationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsaudiolocationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,120 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsaudiolocationcontrol.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioLocationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioLocationControl* CAMMSAudioLocationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSAudioLocationControl* self = + new(ELeave) CAMMSAudioLocationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSAudioLocationControl::~CAMMSAudioLocationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioLocationControl::~CAMMSAudioLocationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete(CAudioEffect*)iLocationEffect; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioLocationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioLocationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iLocationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioLocationControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Set the base class location effect as CSourceLocation + // Effect API takes the ownership of customCommandUtility. + iLocationEffect = CSourceLocation::NewL(customCommandUtility); + + // Enable the Effect API Control + iLocationEffect->EnableL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioLocationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioLocationControl::DeallocateControl() +{ + if (iLocationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioLocationControl::DeallocateControl"); + + // Disable the Effect API Control + TRAPD(err, iLocationEffect->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class. + // The class that is derived from CLocation is casted here to the + // base class CAudioEffect, since CLocation has the destructor + // defined as protected, but the derived class and the base class + // have it defined as public. + delete(CAudioEffect*)iLocationEffect; + iLocationEffect = NULL; + } +} + +const TDesC& CAMMSAudioLocationControl::ClassName() const +{ + return KAMMSAudioLocationControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioLocationControl::CAMMSAudioLocationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioLocationControl::CAMMSAudioLocationControl(CMMAPlayer* aPlayer) + : CAMMSLocationControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsaudiooutputcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsaudiooutputcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,435 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the audio output mode. +* +*/ + +// INCLUDE FILES +#include +#include +#include "cammsaudiooutputcontrol.h" +#include +#include +#include +#include +#include +#include +#include +// CONSTANTS +_LIT(KErrAudioOutputControlError, "AMMS AudioOutputControl error: %d"); +const TInt KEventMessageSize = 64; +const TInt KNoPriference = 0; +const TInt KAllSpeakers = 1; +const TInt KNoAudioOutput = 2; +const TInt KAudioEarpiece = 3; +const TInt KAudioLoudspeaker = 4; + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioOutputControl* CAMMSAudioOutputControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSAudioOutputControl* self = new(ELeave) CAMMSAudioOutputControl(aPlayer); + + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSAudioOutputControl::~CAMMSAudioOutputControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::~"); + if (iAudioOutput) + { + iAudioOutput->UnregisterObserver(*this); + delete iAudioOutput; + } + if (iAccMonitor) + { + iAccMonitor ->StopObserving(); + delete iAccMonitor; + } +} + +//set java AudioOutput object +void CAMMSAudioOutputControl::SetJavaAudioOutputObject(jobject object) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::SetJavaAudioOutputObject "); + iJavaAudioOutputObj = object; + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + // iJni = JniEnvWrapper::GetValidJniRef(); +} + +void CAMMSAudioOutputControl::ResetJavaAudioOutputObject() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::ResetJavaAudioOutputObject "); + jmethodID setOutputModeID = iJni->GetMethodID( + iJni->GetObjectClass(iJavaAudioOutputObj), + "setOutputMode", + "(I)V"); + + jint jpref = (jint)GetCurrentPrefInt(); + iJni->CallVoidMethod(iJavaAudioOutputObj,setOutputModeID,jpref); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::SetAudioOutput +// Sets the preference using a linear point scale between 0 and 4. +// ----------------------------------------------------------------------------- +// +TInt CAMMSAudioOutputControl::SetAudioOutput(TInt aPreference) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::SetAudioOutputL %d", aPreference); + + TInt temppreference = 0; + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::SetAudioOutputL After __ASSERT_DEBUG"); + // Set a new preference only if it differs from the previous one. + if (aPreference != iRoutingUserPreference) + { + switch (aPreference) + { + case KNoPriference: + { + temppreference = SetAudioOutputToMmf(CAudioOutput::ENoPreference); + } + break; + case KAllSpeakers: + { + temppreference = SetAudioOutputToMmf(CAudioOutput::EAll); + } + break; + case KNoAudioOutput: + { + temppreference = SetAudioOutputToMmf(CAudioOutput::ENoOutput); + } + break; + case KAudioEarpiece: + { + temppreference = SetAudioOutputToMmf(CAudioOutput::EPrivate); + } + break; + case KAudioLoudspeaker: + { + temppreference = SetAudioOutputToMmf(CAudioOutput::EPublic); + } + break; + default: + break; + } + } + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::SetAudioOutputL - = %d", temppreference); + return temppreference; + +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::GetAudioOutput +// Gets the preference. +// ----------------------------------------------------------------------------- +TInt CAMMSAudioOutputControl::GetAudioOutput() +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::GetAudioOutput %d", (TInt)iRoutingUserPreference); + return (TInt)iRoutingUserPreference; +} + +// ---------------------------------------------------------------------------------------- +// CAMMSAudioOutputControl::GetCurrentPreference +// Gets the preference.if user preference is not set return the current device preference +// ---------------------------------------------------------------------------------------- +void CAMMSAudioOutputControl::GetCurrentPreference() +{ + // reset the java AudioOutput object with current mode + ResetJavaAudioOutputObject(); +} + +// ---------------------------------------------------------------------------------------- +// CAMMSAudioOutputControl::GetCurrentPrefInt +// Gets the preference.if user preference is not set return the current device preference in TInt form +// ---------------------------------------------------------------------------------------- + +TInt CAMMSAudioOutputControl::GetCurrentPrefInt() +{ + TInt pref ; + // get the value of current preference + if (iRoutingUserPreference == CAudioOutput::ENoPreference) + { + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::GetCurrentPrefInt_if %d", (TInt)iDefaultDevicePreference); + pref = GetDeviceDefaultPreference(); + } + else + { + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::GetCurrentPrefInt_else %d", (TInt)iRoutingUserPreference); + pref = (TInt)iRoutingUserPreference; + } + return pref; +} +// ---------------------------------------------------------------------------------------- +// CAMMSAudioOutputControl::GetDeviceDefaultPreference +// Gets the current device preference used as default +// ---------------------------------------------------------------------------------------- +TInt CAMMSAudioOutputControl::GetDeviceDefaultPreference() +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::GetDeviceDefaultPreference %d", (TInt)iDefaultDevicePreference); + array.Reset(); + TInt temp = 0; + TRAPD(err,iAccMonitor->GetConnectedAccessoriesL(array)); + if (err) + { + temp = -1; + } + TInt count = array.Count(); + if (count == 0) + { + temp = (TInt)CAudioOutput::EPublic; + } + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::GetDeviceDefaultPreference :RConnectedAccessories count = %d",count); + for (TInt i = 0; i != count; i++) + { + TAccMonCapability deviceType = array[ i ]->AccDeviceType(); + if ((deviceType == KAccMonHeadset)||(deviceType == KAccMonBluetooth)) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::CreateHeadsetStateObserverL info = Headset Connected "); + temp = (TInt)CAudioOutput::EPrivate; + break; + } + + } + return temp; +} +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::StateChanged +// Called when player state is changed. +// ----------------------------------------------------------------------------- +void CAMMSAudioOutputControl::StateChanged(TInt aState) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::StateChanged +, state = %d", aState); + playerState = (CMMAPlayer::TPlayerState)aState; + if (aState == CMMAPlayer::EStarted) + { + NotifyJavaOnChange(); + } +} + +const TDesC& CAMMSAudioOutputControl::ClassName() const +{ + LOG( EJavaAMMS, EInfo, "CAMMSAudioOutputControl::ClassName"); + return KAMMSAudioOutputControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::SetPriorityToMmf +// Scales the given AMMS priority to MMF priority and sets it to MMF. +// ----------------------------------------------------------------------------- +TInt CAMMSAudioOutputControl::SetAudioOutputToMmf(CAudioOutput::TAudioOutputPreference aPref) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::SetAudioOutputToMmfL +"); + CAudioOutput::TAudioOutputPreference tempPreference = iRoutingUserPreference ; + iRoutingUserPreference = aPref; + TRAPD(err,CreateNativeAudioOutputControlL(); + iAudioOutput->SetAudioOutputL(aPref)); + if (KErrNone != err) + { + iRoutingUserPreference = tempPreference; + TBuf errorMessage; + errorMessage.Format(KErrAudioOutputControlError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } + // if during play user set a preference event should be sent to java + if (playerState == CMMAPlayer::EStarted) + { + NotifyJavaOnChange(); + } + return (TInt)iRoutingUserPreference; +} +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::DefaultAudioOutputChanged +// MAudioOutputObserver's function is implemented to notify about the change in routing preference +// ----------------------------------------------------------------------------- + +void CAMMSAudioOutputControl::DefaultAudioOutputChanged(CAudioOutput& /*aAudioOutput*/, + CAudioOutput::TAudioOutputPreference /*aNewDefault*/) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DefaultAudioOutputChanged "); + +} + +void CAMMSAudioOutputControl::NotifyJavaOnChange() +{ + TInt tempPref = GetCurrentPrefInt(); + if (iCurrentPreference == tempPref) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::NotifyJavaOnChange - No Event "); + return; + } + //reset the java side object with the current iCurrentActualPreference + ResetJavaAudioOutputObject(); + iCurrentPreference = tempPref; + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::NotifyJavaOnChange - Sending Event "); + iPlayer->PostObjectEvent(CMMAPlayerEvent::EAudioOutputPreferenceChangeEvent, iJavaAudioOutputObj); +} + +void CAMMSAudioOutputControl::AccMonitorObserverError(TInt /*aError*/) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::AccMonitorObserverError"); +} +// ----------------------------------------------------------------------------- +// CAMMSAudioOutputControl::CAMMSAudioOutputControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioOutputControl::CAMMSAudioOutputControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer), + iRoutingUserPreference(CAudioOutput::ENoPreference) +{ +} +// HEADSET CONNECTED OR NOT +void CAMMSAudioOutputControl::ConnectedL(CAccMonitorInfo* aAccessoryInfo) +{ // Reserve memory for the accessory information instance if necessary + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::ConnectedL +"); + if (!iAccessoryInfo) + { + iAccessoryInfo = CAccMonitorInfo::NewL(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::ConnectedL iAccessoryInfo created"); + } + // Otherwise just reset accessory information instance + else + { + iAccessoryInfo->Reset(); + } + iAccessoryInfo->CopyL(aAccessoryInfo); + TAccMonCapability deviceType = iAccessoryInfo->AccDeviceType() ; + if ((deviceType == KAccMonHeadset) || (deviceType == KAccMonBluetooth)) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DisconnectedL: Headset connected"); + //send a callback + if (iRoutingUserPreference == (TInt)(CAudioOutput::ENoPreference)) + { + NotifyJavaOnChange(); + } + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::ConnectedL -"); +} + + +void CAMMSAudioOutputControl::DisconnectedL(CAccMonitorInfo* aAccessoryInfo) +{ // Reserve memory for the accessory information instance if necessary + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DisconnectedL +"); + if (!iAccessoryInfo) + { + iAccessoryInfo = CAccMonitorInfo::NewL(); + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DisconnectedL: iAccessoryInfo created"); + } + else + { + iAccessoryInfo->Reset(); + } + iAccessoryInfo->CopyL(aAccessoryInfo); + TAccMonCapability deviceType = iAccessoryInfo->AccDeviceType(); + if ((deviceType == KAccMonHeadset)||(deviceType == KAccMonBluetooth)) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DisconnectedL: Headset Disconnected"); + //send a callback + if (iRoutingUserPreference == (TInt)(CAudioOutput::ENoPreference)) + { + NotifyJavaOnChange(); + } + } + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::DisconnectedL -"); +} + +// start observing headset connection disconnection + +void CAMMSAudioOutputControl::CreateHeadsetStateObserverL() +{ + // Headset connection and disconnection + iAccessoryInfo = NULL; + capabilityArray.Append(KAccMonHeadset); + capabilityArray.Append(KAccMonBluetooth); + + iAccMonitor = CAccMonitor::NewL(); + iDefaultDevicePreference = (CAudioOutput::TAudioOutputPreference)GetDeviceDefaultPreference(); + iCurrentPreference = (TInt)iDefaultDevicePreference; + TBool isObserving = iAccMonitor->IsObserving(); + if (!isObserving) + { + iAccMonitor->StartObservingL(this, capabilityArray); + } +} + +// end CreateHeadsetStateObserver + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::ConstructL +// 2nd phase constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSAudioOutputControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioOutputControl::ConstructL +"); + // create an observer to notify the state of headset + //and initialize iDefaultDevicePreference with CAudioOutput::EPrivate if headset is connected. + CreateHeadsetStateObserverL(); + iPlayer->AddStateListenerL(this); +} + +void CAMMSAudioOutputControl::CreateNativeAudioOutputControlL() +{ + if (iAudioOutput) + { + return; + } + + if (iPlayer->Type() == KMMAMIDIPlayer) + { + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + iAudioOutput = CAudioOutput::NewL(*(mmaMIDIPlayer->MidiClient())); + } + else if (iPlayer->Type() == KMMAAudioPlayer) + { + MCustomCommand* customCommandUtility = (MCustomCommand *)CreateCustomCommandUtilityL(); + // Create the CAudioOutput Object to handle the audio routing + iAudioOutput = CAudioOutput::NewL(*customCommandUtility); + } + else if (iPlayer->Type() == KMMAVideoPlayer) + { + CMMAVideoPlayer* mmaVideoPlayer = + reinterpret_cast< CMMAVideoPlayer* >(iPlayer); + RMMFController& mmfController = mmaVideoPlayer->Controller(); + MCustomCommand* customCommandUtility = + CAMMSCustomCommandUtility::NewL(mmfController); + iAudioOutput = CAudioOutput::NewL(*customCommandUtility); + } + + if(iAudioOutput) + { + iAudioOutput->RegisterObserverL(*this); + } + else + { + User::Leave(KErrNotSupported); + } +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsaudiovirtualizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsaudiovirtualizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,244 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Virtualizes audio channels. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsaudiovirtualizercontrol.h" + +// CONSTANTS +const TInt KAMMSDefaultStereoWideningLevel = 100; + +// ============================ MEMBER FUNCTIONS =============================== + + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSAudioVirtualizerControl* CAMMSAudioVirtualizerControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSAudioVirtualizerControl* self = + new(ELeave) CAMMSAudioVirtualizerControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSAudioVirtualizerControl::~CAMMSAudioVirtualizerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::~CAMMSAudioVirtualizerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete iStereoWideningUtility; + delete iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioVirtualizerControl::SetPresetL(const TDesC& aPreset) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::SetPresetL \"%S\"", + aPreset.Ptr()); + + const CDesCArray& presetNames = PresetNamesL(); + + TInt presetPosition = 0; + TInt findPreset = presetNames.Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + // This supposes that the indexing of the presets starts at zero. + iStereoWideningUtility->GetPresetL(presetPosition); + + // Set the base class audio effect as the new CStereoWidening + // that is set with the previous GetPresetL method. + iAudioEffect = &(iStereoWideningUtility->StereoWidening()); + iCurrentPreset = presetPosition; + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::SetPresetL \"%S\" GetPresetL OK", + aPreset.Ptr()); + } + else + { + User::Leave(KErrArgument); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSAudioVirtualizerControl::PresetNamesL() +{ + // Returns an array of all preset names (pre-defined and user-defined). + // The pre-defined presets are in the beginning of the list. + + TArray< TEfStereoWideningUtilityPreset > presetNames = + iStereoWideningUtility->Presets(); + + // Before appending the preset names, reset the member array + iPresetNames->Reset(); + for (TInt i = 0; i < presetNames.Count(); i++) + { + iPresetNames->AppendL(presetNames[ i ].iPresetName); + } + + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSAudioVirtualizerControl::PresetL() +{ + //if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + else + { + // Retrieves a Preset with the given index from the Central Repository + return iStereoWideningUtility->GetPresetL(iCurrentPreset); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioVirtualizerControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect. + + ((CStereoWidening*)iAudioEffect)->SetStereoWideningLevelL( + KAMMSDefaultStereoWideningLevel); + + // Instead of using CAudioEffectBase: virtual void EnableL(), + // use the derived effect's (=preset's) ApplyL which calls EnableL. + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::SetEnabledL(true), calling ApplyL"); + iAudioEffect->ApplyL(); + } + else + { + // Disable the effect + // Instead of using CAudioEffectBase: virtual void DisableL(), + // use the utility class DisableStereoWideningL, + // which calls DisableL for the correct preset + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::SetEnabledL(false), calling DisableStereoWideningL"); + iStereoWideningUtility->DisableStereoWideningL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioVirtualizerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iStereoWideningUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Effect API takes the ownership of customCommandUtility. + iStereoWideningUtility = CStereoWideningUtility::NewL( + customCommandUtility); + + // Set the base class audio effect as CStereoWidening + // even the native CStereoWideningUtility has an empty CStereoWidening + iAudioEffect = &(iStereoWideningUtility->StereoWidening()); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSAudioVirtualizerControl::DeallocateControl() +{ + if (iStereoWideningUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSAudioVirtualizerControl::DeallocateControl"); + + // Delete the Effect API class. + TRAPD(err, iStereoWideningUtility->DisableStereoWideningL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Utility + // class is already created, that situation can be discarded here. + } + + delete iStereoWideningUtility; + iStereoWideningUtility = NULL; + } +} + +const TDesC& CAMMSAudioVirtualizerControl::ClassName() const +{ + return KAMMSAudioVirtualizerControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSAudioVirtualizerControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSAudioVirtualizerControl::CAMMSAudioVirtualizerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSAudioVirtualizerControl::CAMMSAudioVirtualizerControl( + CMMAPlayer* aPlayer) + : CAMMSEffectControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsbasedistanceattenuationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsbasedistanceattenuationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsbasedistanceattenuationcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + + +// Destructor +CAMMSBaseDistanceAttenuationControl::~CAMMSBaseDistanceAttenuationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSBaseDistanceAttenuationControl::~CAMMSBaseDistanceAttenuationControl"); + +} + +// ----------------------------------------------------------------------------- +// CAMMSBaseDistanceAttenuationControl::CAMMSBaseDistanceAttenuationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSBaseDistanceAttenuationControl::CAMMSBaseDistanceAttenuationControl( + CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsbaseequalizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsbaseequalizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsbaseequalizercontrol.h" + + + +// ============================ MEMBER FUNCTIONS =============================== + + +// Destructor +CAMMSBaseEqualizerControl::~CAMMSBaseEqualizerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSBaseEqualizerControl::~CAMMSBaseEqualizerControl"); + +} + +// ----------------------------------------------------------------------------- +// CAMMSBaseEqualizerControl::CAMMSBaseEqualizerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSBaseEqualizerControl::CAMMSBaseEqualizerControl(CMMAPlayer* aPlayer) + : CAMMSEffectControl(aPlayer) +{ +} + +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsbasereverbcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsbasereverbcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsbasereverbcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSBaseReverbControl::~CAMMSBaseReverbControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSBaseReverbControl::~CAMMSBaseReverbControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSBaseReverbControl::GetEnvironmentalReverbUtilityL +// Returns the environmental reverb utility. +// ----------------------------------------------------------------------------- +void CAMMSBaseReverbControl::GetEnvironmentalReverbUtilityL( + CEnvironmentalReverbUtility** /*aEnvironmentalReverbUtility*/) +{ + // Derived Class will implement this method +} +// only require if platform support EMC +#ifdef RD_JAVA_HTTP_EMC_ENABLED +MReverbControl* CAMMSBaseReverbControl::GetReverbControlL() +{ + // derived class will implement this method + return (MReverbControl*)NULL; +} +#endif +// ----------------------------------------------------------------------------- +// CAMMSBaseReverbControl::CAMMSBaseReverbControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSBaseReverbControl::CAMMSBaseReverbControl(CMMAPlayer* aPlayer) + : CAMMSEffectControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsbasereverbsourcecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsbasereverbsourcecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect reverb source. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsbasereverbsourcecontrol.h" + + + +// ============================ MEMBER FUNCTIONS =============================== + + +// Destructor +CAMMSBaseReverbSourceControl::~CAMMSBaseReverbSourceControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSBaseReverbSourceControl::~CAMMSBaseReverbSourceControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSBaseReverbSourceControl::CAMMSBaseReverbSourceControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSBaseReverbSourceControl::CAMMSBaseReverbSourceControl( + CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammscontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammscontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for AMMS controls. +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cammscontrol.h" +#include "cammscustomcommandutility.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSControl::~CAMMSControl() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSControl::CreateCustomCommandUtilityL +// Creates a custom command utility. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +CCustomCommandUtility* CAMMSControl::CreateCustomCommandUtilityL() +{ + CCustomCommandUtility* customCommandUtility = NULL; + + if (iPlayer->Type() == KMMAMIDIPlayer) + { + CMMAMIDIPlayer* mmaMIDIPlayer = + reinterpret_cast< CMMAMIDIPlayer* >(iPlayer); + + CMidiClientUtility* midiClientUtility = mmaMIDIPlayer->MidiClient(); + customCommandUtility = + CCustomCommandUtility::NewL(*midiClientUtility); + } + else if (iPlayer->Type() == KMMAAudioPlayer) + { + CMMAAudioPlayer* mmaAudioPlayer = + reinterpret_cast< CMMAAudioPlayer* >(iPlayer); + + RMMFController& mmfController = mmaAudioPlayer->Controller(); + customCommandUtility = + CAMMSCustomCommandUtility::NewL(mmfController); + } + else + { + // Player is KMMAEMCAudioPlayer or of other type + // Do nothing + } + + return customCommandUtility; +} + +// ----------------------------------------------------------------------------- +// CAMMSControl::PublicClassName +// Returns public class name. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSControl::PublicClassName() const +{ + // Return null descriptor so that the control name is not visible in MMA. + return KNullDesC; +} + +// ----------------------------------------------------------------------------- +// CAMMSControl::PrepareControlL +// Virtual function to prepare Controls. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSControl::PrepareControlL() +{ + // Empty implementation, the Controls that need preparing overwrite this +} + +// ----------------------------------------------------------------------------- +// CAMMSControl::DeallocateControl +// Virtual function to deallocate Controls. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSControl::DeallocateControl() +{ + // Empty implementation, the Controls that need deallocating overwrite this +} + +// ----------------------------------------------------------------------------- +// CAMMSControl::CAMMSControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSControl::CAMMSControl(CMMAPlayer* aPlayer) + : iPlayer(aPlayer) +{ +} + +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammscustomcommandutility.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammscustomcommandutility.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,147 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Custom command utility class for AMMS custom commands. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammscustomcommandutility.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSCustomCommandUtility::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSCustomCommandUtility* CAMMSCustomCommandUtility::NewL( + RMMFController& aMMFController) +{ + CAMMSCustomCommandUtility* self = NewLC(aMMFController); + CleanupStack::Pop(self); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSCustomCommandUtility::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSCustomCommandUtility* CAMMSCustomCommandUtility::NewLC( + RMMFController& aMMFController) +{ + CAMMSCustomCommandUtility* self = + new(ELeave) CAMMSCustomCommandUtility(aMMFController); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSCustomCommandUtility::~CAMMSCustomCommandUtility() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSCustomCommandUtility::~CAMMSCustomCommandUtility"); +} + +TInt CAMMSCustomCommandUtility::CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom) +{ + LOG1( EJavaAMMS, EInfo, + "AMMS::CAMMSCustomCommandUtility::CustomCommandSync(1) function: %d", + aFunction); + + // In the first message (ECibGetBuilder) the aDataTo1 is null, + // but in the second message (ECibBuild) it should contain the interface ID + + return iMMFController.CustomCommandSync( + aDestination, + aFunction, + aDataTo1, + aDataTo2, + aDataFrom); +} + +TInt CAMMSCustomCommandUtility::CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2) +{ + LOG1( EJavaAMMS, EInfo, + "AMMS::CAMMSCustomCommandUtility::CustomCommandSync(2) function: %d", + aFunction); + return iMMFController.CustomCommandSync( + aDestination, + aFunction, + aDataTo1, + aDataTo2); +} + +void CAMMSCustomCommandUtility::CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom, + TRequestStatus& aStatus) +{ + LOG1( EJavaAMMS, EInfo, + "AMMS::CAMMSCustomCommandUtility::CustomCommandAsync(1) function: %d", + aFunction); + iMMFController.CustomCommandAsync( + aDestination, + aFunction, + aDataTo1, + aDataTo2, + aDataFrom, + aStatus); +} + +void CAMMSCustomCommandUtility::CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TRequestStatus& aStatus) +{ + LOG1( EJavaAMMS, EInfo, + "AMMS::CAMMSCustomCommandUtility::CustomCommandAsync(2) function: %d", + aFunction); + iMMFController.CustomCommandAsync( + aDestination, + aFunction, + aDataTo1, + aDataTo2, + aStatus); +} + +// ----------------------------------------------------------------------------- +// CCAMMSCustomCommandUtility::CAMMSCustomCommandUtility +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSCustomCommandUtility::CAMMSCustomCommandUtility( + RMMFController& aMMFController): + iMMFController(aMMFController) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsdistanceattenuationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsdistanceattenuationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls how the sound is attenuated with its distance. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsdistanceattenuationcontrol.h" + +// CONSTANTS +namespace +{ +const TInt KAMMSRoomRollOffFactor = 0; // The logical default value set to 0 +// Rolloff factor 1000 in AMMS is 100 in Effect API +const TInt KAMMSRolloffDivider = 10; + +#ifdef _DEBUG +const TInt KAMMSMinDistance = 1; +const TInt KAMMSMinRollofFactor = 0; +#endif // _DEBUG +} + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSDistanceAttenuationControl* CAMMSDistanceAttenuationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSDistanceAttenuationControl* self = + new(ELeave)CAMMSDistanceAttenuationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSDistanceAttenuationControl::~CAMMSDistanceAttenuationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDistanceAttenuationControl::~CAMMSDistanceAttenuationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete iDistanceAttenuation; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControl::SetParametersL +// Sets all the 3D audio distance attenuation parameters simultaneously. +// ----------------------------------------------------------------------------- +// +void CAMMSDistanceAttenuationControl::SetParametersL( + TInt aMinDistance, + TInt aMaxDistance, + TBool aMuteAfterMax, + TInt aRolloffFactor) +{ + // Check in debug build that parameters are within valid range. + __ASSERT_DEBUG( + (aMaxDistance > aMinDistance) && + (aMinDistance >= KAMMSMinDistance) && + (aMaxDistance >= KAMMSMinDistance) && + (aRolloffFactor >= KAMMSMinRollofFactor), + User::Invariant()); + + // NOTE: Effect API uses hundreths (100 corresponds to 1.00), + // but JSR234 uses thousandths (1000 represents a rolloff factor of 1.0) + // + LOG4( EJavaMMAPI, EInfo, "AMMS::CAMMSDistanceAttenuationControl::SetParametersL %d, %d, %d, %d", + aMinDistance, aMaxDistance, aMuteAfterMax, aRolloffFactor); + + TInt convertedRolloffFactor = aRolloffFactor / KAMMSRolloffDivider; + + iDistanceAttenuation->SetDistanceAttenuationL(aMinDistance, aMaxDistance, + aMuteAfterMax, convertedRolloffFactor, KAMMSRoomRollOffFactor); + + // Apply updated settings to Effect API. + iDistanceAttenuation->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSDistanceAttenuationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iDistanceAttenuation) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDistanceAttenuationControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Effect API takes the ownership of customCommandUtility. + iDistanceAttenuation = CDistanceAttenuation::NewL( + customCommandUtility); + + // Enable the Effect API Control + iDistanceAttenuation->EnableL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSDistanceAttenuationControl::DeallocateControl() +{ + if (iDistanceAttenuation) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDistanceAttenuationControl::DeallocateControl"); + + // Disable the Effect API Control + TRAPD(err, iDistanceAttenuation->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class (it deletes CustomCommandUtility) + delete iDistanceAttenuation; + iDistanceAttenuation = NULL; + } +} + +const TDesC& CAMMSDistanceAttenuationControl::ClassName() const +{ + return KAMMSDistanceAttenuationControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSDistanceAttenuationControl::CAMMSDistanceAttenuationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSDistanceAttenuationControl::CAMMSDistanceAttenuationControl( + CMMAPlayer* aPlayer) + : CAMMSBaseDistanceAttenuationControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsdopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsdopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,140 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an effect called Doppler. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include "cammsdopplercontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSDopplerControl::~CAMMSDopplerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::~CAMMSDopplerControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::SetEnabled +// Specifies if this Doppler effect is active or ignored. +// ----------------------------------------------------------------------------- +// +void CAMMSDopplerControl::SetEnabledL(TBool aDopplerEnabled) +{ + if (aDopplerEnabled) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::SetEnabledL(true)"); + iDopplerEffect->EnableL(); + } + else + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::SetEnabledL(false)"); + iDopplerEffect->DisableL(); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::Enabled +// Returns whether this Doppler effect is currently active. +// ----------------------------------------------------------------------------- +// +TBool CAMMSDopplerControl::Enabled() +{ + return iDopplerEffect->IsEnabled(); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::SetVelocityCartesianL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSDopplerControl::SetVelocityCartesianL( + TInt aX, + TInt aY, + TInt aZ) +{ + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::SetVelocityCartesianL: X=%d, Y=%d, Z=%d", + aX, aY, aZ); + + iDopplerEffect->SetCartesianVelocityL(aX, aY, aZ); + + // Apply updated settings to Effect API. + iDopplerEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::VelocityCartesian +// Returns the current velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSDopplerControl::VelocityCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Get the velocity's cartesian settings + // aX, aY and aZ are velocities in format mm/s + + iDopplerEffect->CartesianVelocity( + (TInt32&)aX, (TInt32&)aY, (TInt32&)aZ); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::SetVelocitySphericalL +// Sets the velocity, used in calculations for the Doppler effect. +// ----------------------------------------------------------------------------- +// +void CAMMSDopplerControl::SetVelocitySphericalL( + TInt aAzimuth, + TInt aElevation, + TInt aRadius) +{ + // Parameters are thousandths of radians + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::SetVelocitySphericalL %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedElevation = (TInt32)(aElevation * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSDopplerControl::SetVelocitySphericalL %d, %d", + convertedAzimuth, convertedElevation); + + iDopplerEffect->SetSphericalVelocityL( + convertedAzimuth, convertedElevation, aRadius); + + // Apply updated settings to Effect API. + iDopplerEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSDopplerControl::CAMMSDopplerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSDopplerControl::CAMMSDopplerControl(CMMAPlayer* aPlayer): + CAMMSControl(aPlayer) +{ +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammseffectcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammseffectcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls an abstract filter with various preset settings. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammseffectcontrol.h" +#include "cammseffectcontrolgroup.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSEffectControl::~CAMMSEffectControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControl::~CAMMSEffectControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::SetEnforcedL +// Enforces the effect to be in use. +// ----------------------------------------------------------------------------- +// +void CAMMSEffectControl::SetEnforcedL(TBool aEnforced) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControl:SetEnforcedL"); + // Indicate the effect is to be enforced or not. ETrue = Enforced. + + iAudioEffect->EnforceL(aEnforced); + + ApplySettingsL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::Enforced +// Returns the current enforced setting of the effect. +// ----------------------------------------------------------------------------- +// +TBool CAMMSEffectControl::Enforced() +{ + // Returns ETrue if the effect is enforced, EFalse if not enforced. + return iAudioEffect->IsEnforced(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::SetScopeL +// Sets the scope of the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEffectControl::SetScopeL(TInt aScope) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControl:SetScopeL"); + // Check in debug build that scope is the only supported scope (LIVE_ONLY). + __ASSERT_DEBUG( + (aScope == CAMMSEffectControlGroup::EScopeLiveOnly), + User::Invariant()); + // Just to suppress warning in release build + (void)aScope; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::Scope +// Returns the scope in which the effect is present. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEffectControl::Scope() +{ + // For now only the (LIVE_ONLY) scope is supported. + return CAMMSEffectControlGroup::EScopeLiveOnly; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::ApplySettingsL +// Apply changed settings if Effect is in enabled state. +// ----------------------------------------------------------------------------- +void CAMMSEffectControl::ApplySettingsL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControl:ApplySettingsL called, checking state"); + if (iAudioEffect->IsEnabled()) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEffectControl:ApplySettingsL calling ApplyL"); + iAudioEffect->ApplyL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEffectControl::ConstructL() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectControl::CAMMSEffectControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEffectControl::CAMMSEffectControl(CMMAPlayer* aPlayer): + CAMMSControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsequalizercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsequalizercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,365 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the equalization settings of a Player. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsequalizercontrol.h" + + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEqualizerControl* CAMMSEqualizerControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSEqualizerControl* self = + new(ELeave) CAMMSEqualizerControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSEqualizerControl::~CAMMSEqualizerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::~CAMMSEqualizerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete iEqualizerUtility; + delete iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::BandLevelL +// Gets the gain set for the given equalizer band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::BandLevelL(TInt aBand) +{ + // if aBand is out of range the method must leave with KErrArgument. + if (aBand < 0 || aBand > (NumberOfBands() - 1)) + { + User::Leave(KErrArgument); + } + + // Returns the band level in mB for the specified band + // AudioEqualizerBase: TInt32 BandLevel( TUint8 aBand ) const; + return ((CAudioEqualizer*)iAudioEffect)->BandLevel( + (TUint8)(aBand + KAMMSBandOffset)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::MaxBandLevel +// Returns the maximum band level supported. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::MaxBandLevel() +{ + // Get the dB range in mB for the equalizer. + + TInt32 minLevel = 0; + TInt32 maxLevel = 0; + ((CAudioEqualizer*)iAudioEffect)->DbLevelLimits(minLevel, maxLevel); + + return maxLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::MinBandLevel +// Returns the minimum band level supported. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::MinBandLevel() +{ + // Get the dB range in mB for the equalizer. + + TInt32 minLevel = 0; + TInt32 maxLevel = 0; + ((CAudioEqualizer*)iAudioEffect)->DbLevelLimits(minLevel, maxLevel); + + return minLevel; +} + + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::BandWidth +// Returns the band width in Hz for the specified band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::BandWidth(TInt aBand) +{ + return ((CAudioEqualizer*)iAudioEffect)->BandWidth( + (TUint8)(aBand + KAMMSBandOffset)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::CenterFrequency +// Returns the center frequency in Hz for a given band. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::CenterFrequency(TInt aBand) +{ + return ((CAudioEqualizer*)iAudioEffect)->CenterFrequency( + (TUint8)(aBand + KAMMSBandOffset)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::CrossoverFrequency +// Returns the cross-over frequency between the given frequency. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::CrossoverFrequency(TInt aBand) +{ + return ((CAudioEqualizer*)iAudioEffect)->CrossoverFrequency( + (TUint8)(aBand + KAMMSBandOffset)); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::NumberOfBands +// Gets the number of frequency bands that the equalizer supports. +// ----------------------------------------------------------------------------- +// +TInt CAMMSEqualizerControl::NumberOfBands() +{ + // Returns the number of equalizer bands. + // AudioEqualizerBase: TUint8 NumberOfBands() const; + return ((CAudioEqualizer*)iAudioEffect)->NumberOfBands(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::SetBandLevelL +// Sets the given equalizer band to the given gain value. +// ----------------------------------------------------------------------------- +// +void CAMMSEqualizerControl::SetBandLevelL( + TInt aLevel, + TInt aBand) +{ + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::SetBandLevelL: level=%d, band=%d", + aLevel, aBand); + + // If aBand or aLevel is out of valid range the method must leave + // with KErrArgument. + if (aBand < 0 || + aBand > (NumberOfBands() - 1) || + aLevel < MinBandLevel() || + aLevel > MaxBandLevel()) + { + User::Leave(KErrArgument); + } + + // Sets the equalizer band level value in mB, ranging from Min to Max + ((CAudioEqualizer*)iAudioEffect)->SetBandLevelL( + (TInt8)(aBand + KAMMSBandOffset), aLevel); + + ApplySettingsL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSEqualizerControl::SetPresetL(const TDesC& aPreset) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::SetPresetL \"%S\"", aPreset.Ptr()); + + const CDesCArray& presetNames = PresetNamesL(); + + TInt presetPosition = 0; + TInt findPreset = presetNames.Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + // This supposes that the indexing of the presets starts at zero. + iEqualizerUtility->GetPresetL(presetPosition); + + // Set the base class audio effect as the new CAudioEqualizer + // that is set with the previous GetPresetL method. + iAudioEffect = &(iEqualizerUtility->Equalizer()); + iCurrentPreset = presetPosition; + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::SetPresetL \"%S\" GetPresetL OK", + aPreset.Ptr()); + } + else + { + User::Leave(KErrArgument); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSEqualizerControl::PresetNamesL() +{ + // Returns an array of all preset names (pre-defined and user-defined). + // The pre-defined presets are in the beginning of the list. + + TArray< TEfAudioEqualizerUtilityPreset > presetNames = + iEqualizerUtility->Presets(); + + // Before appending the preset names, reset the member array + iPresetNames->Reset(); + for (TInt i = 0; i < presetNames.Count(); i++) + { + iPresetNames->AppendL(presetNames[ i ].iPresetName); + } + + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSEqualizerControl::PresetL() +{ + //if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + else + { + // Retrieves a Preset with the given index from the Central Repository + // AudioEqualizerUtility.h: + // const TDesC& GetPresetL(TInt aPresetIndex) + return iEqualizerUtility->GetPresetL(iCurrentPreset); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSEqualizerControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect + // Instead of using CAudioEffectBase: virtual void EnableL(), + // use the derived effect's (=preset's) ApplyL which calls EnableL. + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::SetEnabledL(true), calling ApplyL"); + iAudioEffect->ApplyL(); + } + else + { + // Disable the effect + // Instead of using CAudioEffectBase: virtual void DisableL(), + // use the utility class DisableEqualizerL, + // which calls DisableL for the correct preset + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::SetEnabledL(false), calling DisableEqualizerL"); + iEqualizerUtility->DisableEqualizerL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEqualizerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iEqualizerUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Effect API takes the ownership of customCommandUtility. + iEqualizerUtility = CAudioEqualizerUtility::NewL( + customCommandUtility); + + // Set the base class audio effect as CAudioEqualizer, + // even the native AudioEqualizerUtility has an empty CAudioEqualizer + iAudioEffect = &(iEqualizerUtility->Equalizer()); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSEqualizerControl::DeallocateControl() +{ + if (iEqualizerUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSEqualizerControl::DeallocateControlL"); + + // Delete the Effect API class. + TRAPD(err, iEqualizerUtility->DisableEqualizerL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Utility + // class is already created, that situation can be discarded here. + } + + delete iEqualizerUtility; + iEqualizerUtility = NULL; + } +} + +const TDesC& CAMMSEqualizerControl::ClassName() const +{ + return KAMMSEqualizerControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEqualizerControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSEqualizerControl::CAMMSEqualizerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEqualizerControl::CAMMSEqualizerControl(CMMAPlayer* aPlayer) + : CAMMSBaseEqualizerControl(aPlayer) +{ +} + +// End of File + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammslocationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammslocationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,121 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of an object. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include "cammslocationcontrol.h" + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMinRadius = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSLocationControl::~CAMMSLocationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSLocationControl::~CAMMSLocationControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControl::SetLocationCartesianL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSLocationControl::SetLocationCartesianL( + TInt& aX, + TInt& aY, + TInt& aZ) +{ + // Sets the cartesian coordinates for the listener/source location. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSLocationControl::SetLocationCartesianL: %d, %d, %d", + aX, aY, aZ); + + iLocationEffect->SetLocationCartesianL( + (TInt32&)aX, (TInt32&)aY, (TInt32&)aZ); + + // Apply updated settings to Effect API. + iLocationEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControl::LocationCartesian +// Gets the coordinates of the current location. +// ----------------------------------------------------------------------------- +void CAMMSLocationControl::LocationCartesian( + TInt& aX, TInt& aY, TInt& aZ) +{ + // Gets the cartesian coordinates for the location of the listener position. + // The coordinates of the positions are in millimeters. + + iLocationEffect->LocationCartesian( + (TInt32&)aX, (TInt32&)aY, (TInt32&)aZ); +} + + +// ----------------------------------------------------------------------------- +// CAMMSLocationControl::SetLocationSphericalL +// Moves the object to the new location. +// ----------------------------------------------------------------------------- +void CAMMSLocationControl::SetLocationSphericalL( + TInt& aAzimuth, + TInt& aElevation, + TInt& aRadius) +{ + // Check in debug build that aRadius is within valid range. + __ASSERT_DEBUG(aRadius >= KAMMSMinRadius, User::Invariant()); + + // Sets the spherical coordinates for the location of the listener position. + // The parameters are thousandths of radians + // + // NOTE: Effect API uses thousandths of radians for aAzimuth and aElevation, + // but JSR234 uses degrees. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSLocationControl::SetLocationSphericalL: %d, %d, %d", + aAzimuth, aElevation, aRadius); + + TInt32 convertedAzimuth = (TInt32)(aAzimuth * + KDegToRad * 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedElevation = (TInt32)(aElevation * + KDegToRad * 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSLocationControl::SetLocationSphericalL: %d, %d", + convertedAzimuth, convertedElevation); + + iLocationEffect->SetLocationSphericalL( + convertedAzimuth, convertedElevation, (TInt32&)aRadius); + + // Apply updated settings to Effect API. + iLocationEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSLocationControl::CAMMSLocationControl +// C++ constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSLocationControl::CAMMSLocationControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsorientationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsorientationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,142 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of an object. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include "cammsorientationcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSOrientationControl::~CAMMSOrientationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSOrientationControl::~CAMMSOrientationControl"); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControl::SetOrientationL +// Turns the object to the new orientation. +// ----------------------------------------------------------------------------- +void CAMMSOrientationControl::SetOrientationL( + TInt aHeading, + TInt aPitch, + TInt aRoll) +{ + // Sets the Heading, Pitch, Roll values for the source/listener orientation. + // Parameters are given in thousandths of radians. + // SourceOrientationBase/ListenerLocationBase : + // + // NOTE: Effect API uses thousandths of radians for all three parameters, + // but JSR234 uses degrees. + // + // From e32Math.h: The multiplying factor to convert degrees to radians. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSOrientationControl::SetOrientationL: %d, %d, %d", + aHeading, aPitch, aRoll); + + TInt32 convertedHeading = (TInt32)(aHeading * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedPitch = (TInt32)(aPitch * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + TInt32 convertedRoll = (TInt32)(aRoll * KDegToRad * + 1000); // CSI: 47 Effect API uses thousands of radians # + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSOrientationControl::SetOrientationL: %d, %d, %d", + convertedHeading, convertedPitch, convertedRoll); + + iOrientationEffect->SetOrientationL( + convertedHeading, convertedPitch, convertedRoll); + + // Apply updated settings to Effect API. + iOrientationEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControl::SetOrientationL +// Turns the object to the new orientation. +// ----------------------------------------------------------------------------- +void CAMMSOrientationControl::SetOrientationL( + TInt aFrontX, TInt aFrontY, TInt aFrontZ, + TInt aAboveX, TInt aAboveY, TInt aAboveZ) +{ + // Check in debug build that parameters are not zero vectors. + __ASSERT_DEBUG(((aFrontX != 0) || + (aFrontY != 0) || + (aFrontZ != 0)) && + ((aAboveX != 0) || + (aAboveY != 0) || + (aAboveZ != 0)), + User::Invariant()); + + // Check in debug build that vectors are not parallel. + // Two vectors are parallel if their cross product is zero vector. + // Cross product of vectors a1*i + a2*j + a3*k and b1*i + b2*j + b3*k : + // (a2*b3 - a3*b2)i + (a3*b1 - a1*b3)j + (a1*b2 - a2*b1)k + __ASSERT_DEBUG( + ((aFrontY * aAboveZ) - (aFrontZ * aAboveY) != 0) || + ((aFrontZ * aAboveX) - (aFrontX * aAboveZ) != 0) || + ((aFrontX * aAboveY) - (aFrontY * aAboveX) != 0), + User::Invariant()); + + // Sets the Front and Above vectors for the orientation of the source/listener. + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSOrientationControl::SetOrientationL: Front %d, %d, %d", + aFrontX, aFrontY, aFrontZ); + + LOG3( EJavaAMMS, EInfo, "AMMS::CAMMSOrientationControl::SetOrientationL: Above %d, %d, %d", + aAboveX, aAboveY, aAboveZ); + + iOrientationEffect->SetOrientationVectorsL( + (TInt32)aFrontX, (TInt32)aFrontY, (TInt32)aFrontZ, + (TInt32)aAboveX, (TInt32)aAboveY, (TInt32)aAboveZ); + + // Apply updated settings to Effect API. + iOrientationEffect->ApplyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControl::OrientationVectors +// Gets the orientation of the object using two vectors. +// ----------------------------------------------------------------------------- +void CAMMSOrientationControl::OrientationVectors( + TInt& aFrontX, TInt& aFrontY, TInt& aFrontZ, + TInt& aAboveX, TInt& aAboveY, TInt& aAboveZ) +{ + // Gets the orientation of the source. + + iOrientationEffect->OrientationVectors( + (TInt32&)aFrontX, (TInt32&)aFrontY, (TInt32&)aFrontZ, + (TInt32&)aAboveX, (TInt32&)aAboveY, (TInt32&)aAboveZ); +} + +// ----------------------------------------------------------------------------- +// CAMMSOrientationControl::CAMMSOrientationControl +// C++ constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSOrientationControl::CAMMSOrientationControl(CMMAPlayer* aPlayer) + : CAMMSControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsplayerbuilder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsplayerbuilder.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for AMMS player builders. +* +*/ + + + +// INCLUDE FILES +#include "cammsplayerbuilder.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSPlayerBuilder::~CAMMSPlayerBuilder() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilder::CAMMSPlayerBuilder +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPlayerBuilder::CAMMSPlayerBuilder() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsplayerbuildergroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsplayerbuildergroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,109 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder group for adding players. +* +*/ + + + +// INCLUDE FILES +#include "cammsplayerbuildergroup.h" + +// CONSTANTS +const TInt KDefaultGranularity = 1; + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPlayerBuilderGroup* CAMMSPlayerBuilderGroup::NewL() +{ + CAMMSPlayerBuilderGroup* self = NewLC(); + CleanupStack::Pop(self); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSPlayerBuilderGroup* CAMMSPlayerBuilderGroup::NewLC() +{ + CAMMSPlayerBuilderGroup* self = new(ELeave) CAMMSPlayerBuilderGroup(); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSPlayerBuilderGroup::~CAMMSPlayerBuilderGroup() +{ + if (iPlayerBuilders) + { + iPlayerBuilders->ResetAndDestroy(); + } + delete iPlayerBuilders; +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::PreparePlayerL +// Performs PreparePlayerL for every player builder in the array. +// ----------------------------------------------------------------------------- +void CAMMSPlayerBuilderGroup::PreparePlayerL(CMMAPlayer* aPlayer) +{ + TInt builderCount = iPlayerBuilders->Count(); + for (TInt i = 0; i < builderCount; i++) + { + iPlayerBuilders->At(i)->PreparePlayerL(aPlayer); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::AddBuilderAndPopL +// Adds a player builder to the array. +// ----------------------------------------------------------------------------- +// +void CAMMSPlayerBuilderGroup::AddBuilderAndPopL( + CAMMSPlayerBuilder* aPlayerBuilder) +{ + iPlayerBuilders->AppendL(aPlayerBuilder); + CleanupStack::Pop(aPlayerBuilder); +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSPlayerBuilderGroup::ConstructL() +{ + iPlayerBuilders = new(ELeave) CArrayPtrSeg< CAMMSPlayerBuilder > + (KDefaultGranularity); +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerBuilderGroup::CAMMSPlayerBuilderGroup +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSPlayerBuilderGroup::CAMMSPlayerBuilderGroup() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsreverbcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsreverbcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,390 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect called reverb. +* +*/ + + +// INCLUDE FILES +#include "cammsreverbcontrol.h" +#include +#include + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxReverbLevel = 0; +const TInt KAMMSMinReverbTime = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSReverbControl* CAMMSReverbControl::NewLC(CMMAPlayer* aPlayer) +{ + CAMMSReverbControl* self = new(ELeave) CAMMSReverbControl(aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSReverbControl::~CAMMSReverbControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::~CAMMSReverbControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete iReverbUtility; + delete iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::SetReverbLevelL +// Sets the gain level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::SetReverbLevelL(TInt aLevel) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbLevelL: %d", aLevel); + + // Check in debug build that aLevel is within valid range. + __ASSERT_DEBUG(aLevel <= KAMMSMaxReverbLevel, User::Invariant()); + + CEnvironmentalReverb* reverbEffect = (CEnvironmentalReverb*)iAudioEffect; + + TInt roomLevel = reverbEffect->RoomLevel(); + TInt tempChange = aLevel - reverbEffect->ReflectionsLevel() - roomLevel; + + // Sets the reverb reflections level in mB + reverbEffect->SetReflectionsLevelL(aLevel - roomLevel); + + + // Calculate native reverb level. + TInt reverbLevel = reverbEffect->ReverbLevel() + tempChange; + + // Ensure that the level is within the limits. + + TInt32 minLevel = 0; + TInt32 maxLevel = 0; + reverbEffect->ReverbLevelRange(minLevel, maxLevel); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbLevelL: orig %d", + reverbLevel); + + reverbLevel = Min(reverbLevel, maxLevel); + reverbLevel = Max(reverbLevel, minLevel); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbLevelL: set %d", + reverbLevel); + + // Sets the reverb level in mB + reverbEffect->SetReverbLevelL(reverbLevel); + + // Apply can be called for Reverb, as it does not internally include EnableL + // unlike in case of Equalizer or StereoWidening + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbLevelL calling ApplyL"); + reverbEffect->ApplyL(); + + // Return the value that was used in setting the reverb + return aLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::SetReverbTimeL +// Sets the reverberation time of the reverb. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbControl::SetReverbTimeL(TInt aTime) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbTimeL: %d", aTime); + + // Check in debug build that aTime is within valid range. + __ASSERT_DEBUG(aTime >= KAMMSMinReverbTime, User::Invariant()); + + // Sets the decay time in milliseconds + ((CEnvironmentalReverb*)iAudioEffect)->SetDecayTimeL(aTime); + + // Apply can be called for Reverb, as it does not internally include EnableL + // unlike in case of Equalizer or StereoWidening + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetReverbTimeL calling ApplyL"); + iAudioEffect->ApplyL(); + +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::ReverbLevel +// Gets the gain level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::ReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::ReverbLevel called"); + // Return here (reflections level + room level) + return (((CEnvironmentalReverb*)iAudioEffect)->ReflectionsLevel() + + ((CEnvironmentalReverb*)iAudioEffect)->RoomLevel()); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::ReverbTime +// Gets the reverberation time. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::ReverbTime() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::ReverbTime called"); + + return (((CEnvironmentalReverb*)iAudioEffect)->DecayTime()); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::MinReverbLevel +// Gets the minimum level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::MinReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::MinReverbLevel called"); + + TInt32 minLevel; + TInt32 maxLevel; + ((CEnvironmentalReverb*)iAudioEffect)->ReverbLevelRange( + minLevel, maxLevel); + + return minLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::MaxReverbLevel +// Gets the maximum level of the reverberation. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::MaxReverbLevel() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::MaxReverbLevel called"); + + TInt32 minLevel; + TInt32 maxLevel; + ((CEnvironmentalReverb*)iAudioEffect)->ReverbLevelRange( + minLevel, maxLevel); + + return maxLevel; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::CurrentPresetIndex +// Gets current preset index. +// ----------------------------------------------------------------------------- +// +TInt CAMMSReverbControl::CurrentPresetIndex() +{ + return iCurrentPreset; +} +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::SetPresetL +// Sets the effect according to the given preset. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbControl::SetPresetL(const TDesC& aPreset) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetPresetL \"%S\"", aPreset.Ptr()); + + const CDesCArray& presetNames = PresetNamesL(); + + TInt presetPosition = 0; + TInt findPreset = presetNames.Find(aPreset, presetPosition); + if (findPreset == 0) // Find returns zero, if a matching element is found. + { + // This supposes that the indexing of the presets starts at zero. + iReverbUtility->GetPresetL(presetPosition); + + // Set the base class audio effect as the new CEnvironmentalReverb + // that is set with the previous GetPresetL method. + iAudioEffect = &(iReverbUtility->EnvironmentalReverb()); + iCurrentPreset = presetPosition; + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetPresetL \"%S\" GetPresetL OK", + aPreset.Ptr()); + } + else + { + User::Leave(KErrArgument); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::PresetNamesL +// Gets the available preset names. +// ----------------------------------------------------------------------------- +// +const CDesCArray& CAMMSReverbControl::PresetNamesL() +{ + // Returns an array of all preset names (pre-defined and user-defined). + // The pre-defined presets are in the beginning of the list. + TArray< TEfEnvironmentalReverbUtilityPreset > presetNames = + iReverbUtility->Presets(); + + // Before appending the preset names, reset the member array + iPresetNames->Reset(); + for (TInt i = 0; i < presetNames.Count(); i++) + { + iPresetNames->AppendL(presetNames[ i ].iPresetName); + } + + return *iPresetNames; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::PresetL +// Gets the current preset. +// ----------------------------------------------------------------------------- +// +const TDesC& CAMMSReverbControl::PresetL() +{ + //if no preset is set, return null + if (iCurrentPreset < 0) + { + return KNullDesC; + } + else + { + // Retrieves a Preset with the given index from the Central Repository + return iReverbUtility->GetPresetL(iCurrentPreset); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::SetEnabledL +// Enables/disables the effect. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbControl::SetEnabledL(TBool aEnable) +{ + if (aEnable) + { + // Enable the effect + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetEnabledL(true), calling EnableL"); + iAudioEffect->EnableL(); + } + else + { + // Disable the effect + // Instead of using CAudioEffectBase: virtual void DisableL(), + // use the utility class DisableEnvironmentalReverbL, + // which calls DisableL for the correct preset + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::SetEnabledL(false), calling DisableEnvironmentalReverbL"); + iReverbUtility->DisableEnvironmentalReverbL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iReverbUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Effect API takes the ownership of customCommandUtility. + iReverbUtility = CEnvironmentalReverbUtility::NewL( + customCommandUtility); + + SetPresetL(KAMMSDefaultReverbPreset); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbControl::DeallocateControl() +{ + if (iReverbUtility) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::DeallocateControlL"); + + // Delete the Effect API class. + TRAPD(err, iReverbUtility->DisableEnvironmentalReverbL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Utility + // class is already created, that situation can be discarded here. + } + + delete iReverbUtility; + iReverbUtility = NULL; + + // Set current preset to a negative value to state it has not been set + iCurrentPreset = -1; + } +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::GetEnvironmentalReverbUtilityL +// Returns the environmental reverb utility. +// ----------------------------------------------------------------------------- +void CAMMSReverbControl::GetEnvironmentalReverbUtilityL( + CEnvironmentalReverbUtility** aEnvironmentalReverbUtility) +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::GetEnvironmentalReverbUtilityL"); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbControl::GetEnvironmentalReverbUtilityL CurrentPreset = %d",CurrentPresetIndex()); + *aEnvironmentalReverbUtility = iReverbUtility; +} + +const TDesC& CAMMSReverbControl::ClassName() const +{ + return KAMMSReverbControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSReverbControl::ConstructL() +{ + // Create array for preset names + iPresetNames = new(ELeave) CDesCArrayFlat(1); + + // Set current preset to a negative value as it is not set yet + iCurrentPreset = -1; + + CAMMSEffectControl::ConstructL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbControl::CAMMSReverbControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSReverbControl::CAMMSReverbControl(CMMAPlayer* aPlayer) + : CAMMSBaseReverbControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsreverbsourcecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsreverbsourcecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,199 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the settings of an audio effect reverb source. +* +*/ + + +// INCLUDE FILES +#include +#include "cammsreverbsourcecontrol.h" +#include "cammsbasereverbcontrol.h" + +// CONSTANTS +const TInt KAMMSDisconnectReverbSource = 2147483647; // From JSR-234 + + +#ifdef _DEBUG +const TInt KAMMSMaxRoomLevel = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSReverbSourceControl* CAMMSReverbSourceControl::NewLC( + CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aReverbControl) +{ + CAMMSReverbSourceControl* self = + new(ELeave)CAMMSReverbSourceControl(aPlayer, aReverbControl); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSReverbSourceControl::~CAMMSReverbSourceControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::~CAMMSReverbSourceControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete iReverbSource; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControl::SetRoomLevelL +// Sets the object specific level for the reverberant sound. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbSourceControl::SetRoomLevelL(TInt aLevel) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL +: %d", aLevel); + + // Check in debug build that aLevel is within valid range. + __ASSERT_DEBUG( + (aLevel <= KAMMSMaxRoomLevel) || + (aLevel == KAMMSDisconnectReverbSource), + User::Invariant()); + + // With the JSR-234 value Integer.MIN_VALUE, the reflected sound for the + // given object can be disabled. + if (aLevel == KMinTInt) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL(Integer.MIN_VALUE)"); + aLevel = 0; + } + + // Check the allowed boundaries for room level. + TInt32 minLevel = 0; + TInt32 maxLevel = 0; + iReverbSource->LevelRange(minLevel, maxLevel); + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL boundaries %d, %d", + minLevel, maxLevel); + + // Check the state of the effect. If it is in disabled state, enable it. + if (!iReverbSource->IsEnabled()) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL calling EnableL"); + iReverbSource->EnableL(); + } + + // With the JSR-234 value DISCONNECT, the object can be disconnected + // from the reverb. + if (aLevel == KAMMSDisconnectReverbSource) + { + // Do not call iReverbSource->DisableL(), instead set the room level to + // _minimum_ value (= smallest negative gain -> maximum attenuation). + // The CRoomLevel must also be kept enabled. + aLevel = minLevel; + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL(DISCONNECT) %d", + minLevel); + } + else + { + // Set the room level within allowed boundaries from Effect API + aLevel = Min(aLevel, maxLevel); + aLevel = Max(aLevel, minLevel); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL setting value: %d", aLevel); + } + + // Sets the RoomLevel level, it will leave if aRoomLevel is not within range + // of Min and Max + iReverbSource->SetRoomLevelL((TInt32)aLevel); + + // Apply updated settings to Effect API. + iReverbSource->ApplyL(); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::SetRoomLevelL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbSourceControl::PrepareControlL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::PrepareControlL"); + + // Perform the action only for the first time, skip if called afterwards + if (!iReverbSource) + { + CEnvironmentalReverbUtility* reverbUtility = NULL; + iReverbControl->GetEnvironmentalReverbUtilityL(&reverbUtility); + // Reverb utility must exist, otherwise room level creation will fail. + __ASSERT_DEBUG(reverbUtility, User::Invariant()); + + CEnvironmentalReverb* reverb = + &(reverbUtility->EnvironmentalReverb()); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Effect API takes the ownership of customCommandUtility. + iReverbSource = CRoomLevel::NewL(customCommandUtility, *reverb); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSReverbSourceControl::DeallocateControl() +{ + if (iReverbSource) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSReverbSourceControl::DeallocateControl"); + + // Disable the Effect API Control + TRAPD(err, iReverbSource->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class (it deletes CustomCommandUtility) + delete iReverbSource; + iReverbSource = NULL; + } +} + +const TDesC& CAMMSReverbSourceControl::ClassName() const +{ + return KAMMSReverbSourceControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSReverbSourceControl::CAMMSReverbSourceControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSReverbSourceControl::CAMMSReverbSourceControl( + CMMAPlayer* aPlayer, + CAMMSBaseReverbControl* aReverbControl) + : CAMMSBaseReverbSourceControl(aPlayer), iReverbControl(aReverbControl) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsspectatordopplercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsspectatordopplercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the doppler effect of the spectator. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsspectatordopplercontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorDopplerControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSSpectatorDopplerControl* CAMMSSpectatorDopplerControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSSpectatorDopplerControl* self = + new(ELeave)CAMMSSpectatorDopplerControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSSpectatorDopplerControl::~CAMMSSpectatorDopplerControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorDopplerControl::~CAMMSSpectatorDopplerControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete(CAudioEffect*)iDopplerEffect; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorDopplerControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorDopplerControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iDopplerEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorDopplerControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Set the base class doppler effect as CListenerDoppler + // Effect API takes the ownership of customCommandUtility. + iDopplerEffect = CListenerDoppler::NewL(customCommandUtility); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorDopplerControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorDopplerControl::DeallocateControl() +{ + if (iDopplerEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorDopplerControl::DeallocateControl"); + + // Doppler for Spectator is always enabled (JSR-234 mandates it) + // so the disabling is needed here + TRAPD(err, iDopplerEffect->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class (it deletes CustomCommandUtility) + // The class that is derived from CDoppler is casted here to the + // base class CAudioEffect, since CDoppler has the destructor + // defined as protected, but the derived class and the base class + // have it defined as public. + delete(CAudioEffect*)iDopplerEffect; + iDopplerEffect = NULL; + } +} + +const TDesC& CAMMSSpectatorDopplerControl::ClassName() const +{ + return KAMMSSpectatorDopplerControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorDopplerControl::CAMMSSpectatorDopplerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSSpectatorDopplerControl::CAMMSSpectatorDopplerControl( + CMMAPlayer* aPlayer) + : CAMMSDopplerControl(aPlayer) +{ +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsspectatorlocationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsspectatorlocationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,124 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual location of the spectator. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsspectatorlocationcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorLocationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSSpectatorLocationControl* CAMMSSpectatorLocationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSSpectatorLocationControl* self = new(ELeave) + CAMMSSpectatorLocationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSSpectatorLocationControl::~CAMMSSpectatorLocationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorLocationControl::~CAMMSSpectatorLocationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete(CAudioEffect*)iLocationEffect; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorLocationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorLocationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iLocationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorLocationControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Set the base class location effect as CListenerLocation + // Effect API takes the ownership of customCommandUtility. + iLocationEffect = CListenerLocation::NewL(customCommandUtility); + + // Enable the Effect API Control + iLocationEffect->EnableL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorLocationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorLocationControl::DeallocateControl() +{ + if (iLocationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorLocationControl::DeallocateControl"); + + // Disable the Effect API Control + TRAPD(err, iLocationEffect->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class. + // The class that is derived from CLocation is casted here to the + // base class CAudioEffect, since CLocation has the destructor + // defined as protected, but the derived class and the base class + // have it defined as public. + delete(CAudioEffect*)iLocationEffect; + iLocationEffect = NULL; + } +} + +const TDesC& CAMMSSpectatorLocationControl::ClassName() const +{ + return KAMMSSpectatorLocationControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorLocationControl::CAMMSSpectatorLocationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSSpectatorLocationControl::CAMMSSpectatorLocationControl( + CMMAPlayer* aPlayer) + : CAMMSLocationControl(aPlayer) +{ +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsspectatororientationcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsspectatororientationcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,124 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manipulates the virtual orientation of the spectator. +* +*/ + + + +// INCLUDE FILES +#include +#include "cammsspectatororientationcontrol.h" + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorOrientationControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSSpectatorOrientationControl* CAMMSSpectatorOrientationControl::NewLC( + CMMAPlayer* aPlayer) +{ + CAMMSSpectatorOrientationControl* self = + new(ELeave)CAMMSSpectatorOrientationControl(aPlayer); + + CleanupStack::PushL(self); + + return self; +} + +// Destructor +CAMMSSpectatorOrientationControl::~CAMMSSpectatorOrientationControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorOrientationControl::~CAMMSSpectatorOrientationControl"); + + // Perform DeallocateControl, if the state change has not yet performed it. + DeallocateControl(); + delete(CAudioEffect*)iOrientationEffect; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorOrientationControl::PrepareControlL +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorOrientationControl::PrepareControlL() +{ + // Perform the action only for the first time, skip if called afterwards + if (!iOrientationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorOrientationControl::PrepareControlL"); + + CCustomCommandUtility* customCommandUtility = + CreateCustomCommandUtilityL(); + + // Set the base class orientation effect as CListenerOrientation + // Effect API takes the ownership of customCommandUtility. + iOrientationEffect = CListenerOrientation::NewL( + customCommandUtility); + + // Enable the Effect API Control + iOrientationEffect->EnableL(); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorOrientationControl::DeallocateControl +// Function which is called after the correct state is set in Player. +// ----------------------------------------------------------------------------- +// +void CAMMSSpectatorOrientationControl::DeallocateControl() +{ + if (iOrientationEffect) + { + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSSpectatorOrientationControl::DeallocateControl"); + + // Disable the Effect API Control + TRAPD(err, iOrientationEffect->DisableL()); + if (err != KErrNone) + { + // The only even theoritically possible error code here would be + // KErrAccessDenied which is a result from Effect API calling ApplyL + // method without having update rights, but since the Effect + // is already created, that situation can be discarded here. + } + + // Delete the Effect API class. + // The class that is derived from COrientation is casted here to the + // base class CAudioEffect, since COrientation has the destructor + // defined as protected, but the derived class and the base class + // have it defined as public. + delete(CAudioEffect*)iOrientationEffect; + iOrientationEffect = NULL; + } +} + +const TDesC& CAMMSSpectatorOrientationControl::ClassName() const +{ + return KAMMSSpectatorOrientationControl; +} + +// ----------------------------------------------------------------------------- +// CAMMSSpectatorOrientationControl::CAMMSSpectatorOrientationControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSSpectatorOrientationControl::CAMMSSpectatorOrientationControl( + CMMAPlayer* aPlayer) + : CAMMSOrientationControl(aPlayer) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsvolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsvolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,105 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Controls the volume of a CMMAVolumeControl. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cammsvolumecontrol.h" + +#ifdef _DEBUG +// CONSTANTS +const TInt KAMMSMaxVolume = 100; +const TInt KAMMSMinVolume = 0; +#endif // _DEBUG + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControl::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSVolumeControl* CAMMSVolumeControl::NewLC(const TDesC& aControlName, + CMMAVolumeControl* aVolumeControl, CMMAPlayer* aPlayer) +{ + CAMMSVolumeControl* self = new(ELeave) CAMMSVolumeControl( + aControlName, aVolumeControl, aPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSVolumeControl::~CAMMSVolumeControl() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSVolumeControl::~CAMMSVolumeControl"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControl::SetVolumeL +// Sets the volume level. +// ----------------------------------------------------------------------------- +// +void CAMMSVolumeControl::SetVolumeL(TInt aVolume) +{ + // Check in debug build that aVolume is within valid range. + __ASSERT_DEBUG( + (aVolume <= KAMMSMaxVolume) && + (aVolume >= KAMMSMinVolume), + User::Invariant()); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSVolumeControl::SetVolumeL: Volume = %d", aVolume); + iVolumeControl->SetVolumeLevelL(iControlLevelIndex, aVolume); +} + +const TDesC& CAMMSVolumeControl::ClassName() const +{ + return iClassName; +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSVolumeControl::ConstructL() +{ + iControlLevelIndex = iVolumeControl->AddLevelL(); + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSVolumeControl::ConstructL level index = %d", + iControlLevelIndex); +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControl::CAMMSVolumeControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSVolumeControl::CAMMSVolumeControl( + const TDesC& aControlName, + CMMAVolumeControl* aVolumeControl, + CMMAPlayer* aPlayer) : + CAMMSControl(aPlayer), + iClassName(aControlName) +{ + iVolumeControl = aVolumeControl; +} + +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/mmacontrol/src/cammsvolumecontrolbuilder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/mmacontrol/src/cammsvolumecontrolbuilder.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: AMMS player builder for adding AMMS audio player controls. +* +*/ + + + +// INCLUDE FILES +#include +#include +#include + +#include "cammsvolumecontrolbuilder.h" +#include "cammsvolumecontrol.h" +#include "ammsconstants.h" +#include "ammsutil.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlBuilder::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSVolumeControlBuilder* CAMMSVolumeControlBuilder::NewLC() +{ + CAMMSVolumeControlBuilder* self = new(ELeave) CAMMSVolumeControlBuilder(); + CleanupStack::PushL(self); + return self; +} + + +// Destructor +CAMMSVolumeControlBuilder::~CAMMSVolumeControlBuilder() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlBuilder::PreparePlayerL +// ----------------------------------------------------------------------------- +// +void CAMMSVolumeControlBuilder::PreparePlayerL(CMMAPlayer* aPlayer) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSVolumeControlBuilder::PreparePlayerL type %S", + aPlayer->Type().Ptr()); + + CMMAControl* control = AMMSUtil::FindControl(aPlayer, + KMMAVolumeControlName); + if (control) + { + CMMAVolumeControl* mmaControl = + reinterpret_cast< CMMAVolumeControl* >(control); + + CAMMSVolumeControl* ammsControl = CAMMSVolumeControl::NewLC( + KAMMSGlobalVolume, + mmaControl, + aPlayer); + aPlayer->AddControlL(ammsControl); + CleanupStack::Pop(ammsControl); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSVolumeControlBuilder::PreparePlayerL add OK"); + } + // else volume control need not to be added, for example camera player. +} + +// ----------------------------------------------------------------------------- +// CAMMSVolumeControlBuilder::CAMMSVolumeControlBuilder +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSVolumeControlBuilder::CAMMSVolumeControlBuilder() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/ammsconstants.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/ammsconstants.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This file defines global constants. +* +*/ + + +#ifndef AMMSCONSTANTS_H +#define AMMSCONSTANTS_H + +/** +* +* This file defines global constants. +* +* +* @since 3.0 +*/ + +const TInt KAMMSVectorComponents = 3; // Components in a vector +const TInt KAMMSTwoVectorComponents = 6; // Components in two vectors + +// Component indexes in vectors +enum TVectorIndex +{ + EComponentX = 0, + EComponentY = 1, + EComponentZ = 2, + EAzimuth = 0, + EElevation = 1, + ERadius = 2 +}; + +enum TAMMSControlTypes +{ + EAMMSBaseControl = 0, + EAMMSSpectatorControl, + EAMMSSoundSource3DControl +}; + +_LIT(KAMMSGlobalVolume, "VolumeGlobal"); + +#endif // AMMSCONSTANTS_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/ammsutil.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/ammsutil.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,166 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Static general reusable methods. +* +*/ + + +#ifndef AMMSUTIL_H +#define AMMSUTIL_H + +// INCLUDES +#include +#include "ammsconstants.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; +class CMMAControl; + +// CLASS DECLARATION + +/** +* Static general reusable methods. +* +* This class contains only static method which can be used in many classes. +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(AMMSUtil) +{ +public: // New functions + /** + * Finds the control of a corresponding type that + * belongs to the player given as a parameter + * + * @param aPlayer The Player where to find the Control + * @param aControlName Name of the control to look for + * @param aControlType Special AMMS type of the Control + * @return Control of type aControlName or NULL if not found + */ + static CMMAControl* FindControl( + CMMAPlayer* aPlayer, + const TDesC& aControlName, + TAMMSControlTypes aControlType = EAMMSBaseControl); + + /** + * Converts vector from spherical to cartesian. + * + * @param aSphericalVector Spherical vector to be converted + * @param aCartesianVector Result cartesian vector + */ + static void FromSphericalToCartesianL( + TInt aSphericalVector[ KAMMSVectorComponents ], + TInt aCartesianVector[ KAMMSVectorComponents ]); + + /* + * Rotates a vector round the given axis. The starting point of each + * vectors is in the origo, and thus, only coordinates of the ending + * point should be given. + * + * @param aVector X, Y, and Z value of a vector to be rotated + * @param aAxisVector X, Y, and Z value of an axis vector + * @param aAngle Rotation angle in degrees + * @param aRotatedVector X, Y, and Z value of the rotated vector + */ + static void RotateVectorL(TReal aVector[ KAMMSVectorComponents ], + TReal aAxisVector[ KAMMSVectorComponents ], + TInt aAngle, + TReal aRotatedVector[ KAMMSVectorComponents ]); + + /** + * Rounds each component in the given vector. + * + * @param aVector A vector to be rounded + * @param aRoundedVector Rounded vector + */ + static void RoundVectorL(TReal aVector[ KAMMSVectorComponents ], + TInt aRoundedVector[ KAMMSVectorComponents ]); + + /** + * Multiplies the given vector by the given scalar value. + * + * @param aVector A vector to be rounded + * @param aMultiplier A multiplier + */ + static void MultiplyVector(TReal aVector[ KAMMSVectorComponents ], + TReal aMultiplier); + + /** + * Calculates vector cross product. + * @param aA A vector having KAMMSVectorComponents elements + * @param aB A vector having KAMMSVectorComponents elements + * @param aResultVector Result of the cross product + */ + static void CrossProduct(TReal aA[ KAMMSVectorComponents ], + TReal aB[ KAMMSVectorComponents ], + TReal aResultVector[ KAMMSVectorComponents ]); + + /** + * Calculates the length of the given vector. + * + * @param aVector A vector whose length is calculated + */ + static TReal VectorLengthL(TReal aVector[ KAMMSVectorComponents ]); + + /** + * Converts the given vector to the unit vector. The original vector + * is replaced by the result vector. + * + * @param aVector A vector that is converted to the unit vector and is + * replaced by the result vector + */ + static void ConvertToUnitVectorL(TReal aVector[ KAMMSVectorComponents ]); + + /** + * Checks whether two given vectors are similar according to the given + * maximum error percentage. The function compares each component in + * aA to the corresponding component in aB. + * + * @param aA A vector + * @param aB A vector + * @param aMaxComponentErrorPercentage Maximum error percentage between + * a component in aA and the corresponding component in aB + * @return ETrue if difference between each component pair is lower + * than the given error, else ETrue is returned + */ + static TBool AreVectorsSimilar(TReal aA[ KAMMSVectorComponents ], + TInt aB[ KAMMSVectorComponents ], + TInt aMaxComponentErrorPercentage); + + /** + * Returns the maximum component value in the given vector. + * + * @param aVector A vector + * @return Maximum component value in aVector + */ + static TReal MaxVectorComponent(TReal aVector[ KAMMSVectorComponents ]); + + /** + * Returns the minimum component value in the given vector. + * + * @param aVector A vector + * @return Minimum component value in aVector + */ + static TReal MinVectorComponent(TReal aVector[ KAMMSVectorComponents ]); + +private: + /** + * C++ default constructor. Private to not allow construction. + */ + AMMSUtil(); +}; + +#endif // AMMSUTIL_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammscontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammscontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,147 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for control groups +* +*/ + + +#ifndef CAMMSCONTROLGROUP_H +#define CAMMSCONTROLGROUP_H + +// INCLUDES +#include +#include "mammscontrolgroup.h" +#include "ammsconstants.h" + +// FORWARD DECLARATIONS +class MAMMSControllable; +class CMMAControl; +class CMMAPlayer; +class CAMMSPlayerStateListener; + +// CLASS DECLARATION +/** + * Base class for control groups + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSControlGroup): public CBase, public MAMMSControlGroup +{ +public: // Constructors and destructor + + /** + * Destructor. + */ + virtual ~CAMMSControlGroup(); + +public: // New functions + + /** + * This function is called when state of a player has changed. + * + * @param aPlayer Player whose state has changed. + * @param aNewState State that the player has now. + */ + void PlayerStateChangedL(CMMAPlayer* aPlayer, + TInt aNewState); + +protected: // New functions + + /** + * 2nd phase constructor. + */ + void ConstructL(); + + /** + * Returns the total count of controls in this group. + * + * @return Count of the controls. + */ + TInt ControlCount() const; + + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + * + * @return the control at given index + */ + CMMAControl* Control(TInt aIndex) const; + + /** + * Called by PlayerAddedL when new player is added + * + * @param aPlayer The player being added + * @param aControl The player's control relevant to this group + */ + virtual void NotifyPlayerAddedL(CMMAPlayer* aPlayer, CMMAControl* aControl); + + /** + * Called by PlayerRemoved when new player is removed + * + * @param aPlayer The player being removed + * @param aControl The player's control relevant to this group + */ + virtual void NotifyPlayerRemoved(CMMAPlayer* aPlayer, CMMAControl* aControl); + +public: // From MAMMSControlGroup + + /** + * Called by the owning module when a player is added + * + * @param aPlayer The player being added + */ + void PlayerAddedL(CMMAPlayer *aPlayer); + + /** + * Called by the owning module when a player is removed + * + * @param aPlayer The player being removed + */ + void PlayerRemoved(CMMAPlayer *aPlayer); + +protected: + /** + * C++ default constructor. + * + * @param aName The name of the corresponding amms control + * (doesn't take a copy!) + * @param aControlType Special AMMS type of the Control + */ + CAMMSControlGroup( + const TDesC& aName, + TAMMSControlTypes aControlType = EAMMSBaseControl); + +protected: // Data + + // Listeners for player state changes, owned. + CArrayPtrSeg< CAMMSPlayerStateListener >* iPlayerStateListeners; + + // Grouped controls, not owned + RArray< CMMAControl* > iControls; + + // The name of contained controls, not owned + const TDesC& iName; + + // The type of the actual Control + TAMMSControlTypes iControlType; + + // Controllable object. Not owned. (Global manager) + MAMMSControllable* iAMMSControllable; + +}; + +#endif // CAMMSCONTROLGROUP_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammseffectmodule.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammseffectmodule.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Module for holding control groups belonging to EffectModule. +* +*/ + + +#ifndef CAMMSEFFECTMODULE_H +#define CAMMSEFFECTMODULE_H + +// INCLUDES +#include "cammsmodule.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; +class CAMMSGlobalManager; + + +// CLASS DECLARATION + +/** +* Module for holding control groups belonging to EffectModule. +* +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSEffectModule): public CAMMSModule +{ +public: + /** + * Two-phased constructor. + * + * @param aGlobalManager Global manager. + */ + static CAMMSEffectModule* NewLC(CAMMSGlobalManager* aGlobalManager); + + /** + * Destructor. + */ + ~CAMMSEffectModule(); + +public: // From CAMMSModule + + void AddPlayerNoStateCheckL(CMMAPlayer* aPlayer); + +protected: + /** + * C++ default constructor. + * + * @param aGlobalManager Global manager. + */ + CAMMSEffectModule(CAMMSGlobalManager* aGlobalManager); + + void ConstructL(); + +private: // Data + + CAMMSGlobalManager* iGlobalManager; // Not owned. +}; + +#endif // CAMMSEFFECTMODULE_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammsglobalmanager.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammsglobalmanager.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,168 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class provides GlobalManager functionality. +* +*/ + + +#ifndef CAMMSGLOBALMANAGER_H +#define CAMMSGLOBALMANAGER_H + +// INCLUDES +#include +#include +#include + +#include "cammsmodule.h" + +// CONSTANTS + +// FORWARD DECLARATIONS +class CAMMSModuleContainer; +class CAMMSPlayerBuilderGroup; + +// CLASS DECLARATION + +/** +* +* This class provides GlobalManager functionality. +* The GlobalManager handles the creation of EffectModules, SoundSource3Ds +* and MediaProcessors. Furthermore, a Spectator can be get from the +* GlobalManager. GlobalManager extends the CAMMSModule and contains global +* controls. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSGlobalManager): public CAMMSModule, public MMMAPlayerInstanceObserver +{ +public: + + /** + * Two-phased constructor. + */ + static CAMMSGlobalManager* NewLC(); + + /** + * Destructor. + */ + ~CAMMSGlobalManager(); + +public: // From MMMAPlayerInstanceObserver + /** + * MMA will call this method when new player is created. + * @since 3.0 + * @param aPlayer Player to add. + */ + void AddPlayerNotifyL(CMMAPlayer* aPlayer); + + /** + * MMA will call this method when player does not exist anymore. + * @since 3.0 + * @param aPlayer Player to remove. + */ + void RemovePlayerNotify(CMMAPlayer* aPlayer); + +public: // New functions + /** + * Initializes GlobalManager. This method is called when Java + * GlobalManager is accessed for the first time. + * This method creates mma controls to the added players and creates + * global controls. After this method is called amms controls are added + * to players immediately. + * @param aPlayers Players created with mma api. + * @since 3.0 + */ + void InitL(RPointerArray< CMMAPlayer >& aPlayers); + + /** + * Creates a new sound source 3D module. + * Module will be owned by global manager. + * @since 3.0 + * @return New sound source 3D module. + */ + CAMMSModule* CreateSoundSource3DL(); + + /** + * Creates a new effect module. + * Module will be owned by global manager. + * @since 3.0 + * @return New effect module. + */ + CAMMSModule* CreateEffectModuleL(); + + /** + * Returns the spectator. + * @since 3.0 + * @return Spectator. + */ + CAMMSModule* Spectator(); + + /** + * Disposes module. + * @param aModule Module to dispose. + */ + void DisposeModule(CAMMSModule* aModule); + + /** + * Checks whether the given player can be added to a module (EffectModule + * or SoundSource3D). + * @param aPlayer Player to be checked. + * @return KErrNone if the player can be added or some error + * code if the adding is not allowed. + */ + TInt PlayerAddingAllowed(CMMAPlayer* aPlayer); + +private: + /** + * C++ default constructor. + */ + CAMMSGlobalManager(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: // New functions + + /** + * Checks whether the given player can be added to a module + * according to the given module (is there any player in + * the module that can prevent player adding to any module). + * @param aPlayer Player to be checked. + * @param aModule Module to be checked. + * @return KErrNone if the player can be added or some error + * code if the adding is not allowed. + */ + TInt PlayerAddingAllowed(CMMAPlayer* aPlayer, CAMMSModule* aModule); + + +private: // Data + // Owned spectator + CAMMSModule* iSpectator; + + // Owned effect modules + CAMMSModuleContainer* iEffectModules; + + // Owned sound source 3Ds + CAMMSModuleContainer* iSoundSource3Ds; + + // Owned player builder + CAMMSPlayerBuilderGroup* iPlayerBuilder; +}; + +#endif // CAMMSGLOBALMANAGER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammsmodule.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammsmodule.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,183 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a container for MAMMSControlGroup objects. +* +*/ + + +#ifndef CAMMSMODULE_H +#define CAMMSMODULE_H + +// INCLUDES +#include + +#include + +#include "mammscontrollable.h" + +// CONSTANTS +const TInt KAMMSPlayerAlreadyInModuleError = -123; + +#ifdef __WINS__ +const TInt KAMMSMixingNotSupported = -1234; +#endif // __WINS__ + + +// FORWARD DECLARATIONS +class CAMMSControlGroup; + +// CLASS DECLARATION + +/** +* +* This class is a container for MAMMSControlGroup objects. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSModule): public CBase, public MAMMSControllable +{ +public: + /** + * Two-phased constructor. + */ + static CAMMSModule* NewL(); + + /** + * Two-phased constructor. + */ + static CAMMSModule* NewLC(); + + /** + * Destructor. + */ + ~CAMMSModule(); + +public: // New functions + /** + * Adds new control group to module. Ownership is transferred to + * the module and aGroup is removed from the cleanupstack + * if this method does not leave. + * @since 3.0 + * @param aGroup New control group. Must be the previous item in the + * cleanupstack. + */ + void AddControlGroupAndPopL(CAMMSControlGroup* aGroup); + + /** + * Adds new player to this module. + * @param aPlayer New player to add + */ + virtual void AddPlayerL(CMMAPlayer* aPlayer); + + /** + * Removes player from module. + * @param aPlayer player to remove + * @return KErrNotFound if player was not in the module. + */ + virtual TInt RemovePlayer(CMMAPlayer* aPlayer); + + /** + * Adds new player to this module without checking player states. + * @param aPlayer New player to add + */ + virtual void AddPlayerNoStateCheckL(CMMAPlayer* aPlayer); + + /** + * Removes player from module without checking player states. + * @param aPlayer player to remove + * @return KErrNotFound if player was not in the module. + */ + virtual TInt RemovePlayerNoStateCheck(CMMAPlayer* aPlayer); + + /** + * Checks whether the given player is in this module. + * @param aPlayer Player to be checked. + * @return ETrue if the specified player exists in this + * module; EFalse otherwise. + */ + TBool HasPlayer(CMMAPlayer* aPlayer); + +#ifdef __WINS__ + + /** + * Returns the count of players whose state is between the given + * limits. + * @param aMinState Minimum player state to be searched. + * @param aMaxState Maximum player state to be searched. + * @return The count of players having state between the given + * limits. + */ + TInt PlayerCount(TInt aMinState, TInt aMaxState); + +#endif // __WINS__ + + +private: // Private new functions + /** + * Checks that none of the players in this module is not in PREFETCHED + * or STARTED state. + * @return KErrNotReady if some player is in PREFETCHED or STARTED + * state, otherwise KErrNone. + */ + TInt CheckAllPlayersState(); + + /** + * Checks that player state is not in PREFETCHED or STARTED state. + * @param aPlayer player to check + * @return KErrNotReady if player is in PREFETCHED or STARTED state, + * otherwise KErrNone. + */ + TInt CheckPlayerState(CMMAPlayer* aPlayer); + + /** + * Static function to be used with TCleanupItem in + * AddPlayerNoStateCheckL method. This method removes last added + * player from module and control groups. + * @param aModule Module to clean. + */ + static void CleanupAddPlayer(TAny* aModule); + +public: // Functions from base classes + MAMMSControlGroup* Find(const TDesC& aClassName); + MAMMSControlGroup* At(TInt aIndex); + TInt Count(); + +protected: + /** + * C++ default constructor. + */ + CAMMSModule(); + +protected: + /** + * Protected because derived classes must call ConstructL. + */ + void ConstructL(); + +private: // Data + // Owned array containing control groups, which are owned. + // Elements are added using AddControlGroupL method and deleted + // in the destructor. + CArrayPtrSeg< CAMMSControlGroup >* iControlGroups; + + // Array containing players. + // Elements are added using AddPlayerL method and removes + // with RemovePlayer + RPointerArray< CMMAPlayer > iPlayers; +}; + +#endif // CAMMSMODULE_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammsmodulecontainer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammsmodulecontainer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Container for CAMMSModule objects. +* +*/ + + +#ifndef CAMMSMODULECONTAINER_H +#define CAMMSMODULECONTAINER_H + +// INCLUDES +#include +#include "cammsmodule.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; + +// CLASS DECLARATION + +/** +* +* This class is a container for CAMMSModule objects. All modules added to +* this class with CArrayPtrSeg::AppendL method are owned and deleted in the +* destructor. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSModuleContainer): public CArrayPtrSeg< CAMMSModule > +{ +public: + /** + * C++ default constructor. + */ + CAMMSModuleContainer(); + + /** + * Destructor. + */ + ~CAMMSModuleContainer(); + +public: // New functions + /** + * Removes player from all modules. Player states are not checked. + * @param aPlayer player to remove + */ + void RemovePlayer(CMMAPlayer* aPlayer); + + /** + * Removes module from container. The module itself is not deleted + * by this method, so it has to be deleted elsewhere. + * Method returns silently if module is not found. + * @param aModule Module to remove. + */ + void RemoveModule(CAMMSModule* aModule); + +}; + +#endif // CAMMSMODULECONTAINER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammsplayerstatelistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammsplayerstatelistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,107 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Implementation for player state listener. +* +*/ + + +#ifndef CAMMSPLAYERSTATELISTENER_H +#define CAMMSPLAYERSTATELISTENER_H + +// INCLUDES +#include +#include + +// FORWARD DECLARATIONS +class CMMAPlayer; +class CAMMSControlGroup; + +// CLASS DECLARATION +/** + * Implementation for player state listener. + * + * @since 3.0 + */ +NONSHARABLE_CLASS(CAMMSPlayerStateListener) + : public CBase, + public MMMAPlayerStateListener +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + * + * @param iPlayer Player to be listened by this listener. + * @param iControlGroup Control group to be informed when + * player state changes. + */ + static CAMMSPlayerStateListener* NewLC( + CMMAPlayer* aPlayer, + CAMMSControlGroup* aControlGroup); + /** + * Destructor. + */ + ~CAMMSPlayerStateListener(); + +private: // Constructors and destructor + + /** + * 2nd phase constructor. + */ + void ConstructL(); + + /** + * C++ constructor. + * @param iPlayer Player to be listened by this listener. + * @param iControlGroup Control group to be informed when + * player state changes. + */ + CAMMSPlayerStateListener(CMMAPlayer* aPlayer, + CAMMSControlGroup* aControlGroup); + + +public: // New methods + + /** + * Returns the player listened by this listener. + * + * @return Player. + */ + CMMAPlayer* Player(); + + /** + * Returns the array index of the listener that listens + * to the given player. + */ + /* static TInt FindPlayerInArray( + CArrayFix< CAMMSPlayerStateListener >* aArray, CMMAPlayer* aPlayer ); + */ + +public: // From MMMAPlayerStateListener + + void StateChanged(TInt aState); + +private: // Data + + // Player to be listened, not owned. + CMMAPlayer* iPlayer; + + // Control group to be informed when player state changes, not owned. + CAMMSControlGroup* iControlGroup; + +}; + +#endif // CAMMSPLAYERSTATELISTENER_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/cammssoundsource3d.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/cammssoundsource3d.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Module for holding control groups belonging to SoundSource3D. +* +*/ + + +#ifndef CAMMSSOUNDSOURCE3D_H +#define CAMMSSOUNDSOURCE3D_H + +// INCLUDES +#include "cammsmodule.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; +class CAMMSGlobalManager; + + +// CLASS DECLARATION + +/** +* Module for holding control groups belonging to SoundSource3D. +* +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(CAMMSSoundSource3D): public CAMMSModule +{ +public: + /** + * Two-phased constructor. + * + * @param aSpectator Spectator. + * @param aGlobalManager Global manager. + */ + static CAMMSSoundSource3D* NewLC(CAMMSModule* aSpectator, + CAMMSGlobalManager* aGlobalManager); + + /** + * Destructor. + */ + ~CAMMSSoundSource3D(); + +public: // New functions + + /** + * From CAMMSModule. + */ + void AddPlayerNoStateCheckL(CMMAPlayer* aPlayer); + + /** + * From CAMMSModule. + */ + TInt RemovePlayerNoStateCheck(CMMAPlayer* aPlayer); + +protected: + /** + * C++ default constructor. + * + * @param aSpectator Spectator. + * @param aGlobalManager Global manager. + */ + CAMMSSoundSource3D(CAMMSModule* aSpectator, + CAMMSGlobalManager* aGlobalManager); + +protected: + /** + * Protected because derived classes must call ConstructL. + */ + void ConstructL(); + +private: // Data + + CAMMSModule* iSpectator; // Not owned. + CAMMSGlobalManager* iGlobalManager; // Not owned. +}; + +#endif // CAMMSSOUNDSOURCE3D_H + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/mammscontrolgroup.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/mammscontrolgroup.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface for all control groups. +* +*/ + + +#ifndef MAMMSCONTROLGROUP_H +#define MAMMSCONTROLGROUP_H + +// INCLUDES +#include + +// FORWARD DECLARATIONS + +// CLASS DECLARATION +/** +* +* Interface for all control groups. +* +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(MAMMSControlGroup) +{ +protected: // Enumerations + + enum TCommitMode { EImmediate, EDeferred }; + +public: // New functions + /** + * Returns class name that identifies this control group. + * @return Control group name. + */ + virtual const TDesC& ClassName() = 0; + + /** + * Sets the mode of the CommitControl. + * + * @param aMode commit mode + */ + virtual void SetModeL(TCommitMode /*aMode*/) {}; + + /** + * Commit all the controls in the group + * in immediate mode commits, in deferred mode marks what variables + * need to be commited later + */ + virtual void CommitGroupL() {}; + +protected: + /** + * Protected destructor not allow delete throw this interface. + */ + virtual ~MAMMSControlGroup() {}; +}; +#endif // MAMMSCONTROLGROUP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/inc/mammscontrollable.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/inc/mammscontrollable.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface to access control groups. +* +*/ + + +#ifndef MAMMSCONTROLLABLE_H +#define MAMMSCONTROLLABLE_H + +// INCLUDES +#include + +// FORWARD DECLARATIONS +class MAMMSControlGroup; + +// CLASS DECLARATION +/** +* +* Interface to access control groups. +* +* @since 3.0 +*/ +NONSHARABLE_CLASS(MAMMSControllable) +{ +public: + /** + * Finds and returns control group specified with a name. + * @since 3.0 + * @param aClassName Name of the control group. + * @return Control group or NULL if group can't be found. + */ + virtual MAMMSControlGroup* Find(const TDesC& aClassName) = 0; + + /** + * Returns control group at the specified index. + * @since 3.0 + * @param aIndex Group index. + * @return A control group at specified index. + */ + virtual MAMMSControlGroup* At(TInt aIndex) = 0; + + /** + * Return number of control groups. + * @since 3.0 + * @return Number of control groups. + */ + virtual TInt Count() = 0; +protected: + + /** + * Protected destructor not to allow delete through this interface. + */ + virtual ~MAMMSControllable() {}; +}; + +#endif // MAMMSCONTROLLABLE_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/ammsutil.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/ammsutil.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,366 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Static general reusable methods. +* +*/ + + +// INCLUDE FILES +#include +#include "ammsutil.h" +#include +#include +#include "cammscontrol.h" + +// CONSTANTS +namespace +{ +const TInt KAMMSStraightAngle = 180; + +// Set a value to 0 if its absolute value is less than this. +const TReal KAMMSDiscreteErrorConstant = 0.00000001; +} + +// ============================ MEMBER FUNCTIONS =============================== + + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::FindControl +// Finds the control of a corresponding name. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CMMAControl* AMMSUtil::FindControl(CMMAPlayer* aPlayer, + const TDesC& aControlName, + TAMMSControlTypes aControlType) +{ + TInt controlCount = aPlayer->ControlCount(); + TInt index = 0; + + // if control is not found NULL will be returned + CMMAControl* control = NULL; + + // go through all controls + while (index < controlCount) + { + CMMAControl* tmp = aPlayer->Control(index); + + // if the name of the Control matches the name used in finding + if (tmp->ClassName() == aControlName) + { + + // a base Control can be accepted always, it can not be derived + if (aControlType == EAMMSBaseControl) + { + // found correct control + control = tmp; + + // set index to stop while loop + index = controlCount; + } + + // in case the Control is not a base Control, check AMMS subtype + else + { + if (aControlType == ((CAMMSControl*)tmp)->iControlType) + { + // found correct (derived) control + control = tmp; + + // set index to stop while loop + index = controlCount; + } + else + { + // move to next control + index++; + } + } + } + + // Control name was not the one used in finding + else + { + // move to next control + index++; + } + } + return control; +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::FromSphericalToCartesianL +// Converts vector from spherical to cartesian. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::FromSphericalToCartesianL( + TInt aSphericalVector[ KAMMSVectorComponents ], + TInt aCartesianVector[ KAMMSVectorComponents ]) +{ + // convert to radians + TReal elevation = aSphericalVector[ EElevation ] * + (KPi / KAMMSStraightAngle); + TReal azimuth = aSphericalVector[ EAzimuth ] * + (KPi / KAMMSStraightAngle); + TReal radius = aSphericalVector[ ERadius ]; + + TReal elevationSin; + TReal elevationCos; + User::LeaveIfError(Math::Sin(elevationSin, elevation)); + User::LeaveIfError(Math::Cos(elevationCos, elevation)); + + TReal cartesian[ KAMMSVectorComponents ]; + + cartesian[ EComponentY ] = elevationSin * radius; + TReal distXZ = elevationCos * radius; // distance in x-z plane + + TReal azimuthSin; + TReal azimuthCos; + User::LeaveIfError(Math::Sin(azimuthSin, azimuth)); + User::LeaveIfError(Math::Cos(azimuthCos, azimuth)); + + // azimuth of 0 degrees points to negative z axis + cartesian[ EComponentZ ] = -azimuthCos * distXZ; + cartesian[ EComponentX ] = azimuthSin * distXZ; + + // round real values and convert them to integers + RoundVectorL(cartesian, aCartesianVector); +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::RotateVectorL +// Rotates a vector round the given axis. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::RotateVectorL( + TReal aVector[ KAMMSVectorComponents ], + TReal aAxisVector[ KAMMSVectorComponents ], + TInt aAngle, + TReal aRotatedVector[ KAMMSVectorComponents ]) +{ + // calculate the length of the axis vector + TReal lengthSquare = aAxisVector[ EComponentX ] * + aAxisVector[ EComponentX ] + aAxisVector[ EComponentY ] * + aAxisVector[ EComponentY ] + aAxisVector[ EComponentZ ] * + aAxisVector[ EComponentZ ]; + + TReal length; + User::LeaveIfError(Math::Sqrt(length, lengthSquare)); + + // check that the vector is long enough + __ASSERT_DEBUG(length > 0, User::Invariant()); + + // normalize the axis vector + TReal x = aAxisVector[ EComponentX ] / length; + TReal y = aAxisVector[ EComponentY ] / length; + TReal z = aAxisVector[ EComponentZ ] / length; + + // calculate sine and cosine values + TReal angleRad = aAngle / 180.0 * KPi; + TReal c; + User::LeaveIfError(Math::Cos(c, angleRad)); + TReal s; + User::LeaveIfError(Math::Sin(s, angleRad)); + + // calculate some help variables + TReal t = 1 - c; + TReal txy = t * x * y; + TReal txz = t * x * z; + TReal tyz = t * y * z; + TReal sz = s * z; + TReal sy = s * y; + TReal sx = s * x; + TReal x2 = aVector[ EComponentX ]; + TReal y2 = aVector[ EComponentY ]; + TReal z2 = aVector[ EComponentZ ]; + + // calculate new x value + aRotatedVector[ EComponentX ] = (t * x * x + c) * x2 + + (txy - sz) * y2 + (txz + sy) * z2; + + // calculate new y value + aRotatedVector[ EComponentY ] = (txy + sz) * x2 + + (t * y * y + c) * y2 + (tyz - sx) * z2; + + // calculate new z value + aRotatedVector[ EComponentZ ] = (txz - sy) * x2 + + (tyz + sx) * y2 + (t * z * z + c) * z2; + + // Remove error of discrete values. + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + if (Abs(aRotatedVector[ i ]) < KAMMSDiscreteErrorConstant) // CSI: 2 Wrong index means implementation error # + { + aRotatedVector[ i ] = 0; // CSI: 2 Wrong index means implementation error # + } + } +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::RoundVectorL +// Rounds vector components. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::RoundVectorL( + TReal aVector[ KAMMSVectorComponents ], + TInt aRoundedVector[ KAMMSVectorComponents ]) +{ + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + TReal roundedValue; + User::LeaveIfError(Math::Round(roundedValue, + (TReal)aVector[ i ], 0)); // CSI: 2 Wrong index means implementation error # + + aRoundedVector[ i ] = (TInt)roundedValue; // CSI: 2 Wrong index means implementation error # + } +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::MultiplyVector +// Multiplies a vector by a scalar. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::MultiplyVector( + TReal aVector[ KAMMSVectorComponents ], + TReal aMultiplier) +{ + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + aVector[ i ] *= aMultiplier; // CSI: 2 Wrong index means implementation error # + } +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::CrossProduct +// Calculates vector cross product. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::CrossProduct( + TReal aA[ KAMMSVectorComponents ], + TReal aB[ KAMMSVectorComponents ], + TReal aResultVector[ KAMMSVectorComponents ]) +{ + // This function can handle only vectors with 3 components + + // Calculate the cross product. + aResultVector[ EComponentX ] = -aA[ EComponentZ ] * aB[ EComponentY ] + + aA[ EComponentY ] * aB[ EComponentZ ]; + + aResultVector[ EComponentY ] = aA[ EComponentZ ] * aB[ EComponentX ] - + aA[ EComponentX ] * aB[ EComponentZ ]; + + aResultVector[ EComponentZ ] = -aA[ EComponentY ] * aB[ EComponentX ] + + aA[ EComponentX ] * aB[ EComponentY ]; +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::VectorLengthL +// Calculates the length of the given vector. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TReal AMMSUtil::VectorLengthL( + TReal aVector[ KAMMSVectorComponents ]) +{ + TReal squareLength = 0; + + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + squareLength += aVector[ i ] * aVector[ i ]; + } + + TReal length; + User::LeaveIfError(Math::Sqrt(length, squareLength)); + + return length; +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::ConvertToUnitVectorL +// Converts the given vector to unit vector. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void AMMSUtil::ConvertToUnitVectorL( + TReal aVector[ KAMMSVectorComponents ]) +{ + TReal length = VectorLengthL(aVector); + + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + aVector[ i ] /= length; // CSI: 2 Wrong index means implementation error # + } +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::AreVectorsSimilar +// Checks whether two vectors are similar enough. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TBool AMMSUtil::AreVectorsSimilar( + TReal aA[ KAMMSVectorComponents ], + TInt aB[ KAMMSVectorComponents ], + TInt aMaxComponentErrorPercentage) +{ + TReal maxRelativeError = aMaxComponentErrorPercentage / 100.0; // CSI: 47 Value 100 means 100% # + + for (TInt i = 0; i < KAMMSVectorComponents; i++) + { + TReal maxError = + Max(Abs(aA[ i ]), Abs(aB[ i ])) * maxRelativeError; // CSI: 2 Wrong index means implementation error # + + if (Abs(aA[ i ] - aB[ i ]) > maxError) // CSI: 2 Wrong index means implementation error # + { + return EFalse; + } + } + + // Vectors were similar enough. + return ETrue; +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::MaxVectorComponent +// Returns the maximum component in the given vector. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TReal AMMSUtil::MaxVectorComponent( + TReal aVector[ KAMMSVectorComponents ]) +{ + TReal maxValue = aVector[ 0 ]; + + for (TInt i = 1; i < KAMMSVectorComponents; i++) + { + maxValue = Max(maxValue, aVector[ i ]); // CSI: 2 Wrong index means implementation error # + } + + return maxValue; +} + +// ----------------------------------------------------------------------------- +// AMMSUtil::MinVectorComponent +// Returns the minimum component in the given vector. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TReal AMMSUtil::MinVectorComponent( + TReal aVector[ KAMMSVectorComponents ]) +{ + TReal minValue = aVector[ 0 ]; + + for (TInt i = 1; i < KAMMSVectorComponents; i++) + { + minValue = Min(minValue, aVector[ i ]); // CSI: 2 Wrong index means implementation error # + } + + return minValue; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammscontrolgroup.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammscontrolgroup.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,286 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for control groups +* +*/ + + +// INCLUDE FILES +#include +#include "cammscontrolgroup.h" +#include +#include "cammscontrol.h" +#include "ammsutil.h" +#include "cammsplayerstatelistener.h" + +#ifdef _DEBUG +_LIT(KAMMSNoGroupNameError, "No group name"); +#endif + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::~CAMMSControlGroup +// Destructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSControlGroup::~CAMMSControlGroup() +{ + if (iPlayerStateListeners) + { + iPlayerStateListeners->ResetAndDestroy(); + delete iPlayerStateListeners; + } + + iControls.Close(); +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::PlayerStateChangedL +// This function is called when state of a player has changed. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::PlayerStateChangedL( + CMMAPlayer* aPlayer, + TInt aNewState) +{ + CMMAControl* findControl = AMMSUtil::FindControl( + aPlayer, iName, iControlType); + + // It is safe to cast CMMAControl to the subclass CAMMSControl, as only + // AMMS Controls are returned from FindControl method + CAMMSControl* control = static_cast< CAMMSControl* >(findControl); + + // The player has a control belonging to this group if this function + // is called. + __ASSERT_DEBUG(control, User::Invariant()); + + TInt controlIndex = iControls.Find(control); + + // Add the control of the player to the group if the player is prefetched + // or started. + if (controlIndex == KErrNotFound) + { + if ((aNewState == CMMAPlayer::EPrefetched) || + (aNewState == CMMAPlayer::EStarted)) + { + // Now it is safe to call PrepareControlL to initialize the Control + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSControlGroup::PlayerStateChangedL calling PrepareControl for type: %d", + control->iControlType); + control->PrepareControlL(); + + // Add control to controls array + User::LeaveIfError(iControls.Append(control)); + + // Notify derived classes about new player control + NotifyPlayerAddedL(aPlayer, control); + } + } + + // Remove the control of the player from the group if the player is + // deallocated or closed. + else + { + if ((aNewState == CMMAPlayer::ERealized) || + (aNewState == CMMAPlayer::EClosed)) + { + // Call DeallocateControl to delete the Control's Effect API class + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSControlGroup::PlayerStateChangedL calling DeallocateControl for type: %d", + control->iControlType); + control->DeallocateControl(); + + NotifyPlayerRemoved(aPlayer, control); + iControls.Remove(controlIndex); + } + } +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::ConstructL +// 2nd phase constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::ConstructL() +{ + iPlayerStateListeners = + new(ELeave) CArrayPtrSeg< CAMMSPlayerStateListener >(1); +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::ControlCount +// Returns the total count of controls in this group. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSControlGroup::ControlCount() const +{ + return iControls.Count(); +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::Control +// Gets control. Ownership is not tranferred. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CMMAControl* CAMMSControlGroup::Control(TInt aIndex) const +{ + // aIndex must not be negative and must not be greater than the number + // of objects currently in the array, + // otherwise the operator raises a USER-130 panic. + return iControls[ aIndex ]; +} + + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::NotifyPlayerRemoved +// Called by PlayerAddedL when new player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::NotifyPlayerAddedL( + CMMAPlayer* /*aPlayer*/, + CMMAControl* /*aControl*/) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::NotifyPlayerRemoved +// Called by PlayerRemoved when a player is removed +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::NotifyPlayerRemoved( + CMMAPlayer* /*aPlayer*/, + CMMAControl* /*aControl*/) +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::PlayerAddedL +// Called by the owning module when a player is added +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::PlayerAddedL(CMMAPlayer *aPlayer) +{ + // All derived classes must define name for the group + __ASSERT_DEBUG(iName != KNullDesC, + User::Panic(KAMMSNoGroupNameError, + KErrUnknown)); + + // Do nothing if the player does not have a control belonging to this group. + CMMAControl* findControl = AMMSUtil::FindControl( + aPlayer, iName, iControlType); + if (!findControl) + { + return; + } + + // It is safe to cast CMMAControl to the subclass CAMMSControl, as only + // AMMS Controls are returned from FindControl method + CAMMSControl* control = static_cast< CAMMSControl* >(findControl); + + CAMMSPlayerStateListener* playerListener = + CAMMSPlayerStateListener::NewLC(aPlayer, this); + + iPlayerStateListeners->AppendL(playerListener); + + CleanupStack::Pop(playerListener); + + // Add the control of the player directly to the group + // if the player is in STARTED or PREFETCHED state. + // If not, the control is added later when the player changes + // its state to PREFETCHED. + TInt playerState = aPlayer->State(); + + if ((playerState == CMMAPlayer::EPrefetched) || + (playerState == CMMAPlayer::EStarted)) + { + // Now it is safe to call PrepareControlL to initialize the Control + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSControlGroup::PlayerAddedL calling PrepareControl for type: %d", + control->iControlType); + control->PrepareControlL(); + + // Add control to controls array + User::LeaveIfError(iControls.Append(control)); + + // Notify derived classes about new player control + NotifyPlayerAddedL(aPlayer, control); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::PlayerRemoved +// Called by the owning module when a player is removed +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSControlGroup::PlayerRemoved(CMMAPlayer *aPlayer) +{ + CMMAControl* control = AMMSUtil::FindControl( + aPlayer, iName, iControlType); + + // Do nothing if the player does not have a control belonging to this group. + if (!control) + { + return; + } + + // Remove the control of the player if the control is in the group. + TInt controlIndex = iControls.Find(control); + if (controlIndex != KErrNotFound) + { + // It is safe to cast CMMAControl to the subclass CAMMSControl, as only + // AMMS Controls are returned from FindControl method + CAMMSControl* ammsControl = static_cast< CAMMSControl* >(control); + + // Call DeallocateControl to delete the Control's Effect API class + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSControlGroup::PlayerRemoved calling DeallocateControl for type: %d", + ammsControl->iControlType); + ammsControl->DeallocateControl(); + + NotifyPlayerRemoved(aPlayer, ammsControl); + iControls.Remove(controlIndex); + } + + // Remove the state listener belonging to the given player. + + TInt listenerCount = iPlayerStateListeners->Count(); + TInt listenerIndex = KErrNotFound; + + for (TInt i = 0; i < listenerCount; i++) + { + // Elements in the listener array are never null. + if (iPlayerStateListeners->At(i)->Player() == aPlayer) + { + listenerIndex = i; + break; + } + } + + if (listenerIndex != KErrNotFound) + { + delete iPlayerStateListeners->At(listenerIndex); + iPlayerStateListeners->Delete(listenerIndex); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSControlGroup::CAMMSControlGroup +// C++ default constructor can NOT contain any code, that might leave. +// ----------------------------------------------------------------------------- +CAMMSControlGroup::CAMMSControlGroup( + const TDesC& aName, + TAMMSControlTypes aControlType) : + iName(aName), + iControlType(aControlType) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammseffectmodule.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammseffectmodule.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Module for holding control groups belonging to EffectModule. +* +*/ + + +// INCLUDE FILES +#include "cammseffectmodule.h" +#include "cammsaudiovirtualizercontrolgroup.h" +#include "cammsglobalmanager.h" +#include + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSEffectModule::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSEffectModule* CAMMSEffectModule::NewLC( + CAMMSGlobalManager* aGlobalManager) +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::NewLC +"); + + CAMMSEffectModule* self = new(ELeave) CAMMSEffectModule(aGlobalManager); + + CleanupStack::PushL(self); + self->ConstructL(); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::NewLC -"); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectModule::~CAMMSEffectModule() +// Destructor. +// ----------------------------------------------------------------------------- +// +CAMMSEffectModule::~CAMMSEffectModule() +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::~"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectModule::AddPlayerNoStateCheckL +// Adds player without checking its state. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSEffectModule::AddPlayerNoStateCheckL(CMMAPlayer* aPlayer) +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::AddPlayerNoStateCheckL +"); + + // Check that the player can be added. + User::LeaveIfError(iGlobalManager->PlayerAddingAllowed(aPlayer)); + + // Add the player to this module. + CAMMSModule::AddPlayerNoStateCheckL(aPlayer); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::AddPlayerNoStateCheckL -"); +} + + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSEffectModule::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::ConstructL +"); + + CAMMSModule::ConstructL(); + + // Add required controls to the EffectModule. + + AddControlGroupAndPopL(CAMMSAudioVirtualizerControlGroup::NewLC()); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSEffectModule::ConstructL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSEffectModule::CAMMSEffectModule +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSEffectModule::CAMMSEffectModule(CAMMSGlobalManager* aGlobalManager) + : iGlobalManager(aGlobalManager) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammsglobalmanager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammsglobalmanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,332 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class provides GlobalManager functionality. +* +*/ + + +// INCLUDE FILES +#include + +#include "cammsglobalmanager.h" +#include "cammsmodulecontainer.h" +#include "cammssoundsource3d.h" +#include "cammseffectmodule.h" + +// Audio 3d includes. +#include "cammsdopplercontrolgroup.h" +#include "cammslocationcontrolgroup.h" + +// Global manager +#include "cammsreverbcontrolgroup.h" +#include "cammsequalizercontrolgroup.h" +#include "cammsvolumecontrolgroup.h" +#include "cammspancontrolgroup.h" +#include "cammscommitcontrolgroup.h" +#include "cammsorientationcontrolgroup.h" + +#include "cammsplayerbuildergroup.h" +#include "cammsaudioplayerbuilder.h" +#include "cammsvolumecontrolbuilder.h" +#include "ammsconstants.h" + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSGlobalManager* CAMMSGlobalManager::NewLC() +{ + CAMMSGlobalManager* self = new(ELeave) CAMMSGlobalManager; + + CleanupStack::PushL(self); + self->ConstructL(); + + return self; +} + +// Destructor +CAMMSGlobalManager::~CAMMSGlobalManager() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::~CAMMSGlobalManager"); + delete iSpectator; + delete iEffectModules; + delete iSoundSource3Ds; + delete iPlayerBuilder; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::AddPlayerNotifyL +// Adds new player +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSGlobalManager::AddPlayerNotifyL(CMMAPlayer* aPlayer) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::AddPlayerNotifyL player type %S", + aPlayer->Type().Ptr()); + + // Add amms controls to player. + iPlayerBuilder->PreparePlayerL(aPlayer); + + // AddPlayerNoStateCheckL is used to add players to global manager and + // global controls because mma player may be started or prefetched before + // amms global manager is created. + + // Add player to global manager. All global control groups will be informed. + AddPlayerNoStateCheckL(aPlayer); +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::RemovePlayerNotify +// Removes player +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSGlobalManager::RemovePlayerNotify(CMMAPlayer* aPlayer) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::RemovePlayerNotify player type %S", + aPlayer->Type().Ptr()); + + // RemovePlayer can return only KErrNotFound or KErrNone, and in this case + // we do not need to handle KErrNotFound + RemovePlayerNoStateCheck(aPlayer); + + // Removing player from other modules + iEffectModules->RemovePlayer(aPlayer); + iSoundSource3Ds->RemovePlayer(aPlayer); +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::InitL +// Initializes GlobalManager. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSGlobalManager::InitL(RPointerArray< CMMAPlayer >& aPlayers) +{ + TInt playerCount = aPlayers.Count(); + + // Add all players to the global controls and to the spectator. + for (TInt i = 0; i < playerCount; i++) + { + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::InitL adding controls to %S", + aPlayers[ i ]->Type().Ptr()); + AddPlayerNotifyL(aPlayers[ i ]); + } +} + + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::CreateSoundSource3DL +// Creates a new sound source 3D module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +CAMMSModule* CAMMSGlobalManager::CreateSoundSource3DL() +{ + // InitL must have been called before call to this methdod. + __ASSERT_DEBUG(iSpectator, User::Invariant()); + + CAMMSSoundSource3D* soundSource3D = + CAMMSSoundSource3D::NewLC(iSpectator, this); + + iSoundSource3Ds->AppendL(soundSource3D); + + CleanupStack::Pop(soundSource3D); + + return soundSource3D; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::CreateEffectModuleL +// Creates a new effect module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +CAMMSModule* CAMMSGlobalManager::CreateEffectModuleL() +{ + CAMMSEffectModule* module = CAMMSEffectModule::NewLC(this); + + iEffectModules->AppendL(module); + + CleanupStack::Pop(module); + + return module; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::Spectator +// Returns the spectator. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +CAMMSModule* CAMMSGlobalManager::Spectator() +{ + return iSpectator; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::DisposeModule +// Disposes module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSGlobalManager::DisposeModule(CAMMSModule* aModule) +{ + // Remove the module from the module containers. + iSoundSource3Ds->RemoveModule(aModule); + iEffectModules->RemoveModule(aModule); + + // Delete the module itself. + delete aModule; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::PlayerAddingAllowed +// Checks whether the given player can be added to a module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSGlobalManager::PlayerAddingAllowed(CMMAPlayer* aPlayer) +{ + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::PlayerAddingAllowed %d +", + (TInt)aPlayer); + + TInt result = KErrNone; + + // Check whether the player can be added according to SoundSource3Ds. + TInt modules = iSoundSource3Ds->Count(); + + for (TInt i = 0; (result == KErrNone) && (i < modules); i++) + { + CAMMSModule* module = iSoundSource3Ds->At(i); + + result = PlayerAddingAllowed(aPlayer, module); + } + + + // Check whether the player can be added according to EffectModules. + modules = iEffectModules->Count(); + + for (TInt i = 0; (result == KErrNone) && (i < modules); i++) + { + CAMMSModule* module = iEffectModules->At(i); + + result = PlayerAddingAllowed(aPlayer, module); + } + + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::PlayerAddingAllowed %d -", result); + + return result; +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::CAMMSGlobalManager +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSGlobalManager::CAMMSGlobalManager() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSGlobalManager::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::ConstructL +"); + + CAMMSModule::ConstructL(); + + iSoundSource3Ds = new(ELeave) CAMMSModuleContainer(); + iEffectModules = new(ELeave) CAMMSModuleContainer(); + iPlayerBuilder = CAMMSPlayerBuilderGroup::NewL(); + iPlayerBuilder->AddBuilderAndPopL(CAMMSAudioPlayerBuilder::NewLC()); + iPlayerBuilder->AddBuilderAndPopL(CAMMSVolumeControlBuilder::NewLC()); + + // Add control groups to global manager + AddControlGroupAndPopL(CAMMSReverbControlGroup::NewLC()); + AddControlGroupAndPopL(CAMMSEqualizerControlGroup::NewLC()); + AddControlGroupAndPopL(CAMMSVolumeControlGroup::NewLC( + KAMMSGlobalVolume)); + +#ifndef __WINS__ + // PanControl is not supported in WINSCW builds. + // This is because of limited pan support in DirectX. + AddControlGroupAndPopL(CAMMSPanControlGroup::NewLC()); +#endif // __WINS__ + + // Create spectator and add controls. + iSpectator = CAMMSModule::NewL(); + iSpectator->AddControlGroupAndPopL(CAMMSLocationControlGroup::NewLC( + EAMMSSpectatorControl)); + iSpectator->AddControlGroupAndPopL(CAMMSOrientationControlGroup::NewLC()); + iSpectator->AddControlGroupAndPopL(CAMMSDopplerControlGroup::NewLC( + EAMMSSpectatorControl)); + + // Add Commit control group to global manager, and pass required references + AddControlGroupAndPopL(CAMMSCommitControlGroup::NewLC( + *iSpectator, + *iSoundSource3Ds)); + + LOG( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::ConstructL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSGlobalManager::PlayerAddingAllowed +// Checks whether the given player can be added to a module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CAMMSGlobalManager::PlayerAddingAllowed(CMMAPlayer* aPlayer, + CAMMSModule* aModule) +{ + LOG2( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::PlayerAddingAllowed %d %d +", + (TInt)aPlayer, (TInt)aModule); + + TBool playerExists = aModule->HasPlayer(aPlayer); + + TInt result = (playerExists ? KAMMSPlayerAlreadyInModuleError : KErrNone); + +// WINSCW build does not support audio mixing. +// Thus, check in WINSCW build that there is not any non-closed player +// in the module. If there is any non-closed player in the module, +// adding a new player is not allowed to ANY module. +// However, allow a player to be in CLOSED state, because it cannot be started +// anymore and cannot thus reserve any resources anymore. + +#ifdef __WINS__ + + if (result == KErrNone) + { + TInt players = aModule->PlayerCount(CMMAPlayer::EUnrealized, + CMMAPlayer::EStarted); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::PlayerAddingAllowed players=%d", + players); + + result = (players == 0 ? KErrNone : KAMMSMixingNotSupported); + } + +#endif // __WINS__ + + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSGlobalManager::PlayerAddingAllowed %d -", result); + + return result; +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammsmodule.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammsmodule.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,379 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a container for MAMMSControlGroup objects. +* +*/ + + +// INCLUDE FILES +#include "cammsmodule.h" +#include "cammscontrolgroup.h" +#include + + +// CONSTANTS +// Before further testing is done, 4 is sufficient average value to be used here. +const TInt KAMMSModuleDefaultGranularity = 4; + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSModule::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSModule* CAMMSModule::NewL() +{ + CAMMSModule* self = NewLC(); + CleanupStack::Pop(self); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSModule* CAMMSModule::NewLC() +{ + CAMMSModule* self = new(ELeave) CAMMSModule; + + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +// Destructor +CAMMSModule::~CAMMSModule() +{ + // Check that construction fully succeed. + if (iControlGroups) + { + // control groups are owned and they must be deleted. + iControlGroups->ResetAndDestroy(); + delete iControlGroups; + } + + // Players are not owned. + iPlayers.Close(); +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::AddControlGroupL +// Add control to iControlGroups array. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModule::AddControlGroupAndPopL(CAMMSControlGroup* aGroup) +{ + // Check in debug build that group is not null. + __ASSERT_DEBUG(aGroup, User::Invariant()); + + iControlGroups->AppendL(aGroup); + + // aGroup must be the previous item in the cleanupstack + CleanupStack::Pop(aGroup); +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::AddPlayerL +// Adds new player to this module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModule::AddPlayerL(CMMAPlayer* aPlayer) +{ + // Check in debug build that player is not null. + __ASSERT_DEBUG(aPlayer, User::Invariant()); + + // Must leave if the player is already in the module + if (HasPlayer(aPlayer)) + { + User::Leave(KErrArgument); + } + + // Must leave if player is in PREFETCHED or STARTED state + User::LeaveIfError(CheckPlayerState(aPlayer)); + + // Check that none of the players is not in PREFETCHED or STARTED state + User::LeaveIfError(CheckAllPlayersState()); + + AddPlayerNoStateCheckL(aPlayer); +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::RemovePlayer +// Removes player from module.. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::RemovePlayer(CMMAPlayer* aPlayer) +{ + // call RemovePlayerNoStateCheck only if aPlayer and all players in the + // module are in the right state. + TInt error = CheckPlayerState(aPlayer); + if (error == KErrNone) + { + error = CheckAllPlayersState(); + if (error == KErrNone) + { + error = RemovePlayerNoStateCheck(aPlayer); + } + } + return error; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::AddPlayerNoStateCheckL +// Adds player without checking its state. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModule::AddPlayerNoStateCheckL(CMMAPlayer* aPlayer) +{ + iPlayers.AppendL(aPlayer); + + // If adding players leaves CAMMSModule::CleanupAddPlayer method will be + // called and player removed from module and from groups. + CleanupStack::PushL(TCleanupItem(&CAMMSModule::CleanupAddPlayer, this)); + + // Inform all control groups + TInt count = iControlGroups->Count(); + for (TInt i = 0; i < count; i++) + { + iControlGroups->At(i)->PlayerAddedL(aPlayer); + } + + CleanupStack::Pop(); // CSI: 12 Parameter TCleanupItem cannot be used as a parameter in Pop # +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::RemovePlayerNoStateCheck +// Removes player without checking its state +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::RemovePlayerNoStateCheck(CMMAPlayer* aPlayer) +{ + TInt index = iPlayers.Find(aPlayer); + if (index != KErrNotFound) + { + // player was in the array, remove it + iPlayers.Remove(index); + + // inform all groups + TInt count = iControlGroups->Count(); + for (TInt i = 0; i < count; i++) + { + iControlGroups->At(i)->PlayerRemoved(aPlayer); + } + } + + // Find returned KErrNotFound if player was not in the module + return index; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::HasPlayer +// Checks whether the given player is in this module. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TBool CAMMSModule::HasPlayer(CMMAPlayer* aPlayer) +{ + LOG1( EJavaAMMS, EInfo, "AMMS:CAMMSModule::HasPlayer %d +", (TInt)aPlayer); + + TInt index = iPlayers.Find(aPlayer); + + LOG1( EJavaAMMS, EInfo, "AMMS:CAMMSModule::HasPlayer index=%d -", index); + + return (index != KErrNotFound); +} + + +#ifdef __WINS__ + +// ----------------------------------------------------------------------------- +// CAMMSModule::PlayerCount +// Returns the count of players whose state is between the given limits. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::PlayerCount(TInt aMinState, TInt aMaxState) +{ + LOG2( EJavaAMMS, EInfo, "AMMS:CAMMSModule::PlayerCount %d %d +", aMinState, aMaxState); + + TInt result = 0; + + TInt playerCount = iPlayers.Count(); + + LOG1( EJavaAMMS, EInfo, "AMMS:CAMMSModule::HasPlayer, players=%d", playerCount); + + for (TInt i = 0; i < playerCount; i++) + { + TInt playerState = iPlayers[ i ]->State(); + + LOG2( EJavaAMMS, EInfo, "AMMS:CAMMSModule::HasPlayer %d, state=%d", i, + playerState); + + if ((playerState >= aMinState) && + (playerState <= aMaxState)) + { + result++; + } + } + + LOG1( EJavaAMMS, EInfo, "AMMS:CAMMSModule::PlayerCount %d -", result); + + return result; +} + +#endif // __WINS__ + +// ----------------------------------------------------------------------------- +// CAMMSModule::CheckPlayerState +// Checks all players state. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::CheckAllPlayersState() +{ + TInt error = KErrNone; + + TInt playerCount = iPlayers.Count(); + + // Loop until all players are checked or one of the players is in + // PREFETCHED or STARTED state + for (TInt i = 0; (i < playerCount) && + (error == KErrNone); i++) + { + error = CheckPlayerState(iPlayers[ i ]); + } + return error; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::CheckPlayerState +// Checks player state. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::CheckPlayerState(CMMAPlayer* aPlayer) +{ + // Player may not be in PREFETCHED or STARTED state + TInt retVal = KErrNone; + TInt playerState = aPlayer->State(); + if (playerState == CMMAPlayer::EStarted || + playerState == CMMAPlayer::EPrefetched) + { + retVal = KErrNotReady; + } + return retVal; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::CleanupAddPlayer +// Static function to be used with TCleanupItem in AddPlayerNoStateCheckL +// method. This method removes last added player from module and control +// groups. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModule::CleanupAddPlayer(TAny* aModule) +{ + CAMMSModule* module = static_cast< CAMMSModule* >(aModule); + + // This method is called from AddPlayerNoStateCheckL and there is always + // at least one player. + __ASSERT_DEBUG(module->iPlayers.Count() > 0, User::Invariant()); + + // Remove last added player from module and from control groups + module->RemovePlayerNoStateCheck( + module->iPlayers[ module->iPlayers.Count() - 1 ]); +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::Find +// Find control group with specified class name. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +MAMMSControlGroup* CAMMSModule::Find(const TDesC& aClassName) +{ + MAMMSControlGroup* group = NULL; + TInt groupIndex = 0; + TInt groupCount = iControlGroups->Count(); + + // Loop until group is found or all group are checked + while (!group && (groupIndex < groupCount)) + { + MAMMSControlGroup* tmpGroup = iControlGroups->At(groupIndex); + + if (tmpGroup->ClassName() == aClassName) + { + // found the group, set return value which will stop while loop + group = tmpGroup; + } + + groupIndex++; + } + + return group; +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::At +// Index must be non-negative and less than the number of objects currently +// within the array otherwise the functions raise an E32USER-CBase 21 panic. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +MAMMSControlGroup* CAMMSModule::At(TInt aIndex) +{ + return iControlGroups->At(aIndex); // CSI: 1 Array range panic allowed according to function description # +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::Count +// return iControlGroup count. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSModule::Count() +{ + return iControlGroups->Count(); +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSModule::ConstructL() +{ + // Create array with default granularity, all derived classes must call + // this method. + iControlGroups = new(ELeave)CArrayPtrSeg< CAMMSControlGroup >( + KAMMSModuleDefaultGranularity); + +} + +// ----------------------------------------------------------------------------- +// CAMMSModule::CAMMSModule +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSModule::CAMMSModule() +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammsmodulecontainer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammsmodulecontainer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Container for CAMMSModule objects. +* +*/ + + +// INCLUDE FILES +#include + +#include "cammsmodulecontainer.h" + +// CONSTANTS +// Before further testing is done, 4 is sufficient average value to be used here. +const TInt KAMMSContainerDefaultGranularity = 4; + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +CAMMSModuleContainer::~CAMMSModuleContainer() +{ + ResetAndDestroy(); +} + +// ----------------------------------------------------------------------------- +// CAMMSModuleContainer::RemovePlayer +// Removes player from all modules. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModuleContainer::RemovePlayer(CMMAPlayer* aPlayer) +{ + // Remove player from all modules + for (TInt i = 0; i < Count(); i++) + { + At(i)->RemovePlayerNoStateCheck(aPlayer); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSModuleContainer::RemoveModule +// Removes module from container. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSModuleContainer::RemoveModule(CAMMSModule* aModule) +{ + // If the element is found, index is set to the position of that module + // element within the array. + TInt index = KErrNotFound; + + TKeyArrayFix key(0, ECmpTInt); // offset = 0, type integer + + // find returns 0, if the element with the specified key is found. Non-zero + // if the element with the specified key is not found + TInt retVal = Find(aModule, key, index); + + LOG1( EJavaAMMS, EInfo, "AMMS::CAMMSModuleContainer::DisposeModule find result %d", + retVal); + + if (retVal == KErrNone) + { + // Remove the element by position. The module itself is not deleted + // here, so it has to be deleted elsewhere if needed. + Delete(index); + } + // else, module was not added to this container +} + +// ----------------------------------------------------------------------------- +// CAMMSModuleContainer::CAMMSModuleContainer +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSModuleContainer::CAMMSModuleContainer(): + CArrayPtrSeg< CAMMSModule >(KAMMSContainerDefaultGranularity) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammsplayerstatelistener.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammsplayerstatelistener.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Implementation for player state listener. +* +*/ + + +// INCLUDE FILES +#include "cammsplayerstatelistener.h" +#include "cammscontrolgroup.h" +#include +#include + +// CONSTANTS +const TInt KErrorMessageSize = 32; +_LIT(KErrDefaultError, "AMMS error: %d"); + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::NewLC +// Two-phased constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSPlayerStateListener* CAMMSPlayerStateListener::NewLC( + CMMAPlayer* aPlayer, + CAMMSControlGroup* aControlGroup) +{ + CAMMSPlayerStateListener* self = + new(ELeave) CAMMSPlayerStateListener(aPlayer, + aControlGroup); + CleanupStack::PushL(self); + + self->ConstructL(); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::~CAMMSPlayerStateListener +// Destructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSPlayerStateListener::~CAMMSPlayerStateListener() +{ + if (iPlayer) + { + iPlayer->RemoveStateListener(this); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::ConstructL +// 2nd phase constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPlayerStateListener::ConstructL() +{ + __ASSERT_DEBUG(iPlayer && iControlGroup, User::Invariant()); + + iPlayer->AddStateListenerL(this); +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::CAMMSPlayerStateListener +// C++ constructor. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CAMMSPlayerStateListener::CAMMSPlayerStateListener( + CMMAPlayer* aPlayer, + CAMMSControlGroup* aControlGroup) + : iPlayer(aPlayer), + iControlGroup(aControlGroup) +{ +} + + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::Player +// Returns the player listened by this listener. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +CMMAPlayer* CAMMSPlayerStateListener::Player() +{ + return iPlayer; +} + +// ----------------------------------------------------------------------------- +// CAMMSPlayerStateListener::StateChanged +// Called when player state is changed. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSPlayerStateListener::StateChanged(TInt aState) +{ + TRAPD(err, iControlGroup->PlayerStateChangedL(iPlayer, aState)); + + if (err != KErrNone) + { + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/module/src/cammssoundsource3d.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/module/src/cammssoundsource3d.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,186 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Module for holding control groups belonging to SoundSource3D. +* +*/ + + +// INCLUDE FILES +#include "cammssoundsource3d.h" +#include "cammsdopplercontrolgroup.h" +#include "cammslocationcontrolgroup.h" +#include "cammsreverbsourcecontrolgroup.h" +#include "cammsdistanceattenuationcontrolgroup.h" +#include "cammspancontrolgroup.h" +#include "cammsglobalmanager.h" +#include + + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +CAMMSSoundSource3D* CAMMSSoundSource3D::NewLC(CAMMSModule* aSpectator, + CAMMSGlobalManager* aGlobalManager) +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::NewLC +"); + + CAMMSSoundSource3D* self = new(ELeave) CAMMSSoundSource3D(aSpectator, + aGlobalManager); + + CleanupStack::PushL(self); + self->ConstructL(); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::NewLC -"); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::~CAMMSSoundSource3D() +// Destructor. +// ----------------------------------------------------------------------------- +// +CAMMSSoundSource3D::~CAMMSSoundSource3D() +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::~"); +} + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::AddPlayerNoStateCheckL +// Adds player without checking its state. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSSoundSource3D::AddPlayerNoStateCheckL(CMMAPlayer* aPlayer) +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::AddPlayerNoStateCheckL +"); + + // Check that the player can be added. + User::LeaveIfError(iGlobalManager->PlayerAddingAllowed(aPlayer)); + + // Remove the pan control from the global manager because the pan control + // cannot be used when 3D sound is in use. + CAMMSPanControlGroup* panControlGroup = + (CAMMSPanControlGroup*)iGlobalManager->Find( + KAMMSPanControlClassName); + + // PanControl is not supported in WINSCW builds. + if (panControlGroup) + { + panControlGroup->PlayerRemoved(aPlayer); + } + + + // Add the player to the spectator. + iSpectator->AddPlayerNoStateCheckL(aPlayer); + + // Add the player to this module. + CAMMSModule::AddPlayerNoStateCheckL(aPlayer); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::AddPlayerNoStateCheckL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::RemovePlayerNoStateCheck +// Removes player without checking its state +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt CAMMSSoundSource3D::RemovePlayerNoStateCheck(CMMAPlayer* aPlayer) +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::RemovePlayerNoStateCheck +"); + + // Remove the player from the module. The method returns the index + // of the Player or an error code. + TInt error = CAMMSModule::RemovePlayerNoStateCheck(aPlayer); + + ELOG1( EJavaAMMS, "AMMS:CAMMSSoundSource3D::RemovePlayerNoStateCheck err %d", + error); + + // If the player was found in this module, remove the player also from the + // spectator. The method returns the index of the Player or an error code. + if (error >= KErrNone) + { + error = iSpectator->RemovePlayerNoStateCheck(aPlayer); + + ELOG1( EJavaAMMS, "AMMS:CAMMSSoundSource3D::RemovePlayerNoStateCheck err2 %d", + error); + } + + // If the player is deleted from the module, it is required to add the + // pan control to the global manager. + if (error >= KErrNone) + { + CAMMSPanControlGroup* panControlGroup = + (CAMMSPanControlGroup*)iGlobalManager->Find( + KAMMSPanControlClassName); + + // PanControl is not supported in WINSCW builds. + if (panControlGroup) + { + TRAP(error, panControlGroup->PlayerAddedL(aPlayer)); + } + + ELOG1( EJavaAMMS, "AMMS:CAMMSSoundSource3D::RemovePlayerNoStateCheck err3 %d", + error); + } + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::RemovePlayerNoStateCheck -"); + + return error; +} + + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +void CAMMSSoundSource3D::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::ConstructL +"); + + CAMMSModule::ConstructL(); + + // Add required controls to the SoundSource3D. + + AddControlGroupAndPopL(CAMMSDopplerControlGroup::NewLC( + EAMMSSoundSource3DControl)); + + AddControlGroupAndPopL(CAMMSLocationControlGroup::NewLC( + EAMMSSoundSource3DControl)); + + AddControlGroupAndPopL(CAMMSDistanceAttenuationControlGroup::NewLC()); + + AddControlGroupAndPopL(CAMMSReverbSourceControlGroup::NewLC()); + + LOG( EJavaAMMS, EInfo, "AMMS:CAMMSSoundSource3D::ConstructL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSSoundSource3D::CAMMSSoundSource3D +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +CAMMSSoundSource3D::CAMMSSoundSource3D(CAMMSModule* aSpectator, + CAMMSGlobalManager* aGlobalManager) + : iSpectator(aSpectator), + iGlobalManager(aGlobalManager) +{ +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/javasrc/com/nokia/amms/control/tuner/TunerControlImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/javasrc/com/nokia/amms/control/tuner/TunerControlImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,548 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements + * javax.microedition.amms.control.tuner.TunerControl + * +*/ + + +package com.nokia.amms.control.tuner; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Control; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.PlayerImpl; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.control.ControlImpl; +import com.nokia.mj.impl.rt.legacy.NativeError; + +public class TunerControlImpl + extends ControlImpl + implements javax.microedition.amms.control.tuner.TunerControl +{ + //preset name max length + private static final int MAX_PRESET_NAME_LENGTH = 100; + //max number of presets + private static final int MAX_NUMBER_OF_PRESETS = 20; + //all frequencys are in 100 Hertzs + private static final int HERTZ_MULTIPLIER = 100; + + /** + * Constructor + */ + public TunerControlImpl() + { + //JDEBUG( "AMMS TunerControlImpl Constructor" ); + } + + /** + * Gets the minimum frequency supported by this tuner + * with the given modulation. + * + * @param modulation The modulation whose supported minimum frequency + * is asked. + * @return The minimum frequency in 100 Hertzs. + * @throws IllegalArgumentException if the modulation is not supported or it is null. + */ + public int getMinFreq(String aModulation) + { + if (aModulation != MODULATION_FM) + { + throw new IllegalArgumentException("Modulation is not valid."); + } + + int minFreq = _getMinFreq(iEventSource, + iControlHandle); + + NativeError.check(minFreq); + + return minFreq / HERTZ_MULTIPLIER; + } + + /** + * Gets the maximum frequency supported by this tuner + * with the given modulation. + * + * @param modulation The modulation whose supported maximum frequency + * is asked. + * @return The maximum frequency in 100 Hertzs. + * @throws IllegalArgumentException if the modulation is not supported or it is null. + */ + public int getMaxFreq(String aModulation) + { + if (aModulation != MODULATION_FM) + { + throw new IllegalArgumentException("Modulation is not valid."); + } + + int maxFreq = _getMaxFreq(iEventSource, + iControlHandle); + + NativeError.check(maxFreq); + + return maxFreq / HERTZ_MULTIPLIER; + } + + /** + * Tunes to the given frequency or to the closest supported frequency. + * + * @param freq The frequency in 100 Hertzs that will be taken into use. + * If that frequency is not supported, the closest supported + * frequency will be taken into use. + * + * @param modulation The modulation to be used. TunerControl specifies + * predefined constants MODULATION_FM and MODULATION_AM + * but other modulations can be supported as well. Supported modulations can be queried + * by System property tuner.modulations. + * + * @throws IllegalArgumentException if freq is not inside the frequency band supported + * by the device or if the modulation is not supported or the modulation is null. + * + * @return the frequency in 100 Hertzs that was taken into use. + */ + public int setFrequency(int aFreq, String aModulation) + { + if (aModulation != MODULATION_FM) + { + throw new IllegalArgumentException("Modulation is not valid."); + } + + int freqInUse = _setFrequency(iEventSource, + iControlHandle, + aFreq * HERTZ_MULTIPLIER); + + NativeError.check(freqInUse); + + return freqInUse / HERTZ_MULTIPLIER; + } + + /** + * Gets the frequency which the tuner has been tuned to. + * + * @return The frequency to which the device has been tuned, in 100 Hertzs. + */ + public int getFrequency() + { + int freq = _getFrequency(iEventSource, iControlHandle); + + NativeError.check(freq); + + return freq / HERTZ_MULTIPLIER; + } + + /** + *

Seeks for the next broadcast signal. If the end of the Player's + * frequency band is reached before a signal was found, the scan + * continues from the other end until a signal is found or the + * starting frequency is reached.

+ * + *

After seeking, the frequency of the Player is the one that + * was returned or if nothing was found, the original frequency.

+ * + * @param startFreq the frequency in 100 Hertzs wherefrom the scan starts (inclusive) + * + * @param modulation The modulation to be used. TunerControl specifies + * predefined constants MODULATION_FM and MODULATION_AM + * but other modulations can be supported as well. Supported modulations can be queried + * by System property tuner.modulations. + * @param upwards if true, the scan proceeds towards higher frequencies, + * otherwise towards lower frequencies + * + * @return The found frequency in 100 Hertzs or, if no signal was found, 0. + * + * @throws IllegalArgumentException if startFreq is not between the supported minimum + * and maximum frequencies or if the modulation is null. + * @throws MediaException if the seek functionality is not available for the given modulation. + */ + public int seek(int aStartFreq, String aModulation, boolean aUpwards) + throws MediaException + { + if (aModulation != MODULATION_FM) + { + throw new IllegalArgumentException("Modulation is not valid."); + } + + int foundFreq = _seek(iEventSource, + iControlHandle, + aStartFreq * HERTZ_MULTIPLIER, + aUpwards); + + NativeError.check(foundFreq); + + return foundFreq / HERTZ_MULTIPLIER; + } + + /** + * Gets the current squelching (muting in frequencies without broadcast) + * setting. + * + * @return true if squelch is on or false if squelch is off. + */ + public boolean getSquelch() + { + int retValue = _getSquelch(iEventSource, iControlHandle); + + NativeError.check(retValue); + + if (retValue == NativeError.KErrNone) + { + return true; + } + + return false; + } + + /** + * Sets squelching on or off. Squelching means muting the frequencies + * that do not contain radio broadcast. + * + * @param squelch true to turn the squelch on or false to turn the squelch off. + * @throws MediaException if the given squelch setting is not supported. + */ + public void setSquelch(boolean aSquelch) throws MediaException + { + int err = _setSquelch(iEventSource, iControlHandle, aSquelch); + + NativeError.check(err); + } + + /** + * Gets the modulation in use. + * + * @return The modulation currently in use. + */ + public String getModulation() + { + //only FM modulation is supported + return MODULATION_FM; + } + + /** + * Gets the strength of the recepted signal. + * + * @return A value between 0 and 100 where 0 means the faintest and 100 the strongest possible signal strength. + * @throws MediaException if querying the signal strength is not supported. + */ + public int getSignalStrength() throws MediaException + { + int signalStrength = _getSignalStrength(iEventSource, + iControlHandle); + + if (signalStrength != NativeError.KErrNone) + { + throw new MediaException("Signal strength is not supported."); + } + + return signalStrength; + } + + /** + * Gets the stereo mode in use. + * + * @return The stereo mode in use. Stereo mode is one of MONO, + * STEREO or AUTO. + */ + public int getStereoMode() + { + int stereoMode = _getStereoMode(iEventSource, iControlHandle); + + NativeError.check(stereoMode); + + return stereoMode; + } + + /** + * Sets the stereo mode. + * + * @param mode The stereo mode to be used. Stereo mode is one of MONO, + * STEREO or AUTO. + * @throws IllegalArgumentException if the given mode is not supported. + */ + public void setStereoMode(int aStereoMode) + { + if (aStereoMode != MONO && aStereoMode != STEREO && aStereoMode != AUTO) + { + throw new IllegalArgumentException(); + } + + int err = _setStereoMode(iEventSource, iControlHandle, aStereoMode); + + if (err != NativeError.KErrNone) + { + throw new IllegalArgumentException("Stereo mode is not supported."); + } + } + + /** + * Gets the number of presets. The numbering of presets starts from one and the largest + * preset number equals the value returned from this method. + * + * @return The number of presets, or zero if the presets are not supported. + */ + public int getNumberOfPresets() + { + + return 0; + } + + /** + * Tunes the tuner by using settings specified in the preset. Changes to + * presets following a usePreset call do not tune the tuner automatically. + * + * @param preset the preset to be used. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets. + */ + public void usePreset(int aPreset) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + int err = _usePreset(iEventSource, iControlHandle, aPreset); + + NativeError.check(err); + } + + /** + * Configures the preset using current frequency and modulation + * (and stereo mode if native presets support storing it). + * + * @param preset the preset to be set. + * @throws IllegalArgumentException if preset < 1 or preset > number of preset range. + * @throws SecurityException if setting presets has been prohibited. + */ + public void setPreset(int aPreset) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + int err = _setPreset(iEventSource, iControlHandle, aPreset); + + NativeError.check(err); + } + + /** + * Configures the preset using given settings. + * The stereo mode might not be stored if it is not supported by the presets. + * (In that case, IllegalArgumentException is not thrown.) + * + * @param preset the preset to be configured. + * @param freq the frequency of the preset in 100 Hertzs. + * @param mod the modulation of the preset. + * @param stereoMode the stereo mode of the preset. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets or + * freq or modulation are not available or if the modulation is null or if stereoMode is not a supported stereo mode. + * @throws SecurityException if setting presets has been prohibited. + */ + public void setPreset(int aPreset, int aFreq, String aModulation, int aStereoMode) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + if (aModulation != MODULATION_FM) + { + throw new IllegalArgumentException("Modulation is not valid."); + } + if (aStereoMode != MONO && aStereoMode != STEREO && aStereoMode != AUTO) + { + throw new IllegalArgumentException("Stereo mode is not supported."); + } + + int err = _setPreset(iEventSource, iControlHandle, aPreset, aFreq * HERTZ_MULTIPLIER, aStereoMode); + + NativeError.check(err); + } + + /** + * Gets the preset's frequency. + * + * @param preset the preset whose frequency is to be returned. + * @return The frequency of the preset in 100 Hertzs. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets. + */ + public int getPresetFrequency(int aPreset) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + + int presetFreq = _getPresetFrequency(iEventSource, iControlHandle, aPreset); + + NativeError.check(presetFreq); + + return presetFreq / HERTZ_MULTIPLIER; + } + + /** + * Gets the preset's modulation. + * + * @param preset the preset whose modulation is to be returned. + * @return The modulation of the preset. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets. + */ + public String getPresetModulation(int aPreset) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + return MODULATION_FM; + } + + /** + * Gets the preset's stereo mode. + * + * @param preset the preset whose stereo mode is to be returned. + * @return The stereo mode of the preset. Stereo mode is one of + * MONO, STEREO or AUTO. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets. + * @throws MediaException if the presets do not support storing of the stereo mode. + */ + public int getPresetStereoMode(int aPreset) throws MediaException + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + + int presetStereoMode = _getPresetStereoMode(iEventSource, iControlHandle, aPreset); + + NativeError.check(presetStereoMode); + + return presetStereoMode; + } + + /** + * Gets the preset name. + * + * @param preset the preset whose name is to be returned. + * @return A String containing the preset name. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets. + */ + public String getPresetName(int aPreset) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + + int[] error = new int[ 1 ]; + + String presetName = _getPresetName(iEventSource, iControlHandle, aPreset, error); + + NativeError.check(error[ 0 ]); + + return presetName; + } + + /** + * Sets the preset name. + * + * @param preset the preset whose name is to be set. + * @param name the name of the preset. + * @throws IllegalArgumentException if preset < 1 or preset > number of presets or + * if the name is null. + * @throws SecurityException if setting presets has been prohibited. + */ + public void setPresetName(int aPreset, String aName) + { + if (aPreset < 0 || aPreset > MAX_NUMBER_OF_PRESETS) + { + throw new IllegalArgumentException("Preset out of preset range."); + } + if (aName.length() > MAX_PRESET_NAME_LENGTH) + { + throw new IllegalArgumentException("Preset name too long"); + } + + int err = _setPresetName(iEventSource, iControlHandle, aPreset, aName); + + NativeError.check(err); + } + + + private native int _getMinFreq(int aEventSourceHandle, + int aTunerControlHandle); + + private native int _getMaxFreq(int aEventSourceHandle, + int aTunerControlHandle); + + private native int _setFrequency(int aEventSourceHandle, + int aTunerControlHandle, + int aFreq); + + private native int _getFrequency(int aEventSourceHandle, + int aTunerControlHandle); + + + private native int _seek(int aEventSourceHandle, + int aTunerControlHandle, + int aStartFreq, + boolean aUpwards); + + private native int _getSquelch(int aEventSourceHandle, + int aTunerControlHandle); + + private native int _setSquelch(int aEventSourceHandle, + int aTunerControlHandle, + boolean aSquelch); + + private native int _getSignalStrength(int aEventSourceHandle, + int aTunerControlHandle); + + private native int _getStereoMode(int aEventSourceHandle, + int aTunerControlHandle); + + private native int _setStereoMode(int aEventSourceHandle, + int aTunerControlHandle, + int aStereoMode); + + private native int _usePreset(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset); + + private native int _setPreset(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset); + + private native int _setPreset(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset, + int aFreq, + int aStereoMode); + + private native int _getPresetFrequency(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset); + + private native int _getPresetStereoMode(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset); + + private native int _setPresetName(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset, + String aName); + + private native String _getPresetName(int aEventSourceHandle, + int aTunerControlHandle, + int aPreset, + int[] aError); + + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/javasrc/com/nokia/microedition/media/protocol/capture/radio/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/javasrc/com/nokia/microedition/media/protocol/capture/radio/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is capture://radio protocol + * +*/ + +package com.nokia.microedition.media.protocol.capture.radio; + +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.PlayerImpl; +import javax.microedition.media.MediaException; +import com.nokia.mj.impl.rt.legacy.NativeError; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.amms.control.tuner.TunerControlImpl; + +/** + * This class is capture://radio protocol. + */ +public class Protocol + implements com.nokia.microedition.media.protocol.Protocol +{ + // Constants + private static final String TUNER_CONTROL_NAME = + "javax.microedition.amms.control.tuner.TunerControl"; + + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + // JDEBUG( "AMMS Tuner Protocol createPlayer" ); + + String locatorParameters = aLocator.getParameters(); + + // Create native tuner player. The native tuner player + // creates a native tuner control and adds it to its list. + // Handle for the native player are returned. + int playerHandle = 0; + playerHandle = _createNativeTunerPlayer( + ManagerImpl.getEventSource(), + locatorParameters); + +// JDEBUG( "AMMS Tuner Protocol createPlayer playerHandle = " + playerHandle ); + + NativeError.check(playerHandle); + + PlayerImpl tunerPlayer = new PlayerImpl(playerHandle); + + return tunerPlayer; + } + + /** + * Creates native tuner player. + * Native tuner player creates and adds native tuner control. + * + * @param aEventSourceHandle Handle to event source. + * @param aLocatorParameters + * @return Error code. + */ + private native int _createNativeTunerPlayer(int aEventSourceHandle, + String aLocatorParameters); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/external_include/fmradioenginecrkeys.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/external_include/fmradioenginecrkeys.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Definition of central repository keys for FM Radio Engine. +* +*/ + + +#ifndef FMRADIOENGINECRKEYS_H +#define FMRADIOENGINECRKEYS_H + +// FM Radio Engine UID +const TUid KCRUidFMRadioEngine = {0x101F7CBC}; + +// Radio headset volume +const TUint32 KRadioHeadsetVolume = 0x00000001; + +// Radio speaker volume +const TUint32 KRadioSpeakerVolume = 0x00000002; + +// The last played radio frequency +const TUint32 KFmRadioFrequency = 0x00000003; + +// The last played radio channel +const TUint32 KFmRadioChannel = 0x00000004; + +// The radio mode before radio off +const TUint32 KFmRadioMode = 0x00000005; + +// The first preset channel's location in central repository +const TUint32 KFmRadioPresetChannel1 = 0x0000000A; + +#endif // FMRADIOENGINECRKEYS_H + +// End of file + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/external_include/tuner.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/external_include/tuner.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,2535 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Header file for Tuner component. +* +*/ + + +#ifndef TUNER_H +#define TUNER_H + +#include +#include +#include +#include +#include +#include +#include +#include +class RRadioSession; + +/** +@file +@publishedAll +@prototype +*/ +/** +The Tuner Capabilities structure defines the capabilities of the tuner +on the device, as retrieved using the function GetCapabilities. +*/ +class TTunerCapabilities +{ +public: + inline TTunerCapabilities(); + inline TTunerCapabilities(TUint32 aTunerBands, TUint32 aAdditionalFunctions); +public: + /** + Bitfield (as defined by CMMTunerUtility::TTunerBand) with the bits of the + supported bands set + */ + TUint32 iTunerBands; + + /** Tuner Function bit flags - may be extended in future */ + enum TTunerFunctions + { + /** Recording of Tuner Audio is possible */ + ETunerFunctionRecording = 0x01, + /** Tuner can record and play back simultaneously */ + ETunerFunctionSimultaneousPlayAndRecord = 0x02, + /** The tuner requires an external antenna (e.g. a headset) to function */ + ETunerFunctionRequiresAntenna = 0x04, + /** CMMRdsTunerUtility supported */ + ETunerFunctionRds = 0x08, + /** The tuner can be used when the device is in flight mode */ + ETunerFunctionAvailableInFlightMode = 0x10 + }; + + /** Bitfield (as defined by ETunerFunctions) with the bits of the supported functions set */ + TUint32 iAdditionalFunctions; +}; + +/** +Class representing a frequency. +*/ +class TFrequency +{ +public: + inline TFrequency(); + explicit inline TFrequency(TInt aFrequency); + inline TInt operator==(const TFrequency& aFrequency) const; + inline TInt operator!=(const TFrequency& aFrequency) const; + inline TInt operator> (const TFrequency& aFrequency) const; + inline TInt operator>=(const TFrequency& aFrequency) const; + inline TInt operator< (const TFrequency& aFrequency) const; + inline TInt operator<=(const TFrequency& aFrequency) const; +public: + /** + The Frequency, in Hertz. A TInt is at least 32 bits, giving a maximum frequency + of at least 2.4GHz (i.e. 0x7fffffff Hz) + */ + TInt iFrequency; +}; + + +class MMMTunerObserver; +class MMMTunerChangeObserver; +class MMMTunerStereoObserver; +class MMMSignalStrengthObserver; +class MMMTunerAudioPlayerObserver; +class MMMTunerAudioRecorderObserver; +class CMMTunerAudioPlayerUtility; +class CMMTunerAudioRecorderUtility; +class CMMTunerScannerUtility; +class CMMRdsTunerUtility; + +/** +The MMF Tuner API is present to allow clients to control +the tuner hardware present on a device. +*/ +class CMMTunerUtility : public CBase +{ + friend class CMMTunerAudioPlayerUtility; + friend class CMMTunerAudioRecorderUtility; + friend class CMMTunerScannerUtility; + friend class CMMRdsTunerUtility; +public: + /** Tuner Band bit flags - may be extended in future */ + enum TTunerBand + { + ETunerNoBand = 0x00, + /** Long Wave - uses frequencies */ + ETunerBandLw = 0x01, + /** Amplitude Modulation or Medium Wave - uses frequencies */ + ETunerBandAm = 0x02, + /** Frequency Modulation, European and American band - uses frequencies */ + ETunerBandFm = 0x04, + /** Frequency Modulation, Japanese band - uses frequencies */ + ETunerBandJapaneseFm = 0x08, + /** Digital Audio Broadcasting - uses channels */ + ETunerBandDab = 0x10, + /** Digital Video Broadcasting */ + ETunerBandDvb = 0x20 + }; + /** + Search direction enumeration + */ + enum TSearchDirection + { + /** Search for stations upwards - i.e. by increasing frequency */ + ESearchDirectionUp = 1, + /** Search for stations downwards - i.e. by decreasing frequency */ + ESearchDirectionDown + }; + /** + The Tuner Access Priority enables clients to correctly identify their needs + when it comes to accessing the tuner. A process must have the MultimediaDD + capability to use priorities greater than ETunerAccessPriorityNormal. + */ + enum TTunerAccessPriority + { + /** Radio accessible when device is idle */ + ETunerAccessPriorityBackground = -100, + /** Ordinary application priority */ + ETunerAccessPriorityNormal = 0, + /** Radio is to be used as an alarm sound */ + ETunerAccessPriorityAlarm = 75, + /** System use only */ + ETunerAccessPrioritySystem = 100 + }; + /** + Bitmasks to indicate what state the tuner is in. + */ + enum TTunerState + { + /** + Tuner is active, and can therefore report frequency etc. If this bit is + not set, none of the others should be set. + */ + ETunerStateActive = 0x01, + /** The tuner is playing sound. */ + ETunerStatePlaying = 0x02, + /** The tuner is currently recording. */ + ETunerStateRecording = 0x04, + /** The tuner is currently retuning or searching for a new station. */ + ETunerStateRetuning = 0x08, + }; +public: + + /** + Factory function to create a new instance of the Tuner. Tuner access priority + setting is required to ensure that applications such as alarms using the radio + as an alarm sound are not prevented from doing so by other clients. Priority + setting is needed for audio output when accessing the sound device. Tuner is + ready for use on return from this function. + + @param aObserver The observer object for receiving async completion callbacks + @param aTunerIndex An index from 0 to TunersAvailable() - 1 specifying the tuner + device to use. + @param aAccessPriority Tuner access priority value + @leave KErrNoMemory Out of memory + @leave KErrNotFound The specified tuner or tuner controller is not present + @return A pointer and ownership of the fully constructed CMMTunerUtility object + */ + IMPORT_C static CMMTunerUtility* NewL(MMMTunerObserver& aObserver, + TTunerBand aBand, + TInt aTunerIndex, + CMMTunerUtility::TTunerAccessPriority aAccessPriority = ETunerAccessPriorityNormal); + + IMPORT_C virtual ~CMMTunerUtility(); + + + + /** + Set the current tuner access priority of this client. This priority is used to + arbitrate between multiple tuner clients, determining who get control of the + tuner. + + The platform security capability is MultimediaDD and a client with this capability + is allowed to set the priority in preference to a client with a lower capability. + + @param aAccessPriority The new priority to use. + @capability MultimediaDD + @return A standard system error code. + */ + IMPORT_C TInt SetPriority(TTunerAccessPriority aAccessPriority); + + /** + Get the current tuner access priority of this client. + + @param aAccessPriority A variable to which the current priority will be written. + @return A standard system error code. + */ + IMPORT_C TInt GetPriority(TTunerAccessPriority& aAccessPriority) const; + + + /** + Get the current state of the tuner. + + @param aState A variable to set with the current state. Bits set according to + TTunerState. + @return A standard system error code. + */ + IMPORT_C TInt GetState(TUint32& aState) const; + + /** + Indicates if the external antenna is currently attached or not. The tuner + capabilties should be queried to determine if the external antenna is required + to use the tuner or not; A value of false returned here does not necessarily + imply that the tuner cannot be used. + + @param aAttached When this function returns, this will contain ETrue if and only + if an external antenna is attached. + @return A standard system error code. + */ + IMPORT_C TInt IsAntennaAttached(TBool& aAttached); + + /** + Indicates if the device is currently in 'flight mode' or not. The tuner + capabilities should be queried to determine in the tuner can be used in flight + mode or not. + + @param aFlightMode On return, this will have been set to ETrue if and only if + the device is in flight mode. + @return A standard system error code. + */ + IMPORT_C TInt GetFlightMode(TBool& aFlightMode) const; + + /** + Tune the tuner to the required frequency specified in Hertz. This is an asynchronous + command and will result in a callback to MToTuneComplete or MToTunerError. + + If the session does not currently have control of the tuner, a request for control + will be made. If control of the tuner is granted, a callback to MToTunerControlGranted + will occur. If not, there will be a callback to MtoTunerError with error value + KErrAccessDenied. + + Once control of the tuner has been granted, it will be retained until either a + call to ReleaseTunerControl, or the session is preempted in which case there + will be a callback to MToTunerError with error value KErrAccessDenied. + + @param aFrequency The frequency to tune to + @param aBand The band to which aFrequency belongs + */ + IMPORT_C void Tune(TFrequency aFrequency); + + /** + Find a radio station, starting at the start frequency and searching in the + direction specified (i.e. Up or down) the search is limited to the specified + band. If the session does not currently have control of the tuner, a request + for control will be made. If control of the tuner is granted, a callback to + MToTunerControlGranted will occur. If not, there will be a callback to MToTunerError + with error value KErrAccessDenied. + + Once control of the tuner has been granted, it will be retained until either a + call to ReleaseTunerControl, or the session is preempted in which case there + will be a callback to MToTunerError with error value KErrAccessDenied. + + A callback to MToTuneComplete will occur if the Seek is successful. + + @param aBand The band + @param aSearchDirect The direction to search in + @param aCircularSeek If set to ETrue the station seek will loop back to the other + end of the band once the end of the band has been reached. (Defaults to ETrue) + If not set reaching the end of the band without finding a station will result + in a callback to MToTuneComplete with error KErrNotFound. + */ + IMPORT_C void StationSeek(TSearchDirection aSearchDirection); + + /** + Cancels an ongoing retune operation, as initiated by a call to Tune or StationSeek. + The usual callback will not occur if this has been called. + + Has not affect if no tune or seek operation is ongoing. + */ + IMPORT_C void CancelRetune(); + + /** + Makes a synchronous request for control of the tuner. If this method returns + KErrNone, control of the tuner has been granted. Control of the tuner is kept + until it is explically released using ReleaseTunerControl, or it is revoked + in which case a callback to MToTunerError with an error of KErrAccessDenied + will occur. + + If this method returns with KErrAccessDenied, a request to recieve a + notifiaction when control could be granted can be made using + NotifyTunerControl. + + Note that methods that require control of the tuner (such as Tune) will make + a request for control themselves if control has not already been granted. + + @return A standard system error code. If control was granted, KErrNone, and if + control was denied KErrAccessDenied. + */ + IMPORT_C TInt RequestTunerControl(); + + /** + Makes an asyncronous request for control of the tuner. This method should be + called after an control of the tuner has been denied to receive a notification + when control of the tuner can be granted. A callback to MToTunerControlGranted + will occur in this event. + */ + IMPORT_C TInt NotifyTunerControl(); + + /** + Release control of the tuner, allowing other clients to tune it. Change + notifications may still be received. A request for control of the tuner can be + made again by calling RequestTunerControl, or any methods that require control + of the tuner. + */ + IMPORT_C void ReleaseTunerControl(); + + /** + Release the tuner. Any ongoing playing or recording activity will be stopped, + control of the tuner will be released, and the hardware will be powered down if + no other clients need it. + */ + IMPORT_C void Close(); + + /** + Retrieve the current frequency that the tuner is tuned to + + @param aFrequency The variable to set to the current frequency, + -1 if channels are in use + @param aBand The variable used to set the current band. + @return A standard system error code + */ + IMPORT_C TInt GetFrequency(TFrequency& aFrequency) const; + + /** + Retrieve the signal strenth of the currently tuned signal + + @param aSignalStrength Variable into which the signal strength will be written. + @return A standard system error code + */ + IMPORT_C TInt GetSignalStrength(TInt& aSignalStrength) const; + + /** + Get the maximum possible signal strength of a tuned signal. + + @param aMaxSignalStrength A variable that will have the maximun signal strength + written to. + @return A standard system error code + */ + IMPORT_C TInt GetMaxSignalStrength(TInt& aMaxSignalStrength) const; + + /** + Request notifications when the signal strength changes. Due to the potentially + short intervals at which the signal strength may change at, notifications will + only be sent when a relatively large change occurrs. This should allow a visual + display of signal strength to be maintained fairly accurately. + + The first signal strength notification will be sent immediately after this + request. + + @param aObserver The object which will receive notifications of signal strength + changes. + @return A standard system error code + */ + IMPORT_C TInt NotifySignalStrength(MMMSignalStrengthObserver& aObserver); + + /** + Cancel an outstanding NotifySignalStrength request. + */ + IMPORT_C void CancelNotifySignalStrength(); + + /** + Find out if the current signal is being received in stereo or not. + + @param aStereo On return, will be ETrue if and only if a stereo signal is + currently being received. + */ + IMPORT_C TInt IsStereoSignal(TBool& aStereo); + + /** + Request notifications when stereo reception is lost/restored. + + @param aObserver The object requiring notification when a stereo signal is lost + or restored. The first notification will occur immediately. + @return A standard system error code + */ + IMPORT_C TInt NotifyStereoChange(MMMTunerStereoObserver& aObserver); + + /** + Cancels a stereo change notification request. + */ + IMPORT_C void CancelNotifyStereoChange(); + + /** + Indicates whether the reception should be forced into monophonic mode. + + @param aMono If ETrue, all reception will be in mono mode even if a stereo + signal is available. If EFalse, a stereo signal will be received when + possible. + @return A standard system error code. + */ + IMPORT_C TInt ForceMonoReception(TBool aMono); + + /** + Find out whether reception is forced into monophonic mode or not. + + @param aMono This will be set to ETrue if all reception is forced to be mono. If + this is EFalse, this does not imply that stereo reception is currently + available. + @return A standard system error code. + */ + IMPORT_C TInt GetForcedMonoReception(TBool& aMono) const; + + /** + Sets the current squleching (muting in frequencies without reception) setting. + + @param aEnabled ETrue to enable squelching, EFalse to disable it. + @return KErrNone if successful, else a system wide error code. + */ + IMPORT_C TInt SetSquelch(TBool aEnabled); + + /** + Gets the current squleching (muting in frequencies without reception) setting. + + @param aEnabled This will be set to ETrue if squelching is enabled, EFalse otherwise. + @return KErrNone if successful, else a system wide error code. + */ + IMPORT_C TInt GetSquelch(TBool& aEnabled) const; + + /** + Get the capabilities of the tuner on the device + + @param aCaps The capabilities object to fill + @return A standard system error code + */ + IMPORT_C TInt GetCapabilities(TTunerCapabilities& aCaps) const; + + /** + Get the frequency range (in Hertz) of the specified band. + This function should be used to enquire the frequency range + of the bands that GetCapabilities reports as supported. + + @param aBand The band to query + @param aBottomFrequency The variable to set to the lowest frequency allowed + @param aTopFrequency The variable to set to the highest frequency allowed + @return A standard system error code + */ + IMPORT_C TInt GetFrequencyBandRange(TFrequency& aBottomFrequency, TFrequency& aTopFrequency); + + /** + Request to be notified when the tuned frequency or channel changes, or when the + tuner changes state (e.g. starts playing or recording) + + @param aObserver The object wishing to receive tuning change events + @return A standard system error code + */ + IMPORT_C TInt NotifyChange(MMMTunerChangeObserver& aObserver); + + /** + Cancel request to be notified when the tuned frequency or channel changes + */ + IMPORT_C void CancelNotifyChange(); + + /** + Send a synchronous custom command to the tuner. + + @param aFunction The function number to indicate which function is to be called + on the interface defined by the first IPC argument + @param aArgs The IPC arguments to send to the tuner. The first of these + arguments must be the UID of the interface within the tuner to which the + command is destined, represented as an integer. Failure to set the first + argument properly will result in the command completing with + KErrNotSupported at best, but possibly the client being panicked. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync(TInt aFunction, const TIpcArgs& aArgs); + + /** + Send an asynchronous custom command to the tuner. + + @param aFunction The function number to indicate which function is to be called + on the interface defined by the first IPC argument + @param aArgs The IPC arguments to send to the tuner. The first of these + arguments must be the UID of the interface within the tuner to which the + command is destined, represented as an integer. Failure to set the first + argument properly will result in the command completing with + KErrNotSupported at best, but possibly the client being panicked. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + */ + IMPORT_C void CustomCommandAsync(TInt aFunction, const TIpcArgs& aArgs, TRequestStatus& aStatus); + + /** + Get the Tuner Player Utility + + @param aAccessPriority A variable to which the current priority will be written. + @return A standard system error code. + */ + IMPORT_C CMMTunerAudioPlayerUtility* TunerPlayerUtilityL(MMMTunerAudioPlayerObserver& aObserver) ; + /** + Get the Tuner Recorder Utility + + @param aAccessPriority A variable to which the current priority will be written. + @return A standard system error code. + */ + IMPORT_C CMMTunerAudioRecorderUtility* TunerRecorderUtilityL(MMMTunerAudioRecorderObserver& aObserver) ; + + /** + Get the Tuner Scanner Utility + + @param aAccessPriority A variable to which the current priority will be written. + @return A standard system error code. + */ + IMPORT_C CMMTunerScannerUtility* TunerScannerUtilityL() ; + + /** + Get the Tuner Rds Utility + + @param aAccessPriority A variable to which the current priority will be written. + @return A standard system error code. + */ + IMPORT_C CMMRdsTunerUtility* TunerRdsUtilityL() ; + +private: + CMMTunerUtility(); +protected: + class CBody; +private: + CBody* iBody; +}; + +/** +The Tuner Observer mixin class defines asynchronous +event completion function callbacks +*/ +class MMMTunerObserver +{ +public: + /** + Tune complete event. This event is asynchronous + and is received after a call to the Tune method. + + @param aError A standard system error + */ + virtual void MToTuneComplete(TInt aError) = 0; + +}; + +/** +The Tuner Change Observer mixin class defines the interface via which +notification for changes to the tuned frequency, channel and other tuner +state can be received. A client interested in these notifications +should call the function CMMTunerUtility::NotifyChange. +*/ +class MMMTunerChangeObserver +{ +public: + /** + Called when the tuned frequency changes + + @param aOldFrequency The frequency in use before the change + @param aNewFrequency The new tuned frequency + */ + virtual void MTcoFrequencyChanged(const TFrequency& aOldFrequency, const TFrequency& aNewFrequency) = 0; + + /** + Called when the state of the tuner changes. + + @param aOldState The old state. Bits are set according to TTunerState. + @param aNewState The new state. Bits are set according to TTunerState. + */ + virtual void MTcoStateChanged(const TUint32& aOldState, const TUint32& aNewState) = 0; + + /** + This function is called when an external antenna is detached from the device. + This does not necessarily indicate that the tuner can no longer be used; the + capabilities of the tuner indicate if the external antenna is required in order + to use the tuner. + */ + virtual void MTcoAntennaDetached() = 0; + + /** + This function is called when an external antenna is attached to the device. If + the antenna is required to use the tuner, this indicates that the tuner can be + used again. + */ + virtual void MTcoAntennaAttached() = 0; + + /** + This function is called when the device enters or leaves flight mode. If the tuner + cannot be used in flight mode when the device enters this mode, this indicates + that the tuner can no longer be used; the capabilities of the tuner indicate if + it can be used in flight mode or not. + + @param aFlightMode ETrue if the device has just entered flight mode, EFalse if + flight mode has just been left. + */ + virtual void FlightModeChanged(TBool aFlightMode) = 0; +}; + +/** +The stereo observer mixin class defines the interface by which clients can be +notified when a stereo signal is received/lost. An interested client should call +the function CMMTunerUtility::NotifyStereoChange. +*/ +class MMMTunerStereoObserver +{ +public: + /** + Called when stereo reception is lost/restored. + + @param aStereo If true, indicates that stereo reception has just been restored. + If false, indicates that stereo reception has just been lost. + */ + virtual void MTsoStereoReceptionChanged(TBool aStereo) = 0; + + /** + Called when a client enables/disabled forced mono reception. + + @param aForcedMono ETrue if reception is forced to be mono, even when a stereo + signal is available. + */ + virtual void MTsoForcedMonoChanged(TBool aForcedMono) = 0; +}; + +/** +This mixin class should be derived from by clients wishing to receive +notifications when the signal strength changes. Such a client should call +function CMMTunerUtility::NotifySignalStrength. +*/ +class MMMSignalStrengthObserver +{ +public: + /** + Callback indicating that the signal strength has changed by an amount meriting + a notification. + + @param aNewSignalStrength The new signal strength. + */ + virtual void MssoSignalStrengthChanged(TInt aNewSignalStrength) = 0; +}; + + +class MMMAudioResourceNotificationCallback; + +/** +The Tuner Audio Player Utility is used to initiate and control playback of audio +from the tuner. +*/ +class CMMTunerAudioPlayerUtility : public CBase, public MCustomCommand +{ + friend class CMMTunerUtility::CBody; +public: + + IMPORT_C ~CMMTunerAudioPlayerUtility(); + + /** + Set-up the API for playing the output from tuner to the speaker asynchronously. + Calls MMMTunerAudioPlayerObserver::MTapoInitializeComplete on completion. This must be + called before Play. + + @param aPriority Sound device priority value + @param aPref Sound device priority preference value + */ + IMPORT_C void InitializeL(TInt aAudioPriority = EMdaPriorityNormal, TMdaPriorityPreference aPref = EMdaPriorityPreferenceTimeAndQuality); + + /** + Start playback of the tuner output. To stop playback, call Mute, or Stop if + play will not need to be restarted. InitializeL() must have already been + called, and a callback to MTapoInitializeComplete with an error of KErrNone must + have occurred; if this is not the case, this raises a TunerAudioPlay 1 panic. + */ + IMPORT_C void Play(); + + /** + Mute or unmute playback. + + Raises a TunerAudioPlay 1 panic if the player is not properly initialized. + + @param aMute ETrue to mute the audio, EFalse to unmute it. + @return A standard system error code + */ + IMPORT_C TInt Mute(TBool aMute); + + /** + Stop playback, and release the output device for use by other clients + + Raises a TunerAudioPlay 1 panic if the player is not properly initialized. + + Playback should already be under way. + */ + IMPORT_C void Stop(); + + /** + Set the current audio priority. This priority is used to arbitrate + between multiple audio sources trying to access the audio hardware. + + @param aPriority A priority between EMdaPriorityMin and EMdaPriorityMax + @param aPref Time vs Quality priority preferences, enumerated in TMdaPriorityPreference + @return A standard system error code + */ + IMPORT_C TInt SetPriority(TInt aPriority, TMdaPriorityPreference aPref); + + /** + Get the current audio priority. This is used to arbitrate between simultaneous + accesses to the sound hardware. + + @param aPriority A priority between EMdaPriorityMin and EMdaPriorityMax to return + @param aPref Time vs Quality priority preferences to return, enumerated in TMdaPriorityPreference + @return A standard system error code + */ + IMPORT_C TInt GetPriority(TInt& aPriority, TMdaPriorityPreference& aPref) const; + + /** + Set the volume to the specified level + + Raises a TunerAudioPlay 1 panic if the player is not properly initialized. + + @param aVolume The volume level to set + @return A standard system error code + */ + IMPORT_C TInt SetVolume(TInt aVolume); + + /** + Return the current volume + + @param aVolume The variable to set to the current volume + @return A standard system error code + */ + IMPORT_C TInt GetVolume(TInt& aVolume) const; + + /** + Define a volume ramp, aRampInterval defining + the interval between valid volume settings + + Raises a TunerAudioPlay 1 panic if the player is not properly initialized. + + @param aRampInterval The time interval over which the volume + should be increased from zero to the current volume setting + @return A standard system error code + */ + IMPORT_C TInt SetVolumeRamp(const TTimeIntervalMicroSeconds& aRampInterval); + + /** + Return the maximum volume supported + + @return The maximum volume setting permitted + */ + IMPORT_C TInt MaxVolume() const; + + /** + Set the stereo balance between left and right channels + + Raises a TunerAudioPlay 1 panic if the player is not properly initialized. + + @param aBalance The balance value to set - must be between + KMMFBalanceMaxLeft and KMMFBalanceMaxRight + @return A standard system error code + */ + IMPORT_C TInt SetBalance(TInt aBalance = KMMFBalanceCenter); + + /** + Return the current stereo balance + + @param aBalance The variable to set to the current balance + @return A standard system error code + */ + IMPORT_C TInt GetBalance(TInt& aBalance) const; + + /** + Register for audio resource notifications, in the event that the audio resource is lost due to pre-emption + by a higher priority audio client. + */ + IMPORT_C TInt RegisterAudioResourceNotification(MMMAudioResourceNotificationCallback& aCallback, TUid aNotificationEventUid, const TDesC8* aNotificationRegistrationData = NULL); + + /** + Cancel an outstanding audio resource notification. + */ + IMPORT_C void CancelRegisterAudioResourceNotification(TUid aNotificationEventId); + + /** + Returns the controller implementation information associated with the current controller, if any. + + @return The controller implementation structure associated with the controller + @leave KErrNotFound if no controller is in use. + */ + IMPORT_C const CMMFControllerImplementationInformation& ControllerImplementationInformationL(); + + /** + Send a synchronous custom command to the playback controller, if ones exists. + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2); + + /** + Send a synchronous custom command to the playback controller, if ones exists. + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataFrom The area of memory to which the controller framework + will write any data to be passed back to the client. Can't be KNullDesC8. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom); + + /** + Send an asynchronous custom command to the playback controller, if ones exists. + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + */ + IMPORT_C void CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TRequestStatus& aStatus); + + /** + Send an asynchronous custom command to the playback controller, if ones exists. + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataFrom The area of memory to which the controller framework + will write any data to be passed back to the client. Can't be KNullDesC8. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + */ + IMPORT_C void CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom, + TRequestStatus& aStatus); + +protected: + /** + Factory function to create a new Tuner Audio Player utility. Note that only one audio player + utility may be created per instance of CMMTunerUtility. Multiple instances will result in an + error of KErrAlreadyExists when InitializeL() is called. + + @param aTuner The tuner object which this utility will play the audio from. + @param aObserver The observer of the player utility to receive asychronous completion and + notifiction callbacks. + @leave KErrNoMemory Out of memory + @leave KErrNotSupported If the given tuner doesn't support audio playback. + @return A new tuner audio player utility. + */ + static CMMTunerAudioPlayerUtility* NewL(CMMTunerUtility& aTuner, RRadioSession& aRadioSession, MMMTunerAudioPlayerObserver& aObserver); + +private: + CMMTunerAudioPlayerUtility(); +private: + class CBody; + CBody* iBody; +}; + +class MMMTunerAudioPlayerObserver +{ +public: + /** + The TEvent enumeration is used to indicate which type of event is being sent to the client. + Each event will be associated with an error code and potentially some addition information, + and will be passed to the client via method MTapoPlayEvent(). + */ + enum TEventType + { + /** An event relating to the tuner itself. Any error other than KErrNone associated + with this event type may indicate that the tuner cannot be used anymore. + + No additional information is associated with this type of event. */ + ETunerEvent, + /** + An event relating to audio playback. + + No additional information is associated with this type of event. + */ + EAudioEvent + }; +public: + /** + Initialize complete event. This event is asynchronous and is received after + a call to CMMTunerAudioPlayerUtility::InitializeL(). + + @param aError A standard system error + */ + virtual void MTapoInitializeComplete(TInt aError) = 0; + + /** + Passes an asychronous event to the tuner client. + + @param aEvent The type of event. See enumeration MMMTunerAudioPlayerObserver::TEventType + for more information about when the event types mean. + @param aError An error code associated with the event. + @param aAdditionalInfo Any additional information associated with the event, or NULL if + no such additional information exists. + */ + virtual void MTapoPlayEvent(TEventType aEvent, TInt aError, TAny* aAdditionalInfo) = 0; +}; + +/** +This class is used to perform recording of audio from the tuner. Many of the methods +in this class have identical functionality to similarly names functions in class +CMdaAudioRecorderUtility. +*/ +class CMMTunerAudioRecorderUtility : public CBase +{ + friend class CMMTunerUtility::CBody; +public: + + IMPORT_C ~CMMTunerAudioRecorderUtility(); + + /** + Initialize for recording from the tuner to the specified file + asynchronously. Calls MMMTunerAudioRecorderObserver::MTaroInitializeComplete on completion + + @param aRecordFilename The name of the file to create, if necessary, and record to + @param "aDestinationDataType" Data type for recording + @param "aControllerUid" The Uid of the controller to use for recording + @param "aDestinationFormatUid" Uid of record format + @param aPriority Sound device priority value + @param aPref Sound device priority preference value + */ + IMPORT_C void InitializeL(const TDesC& aRecordFilename, + TFourCC aDestinationDataType = KFourCCNULL, + TUid aControllerUid=KNullUid, + TUid aDestinationFormatUid=KNullUid, + TInt aAudioPriority = EMdaPriorityNormal, + TMdaPriorityPreference aPref = EMdaPriorityPreferenceTimeAndQuality); + + /** + Initialize for recording from the tuner to the specified descriptor + asynchronously. Calls MMMTunerAudioRecorderObserver::MTaroInitializeComplete on completion + + @param aRecordDescriptor The descriptor to record to + @param "aDestinationDataType" Data type for recording + @param "aControllerUid" The Uid of the controller to use for recording + @param "aDestinationFormatUid" Uid of record format + @param aPriority Sound device priority value + @param aPref Sound device priority preference value + */ + IMPORT_C void InitializeL(TDes8& aRecordDescriptor, + TFourCC aDestinationDataType = KFourCCNULL, + TUid aControllerUid=KNullUid, + TUid aDestinationFormatUid=KNullUid, + TInt aAudioPriority = EMdaPriorityNormal, + TMdaPriorityPreference aPref = EMdaPriorityPreferenceTimeAndQuality); + + /** + Return a list of the supported data types for the record destination + @param "aSupportedDataTypes" list of four character codes, representing supported data + encodings for the record destination. + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void GetSupportedDestinationDataTypesL(RArray& aSupportedDataTypes) const; + + /** + Set the data type of the destination audio clip + @param "aDataType" four character code, representing the encoding of the destination audio clip + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void SetDestinationDataTypeL(TFourCC aDataType); + + /** + Return the data type of the destination audio clip + @returns four character code, representing the encoding of the destination audio clip + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C TFourCC DestinationDataTypeL() const; + + /** + Set the bit rate for recording + @param "aBitRate" destination bit rate in bits/second + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void SetDestinationBitRateL(TUint aBitRate); + + /** + Return the recording bit rate + @returns destination bit rate in bits/second + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C TUint DestinationBitRateL() const; + + /** + Return a list of the supported bit rates for recording + @param "aSupportedBitRates" List of bit rates supported for the record + destination + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void GetSupportedBitRatesL(RArray& aSupportedBitRates) const; + + /** + Set the sample rate for the record destination + @param "aSampleRate" The sample rate of the record destination + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void SetDestinationSampleRateL(TUint aSampleRate); + + /** + Return the sample rate of the record destination + @returns The sample rate of the record destination + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C TUint DestinationSampleRateL() const; + + /** + Get a list of supported recording sample rates. + @param "aSupportedSampleRates" List of the sample rates that are supported for + recording + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void GetSupportedSampleRatesL(RArray& aSupportedSampleRates) const; + + /** + Set the format of the audio clip. This can only be done if the audio clip does not + exist + + @param "aFormatUid" Uid of the audio clip format + @leaves KErrAlreadyExists if the clip already exists and the format is different + from the existing format, or can leave with one of the system-wide error codes + */ + IMPORT_C void SetDestinationFormatL(TUid aFormatUid); + + /** + Return the format of the audio clip + @returns Uid of the audio clip format + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C TUid DestinationFormatL() const; + + /** + Set the number of channels for the recorded audio clip + @param "aNumberOfChannels" The number of channels to record + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void SetDestinationNumberOfChannelsL(TUint aNumberOfChannels); + + /** + Return the number of channels in audio clip + @returns number of channels supported by audio clip + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C TUint DestinationNumberOfChannelsL() const; + + /** + Return a list of the supported number of channels for recording + @param "aSupportedNumChannels" List of the number of channels supported for + recording + @leaves Can leave with one of the system-wide error codes + */ + IMPORT_C void GetSupportedNumberOfChannelsL(RArray& aSupportedNumChannels) const; + + /** Start recording of the tuner output */ + IMPORT_C void RecordL(); + + /** + Pause recording. Recording can be resumed with another call to Record. + + @return A standard system error code + */ + IMPORT_C TInt PauseRecord(); + + /** + Stop recording, and release the output device for use by other clients + + Recording should already be under way. + */ + IMPORT_C void Stop(); + + /** + Stop recording, and release the output device for use by other clients + + Recording should already be under way. + */ + IMPORT_C void Close(); + + /** + Return the maximum value for the gain + + @return The maximum gain. For devices where automatic gain control is used, this value may be zero. + */ + IMPORT_C TInt MaxGain() const; + + /** + Sets the gain for the audio device to a specified value. + + @param aGain The gain setting. This can be any value from zero to the value returned by a call to + MaxGain(). A value which is less than zero is set to zero. A value which is greater than + MaxGain() is set to MaxGain(). + */ + IMPORT_C void SetGain(TInt aGain); + + /** + Sets the current recording balance setting between the left and right stereo channels + + The balance can be changed before or during recording and is effective immediately. + + @param aBalance The balance value to set. Any value between KMMFBalanceMaxLeft and + KMMFBalanceMaxRight, the default value being KMMFBalanceCenter. + @return An error code indicating if the call was successful. KErrNone on success, + otherwise another of the system-wide error codes. + */ + IMPORT_C TInt SetRecordBalance(TInt aBalance = KMMFBalanceCenter); + + /** + Returns the current recording balance setting between the left and right stereo channels. + + @param aBalance On return, contains the current recording balance between KMMFBalanceMaxLeft + and KMMFBalanceMaxRight. + @return An error code indicating if the call was successful. KErrNone on success, otherwise + another of the system-wide error codes. + */ + IMPORT_C TInt GetRecordBalance(TInt& aBalance) const; + + /** + Set the current audio priority. This priority is used to arbitrate + between multiple audio sources trying to access the audio hardware. + + @param aPriority A priority between EMdaPriorityMin and EMdaPriorityMax + @param aPref Time vs Quality priority preferences, enumerated in TMdaPriorityPreference + @return A standard system error code + */ + IMPORT_C TInt SetPriority(TInt aPriority, TMdaPriorityPreference aPref); + + /** + Get the current audio priority. This is used to arbitrate between simultaneous + accesses to the sound hardware. + + @param aPriority A priority between EMdaPriorityMin and EMdaPriorityMax to return + @param aPref Time vs Quality priority preferences to return, enumerated in TMdaPriorityPreference + @return A standard system error code + */ + IMPORT_C TInt GetPriority(TInt& aPriority, TMdaPriorityPreference& aPref) const; + + /** + Register for audio resource notifications, in the event that the audio resource is lost due to pre-emption + by a higher priority audio client. + */ + IMPORT_C TInt RegisterAudioResourceNotification(MMMAudioResourceNotificationCallback& aCallback, TUid aNotificationEventUid, const TDesC8* aNotificationRegistrationData = NULL); + + /** + Cancel an outstanding audio resource notification. + */ + IMPORT_C void CancelRegisterAudioResourceNotification(TUid aNotificationEventId); + + + /** + Sets the maximum size for a file that is being recorded. + + When this limit is reached, MMF stops recording and notifies the client application. Notification is caused + by MMdaObjectStateChangeObserver::MoscoStateChangeEvent() with the error code KErrEof. + + This function is provided so that applications such as recorders can limit the amount of file storage/memory + that should be allocated. + + @param aMaxWriteLength + The maximum file size in kilobytes. If the default value is used, there is no maximum file size. + + */ + IMPORT_C void SetMaxWriteLength(TInt aMaxWriteLength = KMdaClipLocationMaxWriteLengthNone); + + /** + Returns the recording time available for the selected file or descriptor and encoding format. + */ + IMPORT_C const TTimeIntervalMicroSeconds& RecordTimeAvailable(); + + /** + Returns the duration of the audio sample data. + */ + IMPORT_C const TTimeIntervalMicroSeconds& Duration(); + + /** + Return the controller implementation information structure of the current controller + + @leave KErrNoMemory Out of memory + @return A reference to the current controller information + */ + IMPORT_C const CMMFControllerImplementationInformation& ControllerImplementationInformationL(); + + /* + Returns the number of meta data entries associated with this clip. + @return Number of metadata entries + */ + IMPORT_C TInt GetNumberOfMetaDataEntries(TInt& aNumEntries); + + /* + Returns the specified meta data entry from the current audio clip. + @return Metadata entry + */ + IMPORT_C CMMFMetaDataEntry* GetMetaDataEntryL(TInt aMetaDataIndex); + + /* + Adds a meta data entry to the audio clip. + */ + IMPORT_C void AddMetaDataEntryL(CMMFMetaDataEntry& aMetaDataEntry); + + /* + Removes a specified meta data entry from the audio clip + @return An error code indicating if the call was successful + */ + IMPORT_C TInt RemoveMetaDataEntry(TInt aMetaDataIndex); + + /* + Replaces the specified meta data entry with a new entry + */ + IMPORT_C void ReplaceMetaDataEntryL(TInt aMetaDataIndex, CMMFMetaDataEntry& aMetaDataEntry); + + + /** + Send a synchronous custom command to the recording controller + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2); + + /** + Send a synchronous custom command to the recording controller + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataFrom The area of memory to which the controller framework + will write any data to be passed back to the client. Can't be KNullDesC8. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom); + + /** + Send an asynchronous custom command to the recording controller + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + @return A standard system error code + */ + IMPORT_C void CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TRequestStatus& aStatus); + + /** + Send an asynchronous custom command to the recording controller + + @param aDestination The destination of the message, consisting of the uid of + the interface of this message + @param aFunction The function number to indicate which function is to be called + on the interface defined in the aDestination parameter + @param aDataTo1 The first chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataTo2 The second chunk of data to be copied to the controller + framework. The exact contents of the data are dependent on the + interface being called. Can be KNullDesC8. + @param aDataFrom The area of memory to which the controller framework + will write any data to be passed back to the client. Can't be KNullDesC8. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + @return A standard system error code + */ + IMPORT_C void CustomCommandAsync( + const TMMFMessageDestinationPckg& aDestination, + TInt aFunction, + const TDesC8& aDataTo1, + const TDesC8& aDataTo2, + TDes8& aDataFrom, + TRequestStatus& aStatus); + +protected: + /** + Create a new audio recorder utility. Note that only one audio recorder utility may be created + per instance of CMMTunerUtility. Multiple instances will result in an error of KErrAlreadyExists + when InitializeL() is called. + */ + static CMMTunerAudioRecorderUtility* NewL(CMMTunerUtility& aTuner, MMMTunerAudioRecorderObserver& aObserver); + +private: + CMMTunerAudioRecorderUtility(); +private: + class CBody; + CBody* iBody; + +}; + +class MMMTunerAudioRecorderObserver +{ +public: + /** + The TEvent enumeration is used to indicate which type of event is being sent to the client. + Each event will be associated with an error code and potentially some addition information, + and will be passed to the client via method MTaroRecordEvent(). + */ + enum TEventType + { + /** An event relating to the tuner itself. Any error other than KErrNone associated + with this event type may indicate that the tuner cannot be used anymore. + + No additional information is associated with this type of event. */ + ETunerEvent, + /** + An event relating to audio recording. + + No additional information is associated with this type of event. + */ + EAudioEvent + }; +public: + /** + Initialize complete event. This event is asynchronous and is received after + a call to CMMTunerAudioRecorderUtility::InitializeL. + + @param aError A standard system error + */ + virtual void MTaroInitializeComplete(TInt aError) = 0; + + /** + Passes an asychronous event to the tuner client. + + @param aEvent The type of event. See enumeration MMMTunerAudioRecorderObserver::TEventType + for more information about when the event types mean. + @param aError An error code associated with the event. + @param aAdditionalInfo Any additional information associated with the event, or NULL if + no such additional information exists. + */ + virtual void MTaroRecordEvent(TEventType aEvent, TInt aError, TAny* aAdditionalInfo) = 0; +}; + +/** +This class augments CMMTunerUtility to provide station scanning functionality, +whereby the frequency spectrum is searched, pausing for a specified amount of +time when a station is found. +*/ +class CMMTunerScannerUtility : public CBase +{ + friend class CMMTunerUtility::CBody; +public: + + IMPORT_C ~CMMTunerScannerUtility(); + + /** + Continuously scan for a radio station, pausing for the time specified before + continuing on to the next station. Call StopScan to select the currently tuned + station. The search is limited to the specified band. + + @note The control of a CMMTunerUtility object must have been passed to this + class (using TransferTunerControl) before this function is called. + + @param aBand The band to which aStartFrequency belongs + @param aSearchDirect The direction to search in + @param aPauseDuration Time to pause at each station + @param aCircularScan If set to ETrue the station scan will loop back to the other + end of the band once the end of the band has been reached. (Defaults to ETrue) + */ + IMPORT_C void StationScan(CMMTunerUtility::TSearchDirection aSearchDirection, + TTimeIntervalMicroSeconds32 aPauseDuration + ); + + /** + Stop scanning and use the currently tuned station + + @return ETrue if a station is tuned, EFalse otherwise + */ + IMPORT_C TBool StopScan(); + +protected: + /** + Factory function to create a new CMMTunerScannerUtility. + + @param aTuner The tuner with which to perform the scanning. + @leave KErrNoMemory Out of memory. + @return A newly contructed tuner scanner utility. + */ + static CMMTunerScannerUtility* NewL(CMMTunerUtility& aTuner,CMMTunerUtility::TTunerBand aBand); + +private: + CMMTunerScannerUtility(); +private: + class CBody; + CBody* iBody; + +}; + + +/** Programme Station name, 8 characters */ +typedef TBuf<8> TRdsStationName; +/** Programme Type Name, 8 characters */ +typedef TBuf<8> TRdsProgrammeTypeName; +/** RDS Programme Identifier, a unique ID for each radio station */ +typedef TInt TRdsProgrammeIdentifier; + +/** +Programme Item Number - identifies the start time of the current programme, +as published by the broadcaster. +*/ +class TRdsProgrammeItemNumber +{ +public: + /** The day of the month of the broadcast, in the range 1-31 */ + TInt iDayOfMonth; + /** The hour of the day, in the range 0-23 */ + TInt iHour; + /** The minute past the hour, in the range 0-59 */ + TInt iMinute; +public: + inline TInt operator==(const TRdsProgrammeItemNumber& aPin) const; + inline TInt operator!=(const TRdsProgrammeItemNumber& aPin) const; +}; + +/** +An RDS extended country code. The meaning of a value of this type is defined +by the RDS specification, IEC62106. +*/ +typedef TInt TRdsCountryCode; + +/** +An RDS language identification code. The meaning of a value of this type is +defined by the RDS specification, IEC62106. +*/ +typedef TInt TRdsLanguageIdentifier; + +/** +RDS Programme Type. + +The interpretation of values of this type depends on the origin of the RDS +broadcast: in North America, a slightly different standard, RBDS, is used. +These PTY codes are defined by static values KRbdsPtyXxxxx, for example +KRbdsPtySoftRock. + +Elsewhere, including Europe, the RDS standard is used. In these areas, the +PTY codes are defined by static values KRdsPtyXxxxx, for example +KRdsPtyChildrensProgrammes. + +In all other important aspects, the European RDS and North American RBDS +standards are identical. +*/ +typedef TInt TRdsProgrammeType; + +/** No programme type or undefined */ +const static TRdsProgrammeType KRdsPtyNone = 0; +/** News */ +const static TRdsProgrammeType KRdsPtyNews = 1; +/** CurrentAffairs */ +const static TRdsProgrammeType KRdsPtyCurrentAffairs = 2; +/** Information */ +const static TRdsProgrammeType KRdsPtyInformation = 3; +/** Sport */ +const static TRdsProgrammeType KRdsPtySport = 4; +/** Education */ +const static TRdsProgrammeType KRdsPtyEducation = 5; +/** Drama */ +const static TRdsProgrammeType KRdsPtyDrama = 6; +/** Culture */ +const static TRdsProgrammeType KRdsPtyCulture = 7; +/** Science */ +const static TRdsProgrammeType KRdsPtyScience = 8; +/** VariedSpeech */ +const static TRdsProgrammeType KRdsPtyVariedSpeech = 9; +/** PopMusic */ +const static TRdsProgrammeType KRdsPtyPopMusic = 10; +/** RockMusic */ +const static TRdsProgrammeType KRdsPtyRockMusic = 11; +/** EasyListening */ +const static TRdsProgrammeType KRdsPtyEasyListening = 12; +/** LightClassical */ +const static TRdsProgrammeType KRdsPtyLightClassical = 13; +/** SeriousClassics */ +const static TRdsProgrammeType KRdsPtySeriousClassical = 14; +/** OtherMusic */ +const static TRdsProgrammeType KRdsPtyOtherMusic = 15; +/** Weather */ +const static TRdsProgrammeType KRdsPtyWeather = 16; +/** Finance */ +const static TRdsProgrammeType KRdsPtyFinance = 17; +/** ChildrensProgrammes */ +const static TRdsProgrammeType KRdsPtyChildrensProgrammes = 18; +/** SocialAffairs */ +const static TRdsProgrammeType KRdsPtySocialAffairs = 19; +/** Religion */ +const static TRdsProgrammeType KRdsPtyReligion = 20; +/** PhoneIn */ +const static TRdsProgrammeType KRdsPtyPhoneIn = 21; +/** Travel */ +const static TRdsProgrammeType KRdsPtyTravel = 22; +/** Leisure */ +const static TRdsProgrammeType KRdsPtyLeisure = 23; +/** JazzMusic */ +const static TRdsProgrammeType KRdsPtyJazzMusic = 24; +/** CountryMusic */ +const static TRdsProgrammeType KRdsPtyCountryMusic = 25; +/** NationalMusic */ +const static TRdsProgrammeType KRdsPtyNationalMusic = 26; +/** OldiesMusic */ +const static TRdsProgrammeType KRdsPtyOldiesMusic = 27; +/** FolkMusic */ +const static TRdsProgrammeType KRdsPtyFolkMusic = 28; +/** Documentary */ +const static TRdsProgrammeType KRdsPtyDocumentary = 29; +/** AlarmTest */ +const static TRdsProgrammeType KRdsPtyAlarmTest = 30; +/** Alarm */ +const static TRdsProgrammeType KRdsPtyAlarm = 31; + + +/** No programme type or undefined */ +const static TRdsProgrammeType KRbdsPtyNone = 0; +/** News */ +const static TRdsProgrammeType KRbdsPtyNews = 1; +/** Informaion */ +const static TRdsProgrammeType KRbdsPtyInformation = 2; +/** Sports */ +const static TRdsProgrammeType KRbdsPtySports = 3; +/** Talk */ +const static TRdsProgrammeType KRbdsPtyTalk = 4; +/** Rock */ +const static TRdsProgrammeType KRbdsPtyRock = 5; +/** Classic Rock */ +const static TRdsProgrammeType KRbdsPtyClassicRock = 6; +/** Adult Hits */ +const static TRdsProgrammeType KRbdsPtyAdultHits = 7; +/** Soft Rock */ +const static TRdsProgrammeType KRbdsPtySoftRock = 8; +/** Top 40 */ +const static TRdsProgrammeType KRbdsPtyTop40 = 9; +/** Country */ +const static TRdsProgrammeType KRbdsPtyCountry = 10; +/** Oldies */ +const static TRdsProgrammeType KRbdsPtyOldies = 11; +/** Soft */ +const static TRdsProgrammeType KRbdsPtySoft = 12; +/** Nostalgia */ +const static TRdsProgrammeType KRbdsPtyNostalgia = 13; +/** Jazz */ +const static TRdsProgrammeType KRbdsPtyJazz = 14; +/** Classical */ +const static TRdsProgrammeType KRbdsPtyClassical = 15; +/** Rhythm and Blues */ +const static TRdsProgrammeType KRbdsPtyRhythmAndBlues = 16; +/** Soft Rhythm and Blues */ +const static TRdsProgrammeType KRbdsPtySoftRhythmAndBlues = 17; +/** Language */ +const static TRdsProgrammeType KRbdsPtyLanguage = 18; +/** Religious Music */ +const static TRdsProgrammeType KRbdsPtyReligiousMusic = 19; +/** Religious Talk */ +const static TRdsProgrammeType KRbdsPtyReligiousTalk = 20; +/** Personality */ +const static TRdsProgrammeType KRbdsPtyPersonality = 21; +/** Public */ +const static TRdsProgrammeType KRbdsPtyPublic = 22; +/** College */ +const static TRdsProgrammeType KRbdsPtyCollege = 23; +/** Unassigned */ +const static TRdsProgrammeType KRbdsPtyUnassigned1 = 24; +/** Unassigned */ +const static TRdsProgrammeType KRbdsPtyUnassigned2 = 25; +/** Unassigned */ +const static TRdsProgrammeType KRbdsPtyUnassigned3 = 26; +/** Unassigned */ +const static TRdsProgrammeType KRbdsPtyUnassigned4 = 27; +/** Unassigned */ +const static TRdsProgrammeType KRbdsPtyUnassigned5 = 28; +/** Weather */ +const static TRdsProgrammeType KRbdsPtyWeather = 29; +/** Emergency Test */ +const static TRdsProgrammeType KRbdsPtyEmergencyTest = 30; +/** Emergency */ +const static TRdsProgrammeType KRbdsPtyEmergency = 31; + +/** +The RDS Capabilities class defines the capabilities of the RDS tuner on the +device, as retrieved using the function GetRdsCapabilities. +*/ +class TRdsCapabilities +{ +public: + /** RDS Function Bit Flags */ + enum TRdsFunctions + { + /** Traffic Announcement */ + ERdsFunctionTa = 0x01, + /** Regional Links */ + ERdsFunctionRegLink = 0x02, + /** News Announcement */ + ERdsFunctionNa = 0x04, + /** Programme Type */ + ERdsFunctionPty = 0x08, + /** Clock Time */ + ERdsFunctionCt = 0x10, + /** Enhanced Other Networks */ + ERdsFunctionEon = 0x20, + /** Alternative Frequency */ + ERdsFunctionAf = 0x40 + }; +public: + /** Bitfield as defined by ERdsFunctions with the bits of the supported functions set */ + TUint32 iRdsFunctions; +}; + +class MMMRdsDataObserver; +class MMMRdsEonObserver; +class MMMRdsStateChangeObserver; +class MMMRdsAnnouncementObserver; + +/** +This class represents the basic RDS data associated with an RDS station. +*/ +class TRdsData +{ +public: + inline TRdsData(); +public: + /** + Enumeration to indicate a subset of the members of class TRdsData. These values should + be bitwise or'ed together to indicate which members belong in a set. + */ + enum TField + { + /** Indicates the the member iPi is in a set */ + EProgrammeIdentifier = 0x001, + /** Indicates the the member iPs is in a set */ + EStationName = 0x002, + /** Indicates the the member iTp is in a set */ + ETrafficProgramme = 0x004, + /** Indicates the the member iTa is in a set */ + ETrafficAnnouncement = 0x008, + /** Indicates the the member iPty is in a set */ + EProgrammeType = 0x010, + /** Indicates the the member iPtyn is in a set */ + EProgrammeTypeName = 0x020, + /** Indicates the the member iPin is in a set */ + EProgrammeItemNumber = 0x040, + /** Indicates the the member iMs is in a set */ + EMusicSpeech = 0x080, + /** Indicates the the member iBroadcastLanguage is in a set */ + EBroadcastLanguage = 0x100, + /** Indicates the the member iEcc is in a set */ + EExtendedCountryCode = 0x200 + }; + /** + A value indicating a set containig all RDS data encapsulated by class TRdsData. + */ + const static TUint32 KAllRdsData = (EProgrammeIdentifier | EStationName | ETrafficProgramme | ETrafficAnnouncement + | EProgrammeType | EProgrammeTypeName | EProgrammeItemNumber | EMusicSpeech + | EBroadcastLanguage | EExtendedCountryCode); +public: + /** Programme Identifier of the station */ + TRdsProgrammeIdentifier iPi; + /** Programme Station name of the station */ + TRdsStationName iPs; + /** Value of the Traffic Programme flag of the station */ + TBool iTp; + /** Value of the Traffic Announcement flag of the station */ + TBool iTa; + /** Programme Type of the station */ + TRdsProgrammeType iPty; + /** Programme Type Name of the station */ + TRdsProgrammeTypeName iPtyn; + /** Programme Item Number of the station */ + TRdsProgrammeItemNumber iPin; + /** Value of the Music Speech flag of the station. EFalse indicates the speech is being + broadcast at present. ETrue indicates that music is being broadcast, or that the flag is + not in use by the broadcaster. */ + TBool iMs; + /** The current language of the broadcast */ + TRdsLanguageIdentifier iBroadcastLanguage; + /** The Extended Country Code of the station */ + TRdsCountryCode iEcc; +}; + +/** +Class representing a station broadcast as an Enhanced Other Networks station. +*/ +class TEonStation +{ +public: + /** + Enumeration to indicate a subset of the members of class TEonStation. These values should + be bitwise or'ed together to indicate which members belong in a set. + */ + enum TField + { + /** Indicates that member iProgrammeIdentifier is valid. */ + EProgrammeIdentifier= 0x01, + /** Indicates that member iStationName is valid. */ + EStationName = 0x02, + /** Indicates that member iProgrammeType is valid. */ + EProgrammeType = 0x04, + /** Indicates that member iTrafficProgramme is valid. */ + ETrafficProgramme = 0x08, + /** Indicates that member iTrafficAnnouncement is valid. */ + ETrafficAnnouncement= 0x10, + /** Indicates that member iProgrammeItemNumber is valid. */ + EProgrammeItemNumber= 0x20, + /** Indicates that member iNoFrequencies is valid. */ + ENoFrequencies = 0x40, + /** Indicates that member iNoMappedFrequencies is valid. */ + ENoMappedFrequencies= 0x80 + }; +public: + /** The unique identifier of this station */ + TRdsProgrammeIdentifier iProgrammeIdentifier; + /** The textual name of this station */ + TRdsStationName iStationName; + /** The current programme type (PTY) of this station */ + TRdsProgrammeType iProgrammeType; + /** Indicates if this station broadcasts traffic programmes */ + TBool iTrafficProgramme; + /** Indicates if this station is currently broadcasting a traffic announcement */ + TBool iTrafficAnnouncement; + /** The programme item number (PIN) of the current broadcast on this station. */ + TRdsProgrammeItemNumber iProgrammeItemNumber; + /** + The number of frequencies associated with this station. If this number is zero, + it may be that the EON station uses the mapped frequencies method instead. See + iNoMappedFrequencies. + */ + TInt iNoFrequencies; + /** + The number of mapped frequencies associated with this station. If this number is + zero, it may be that the EON station uses a flat frequency list instead. See + iNoFrequencies. + */ + TInt iNoMappedFrequencies; + /** + Indicates the subset of fields of the class that are valid. Bits are set according to enumeration + TEonStation::TField + */ + TUint32 iValid; +}; + +/** +Mapped frequencies can be broadcast as a part of the EON information. They relate the +current tuning frequency with the frequency which the referred EON station will be +broadcast on. +*/ +class TEonMappedFrequency +{ +public: + inline TEonMappedFrequency(TFrequency aTuningFrequency, TFrequency aMappedFrequency); +public: + /** The current tuning frequency, relating to the station broadcasting the EON informarion. */ + TFrequency iTuningFrequency; + /** + The mapped frequency. If iTunedFrequency matches the currently tuned frequency, the + EON station will be broadcast on this frequency. + */ + TFrequency iMappedFrequency; +}; + +/** +The RDS class augments the tuner API to give access to the RDS capabilities +of the device. As such additional tuner technologies can be supported without +changing the Tuner API. + +Note that despite this class being names 'RDS', it is capable of supporting both +the RDS standard, and the North American equivilant RBDS. The only important difference +from the APIs perspective is the interpretation of the Programme Type (PTY) codes. See +TRdsProgrammeType for more information. +*/ +class CMMRdsTunerUtility : public CBase +{ + friend class CMMTunerUtility::CBody; +public: + /** RDS Announcement Type */ + enum TAnnouncementType + { + /** Traffic announcement */ + ERdsTrafficAnnouncement, + /** News announcement */ + ERdsNewsAnnouncement + }; +public: + /** + Factory function to create a new instance of the RDS Tuner API + + @param aTuner A RDS capable tuner object (check using CMMTunerUtility::GetCapabilities()) + @param aObserver The observer of the tuner to receive asynchronous completion messages. + @leave KErrNoMemory Out of memory + @leave KErrNotFound CMMRdsTunerUtility object is not present + @leave KErrNotSupported RDS is not supported by the tuner + @return A pointer and ownership of a fully constructed CMMRdsTunerUtility object + */ + IMPORT_C static CMMRdsTunerUtility* NewL(CMMTunerUtility& aTuner, MMMTunerObserver& aObserver, CMMTunerUtility::TTunerBand aBand); + + IMPORT_C ~CMMRdsTunerUtility(); + + /** + Get the RDS capabilities of the device + + @param aCaps The capabilities object to fill + @return A standard system error code + */ + IMPORT_C TInt GetRdsCapabilities(TRdsCapabilities& aCaps) const; + + /** + Find a radio station which contains RDS data starting at the start frequency + and searching in the direction specified (i.e. Up or down). + + @note this function is subject to the same access control scheme as the Tune + methods of CMMTunerUtility + + @param aStartFrequency The frequency to start searching from, or 0 to start at the + beginning of the stated band. + @param aBand The frequency band to search. This must be a FM band. + @param aSearchDirection The direction to search in + @param aCircularSeek If set to ETrue the station seek will loop back to the + other end of the band once the end of the band has been reached. + (Defaults to ETrue) If not set reaching the end of the band without + finding a station will result in a callback to MToTuneComplete with error + KErrNotFound. + */ + IMPORT_C void StationSearchByRds(TFrequency aStartFrequency, + CMMTunerUtility::TSearchDirection aSearchDirection + ); + + /** + Find a radio station, of the specified programme type starting at the start + frequency and searching in the direction specified (i.e. Up or down). + + @note this function is subject to the same access control scheme as the Tune + methods of CMMTunerUtility + + @param aProgType The type of programme to search for + @param aStartFrequency The frequency to start searching from, or 0 to start at the + beginning of the stated band. + @param aBand The frequency band to search. This must be a FM band. + @param aSearchDirection The direction to search in + @param aCircularSeek If set to ETrue the station seek will loop back to the + other end of the band once the end of the band has been reached. + (Defaults to ETrue) If not set reaching the end of the band without + finding a station will result in a callback to MToTuneComplete with error + KErrNotFound. + */ + IMPORT_C void StationSearchByProgrammeType( + TRdsProgrammeType aProgType, + TFrequency aStartFrequency, + CMMTunerUtility::TSearchDirection aSearchDirection + ); + + /** + Find a radio station, with the specified programme identifier starting at the + start frequency and searching in the direction specified (i.e. Up or down). + + @note this function is subject to the same access control scheme as the Tune + methods of CMMTunerUtility + + @param aPi The programme identifier of the station to search for + @param aStartFrequency The frequency to start searching from, or 0 to start at the + beginning of the stated band. + @param aBand The frequency band to search. This must be a FM band. + @param aSearchDirection The direction to search in + @param aCircularSeek If set to ETrue the station seek will loop back to the other + end of the band once the end of the band has been reached. (Defaults to ETrue) + If not set reaching the end of the band without finding a station will result + in a callback to MToTuneComplete with error KErrNotFound. + */ + IMPORT_C void StationSearchByProgrammeIdentifier( + TRdsProgrammeIdentifier aPi, + TFrequency aStartFrequency, + CMMTunerUtility::TSearchDirection aSearchDirection + ); + + /** + Find a radio station, with the specified traffic programme flag value starting at + the start frequency and searching in the direction specified (i.e. Up or down). + + @note this function is subject to the same access control scheme as the Tune + methods of CMMTunerUtility + + @param aTp The TP flag value of a station to search for + @param aStartFrequency The frequency to start searching from, or 0 to start at the + beginning of the stated band. + @param aBand The frequency band to search. This must be a FM band. + @param aSearchDirection The direction to search in + @param aCircularSeek If set to ETrue the station seek will loop back to the other + end of the band once the end of the band has been reached. (Defaults to ETrue) + If not set reaching the end of the band without finding a station will result + in a callback to MToTuneComplete with error KErrNotFound. + */ + IMPORT_C void StationSearchByTrafficProgramme( + TBool aTp, + TFrequency aStartFrequency, + CMMTunerUtility::TSearchDirection aSearchDirection + ); + + /** + Cancels an ongoing RDS search as initiated by one of the functions + StationSearchByRds, StationSearchByProgrammeType, + StationSearchByProgrammeIdentifier or StationSearchByTrafficProgramme. The + asynchronous callback will not occur if this is called. + + Has not affect if no RDS search operation is ongoing. + */ + IMPORT_C void CancelRdsSearch(); + + /** + Requests notifications when all RDS data become invalid due to the tuner being + retuned. + + @param aObserver The client to be notified. + @param aWhichData The subset of data for which change notifications are required. + @return A standard system wide error code. + */ + IMPORT_C TInt NotifyRdsDataChange(MMMRdsDataObserver& aObserver, TUint32 aWhichData = TRdsData::KAllRdsData); + + /** + Cancel a NotifyRdsDataChange request. + */ + IMPORT_C void CancelNotifyRdsDataChange(); + + /** + Request some RDS data. This will complete immediately with whatever RDS data have already been + received. + + When this function returns, and data that was requested but is not indicated to be + valid can be assumed not to have been received. + + @param aData The RDS data will be written to this variable. + @param aValid On return, indicates a subset of RDS data that are valid. + @param aWhichData The subset of RDS data that are being requested. + @return A standard system wide error code. + */ + IMPORT_C TInt GetRdsData(TRdsData& aData, TUint32& aValid, TUint32 aWhichData = TRdsData::KAllRdsData) const; + + /** + Converts an RDS language identifier into a Symbian TLanguage type. Note that not all + languages defined by the RDS specification IEC62106 are present in the TLanguage + enumeration; in these cases, a value of ELangOther will be returned. + + @param aRdsLangId An RDS language identification code + @return The corresponding TLanguage member, or ELangOther if none exists. + */ + IMPORT_C static TLanguage ConvertRdsLanguageId(TRdsLanguageIdentifier aRdsLangId); + + /** + Get the length of the available radio text. If no radio text is available this + function will return KErrNotFound. The maximum possible length for radio text is 64 characters. + + @param aLength The variable to set to the length of the avaiable radio text + @return A standard system error code. + */ + IMPORT_C TInt GetRadioTextLength(TUint& aLength) const; + + /** + Get the radio text. If no radio text is available, this will return KErrNotFound. In this + case, a client can call NotifyRadioText to receive a notification when it is received. + + The radio text will have been converted to unicode, eliminating any control characters + within it. + + @param aRadioText The descriptor to fill with the radio text + @return A standard system error code + */ + IMPORT_C TInt GetRadioText(TDes& aRadioText) const; + + /** + Request notification when the radio text is received or changes. + + @param aObserver The client to be notified when the radio text is received or changes. + @return A standard system wide error code. + */ + IMPORT_C TInt NotifyRadioText(MMMRdsDataObserver& aObserver); + + /** + Cancel a NotifyRadioText request. + */ + IMPORT_C void CancelNotifyRadioText(); + + /** + Turns regional link function on or off depending on the value of the parameter. + A value of ETrue should be passed if you wish to stay tuned to the currently + tuned local station regardless of signal quality and signal strength. + i.e. don't switch to another local station in the region. + + @param aRegOn ETrue to turn regional link on, EFalse to turn it off + @return A standard system error code + */ + IMPORT_C TInt SetRegionalLink(TBool aRegOn); + + /** + Finds out if the regional link function is currently on or off. + + @param aRegOn This will be set to ETrue on return if and only if the regional + link function is currently enabled. + @return A standard system error code. + */ + IMPORT_C TInt GetRegionalLink(TBool& aRegOn) const; + + /** + Turn the travel announcement function on or off depending on the value of the + parameter. A value of ETrue turns on Traffic Announcements, EFalse turns them off. + + If Traffic announcements are disabled while the tuner is retuned to a traffic + announcement, the tuner will not revert to the original frequency. To revert to + the original frequency, StopAnnouncement() must be called before the traffic + announcement feature is disabled. + + @param aTaOn ETrue to turn TA on, EFalse to turn it off + @return A standard system error code + */ + IMPORT_C TInt SetTrafficAnnouncement(TBool aTaOn); + + /** + Finds out if the traffic announcement function is currently enabled or not. + + @param aTaOn This is set to ETrue on return if and only if the traffic + announcement function is currenly enabled. + */ + IMPORT_C TInt GetTrafficAnnouncement(TBool& aTaOn) const; + + /** + Set the absolute volume to apply during a traffic or news announcement. + + @param aVolume The volume to use. Must be between 0 and MaxVolume. + @return A standard system error code. + */ + IMPORT_C TInt SetAnnouncementVolume(TInt aVolume); + + /** + Find the current absolute volume level used for news of traffic annoucements. + + @param aVolume This will be set to the current volume used for annoucements. + @return A standard system error code, KErrNotFound if a annoucement volume offset has been set. + use. + */ + IMPORT_C TInt GetAnnouncementVolume(TInt& aVolume) const; + + /** + Set the offset to the system volume level to apply during a traffic or news announcement + + @param aVolumeOffset The offset to the volume level to set for announcements. Must be between -MaxVolume and MaxVolume inclusive. + the actual volume with the offset applied will be clipped between 0 and MaxVolume if the offset would + otherwise result in a volume outside this range. + @return A standard system error code + */ + IMPORT_C TInt SetAnnouncementVolumeOffset(TInt aVolumeOffset); + + /** + Find the current offset of the system volume that applies during traffic and news announcements. + + @param aVolumeOffset This will be set to the current traffic and news announcement offset on return. + @return A standard system error code, KErrNotFound if an absolute annoucement volume has been set. + */ + IMPORT_C TInt GetAnnouncementVolumeOffset(TInt& aVolumeOffset) const; + + /** + Turn the news announcement function on or off depending on the value of the + parameter. The news announcement function when enabled causes the radio to + retune to a station when that station is broadcasting a news report. When the + news announcement is finished the radio will tune back to the original station. + A value of ETrue turns on News Announcements, EFalse turns them off. + + If News announcements are disabled while the tuner is retuned to a news + announcement, the tuner will not revert to the original frequency. To revert to + the original frequency, StopAnnouncement() must be called before the news + announcement feature is disabled. + + @param aNaOn ETrue to turn NA on, EFalse to turn it off + @return A standard system error code + */ + IMPORT_C TInt SetNewsAnnouncement(TBool aNaOn); + + /** + Finds out whether the news announcement function is on or off. + + @param aNaOn This will be set to ETrue if and only if the new announcement + function is currently on. + @return A standard system error code. + */ + IMPORT_C TInt GetNewsAnnouncement(TBool& aNaOn) const; + + /** + Cancels any current announcement, reverting to the original frequency. The announcement + feature will remain enabled. If no announcement is currently happening, this function + has no affect. This can be used for both News and Traffic announcements. + + @return A standard system error code. KErrNone if an announcement was successfully + stopped, or KErrNotReady if no announcement is currently happening. + */ + IMPORT_C TInt StopAnnouncement(); + + /** + Turns alternative frequency function on or off depending on the value of the parameter. + A value of ETrue should be passed if you wish to enable automatic retuning to the current + station on an alternative frequency. + + @param aAfOn ETrue to turn alternative frequency on, EFalse to turn it off + @return A standard system error code + */ + IMPORT_C TInt SetAlternativeFrequency(TBool aAfOn); + + /** + Finds out whether the alternative frequency function is on or off. + + @param aAfOn This will be set to ETrue if and only if the alternative frequency + function is currently on. + @return A standard system error code. + */ + IMPORT_C TInt GetAlternativeFrequency(TBool& aAfOn) const; + + /** + Requests a notification when RDS functionality is enabled or disabled, or when + the traffic announcement volume offset is changed. + + @param aObserver The class which is to be notified of the changes. + @return A standard system error code. + */ + IMPORT_C TInt NotifyRdsStateChange(MMMRdsStateChangeObserver& aObserver); + + /** + Cancels an outstanding RDS state change notification request. + */ + IMPORT_C void CancelNotifyRdsStateChange(); + + /** + Get the current RDS time. This is an asynchronous function due to the latency of + the RDS information becoming available. This information is broadcast at the start of + every minute, and is not cached for obvious reasons. Thus, whenever a request is made, + it will complete next time the Data and Time are broadcast. The RDS standard states + that this is broadcast within 0.1s of the start of a minute, and is accurate to one + minute. The latency of the notification reaching the application cannot be guarteed. + + @param aTimeAndDate The variable to set to the current RDS time and date + @param aStatus A TRequestStatus. This will be signalled when the request completes + and will contain the result of the request, this will be one of the system error codes. + */ + IMPORT_C void GetRdsTime(TPckg& aTimeAndDate, TRequestStatus& aStatus) const; + + /** + Cancel the GetRdsTime request + */ + IMPORT_C void CancelGetRdsTime(); + + /** + Request notification when a retune caused by an announcement occurs. This will be + a traffic or news announcement. A notification will be provided both at + the start of the announcement and at the end. + + @param aObserver The object wishing to receive announcement events + @return A standard system error code + */ + IMPORT_C TInt NotifyAnnouncement(MMMRdsAnnouncementObserver& aObserver); + + /** + Cancel the NotifyAnnouncement request + */ + IMPORT_C void CancelNotifyAnnouncement(); + + /** + Returns a list containing information about other networks broadcast with the currently tuned + programmme. This call will return immediately with whatever EON information is currently available. + Note that is is possible for this function to return no EON stations when several are being broadcast + simply because not enough RDS frames have been received yet. An interested application should make a + call to NotifyEonInfo to receive notifications when EON information is received or changes. + + @param aEonInfo An array to which the EON information will be appended. + */ + IMPORT_C void GetEonInfoL(RArray& aEonInfo) const; + + /** + Gets the frequencies assoicated with an EON station. This will complete immediately with whatever + frequencies are currently cached. An interested application should make a call to NotifyEonChange + to receive notifications when more frequencies are received. + + @param aEonStation the EON station to get the frequencies for + @param aFrequencies an array to which the frequencies associated with the given station will be + appended. + */ + IMPORT_C void GetEonFrequenciesL(const TEonStation& aEonStation, RArray& aFrequencies) const; + + /** + Gets the mapped frequencies associated with an EON station. This will complete immediately with whatever + mapped frequencies are currently cached. An interested application should make a call to NotifyEonChange + to receive notifications when more frequencies are received. + + @param aEonStation the EON station to get the mapped frequencies for + @param aMappedFrequencies an array to which the mapped frequencies associated with the given station + will be appended. + */ + IMPORT_C void GetEonMappedFrequenciesL(const TEonStation& aEonStation, RArray& aMappedFrequencies) const; + + /** + Request notification when the Enhanced Other Networks (EON) information changes. + + @param aObserver The client to be notifier when EON information changes or an error occurs. + */ + IMPORT_C TInt NotifyEonInfo(MMMRdsEonObserver& aObserver); + + /** + Cancels a NotifyEonInfo request. + */ + IMPORT_C void CancelNotifyEonInfo(); + + /** + Tunes to a station represented by a TEonStation. This will result to a callback to MtoTuneComplete. + + @param aEonStation The EON station that is to be tuned to. + */ + IMPORT_C void TuneToEonStation(const TEonStation& aEonStation); + + /** + Send a synchronous custom command to the RDS tuner. + + @param aFunction The function number to indicate which function is to be called + on the interface defined by the first IPC argument + @param aArgs The IPC arguments to send to the RDS tuner. The first of these + arguments must be the UID of the interface within the tuner to which the + command is destined, represented as an integer. Failure to set the first + argument properly will result in the command completing with + KErrNotSupported at best, but possibly the client being panicked. + @return A standard system error code + */ + IMPORT_C TInt CustomCommandSync(TInt aFunction, const TIpcArgs& aArgs); + + /** + Send an asynchronous custom command to the RDS tuner. + + @param aFunction The function number to indicate which function is to be called + on the interface defined by the first IPC argument + @param aArgs The IPC arguments to send to the RDS tuner. The first of these + arguments must be the UID of the interface within the tuner to which the + command is destined, represented as an integer. Failure to set the first + argument properly will result in the command completing with + KErrNotSupported at best, but possibly the client being panicked. + @param aStatus The TRequestStatus of an active object. This will contain the + result of the request on completion. The exact range of result values is + dependent on the interface. + */ + IMPORT_C void CustomCommandAsync(TInt aFunction, const TIpcArgs& aArgs, TRequestStatus& aStatus); + +private: + CMMRdsTunerUtility(); +private: + class CBody; + CBody* iBody; + +}; + +/** +This mixin class should be implemented by applications wishing to receive notifications +when RDS data is received, changes or becomes invalid. Each method corresponds to a +particular request in CMMRdsTunerUtility. Only methods corresponding to requests in +CMMRdsTunerUtility that are used by a client need be implemented - empty default +implementations are provided. +*/ +class MMMRdsDataObserver +{ +public: + /** + Called when some error occurs which makes RDS data unavailable. + */ + virtual void MrdoError(TInt aError) = 0; + + /** + Called when some RDS data is received or has changed. + + Two subsets of the RDS data supplied are indicted: that which has changed and that which is + valid. This information can be interpreted as follows: + For an item of RDS data x: + valid(x) & !changed(x) => x was received before and has not changed + valid(x) & changed(x) => x has either just been received for the first time, or has just changed + !valid(x) & changed(x) => x is no longer available + !valid(x) & !changed(x) => x was not available before, and is still not available. + + When the tuner is retuned to a new station, all RDS data will be flushed. This will result in + a call to this function indicating that all RDS data has changed and is longer valid. + + @param aData The RDS data. + @param aValid Indicates a subset of aData that is valid (i.e. has been received) + @param aChanged Indicates a subset of aData that has changed since the last call to this function. + */ + virtual void MrdoDataReceived(const TRdsData& aData, TUint32 aValid, TUint32 aChanged) = 0; + + /** + Called when the RDS Radio Text (RT) is received, changes, or is no longer available. + + @param aRt The Radio Text message. This will be empty if aValid==EFalse. + @param aValid Indicates if the radio text is valid. + @param aChanges Indicates if the radio test has changed. + */ + virtual void MrdoRadioTextReceived(const TDesC& aRt, TBool aValid, TBool aChanged) = 0; +}; + +/** +The state change observer mixin class defines the interface via which changes to +the state of the RDS radio can be observed. These state changes will be a result +of a client enabling or disabling RDS functionality. +*/ +class MMMRdsStateChangeObserver +{ +public: + /** + Called when the regional link functionality is enabled/disabled. + + @param aNewRegLinkOn The new setting: ETrue if the regional link function has + just been enabled. + */ + virtual void MrscoRegionalLinkChanged(TBool aNewRegLinkOn) = 0; + + /** + Called when the traffic announcement functionality has just been enabled or + disabled. + + @param aNewTaOn ETrue if the TA function is now on, EFalse otherwise. + */ + virtual void MrscoTrafficAnnouncementChanged(TBool aNewTaOn) = 0; + + /** + Called when the traffic and news announcement volume offset is changed. A callback to + this method indicates the a volume offset is being used instead of an absolute volume. + + @param aOldOffset The announcement volume offset before the change + @param aNewOffset The announcement volume offset after the change + */ + virtual void MrscoAnnouncementVolumeOffsetChanged(TInt aOldOffset, TInt aNewOffset) = 0; + + /** + Called when the traffic an news announcement volume is changed. A callback to + this method indicates that an absolute volume is being used instead of volume offsets. + + @param aOldVolume The announcement volume before the change. + @param aNewVolume The announcement volume after the change. + */ + virtual void MrscoAnnouncementVolumeChanged(TInt aOldVolume, TInt aNewVolume) = 0; + + /** + Called when the news announcement functionality has just been enabled or + disabled. + + @param aNewNAOn ETrue if the NA function is now enabled, else EFalse. + */ + virtual void MrscoNewsAnnouncementChanged(TBool aNewNAOn) = 0; + + /** + Called when the alternative frequencies function is turned on or off. + + @param aNewAFOn ETrue if the AF function has just been turned on, else EFalse. + */ + virtual void MrscoAlternativeFrequenciesChanged(TBool aNewAFOn) = 0; +}; + + +/** +The Announcement Observer mixin class defines the interface via which +announcement events can be received. A client interested in such +information calls the function NotifyAnnouncement. +*/ +class MMMRdsAnnouncementObserver +{ +public: + /** + Called when an announcement starts + + @param aType The type of announcement (travel or news) + */ + virtual void MraoAnnouncementStart(CMMRdsTunerUtility::TAnnouncementType aType) = 0; + + /** + Called when an announcement ends + + @param aType The type of announcement (travel or news) + */ + virtual void MraoAnnouncementEnd(CMMRdsTunerUtility::TAnnouncementType aType) = 0; + + /** + Called when an error occurs which results in announcement notifications + becoming unavailable. + */ + virtual void MraoError(TInt aError) = 0; +}; + +/** +The enhanced other networks observer mixin class defines the interface via +which changes to the enhanced other networks information can be notified. A +client interested in such information calls the function NotifyEonChange. +*/ +class MMMRdsEonObserver +{ +public: + /** + Called when some details of an EON station change. The station can be referenced + to an existing one using it's Programme Identifier, which cannot change. + + @param aStation A TEonStation containing the new information about the station. + @param aChanged The subset of the members of aStation that have changed. Bits are + set according to TEonStation::TField. + */ + virtual void MreoEonStationChanged(const TEonStation& aStation, TUint32 aChanged) = 0; + + /** + Called when details of a new EON station are received. + + @param aStation A TEonStation containing the new information about the station. + */ + virtual void MreoNewEonStation(const TEonStation& aStation) = 0; + + /** + Called when details of all EON stations cease to be broadcast. This will + typically happen when the tuner is retuned. More EON stations may continue to be + recieved: this call does not indicate that EON information is no longer available. + */ + virtual void MreoAllEonStationsRemoved() = 0; + + /** + Called when details of an EON station cease to be broadcast. + + @param aPi The programme identifier of the EON station which has been removed. + */ + virtual void MreoEonStationRemoved(const TRdsProgrammeIdentifier& aPi) = 0; + + /** + Called when an error occurs resulting in EON notifications not being available. + */ + virtual void MreoError(TInt aError) = 0; +}; + +#include + +#endif // TUNER_H + +// End of file + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/external_include/tuner.inl --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/external_include/tuner.inl Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Inline functions for Tuner component. +* +*/ + + +TTunerCapabilities::TTunerCapabilities() + : iTunerBands(0), iAdditionalFunctions(0) +{} + +TTunerCapabilities::TTunerCapabilities(TUint32 aTunerBands, TUint32 aAdditionalFunctions) + : iTunerBands(aTunerBands), iAdditionalFunctions(aAdditionalFunctions) +{} + +TFrequency::TFrequency() + : iFrequency(0) +{} + +TFrequency::TFrequency(TInt aFrequency) + : iFrequency(aFrequency) +{} + +TInt TFrequency::operator==(const TFrequency& aFrequency) const +{ + return (iFrequency==aFrequency.iFrequency); +} + +TInt TFrequency::operator!=(const TFrequency& aFrequency) const +{ + return (iFrequency!=aFrequency.iFrequency); +} + +TInt TFrequency::operator> (const TFrequency& aFrequency) const +{ + return (iFrequency>aFrequency.iFrequency); +} + +TInt TFrequency::operator>=(const TFrequency& aFrequency) const +{ + return (iFrequency>=aFrequency.iFrequency); +} + +TInt TFrequency::operator< (const TFrequency& aFrequency) const +{ + return (iFrequency + +#include "CAMMSTunerControl.h" + +// FORWARD DECLARATIONS +class CAMMSTunerPlayer; +class CAMMSTunerControl; + +// CLASS DECLARATION +/** +* This class is used to create tuner player and control. +* It parses locator parameters and set them to control. +*/ + +NONSHARABLE_CLASS(AMMSTunerFactory) +{ +public: // Constructors and destructor + + /** + * Destructor. + */ + virtual ~AMMSTunerFactory(); + +public: // New functions + + /** + * ?member_description. + * @param aTunerPlayer + * @param aLocatorParams + */ + static void CreatePlayerL(CAMMSTunerPlayer** aTunerPlayer, + const TDesC* aLocatorParams); + +protected: // New functions + + /** + * Parse all locator parameters. + * @param aLocatorParams + * @param aFrequency + * @param aStereoMode + * @param aPreset + */ + static void ParseParamsL(const TDesC* aLocatorParams, + TInt& aFrequency, + TInt& aStereoMode, + TInt& aPreset); + + /** + * Parses frequency parameter + * @param aFrequency - locator's frequency parameter + * @return frequency in TInt + */ + static TInt ParseFreqL(const TPtrC aFrequency); + + /** + * Converts TPtrC to TReal using TLex. + * @param aHertz - hertzs in TPtrC + * @return hertzs in TReal + */ + static TReal TDesCToTRealL(const TPtrC aHertz); + +private: + + /** + * C++ default constructor. + */ + AMMSTunerFactory(); +}; + +#endif // AMMSTUNERFACTORY_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/inc/cammstunercontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/inc/cammstunercontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,290 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Control for tuner +* +*/ + + +#ifndef CAMMSTUNERCONTROL_H +#define CAMMSTUNERCONTROL_H + +// INCLUDES +#include +#include + +#include + + +// FORWARD DECLARATIONS +class CAMMSTunerPlayer; +class CAMMSTunerPresetsHandler; + +// CLASS DECLARATION +/** +* Control for tuner +*/ + +NONSHARABLE_CLASS(CAMMSTunerControl) : public CMMAControl, + public MMMTunerObserver, + public MMMTunerChangeObserver, + public MMMTunerStereoObserver +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSTunerControl* NewL(); + + /** + * Destructor. + */ + virtual ~CAMMSTunerControl(); + +public: // New functions + + /** + * Getter for CMMTunerUtility + * @return CMMTunerUtility + */ + CMMTunerUtility* TunerUtility(); + + /** + * Gets the minimum frequency supported by this tuner + * with the given modulation. + * @return minimum frequency supported by this tuner + */ + TInt MinFreqL(); + + /** + * Gets the maximum frequency supported by this tuner + * with the given modulation. + * @return maximum frequency supported by this tuner + */ + TInt MaxFreqL(); + + /** + * Tunes to the given frequency or to the closest supported frequency. + * @param aFreq - the frequency in Hertzs that will be taken into use + * @return the frequency in 100 Hertzs that was taken into use + + */ + void SetFrequencyL(TInt aFreq); + + /** + * Gets the frequency which the tuner has been tuned to. + * @return the frequency to which the device has been tuned, + * in 100 Hertzs + */ + TInt FrequencyL(); + + /** + * Seeks for the next broadcast signal. + * @param aStartFreq - the frequency in Hertzs wherefrom the scan starts + * @param aUpwards - if true, the scan proceeds towards higher + * frequencies, otherwise towards lower frequencies + * @return the found frequency + */ + TInt SeekL(TInt aStartFreq, TBool aUpwards); + + /** + * Gets the current squelching (muting in frequencies without broadcast) + * setting. + * @return true if squelch is on or false if squelch is off + */ + TBool SquelchL(); + + /** + * Sets squelching on or off. + * @param aSquelch - true to turn the squelch on or false + * to turn the squelch off + */ + void SetSquelchL(TBool aSquelch); + + /** + * Gets the strength of the recepted signal. + * @return a value between 0 and 100 where 0 means the faintest + * and 100 the strongest possible signal strength + */ + TInt SignalStrengthL(); + + /** + * Gets the stereo mode in use. + * @return stereo mode in use + */ + TInt StereoModeL(); + + /** + * Sets the stereo mode. + * @param aMode - the stereo mode to be used + */ + void SetStereoModeL(TInt aMode); + + /** + * Tunes the tuner by using settings specified in the preset. + * @param aPreset - the preset to be used. + */ + void UsePresetL(TInt aPreset); + + /** + * Configures the preset using current frequency and modulation + * and stereo mode. + * @param aPreset - the preset to be set. + */ + void SetPresetL(TInt aPreset); + + /** + * Configures the preset using given settings. + * @param aPreset - the preset to be set. + * @param aFrequency - the frequency to be set. + * @param aStereoMode - the stereo mode to be set. + */ + void SetPresetL(TInt aPreset, TInt aFrequency, TInt aStereoMode); + + /** + * Gets preset frequency + * @param aPreset - the preset whose frequency is to be returned + . * @return the frequency of the preset in 100 Hertzs + */ + TInt PresetFrequencyL(TInt aPreset); + + /** + * Gets preset stereo mode + * @param aPreset - the preset whose stereo mode is to be returned + . * @return the stereo mode of the preset. + */ + TInt PresetStereoModeL(TInt aPreset); + + /** + * Set preset name + * @param aPreset - the preset whose name is to be set + * @param aPresetName - the name of the preset + */ + void SetPresetNameL(TInt aPreset, const TDesC* aPresetName); + + /** + * Get preset name + * @param aPreset - the preset whose name is asked + * @param aPresetName - the name of the preset + */ + void GetPresetNameL(TInt aPreset, TPtrC* aPresetName); + +public: // functions from base classes + + // from CMMAControl + + const TDesC& ClassName() const; + + const TDesC& PublicClassName() const; + + // from MMMTunerObserver + + void MToTuneComplete(TInt aError); + + // from class MMMTunerChangeObserver + + /** + Called when the tuned frequency changes + + @param aOldFrequency The frequency in use before the change + @param aNewFrequency The new tuned frequency + */ + void MTcoFrequencyChanged(const TFrequency& aOldFrequency, + const TFrequency& aNewFrequency); + + /** + Called when the state of the tuner changes. + + @param aOldState The old state. Bits are set according to TTunerState. + @param aNewState The new state. Bits are set according to TTunerState. + */ + void MTcoStateChanged(const TUint32& aOldState, + const TUint32& aNewState); + + /** + This function is called when an external antenna is detached from the device. + This does not necessarily indicate that the tuner can no longer be used; the + capabilities of the tuner indicate if the external antenna is required in order + to use the tuner. + */ + void MTcoAntennaDetached(); + + /** + This function is called when an external antenna is attached to the device. If + the antenna is required to use the tuner, this indicates that the tuner can be + used again. + */ + void MTcoAntennaAttached(); + + /** + This function is called when the device enters or leaves flight mode. If the tuner + cannot be used in flight mode when the device enters this mode, this indicates + that the tuner can no longer be used; the capabilities of the tuner indicate if + it can be used in flight mode or not. + + @param aFlightMode ETrue if the device has just entered flight mode, EFalse if + flight mode has just been left. + */ + void FlightModeChanged(TBool aFlightMode); + + // from class MMMTunerStereoObserver + + /** + Called when stereo reception is lost/restored. + + @param aStereo If true, indicates that stereo reception has just been restored. + If false, indicates that stereo reception has just been lost. + */ + void MTsoStereoReceptionChanged(TBool aStereo); + + /** + Called when a client enables/disabled forced mono reception. + + @param aForcedMono ETrue if reception is forced to be mono, even when a stereo + signal is available. + */ + void MTsoForcedMonoChanged(TBool aForcedMono); + + +private: + + /** + * C++ default constructor. + */ + CAMMSTunerControl(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + + // Prohibit copy constructor if not deriving from CBase. + // CAMMSTunerControl( const CAMMSTunerControl& ); + // Prohibit assigment operator if not deriving from CBase. + // CAMMSTunerControl& operator=( const CAMMSTunerControl& ); + + +private: // Data + + TInt iMinFreq; + TInt iMaxFreq; + + CMMTunerUtility* iTunerUtility; + CActiveSchedulerWait* iActiveSchedulerWait; + CAMMSTunerPresetsHandler* iPresetsHandler; +}; + +#endif // CAMMSTUNERCONTROL_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/inc/cammstunerplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/inc/cammstunerplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + + +#ifndef CAMMSTUNERPLAYER_H +#define CAMMSTUNERPLAYER_H + +// INCLUDES +#include +#include "CAMMSTunerControl.h" + +#include +#include + + +// CLASS DECLARATION + +/** +* Player for tuner +* +*/ +NONSHARABLE_CLASS(CAMMSTunerPlayer) : public CMMAPlayer, + public MMMTunerAudioPlayerObserver +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSTunerPlayer* NewL(CAMMSTunerControl* aTunerControl); + + /** + * Destructor. + */ + virtual ~CAMMSTunerPlayer(); + +public: // from CMMAPlayer + + void PrefetchL(); + void StartL(); + void StopL(TBool aPostEvent); + void DeallocateL(); + void GetMediaTime(TInt64* aMediaTime); + +public: // from MMMTunerAudioPlayerObserver + + void MTapoInitializeComplete(TInt aError); + void MTapoPlayEvent(MMMTunerAudioPlayerObserver::TEventType aEvent, TInt aError, TAny* aAdditionalInfo); + +private: + + /** + * C++ default constructor. + */ + CAMMSTunerPlayer(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(CAMMSTunerControl* aTunerControl); + + + TInt64 CurrentTime(); + +private: // Data + CMMTunerAudioPlayerUtility* iTunerPlayerUtility; + CAMMSTunerControl* iTunerControl; + CActiveSchedulerWait* iActiveSchedulerWait; + + TBool iIsInitialized; + TInt64 iMediaTime; + TInt64 iStartTime; +}; + +#endif // CAMMSTUNERPLAYER_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/inc/cammstunerpresetshandler.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/inc/cammstunerpresetshandler.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class handles presets central repository usage. +* +*/ + + + +#ifndef CAMMSTUNERPRESETSHANDLER_H +#define CAMMSTUNERPRESETSHANDLER_H + +// INCLUDES +#include +#include + + +// FORWARD DECLARATIONS +class TAMMSTunerPreset; + +// CLASS DECLARATION +/** +* This class handles presets central repository usage. +* +* @lib ?library +* @since ?Series60_version +*/ +NONSHARABLE_CLASS(CAMMSTunerPresetsHandler) : public CBase +{ +public: // Constructors and destructor + + /** + * Two-phased constructor. + */ + static CAMMSTunerPresetsHandler* NewL(); + + /** + * Destructor. + */ + virtual ~CAMMSTunerPresetsHandler(); + +public: // New functions + + /** + * Gets presets from central repository + * @param aPreset - presets index + * @param aTunerPreset + */ + void GetPresetL(TInt aPreset, TAMMSTunerPreset &aTunerPreset); + + /** + * Save presets to central repository + * @param aPreset - presets index + * @param aTunerPreset + */ + void SavePresetL(TInt aPreset, TAMMSTunerPreset aTunerPreset); + +private: + + /** + * C++ default constructor. + */ + CAMMSTunerPresetsHandler(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + + // Prohibit copy constructor if not deriving from CBase. + // CAMMSTunerPresetsHandler( const CAMMSTunerPresetsHandler& ); + // Prohibit assigment operator if not deriving from CBase. + // CAMMSTunerPresetsHandler& operator=( const CAMMSTunerPresetsHandler& ); + + +private: // Data + + CRepository* iCentralRepository; + + +}; + +#endif // CAMMSTUNERPRESETSHANDLER_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/inc/cammstunervolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/inc/cammstunervolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to tuner player +* +*/ + + +#ifndef CAMMSTUNERVOLUMECONTROL_H +#define CAMMSTUNERVOLUMECONTROL_H + +// INCLUDES +#include + +#include + +// FORWARD DECLARATIONS +class CAMMSTunerPlayer; + +// CLASS DECLARATION +/** +* This class is used for setting volume to tuner player +*/ + +NONSHARABLE_CLASS(CAMMSTunerVolumeControl) : public CMMAVolumeControl +{ +public: // Constructor + static CAMMSTunerVolumeControl* NewL(CAMMSTunerPlayer* aTunerPlayer); + +public: // functions from base classes + + // from CMMAVolumeControl + + void DoSetLevelL(TInt aLevel); + +private: + + /** + * C++ default constructor. + */ + CAMMSTunerVolumeControl(CAMMSTunerPlayer* aTunerPlayer); + + +private: // Data + + CAMMSTunerPlayer* iTunerPlayer; +}; + +#endif // CAMMSTUNERVOLUMECONTROL_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/inc/tammstunerpreset.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/inc/tammstunerpreset.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Helper class for preset handling, reads and writes preset +* values in/out stream. +* +*/ + + + +#ifndef TAMMSTUNERPRESET_H +#define TAMMSTUNERPRESET_H + +// INCLUDES +#include + + +// FORWARD DECLARATIONS +class RWriteStream; +class RReadStream; + +// CONSTANTS +const TInt KPresetNameLength = 100; + +// CLASS DECLARATION +/** +* Helper class for preset handling, reads and writes preset +* values in/out stream. +* +* @lib ?library +* @since ?Series60_version +*/ +NONSHARABLE_CLASS(TAMMSTunerPreset) +{ +public: + + /** + * C++ default constructor. + */ + TAMMSTunerPreset(); + + /** + * Setter for preset name. + */ + void SetPresetName(const TDesC* aPresetName); + + /** + * Setter for preset frequency. + */ + void SetPresetFrequency(const TInt aPresetFrequency); + + /** + * Setter for preset stereo mode. + */ + void SetPresetStereoMode(const TInt aPresetStereoMode); + + /** + * Getter for preset name. + */ + TPtrC PresetName(); + + /** + * Getter for preset frequency. + */ + TInt PresetFrequency(); + + /** + * Getter for preset stereo mode. + */ + TInt PresetStereoMode(); + + /** + * Serialize the data to stream. + * @param aStream - used for write stream + */ + void ExternalizeL(RWriteStream &aStream) const; + + /** + * deserialize the data out of stream. + * @param aStream used for read stream + */ + void InternalizeL(RReadStream &aStream); + +private: + + TBuf iPresetName; + TInt iPresetFrequency; + TInt iPresetStereoMode; + +}; + +#endif // TAMMSTUNERPRESET_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/ammstunerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/ammstunerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,300 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to create tuner player and control +* +*/ + + + +// INCLUDE FILES +#include "AMMSTunerFactory.h" +#include "CAMMSTunerPlayer.h" +#include "CAMMSTunerControl.h" +//#include "CAMMSTunerVolumeControl.h" +#include + +#include +#include +#include + +// CONSTANTS +_LIT(KFreqParam, "f"); + +_LIT(KModulationParam, "mod"); + +_LIT(KStereoModeParam, "st"); +MMA_PARAMETER_STR(KStereoModeParamMono, "mono"); +MMA_PARAMETER_STR(KStereoModeParamStereo, "stereo"); +MMA_PARAMETER_STR(KStereoModeParamAuto, "auto"); +MMA_PARAMETER_ARRAY(KValidStereoModeValues) +{ + { + &KStereoModeParamMono + }, {&KStereoModeParamStereo}, {&KStereoModeParamAuto} +}; + +_LIT(KProgramIdParam, "id"); +_LIT(KPresetParam, "preset"); + +_LIT(KModulationFm, "fm"); + +_LIT(KStereoModeMono, "mono"); +_LIT(KStereoModeStereo, "stereo"); +_LIT(KStereoModeAuto, "auto"); + +const TInt KMegaHertzChar = 'M'; +const TInt KKiloHertzChar = 'k'; +const TInt KFreqDotChar = '.'; + +const TInt KMegaHzMultiplier = 1000000; +const TInt KKiloHzMultiplier = 1000; + +const TInt KStereoModeMonoInt = 1; +const TInt KStereoModeStereoInt = 2; +const TInt KStereoModeAutoInt = 3; + +// ============================ MEMBER FUNCTIONS =============================== + +// Destructor +AMMSTunerFactory::~AMMSTunerFactory() +{ + +} + + +// ----------------------------------------------------------------------------- +// AMMSTunerFactory::CreatePlayerL +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void AMMSTunerFactory::CreatePlayerL(CAMMSTunerPlayer** aTunerPlayer, + const TDesC* aLocatorParams) +{ + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::CreatePlayerL +"); + + TInt frequency = 0; + TInt stereoMode = 0; + TInt preset = 0; + + if (aLocatorParams->Length() != 0) + { + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::CreatePlayerL 1"); + ParseParamsL(aLocatorParams, frequency, stereoMode, preset); + } + + //create tunercontrol + CAMMSTunerControl* tunerControl = CAMMSTunerControl::NewL(); + CleanupStack::PushL(tunerControl); + + //set values to tunercontrol + if (frequency > 0) + { + tunerControl->SetFrequencyL(frequency); + } + + if (frequency == 0) + { + //by default frequency is fm modulation's min freq + tunerControl->SetFrequencyL(tunerControl->MinFreqL()); + } + + if (stereoMode > 0) + { + tunerControl->SetStereoModeL(stereoMode); + } + + if (preset > 0) + { + tunerControl->UsePresetL(preset); + } + + //create tunerplayer + *aTunerPlayer = CAMMSTunerPlayer::NewL(tunerControl); + + //create tunervolumeconrol + //CAMMSTunerVolumeControl* tunerVolumeControl = CAMMSTunerVolumeControl::NewL( *aTunerPlayer ); + + //add controls to player + (*aTunerPlayer)->AddControlL(tunerControl); + //(*aTunerPlayer)->AddControlL( tunerVolumeControl ); + CleanupStack::Pop(tunerControl); + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::CreatePlayerL -"); +} + +// ----------------------------------------------------------------------------- +// AMMSTunerFactory::ParseParamsL +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void AMMSTunerFactory::ParseParamsL(const TDesC* aLocatorParams, + TInt& aFrequency, + TInt& aStereoMode, + TInt& aPreset) +{ + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::ParseParamsL +"); + CMMAParameterRuleSet* rules = CMMAParameterRuleSet::NewLC(); + + //freq rule + TMMAParameterRuleDes freqRule(KFreqParam); + rules->AppendRuleL(&freqRule); + + //modulation rule + TMMAParameterRuleDes modulationRule(KModulationParam); + rules->AppendRuleL(&modulationRule); + + //stereo mode rule + TMMAParameterRuleDes stereoModeRule(KStereoModeParam, KValidStereoModeValues, + MMA_PARAMETER_ARRAY_SIZE(KValidStereoModeValues)); + rules->AppendRuleL(&stereoModeRule); + + //preset rule KMinTInt-KMaxTInt + TMMAParameterRuleInt presetRule(KPresetParam); + rules->AppendRuleL(&presetRule); + + //id rule + TMMAParameterRuleDes idRule(KProgramIdParam); + rules->AppendRuleL(&idRule); + + CMMAPlayerProperties* properties = CMMAPlayerProperties::NewL(*aLocatorParams, *rules); + CleanupStack::PushL(properties); + + // validating properties + properties->ValidateL(); + + //get freq + TPtrC freq(NULL, 0); + properties->GetProperty(KFreqParam, freq); + //parse frequency + if (freq.Length() != 0) + { + aFrequency = ParseFreqL(freq); + } + + //get modulation + TPtrC modulation(NULL, 0); + properties->GetProperty(KModulationParam, modulation); + if (modulation.Length() != 0) + { + // only fm modulation is supported + if (modulation.Compare(KModulationFm) != 0) + { + User::Leave(KErrNotSupported); + } + } + + //get stereo mode + TPtrC stereoMode(NULL, 0); + properties->GetProperty(KStereoModeParam, stereoMode); + if (stereoMode.Compare(KStereoModeMono) == 0) + { + aStereoMode = KStereoModeMonoInt; + } + else if (stereoMode.Compare(KStereoModeStereo) == 0) + { + aStereoMode = KStereoModeStereoInt; + } + else if (stereoMode.Compare(KStereoModeAuto) == 0) + { + aStereoMode = KStereoModeAutoInt; + } + + //get preset + properties->GetProperty(KPresetParam, aPreset); + + //get id + TPtrC id(NULL, 0); + properties->GetProperty(KProgramIdParam, id); + if (id.Length() != 0) + { + // id is not supported + User::Leave(KErrNotSupported); + } + + CleanupStack::PopAndDestroy(properties); + CleanupStack::PopAndDestroy(rules); + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::ParseParamsL -"); +} + +// ----------------------------------------------------------------------------- +// AMMSTunerFactory::ParseFreqL +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TInt AMMSTunerFactory::ParseFreqL(const TPtrC aFrequency) +{ + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::ParseFreqL +"); + TReal freqReal = 0; + + //is value MHz or kHz or just hertz + TInt freqPrefixMPos = aFrequency.Locate(KMegaHertzChar); + TInt freqPrefixKPos = aFrequency.Locate(KKiloHertzChar); + + if (freqPrefixMPos != KErrNotFound) + { + //there is a M + TPtrC hertz = aFrequency.Left(freqPrefixMPos); + //TPtrC -> TReal + TReal value = TDesCToTRealL(hertz); + + freqReal = value * KMegaHzMultiplier; + } + else if (freqPrefixKPos != KErrNotFound) + { + //there is a k + TPtrC hertz = aFrequency.Left(freqPrefixKPos); + //TPtrC -> TReal + TReal value = TDesCToTRealL(hertz); + + freqReal = value * KKiloHzMultiplier; + } + else + { + //parameter value is simply hertz, there is no M or k + //TPtrC -> TReal + freqReal = TDesCToTRealL(aFrequency); + } + TInt32 freqInt = 0; + //TReal -> TInt + TInt err = Math::Int(freqInt, freqReal); + if (err != KErrNone) + { + User::Leave(KErrArgument); + } + + return freqInt; +} + +// ----------------------------------------------------------------------------- +// AMMSTunerFactory::TDesCToTRealL +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +TReal AMMSTunerFactory::TDesCToTRealL(const TPtrC aHertz) +{ + LOG( EJavaAMMS, EInfo, "AMMSTunerFactory::TDesCToTRealL +"); + TReal valueReal = 0; + TLex lex(aHertz); + if ((lex.Val(valueReal, KFreqDotChar) != KErrNone) || + !lex.Eos()) + { + User::Leave(KErrArgument); + } + return valueReal; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/cammstunercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/cammstunercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,504 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to control tuner +* +*/ + + + +// INCLUDE FILES +#include "CAMMSTunerControl.h" +#include "CAMMSTunerPlayer.h" +#include "CAMMSTunerPresetsHandler.h" +#include "TAMMSTunerPreset.h" +#include "AMMSTunerFactory.h" + +#include +#include + + +// CONSTANTS +_LIT(KControlImplName, "com.nokia.amms.control.tuner.TunerControlImpl"); +_LIT(KControlPublicName, "javax.microedition.amms.control.tuner.TunerControl"); + +const TInt KStereoModeMono = 1; +const TInt KStereoModeStereo = 2; +const TInt KStereoModeAuto = 3; + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::CAMMSTunerControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +CAMMSTunerControl::CAMMSTunerControl() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +// +CAMMSTunerControl* CAMMSTunerControl::NewL() +{ + CAMMSTunerControl* self = new(ELeave) CAMMSTunerControl; + + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + + return self; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +// +void CAMMSTunerControl::ConstructL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::ConstructL +"); + + iTunerUtility = CMMTunerUtility::NewL(*this, + CMMTunerUtility::ETunerBandFm, + 1, + CMMTunerUtility::ETunerAccessPriorityNormal); + + iActiveSchedulerWait = new(ELeave) CActiveSchedulerWait(); + + iPresetsHandler = CAMMSTunerPresetsHandler::NewL(); + + iMinFreq = MinFreqL(); + iMaxFreq = MaxFreqL(); + + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::ConstructL -"); +} + + +// Destructor +CAMMSTunerControl::~CAMMSTunerControl() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::~CAMMSTunerControl +"); + delete iTunerUtility; + delete iActiveSchedulerWait; + delete iPresetsHandler; + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::~CAMMSTunerControl -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::TunerUtility() +// ----------------------------------------------------------------------------- +CMMTunerUtility* CAMMSTunerControl::TunerUtility() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::TunerUtility"); + return iTunerUtility; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MinFreq() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::MinFreqL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MinFreqL +"); + TFrequency minFreq; + TFrequency maxFreq; + User::LeaveIfError(iTunerUtility->GetFrequencyBandRange(minFreq, + maxFreq)); + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::MinFreqL = %d", minFreq.iFrequency); + return minFreq.iFrequency; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MaxFreq() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::MaxFreqL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MaxFreqL +"); + TFrequency minFreq; + TFrequency maxFreq; + User::LeaveIfError(iTunerUtility->GetFrequencyBandRange(minFreq, + maxFreq)); + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::MaxFreqL = %d", maxFreq.iFrequency); + return maxFreq.iFrequency; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetFrequency() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetFrequencyL(TInt aFreq) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetFrequency +"); + if (aFreq < iMinFreq || aFreq > iMaxFreq) + { + User::Leave(KErrArgument); + } + + TFrequency freq = TFrequency(aFreq); + + TUint32 state = 0; + iTunerUtility->GetState(state); + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::SetFrequency, state = %d", state); + + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::SetFrequency = %d", freq.iFrequency); + + iTunerUtility->Tune(freq); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); // CSI: 10 Active object state already checked. # + } + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetFrequency -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::Frequency() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::FrequencyL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::Frequency +"); + TFrequency freq; + + User::LeaveIfError(iTunerUtility->GetFrequency(freq)); + TInt frequency = freq.iFrequency; + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::Frequency frequency = %d", frequency); + return frequency; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SeekL() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::SeekL(TInt aStartFreq, TBool aUpwards) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SeekL +"); + if (aStartFreq < iMinFreq || aStartFreq > iMaxFreq) + { + User::Leave(KErrArgument); + } + + if (aUpwards) + { + iTunerUtility->StationSeek(CMMTunerUtility::ESearchDirectionUp); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); // CSI: 10 Active object state already checked. # + } + } + else + { + iTunerUtility->StationSeek(CMMTunerUtility::ESearchDirectionDown); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); // CSI: 10 Active object state already checked. # + } + } + + return FrequencyL(); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SquelchL() +// ----------------------------------------------------------------------------- +TBool CAMMSTunerControl::SquelchL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SquelchL +"); + TBool enabled = EFalse; + User::LeaveIfError(iTunerUtility->GetSquelch(enabled)); + return enabled; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetSquelchL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetSquelchL(TBool aSquelch) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetSquelchL +"); + User::LeaveIfError(iTunerUtility->SetSquelch(aSquelch)); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SignalStrengthL() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::SignalStrengthL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SignalStrengthL +"); + TInt maxSignalStrength = 0; + TInt signalStrength = 0; + + User::LeaveIfError(iTunerUtility->GetMaxSignalStrength(maxSignalStrength)); + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::SignalStrengthL, maxSignalStrength = %d", maxSignalStrength); + User::LeaveIfError(iTunerUtility->GetSignalStrength(signalStrength)); + LOG1( EJavaAMMS, EInfo, "CAMMSTunerControl::SignalStrengthL, signalStrength = %d", signalStrength); + if (maxSignalStrength > 0) + { + return signalStrength / maxSignalStrength * 100; // CSI: 47 signal strength must be between 0 and 100 # + } + return KErrNotSupported; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::StereoModeL() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::StereoModeL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::StereoModeL +"); + TBool mono = EFalse; + TBool stereo = EFalse; + + User::LeaveIfError(iTunerUtility->GetForcedMonoReception(mono)); + if (mono) + { + return KStereoModeMono; + } + + //User::LeaveIfError( iTunerUtility->IsStereoSignal( stereo ) ); + TInt err = iTunerUtility->IsStereoSignal(stereo); + //this is for emulator testing, FIX IT + if (err == KErrNotReady) + { + return KStereoModeAuto; + } + else if (err != KErrNone) + { + User::LeaveIfError(err); + } + + if (stereo) + { + return KStereoModeStereo; + } + + return KStereoModeAuto; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetStereoMode() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetStereoModeL(TInt aMode) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetStereoModeL +"); + if (aMode == KStereoModeMono) + { + User::LeaveIfError(iTunerUtility->ForceMonoReception(ETrue)); + } + + if (aMode == KStereoModeStereo) + { + User::LeaveIfError(iTunerUtility->ForceMonoReception(EFalse)); + TBool stereo = EFalse; + User::LeaveIfError(iTunerUtility->IsStereoSignal(stereo)); + if (!stereo) + { + User::Leave(KErrNotSupported); + } + } + + if (aMode == KStereoModeAuto) + { + User::LeaveIfError(iTunerUtility->ForceMonoReception(EFalse)); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::UsePresetL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::UsePresetL(TInt aPreset) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::UsePresetL +"); + TAMMSTunerPreset tunerPreset; + + //get presets + iPresetsHandler->GetPresetL(aPreset, tunerPreset); + + //set presets to tunerutility + SetFrequencyL(tunerPreset.PresetFrequency()); + SetStereoModeL(tunerPreset.PresetStereoMode()); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetPresetL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetPresetL(TInt aPreset) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetPresetL1 +"); + TAMMSTunerPreset tunerPreset; + + //get current frequency + tunerPreset.SetPresetFrequency(FrequencyL()); + //get current stereo mode + tunerPreset.SetPresetStereoMode(StereoModeL()); + + iPresetsHandler->SavePresetL(aPreset, tunerPreset); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetPresetL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetPresetL(TInt aPreset, + TInt aFrequency, + TInt aStereoMode) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetPresetL2 +"); + TAMMSTunerPreset tunerPreset; + + tunerPreset.SetPresetFrequency(aFrequency); + tunerPreset.SetPresetStereoMode(aStereoMode); + + iPresetsHandler->SavePresetL(aPreset, tunerPreset); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::PresetFrequencyL() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::PresetFrequencyL(TInt aPreset) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::PresetFrequencyL +"); + TAMMSTunerPreset tunerPreset; + + iPresetsHandler->GetPresetL(aPreset, tunerPreset); + + return tunerPreset.PresetFrequency(); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::PresetStereoModeL() +// ----------------------------------------------------------------------------- +TInt CAMMSTunerControl::PresetStereoModeL(TInt aPreset) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::PresetStereoModeL +"); + TAMMSTunerPreset tunerPreset; + + iPresetsHandler->GetPresetL(aPreset, tunerPreset); + + return tunerPreset.PresetStereoMode(); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::SetPresetNameL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::SetPresetNameL(TInt aPreset, const TDesC* aPresetName) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::SetPresetNameL +"); + TAMMSTunerPreset tunerPreset; + + iPresetsHandler->GetPresetL(aPreset, tunerPreset); + + tunerPreset.SetPresetName(aPresetName); + + iPresetsHandler->SavePresetL(aPreset, tunerPreset); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::GetPresetNameL() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::GetPresetNameL(TInt aPreset, TPtrC* aPresetName) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::GetPresetNameL +"); + TAMMSTunerPreset tunerPreset; + + iPresetsHandler->GetPresetL(aPreset, tunerPreset); + + aPresetName->Set(tunerPreset.PresetName()); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::ClassName() +// ----------------------------------------------------------------------------- +const TDesC& CAMMSTunerControl::ClassName() const +{ + return KControlImplName; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::PublicClassName() +// ----------------------------------------------------------------------------- +const TDesC& CAMMSTunerControl::PublicClassName() const +{ + return KControlPublicName; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MToTuneComplete() +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MToTuneComplete(TInt aError) +{ + if (iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MToTuneComplete AsyncStop"); + iActiveSchedulerWait->AsyncStop(); + } + ELOG1( EJavaAMMS, "CAMMSTunerControl::MToTuneComplete ERROR = %d", aError); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTcoFrequencyChanged +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTcoFrequencyChanged(const TFrequency& /*aOldFrequency*/, + const TFrequency& /*aNewFrequency*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTcoFrequencyChanged"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTcoStateChanged +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTcoStateChanged(const TUint32& /*aOldState*/, + const TUint32& /*aNewState*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTcoStateChanged"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTcoAntennaDetached +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTcoAntennaDetached() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTcoAntennaDetached"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTcoAntennaAttached +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTcoAntennaAttached() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTcoAntennaAttached"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::FlightModeChanged +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::FlightModeChanged(TBool /*aFlightMode*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::FlightModeChanged"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTsoStereoReceptionChanged +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTsoStereoReceptionChanged(TBool /*aStereo*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTsoStereoReceptionChanged"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerControl::MTsoForcedMonoChanged +// ----------------------------------------------------------------------------- +void CAMMSTunerControl::MTsoForcedMonoChanged(TBool /*aForcedMono*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MTsoForcedMonoChanged"); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/cammstunerplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/cammstunerplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,236 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a tuner player +* +*/ + + + +// INCLUDE FILES +#include "CAMMSTunerPlayer.h" +#include "CAMMSTunerControl.h" + +#include +#include + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::CAMMSTunerPlayer +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +CAMMSTunerPlayer::CAMMSTunerPlayer() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +// +CAMMSTunerPlayer* CAMMSTunerPlayer::NewL(CAMMSTunerControl* aTunerControl) +{ + CAMMSTunerPlayer* self = new(ELeave) CAMMSTunerPlayer; + + CleanupStack::PushL(self); + self->ConstructL(aTunerControl); + CleanupStack::Pop(); + + return self; +} + + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +// +void CAMMSTunerPlayer::ConstructL(CAMMSTunerControl* aTunerControl) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::ConstructL +"); + iTunerControl = aTunerControl; + iTunerPlayerUtility = iTunerControl->TunerUtility()->TunerPlayerUtilityL(*this); + iActiveSchedulerWait = new(ELeave) CActiveSchedulerWait(); + iIsInitialized = EFalse; + + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::ConstructL -"); +} + +// Destructor +CAMMSTunerPlayer::~CAMMSTunerPlayer() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::~CAMMSTunerPlayer +"); + delete iTunerPlayerUtility; + delete iActiveSchedulerWait; + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::~CAMMSTunerPlayer -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::PrefetchL() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::PrefetchL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::PrefetchL +"); + //this must be called before play, stop, mute etc... + iTunerPlayerUtility->InitializeL(EMdaPriorityNormal, + EMdaPriorityPreferenceTimeAndQuality); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); // CSI: 10 Active object state already checked. # + } + + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::PrefetchL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::StartL() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::StartL() +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::StartL +"); + if (iIsInitialized) + { + // inform java side + ChangeState(EStarted); + iTunerPlayerUtility->Play(); + // set time when started + iStartTime = CurrentTime(); + + TInt64 time; + GetMediaTime(&time); + PostLongEvent(CMMAPlayerEvent::EStarted, time); + } + else + { + User::Leave(KErrNotReady); + } + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::StartL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::StopL() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::StopL(TBool /*aPostEvent*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::StopL +"); + if (iIsInitialized) + { + ChangeState(EPrefetched); + + iTunerPlayerUtility->Stop(); + + TInt64 time; + GetMediaTime(&time); + iStartTime = KErrNotFound; + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + else + { + User::Leave(KErrNotReady); + } + + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::StopL -"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::DeallocateL() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::DeallocateL() +{ + +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::GetMediaTime() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::GetMediaTime(TInt64* aMediaTime) +{ + if (iState == EStarted) + { + // add play time to media time + iMediaTime += CurrentTime() - iStartTime; + // set new start time + iStartTime = CurrentTime(); + } + + // set value to parameter + (*aMediaTime) = iMediaTime; +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::MTapoInitializeComplete +// Initialize complete event. This event is asynchronous and is received after +// a call to CMMTunerAudioPlayerUtility::InitializeL(). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::MTapoInitializeComplete(TInt aError) +{ + ELOG1( EJavaAMMS, "CAMMSTunerPlayer::MTapoInitializeComplete aError = %d", aError); + if (iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaAMMS, EInfo, "CAMMSTunerControl::MToTuneComplete AsyncStop"); + iActiveSchedulerWait->AsyncStop(); + } + if (aError == KErrNone) + { + iIsInitialized = ETrue; + ChangeState(EPrefetched); + // Inform Java side. + PostActionCompleted(KErrNone); + } + else + { + ELOG1( EJavaAMMS, "CAMMSTunerPlayer::MTapoInitializeComplete aError = %d", aError); + PostLongEvent(CMMAPlayerEvent::EError, aError); + //User::Leave( aError ); + } +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::MTapoPlayEvent +// Passes an asychronous event to the tuner client. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +void CAMMSTunerPlayer::MTapoPlayEvent( + MMMTunerAudioPlayerObserver::TEventType /*aEvent*/, + TInt /*aError*/, TAny* /*aAdditionalInfo*/) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerPlayer::MTapoPlayEvent +"); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPlayer::CurrentTime() +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt64 CAMMSTunerPlayer::CurrentTime() +{ + TTime time; + time.HomeTime(); + return time.Int64(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/cammstunerpresetshandler.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/cammstunerpresetshandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,133 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: ?Description +* +*/ + + + +// INCLUDE FILES +#include "CAMMSTunerPresetsHandler.h" +#include "TAMMSTunerPreset.h" + +#include +#include +#include + + +// CONSTANTS + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CAMMSTunerPresetsHandler::CAMMSTunerPresetsHandler +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +CAMMSTunerPresetsHandler::CAMMSTunerPresetsHandler() +{ +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPresetsHandler::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +// +void CAMMSTunerPresetsHandler::ConstructL() +{ + iCentralRepository = CRepository::NewL(KCRUidFMRadioEngine); +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPresetsHandler::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +// +CAMMSTunerPresetsHandler* CAMMSTunerPresetsHandler::NewL() +{ + CAMMSTunerPresetsHandler* self = new(ELeave) CAMMSTunerPresetsHandler; + + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + + return self; +} + + +// Destructor +CAMMSTunerPresetsHandler::~CAMMSTunerPresetsHandler() +{ + delete iCentralRepository; +} + + +// ----------------------------------------------------------------------------- +// CAMMSTunerPresetsHandler::GetPreset +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSTunerPresetsHandler::GetPresetL(TInt aPreset, TAMMSTunerPreset &aTunerPreset) +{ + // KFmRadioPresetChannel1 = The first preset channel's location in central repository + TInt tempChannelIndex = KFmRadioPresetChannel1 + aPreset; + + HBufC8* buf = HBufC8::NewLC(sizeof(TAMMSTunerPreset)); + TPtr8 bufPtr = buf->Des(); + + TInt err = iCentralRepository->Get(tempChannelIndex, bufPtr); + if (err == KErrNone) + { + RDesReadStream inStream; + inStream.Open(bufPtr); + CleanupClosePushL(inStream); + aTunerPreset.InternalizeL(inStream); + CleanupStack::PopAndDestroy(&inStream); + } + else + { + User::Leave(err); + } + CleanupStack::PopAndDestroy(); // buf +} + +// ----------------------------------------------------------------------------- +// CAMMSTunerPresetsHandler::SavePreset +// ?implementation_description +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void CAMMSTunerPresetsHandler::SavePresetL(TInt aPreset, TAMMSTunerPreset aTunerPreset) +{ + // KFmRadioPresetChannel1 = The first preset channel's location in central repository + TInt fieldNameIndex = KFmRadioPresetChannel1 + TUint32(aPreset); + + HBufC8* buf = HBufC8::NewLC(sizeof(TAMMSTunerPreset)); + TPtr8 bufPtr = buf->Des(); + + RDesWriteStream outStream(bufPtr); + CleanupClosePushL(outStream); + aTunerPreset.ExternalizeL(outStream); + outStream.CommitL(); + CleanupStack::PopAndDestroy(&outStream); + + iCentralRepository->Set(fieldNameIndex, bufPtr); + CleanupStack::PopAndDestroy(); //buf +} + + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/cammstunervolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/cammstunervolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to tuner player +* +*/ + + + +// INCLUDE FILES +#include "CAMMSTunerVolumeControl.h" +#include "CAMMSTunerPlayer.h" + +#include + + +CAMMSTunerVolumeControl::CAMMSTunerVolumeControl(CAMMSTunerPlayer* aTunerPlayer) + : CMMAVolumeControl(aTunerPlayer) +{ + iTunerPlayer = aTunerPlayer; +} + +CAMMSTunerVolumeControl* CAMMSTunerVolumeControl::NewL(CAMMSTunerPlayer* aTunerPlayer) +{ + LOG( EJavaAMMS, EInfo, "CAMMSTunerVolumeControl::NewL +"); + CAMMSTunerVolumeControl* self = new(ELeave) CAMMSTunerVolumeControl(aTunerPlayer); + + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + + return self; +} + +void CAMMSTunerVolumeControl::DoSetLevelL(TInt aLevel) +{ + LOG1( EJavaAMMS, EInfo, "CAMMSTunerVolumeControl::DoSetLevelL, aLevel = %d", aLevel); + // TunerPlayer does not currently have SetVolumeL method + User::Invariant(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/protocol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/protocol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Protocol JNI wrapper. + * +*/ + + +// EXTERNAL INCLUDES +//#include +#include + +// INTERNAL INCLUDES +#include "com_nokia_microedition_media_protocol_capture_radio_Protocol.h" +#include +#include "CAMMSTunerControl.h" +#include "CAMMSTunerPlayer.h" +#include "AMMSTunerFactory.h" +#include "jstringutils.h" +using namespace java::util; + +// Creates native tuner player +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_protocol_capture_radio_Protocol__1createNativeTunerPlayer( + JNIEnv* aJniEnv, + jobject /*aPeer*/, + jint aEventSourceHandle, + jstring aLocatorParameters) +{ + LOG( EJavaAMMS, EInfo, "AMMS Java_com_nokia_microedition_media_protocol_capture_radio_Protocol__1createNativeTunerPlayer +"); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + JStringUtils locatorParams(*aJniEnv, aLocatorParameters); + + CAMMSTunerPlayer* tunerPlayer = NULL; + + TInt error = eventSource->ExecuteTrap( + &AMMSTunerFactory::CreatePlayerL, + &tunerPlayer, + (const TDesC*)&locatorParams); + + ELOG1( EJavaAMMS, "AMMS __1createNativeTunerPlayer, error = %d", error); + + if (error != KErrNone) + { + return error; + } + + return reinterpret_cast(tunerPlayer); +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/tammstunerpreset.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/tammstunerpreset.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: ?Description +* +*/ + + + +// INCLUDE FILES +#include "TAMMSTunerPreset.h" + +#include +#include + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::TAMMSTunerPreset +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +TAMMSTunerPreset::TAMMSTunerPreset() +{ +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::SetPresetName +// ----------------------------------------------------------------------------- +// +void TAMMSTunerPreset::SetPresetName(const TDesC* aPresetName) +{ + iPresetName.Copy(*aPresetName); +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::SetPresetFrequency +// ----------------------------------------------------------------------------- +// +void TAMMSTunerPreset::SetPresetFrequency(const TInt aPresetFrequency) +{ + iPresetFrequency = aPresetFrequency; +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::SetPresetStereoMode +// ----------------------------------------------------------------------------- +// +void TAMMSTunerPreset::SetPresetStereoMode(const TInt aPresetStereoMode) +{ + iPresetStereoMode = aPresetStereoMode; +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::PresetName +// ----------------------------------------------------------------------------- +// +TPtrC TAMMSTunerPreset::PresetName() +{ + return iPresetName; +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::PresetFrequency +// ----------------------------------------------------------------------------- +// +TInt TAMMSTunerPreset::PresetFrequency() +{ + return iPresetFrequency; +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::PresetStereoMode +// ----------------------------------------------------------------------------- +// +TInt TAMMSTunerPreset::PresetStereoMode() +{ + return iPresetStereoMode; +} + +// ----------------------------------------------------------------------------- +// TAMMSTunerPreset::ExternalizeL +// Writes preset values to stream. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +// +void TAMMSTunerPreset::ExternalizeL(RWriteStream& aStream) const +{ + aStream<>iPresetName; + iPresetFrequency = aStream.ReadUint32L(); + iPresetStereoMode = aStream.ReadUint32L(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/amms_qt/src_tuner/native/src/tunercontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/amms_qt/src_tuner/native/src/tunercontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,731 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: TunerControl JNI wrapper. + * +*/ + + +// EXTERNAL INCLUDES +//#include + +// INTERNAL INCLUDES +#include "com_nokia_amms_control_tuner_TunerControlImpl.h" +#include +#include "CAMMSTunerControl.h" +#include "jstringutils.h" +using namespace java::util; + +/** +* Static delegator function for getMinFreq +*/ +LOCAL_C void GetMinFreqL(CAMMSTunerControl* aNativeClass, + TInt *aMinFreq) +{ + + *aMinFreq = aNativeClass->MinFreqL(); +} + +/** +* getMinFreq JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getMinFreq( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + TInt minFreq; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetMinFreqL, + nativeHandle, + &minFreq); + + if (err != KErrNone) + { + return err; + } + + return minFreq; +} + + +/** +* Static delegator function for getMaxFreq +*/ +LOCAL_C void GetMaxFreqL(CAMMSTunerControl* aNativeClass, + TInt *aMaxFreq) +{ + + *aMaxFreq = aNativeClass->MaxFreqL(); +} + +/** +* getMaxFreq JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getMaxFreq( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + TInt maxFreq; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetMaxFreqL, + nativeHandle, + &maxFreq); + + if (err != KErrNone) + { + return err; + } + + return maxFreq; +} + + +/** +* Static delegator function for setFrequency +*/ +LOCAL_C void SetFreqL(CAMMSTunerControl* aNativeClass, + TInt aFreq) +{ + + aNativeClass->SetFrequencyL(aFreq); +} + +/** +* Static delegator function for getFrequency +*/ +LOCAL_C void GetFreqL(CAMMSTunerControl* aNativeClass, + TInt *aFreq) +{ + *aFreq = aNativeClass->FrequencyL(); +} + +/** +* setFrequency JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setFrequency( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aFreq) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SetFreqL, + nativeHandle, + aFreq); + + if (err != KErrNone) + { + return err; + } + + //get tuned frequency + TInt tunedFreq; + err = eventSource->ExecuteTrap(GetFreqL, + nativeHandle, + &tunedFreq); + if (err != KErrNone) + { + return err; + } + + return tunedFreq; +} + +/** +* getFrequency JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getFrequency( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + TInt freq; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetFreqL, + nativeHandle, + &freq); + if (err != KErrNone) + { + return err; + } + + return freq; +} + + +/** +* Static delegator function for seek +*/ +LOCAL_C void SeekL(CAMMSTunerControl* aNativeClass, + TInt aStartFreq, + TBool aUpwards, + TInt* aSeekedFreq) +{ + + *aSeekedFreq = aNativeClass->SeekL(aStartFreq, aUpwards); +} + +/** +* seek JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1seek( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aStartFreq, + jboolean aUpwards) +{ + TInt seekedFreq; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SeekL, + nativeHandle, + aStartFreq, + (TBool) aUpwards, + &seekedFreq); + + if (err != KErrNone) + { + return err; + } + + return seekedFreq; +} + + +/** +* Static delegator function for getSquelch +*/ +LOCAL_C void GetSquelchL(CAMMSTunerControl* aNativeClass, + TBool* aSquelch) +{ + + *aSquelch = aNativeClass->SquelchL(); +} + +/** +* getSquelch JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getSquelch( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TBool squelch = EFalse; + + TInt err = eventSource->ExecuteTrap(GetSquelchL, + nativeHandle, + &squelch); + + if (err != KErrNone) + { + return err; + } + + if (!squelch) + { + //return 1 if false + return 1; + } + //return 0 if true + return KErrNone; +} + + +/** +* Static delegator function for setSquelch +*/ +LOCAL_C void SetSquelchL(CAMMSTunerControl* aNativeClass, + TBool aSquelch) +{ + + aNativeClass->SetSquelchL(aSquelch); +} + +/** +* setSquelch JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setSquelch( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jboolean aSquelch) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SetSquelchL, + nativeHandle, + (TBool) aSquelch); + + if (err != KErrNone) + { + return err; + } + + return KErrNone; +} + + +/** +* Static delegator function for getSignalStrength +*/ +LOCAL_C void GetSignalStrengthL(CAMMSTunerControl* aNativeClass, + TInt *aSignalStrength) +{ + + *aSignalStrength = aNativeClass->SignalStrengthL(); +} + +/** +* getSignalStrength JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getSignalStrength( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + TInt signalStrength; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetSignalStrengthL, + nativeHandle, + &signalStrength); + if (err != KErrNone) + { + return err; + } + + return signalStrength; +} + + +/** +* Static delegator function for getStereoMode +*/ +LOCAL_C void GetStereoModeL(CAMMSTunerControl* aNativeClass, + TInt *aStereoMode) +{ + + *aStereoMode = aNativeClass->StereoModeL(); +} + +/** +* getStereoMode JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getStereoMode( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle) +{ + TInt stereoMode; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetStereoModeL, + nativeHandle, + &stereoMode); + if (err != KErrNone) + { + return err; + } + + return stereoMode; +} + + +/** +* Static delegator function for setStereoMode +*/ +LOCAL_C void SetStereoModeL(CAMMSTunerControl* aNativeClass, + TInt aStereoMode) +{ + aNativeClass->SetStereoModeL(aStereoMode); +} + +/** +* setStereoMode JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setStereoMode( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aStereoMode) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SetStereoModeL, + nativeHandle, + aStereoMode); + + return err; +} + + +/** +* Static delegator function for usePreset +*/ +LOCAL_C void UsePresetL(CAMMSTunerControl* aNativeClass, + TInt aPreset) +{ + aNativeClass->UsePresetL(aPreset); +} + +/** +* usePreset JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1usePreset( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(UsePresetL, + nativeHandle, + aPreset); + + return err; +} + + +/** +* Static delegator function for setPreset__III +*/ +LOCAL_C void SetPresetL(CAMMSTunerControl* aNativeClass, + TInt aPreset) +{ + aNativeClass->SetPresetL(aPreset); +} + +/** +* setPreset__III JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setPreset__III( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SetPresetL, + nativeHandle, + aPreset); + + return err; +} + + +/** +* Static delegator function for setPreset__IIIII +*/ +LOCAL_C void SetPresetL(CAMMSTunerControl* aNativeClass, + TInt aPreset, + TInt aFrequency, + TInt aStereoMode) +{ + aNativeClass->SetPresetL(aPreset, aFrequency, aStereoMode); +} + +/** +* setPreset__IIIII JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setPreset__IIIII( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset, + jint aFrequency, + jint aStereoMode) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(SetPresetL, + nativeHandle, + aPreset, + aFrequency, + aStereoMode); + + return err; +} + + +/** +* Static delegator function for getPresetFrequency +*/ +LOCAL_C void GetPresetFreqL(CAMMSTunerControl* aNativeClass, + TInt aPreset, + TInt *aPresetFreq) +{ + + *aPresetFreq = aNativeClass->PresetFrequencyL(aPreset); +} + +/** +* getPresetFrequency JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getPresetFrequency( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset) +{ + TInt presetFreq; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetPresetFreqL, + nativeHandle, + aPreset, + &presetFreq); + if (err != KErrNone) + { + return err; + } + + return presetFreq; +} + + +/** +* Static delegator function for getPresetStereoMode +*/ +LOCAL_C void GetPresetStereoModeL(CAMMSTunerControl* aNativeClass, + TInt aPreset, + TInt *aPresetStereoMode) +{ + + *aPresetStereoMode = aNativeClass->PresetStereoModeL(aPreset); +} + +/** +* getPresetStereoMode JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getPresetStereoMode( + JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset) +{ + TInt presetStereoMode; + + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TInt err = eventSource->ExecuteTrap(GetPresetStereoModeL, + nativeHandle, + aPreset, + &presetStereoMode); + if (err != KErrNone) + { + return err; + } + + return presetStereoMode; +} + + +/** +* Static delegator function for setPresetName +*/ +LOCAL_C void SetPresetNameL(CAMMSTunerControl* aNativeClass, + TInt aPreset, + const TDesC* aPresetName) +{ + aNativeClass->SetPresetNameL(aPreset, aPresetName); +} + +/** +* setPresetName JNI function +*/ +JNIEXPORT jint JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1setPresetName( + JNIEnv* aJni, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset, + jstring aPresetName) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + JStringUtils presetName(*aJni, aPresetName); + + TInt err = eventSource->ExecuteTrap(SetPresetNameL, + nativeHandle, + aPreset, + (const TDesC*)&presetName); + + return err; +} + + +/** +* Static delegator function for getPresetName +*/ +LOCAL_C void GetPresetNameL(CAMMSTunerControl* aNativeClass, + TInt aPreset, + TPtrC* aPresetName) +{ + aNativeClass->GetPresetNameL(aPreset, aPresetName); +} + +/** +* getPresetName JNI function +*/ +JNIEXPORT jstring JNICALL +Java_com_nokia_amms_control_tuner_TunerControlImpl__1getPresetName( + JNIEnv* aJni, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aTunerControlHandle, + jint aPreset, + jintArray aError) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CAMMSTunerControl* nativeHandle = + reinterpret_cast(aTunerControlHandle); + + TPtrC presetNamePtr(NULL, 0); + jstring presetName = NULL; + + TInt err = eventSource->ExecuteTrap(GetPresetNameL, + nativeHandle, + aPreset, + &presetNamePtr); + + if (err == KErrNone) + { + presetName = S60CommonUtils::NativeToJavaString(*aJni, presetNamePtr); + if (!presetName) + { + err = KErrNotSupported; + } + } + + jint javaErr[ 1 ] = { err }; + aJni->SetIntArrayRegion(aError, 0, 1, javaErr); + + return presetName; +} + +// End of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/coreui_akn/src/javauiavkonimpl.cpp --- a/javauis/coreui_akn/src/javauiavkonimpl.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/coreui_akn/src/javauiavkonimpl.cpp Fri May 14 15:47:24 2010 +0300 @@ -35,6 +35,7 @@ JavaUiAvkonAppUi::~JavaUiAvkonAppUi() { JELOG2(EJavaUI); + mDestroying = true; if (mAppView) { delete mAppView; @@ -196,20 +197,25 @@ setDefaultProcessPriority(timeForCurrentPriority); } - if (hasStartScreen()) + if (event.Type() == EEventFocusLost) { - ASSERT(mAppView); - if (event.Type() == EEventFocusLost) + mIsForeground = false; + if (hasStartScreen()) { - mIsForeground = false; - mAppView->HandleForeground(false); + ASSERT(mAppView); + mAppView->HandleForeground(false); } - else if (event.Type() == EEventFocusGained) + } + else if (event.Type() == EEventFocusGained) + { + mIsForeground = true; + if (hasStartScreen()) { - mIsForeground = true; + ASSERT(mAppView); mAppView->HandleForeground(true); } } + bool eventBlocked = false; if (mActiveChild) { diff -r 2a9601315dfc -r 98ccebc37403 javauis/coreui_akn/src/javauiavkonimpl.h --- a/javauis/coreui_akn/src/javauiavkonimpl.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/coreui_akn/src/javauiavkonimpl.h Fri May 14 15:47:24 2010 +0300 @@ -89,6 +89,11 @@ * Get the moment of startup. */ TInt64 startupTime() const; + + /** + * Returns true, after the app has started to be destroyed. + */ + bool destroying() const {return mDestroying;}; public: // From CoreUiAvkonAppUi /** @@ -223,6 +228,7 @@ bool mIsDefaultPriorityInUse; TInt64 mStartupTime; bool mStartupCancelled; + bool mDestroying; }; NONSHARABLE_CLASS(JavaUiAvkonApplication): public CAknApplication diff -r 2a9601315dfc -r 98ccebc37403 javauis/coreui_akn/src/startupscreen/startscreen.cpp --- a/javauis/coreui_akn/src/startupscreen/startscreen.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/coreui_akn/src/startupscreen/startscreen.cpp Fri May 14 15:47:24 2010 +0300 @@ -626,28 +626,18 @@ { if (mState == ESyncRead) { - if (iStatus == KErrUnderflow) - { - ELOG1(EJavaUI, "CStartScreen::RunL, " - "CImageDecoder::Convert failed: %d", KErrUnderflow); - mDecoder->ContinueConvert(&iStatus); - SetActive(); - } - else + if (mWait.IsStarted()) { - if (mWait.IsStarted()) - { - mWait.AsyncStop(); - } + mWait.AsyncStop(); + } - // Release the lock on the file. - ASSERT(mDecoder); - delete mDecoder; - mDecoder = NULL; + // Release the lock on the file. + ASSERT(mDecoder); + delete mDecoder; + mDecoder = NULL; - // Reset state - mState = EIdle; - } + // Reset state + mState = EIdle; } else if (mState == EAsyncWrite) { diff -r 2a9601315dfc -r 98ccebc37403 javauis/coreui_akn/src/startupscreen/startscreencontainer.cpp --- a/javauis/coreui_akn/src/startupscreen/startscreencontainer.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/coreui_akn/src/startupscreen/startscreencontainer.cpp Fri May 14 15:47:24 2010 +0300 @@ -19,9 +19,9 @@ #include #include #include -#ifdef RD_JAVA_UI_ALFDRAWER_ENABLED +#ifdef RD_JAVA_S60_RELEASE_9_2 #include -#endif // RD_JAVA_UI_ALFDRAWER_ENABLED +#endif // RD_JAVA_S60_RELEASE_9_2 #include "startscreencontainer.h" #include "startscreen.h" @@ -49,8 +49,13 @@ { JELOG2(EJavaUI); - if (HidesIndicators()) - ShowIndicators(ETrue); + if (!mAppUi.destroying()) + { + if (HidesIndicators()) + { + ShowIndicators(ETrue); + } + } mFader.FadeBehindPopup(this, this, EFalse); mAppUi.RemoveFromStack(this); @@ -231,7 +236,11 @@ TBool CStartScreenContainer::HidesIndicators() const { +#ifdef RD_JAVA_S60_RELEASE_9_2 return (mStartScreen && mStartScreen->Type() == CStartScreen::EStartScreenAutomatic); +#else + return EFalse; +#endif } void CStartScreenContainer::Draw(const TRect& aRect) const @@ -309,6 +318,7 @@ JELOG2(EJavaUI); mStartScreenTimer = CStartScreenTimer::NewL(*this); + mStartScreenTimer->Start(); CreateWindowL(); SetMopParent(&mAppUi); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtapifacade/src/swtbrowserschemehandler.cpp --- a/javauis/eswt_akn/eswtapifacade/src/swtbrowserschemehandler.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtapifacade/src/swtbrowserschemehandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -16,8 +16,8 @@ */ +#include -#include #include "swtbrowserschemehandler.h" diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtapifacade/src/swtlaffacade.cpp --- a/javauis/eswt_akn/eswtapifacade/src/swtlaffacade.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtapifacade/src/swtlaffacade.cpp Fri May 14 15:47:24 2010 +0300 @@ -377,9 +377,16 @@ layoutRect.LayoutRect(aRect, AknLayoutScalable_Avkon:: list_single_popup_submenu_pane(0).LayoutLine()); break; + case EPopupEswtTasktipWindow: +#ifdef RD_JAVA_S60_RELEASE_9_2 + layoutRect.LayoutRect(aRect, AknLayoutScalable_Avkon:: + popup_discreet_window(aArg1).LayoutLine()); +#else layoutRect.LayoutRect(aRect, AknLayoutScalable_Avkon:: popup_eswt_tasktip_window(aArg1).LayoutLine()); +#endif + break; case EWaitBarPaneCp71: layoutRect.LayoutRect(aRect, AknLayoutScalable_Avkon:: @@ -576,10 +583,6 @@ layoutText.LayoutText(aRect, AknLayout:: Form_data_wide_graphic_field_texts_Line_2(aArg1)); break; - case EPopupEswtTasktipWindowT1: - layoutText.LayoutText(aRect, AknLayoutScalable_Avkon:: - popup_eswt_tasktip_window_t1(aArg1).LayoutLine()); - break; case ETabs4ActivePaneT1: layoutText.LayoutText(aRect, AknLayoutScalable_Avkon:: tabs_4_active_pane_t1(aArg1).LayoutLine()); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtapifacade/src/swtpopupformproxyprivate.cpp --- a/javauis/eswt_akn/eswtapifacade/src/swtpopupformproxyprivate.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtapifacade/src/swtpopupformproxyprivate.cpp Fri May 14 15:47:24 2010 +0300 @@ -110,7 +110,6 @@ // void CSwtPopupFormProxyPrivate::ProcessCommandL(TInt aCommandId) { - if (iTimeOut) { // if timed messsagebox @@ -134,11 +133,19 @@ TKeyResponse CSwtPopupFormProxyPrivate::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType) { - if (!iTimeOut) { // Other than TimedMessageBox - CAknPopupForm::OfferKeyEventL(aKeyEvent, aType); + TKeyResponse res = CAknPopupForm::OfferKeyEventL(aKeyEvent, aType); + if (aType == EEventKey && res == EKeyWasNotConsumed) + { + if (aKeyEvent.iCode == EKeyEnter || aKeyEvent.iCode == EKeyOK) + { + // Trigger the positive CBA action / soft key + TKeyEvent ev = {EKeyCBA1, EStdKeyDevice0, 0, 0}; + TRAP_IGNORE(CCoeEnv::Static()->SimulateKeyEventL(ev, EEventKey)); + } + } } else { @@ -152,7 +159,7 @@ CAknPopupForm::OfferKeyEventL(aKeyEvent, aType); } } - + // Keys cannot be allowed to "pass trough" the dialog. return EKeyWasConsumed; } @@ -166,7 +173,6 @@ void CSwtPopupFormProxyPrivate::HandlePointerEventL( const TPointerEvent& aPointerEvent) { - if (!iTimeOut) { // if not a timed messagebox diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/inc/org_eclipse_swt_widgets_DCControl.h --- a/javauis/eswt_akn/eswtdirectcontent/native/inc/org_eclipse_swt_widgets_DCControl.h Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -/* -* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_eclipse_swt_widgets_DCControl */ - -#ifndef _Included_org_eclipse_swt_widgets_DCControl -#define _Included_org_eclipse_swt_widgets_DCControl -#ifdef __cplusplus -extern "C" -{ -#endif -#undef org_eclipse_swt_widgets_DCControl_DISPOSED -#define org_eclipse_swt_widgets_DCControl_DISPOSED 1L -#undef org_eclipse_swt_widgets_DCControl_CANVAS -#define org_eclipse_swt_widgets_DCControl_CANVAS 2L -#undef org_eclipse_swt_widgets_DCControl_KEYED_DATA -#define org_eclipse_swt_widgets_DCControl_KEYED_DATA 4L -#undef org_eclipse_swt_widgets_DCControl_DISABLED -#define org_eclipse_swt_widgets_DCControl_DISABLED 8L -#undef org_eclipse_swt_widgets_DCControl_HIDDEN -#define org_eclipse_swt_widgets_DCControl_HIDDEN 16L -#undef org_eclipse_swt_widgets_DCControl_GRAB -#define org_eclipse_swt_widgets_DCControl_GRAB 32L -#undef org_eclipse_swt_widgets_DCControl_MOVED -#define org_eclipse_swt_widgets_DCControl_MOVED 64L -#undef org_eclipse_swt_widgets_DCControl_RESIZED -#define org_eclipse_swt_widgets_DCControl_RESIZED 128L -#undef org_eclipse_swt_widgets_DCControl_EXPANDING -#define org_eclipse_swt_widgets_DCControl_EXPANDING 256L -#undef org_eclipse_swt_widgets_DCControl_LAYOUT_NEEDED -#define org_eclipse_swt_widgets_DCControl_LAYOUT_NEEDED 512L -#undef org_eclipse_swt_widgets_DCControl_LAYOUT_CHANGED -#define org_eclipse_swt_widgets_DCControl_LAYOUT_CHANGED 1024L -#undef org_eclipse_swt_widgets_DCControl_IGNORE_WHEEL -#define org_eclipse_swt_widgets_DCControl_IGNORE_WHEEL 2048L -#undef org_eclipse_swt_widgets_DCControl_DEFAULT_WIDTH -#define org_eclipse_swt_widgets_DCControl_DEFAULT_WIDTH 64L -#undef org_eclipse_swt_widgets_DCControl_DEFAULT_HEIGHT -#define org_eclipse_swt_widgets_DCControl_DEFAULT_HEIGHT 64L - /* - * Class: org_eclipse_swt_widgets_DCControl - * Method: _createDCControl - * Signature: (II)I - */ - JNIEXPORT jint JNICALL Java_org_eclipse_swt_widgets_DCControl__1createDCControl - (JNIEnv *, jobject, jint, jint); - - /* - * Class: org_eclipse_swt_widgets_DCControl - * Method: _getControlHandle - * Signature: (I)I - */ - JNIEXPORT jint JNICALL Java_org_eclipse_swt_widgets_DCControl__1getControlHandle - (JNIEnv *, jobject, jint); - - /* - * Class: org_eclipse_swt_widgets_DCControl - * Method: _drawNow - * Signature: (I)V - */ - JNIEXPORT void JNICALL Java_org_eclipse_swt_widgets_DCControl__1drawNow - (JNIEnv *, jobject, jint); - - /* - * Class: org_eclipse_swt_widgets_DCControl - * Method: _setFullScreen - * Signature: (IZ)V - */ - JNIEXPORT void JNICALL Java_org_eclipse_swt_widgets_DCControl__1setFullScreen - (JNIEnv *, jobject, jint, jboolean); - -#ifdef __cplusplus -} -#endif -#endif diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/inc/swtdccontrol.h --- a/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdccontrol.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdccontrol.h Fri May 14 15:47:24 2010 +0300 @@ -51,7 +51,7 @@ , public MSwtAppFocusObserver , public MMMAContainer , public MSwtDcEventConsumer -#ifdef SWTDCCONTROL_DSA_ENABLED +#ifdef SWTDCCONTROL_DSA_ENABLED , public MDirectScreenAccess #endif { @@ -119,8 +119,8 @@ public: // From MSwtDcFullscreenProvider void HandleDcEvent(int aType); - -#ifdef SWTDCCONTROL_DSA_ENABLED + +#ifdef SWTDCCONTROL_DSA_ENABLED public: // MDirectScreenAccess void Restart(RDirectScreenAccess::TTerminationReasons aReason); void AbortNow(RDirectScreenAccess::TTerminationReasons aReason); @@ -153,7 +153,7 @@ private: TBool IsControlActive() const; -#ifdef SWTDCCONTROL_DSA_ENABLED +#ifdef SWTDCCONTROL_DSA_ENABLED TBool IsDsaRegionValid() const; #endif TBool IsContentVisibilityAllowed() const; @@ -188,13 +188,13 @@ // True, is DSA was started already TBool iDsaWasStartedAlready; #endif - + // Own. // This observer receives requests from any thread and asynchronously // calls a callback in ESWT thread to a given receiver CSwtDcObserver* iDcObserver; - - + + }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/inc/swtdceventconsumer.h --- a/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdceventconsumer.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdceventconsumer.h Fri May 14 15:47:24 2010 +0300 @@ -12,7 +12,7 @@ * Contributors: * * Description: THIS FILE IS NOT INCLUDED INTO ECLIPSE CVS DELIVERY -* An interface to sent events from using CSwtDcObserver. +* An interface to sent events from using CSwtDcObserver. * */ @@ -22,7 +22,7 @@ class MSwtDcEventConsumer { public: - virtual void HandleDcEvent(int aType) = 0; + virtual void HandleDcEvent(int aType) = 0; }; #endif // SWTDCEVENTCONSUMER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/inc/swtdcobserver.h --- a/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdcobserver.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtdirectcontent/native/inc/swtdcobserver.h Fri May 14 15:47:24 2010 +0300 @@ -99,7 +99,7 @@ * @param aCallbackId Id which is provided to the callback */ void InvokeUICallback(MUiEventConsumer& aConsumer, TInt aCallbackId); - + private: /** CSwtDcObserver event datatype */ enum TDcEventType @@ -148,7 +148,7 @@ MUiEventConsumer *aConsumer, TInt aCallbackId); - + // from base class CActive /** diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/src/jni_lookup.cpp --- a/javauis/eswt_akn/eswtdirectcontent/native/src/jni_lookup.cpp Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,103 +0,0 @@ -/* -* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -* All rights reserved. -* This component and the accompanying materials are made available -* under the terms of "Eclipse Public License v1.0" -* which accompanies this distribution, and is available -* at the URL "http://www.eclipse.org/legal/epl-v10.html". -* -* Initial Contributors: -* Nokia Corporation - initial contribution. -* -* Contributors: -* -* Description: -* -*/ -#include -#include -#include // Needed for strcmp - -#ifdef RD_JAVA_JXE_LOOKUP -#include -extern "C" -{ - extern const U_64 j9Jar[]; - - void* J9GetJXE() - { - return const_cast(reinterpret_cast(j9Jar)); - } -} -#endif - -#include "org_eclipse_swt_widgets_DCControl.h" - - -typedef void (*TFunc)(); - -typedef struct -{ - char *token; - unsigned int procaddr; -} TABLE_ENTRY; - -// lookup_table MUST be defined as 'const' or this file will cause a build error -// when comipling for the ARMI target -const TABLE_ENTRY lookup_table[]= -{ - { "Java_org_eclipse_swt_widgets_DCControl__1createDCControl", (unsigned int) Java_org_eclipse_swt_widgets_DCControl__1createDCControl }, - { "Java_org_eclipse_swt_widgets_DCControl__1drawNow", (unsigned int) Java_org_eclipse_swt_widgets_DCControl__1drawNow }, - { "Java_org_eclipse_swt_widgets_DCControl__1getControlHandle", (unsigned int) Java_org_eclipse_swt_widgets_DCControl__1getControlHandle }, - { "Java_org_eclipse_swt_widgets_DCControl__1setFullScreen", (unsigned int) Java_org_eclipse_swt_widgets_DCControl__1setFullScreen }, -}; - -// table_size MUST be defined as 'const' or this file will cause a build error -// when comipling for the ARMI target -const int table_size = sizeof(lookup_table) / sizeof(TABLE_ENTRY); - - -IMPORT_C TFunc jni_lookup(const char* aName); -EXPORT_C TFunc jni_lookup(const char* aName) -{ - int res=0; - int mid=0; - int top=0; - int bottom=table_size-1; - -#ifdef RD_JAVA_JXE_LOOKUP - if (!strcmp(aName, "J9GetJXE")) return (TFunc)J9GetJXE; -#endif - // Loop while the number of the items left in the list is greater - // than 2. Each iteration will split the number of items left to search - // in half - while ((bottom - top) > 1) - { - // This case handles the normal serach case where the number of - // items left to search is greater than 2 - mid=(top+bottom)/2; - res=strcmp(aName,lookup_table[mid].token); - if (res==0) return((TFunc) lookup_table[mid].procaddr); - if (res>0) top=mid; - else bottom=mid; - } - - // If there are two items left in the list then the bottom item should be - // checked for a match - if (bottom != top) - { - // Check the bottom item to see if it is a match - res=strcmp(aName,lookup_table[bottom].token); - if (res == 0) return ((TFunc) lookup_table[bottom].procaddr); - } - - // Check the top item to see if it is a match - res=strcmp(aName,lookup_table[top].token); - - if (res == 0) return ((TFunc) lookup_table[top].procaddr); - - // Neither the top or bottom items were a match so the - // method must not exist in the file - return NULL; -} - diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/eswtdirectcontent/native/src/swtdccontrol.cpp --- a/javauis/eswt_akn/eswtdirectcontent/native/src/swtdccontrol.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/eswtdirectcontent/native/src/swtdccontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -422,7 +422,7 @@ } } #else - (void)aFocused; //Supresses compilation warning + (void)aFocused; //Supresses compilation warning #endif } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/build/eswt.pro --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/build/eswt.pro Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/build/eswt.pro Fri May 14 15:47:24 2010 +0300 @@ -124,7 +124,6 @@ ../src/swttableitemdrawer.cpp \ ../src/swttablelistbox.cpp \ ../src/swttablelistboxview.cpp \ - ../src/swttasktip.cpp \ ../src/swttext.cpp \ ../src/swttextbase.cpp \ ../src/swttextextension.cpp \ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/browserpreferences.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/browserpreferences.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/browserpreferences.h Fri May 14 15:47:24 2010 +0300 @@ -34,29 +34,32 @@ TUint iAssocVpn; TBool iAccessPointSelectionMode; TBool iAutoLoadImages; - TInt iFontSize; + TUint iFontSize; TBool iTextWrap; - TWmlSettingsCookies iCookies; + TBool iCookies; TBool iPageOverview; TBool iBackList; TBool iAutoRefresh; - TWmlSettingsECMA iEcma; - TWmlSettingsIMEI iIMEINotification; + TBool iEcma; + TBool iIMEINotification; TUint32 iEncoding; - TWmlSettingsFullScreen iFullScreen; + TBool iFullScreen; TBool iQueryOnExit; TBool iSendReferrer; - TWmlSettingsHomePage iHomePgType; + TUint iHomePgType; TBool iHTTPSecuritySupressed; TBool iConnDialogs; TBool iHttpSecurityWarnings; - TInt iMediaVolume; + TUint iMediaVolume; HBufC* iSearchPgURL; HBufC* iHomePgURL; TBool iPopupBlocking; - TWmlSettingsFormData iFormDataSaving; - TWmlSettingsAutomaticUpdating iAutomaticUpdating; + TUint iFormDataSaving; + TUint iAutomaticUpdating; TUint iAutomaticUpdatingAP; + TUint iZoomMin; + TUint iZoomMax; + TUint iZoomDef; }; @@ -106,7 +109,7 @@ * central repository values * @return Returns references of TPreferencesValues which contains all preferences */ - virtual const TPreferencesValues& AllPreferencesL() = 0; + virtual const TPreferencesValues& AllPreferences() const = 0; /** * To access DefaultAccessPoint setting @@ -216,20 +219,20 @@ * To access Cookies setting * @return TWmlSettingsCookies */ - virtual TWmlSettingsCookies Cookies() const = 0; + virtual TBool Cookies() const = 0; /** * To access ECMA setting * @return TWmlSettingsECMA */ - virtual TWmlSettingsECMA Ecma() const = 0; + virtual TBool Ecma() const = 0; /** * Get IMEI notification setting * @return EWmlSettingsIMEIEnable if notification is enabled, * otherwise EWmlSettingsIMEIDisable */ - virtual TWmlSettingsIMEI IMEINotification() const = 0; + virtual TBool IMEINotification() const = 0; /** * Sends/Don not send the referrer header @@ -249,7 +252,7 @@ * To access Form Data Saving setting. * @return value of setting */ - virtual TWmlSettingsFormData FormDataSaving() const = 0; + virtual TUint FormDataSaving() const = 0; /** * Adds an observer to be notified about changes. Derived classes MUST diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswt.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswt.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswt.h Fri May 14 15:47:24 2010 +0300 @@ -801,7 +801,7 @@ * Unregisters a resource change observer. */ virtual void RemoveResourceChangeObserver(MSwtResourceChangeObserver* aObserver) = 0; - + /** * Registers app focus observer. * MSwtUiUtils and MSwtShell instances are already informed separately so don't add them. @@ -1138,7 +1138,7 @@ * Checks if the UI has started to be displayed on screen. */ virtual TBool IsUiReady() const =0; - + /** * Whatever UI component is getting ready to be displayed should notify the display. * @param aFullScreenUi Specifies if the starting ui is full screen. @@ -1155,15 +1155,15 @@ * Returns names of all fonts according to aScalable parameter. */ virtual CDesC16ArrayFlat* GetFontNamesL(TBool aScalable) const =0; - + /** - * Check if the current pointer event being handled is + * Check if the current pointer event being handled is * intended to revert the state of the grabbing control. */ virtual TBool RevertPointerEvent() const =0; - + /** - * Set the current pointer event being handled as + * Set the current pointer event being handled as * intended to revert the state of the grabbing control. */ virtual void SetRevertPointerEvent(TBool aStatus) =0; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtexpanded.hrh --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtexpanded.hrh Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtexpanded.hrh Fri May 14 15:47:24 2010 +0300 @@ -17,117 +17,59 @@ // FullScreen enum TWmlSettingsFullScreen - { +{ EWmlSettingsFullScreenSoftkeysOnly, EWmlSettingsFullScreenFullScreen - }; +}; // MediaVolume enum TWmlSettingsMediaVolume - { +{ EWmlSettingsVolumeMuted = 0, EWmlSettingsVolume1 = 2, EWmlSettingsVolume2 = 5, EWmlSettingsVolume3 = 8, EWmlSettingsVolume4 = 10 - }; +}; // Automatic updating enum TWmlSettingsAutomaticUpdating - { +{ EWmlSettingsAutomaticUpdatingWeekly, EWmlSettingsAutomaticUpdatingDaily, EWmlSettingsAutomaticUpdating4hours, EWmlSettingsAutomaticUpdatingHourly, EWmlSettingsAutomaticUpdating15min, EWmlSettingsAutomaticUpdatingOff - }; +}; // Cookies enum TWmlSettingsCookies - { +{ EWmlSettingsCookieReject, EWmlSettingsCookieAllow - }; +}; // ECMA enum TWmlSettingsECMA - { +{ EWmlSettingsECMADisable, EWmlSettingsECMAEnable - }; +}; // IMEI enum TWmlSettingsIMEI - { +{ EWmlSettingsIMEIDisable, EWmlSettingsIMEIEnable - }; - -// HomePage -enum TWmlSettingsHomePage - { - EWmlSettingsHomePageAccessPoint, // 0 - EWmlSettingsHomePageAddress, // 1 - EWmlSettingsHomePageUseCurrent, // 2 - EWmlSettingsHomePageBookmarks // 3 - }; - -// FormData -enum TWmlSettingsFormData - { - EWmlSettingsFormDataOff, // 0 - EWmlSettingsFormDataOnly, // 1 - EWmlSettingsFormDataPlusPassword // 2 - }; - -// settings listbox items -enum TWmlBrowserSettingsItems - { - // Main Settings Categories - EWmlSettingsGeneral = 0, - EWmlSettingsPage, - EWmlSettingsPrivacy, - EWmlSettingsWebFeeds, - - // Individual Settings - EWmlSettingsAccesspoint, - EWmlSettingsAutoLoadImages, - EWmlSettingsPageOverview, - EWmlSettingsBackList, - EWmlSettingsAutoRefresh, - EWmlSettingsEncoding, - EWmlSettingsFullScreen, - EWmlSettingsCookies, - EWmlSettingsEcma, - EWmlSettingsHttpSecurityWarnings, - EWmlSettingsIMEINotification, - - EWmlSettingsMediaVolume, - EWmlSettingsAutomaticUpdating, - EWmlSettingsAutomaticUpdatingAP, - EWmlSettingsHomePage, - EWmlSettingsFormDataSaving, - EWmlSettingsFontSize, - - // Multiple Windows Support - EWmlSettingsPopupBlocking, - - - - // For CDMA settings, use any values within this range - EWmlSettingsCDMAMin = 50, - EWmlSettingsSendReferrer, - EWmlSettingsCDMAMax = 70 - }; - +}; // Default Access Point enum TWmlSettingsAccessPointSelectionMode - { +{ EWmlSettingsAccessPointSelectionModeUserDefined, EWmlSettingsAccessPointSelectionModeAlwaysAsk - }; +}; #endif // ESWTEXPANDED_HRH diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtgraphics.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtgraphics.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtgraphics.h Fri May 14 15:47:24 2010 +0300 @@ -599,7 +599,7 @@ * Copies a rectangular area to a given position. */ virtual void CopyArea(const TRect& aSource, const TPoint& aDestination) =0; - + #ifdef RD_JAVA_NGA_ENABLED /** * Ensure that all drawing commands have been issued and diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtmobileextensions.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtmobileextensions.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtmobileextensions.h Fri May 14 15:47:24 2010 +0300 @@ -1437,23 +1437,6 @@ /** - * Interface class for the org.eclipse.ercp.swt.mobile.TaskTip class. - */ -class MSwtTaskTip -{ -protected: - virtual ~MSwtTaskTip() {} // Made protected to prevent destruction through the interface - -public: - virtual TSwtPeer Dispose() =0; - virtual TRect GetBarDefaultBounds(TBool aHasText) const=0; - virtual TRect GetLabelDefaultBounds(TBool aHasText) const=0; - virtual TRect GetShellDefaultBounds(TBool aHasText) const=0; - virtual TSwtPeer JavaPeer() const =0; -}; - - -/** * Interface class for the org.eclipse.ercp.swt.mobile.TextExtension class. */ class MSwtTextExtension diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtwidgetscore.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtwidgetscore.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/eswtwidgetscore.h Fri May 14 15:47:24 2010 +0300 @@ -52,7 +52,6 @@ class MSwtListBox; class MSwtListView; class MSwtSortedList; -class MSwtTaskTip; class MSwtTextExtension; class MSwtClipboard; class MSwtTableColumn; @@ -762,9 +761,9 @@ virtual TBool IsLongTapAnimationCandidate(const TPointerEvent& aPointerEvent) const =0; virtual void DoControlSpecificFeedback(const TBool& aFirstTap, - const TBool& aTappedToChildRect, + const TBool& aTappedToChildRect, const TPointerEvent& aPointerEvent) const = 0; - + virtual void PostMouseEventL(const TPointerEvent& aPointerEvent) = 0; }; @@ -956,7 +955,7 @@ * In case this is a ScrolledComposite, returns one of the possible physics actions defined in eswt.h */ virtual TInt ScrolledCompositePysicsAction() const = 0; - + /** * Draw scrollbar background. */ @@ -1128,7 +1127,7 @@ * Interface class for the org.eclipse.swt.widgets.Shell class * A class that implements MSwtShell must also implement MSwtDecorations. */ -class MSwtShell +class MSwtShell : public MEikStatusPaneObserver { public: @@ -1397,12 +1396,18 @@ */ virtual TBool AsyncPainting() const = 0; virtual void SetAsyncPainting(TBool aStatus) = 0; - + /** * Attached CBA to the Shell. Cannot be undone. */ virtual void InstallCba() = 0; virtual TBool HasCba() const = 0; + + /** + * Set task tip style. + */ + virtual void SetTaskTip() = 0; + virtual TBool IsTaskTip() const = 0; }; /** @@ -2798,18 +2803,18 @@ * Returns number of active browsers in applicaition. */ virtual TInt ActiveBrowserCount() const = 0; - + /** * Setter and getter for key input flag. */ virtual TBool NaviKeyInput() const = 0; virtual void SetNaviKeyInput(TBool aKeyInput) = 0; - + /** * This should be always used to hide, show the CBA. */ virtual void SetCbaVisible(TBool aVisible) = 0; - + /** * Returns the pointer to the control that is currently receiving the pointer events * because it has received EButton1Down event. This returns a valid control only between @@ -2817,6 +2822,22 @@ * @return Pointer to the control that is receiving the pointer events currently or NULL. */ virtual MSwtControl* GetPointerGrabbingControl() = 0; + + /** + * Default bounds for TaskTips + */ + virtual TRect TaskTipRect() const = 0; + + /** + * Sets the pointerGrabbingControl + * Calling with NULL of course unsets. + */ + virtual void SetPointerCaptureControl(MSwtControl* aControl) = 0; + + /** + * Returns the current control that is grabbing the pointer events. + */ + virtual MSwtControl* PointerCaptureControl() = 0; }; @@ -3157,14 +3178,6 @@ TSwtPeer aPeer, MSwtComposite& aParent, TInt aStyle) const =0; /** - * Constructs a TaskTip - * @param aDisplay The Display this TaskTip belongs to. - * @param aPeer The Java object associated with this C++ object - */ - virtual MSwtTaskTip* NewTaskTipL(MSwtDisplay& aDisplay, - TSwtPeer aPeer, TInt aStyle) const =0; - - /** * Constructs a TextExtension * @param aDisplay The Display this TextExtension belongs to. * @param aPeer The Java object associated with this C++ object diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbrowserpreferences.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbrowserpreferences.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbrowserpreferences.h Fri May 14 15:47:24 2010 +0300 @@ -70,7 +70,7 @@ // From MActiveApDbObserver // From MBrowserPreferences - const TPreferencesValues& AllPreferencesL(); + const TPreferencesValues& AllPreferences() const; void AddObserverL(MPreferencesObserver* anObserver); void RemoveObserver(MPreferencesObserver* anObserver); void NotifyObserversL(TPreferencesEvent aEvent, @@ -85,7 +85,6 @@ TUint aAssocVpn = KWmlNoDefaultAccessPoint); void SetFontSizeL(TInt aFontSize); void SetEncodingL(TUint32 aEncoding); - void SetHomePageTypeL(TWmlSettingsHomePage aHomePageType); TPtrC SelfDownloadContentTypesL(); TBool AccessPointSelectionMode(); void SetAccessPointSelectionModeL( @@ -93,12 +92,12 @@ TBool AutoLoadImages() const; TBool BackList() const; TBool AutoRefresh() const; - TWmlSettingsCookies Cookies() const; - TWmlSettingsECMA Ecma() const; - TWmlSettingsIMEI IMEINotification() const; + TBool Cookies() const; + TBool Ecma() const; + TBool IMEINotification() const; TBool SendReferrer() const; TBool PageOverview() const; - virtual TWmlSettingsFormData FormDataSaving() const; + TUint FormDataSaving() const; private: /** diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbutton.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbutton.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtbutton.h Fri May 14 15:47:24 2010 +0300 @@ -135,19 +135,19 @@ void RetrieveDefaultFontL(); void ProcessFontUpdate(); - + #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK /** * Returns ETrue when tactile feedback is needed on touch down */ TBool IsFeedbackOnTouchDownNeeded( - const TPointerEvent& aPointerEvent) const; + const TPointerEvent& aPointerEvent) const; /** * Returns ETrue when tactile feedback is needed on touch release */ TBool IsFeedbackOnTouchReleaseNeeded( - const TPointerEvent& aPointerEvent) const; + const TPointerEvent& aPointerEvent) const; #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK // From CCoeControl diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcaptionedcontrol.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcaptionedcontrol.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcaptionedcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -42,7 +42,7 @@ * @return pointer to an object of this class */ static CSwtCaptionedControl* NewL(MSwtDisplay& aDisplay, TSwtPeer aPeer, - MSwtComposite& aParent, TInt aStyle); + MSwtComposite& aParent, TInt aStyle); private: /** @@ -264,7 +264,7 @@ * Not Own. */ const MSwtColor* iForegroundColor; - + /** * Can be the child or null. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtclipboard.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtclipboard.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtclipboard.h Fri May 14 15:47:24 2010 +0300 @@ -80,7 +80,7 @@ * The java peer object */ const TSwtPeer iPeer; - + CEikonEnv* iCoeEnv; }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcomposite.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcomposite.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcomposite.h Fri May 14 15:47:24 2010 +0300 @@ -19,7 +19,9 @@ #include #include "eswtwidgetscore.h" #include "swtscrollablebase.h" - +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK +#include +#endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK class CEikScrollBarFrame; class CSwtScrollBar; @@ -136,6 +138,7 @@ void PaintUrgently() const; #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK void UpdateTactileFeedbackDensity(); + void DoScrollingFeedback(); #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK // Data @@ -205,8 +208,10 @@ /** * Kinetic scrolling tactile feedback */ + MTouchFeedback* iFeedback; // Not own TInt iLastTactileFeedbackPos; - TInt iTactileFeedbackDensity; + TInt iTactileFeedbackDensity; + TInt iLastPointerEventType; #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcontrolbase.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcontrolbase.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtcontrolbase.h Fri May 14 15:47:24 2010 +0300 @@ -71,7 +71,7 @@ * its parent. Other controls in the same parent are not taken * into account. * @param aRect Rectangle to be clipped - * @return Clipped rectangle + * @return Clipped rectangle */ TRect ClipToVisibleRect(const TRect& aRect) const; @@ -148,6 +148,9 @@ */ void RedrawFocusBackground(); + /** + * Checks if this controls should display a border / frame in case of Shells. + */ TBool HasBorderStyle() const; /** @@ -236,14 +239,14 @@ * Needs to be called by all inheritors from their PositionChanged(). */ IMPORT_C void HandlePositionChanged(); - + /** * Draws the non-window-owning component controls of the specified control * The GC must have already been activated. */ static void DrawComponentControls(const CCoeControl& aControl, const TRect& aRect, CWindowGc& aGc, TBool aCanDrawOutsideRect); - + static TBool RectContainsRect(const TRect& aContainer, const TRect& aContainee); /** @@ -260,17 +263,17 @@ * Check if one of the children is focused. */ TBool ChildIsFocused() const; - + /** * Same as SetFontL but without redraw. */ void DoSetFontL(const MSwtFont* aFont); - + /** * Same as SetBackgroundL but without redraw. */ void DoSetBackgroundL(const MSwtColor* aColor); - + /** * Same as SetForegroundL but without redraw. */ @@ -417,7 +420,7 @@ // True if control changed its focus. // Currently used for advanced tactile feedback. TBool iFocusChanged; - + /** * Used to implement visual pressed down feedback for some controls. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdateeditor.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdateeditor.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdateeditor.h Fri May 14 15:47:24 2010 +0300 @@ -118,7 +118,7 @@ * @param aIsFieldNumeric indicates whether field is numeric field * @returns true if field was modified, false otherwise. */ - TBool CSwtDateEditor::IsCurrentFieldChanged(TBool aIsFieldNumeric); + TBool IsCurrentFieldChanged(TBool aIsFieldNumeric); /** * Updates current field counters if necessary. diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdisplaybase.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdisplaybase.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtdisplaybase.h Fri May 14 15:47:24 2010 +0300 @@ -192,11 +192,11 @@ // From MSwtPopupMenuCallBack public: void HandlePopupMenuClosedL(); - + // From MSwtMediaKeysListener public: void HandleMediaKeyEvent(TKeyEvent& aKeyEvent, TInt aEventType); - + private: TInt LoadResourceFileL(); @@ -204,10 +204,10 @@ protected: // The thread of the Java VM RThread iJavaUiThread; - + // The event queue, owned, cannot be NULL CSwtEventQueue* iEventQueue; - + // Our status object used for notification of events TRequestStatus iRequestStatus; @@ -215,62 +215,62 @@ protected: // DLL's factory, owned, cannot be NULL MSwtFactory* iFactory; - + // The UI utility object, owned, cannot be NULL MSwtUiUtils* iUiUtils; - + // The Menu arranger, owned, cannot be NULL MSwtMenuArranger* iMenuArranger; - + // The Command arranger, owned, may be NULL MSwtCommandArranger* iCommandArranger; - + // The key mapper, owned, cannot be NULL CSwtKeyMapper* iKeyMapper; - - // The system font, object owned. Null at construction, + + // The system font, object owned. Null at construction, // allocated at the first SystemFontL() method call. MSwtFont* iSystemFont; - + // The java side timers that are currently active - RPointerArray iTimers; - + RPointerArray iTimers; + // Registered resource change observers RPointerArray iResourceChangeObservers; - + // Registered app focus observers RPointerArray iAppFocusObservers; - + // The unique instance of the mobile device MSwtMobileDevice* iMobileDevice; - + // The listener object for media keys CSwtMIDRemConObserver* iRemConObserver; - - // The shared object taking care of drawing the Java + + // The shared object taking care of drawing the Java // content for all controls, owned, cannot be NULL CSwtJavaBufferDrawer* iJavaBufferDrawer; - + #ifdef RD_SCALABLE_UI_V2 // The long tap detector, cannot be NULL CAknLongTapDetector* iLongTapDetector; - + // Indicates if a long tap has been detected after the previous EButton1Down event. TBool iLongTapDetected; - + // The pointer event of type EButton1Down which initiates the long tap TPointerEvent iLongTapPointerEvent; - + // The control upon which long tap started MSwtControl* iLongTapControl; #endif - + // Id of the loaded resource file TInt iResId; - + // Cached Coe env reference. CEikonEnv* iCoeEnv; - + // Flag for state reverting pointer events. TBool iRevertPointerEvent; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtedwincustomdrawer.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtedwincustomdrawer.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtedwincustomdrawer.h Fri May 14 15:47:24 2010 +0300 @@ -56,7 +56,7 @@ const TInt aStart, const TInt aEnd, const TPoint& aTextOrigin, TInt aExtraPixels) const; #endif - + TRgb SystemColor(TUint aColorIndex, TRgb aDefaultColor) const; private: @@ -64,13 +64,13 @@ * Control owning the drawer. */ const CEikEdwin& iEdwin; - + /** * Original drawer used for actual drawing. * Not own. */ const MFormCustomDraw* iEdWinDrawer; - + /** * Clipping rectangle. * Applied before iEdWinDrawer draws. diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtfactory.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtfactory.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtfactory.h Fri May 14 15:47:24 2010 +0300 @@ -103,8 +103,6 @@ MSwtComposite& aParent, TInt aStyle) const; MSwtSortedList* NewSortedListL(MSwtDisplay& aDisplay, TSwtPeer aPeer, MSwtComposite& aParent, TInt aStyle) const; - MSwtTaskTip* NewTaskTipL(MSwtDisplay& aDisplay, TSwtPeer aPeer, - TInt aStyle) const; MSwtTextExtension* NewTextExtensionL(MSwtDisplay& aDisplay, TSwtPeer aPeer, MSwtComposite& aParent, TInt aStyle) const; void RunTimedMessageBoxDlgLD(const TDesC& aTitle, const TDesC& aMessage, diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtgrid.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtgrid.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtgrid.h Fri May 14 15:47:24 2010 +0300 @@ -68,7 +68,7 @@ * Updates item drawer's custom clipping rectangle. */ void SetItemDrawerClippingRect(const TRect& aRect); - + /** * Wrapper for protected member function HandleScrollEventL of CAknGrid. */ @@ -80,7 +80,7 @@ // From CAknGrid protected: void CreateItemDrawerL(); - + private: /** * Called when size or position has changed. diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swthyperlink.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swthyperlink.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swthyperlink.h Fri May 14 15:47:24 2010 +0300 @@ -135,7 +135,7 @@ * Link fragment text color. */ TRgb iLinkColor; - + /** * Link fragment text color when highlighted. */ @@ -162,7 +162,7 @@ * Not own. */ MTouchFeedback* iFeedback; - + /** * True for as long as pressed by pointer. * Eclipses ASwtControlBase::iPressed! diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtimagedataloader.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtimagedataloader.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtimagedataloader.h Fri May 14 15:47:24 2010 +0300 @@ -95,7 +95,7 @@ * Set the logical values for height or width equal to * the values of the greatest frame (for height or width). */ - void CSwtImageDataLoader::SetLogicalScreenValues(const TFrameInfo& aInfo); + void SetLogicalScreenValues(const TFrameInfo& aInfo); /** * Set the x and y coordinates of the image in the current frame. diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlaffacade.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlaffacade.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlaffacade.h Fri May 14 15:47:24 2010 +0300 @@ -149,19 +149,8 @@ EChildShellWithoutTitlePane, EMenuItemPane, ESubMenuItemPane, - - /** - * popup_eswt_tasktip_window(0): task tip bar + label - * popup_eswt_tasktip_window(1): task tip bar or label only - */ EPopupEswtTasktipWindow, - - /** - * wait_bar_pane_cp71(0): progress bar in task tip bar + label - * wait_bar_pane_cp71(1): progress bar in task tip bar or label only - */ EWaitBarPaneCp71, - EChildShellTitleImagePane, EFindPane, EPopupMidpNoteAlarmWindowG1, @@ -202,14 +191,7 @@ EListDoubleLargeGraphicPaneT2, ECellEswtAppPaneT1, EFormDataWideGraphicFieldTextsLine2, - - /** - * popup_eswt_tasktip_window_t1(0): label in task tip bar + label - * popup_eswt_tasktip_window_t1(1): label in task tip bar or label only - */ - EPopupEswtTasktipWindowT1, ETabs4ActivePaneT1, - ECellHcAppPaneT1, ECellAppPaneT1, }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlink.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlink.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlink.h Fri May 14 15:47:24 2010 +0300 @@ -95,9 +95,9 @@ TInt DoTrailingWhitespaceCorrection( const TInt aCurrentTextPosition) const; TRect GetDrawableFragmentRectangle(const CFont& aFont, - const TDesC& aText, const TInt aLinePosition, const TInt aLength, - const TInt aAvailableWidth, const TInt aXOffset, const TInt aYOffset, - const TInt aCurrentLineIndex) const; + const TDesC& aText, const TInt aLinePosition, const TInt aLength, + const TInt aAvailableWidth, const TInt aXOffset, const TInt aYOffset, + const TInt aCurrentLineIndex) const; void SetFocusedFragment(); TBool IsRtl() const; @@ -181,7 +181,7 @@ * Link fragment text color. */ TRgb iLinkColor; - + /** * Link fragment text color when highlighted. */ @@ -224,13 +224,13 @@ * Own. */ const CSwtLinkFragmentDescriptor* iFocusedFragment; - + /** * True for as long as pressed by pointer. * Eclipses ASwtControlBase::iPressed! */ TBool iPressed; - + /** * True if 2 or more targets. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlist.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlist.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlist.h Fri May 14 15:47:24 2010 +0300 @@ -8,7 +8,7 @@ * Contributors: * Nokia Corporation - S60 implementation *******************************************************************************/ - + #ifndef SWTLIST_H #define SWTLIST_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbase.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbase.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbase.h Fri May 14 15:47:24 2010 +0300 @@ -222,8 +222,8 @@ /** * Second phase constructor */ - void ConstructL(); - + void ConstructL(); + private: /** * Update the default font. @@ -256,7 +256,7 @@ void PositionChanged(); void FocusChanged(TDrawNow aDrawNow); TTypeUid::Ptr MopSupplyObject(TTypeUid aId); - + private: void Draw(const TRect& aRect) const; @@ -358,12 +358,12 @@ * Stores last known focus index. Use only during paint and key handlers. */ TInt iPrevFocusIndex; - + /** * Type of the list */ TInt iListType; - + /** * View visible rect at last draw */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbox.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbox.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistbox.h Fri May 14 15:47:24 2010 +0300 @@ -151,7 +151,7 @@ void PositionChanged(); void FocusChanged(TDrawNow aDrawNow); TTypeUid::Ptr MopSupplyObject(TTypeUid aId); - + private: void Draw(const TRect& aRect) const; @@ -480,7 +480,7 @@ * Stores last known focus index. Use only during paint and key handlers. */ TInt iPrevFocusIndex; - + /** * View visible rect at last draw */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlists.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlists.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlists.h Fri May 14 15:47:24 2010 +0300 @@ -259,6 +259,14 @@ TInt aListType, CEikTextListBox* aList, TInt aHorizontal, TInt aVertical); + + /** + * Change stretching + */ + static void EnableStretching( + TInt aListType, + CEikTextListBox* aList, + TBool aEnabled); }; #endif // SWTLISTBOXLISTS_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlistsitemdrawer.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlistsitemdrawer.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistboxlistsitemdrawer.h Fri May 14 15:47:24 2010 +0300 @@ -55,7 +55,7 @@ CEikListBox* aOwner); ~CSwtColumnListBoxItemDrawer(); - + // From CListItemDrawer protected: void DrawItemText(TInt aItemIndex, @@ -76,7 +76,7 @@ CColumnListBoxData* aListBoxData, CEikListBox* aOwner); ~CSwtSingleHeadingStyleListBoxItemDrawer(); - + // From CListItemDrawer protected: void DrawItemText(TInt aItemIndex, diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistview.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistview.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtlistview.h Fri May 14 15:47:24 2010 +0300 @@ -8,7 +8,7 @@ * Contributors: * Nokia Corporation - S60 implementation *******************************************************************************/ - + #ifndef SWTLISTVIEW_H #define SWTLISTVIEW_H @@ -198,7 +198,7 @@ CSwtLafFacade::TSwtLafFacadeTextId& aRectIdPaneT1, CSwtLafFacade::TSwtLafFacadeFontId& aRectIdPaneT1Font ) const; - void CoerceCellRect(const TSwtListViewDensity& aDensity, + void CoerceCellRect(const TSwtListViewDensity& aDensity, TRect& aCellRect) const; #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK @@ -332,7 +332,7 @@ * Stores grid cell layout update status */ TBool iIsGridCellLayoutNeeded; - + /** * View visible rect at last draw */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmenuarranger.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmenuarranger.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmenuarranger.h Fri May 14 15:47:24 2010 +0300 @@ -25,7 +25,7 @@ /** * CSwtMenuArranger * @lib eswt - * + * * Context menus contain: * # Prior to 9.2: * - Specific control menu of focused control (Mark, Unmark, etc.). @@ -33,7 +33,7 @@ * - OK & SELECT commands of all parents of focused control. * # Since 9.2: * - No context menus in 9.2. - * + * * Stylus popup menus contain: * # Prior to 9.2: * - Specific control menu of long tapped control (Mark, Unmark, etc.). @@ -45,7 +45,7 @@ * - Specific control menu of long tapped control (Mark, Unmark, etc.). * - All commands of long tapped control. * - Popup menu of long tapped control (Control.setMenu()). - * + * * Options menus contain: * # Prior to 9.2: * - Menu bar of active shell. @@ -179,7 +179,7 @@ CEikMenuPane* ParentPane(CEikMenuPane& aPane) const; #ifdef RD_SCALABLE_UI_V2 - void OpenStylusPopupMenuL(const MSwtControl& aControl, const TPoint& aPoint, + void OpenStylusPopupMenuL(const MSwtControl& aControl, const TPoint& aPoint, MSwtPopupMenuCallBack* aCallBack = NULL); void OpenStylusPopupMenuL(const MSwtMenu& aMenu, const TPoint& aPoint); void CloseStylusPopupMenuL(); @@ -292,7 +292,7 @@ * Cached image size for the panes */ TSize iImageSize; - + MSwtPopupMenuCallBack* iPopupMenuCallback; }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmidmediakeyslistener.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmidmediakeyslistener.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmidmediakeyslistener.h Fri May 14 15:47:24 2010 +0300 @@ -8,7 +8,7 @@ * Contributors: * Nokia Corporation - S60 implementation *******************************************************************************/ - + #ifndef SWTMIDMEDIAKEYSLISTENER_H #define SWTMIDMEDIAKEYSLISTENER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmobiledevice.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmobiledevice.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtmobiledevice.h Fri May 14 15:47:24 2010 +0300 @@ -8,7 +8,7 @@ * Contributors: * Nokia Corporation - S60 implementation *******************************************************************************/ - + #ifndef SWTMOBILEDEVICE_H #define SWTMOBILEDEVICE_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtquerydialog.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtquerydialog.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtquerydialog.h Fri May 14 15:47:24 2010 +0300 @@ -54,7 +54,7 @@ : public CAknTextQueryDialog { private: - CSwtQueryDialogText::CSwtQueryDialogText(TInt aMinimum, TDes& aResult); + CSwtQueryDialogText(TInt aMinimum, TDes& aResult); public: enum TTextDialogStyle @@ -86,7 +86,7 @@ : public CAknFloatingPointQueryDialog { private: - CSwtQueryDialogNumeric::CSwtQueryDialogNumeric(TReal& aResult, + CSwtQueryDialogNumeric(TReal& aResult, const TDesC& aDefaultValue, TInt aMinimum, TInt aMaximum); public: @@ -114,7 +114,7 @@ : public CAknTimeQueryDialog { private: - CSwtQueryDialogDateTime::CSwtQueryDialogDateTime(TTime& aTime); + CSwtQueryDialogDateTime(TTime& aTime); public: enum TDateTimeDialogStyle diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtshell.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtshell.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtshell.h Fri May 14 15:47:24 2010 +0300 @@ -148,6 +148,8 @@ void SetAsyncPainting(TBool aStatus); void InstallCba(); TBool HasCba() const; + void SetTaskTip(); + TBool IsTaskTip() const; // From MEikStatusPaneObserver public: @@ -155,7 +157,7 @@ private: void FinishRedraw() const; - + // Data private: /** @@ -248,11 +250,16 @@ * this goes ETrue. */ TBool iAsyncPainting; - + /** * Once turned on can never be turned off. */ TBool iHasCba; + + /** + * Task tip style. + */ + TBool iIsTaskTip; }; #endif // SWTSHELL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtsortedlist.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtsortedlist.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtsortedlist.h Fri May 14 15:47:24 2010 +0300 @@ -43,7 +43,7 @@ * @return pointer to an object of this class */ static CSwtSortedList* NewL(MSwtDisplay& aDisplay, TSwtPeer aPeer, - MSwtComposite& aParent, TInt aStyle); + MSwtComposite& aParent, TInt aStyle); protected: /** @@ -130,7 +130,7 @@ * @param aSearchField the search field. */ void UpdateSearchTextViewRect(const CAknSearchField* aSearchField); - + /** * Rebound the filter. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swttablelistbox.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swttablelistbox.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swttablelistbox.h Fri May 14 15:47:24 2010 +0300 @@ -294,7 +294,7 @@ * Stores last known focus index. Use only during paint and key handlers. */ TInt iPrevFocusIndex; - + /** * Used to implement horizontal panning. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swttasktip.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swttasktip.h Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Nokia Corporation and/or its subsidiary(-ies). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Nokia Corporation - S60 implementation - *******************************************************************************/ - - -#ifndef SWTTASKTIP_H -#define SWTTASKTIP_H - - -#include "eswtmobileextensions.h" - - -/** - * CSwtTaskTip - * @lib eswt - */ -NONSHARABLE_CLASS(CSwtTaskTip) - : public CBase - , public MSwtTaskTip - , public MSwtResourceChangeObserver -{ -// Own methods -public: - static CSwtTaskTip* NewL(MSwtDisplay& aDisplay, TSwtPeer aPeer, TInt aStyle); - -// From MSwtTaskTip -public: - TSwtPeer Dispose(); - TSwtPeer JavaPeer() const; - TRect GetBarDefaultBounds(TBool aHasText) const; - TRect GetLabelDefaultBounds(TBool aHasText) const; - TRect GetShellDefaultBounds(TBool aHasText) const; - -// From MSwtResourceChangeObserver -public: - void OfferResourceChangeL(TInt aType); - -// Own methods -private: - CSwtTaskTip(MSwtDisplay& aDisplay, TSwtPeer aPeer, TInt aStyle); - ~CSwtTaskTip(); - void ConstructL(); - void UpdateLayout(); - -// Data -private: - MSwtDisplay& iDisplay; - const TSwtPeer iPeer; - TInt iStyle; - TRect iRectShell; - TRect iRectShellBarOrLabelOnly; - TRect iRectLabel; - TRect iRectLabelOnly; - TRect iRectBar; - TRect iRectBarOnly; -}; - -#endif // SWTTASKTIP_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtuiutils.h --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtuiutils.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/inc/swtuiutils.h Fri May 14 15:47:24 2010 +0300 @@ -85,17 +85,6 @@ void ShellActivabilityChanged(MSwtShell& aShell); /** - * Sets the pointerGrabbingControl - * Calling with NULL of course unsets. - */ - void SetPointerCaptureControl(MSwtControl* aControl); - - /** - * Returns the current control that is grabbing the pointer events. - */ - MSwtControl* PointerCaptureControl(); - - /** * Sets next focused control. This function is called when app lost focus, which stores * a pointer of control that can be focused when app gains focus again. * Calling with NULL of course unsets. @@ -195,7 +184,7 @@ * Highest inline control default font. See InlineReferenceFontHeight. */ const CFont& InlineReferenceFont() const; - + void HideIndicator(TInt aId); void HideIndicators(); @@ -237,10 +226,13 @@ void SetNaviKeyInput(TBool aStatus); void SetCbaVisible(TBool aVisible); MSwtControl* GetPointerGrabbingControl(); + TRect TaskTipRect() const; + void SetPointerCaptureControl(MSwtControl* aControl); + MSwtControl* PointerCaptureControl(); protected: void HandleFreeRamEventL(TInt aEventType); - + // From MSwtAppFocusObserver public: void HandleAppFocusChangeL(TBool aFocused); @@ -264,7 +256,7 @@ * Display reference needed for getting CEikEnv for now. */ MSwtDisplay& iDisplay; - + /** * All shells. * Not own. @@ -385,14 +377,14 @@ * Cached scrollbar breadth. Valid till next resolution change. */ TInt iScrollBarBreadth; - + /** * Inline reference stuff */ mutable const CFont* iInlineFont; mutable TInt iInlineFontHeight; - mutable TMargins8 iInlinePadding; - + mutable TMargins8 iInlinePadding; + /** * Key input flag. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_ercp_swt_mobile_internal_OS.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_ercp_swt_mobile_internal_OS.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_ercp_swt_mobile_internal_OS.cpp Fri May 14 15:47:24 2010 +0300 @@ -2526,81 +2526,16 @@ } - /* + /** * Class TaskTip */ - JNIEXPORT jint JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1New( - JNIEnv *aJniEnv, - jclass, - jobject aPeer, - jint aStyle) - { - jweak peerRef = aJniEnv->NewWeakGlobalRef(aPeer); - if (peerRef == NULL) - { - return NULL; - } - - CSwtDisplay& display = CSwtDisplay::Current(); - const MSwtFactory* factory = &display.Factory(); - MSwtTaskTip* result = NULL; - TRAPD(error, CallMethodL(result, factory, &MSwtFactory::NewTaskTipL, display, peerRef, aStyle)); - if (error) - { - aJniEnv->DeleteWeakGlobalRef(peerRef); - Throw(error, aJniEnv); - } - INCREASE_INSTANCE_COUNT(result, TaskTip); - - return reinterpret_cast(result); - } - - JNIEXPORT void JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1Dispose( - JNIEnv* aJniEnv, - jclass, - jint aHandle) + JNIEXPORT jobject JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1DefaultBounds( + JNIEnv* aJniEnv, jclass) { - MSwtTaskTip* tasktip = reinterpret_cast(aHandle); - TSwtPeer peerRef; - CallMethod(peerRef, tasktip, &MSwtTaskTip::Dispose); - ReleasePeer(aJniEnv, peerRef); - DECREASE_INSTANCE_COUNT(TaskTip); - } - - JNIEXPORT jobject JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1GetBarDefaultBounds( - JNIEnv* aJniEnv, - jclass, - jint aHandle, - jboolean aHasText) - { - MSwtTaskTip* tasktip = reinterpret_cast(aHandle); - TRect bounds(TRect::EUninitialized); - CallMethod(bounds, tasktip, &MSwtTaskTip::GetBarDefaultBounds, aHasText); - return NewJavaRectangle(aJniEnv, bounds); - } - - JNIEXPORT jobject JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1GetLabelDefaultBounds( - JNIEnv* aJniEnv, - jclass, - jint aHandle, - jboolean aHasText) - { - MSwtTaskTip* tasktip = reinterpret_cast(aHandle); - TRect bounds(TRect::EUninitialized); - CallMethod(bounds, tasktip, &MSwtTaskTip::GetLabelDefaultBounds, aHasText); - return NewJavaRectangle(aJniEnv, bounds); - } - - JNIEXPORT jobject JNICALL Java_org_eclipse_ercp_swt_mobile_internal_OS_TaskTip_1GetShellDefaultBounds( - JNIEnv* aJniEnv, - jclass, - jint aHandle, - jboolean aHasText) - { - MSwtTaskTip* tasktip = reinterpret_cast(aHandle); - TRect bounds(TRect::EUninitialized); - CallMethod(bounds, tasktip, &MSwtTaskTip::GetShellDefaultBounds, aHasText); - return NewJavaRectangle(aJniEnv, bounds); + MSwtDisplay& display = CSwtDisplay::Current(); + TRect res(TRect::EUninitialized); + CallMethod(res, &display.UiUtils(), &MSwtUiUtils::TaskTipRect); + return NewJavaRectangle(aJniEnv, res); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_swt_internal_symbian_OS.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_swt_internal_symbian_OS.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/org_eclipse_swt_internal_symbian_OS.cpp Fri May 14 15:47:24 2010 +0300 @@ -374,7 +374,7 @@ } } } - + JNIEXPORT void JNICALL Java_org_eclipse_swt_internal_symbian_OS_Display_1NotifyFirstPaintComplete (JNIEnv *, jclass, jboolean aTopShell) { @@ -1991,6 +1991,13 @@ CallMethod(shell, &MSwtShell::SetAsyncPainting, aStatus); } + JNIEXPORT void JNICALL Java_org_eclipse_swt_internal_symbian_OS_Shell_1SetTaskTip( + JNIEnv*, jclass, jint aHandle) + { + MSwtShell* shell = reinterpret_cast(aHandle); + CallMethod(shell, &MSwtShell::SetTaskTip); + } + /* * Class Label @@ -3320,4 +3327,13 @@ return result; } + JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_symbian_OS_windowServer(JNIEnv *, jclass) + { +#ifdef RD_JAVA_S60_RELEASE_9_2 + return 2; +#else + return 1; +#endif + } + } // extern "C" diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowser.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowser.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowser.cpp Fri May 14 15:47:24 2010 +0300 @@ -135,7 +135,11 @@ | TBrCtlDefs::ECapabilityCursorNavigation | TBrCtlDefs::ECapabilityFavicon | TBrCtlDefs::ECapabilityToolBar - | TBrCtlDefs::ECapabilityFitToScreen; + | TBrCtlDefs::ECapabilityFitToScreen +#ifdef RD_JAVA_S60_RELEASE_9_2 + | TBrCtlDefs::ECapabilityPinchZoom +#endif + ; if ((iBrowserLevelStyle | KSwtStyleHScroll) || (iBrowserLevelStyle | KSwtStyleVScroll)) { @@ -212,7 +216,7 @@ iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsAutoFormFillEnabled, Preferences().FormDataSaving()); // Update browser local settings according to values stored in preferences - const TPreferencesValues& pref = iPreferences->AllPreferencesL(); + const TPreferencesValues& pref = iPreferences->AllPreferences(); iFontSize = pref.iFontSize; iTextWrap = pref.iTextWrap; iEncoding = pref.iEncoding; @@ -221,6 +225,19 @@ iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsCharacterset, iEncoding); iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsLaunchAppUid, iDisplay.ApplicationUid()); + if (pref.iZoomMin < pref.iZoomMax && pref.iZoomDef >= pref.iZoomMin && pref.iZoomDef <= pref.iZoomMax) + { + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelMin, pref.iZoomMin); + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelMax, pref.iZoomMax); + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelDefault, pref.iZoomDef); + } + else + { + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelMin, 10); + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelMax, 200); + iBrCtlInterface->SetBrowserSettingL(TBrCtlDefs::ESettingsZoomLevelDefault, 100); + } + // WidgetExtension needs a valid base path. // Base path would be used to write preferences on Widget runtime context but // when embedded into eSWT it does not really write any data. The base path still @@ -374,19 +391,32 @@ } #ifdef RD_SCALABLE_UI_V2 +// --------------------------------------------------------------------------- +// Originated from CSwtBrowserContainer, not CSwtShell. +// --------------------------------------------------------------------------- +// void CSwtBrowser::HandlePointerEventL(const TPointerEvent& aPointerEvent) { iHandlingPointerEv = ETrue; - // From parent Shell coordinates to CSwtBrowserContainer coordinates - TPointerEvent event(aPointerEvent); - event.iPosition -= Rect().iTl; - - iBrCtlInterface->HandlePointerEventL(event); - - // Must grab to allow HandlePointerBufferReadyL to be forwarded to Browser - // Enables panning / touch scrolling. - iBrCtlInterface->ClaimPointerGrab(EFalse); + if (!iDisplay.RevertPointerEvent()) + { +#ifdef RD_JAVA_S60_RELEASE_9_2 + // From parent Shell coordinates to CSwtBrowserContainer coordinates + if (aPointerEvent.AdvancedPointerEvent()) + { + TAdvancedPointerEvent event = *(static_cast(&aPointerEvent)); + event.iPosition -= Rect().iTl; + iBrCtlInterface->HandlePointerEventL(event); + } + else +#endif + { + TPointerEvent event = *(static_cast(&aPointerEvent)); + event.iPosition -= Rect().iTl; + iBrCtlInterface->HandlePointerEventL(event); + } + } iHandlingPointerEv = EFalse; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowsercontainer.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowsercontainer.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowsercontainer.cpp Fri May 14 15:47:24 2010 +0300 @@ -42,6 +42,13 @@ // Required by the Browser control. WSERV:43 raised if not provided. Window().AllocPointerMoveBuffer(256, 0); Window().DisablePointerMoveBuffer(); + EnableDragEvents(); +#ifdef RD_JAVA_S60_RELEASE_9_2 +#ifndef __WINSCW__ + Window().EnableAdvancedPointers(); +#endif +#endif // RD_JAVA_S60_RELEASE_9_2 + ActivateL(); } void CSwtBrowserContainer::FocusChanged(TDrawNow aDrawNow) @@ -53,14 +60,31 @@ #ifdef RD_SCALABLE_UI_V2 void CSwtBrowserContainer::HandlePointerEventL(const TPointerEvent& aPointerEvent) { - // From CSwtBrowserContainer coordinates to parent Shell coordinates - TPointerEvent event(aPointerEvent); - event.iPosition += iApiProvider.Rect().iTl; + // Capturing the pointer improves considerably the frequency of drag events + // and the usability of the pinch zooming. It also shortens the route of + // the event back to the browser. + MSwtUiUtils& utils = iApiProvider.Display().UiUtils(); + MSwtControl* prevCapturingCtrl = utils.PointerCaptureControl(); + utils.SetPointerCaptureControl(&iApiProvider); + + MSwtControl* shell = iApiProvider.GetShell().Control(); - // Forward to Shell which will forward to CSwtBrowser. If not done this way, - // CSwtBrowser will not get focused meaning users being unable to use the websites! - MSwtShell& shell = iApiProvider.GetShell(); - shell.Control()->CoeControl().HandlePointerEventL(event); +#ifdef RD_JAVA_S60_RELEASE_9_2 + if (aPointerEvent.AdvancedPointerEvent()) + { + TAdvancedPointerEvent event = *(static_cast(&aPointerEvent)); + event.iPosition += iApiProvider.Rect().iTl; + shell->HandlePointerEventL(event); + } + else +#endif + { + TPointerEvent event = *(static_cast(&aPointerEvent)); + event.iPosition += iApiProvider.Rect().iTl; + shell->HandlePointerEventL(event); + } + + utils.SetPointerCaptureControl(prevCapturingCtrl); } #endif diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowserpreferences.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowserpreferences.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbrowserpreferences.cpp Fri May 14 15:47:24 2010 +0300 @@ -144,47 +144,22 @@ void CSwtBrowserPreferences::RestoreSettingsL() { - // Read auto load images setting iAllPreferences.iAutoLoadImages = GetIntValue(KBrowserNGImagesEnabled); - - // Read font size iAllPreferences.iFontSize = GetIntValue(KBrowserNGFontSize); - - // Read Allow Cookies setting - if (GetIntValue(KBrowserNGCookiesEnabled)) - { - iAllPreferences.iCookies = EWmlSettingsCookieAllow; - } - else - { - iAllPreferences.iCookies = EWmlSettingsCookieReject; - } - - // Read ECMA Setting - if (GetIntValue(KBrowserNGECMAScriptSupport)) - { - iAllPreferences.iEcma = EWmlSettingsECMAEnable; - } - else - { - iAllPreferences.iEcma = EWmlSettingsECMADisable; - } + iAllPreferences.iCookies = GetIntValue(KBrowserNGCookiesEnabled); + iAllPreferences.iEcma = GetIntValue(KBrowserNGECMAScriptSupport); TInt encoding; iRepository->Get(KBrowserNGEncoding, encoding); - iAllPreferences.iEncoding = static_cast< TUint32 >(encoding); + iAllPreferences.iEncoding = (TUint32)encoding; - // Read operator variated settings - iAllPreferences.iPageOverview = GetIntValue( - KBrowserNGPageOverview); - iAllPreferences.iBackList - = GetIntValue(KBrowserNGBackList); - iAllPreferences.iAutoRefresh - = GetIntValue(KBrowserNGAutoRefresh); + iAllPreferences.iPageOverview = GetIntValue(KBrowserNGPageOverview); + iAllPreferences.iBackList = GetIntValue(KBrowserNGBackList); + iAllPreferences.iAutoRefresh = GetIntValue(KBrowserNGAutoRefresh); + iAllPreferences.iIMEINotification = GetIntValue(KBrowserIMEINotification); // Read suppress security UI setting - iAllPreferences.iHTTPSecuritySupressed - = GetIntValue(KBrowserSecurityUI); + iAllPreferences.iHTTPSecuritySupressed = GetIntValue(KBrowserSecurityUI); // Read show connection queries setting iAllPreferences.iConnDialogs = GetIntValue(CSwtLafFacade::GetUintConstant( @@ -207,9 +182,8 @@ CSwtLafFacade::EBrowserNGPopupBlocking)); // Form Data Saving - iAllPreferences.iFormDataSaving - = static_cast< TWmlSettingsFormData >(GetIntValue( - CSwtLafFacade::GetUintConstant(CSwtLafFacade::EBrowserFormDataSaving))); + iAllPreferences.iFormDataSaving = GetIntValue( + CSwtLafFacade::GetUintConstant(CSwtLafFacade::EBrowserFormDataSaving)); // Search Page, dont't want search page if (iAllPreferences.iSearchPgURL) @@ -218,21 +192,28 @@ iAllPreferences.iSearchPgURL = NULL; } - // Web reed feeds settings + // Web feeds settings iAllPreferences.iAutomaticUpdating = static_cast< TWmlSettingsAutomaticUpdating > (GetIntValue(KBrowserNGAutomaticUpdating)); iAllPreferences.iAutomaticUpdatingAP = GetIntValue( KBrowserNGAutomaticUpdatingAccessPoint); +#ifdef RD_JAVA_S60_RELEASE_9_2 + iAllPreferences.iZoomMax = GetIntValue(KBrowserNGZoomMax); + iAllPreferences.iZoomMin = GetIntValue(KBrowserNGZoomMin); + iAllPreferences.iZoomDef = GetIntValue(KBrowserNGZoomDefault); +#endif + // Read Accesss point selection mode for advanced settings iAllPreferences.iAccessPointSelectionMode - = GetIntValue(KBrowserAccessPointSelectionMode); + = GetIntValue(KBrowserAccessPointSelectionMode); // Read default AP setting - // get application specific ap + // Get application specific ap TUint32 appId = iApiProvider.Display().ApplicationUid(); - // get applicatin specific ap + + // Get applicatin specific ap TUint32 ap = CSwtLafFacade::JavaAPNL(appId); if (ap == CSwtLafFacade::GetUintConstant( @@ -246,7 +227,7 @@ if (ap == CSwtLafFacade::GetUintConstant( CSwtLafFacade::EMIDletSuiteAPNNotSpecified)) { - // try to get ap from browser NG reposictory + // Try to get ap from browser NG reposictory ap = GetIntValue(KBrowserDefaultAccessPoint); } if (!ap) @@ -425,7 +406,7 @@ return retVal; } -const TPreferencesValues& CSwtBrowserPreferences::AllPreferencesL() +const TPreferencesValues& CSwtBrowserPreferences::AllPreferences() const { return iAllPreferences; } @@ -489,17 +470,17 @@ return iAllPreferences.iAutoRefresh; } -TWmlSettingsCookies CSwtBrowserPreferences::Cookies() const +TBool CSwtBrowserPreferences::Cookies() const { return iAllPreferences.iCookies; } -TWmlSettingsECMA CSwtBrowserPreferences::Ecma() const +TBool CSwtBrowserPreferences::Ecma() const { return iAllPreferences.iEcma; } -TWmlSettingsIMEI CSwtBrowserPreferences::IMEINotification() const +TBool CSwtBrowserPreferences::IMEINotification() const { return iAllPreferences.iIMEINotification; } @@ -514,7 +495,7 @@ return iAllPreferences.iPageOverview; } -TWmlSettingsFormData CSwtBrowserPreferences::FormDataSaving() const +TUint CSwtBrowserPreferences::FormDataSaving() const { return iAllPreferences.iFormDataSaving; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbutton.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbutton.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtbutton.cpp Fri May 14 15:47:24 2010 +0300 @@ -697,7 +697,7 @@ { // Do not pass SKs to CAknButton as it will activate. if (iButton && (aKeyEvent.iScanCode != EStdKeyDevice0 && aKeyEvent.iScanCode != EStdKeyDevice1)) - { + { TBool forward(EFalse); if ((iStyle & KSwtStyleRadio) && (GetParent()->Control()->CaptionedControlInterface() == NULL) @@ -712,10 +712,11 @@ { forward = ETrue; } - + if (forward) { - if (aKeyEvent.iScanCode == EStdKeyNkpEnter) { + if (aKeyEvent.iScanCode == EStdKeyNkpEnter) + { // Workaround for CAknButton's inability to handle EKeyEnter correctly TKeyEvent ev; ev.iCode = aKeyEvent.iCode; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommand.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommand.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommand.cpp Fri May 14 15:47:24 2010 +0300 @@ -47,7 +47,7 @@ void CSwtCommand::ConstructL() { iParentControl.GetShell().InstallCba(); - + // Notify Command arranger (must be done at the end of ConstructL, // when Command is created for sure) MSwtCommandArranger* commandArranger = iDisplay.CommandArranger(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommandarranger.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommandarranger.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcommandarranger.cpp Fri May 14 15:47:24 2010 +0300 @@ -250,14 +250,14 @@ // Get pointer to first control (the one that is actually focused) to process const MSwtControl* control = GetFirstFocusedControl(); - + #ifdef RD_JAVA_S60_RELEASE_9_2 - if (control) + if (control) { control = control->GetShell().Control(); } #endif // RD_JAVA_S60_RELEASE_9_2 - + const MSwtControl* focusedControl(control); TFixedArray cbaIsAvailable; @@ -760,7 +760,7 @@ if (iCommandMenuOK) { TInt numberOfOKCommands(iCommandMenuOK->CountDisplayableItems()); - + // If MSK enabled, not in fullscreen, no control menu items, // and there is only one OK (or SELECT) command, // this command is not included in the context options menu since @@ -774,7 +774,7 @@ { numberOfOKCommands = 0; } - + // Addition of control menu items and OK (or SELECT) commands iNumberOfContextOptionMenuItems = numberOfOKCommands + numberOfControlMenuItems; @@ -1287,7 +1287,7 @@ // // From MEikCommandObserver // Notified from CEikCba::OfferKeyEventL > CEikButtonGroupContainer::ProcessCommandL -// +// void CSwtCommandArranger::ProcessCommandL(TInt aCommandId) { TInt cmdIndex(aCommandId - KSwtCommandBaseId); @@ -1442,7 +1442,7 @@ { return ETrue; } - + #ifdef RD_JAVA_S60_RELEASE_9_2 if (aControl.IsShell()) { diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcomposite.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcomposite.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcomposite.cpp Fri May 14 15:47:24 2010 +0300 @@ -21,7 +21,6 @@ #include #include #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK -#include #include #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK #include "swtcomposite.h" @@ -44,6 +43,7 @@ CAknControl::SetDimmed(aDimmed); SetFocusing(ETrue); #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + iFeedback = MTouchFeedback::Instance(); UpdateTactileFeedbackDensity(); #endif // RD_JAVA_ADVANCED_TACTILE_FEEDBACK } @@ -367,6 +367,10 @@ CEikScrollBar* hsb = iSbFrame ? iSbFrame->GetScrollBarHandle(CEikScrollBar::EHorizontal) : NULL; +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + iLastPointerEventType = aPointerEvent.iType; +#endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK + // Check if we should start scrollbar grabbing if (aPointerEvent.iType == TPointerEvent::EButton1Down) { @@ -1444,28 +1448,11 @@ } #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + // Flicking or panning the composite content should give the feedback if (iPhysicsAction == KSwtPhysicsPanning || iPhysicsAction == KSwtPhysicsFlicking) { - TRect scrolledRect(coeCtrl.Rect()); - TRect thisRect(CoeControl().Rect()); - if (scrolledRect.iTl.iY < thisRect.iTl.iY && - scrolledRect.iBr.iY > thisRect.iBr.iY) - { - TInt lastFeedbackDistanceY = Abs(iLastTactileFeedbackPos - - iPhysicsViewPos.iY); - - if (lastFeedbackDistanceY >= iTactileFeedbackDensity) - { - iLastTactileFeedbackPos = iPhysicsViewPos.iY; - - MTouchFeedback* feedback = MTouchFeedback::Instance(); - if (feedback) - { - feedback->InstantFeedback(ETouchFeedbackFlick); - } - } - } + DoScrollingFeedback(); } #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK } @@ -1629,8 +1616,61 @@ void CSwtComposite::UpdateTactileFeedbackDensity() { TAknLayoutRect layoutRect = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EListDoubleLargeGraphicPane, + CSwtLafFacade::EListSingleHeadingPane, TRect(), 0, 0, 0); iTactileFeedbackDensity = layoutRect.Rect().Height(); } + +void CSwtComposite::DoScrollingFeedback() +{ + if (!iScrlCompContent) + { + return; + } + + TRect scrolledRect(iScrlCompContent->CoeControl().Rect()); + TRect thisRect(CoeControl().Rect()); + + // Calculate distance between current content position + // and previous position, where last feedback happened + TInt lastFeedbackDistanceY = Abs(iLastTactileFeedbackPos + - iPhysicsViewPos.iY); + TTouchLogicalFeedback feedbackType(ETouchFeedbackNone); + if (lastFeedbackDistanceY >= iTactileFeedbackDensity) + { + if (scrolledRect.iTl.iY < thisRect.iTl.iY && + scrolledRect.iBr.iY > thisRect.iBr.iY) + { + // If top (or bottom) edge of the content is outside + // of visible area of composite, do feedback every time + feedbackType = ETouchFeedbackSensitiveList; + } + else if (iLastPointerEventType != TPointerEvent::EButton1Up) + { + // Begining or end of the content reached (i.e. top or bottom + // egde of the contont is now visible): feedback is given + // only if user do panning. No feedback, if touch release + // happened. + feedbackType = ETouchFeedbackSensitiveList; + } + // Store the position of the content + iLastTactileFeedbackPos = iPhysicsViewPos.iY; + } + + if (iFeedback && feedbackType != ETouchFeedbackNone) + { + if (iLastPointerEventType != TPointerEvent::EButton1Up) + { + iFeedback->EnableFeedbackForControl(this, ETrue, ETrue); + } + else + { + // Disable audion feedback on flicking (i.e. user don't pan by + // touch input) + iFeedback->EnableFeedbackForControl(this, ETrue, EFalse); + } + // Do the feedback if needed + iFeedback->InstantFeedback(this, feedbackType); + } +} #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtconstrainedtext.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtconstrainedtext.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtconstrainedtext.cpp Fri May 14 15:47:24 2010 +0300 @@ -79,7 +79,7 @@ { return; } - + // Update editor's visibility, otherwise text will be drawn // when performing clipboard operations on invisible control. const TBool visible = GetVisibleRecursively(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcontrolbase.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcontrolbase.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtcontrolbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -170,13 +170,16 @@ clippingRegion = SetupChildClippingRegion(composite, aGc, aRect); } + TBool isDialogShell = IsShell() && iParent; + TBool isTaskTip = isDialogShell && ShellInterface()->IsTaskTip(); + // Draw the background. if (!IsDefaultBackgroundUse() #ifdef RD_JAVA_S60_RELEASE_9_2 - // Fill the round corners - || (IsShell() && iParent) + // Fill the round corners + || (isDialogShell && !isTaskTip) #endif // RD_JAVA_S60_RELEASE_9_2 - ) + ) { aGc.SetBrushColor(GetBackground()); aGc.Clear(aRect); @@ -227,9 +230,11 @@ TBool ASwtControlBase::HasBorderStyle() const { TBool res = (iStyle & KSwtStyleBorder); - if (IsShell()) + const MSwtShell* shell = ShellInterface(); + if (shell) { - res = res && (!(iStyle & KSwtStyleNoTrim) && iParent); + // TaskTip shells have the border. + res = shell->IsTaskTip() || (res && !(iStyle & KSwtStyleNoTrim) && iParent); } return res; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdateeditor.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdateeditor.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdateeditor.cpp Fri May 14 15:47:24 2010 +0300 @@ -257,7 +257,7 @@ { iBgColorIsCustom = EFalse; } - + Redraw(); } @@ -268,7 +268,7 @@ void CSwtDateEditor::SetForegroundL(const MSwtColor* aColor) { ASwtControlBase::DoSetForegroundL(aColor); - + TRgb color((aColor) ? aColor->RgbValue() : iEikonEnv->Color(EColorControlText)); iEditor->OverrideColorL(EColorControlText, color); @@ -293,7 +293,7 @@ { iFgColorIsCustom = EFalse; } - + Redraw(); } @@ -1107,7 +1107,7 @@ void CSwtDateEditor::HandlePointerEventL(const TPointerEvent& aPointerEvent) { TBool hit = ETrue; - + #ifdef RD_JAVA_S60_RELEASE_9_2 TBool pressed = iPressed; hit = Rect().Contains(aPointerEvent.iPosition); @@ -1119,9 +1119,9 @@ else if (aPointerEvent.iType == TPointerEvent::EDrag) iPressed = hit; #endif - - if (!(aPointerEvent.iType == TPointerEvent::EButton1Up - && (iDisplay.RevertPointerEvent() || !hit))) + + if (!(aPointerEvent.iType == TPointerEvent::EButton1Up + && (iDisplay.RevertPointerEvent() || !hit))) { iEditor->HandlePointerEventL(aPointerEvent); @@ -1141,7 +1141,7 @@ iCurrentFieldLength = 0; iCurrentFieldDecimalPlacesCount = 0; iLastField = iEditor->CurrentField(); - + #ifdef RD_JAVA_S60_RELEASE_9_2 if (pressed != iPressed) Redraw(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdisplaybase.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdisplaybase.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtdisplaybase.cpp Fri May 14 15:47:24 2010 +0300 @@ -790,7 +790,7 @@ return iRevertPointerEvent || iLongTapDetected; } -void ASwtDisplayBase::SetRevertPointerEvent(TBool aStatus) +void ASwtDisplayBase::SetRevertPointerEvent(TBool aStatus) { iRevertPointerEvent = aStatus; } @@ -1082,6 +1082,8 @@ { iLongTapControl = NULL; iLongTapDetected = EFalse; + + // The Shell is required to already have handled the pointer down. MSwtControl* ctrl = iUiUtils->GetPointerGrabbingControl(); // No long tap animation on scrollbars or trimings. @@ -1091,7 +1093,7 @@ iLongTapControl = ctrl; } } - + iLongTapPointerEvent = aPointerEvent; if (iLongTapControl) @@ -1128,7 +1130,7 @@ return; } - // Will be switched back after the popup menu closes + // Will be switched back after the popup menu closes // and the late pointer up event was delivered. iLongTapDetected = ETrue; @@ -1148,7 +1150,7 @@ event.iType = TPointerEvent::EButton1Up; iLongTapControl->HandlePointerEventL(event); // revert } - + // Just to clear the flags. CancelLongTapAnimation(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtedwin.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtedwin.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtedwin.cpp Fri May 14 15:47:24 2010 +0300 @@ -49,7 +49,7 @@ // CLafEdwinCustomDrawBase* CSwtEdwin::CreateCustomDrawL() { - // Custom draw object is deleted by CEikEdwin + // Custom draw object is deleted by CEikEdwin const MFormCustomDraw* edwinDrawer = CEikEdwin::CreateCustomDrawL(); iClippingCustomDrawer = new(ELeave)CSwtEdwinCustomDrawer( iEikonEnv->LafEnv(), edwinDrawer, *this); @@ -87,7 +87,7 @@ // CLafEdwinCustomDrawBase* CSwtIntegerEdwin::CreateCustomDrawL() { - // Custom draw object is deleted by CEikEdwin + // Custom draw object is deleted by CEikEdwin const MFormCustomDraw* edwinDrawer = CEikEdwin::CreateCustomDrawL(); iClippingCustomDrawer = new(ELeave)CSwtEdwinCustomDrawer( iEikonEnv->LafEnv(), edwinDrawer, *this); @@ -142,7 +142,7 @@ // CLafEdwinCustomDrawBase* CSwtFloatingPointEdwin::CreateCustomDrawL() { - // Custom draw object is deleted by CEikEdwin + // Custom draw object is deleted by CEikEdwin const MFormCustomDraw* edwinDrawer = CEikEdwin::CreateCustomDrawL(); iClippingCustomDrawer = new(ELeave)CSwtEdwinCustomDrawer( iEikonEnv->LafEnv(), edwinDrawer, *this); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtfactory.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtfactory.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -49,7 +49,6 @@ #include "swtmultipagedialog.h" #include "swtscreen.h" #include "swtsortedlist.h" -#include "swttasktip.h" #include "swttextextension.h" #include "swttimedmessagebox.h" #include "swtquerydialog.h" @@ -392,14 +391,6 @@ return CSwtQueryDialog::ConvertDefaultValueL(aString, aQueryType); } -MSwtTaskTip* CSwtFactory::NewTaskTipL( - MSwtDisplay& aDisplay, - TSwtPeer aPeer, - TInt aStyle) const -{ - return CSwtTaskTip::NewL(aDisplay, aPeer, aStyle); -} - MSwtTextExtension* CSwtFactory::NewTextExtensionL( MSwtDisplay& aDisplay, TSwtPeer aPeer, diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtgcbase.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtgcbase.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtgcbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -22,9 +22,9 @@ #include #endif -#ifdef RD_JAVA_UI_ALFDRAWER_ENABLED +#ifdef RD_JAVA_S60_RELEASE_9_2 #include -#endif // RD_JAVA_UI_ALFDRAWER_ENABLED +#endif // RD_JAVA_S60_RELEASE_9_2 /* * This method is used only for M2G support purposes @@ -674,14 +674,14 @@ TInt CSwtGcBase::FinishOperationL() { TInt err = KErrNone; -#ifdef RD_JAVA_UI_ALFDRAWER_ENABLED +#ifdef RD_JAVA_S60_RELEASE_9_2 CAlfDrawer* drawer = CAlfDrawer::NewL(); CleanupStack::PushL(drawer); err = drawer->Finish(); CleanupStack::PopAndDestroy(drawer); #else err = CCoeEnv::Static()->WsSession().Finish(); -#endif // RD_JAVA_UI_ALFDRAWER_ENABLED +#endif // RD_JAVA_S60_RELEASE_9_2 return err; } #endif // RD_JAVA_NGA_ENABLED diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtjavabufferdrawer.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtjavabufferdrawer.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtjavabufferdrawer.cpp Fri May 14 15:47:24 2010 +0300 @@ -397,10 +397,9 @@ TSize* size = reinterpret_cast(&width); TPoint* pointDest = reinterpret_cast(&destX); - (void)aWindow; // Just to suppress a potential warning + (void)aWindow; // Just to suppress a potential warning (void)aDrawRect; // Just to suppress a potential warning -#ifdef RD_JAVA_NGA_ENABLED -#ifdef RD_JAVA_UI_ALFDRAWER_ENABLED +#ifdef RD_JAVA_S60_RELEASE_9_2 aWindow->EndRedraw(); TInt result = KErrAbort; TRAPD(err,result = aGc->FinishOperationL()); @@ -411,8 +410,7 @@ CCoeEnv::Static()->WsSession().Finish(); } aWindow->BeginRedraw(aDrawRect); -#endif // RD_JAVA_UI_ALFDRAWER_ENABLED -#endif // RD_JAVA_NGA_ENABLED +#endif // RD_JAVA_S60_RELEASE_9_2 aGc->CopyArea(TRect(*pointSrc, *size), *pointDest); } @@ -425,10 +423,9 @@ TPoint pos(srcX, srcY); - (void)aWindow; // Just to suppress a potential warning + (void)aWindow; // Just to suppress a potential warning (void)aDrawRect; // Just to suppress a potential warning -#ifdef RD_JAVA_NGA_ENABLED -#ifdef RD_JAVA_UI_ALFDRAWER_ENABLED +#ifdef RD_JAVA_S60_RELEASE_9_2 aWindow->EndRedraw(); TInt result = KErrAbort; TRAPD(err,result = aGc->FinishOperationL()); @@ -439,8 +436,8 @@ CCoeEnv::Static()->WsSession().Finish(); } aWindow->BeginRedraw(aDrawRect); -#endif // RD_JAVA_UI_ALFDRAWER_ENABLED -#endif // RD_JAVA_NGA_ENABLED +#endif // RD_JAVA_S60_RELEASE_9_2 + aGc->CopyAreaL(*image, pos); } break; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlabel.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlabel.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlabel.cpp Fri May 14 15:47:24 2010 +0300 @@ -1205,7 +1205,7 @@ const CFont& font = (swtFont->Font()); DoSetFontL(&font); } - + Redraw(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbase.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbase.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -1460,6 +1460,11 @@ // Update background color listBoxDrawer->SetBackColor(GetBackground()); + + // Suppress margins - they are drawn over scrollbars + // We need to update margins here one more time, because previous + // code re-sets them + CSwtListBoxLists::SetMargins(iListType, iList, 0, 0); } // --------------------------------------------------------------------------- diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbox.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbox.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistbox.cpp Fri May 14 15:47:24 2010 +0300 @@ -895,6 +895,22 @@ // This is needed for the case where the theme has animated highlights. iList->SetFocus(ETrue, ENoDrawNow); +#ifdef RD_JAVA_S60_RELEASE_9_2 + // Disable stretching for two line lists + switch (iProps.iListType) + { + case ESwtLbDouble: + case ESwtLbDoubleGraphic: + case ESwtLbDoubleLarge: + // Disable stretching to keep items double line in landscape + CSwtListBoxLists::EnableStretching(iProps.iListType, iList, EFalse); + break; + default: + // Do nothing + break; + } +#endif + // Must trigger SizeChanged which Avkon lists use to create the layout // columns. Not calling this will result in invisible lists or incorrect // list layouts. Also important is to hide the list while is being @@ -1249,6 +1265,11 @@ // The listbox looses the custom color after resize, therefore reset. if (iColor) UpdateListColor(); + + // Suppress margins - they are drawn over scrollbars + // We need to update margins here one more time, because previous + // code re-sets them + CSwtListBoxLists::SetMargins(iProps.iListType, iList, 0, 0); } // --------------------------------------------------------------------------- @@ -1444,6 +1465,7 @@ list->SetCurrentItemIndex(0); list->SetComponentsToInheritVisibility(ETrue); CreateScrollBarsL(list); + #ifdef RD_SCALABLE_UI_V2 list->SetListBoxObserver(this); #endif // RD_SCALABLE_UI_V2 diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlists.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlists.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlists.cpp Fri May 14 15:47:24 2010 +0300 @@ -204,20 +204,25 @@ && aSbFrame->ScrollBarVisibility(CEikScrollBar::EVertical) != CEikScrollBarFrame::EOff) { + TInt breadth(0); + if (iListObserver) + { + breadth = iListObserver->Utils().ScrollBarBreadth( + aSbFrame->VerticalScrollBar()); + } + else + { + breadth = aSbFrame->ScrollBarBreadth(CEikScrollBar::EVertical); + } + if (!AknLayoutUtils::LayoutMirrored()) { - TInt breadth(0); - if (iListObserver) - { - breadth = iListObserver->Utils().ScrollBarBreadth( - aSbFrame->VerticalScrollBar()); - } - else - { - breadth = aSbFrame->ScrollBarBreadth(CEikScrollBar::EVertical); - } clientRect.iBr.iX -= breadth; } + else + { + clientRect.iTl.iX += breadth; + } } } @@ -471,6 +476,34 @@ } } +// --------------------------------------------------------------------------- +// CSwtListBoxLists::EnableStretching +// --------------------------------------------------------------------------- +// +void CSwtListBoxLists::EnableStretching(TInt aListType, CEikTextListBox* aList, + TBool aEnabled) +{ + ASSERT(IsListType(aListType)); + + switch (aListType) + { + case ESwtLbDouble: + STATIC_CAST(CSwtListBoxDouble*, aList) + ->EnableStretching(aEnabled); + break; + case ESwtLbDoubleGraphic: + STATIC_CAST(CSwtListBoxDoubleGraphic*, aList) + ->EnableStretching(aEnabled); + break; + case ESwtLbDoubleLarge: + STATIC_CAST(CSwtListBoxDoubleLarge*, aList) + ->EnableStretching(aEnabled); + break; + default: + // Other list types are not supported + break; + } +} // The compiler does not automatically instantiate templates defined in other // files. Because of this, code written will often produce undefined symbol diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlistsitemdrawer.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlistsitemdrawer.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistboxlistsitemdrawer.cpp Fri May 14 15:47:24 2010 +0300 @@ -102,7 +102,7 @@ { BeginClipping(iGc); CColumnListBoxItemDrawer::DrawItemText(aItemIndex, aItemTextRect, - aItemIsCurrent, aViewIsEmphasized, aItemIsSelected); + aItemIsCurrent, aViewIsEmphasized, aItemIsSelected); EndClipping(iGc); } @@ -160,14 +160,7 @@ void ASwtListBoxItemDrawerBase::SetCustomClippingRect( const TRect& aRect) { - if (aRect.IsNormalized()) - { - iCustomClippingRect = aRect; - } - else - { - iCustomClippingRect = TRect::EUninitialized; - } + iCustomClippingRect = aRect; } // --------------------------------------------------------------------------- @@ -176,10 +169,7 @@ // void ASwtListBoxItemDrawerBase::BeginClipping(CWindowGc* aGc) const { - if (iCustomClippingRect != TRect::EUninitialized) - { - aGc->SetClippingRect(iCustomClippingRect); - } + aGc->SetClippingRect(iCustomClippingRect); } // --------------------------------------------------------------------------- @@ -188,8 +178,5 @@ // void ASwtListBoxItemDrawerBase::EndClipping(CWindowGc* aGc) const { - if (iCustomClippingRect != TRect::EUninitialized) - { - aGc->CancelClippingRect(); - } + aGc->CancelClippingRect(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistview.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistview.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtlistview.cpp Fri May 14 15:47:24 2010 +0300 @@ -192,6 +192,8 @@ #else gridFlags |= EAknListBoxMarkableGrid; #endif + // Enabling marking only by pressing enter key + gridFlags |= CEikListBox::EEnterMarks; // Create control menu iMenu = CSwtControlMenu::NewL(iDisplay, NULL, 0); @@ -2689,15 +2691,7 @@ { GetSelection(iOldSelectionArray); - TBool shiftKeyPressed = (aKeyEvent.iModifiers & EModifierShift) || - (aKeyEvent.iModifiers & EModifierLeftShift) || - (aKeyEvent.iModifiers & EModifierRightShift); - - // Do not offer menu opening ok key event to the grid - if ((aKeyEvent.iCode != EKeyOK && aKeyEvent.iCode != EKeyEnter) || shiftKeyPressed) - { - iGrid->OfferKeyEventL(aKeyEvent, aType); - } + iGrid->OfferKeyEventL(aKeyEvent, aType); if (aType == EEventKeyUp) { @@ -2931,22 +2925,16 @@ } else if (aKeyCode == EKeyOK || aKeyCode == EKeyEnter) { - if (iStyle & KSwtStyleSingle) + MSwtCommandArranger* commandArranger = iDisplay.CommandArranger(); + if (commandArranger) { - MSwtCommandArranger* commandArranger = iDisplay.CommandArranger(); - if (commandArranger) + if (iStyle & KSwtStyleSingle && + commandArranger->IsContextSensitiveOperationSet()) { - if (commandArranger->IsContextSensitiveOperationSet()) - { - return EFalse; - } + return EFalse; } - return ETrue; } - else - { - return EFalse; - } + return ETrue; } return ETrue; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtmobileshell.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtmobileshell.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtmobileshell.cpp Fri May 14 15:47:24 2010 +0300 @@ -197,7 +197,7 @@ { return; } - + iStatusPaneStyle = statusStyle; // Immediatelly called after construction on Java side. Status style is @@ -215,7 +215,7 @@ { utils.UpdateStatusPaneL(); } - + CCoeControl::SetRect(DefaultBounds()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtscreen.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtscreen.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtscreen.cpp Fri May 14 15:47:24 2010 +0300 @@ -73,6 +73,13 @@ } iIsTheOnlyScreen = (iDisplay.MobileDevice()->GetScreenNumber() == 1); iOrientationState = EOrientationNotSet; + + iActivationState = EFalse; + if (iScreenDevice->GetScreenNumber() == iId) + { + iActivationState = ETrue; + } + if (IsScreenOn()) { iOrientation = CurrentOrientation(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtshell.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtshell.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtshell.cpp Fri May 14 15:47:24 2010 +0300 @@ -146,38 +146,38 @@ CCoeControl::SetPointerCapture(ETrue); } #endif //RD_SCALABLE_UI_V2 - + #ifdef RD_JAVA_S60_RELEASE_9_2 GfxTransEffect::Enable(); - GfxTransEffect::Register(this, - iParent ? KGfxOptionsMenuControlUid : KGfxInformationNoteControlUid, EFalse); + GfxTransEffect::Register(this, + iParent ? KGfxOptionsMenuControlUid : KGfxInformationNoteControlUid, EFalse); // Window transparency cannot be enabled as it breaks the async drawing. - // Since transparency cannot be enabled, set the initial background + // Since transparency cannot be enabled, set the initial background // color to something closer to the theme's background. if (iParent) { TRgb bgColor = iDisplay.UiUtils().GetSystemColor(ESwtColorWidgetBackground); - + TInt r = bgColor.Green(); r -= KSwtRoundCornerBgColorDiff; - if (r < 0) + if (r < 0) r = 0; - + TInt g = bgColor.Green(); g -= KSwtRoundCornerBgColorDiff; - if (g < 0) + if (g < 0) g = 0; - + TInt b = bgColor.Blue(); b -= KSwtRoundCornerBgColorDiff; - if (b < 0) + if (b < 0) b = 0; - + bgColor.SetRed(b); bgColor.SetGreen(b); bgColor.SetBlue(b); - + OverrideColorL(EColorControlBackground, bgColor); } #endif // RD_JAVA_S60_RELEASE_9_2 @@ -304,7 +304,7 @@ #ifdef RD_JAVA_S60_RELEASE_9_2 GfxTransEffect::Deregister(this); #endif // RD_JAVA_S60_RELEASE_9_2 - + CSwtUiUtils& uiUtils = UiUtils(); if (uiUtils.GetActiveShell() == this) { @@ -362,7 +362,7 @@ // --------------------------------------------------------------------------- // CSwtShell::HandlePointerEventL // This is the entry point for all pointer events targeted at any of the children -// of this Shell. +// of this Shell except for Browser's case. // From CCoeControl // --------------------------------------------------------------------------- // @@ -371,19 +371,10 @@ { CSwtUiUtils& utils = UiUtils(); - utils.SetNaviKeyInput(EFalse); - - MSwtControl* capturingControl = utils.PointerCaptureControl(); - if (capturingControl && capturingControl != this) - { - capturingControl->HandlePointerEventL(aPointerEvent); - capturingControl->PostMouseEventL(aPointerEvent); - iDisplay.TryDetectLongTapL(aPointerEvent); - return; - } - if (aPointerEvent.iType == TPointerEvent::EButton1Down) { + utils.SetNaviKeyInput(EFalse); + // Ignore pointer events outside modal Shells. MSwtShell *activeShell = utils.GetActiveShell(); if (!activeShell || (activeShell && activeShell != this && @@ -394,6 +385,20 @@ } } + MSwtControl* capturingControl = utils.PointerCaptureControl(); + if (capturingControl && capturingControl != this) + { + if (aPointerEvent.iType == TPointerEvent::EButton1Down + && capturingControl->IsFocusable()) + { + capturingControl->SetSwtFocus(KSwtFocusByPointer); + } + capturingControl->HandlePointerEventL(aPointerEvent); + capturingControl->PostMouseEventL(aPointerEvent); + iDisplay.TryDetectLongTapL(aPointerEvent); + return; + } + MSwtControl* ctrl = NULL; if (aPointerEvent.iType == TPointerEvent::EButton1Up) @@ -435,9 +440,9 @@ { TRAP_IGNORE(CreateBackgroundL()); } - + CSwtUiUtils& utils = UiUtils(); - + #ifdef RD_JAVA_S60_RELEASE_9_2 TBool doEffect = (IsVisible() != aVisible) && (iDisplay.IsUiReady() || iParent); if (doEffect) @@ -455,9 +460,9 @@ GfxTransEffect::End(this); } #endif // RD_JAVA_S60_RELEASE_9_2 - + utils.ShellActivabilityChanged(*this); - + // Done already if the Shell became active if (aVisible && utils.GetActiveShell() != this) { @@ -919,10 +924,10 @@ // --------------------------------------------------------------------------- // void CSwtShell::SetVisible(TBool aVisible) -{ +{ // A DrawNow() is absolutely mandatory if the ui is set to be ready. CSwtDecorations::SetVisible(aVisible); - + TBool paintingUrgently = !AsyncPainting(); if (aVisible && paintingUrgently && !iDisplay.IsUiReady()) { @@ -2053,6 +2058,38 @@ } // --------------------------------------------------------------------------- +// CSwtShell::SetTaskTip +// From MSwtShell +// --------------------------------------------------------------------------- +// +void CSwtShell::SetTaskTip() +{ + iIsTaskTip = ETrue; +#ifdef RD_JAVA_S60_RELEASE_9_2 + if (iParent && CAknEnv::Static()->TransparencyEnabled()) + { + Window().SetRequiredDisplayMode(EColor16MA); + if (Window().SetTransparencyAlphaChannel() == KErrNone) + { + Window().SetBackgroundColor(~0); + } + } + GfxTransEffect::Deregister(this); // already registered in ConstructL + GfxTransEffect::Register(this, KGfxDiscreetPopupControlUid, EFalse); +#endif +} + +// --------------------------------------------------------------------------- +// CSwtShell::IsTaskTip +// From MSwtShell +// --------------------------------------------------------------------------- +// +TBool CSwtShell::IsTaskTip() const +{ + return iIsTaskTip; +} + +// --------------------------------------------------------------------------- // CSwtShell::HandleStatusPaneSizeChange // From MEikStatusPaneObserver // --------------------------------------------------------------------------- diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtsortedlist.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtsortedlist.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtsortedlist.cpp Fri May 14 15:47:24 2010 +0300 @@ -393,7 +393,7 @@ // TInt CSwtSortedList::CountComponentControls() const { - // The filter is orphaned to force its editor to draw CAknSearchField's + // The filter is orphaned to force its editor to draw CAknSearchField's // background instead of our Shell's background. return 1; } @@ -405,7 +405,7 @@ // CCoeControl* CSwtSortedList::ComponentControl(TInt /*aIndex*/) const { - // The filter is orphaned to force its editor to draw CAknSearchField's + // The filter is orphaned to force its editor to draw CAknSearchField's // background instead of our Shell's background. return iList; } @@ -603,8 +603,8 @@ void CSwtSortedList::DoPaint(const TRect& aRect) const { CSwtListBase::DoPaint(aRect); - - // The filter is orphaned to force its editor to draw CAknSearchField's + + // The filter is orphaned to force its editor to draw CAknSearchField's // background instead of our Shell's background. Therefore drawing must // be done 'manually'. if (iSearchField) @@ -612,7 +612,7 @@ CWindowGc& gc = SystemGc(); iSearchField->SetGc(&gc); // required by effects iSearchField->DrawBackground(aRect); - iSearchField->DrawForeground(aRect); + iSearchField->DrawForeground(aRect); DrawComponentControls(*iSearchField, aRect, gc, EFalse); } } @@ -915,11 +915,11 @@ iSearchField = CAknSearchField::NewL(*this, CAknSearchField::EAdaptiveSearch, NULL, KSwtSearchFieldTextLimit); iSearchField->Editor().AddEdwinObserverL(this); - - // Orphane the filter to force its editor to draw CAknSearchField's + + // Orphane the filter to force its editor to draw CAknSearchField's // background instead of our Shell's background. iSearchField->SetParent(NULL); - + iSearchField->AddAdaptiveSearchTextObserverL(this); iSearchField->SetComponentsToInheritVisibility(ETrue); CAknFilteredTextListBoxModel* model = STATIC_CAST( diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttable.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttable.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttable.cpp Fri May 14 15:47:24 2010 +0300 @@ -1710,13 +1710,13 @@ // Now we know the highest item checkbox/image/font height. // Just add margins and set it. TInt newItemHeight(highestHeight + marginTop + marginBottom); - + MSwtUiUtils& utils = iDisplay.UiUtils(); TMargins8 padding = iDisplay.UiUtils().InlineReferencePadding(); TInt height = utils.InlineReferenceFontHeight(); height += padding.iTop + padding.iBottom; if (newItemHeight < height) newItemHeight = height; - + if (oldItemHeight != newItemHeight) { TRAP_IGNORE( @@ -2096,7 +2096,7 @@ { PackColumn(0); } - + Redraw(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttablelistbox.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttablelistbox.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttablelistbox.cpp Fri May 14 15:47:24 2010 +0300 @@ -356,7 +356,7 @@ #else EAknsCIQsnLineColorsCG6 #endif - ); + ); aGc.SetPenColor(gridLineColor); aGc.SetPenSize(TSize(lineWidth, lineWidth)); aGc.SetPenStyle(CGraphicsContext::ESolidPen); @@ -377,13 +377,13 @@ drawRect.iBr.iX = iView->ViewRect().iBr.iX; } - // Last index means also last index partially visible, - // therefore intentionally we do not substract 1 here. - TInt lastIndex = iView->TopItemIndex() - + iView->NumberOfItemsThatFitInRect(iView->ViewRect()); + // Last index means also last index partially visible, + // therefore intentionally we do not substract 1 here. + TInt lastIndex = iView->TopItemIndex() + + iView->NumberOfItemsThatFitInRect(iView->ViewRect()); TInt lastPotentialItemIndex = Min(iModel->NumberOfItems() - 1, lastIndex); - drawRect.iBr.iY = iView->ItemPos(lastPotentialItemIndex).iY - + iView->ItemSize(lastPotentialItemIndex).iHeight; + drawRect.iBr.iY = iView->ItemPos(lastPotentialItemIndex).iY + + iView->ItemSize(lastPotentialItemIndex).iHeight; if (drawRect.iBr.iY > viewRect.iBr.iY) drawRect.iBr.iY = viewRect.iBr.iY; @@ -403,7 +403,7 @@ p1.iY += itemHeight; p2.iY += itemHeight; } - + // Then draw the vertical lines // Compute the first column edge location @@ -696,14 +696,14 @@ if (deltaX != 0) iView->HScroll(deltaX); } - + iDragPos = aPointerEvent.iPosition; CEikTextListBox::HandlePointerEventL(aPointerEvent); if (aPointerEvent.iType == TPointerEvent::EButton1Up) { TInt focusIndex = CurrentItemIndex(); - + if (iListBoxFlags & EMultipleSelection) { // Multi lists @@ -718,12 +718,12 @@ } else { - View()->SelectItemL(focusIndex); + View()->SelectItemL(focusIndex); } } else { - iTable.PostSelectionEventL(KSwtStyleCheck, focusIndex); + iTable.PostSelectionEventL(KSwtStyleCheck, focusIndex); } } } @@ -1003,18 +1003,18 @@ heightOfItemArea = viewRect.Height(); } - // Last index means also last index partially visible, + // Last index means also last index partially visible, // therefore intentionally we do not substract 1 here. - TInt lastIndex = iView->TopItemIndex() - + iView->NumberOfItemsThatFitInRect(iView->ViewRect()); + TInt lastIndex = iView->TopItemIndex() + + iView->NumberOfItemsThatFitInRect(iView->ViewRect()); TInt lastPotentialItemIndex = Min(iModel->NumberOfItems() - 1, lastIndex); // Clear the unused portion of the viewing area TRect usedPortionOfViewRect(viewRect.iTl.iX, iView->ItemPos(iView->TopItemIndex()).iY, viewRect.iBr.iX, iView->ItemPos(lastPotentialItemIndex).iY + iView->ItemSize(lastPotentialItemIndex).iHeight); - - // This is needed as the horizontal scrollbar is transparent. + + // This is needed as the horizontal scrollbar is transparent. if (usedPortionOfViewRect.iBr.iY > viewRect.iBr.iY) usedPortionOfViewRect.iBr.iY = viewRect.iBr.iY; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttasktip.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttasktip.cpp Mon May 03 12:27:20 2010 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,223 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Nokia Corporation and/or its subsidiary(-ies). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Nokia Corporation - S60 implementation - *******************************************************************************/ - - -#include -#include "swttasktip.h" - - -const TInt KVariationFullScreen = 3; -const TInt KVariationWindow = 0; -const TInt KVariationWindowBarOrTextOnly = 1; -const TInt KVariationBar = 0; -const TInt KVariationBarOnly = 1; -const TInt KVariationLabel = 0; -const TInt KVariationLabelOnly = 1; - - -// ======== MEMBER FUNCTIONS ======== - - -// --------------------------------------------------------------------------- -// CSwtTaskTip::NewL -// --------------------------------------------------------------------------- -// -CSwtTaskTip* CSwtTaskTip::NewL(MSwtDisplay& aDisplay, TSwtPeer aPeer, TInt aStyle) -{ - CSwtTaskTip* self = new(ELeave) CSwtTaskTip(aDisplay, aPeer, aStyle); - CleanupStack::PushL(self); - self->ConstructL(); - CleanupStack::Pop(self); - return self; -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::Dispose -// From MSwtTaskTip -// --------------------------------------------------------------------------- -// -TSwtPeer CSwtTaskTip::Dispose() -{ - TSwtPeer peer(JavaPeer()); - delete this; - return peer; -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::JavaPeer -// From MSwtTaskTip -// --------------------------------------------------------------------------- -// -TSwtPeer CSwtTaskTip::JavaPeer() const -{ - return iPeer; -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::GetBarDefaultBounds -// From MSwtTaskTip -// --------------------------------------------------------------------------- -// -TRect CSwtTaskTip::GetBarDefaultBounds(TBool aHasText) const -{ - if (aHasText - && (((iStyle & KSwtStyleIndeterminate) != 0) - || ((iStyle & KSwtStyleSmooth) != 0))) - { - return iRectBar; - } - else - { - return iRectBarOnly; - } -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::GetLabelDefaultBounds -// From MSwtTaskTip -// --------------------------------------------------------------------------- -// -TRect CSwtTaskTip::GetLabelDefaultBounds(TBool aHasText) const -{ - if (aHasText - && (((iStyle & KSwtStyleIndeterminate) != 0) - || ((iStyle & KSwtStyleSmooth) != 0))) - { - return iRectLabel; - } - else - { - return iRectLabelOnly; - } -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::GetShellDefaultBounds -// From MSwtTaskTip -// --------------------------------------------------------------------------- -// -TRect CSwtTaskTip::GetShellDefaultBounds(TBool aHasText) const -{ - if (aHasText - && (((iStyle & KSwtStyleIndeterminate) != 0) - || ((iStyle & KSwtStyleSmooth) != 0))) - { - return iRectShell; - } - else - { - return iRectShellBarOrLabelOnly; - } -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::OfferResourceChangeL -// From MSwtResourceChangeObserver -// --------------------------------------------------------------------------- -// -void CSwtTaskTip::OfferResourceChangeL(TInt aType) -{ - if (aType == KEikDynamicLayoutVariantSwitch) - { - UpdateLayout(); - } -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::CSwtTaskTip -// --------------------------------------------------------------------------- -// -CSwtTaskTip::CSwtTaskTip(MSwtDisplay& aDisplay, TSwtPeer aPeer, TInt aStyle) - : iDisplay(aDisplay) - , iPeer(aPeer) - , iStyle(aStyle) -{ - iRectShell = TRect(TRect::EUninitialized); - iRectShellBarOrLabelOnly = TRect(TRect::EUninitialized); - iRectLabel = TRect(TRect::EUninitialized); - iRectLabelOnly = TRect(TRect::EUninitialized); - iRectBar = TRect(TRect::EUninitialized); - iRectBarOnly = TRect(TRect::EUninitialized); -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::CSwtTaskTip -// --------------------------------------------------------------------------- -// -CSwtTaskTip::~CSwtTaskTip() -{ - iDisplay.RemoveResourceChangeObserver(this); -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::ConstructL -// --------------------------------------------------------------------------- -// -void CSwtTaskTip::ConstructL() -{ - iDisplay.AddResourceChangeObserverL(this); - UpdateLayout(); -} - -// --------------------------------------------------------------------------- -// CSwtTaskTip::UpdateLayout -// --------------------------------------------------------------------------- -// -void CSwtTaskTip::UpdateLayout() -{ - TRect screenRect; - AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EScreen, screenRect); - TAknLayoutRect layoutMainPane = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EMainEswtPane, - screenRect, - KVariationFullScreen); - TRect mainPaneRect = layoutMainPane.Rect(); - - // Shell bounds - TAknLayoutRect layoutShell = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EPopupEswtTasktipWindow, - mainPaneRect, - KVariationWindow); - iRectShell = layoutShell.Rect(); - layoutShell = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EPopupEswtTasktipWindow, - mainPaneRect, - KVariationWindowBarOrTextOnly); - iRectShellBarOrLabelOnly = layoutShell.Rect(); - - // Label bounds - TAknLayoutText layoutLabel = CSwtLafFacade::GetLayoutText( - CSwtLafFacade::EPopupEswtTasktipWindowT1, - iRectShell, - KVariationLabel); - iRectLabel = layoutLabel.TextRect(); - layoutLabel = CSwtLafFacade::GetLayoutText( - CSwtLafFacade::EPopupEswtTasktipWindowT1, - iRectShellBarOrLabelOnly, - KVariationLabelOnly); - iRectLabelOnly = layoutLabel.TextRect(); - - // Progress bar bounds - if (((iStyle & KSwtStyleIndeterminate) != 0) - || ((iStyle & KSwtStyleSmooth) != 0)) - { - TAknLayoutRect layoutBar = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EWaitBarPaneCp71, - iRectShell, - KVariationBar); - iRectBar = layoutBar.Rect(); - layoutBar = CSwtLafFacade::GetLayoutRect( - CSwtLafFacade::EWaitBarPaneCp71, - iRectShellBarOrLabelOnly, - KVariationBarOnly); - iRectBarOnly = layoutBar.Rect(); - } -} diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttext.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttext.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swttext.cpp Fri May 14 15:47:24 2010 +0300 @@ -614,7 +614,7 @@ { return; } - + // Update editor's visibility, otherwise text will be drawn // when performing clipboard operations on invisible control. const TBool visible = GetVisibleRecursively(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtuiutils.cpp --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtuiutils.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/native/src/swtuiutils.cpp Fri May 14 15:47:24 2010 +0300 @@ -35,6 +35,7 @@ #include "swtdisplaybase.h" _LIT(KSeparator, "-"); +const TInt KVariationFullScreen = 3; // ======== MEMBER FUNCTIONS ======== @@ -676,15 +677,15 @@ &appUi, NULL, CEikButtonGroupContainer::EAddToStack); - + // The Cba will be made visible by the firtst top shell to show // or by the first child Shell with commands to show. iCba->MakeVisible(EFalse); - + #ifdef RD_JAVA_S60_RELEASE_9_2 static_cast(iCba->ButtonGroup())->EnableItemSpecificSoftkey(EFalse); #endif - + const TSize screenSize = iDisplay.CoeEnv()->ScreenDevice()->SizeInPixels(); iCba->SetBoundingRect(TRect(screenSize)); @@ -744,7 +745,7 @@ // Bring back on screen and activate the new Shell. MoveToEndOfQueue(*iActiveShell); - + TRAP_IGNORE(UpdateStatusPaneL()); iActiveShell->Control()->ShowSilently(); @@ -753,7 +754,7 @@ // Remember the new top most Shell for Shell activability changes. iLastTopMostShell = TopMostTopShell(); - + SetShellFade(iActiveShell, ETrue); } @@ -865,7 +866,7 @@ { if (!iStatusPane) return; - + HideIndicator(EEikStatusPaneUidSignal); HideIndicator(EEikStatusPaneUidBattery); HideIndicator(EEikStatusPaneUidIndic); @@ -1134,7 +1135,7 @@ // CSwtUiUtils::UpdateStatusPaneL // From MSwtUiUtils // Calls to this should be kept to a severe minimum! This function is not anymore -// responsible of resizing the topmost shells since Shell's bounds should not +// responsible of resizing the topmost shells since Shell's bounds should not // depend on the current status pane height(See CSwtShell::DefaultBounds()). // --------------------------------------------------------------------------- // @@ -1273,22 +1274,22 @@ iStatusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_SMALL_WITH_SIGNAL_PANE); } iStatusPane->MakeVisible(ETrue); - + java::ui::CoreUiAvkonAppUi* appUi = java::ui::CoreUiAvkonEswt::getInstance().getJavaUiAppUi(); if (appUi && appUi->hidesIndicators()) { HideIndicators(); } - + // The above relies on DrawDeferred which is too slow for some cases. - // For instance, the pane must draw immediately when the app draws the + // For instance, the pane must draw immediately when the app draws the // first time otherwise the startup screenshot will miss the pane. iStatusPane->DrawNow(); } - + // This will cause HandleStatusPaneSizeChange notifications again iStatusPane->SetObserver(this); - + // Shells are trusted to have the correct size already. } @@ -1305,9 +1306,9 @@ { return; } - + ASSERT(!iActiveShell); - + // Update flag iFocusLost = EFalse; TBool getFocused(EFalse); @@ -1316,7 +1317,7 @@ getFocused = iNextFocusedControl->SetSwtFocus(KSwtFocusByForce); iNextFocusedControl = NULL; } - + if (getFocused) { // do nothing @@ -1524,7 +1525,7 @@ iInlineFont = NULL; iInlineFontHeight = -1; iInlinePadding.iTop = -1; - + // Sometimes CBA bounds are incorrect at this point in the case we have // a dialog shell active. As a result Shell gets wrong size. // Set the bounds here to make sure they are always correct. @@ -1613,6 +1614,11 @@ return; } iCba->MakeVisible(aVisible); + +#ifdef RD_JAVA_S60_RELEASE_9_2 + // To enable clock pane in landscape after MIDlet was started + iCba->SetBoundingRect(TRect(0, 0, 0, 0)); +#endif // RD_JAVA_S60_RELEASE_9_2 } // --------------------------------------------------------------------------- @@ -1654,6 +1660,26 @@ // From MSwtUiUtils // --------------------------------------------------------------------------- // +TRect CSwtUiUtils::TaskTipRect() const +{ + TRect screenRect; + AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EScreen, screenRect); + TAknLayoutRect layoutMainPane = CSwtLafFacade::GetLayoutRect( + CSwtLafFacade::EMainEswtPane, + screenRect, + KVariationFullScreen); + TRect mainPaneRect = layoutMainPane.Rect(); + TAknLayoutRect layoutShell = CSwtLafFacade::GetLayoutRect( + CSwtLafFacade::EPopupEswtTasktipWindow, + mainPaneRect); + return layoutShell.Rect(); +} + +// --------------------------------------------------------------------------- +// CSwtUiUtils::HandleFreeRamEventL +// From MSwtUiUtils +// --------------------------------------------------------------------------- +// void CSwtUiUtils::HandleFreeRamEventL(TInt aEventType) { const TInt count = iShells.Count(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/TaskTip.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/TaskTip.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/TaskTip.java Fri May 14 15:47:24 2010 +0300 @@ -18,6 +18,8 @@ import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; @@ -76,8 +78,6 @@ */ public class TaskTip extends Widget { - private int handle = 0; - private Shell tasktipShell = null; private Label tasktipLabel = null; private ProgressBar tasktipBar = null; @@ -89,8 +89,6 @@ private Shell topShell = null; private ControlListener topShellListener = null; - private boolean hasText = false; - /** * * Constructs a TaskTip with plain text style. @@ -151,13 +149,22 @@ SWT.error(SWT.ERROR_NULL_ARGUMENT); } - handle = OS.TaskTip_New(this, getStyle()); - tasktipShell = new Shell(shell, SWT.NO_FOCUS|SWT.ON_TOP|SWT.NO_TRIM); - tasktipLabel = new Label(tasktipShell, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginBottom = 0; + layout.marginTop = 0; + layout.marginLeft = 0; + layout.marginRight = 0; + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.verticalSpacing = 1; + layout.horizontalSpacing = 0; + tasktipShell.setLayout(layout); + tasktipShell.internal_setTaskTip(); if (getStyle() != SWT.NONE) { tasktipBar = new ProgressBar(tasktipShell, getStyle()); + tasktipBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); } // If the parent shell is disposed task tip is disposed also @@ -351,18 +358,25 @@ public void setText(String string) { checkWidget(); - boolean hasTextPrev = hasText; + boolean prevLabel = tasktipLabel != null; if (string == null) { - tasktipLabel.setText(""); - hasText = false; + if (tasktipLabel != null) + { + tasktipLabel.dispose(); + tasktipLabel = null; + } } else { + if (tasktipLabel == null) + { + tasktipLabel = new Label(tasktipShell, SWT.NONE); + tasktipLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); + } tasktipLabel.setText(removeLine(string)); - hasText = true; } - if (hasTextPrev != hasText) + if (prevLabel != (tasktipLabel != null)) { rebound(); } @@ -402,16 +416,6 @@ tasktipShell.setVisible(visible); } - protected void internal_releaseHandle() - { - if (handle != 0) - { - OS.TaskTip_Dispose(handle); - handle = 0; - } - super.internal_releaseHandle(); - } - protected void internal_releaseResources() { if (tasktipShell != null) @@ -428,31 +432,14 @@ private void rebound() { - int heightDifference = 0; - Rectangle labelRect = new Rectangle(0,0,0,0); - Rectangle shellRect = OS.TaskTip_GetShellDefaultBounds(handle, hasText); - if (hasText) - { - labelRect = OS.TaskTip_GetLabelDefaultBounds(handle, hasText); - labelRect.x -= shellRect.x; - labelRect.y -= shellRect.y; - Point labelPrefSize = tasktipLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT); - if (labelPrefSize.y > labelRect.height) - { - heightDifference = labelPrefSize.y - labelRect.height; - labelRect.height = labelPrefSize.y; - } - } - shellRect.height += heightDifference; + Rectangle shellRect = OS.TaskTip_DefaultBounds(); + + Point idealSize = tasktipShell.computeSize(shellRect.width, SWT.DEFAULT); + if (shellRect.height < idealSize.y) + shellRect.height = idealSize.y; + tasktipShell.setBounds(shellRect); - tasktipLabel.setBounds(labelRect); - if (tasktipBar != null) - { - Rectangle barRect = OS.TaskTip_GetBarDefaultBounds(handle, hasText); - barRect.x -= shellRect.x; - barRect.y -= shellRect.y; - tasktipBar.setBounds(barRect); - } + tasktipShell.layout(); } private String removeLine(String aString) diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/internal/OS.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/internal/OS.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/ercp/swt/mobile/internal/OS.java Fri May 14 15:47:24 2010 +0300 @@ -210,11 +210,7 @@ /* * Class TaskTip */ - public static final native int TaskTip_New(TaskTip peer, int style); - public static final native void TaskTip_Dispose(int handle); - public static final native Rectangle TaskTip_GetBarDefaultBounds(int handle, boolean hasText); - public static final native Rectangle TaskTip_GetLabelDefaultBounds(int handle, boolean hasText); - public static final native Rectangle TaskTip_GetShellDefaultBounds(int handle, boolean hasText); + public static final native Rectangle TaskTip_DefaultBounds(); /* * Class TextExtension diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/internal/symbian/OS.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/internal/symbian/OS.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/internal/symbian/OS.java Fri May 14 15:47:24 2010 +0300 @@ -21,7 +21,7 @@ /** * @brief This is the place where all native functions are located. * - * This class is not supposed to be instanciated as it only contains static + * This class is not supposed to be instantiated as it only contains static * methods. Warning: the content of this class is platform dependent. */ public class OS @@ -32,6 +32,12 @@ { Library.loadLibrary("eswt"); } + + public static final int WS_SYMBIAN_S60_50 = 1; + public static final int WS_SYMBIAN_S60_92 = 2; + + // Underlying window server. + public static final int windowServer = windowServer(); /* * Class Device @@ -301,6 +307,7 @@ public static final native void Shell_SetImeInputMode(int shellHandle, int mode); public static final native Rectangle Shell_GetDefaultBounds(int shellHandle); public static final native void Shell_SetAsyncPainting(int shellHandle, boolean status); + public static final native void Shell_SetTaskTip(int shellHandle); /* * Class Label @@ -481,4 +488,8 @@ public static final native int ImageDataLoader_GetLogicalScreenHeight(int handle); public static final native int ImageDataLoader_GetLogicalScreenWidth(int handle); + /* + * General + */ + private static final native int windowServer(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/FontDialog.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/FontDialog.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/FontDialog.java Fri May 14 15:47:24 2010 +0300 @@ -14,8 +14,6 @@ import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Shell; @@ -28,14 +26,11 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.ercp.swt.expanded.internal.OS; -import org.eclipse.ercp.swt.mobile.Command; -import java.util.Vector; /** @@ -208,7 +203,13 @@ flags |= SWT.TITLE; shell = new Shell(getParent(), flags); shell.setText(title); - shell.open(); + + if (org.eclipse.swt.internal.symbian.OS.windowServer + < org.eclipse.swt.internal.symbian.OS.WS_SYMBIAN_S60_92) + { + // On 5.0 the modal Shell needs to be made visible before Combo is created. + shell.open(); + } // Listen to skin and resolution changes settingsListener = new Listener() @@ -325,6 +326,12 @@ } shell.setBounds(rect); + + if (org.eclipse.swt.internal.symbian.OS.windowServer + >= org.eclipse.swt.internal.symbian.OS.WS_SYMBIAN_S60_92) + { + shell.open(); + } // Block till submited isOpen = true; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Label.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Label.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Label.java Fri May 14 15:47:24 2010 +0300 @@ -115,18 +115,6 @@ } /** - * Disable SetMenu method because label is a non-focusable widget. - * - */ - /* - public void setMenu (Menu menu) { - checkWidget (); - } - */ - - - - /** * Returns a value which describes the position of the * text or image in the receiver. The value will be one of * LEFT, RIGHT or CENTER diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Shell.java --- a/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Shell.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_akn/org.eclipse.ercp.swt.s60/src/org/eclipse/swt/widgets/Shell.java Fri May 14 15:47:24 2010 +0300 @@ -104,8 +104,6 @@ { private int shellHandle; - // Widgets registered with this Shell - private Vector widgets = new Vector(); private Vector asyncPaintControls = new Vector(); /** @@ -396,12 +394,26 @@ return size; } + /** + * IMPORTANT: This method is not part of the public + * API for Shell. It is marked public only so that it + * can be shared within the packages provided by SWT. It is not + * available on all platforms, and should never be called from + * application code. + */ protected void internal_setShellHandle(int shellHandle) { this.shellHandle = shellHandle; internal_setDecorationsHandle(OS.Shell_DecorationsHandle(shellHandle)); } + /** + * IMPORTANT: This method is not part of the public + * API for Shell. It is marked public only so that it + * can be shared within the packages provided by SWT. It is not + * available on all platforms, and should never be called from + * application code. + */ public void internal_checkShell() { checkWidget(); @@ -550,15 +562,6 @@ protected void internal_releaseResources() { - int size = widgets.size(); - for (int i=0; iIMPORTANT: This method is not part of the public + * API for Shell. It is marked public only so that it + * can be shared within the packages provided by SWT. It is not + * available on all platforms, and should never be called from + * application code. + */ public int internal_getShellHandle() { return shellHandle; } - public void internal_registerWidget(Widget widget) - { - widgets.addElement(widget); - } - - public void internal_unregisterWidget(Widget widget) - { - widgets.removeElement(widget); - } - + /** + * IMPORTANT: This method is not part of the public + * API for Shell. It is marked public only so that it + * can be shared within the packages provided by SWT. It is not + * available on all platforms, and should never be called from + * application code. + */ public Rectangle internal_getDefaultBounds() { return OS.Shell_GetDefaultBounds(shellHandle); @@ -712,6 +719,18 @@ return OS.Control_GetVisible(this.display.handle, handle); } + /** + * IMPORTANT: This method is not part of the public + * API for Shell. It is marked public only so that it + * can be shared within the packages provided by SWT. It is not + * available on all platforms, and should never be called from + * application code. + */ + public void internal_setTaskTip() + { + OS.Shell_SetTaskTip(shellHandle); + } + void setAsyncPainting(Control child, boolean status) { if (status) diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/build/build.xml --- a/javauis/eswt_qt/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -27,7 +27,7 @@ - + @@ -35,7 +35,8 @@ + org.eclipse.swt.internal.qt.s60.OS, + org.eclipse.swt.internal.extension.OS"/> diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/build/eswtqt.pro --- a/javauis/eswt_qt/build/eswtqt.pro Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/build/eswtqt.pro Fri May 14 15:47:24 2010 +0300 @@ -22,6 +22,8 @@ gui \ webkit +symbian: LIBS += -lhal -lws32 -lgdi + include(../org.eclipse.swt/Eclipse_SWT_PI/qt/library/eswt_widgets.pri) include(../org.eclipse.swt/Eclipse_SWT_PI/qt/library/graphics/graphics.pri) diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/DisplayExtension.java --- a/javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/DisplayExtension.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/DisplayExtension.java Fri May 14 15:47:24 2010 +0300 @@ -11,11 +11,44 @@ package org.eclipse.swt.internal.extension; +import org.eclipse.swt.internal.qt.OS; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Internal_PackageSupport; public final class DisplayExtension extends Display { +private static final class VibraRunnable implements Runnable { + private final int duration; + private final Display display; + boolean result; + private VibraRunnable(int duration, Display display) { + this.duration = duration; + this.display = display; + } + + public void run() { + result= OS.MobileDevice_vibration( + Internal_PackageSupport.initializeMobileDevice(display),duration); + + } + } +private static final class FlashBacklightsRunnable implements Runnable { + private final Display display; + private final int duration; + boolean result; + + private FlashBacklightsRunnable(Display display, int duration) { + this.display = display; + this.duration = duration; + } + + public void run() { + result = OS.MobileDevice_flashLights( + Internal_PackageSupport.initializeMobileDevice( + display),duration); + } + } + /* Image types, same values as MIDP */ public static final int LIST_ELEMENT = 1; public static final int CHOICE_GROUP_ELEMENT = 2; @@ -50,7 +83,39 @@ public static Display getDisplayInstance() { return Internal_PackageSupport.getDisplayInstance(); } - +/** + * Flashes devices backlight. + * + * @param duration Duration in milliseconds. + * @return false if no flashing happened because MIDlet was in background or + * feature is not supported. + */ +public static boolean flashLights( final int duration ){ + final Display display = getDisplayInstance(); + if (display == null || display.isDisposed() ) return false; + FlashBacklightsRunnable runnable = new FlashBacklightsRunnable(display, duration); + display.syncExec(runnable); + return runnable.result; +} +/** + * Vibrates device + * + * @param duration Duration in milliseconds. + * @return false if no vibration happened because MIDlet was in background + * or feature is not supported. + */ +public static boolean startVibra(final int duration) { + final Display display = getDisplayInstance(); + if (display == null || display.isDisposed() ) return false; + VibraRunnable runnable = new VibraRunnable(duration, display); + display.syncExec(runnable); + return runnable.result; +} +/** + * + * @param imageType + * @return + */ private static int getBestImageSize(int imageType) { switch (imageType) { case LIST_ELEMENT: @@ -62,4 +127,6 @@ return -1; } } + + } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/NetworkStatus.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/NetworkStatus.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,423 @@ +/******************************************************************************* + * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Nokia Corporation - initial implementation + *******************************************************************************/ +package org.eclipse.swt.internal.extension; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Internal_PackageSupport; +import org.eclipse.swt.widgets.Listener; + +/** + * This class provides notifications that can be used to determine which type of + * network connections are active at any given moment. + */ +public final class NetworkStatus { + + /** + * A notification state flag that is raised when there are any active + * Ethernet data connections. + */ + public static final int DATA_ETHERNET = 0x00000001; + + /** + * A notification state flag that is raised when there are any active WLAN + * data connections. + */ + public static final int DATA_WLAN = 0x00000002; + + /** + * A notification state flag that is raised when there are any active CSD, + * GPRS, HSCSD, EDGE or cdmaOne data connections. + */ + public static final int DATA_2G = 0x00000004; + + /** + * A notification state flag that is raised when there are any active CDMA + * data connections. + */ + public static final int DATA_CDMA2000 = 0x00000008; + + /** + * A notification state flag that is raised when there are any active + * W-CDMA/UMTS data connections. + */ + public static final int DATA_WCDMA = 0x00000010; + + /** + * A notification state flag that is raised when there are any active High + * Speed Packet Access data connections. + */ + public static final int DATA_HSPA = 0x00000020; + + /** + * A notification state flag that is raised when there are any active + * Bluetooth data connections. + */ + public static final int DATA_BLUETOOTH = 0x00000040; + + /** + * A notification state flag that is raised when there are any active WiMAX + * data connections. + */ + public static final int DATA_WIMAX = 0x00000080; + + /** + * A notification state flag that is raised when there are any active voice + * calls. + */ + public static final int VOICE_CALL = 0x00000100; + + // This flag is set for any other active types than the ones above. + // No events are sent for this type of active connections. + private static final int UNKNOWN = 0x80000000; + + // The notified states of the connection types + private static int notifiedStates; + + // Singleton instance + private static NetworkStatus instance; + + // References to the listeners of the clients + private static NetworkStatusListener[] listeners; + + // QNetworkConfigurationManager and XQCallInfo handles. + // Can be 0 if required native parts not compiled in. + private static int qNetworkConfigurationManagerHandle; + private static int xqCallInfoHandle; + + // QNetworkConfiguration objects for active connections + private static int activeConfigHandles[]; + + // The dispose listener that is added to Display + private static Listener disposeListener; + + private NetworkStatus() { + xqCallInfoHandle = OS.XQCallInfo_create(); + qNetworkConfigurationManagerHandle = OS.QNetworkConfigurationManager_new(0); + hookEvents(); + addDisposeListener(); + handleNetworkConfigurationChange(); + handleCallInformationChanged(); + } + + private static void addDisposeListener() { + Display display = Internal_PackageSupport.getDisplayInstance(); + disposeListener = new Listener() { + public void handleEvent(Event event) { + destroy(); + } + }; + display.addListener(SWT.Dispose, disposeListener); + } + + private static void removeDisposeListener() { + if(disposeListener != null) { + Display display = Internal_PackageSupport.getDisplayInstance(); + if(display != null && !display.isDisposed()) { + display.removeListener(SWT.Dispose, disposeListener); + disposeListener = null; + } + } + } + + private static void checkThread() { + Display display = Internal_PackageSupport.getDisplayInstance(); + if(display == null) { + throw new RuntimeException("Display doesn't exist"); + } + if(!display.getThread().equals(Thread.currentThread())) { + throw new RuntimeException("Not the UI thread"); + } + } + + private static NetworkStatus instance() { + if(instance == null) { + instance = new NetworkStatus(); + } + return instance; + } + + private static boolean hasListeners() { + if(listeners == null) return false; + for(int i = 0; i < listeners.length; ++i) { + if(listeners[i] != null) { + return true; + } + } + return false; + } + + private static void destroy() { + destroyActiveConfigs(); + if(qNetworkConfigurationManagerHandle != 0) { + org.eclipse.swt.internal.qt.QObjectDeleteWrapper.deleteSafely( + qNetworkConfigurationManagerHandle); + qNetworkConfigurationManagerHandle = 0; + } + if(xqCallInfoHandle != 0) { + org.eclipse.swt.internal.qt.QObjectDeleteWrapper.deleteSafely( + xqCallInfoHandle); + xqCallInfoHandle = 0; + } + listeners = null; + instance = null; + } + + /** + * Adds the listener to the collection of listeners who will be notified of + * the network status changes. Can only be called by the eSWT UI thread. If + * there are active connections at the time of adding a listener the + * listener will be notified. Adding the first listener will automatically + * allocate the required native resources and removing the last listener + * will automatically free them. This class will hold a strong reference to + * the listener object preventing it from getting garbage collected until + * the listener is removed. + * + * @param listener + * the listener which should be notified when the event occurs + * + * @exception IllegalArgumentException + *
    + *
  • ERROR_NULL_ARGUMENT - if the listener is null
  • + *
+ * + * @exception RuntimeException + *
    + *
  • If eSWT Display doesn't exist
  • + *
  • If called in a non-UI thread
  • + *
+ * + * @see NetworkStatusListener + * @see #removeListener(NetworkStatusListener) + */ + public static void addListener(NetworkStatusListener listener) { + if (listener == null) throw new IllegalArgumentException(); + checkThread(); + instance(); + hook(listener); + if(notifiedStates != 0) { + final NetworkStatusListener asyncNofityListener = listener; + final int asyncNotifyStates = notifiedStates; + Internal_PackageSupport.getDisplayInstance().asyncExec(new Runnable() { + public void run() { + asyncNofityListener.stateChanged(asyncNotifyStates); + } + }); + } + } + + /** + * Removes the listener from the collection of listeners who will be + * notified of the network status changes. Can only be called by the eSWT UI + * thread. Removing the listener will release the reference held by this + * class to the listener object. When all the listeners have been removed + * the native resources allocated by this class are no longer needed and are + * automatically freed. + * + * @param listener + * the listener which should no longer be notified when the event + * occurs + * + * @exception IllegalArgumentException + *
    + *
  • ERROR_NULL_ARGUMENT - if the listener is null
  • + *
+ * + * @exception RuntimeException + *
    + *
  • If eSWT Display doesn't exist
  • + *
  • If called in a non-UI thread
  • + *
+ * + * @see NetworkStatusListener + * @see #addListener(NetworkStatusListener) + */ + public static void removeListener(NetworkStatusListener listener) { + if (listener == null) throw new IllegalArgumentException(); + checkThread(); + unhook(listener); + if(!hasListeners()) { + destroy(); + removeDisposeListener(); + } + } + + // Connect the signals + private void hookEvents() { + // Packet data connections + if(qNetworkConfigurationManagerHandle != 0) { + int signalProxy = org.eclipse.swt.internal.qt.OS.SignalHandler_new( + qNetworkConfigurationManagerHandle, this, OS.QSIGNAL_NETWORKCONFIGURATIONCHANGED); + org.eclipse.swt.internal.qt.OS.QObject_connectOrThrow( + qNetworkConfigurationManagerHandle, + "configurationAdded(const QNetworkConfiguration&)", + signalProxy, "widgetSignal()", + org.eclipse.swt.internal.qt.OS.QT_AUTOCONNECTION); + org.eclipse.swt.internal.qt.OS.QObject_connectOrThrow( + qNetworkConfigurationManagerHandle, + "configurationChanged(const QNetworkConfiguration&)", + signalProxy, "widgetSignal()", + org.eclipse.swt.internal.qt.OS.QT_AUTOCONNECTION); + org.eclipse.swt.internal.qt.OS.QObject_connectOrThrow( + qNetworkConfigurationManagerHandle, + "configurationRemoved(const QNetworkConfiguration&)", + signalProxy, "widgetSignal()", + org.eclipse.swt.internal.qt.OS.QT_AUTOCONNECTION); + } + + // Voice calls + if(xqCallInfoHandle != 0) { + int signalProxy = org.eclipse.swt.internal.qt.OS.SignalHandler_new( + xqCallInfoHandle, this, OS.QSIGNAL_CALLINFORMATIONCHANGED); + org.eclipse.swt.internal.qt.OS.QObject_connectOrThrow( + xqCallInfoHandle, + "callInformationChanged()", + signalProxy, "widgetSignal()", + org.eclipse.swt.internal.qt.OS.QT_AUTOCONNECTION); + } + } + + // Connected signals come here + boolean eventProcess(int widgetHandle, int eventType, int time, + int arg1, int arg2, int arg3, int arg4, int arg5, String arg6) { + switch(eventType) { + case OS.QSIGNAL_NETWORKCONFIGURATIONCHANGED: + handleNetworkConfigurationChange(); + break; + case OS.QSIGNAL_CALLINFORMATIONCHANGED: + handleCallInformationChanged(); + break; + default: + break; + } + return false; + } + + private static void destroyActiveConfigs() { + // Free the QNetworkConfiguration objects + if(activeConfigHandles != null) { + for(int i = 0; i < activeConfigHandles.length; ++i) { + OS.QNetworkConfiguration_delete(activeConfigHandles[i]); + activeConfigHandles[i] = 0; + } + activeConfigHandles = null; + } + } + + private static void updateActiveConfigs() { + destroyActiveConfigs(); + // Get all the currently active configurations + if(qNetworkConfigurationManagerHandle != 0) { + activeConfigHandles = OS.QNetworkConfigurationManager_allConfigurations( + qNetworkConfigurationManagerHandle, OS.QNETWORKCONFIGURATION_ACTIVE); + } + } + + private static void handleNetworkConfigurationChange() { + updateActiveConfigs(); + + // Find out the new states of all connection types + int newStates = 0; + newStates |= (notifiedStates & VOICE_CALL); // Voice call state didn't change + for(int i = 0; i < activeConfigHandles.length; ++i) { + int activeFlag = bearerNameToConnectionFlag( + OS.QNetworkConfiguration_bearerName(activeConfigHandles[i])); + if(activeFlag == UNKNOWN) continue; + newStates |= activeFlag; + } + + notifyChangedStates(newStates); + } + + private static void handleCallInformationChanged() { + if(xqCallInfoHandle != 0) { + int newStates = notifiedStates; + if(OS.XQCallInfo_swt_hasCalls(xqCallInfoHandle)) { + newStates |= VOICE_CALL; + } else { + newStates &= ~VOICE_CALL; + } + + notifyChangedStates(newStates); + } + } + + private static void notifyChangedStates(int newStates) { + if(newStates != notifiedStates) { + notifyListeners(newStates); + } + } + + private static void notifyListeners(int state) { + if(listeners != null) { + for(int i = 0; i < listeners.length; ++i) { + if(listeners[i] == null) break; + listeners[i].stateChanged(state); + } + } + notifiedStates = state; + } + + private static int bearerNameToConnectionFlag(String bearerName) { + if(bearerName.equalsIgnoreCase("WCDMA")) { + return DATA_WCDMA; + } else if(bearerName.equalsIgnoreCase("HSPA")) { + return DATA_HSPA; + } else if(bearerName.equalsIgnoreCase("2G")) { + return DATA_2G; + } else if(bearerName.equalsIgnoreCase("WLAN")) { + return DATA_WLAN; + } else if(bearerName.equalsIgnoreCase("Bluetooth")) { + return DATA_BLUETOOTH; + } else if(bearerName.equalsIgnoreCase("CDMA2000")) { + return DATA_CDMA2000; + } else if(bearerName.equalsIgnoreCase("WiMAX")) { + return DATA_WIMAX; + } else if(bearerName.equalsIgnoreCase("Ethernet")) { + return DATA_ETHERNET; + } + return UNKNOWN; + } + + private static void hook(NetworkStatusListener listener) { + if (listeners == null) listeners = new NetworkStatusListener[1]; + int length = listeners.length, index = length - 1; + while (index >= 0) { + if (listeners [index] != null) break; + --index; + } + index++; + if (index == length) { + NetworkStatusListener[] newListeners = new NetworkStatusListener[length + 1]; + System.arraycopy (listeners, 0, newListeners, 0, length); + listeners = newListeners; + } + listeners [index] = listener; + } + + private static void unhook(NetworkStatusListener listener) { + if (listeners == null) return; + for (int i = 0; i < listeners.length; i++) { + if (listeners [i] == listener) { + remove (i); + return; + } + } + } + + private static void remove (int index) { + int end = listeners.length - 1; + System.arraycopy (listeners, index + 1, listeners, index, end - index); + index = end; + listeners [index] = null; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/NetworkStatusListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/NetworkStatusListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Nokia Corporation - initial implementation + *******************************************************************************/ +package org.eclipse.swt.internal.extension; + +/** + * A listener interface used in connection with the class + * NetworkStatus. + */ +public interface NetworkStatusListener { + /** + * Called by the class NetworkStatus in the UI thread to + * provide the current state of the network connections. + * + * @param newStateFlags + * Combination of flags representing the currently active network + * connections. The flags are defined in the class + * NetworkStatus. + * @see NetworkStatus + */ + public void stateChanged(int newStateFlags); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/OS.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/eswt_qt/com.nokia.swt.extensions/extensions/org/eclipse/swt/internal/extension/OS.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Nokia Corporation - initial implementation + *******************************************************************************/ +package org.eclipse.swt.internal.extension; + +public final class OS { + public static final int QSIGNAL_NETWORKCONFIGURATIONCHANGED = 1; + public static final int QSIGNAL_CALLINFORMATIONCHANGED = 2; + + public static final int QNETWORKCONFIGURATION_ACTIVE = 0x000000e; + + // + // QNetworkConfigurationManager + // + public static final native int QNetworkConfigurationManager_new(int parent); + public static final native int[] QNetworkConfigurationManager_allConfigurations(int handle, int filter); + + // + // QNetworkConfiguration + // + public static final native String QNetworkConfiguration_bearerName(int handle); + public static final native void QNetworkConfiguration_delete(int handle); + + // + // XQCallInfo + // + public static final native int XQCallInfo_create(); + public static final native boolean XQCallInfo_swt_hasCalls(int handle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.linux.arm.se/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.linux.arm.se/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.linux.arm.se/build.xml Fri May 14 15:47:24 2010 +0300 @@ -218,6 +218,7 @@ + diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.me/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.me/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.me/build.xml Fri May 14 15:47:24 2010 +0300 @@ -233,6 +233,7 @@ + diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.se/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.se/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.linux.x86.se/build.xml Fri May 14 15:47:24 2010 +0300 @@ -212,6 +212,7 @@ + @@ -336,6 +337,7 @@ +
diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.s60.armv5/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.s60.armv5/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.s60.armv5/build.xml Fri May 14 15:47:24 2010 +0300 @@ -249,8 +249,9 @@ - + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.s60.winscw/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.s60.winscw/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.s60.winscw/build.xml Fri May 14 15:47:24 2010 +0300 @@ -255,6 +255,7 @@ + diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt.qt.win32.x86.internal/build.xml --- a/javauis/eswt_qt/org.eclipse.swt.qt.win32.x86.internal/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt.qt.win32.x86.internal/build.xml Fri May 14 15:47:24 2010 +0300 @@ -211,6 +211,7 @@ + diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/MultiPageDialog.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/MultiPageDialog.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/MultiPageDialog.java Fri May 14 15:47:24 2010 +0300 @@ -372,6 +372,7 @@ int mask = SWT.RIGHT_TO_LEFT | SWT.LEFT_TO_RIGHT | SWT.APPLICATION_MODAL | SWT.PRIMARY_MODAL | SWT.SYSTEM_MODAL; shell = new Shell(parent, SWT.DIALOG_TRIM | (Internal_PackageSupport.style(this) & mask)); + Internal_PackageSupport.setWidgetInternalOnly(shell); shell.setText(getText()); shell.setLayout(new FillLayout()); diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/QueryDialog.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/QueryDialog.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/ercp/swt/mobile/QueryDialog.java Fri May 14 15:47:24 2010 +0300 @@ -1,10 +1,10 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Nokia Corporation and/or its subsidiary(-ies). - * All rights reserved. This program and the accompanying materials + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * Yu You (Nokia Corp.) - initial API specification * Nokia Corporation - S60 implementation @@ -37,20 +37,20 @@ /** * A modal window used to prompt the end-user for data input. - * + * *

* A QueryDialog contains a prompt text and an entry field. The QueryDialog * supports five types of entry fields: STANDARD, NUMERIC, PASSWORD, TIME and * DATE. The position and size of the dialog is implementation-dependent. *

- * + * *
*
Styles:
*
APPLICATION_MODAL, PRIMARY_MODAL
*
Query types:
*
STANDARD: alphanumeric data input
*
NUMERIC: numerical only data input
- *
PASSWORD: a platform-dependent way for sensitive information input. + *
PASSWORD: a platform-dependent way for sensitive information input. * The initial input mode is set to allow entry of digit characters
*
TIME: time input. The string format must be the international standard * notation (ISO 8601), hh:mm:ss, where hh is the number of complete hours that @@ -74,7 +74,7 @@ *

*

* Example: - * + * *

  * QueryDialog dialog = new QueryDialog(shell, SWT.NONE, QueryDialog.STANDARD);
  * dialog.setPromptText("Enter name:", "game1");
@@ -98,18 +98,18 @@
     private String  promptText;
     private String  defaultValue;
     private boolean isMidnight;
-    
+
     private static final String     midnightHour = "24:00:00";
     private static final String     platformMidnightHour = "00:00:00";
 
     private String dialogID;
     static int dialogCount;
-    
+
     /**
      * The maximum number of digits that can be entered after the decimals point.
      */
-    private static final int MAX_DECIMALS = 10;  
-    
+    private static final int MAX_DECIMALS = 10;
+
     /**
      * Alphanumeric data entry type
      */
@@ -140,14 +140,14 @@
 
     /**
      * Constructs a new instance of this class given its parent.
-     * 
+     *
      * 

* By default, APPLICATION_MODAL style and STANDARD query type is used. *

- * + * * @param parent * a shell which will be the parent of the new instance - * + * * @exception IllegalArgumentException *
    *
  • ERROR_NULL_ARGUMENT - if the parent is null
  • @@ -167,17 +167,17 @@ /** * Constructs a new instance of this class given its parent and style . - * + * *

    * The style value is either one of the style constants defined in class * Dialog. By default STANDARD query type is used. *

    - * + * * @param parent * a shell which will be the parent of the new instance * @param style * the style of control to construct - * + * * @exception IllegalArgumentException *
      *
    • ERROR_NULL_ARGUMENT - if the parent is null
    • @@ -198,19 +198,19 @@ /** * Constructs a new instance of this class given its parent, style and query * type. - * + * *

      * The style value is either one of the style constants defined in class * Dialog. *

      - * + * * @param parent * a shell which will be the parent of the new instance * @param style * the style of control to construct * @param queryType * one of STANDARD, NUMERIC, PASSWORD, TIME, or DATE. - * + * * @exception IllegalArgumentException *
        *
      • ERROR_NULL_ARGUMENT - if the parent is null
      • @@ -236,23 +236,23 @@ super(parent, checkStyle(parent, style)); checkSubclass(); checkDialog(); - + if (!internal_checkQueryType(queryType)) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } - + dialogCount++; dialogID = toString() + String.valueOf(dialogCount); - + this.queryType = queryType; this.defaultValue = null; isMidnight = false; } - + static protected int checkStyle(Shell parent, int style) { style = Internal_PackageSupport.checkStyle(parent, style); - + int mask = SWT.APPLICATION_MODAL | SWT.PRIMARY_MODAL; if ((style & mask) == 0) style |= SWT.APPLICATION_MODAL; if ((style & SWT.APPLICATION_MODAL) != 0) style = (style & ~mask) | SWT.APPLICATION_MODAL; @@ -261,7 +261,7 @@ } static boolean internal_checkQueryType(int queryType) { - if (queryType != STANDARD && + if (queryType != STANDARD && queryType != NUMERIC && queryType != PASSWORD && queryType != TIME && @@ -274,19 +274,19 @@ private void checkDialog() { Display currentDisplay = getParent().getDisplay(); if (currentDisplay.getThread() != Thread.currentThread ()) SWT.error(SWT.ERROR_THREAD_INVALID_ACCESS); - } + } /** * Creates the prompt dialog in front of its parent shell and waits for input. * This method will return when the input is finished or cancelled. - * + * * @return String the value entered. Null means that input was cancelled, * regardless of whether a default value was specified. For STANDARD, * NUMERIC, and PASSWORD types, the string contains precisely * the characters entered without any formatting, up to the maximum * number of characters. For DATE and TIME - * types, the string contains an ISO 8601 formatted value. - * + * types, the string contains an ISO 8601 formatted value. + * * @exception SWTException *
          *
        • ERROR_THREAD_INVALID_ACCESS - if not called from the @@ -304,9 +304,9 @@ if (isMidnight && result.equals(platformMidnightHour)) { result = midnightHour; } - + } else { - + DisposeListener listener = new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (e.widget == getParent()) { @@ -316,19 +316,19 @@ } }; getParent().addDisposeListener(listener); - + int qtLayoutDirection = (Internal_PackageSupport.style(this) & SWT.RIGHT_TO_LEFT) != 0 ? OS.QT_RIGHTTOLEFT : OS.QT_LEFTTORIGHT; if (queryType == STANDARD || queryType == PASSWORD) { - int echoMode = (queryType == PASSWORD) ? OS.QLINEEDIT_ECHOMODE_PASSWORD : OS.QLINEEDIT_ECHOMODE_NORMAL; + int echoMode = (queryType == PASSWORD) ? OS.QLINEEDIT_ECHOMODE_PASSWORD : OS.QLINEEDIT_ECHOMODE_NORMAL; result = OS.QInputDialog_swt_getText(handle(getParent()), getText(), promptText, echoMode, defaultValue, dialogID, qtLayoutDirection); - + } else { // NUMERIC - + double max = Double.MAX_VALUE; double defaultInput = (defaultValue == null) ? 0 : Double.parseDouble(defaultValue); - + if (maximum > 0) { // Calculate the max double value that can be entered // with the current maximum @@ -338,34 +338,34 @@ } max = Double.parseDouble(str); } - - result = OS.QInputDialog_swt_getDouble(handle(getParent()), getText(), promptText, -max, max, + + result = OS.QInputDialog_swt_getDouble(handle(getParent()), getText(), promptText, -max, max, defaultInput, MAX_DECIMALS, dialogID, qtLayoutDirection); - } - + } + if (getParent() != null && !getParent().isDisposed()) { getParent().removeDisposeListener(listener); } } - + return result; } - + /** * Defines the maximum number of characters that can be entered. - * If the input string already exceeds the maximum, the excessive part of + * If the input string already exceeds the maximum, the excessive part of * the value is not displayed. - * + * * Usually the maximum length is system-dependent, and applications should * not specify it. - * + * * Note: This method has no effect for DATE and TIME types. - * + * * @param maximum * the maximum character length. Must be equal or greater than * zero. Zero means no limit. - * + * * @exception IllegalArgumentException *
            *
          • ERROR_NULL_ARGUMENT - if maximum is negative, or less @@ -384,7 +384,7 @@ *
          • ERROR_WIDGET_DISPOSED - if the dialog has been * disposed
          • *
          - * + * * @see #setMinimum(int) */ public void setMaximum(int maximum) { @@ -392,24 +392,24 @@ if (maximum < 0 || maximum < minimum) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } - + // 0x7fff is the default max length for QLineEdit if (maximum > 0x7fff) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.maximum = maximum; } - + /** * Defines the minimum number of characters that must be entered before * the dialog can be completed (not cancelled). - * + * * Note: This method has no effect for DATE and TIME types. - * + * * @param minimum * the minimum number of characters. Must be equal or greater than * zero. Zero means no limit. - * + * * @exception IllegalArgumentException *
            *
          • ERROR_NULL_ARGUMENT - if minimum is negative, or @@ -424,7 +424,7 @@ *
          • ERROR_WIDGET_DISPOSED - if the dialog has been * disposed
          • *
          - * + * * @see #setMaximum(int) */ public void setMinimum(int minimum) { @@ -437,16 +437,16 @@ /** * Sets the prompt text and default input value. - * + * * @param promptText * the prompt text. Can be null. * @param defaultValue * the initial value. Cannot be null. The {@link #open() open()} * method may return the same value even when no input is - * received from the end-user. If the value length is greater than - * the maximum number of characters, only the maximum will be + * received from the end-user. If the value length is greater than + * the maximum number of characters, only the maximum will be * displayed. - * + * * @exception IllegalArgumentException *
            *
          • ERROR_NULL_ARGUMENT - if defaultValue is null
          • @@ -464,11 +464,11 @@ */ public void setPromptText(String promptText, String defaultValue) { checkDialog(); - + if (defaultValue == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } - + if (checkFormat(defaultValue)) { if (queryType != DATE && queryType != TIME && maximum > 0 && defaultValue.length() > maximum) { @@ -549,24 +549,24 @@ } return true; } - + /** * Custom dialog implementation for DATE and TIME mode QueryDialog. Dialog shell * includes a Label for prompt text, DateEditor for time/date input and OK and Cancel buttons. - * Controls of the dialog are layouted into a GridLayout. + * Controls of the dialog are layouted into a GridLayout. */ private class internal_DateTimeDialog implements SelectionListener { - + private Shell shell; private DateEditor editor; private Button okButton; private Button cancelButton; private Date retValue; - + public internal_DateTimeDialog() { retValue = null; } - + public String open() { createShell(); shell.open(); @@ -574,11 +574,11 @@ while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } - + if (retValue == null) { return null; } - + Calendar calendar = Calendar.getInstance(); calendar.setTime(retValue); @@ -592,7 +592,7 @@ getIntValue(calendar.get(Calendar.DAY_OF_MONTH)); } } - + private void createShell() { shell = new Shell(getParent(), SWT.DIALOG_TRIM | getStyle()); shell.setText(getText()); @@ -601,18 +601,18 @@ if (promptText != null) { label.setText(promptText); } - + int orientationBits = SWT.RIGHT_TO_LEFT | SWT.LEFT_TO_RIGHT; int editorStyle = (queryType == QueryDialog.DATE) ? DateEditor.DATE : DateEditor.TIME; editor = new DateEditor(shell, getStyle() & orientationBits, editorStyle); - + if(queryType == QueryDialog.DATE) editor.setDate(new Date()); else editor.setTime(0); - - // Do always return traverse from the editor, so that default button of the dialog - // gets the enter key press + + // Do always return traverse from the editor, so that default button of the dialog + // gets the enter key press editor.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_RETURN) { @@ -620,7 +620,7 @@ } } }); - + if (defaultValue != null) { Calendar calendar = Calendar.getInstance(); if (queryType == DATE) { @@ -634,11 +634,11 @@ } editor.setDate(calendar.getTime()); } - + cancelButton = new Button(shell, SWT.PUSH); okButton = new Button(shell, SWT.PUSH); shell.setDefaultButton(okButton); - + okButton.setText(SWT.getMessage("ok")); cancelButton.setText(SWT.getMessage("cancel")); okButton.addSelectionListener(this); @@ -647,41 +647,41 @@ // Layout content GridLayout gridLayout = new GridLayout(2, false); shell.setLayout(gridLayout); - + GridData labelData = new GridData(SWT.FILL, SWT.END, false, true, 2, 1); GridData editorData = new GridData(SWT.FILL, SWT.CENTER, false, true, 2, 1); label.setLayoutData(labelData); editor.setLayoutData(editorData); - + GridData cancelButtonData = new GridData(SWT.END, SWT.TOP, true, true, 1, 1); GridData okButtonData = new GridData(SWT.END, SWT.TOP, false, true, 1, 1); cancelButton.setLayoutData(cancelButtonData); okButton.setLayoutData(okButtonData); - + shell.pack(); shell.layout(true); } - + private String getIntValue(int value) { - String string = ""; + String string = ""; if (value < 10) { string += Integer.toString(0); } return string + Integer.toString(value); } - + public void widgetDefaultSelected(SelectionEvent e) { } - + public void widgetSelected(SelectionEvent e) { - if (e.widget.equals(okButton)) { + if (e.widget == okButton) { retValue = editor.getDate(); - } + } shell.dispose(); } } - + private final int handle(Widget w) { - return Internal_PackageSupport.handle(w); + return Internal_PackageSupport.handle(w); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Display.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Display.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Display.java Fri May 14 15:47:24 2010 +0300 @@ -794,7 +794,9 @@ if (activeWindowHandle != 0) { Widget widget = getWidget(activeWindowHandle); if(widget instanceof org.eclipse.swt.widgets.Shell) { + if(!Internal_PackageSupport.isInternalWidget(widget)) { activeShell = (Shell)widget; + } } } return activeShell; diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Widget.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Widget.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse SWT/qt/org/eclipse/swt/widgets/Widget.java Fri May 14 15:47:24 2010 +0300 @@ -56,7 +56,6 @@ Display display; EventTable eventTable; Object data; - PackageProxy packageProxy; static final int checkBits (int style, int int0, int int1, int int2, int int3, int int4, int int5) { @@ -539,6 +538,11 @@ return eventTable.hooks (eventType); } + +boolean isInternalWidget_pp() { + return (state & WidgetState.INTERNAL) != 0; +} + /** * Returns true if the widget has been disposed, * and false otherwise. @@ -1220,6 +1224,10 @@ } } +void setWidgetInternalOnly_pp(){ + state|=WidgetState.INTERNAL; +} + final void setPackageProxy(Object packageProxy) { // If the subclass is in another package then it provides a proxy object // which implements the methods that "override" the package private diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/common_j2me/org/eclipse/swt/internal/ApplicationUidWrapper.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/common_j2me/org/eclipse/swt/internal/ApplicationUidWrapper.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/common_j2me/org/eclipse/swt/internal/ApplicationUidWrapper.java Fri May 14 15:47:24 2010 +0300 @@ -1,18 +1,33 @@ /******************************************************************************* - * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). - * All rights reserved. This program and the accompanying materials + * Copyright (c) 2009,2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: - * Nokia Corporation - initial implementation + * Nokia Corporation - initial implementation *******************************************************************************/ package org.eclipse.swt.internal; +import com.nokia.mj.impl.rt.support.ApplicationInfo; + public final class ApplicationUidWrapper { - public static int uid() { - return com.nokia.mj.impl.runtime.rtport.RuntimeInfoFactory.getRuntimeInfo().getApplicationUid(); + + public static int uid() { + int midletUid = -1; + try{ + String uidS = ApplicationInfo.getInstance().getUid().getStringValue(); + // In Symbian the UID is in format '[]' where is in hex + // format. So wee need to take the brackets away. + // Long is needed in conversion because UIDs greater than 0x80000000 + // would fail if Integer would be used. However typecast from long + // to int is safe since UID in Symbian is 32 bit. + long uidL = Long.parseLong(uidS.substring(1,uidS.length()-1), 16); + return (int)uidL; + } + catch (Throwable t) {/* Not handled*/ } + return midletUid; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/eswt_widgets.pri --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/eswt_widgets.pri Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/eswt_widgets.pri Fri May 14 15:47:24 2010 +0300 @@ -46,6 +46,9 @@ ##### Symbian specific items ###### symbian { +CONFIG += mobility +MOBILITY += bearer + HEADERS += swts60.h \ swtmobiledevice.h \ swtflipwatch.h @@ -64,6 +67,7 @@ LIBS += -lHWRMVibraClient LIBS += -lHWRMLightClient LIBS += -lxqservice +LIBS += -lxqtelephonyservice LIBS += -lQtContacts } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/os.cpp --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/os.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/os.cpp Fri May 14 15:47:24 2010 +0300 @@ -86,7 +86,10 @@ #ifdef __SYMBIAN32__ #include +#include #include +#include +#include #endif #include @@ -11591,7 +11594,6 @@ return result ? JNI_TRUE : JNI_FALSE; } - // // QInputContextFactory // @@ -11611,7 +11613,6 @@ return reinterpret_cast(inputContext); } - JNIEXPORT jstring JNICALL OS_NATIVE( QInputContextFactory_1swt_1key ) (JNIEnv* aJniEnv, jclass, jstring aLanguage) { @@ -11673,10 +11674,6 @@ SWT_CATCH } - - - - // // XQServiceRequest // @@ -11702,8 +11699,6 @@ #endif } - - JNIEXPORT void JNICALL OS_NATIVE( XQServiceRequest_1swt_1setArgumentsForFetchEmail ) #ifdef __SYMBIAN32__ (JNIEnv* aJniEnv, jclass, jint aHandle, jstring aTitle, jstring aAction, jstring aFilter) @@ -11725,7 +11720,6 @@ #endif } - JNIEXPORT void JNICALL OS_NATIVE( XQServiceRequest_1swt_1setArgumentsForDial ) #ifdef __SYMBIAN32__ (JNIEnv* aJniEnv, jclass, jint aHandle, jstring aNumber, jboolean aAsyncAnswer) @@ -11746,7 +11740,6 @@ #endif } - JNIEXPORT jboolean JNICALL OS_NATIVE( XQServiceRequest_1send ) #ifdef __SYMBIAN32__ (JNIEnv* aJniEnv, jclass, jint aHandle) @@ -11812,190 +11805,9 @@ #endif } - -// -// Other -// - -JNIEXPORT jint JNICALL OS_NATIVE(EventHandler_1new) - ( JNIEnv* aJniEnv, jclass) - { - EventCallback* cb = NULL; - SWT_TRY - { - SWT_LOG_JNI_CALL(); - - // Event handler is owned by the Java peer (Display instance) - cb = new EventCallback(); - } - SWT_CATCH - return POINTER_TO_HANDLE( cb ); - } - -JNIEXPORT void JNICALL OS_NATIVE(EventHandler_1destroy) - (JNIEnv* aJniEnv , jclass, jint aHandle) - { - SWT_TRY - { - SWT_LOG_JNI_CALL(); - SWT_LOG_DATA_1("handle=%x", aHandle); - - HANDLE_TO_POINTER( EventCallback*, cb, aHandle ); - cb->Destroy(); - } - SWT_CATCH - } - -JNIEXPORT jint JNICALL OS_NATIVE(SignalHandler_1new) - (JNIEnv* aJniEnv, jclass, jint aWidget, jobject aPeer, jint aSignalId ) - { - SlotCallback* cb = NULL; - SWT_TRY - { - SWT_LOG_JNI_CALL(); - SWT_LOG_DATA_1("peer=%x", aPeer); - - HANDLE_TO_POINTER( QObject*, widget, aWidget ); - - // Widget takes ownership of the signal handler instance - cb = new SlotCallback( aJniEnv, aPeer, widget, aSignalId ); - } - SWT_CATCH - return POINTER_TO_HANDLE( cb ); - } - -JNIEXPORT jint JNICALL OS_NATIVE( JniUtils_1new ) - (JNIEnv* aJniEnv, jclass, jobject aDisplay) - { - // Note that JNI callbacks are not possible before first successfully creating jniUtils - JniUtils* jniUtils = NULL; - try { - jniUtils = new JniUtils(aJniEnv, aDisplay); - } - catch(...) - { - // Can't throw an exception because there's no jniUtils - } - return POINTER_TO_HANDLE( jniUtils ); - } - -JNIEXPORT jboolean JNICALL OS_NATIVE( JniUtils_1safeToDelete ) - (JNIEnv* aJniEnv, jclass, jint aHandle, jint aQObjectHandle) -{ - bool result = false; - SWT_TRY - { - SWT_LOG_JNI_CALL(); - SWT_LOG_DATA_2("handle=%x qobject=%x", aHandle, aQObjectHandle); - - HANDLE_TO_POINTER( JniUtils*, jniUtils, aHandle); - HANDLE_TO_POINTER( QObject*, object, aQObjectHandle ); - - result = jniUtils->safeToDelete(object); - } - SWT_CATCH - return result ? JNI_TRUE : JNI_FALSE; -} - - -JNIEXPORT jint JNICALL OS_NATIVE( windowServer ) - (JNIEnv* aJniEnv , jclass) - { - SWT_TRY - { - SWT_LOG_JNI_CALL(); - } - SWT_CATCH -#ifndef Q_WS_X11 - return 1; -#else - return 2; -#endif - } - - -JNIEXPORT jint JNICALL OS_NATIVE( initUiThread ) - (JNIEnv* -#ifdef __SYMBIAN32__ - aJniEnv -#endif - , jclass, jint -#ifdef __SYMBIAN32__ - aUid -#endif - ) - { - jint retVal = 0; -#ifdef __SYMBIAN32__ - retVal = static_cast(SymbianUtils::initUiThread(aJniEnv, static_cast(aUid))); -#endif - return retVal; - } - -JNIEXPORT void JNICALL OS_NATIVE( cleanUpUiThread ) - (JNIEnv*, jclass) - { -#ifdef __SYMBIAN32__ - SymbianUtils::cleanupUiThread(); -#endif - } - - -JNIEXPORT void JNICALL OS_NATIVE( setSymbianAppName ) -#ifdef __SYMBIAN32__ - (JNIEnv* aJniEnv, jclass, jstring aName) -#else - (JNIEnv*, jclass, jstring) -#endif - { -#ifdef __SYMBIAN32__ - SymbianUtils::setAppName(aJniEnv, aName); -#endif - } - -JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_qt_s60_OS__1startUI -#ifdef __SYMBIAN32__ - (JNIEnv* aJniEnv, jclass, jobject aRunner, jint aUid) -#else -(JNIEnv*, jclass, jobject, jint) -#endif - { - jint retVal = 0; -#ifdef __SYMBIAN32__ - retVal = static_cast(SymbianUtils::startUI( aJniEnv, aRunner, aUid)); -#endif - return retVal; - } - -JNIEXPORT jint JNICALL OS_NATIVE( getScreenDeviceNumber ) - (JNIEnv*, jclass) - { - jint screenNumber = -1; -#ifdef __SYMBIAN32__ - screenNumber = SymbianUtils::GetScreenDeviceNumber(); -#endif - return screenNumber; - } - -JNIEXPORT jint JNICALL OS_NATIVE( getColorDepth ) - (JNIEnv*, jclass) - { - jint colorDepth = 24; -#ifdef __SYMBIAN32__ - colorDepth = SymbianUtils::GetColorDepth(); -#endif - return colorDepth; - } - -JNIEXPORT jint JNICALL OS_NATIVE( getHwInputs ) - (JNIEnv*, jclass) - { - jint hwInputs = 0; -#ifdef __SYMBIAN32__ - hwInputs = SymbianUtils::GetHwInputs(); -#endif - return hwInputs; - } +// +// MobileDevice, Screen, Input +// JNIEXPORT jint JNICALL OS_NATIVE( MobileDevice_1new ) (JNIEnv*, jclass) @@ -12101,7 +11913,340 @@ #endif return ( vibraSupport ? JNI_TRUE : JNI_FALSE ); } -// Add new stuff above the Other, Other is the last category + +JNIEXPORT jint JNICALL OS_NATIVE( getScreenDeviceNumber ) + (JNIEnv*, jclass) + { + jint screenNumber = -1; +#ifdef __SYMBIAN32__ + screenNumber = SymbianUtils::GetScreenDeviceNumber(); +#endif + return screenNumber; + } + +JNIEXPORT jint JNICALL OS_NATIVE( getColorDepth ) + (JNIEnv*, jclass) + { + jint colorDepth = 24; +#ifdef __SYMBIAN32__ + colorDepth = SymbianUtils::GetColorDepth(); +#endif + return colorDepth; + } + +JNIEXPORT jint JNICALL OS_NATIVE( getHwInputs ) + (JNIEnv*, jclass) + { + jint hwInputs = 0; +#ifdef __SYMBIAN32__ + hwInputs = SymbianUtils::GetHwInputs(); +#endif + return hwInputs; + } + +// +// QNetworkConfigurationManager +// + +JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_extension_OS_QNetworkConfigurationManager_1new +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass, jint aParent) +#else +(JNIEnv*, jclass, jint) +#endif +{ + jint result = 0; +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("parent=%x", aParent); + HANDLE_TO_POINTER(QObject*, parent, aParent); + result = POINTER_TO_HANDLE(new QtMobility::QNetworkConfigurationManager(parent)); + } + SWT_CATCH +#endif + return result; +} + +JNIEXPORT jintArray JNICALL Java_org_eclipse_swt_internal_extension_OS_QNetworkConfigurationManager_1allConfigurations +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass, jint aHandle, jint aFilter) +#else +(JNIEnv*, jclass, jint, jint) +#endif +{ + jintArray javaArray = NULL; +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_2("handle=%x filter=%x", aHandle, aFilter); + + HANDLE_TO_POINTER(QtMobility::QNetworkConfigurationManager*, manager, aHandle); + + QList configs = + manager->allConfigurations(static_cast(aFilter)); + + int count = configs.size(); + QVector handles(count); + int* handleData = handles.data(); + for(int i = 0; i < count; ++i) + { + handleData[i] = reinterpret_cast(new QtMobility::QNetworkConfiguration(configs.at(i))); + } + javaArray = swtApp->jniUtils().NewJavaIntArray(aJniEnv, handleData, count); + } + SWT_CATCH +#endif + return javaArray; +} + +// +// QNetworkConfiguration +// + +JNIEXPORT jstring JNICALL Java_org_eclipse_swt_internal_extension_OS_QNetworkConfiguration_1bearerName +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass, jint aHandle) +#else +(JNIEnv *, jclass, jint) +#endif +{ +#ifdef __SYMBIAN32__ + jstring result = NULL; +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("handle=%x", aHandle); + QtMobility::QNetworkConfiguration* config = reinterpret_cast(aHandle); + result = swtApp->jniUtils().QStringToJavaString(aJniEnv, config->bearerName()); + } + SWT_CATCH +#endif + return result; +#endif +} + +JNIEXPORT void JNICALL Java_org_eclipse_swt_internal_extension_OS_QNetworkConfiguration_1delete +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass, jint aHandle) +#else +(JNIEnv *, jclass, jint) +#endif +{ +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("handle=%x", aHandle); + delete reinterpret_cast(aHandle); + } + SWT_CATCH +#endif +} + +// +// XQCallInfo +// + +JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_extension_OS_XQCallInfo_1create +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass) +#else +(JNIEnv *, jclass) +#endif +{ + jint result = 0; +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); +#ifndef __WINSCW__ + result = POINTER_TO_HANDLE(XQCallInfo::create()); +#endif + } + SWT_CATCH +#endif + return result; +} + +JNIEXPORT jboolean JNICALL Java_org_eclipse_swt_internal_extension_OS_XQCallInfo_1swt_1hasCalls +#ifdef __SYMBIAN32__ +(JNIEnv* aJniEnv, jclass, jint aHandle) +#else +(JNIEnv *, jclass, jint) +#endif +{ + jboolean result = JNI_FALSE; +#ifdef __SYMBIAN32__ + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("handle=%x", aHandle); + HANDLE_TO_POINTER(XQCallInfo*, callInfo, aHandle); + QList callInfos; + callInfo->getCalls(callInfos); + result = callInfos.empty() ? JNI_FALSE : JNI_TRUE; + } + SWT_CATCH +#endif + return result; +} + +// +// Other +// + +JNIEXPORT jint JNICALL OS_NATIVE(EventHandler_1new) + ( JNIEnv* aJniEnv, jclass) + { + EventCallback* cb = NULL; + SWT_TRY + { + SWT_LOG_JNI_CALL(); + + // Event handler is owned by the Java peer (Display instance) + cb = new EventCallback(); + } + SWT_CATCH + return POINTER_TO_HANDLE( cb ); + } + +JNIEXPORT void JNICALL OS_NATIVE(EventHandler_1destroy) + (JNIEnv* aJniEnv , jclass, jint aHandle) + { + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("handle=%x", aHandle); + + HANDLE_TO_POINTER( EventCallback*, cb, aHandle ); + cb->Destroy(); + } + SWT_CATCH + } + +JNIEXPORT jint JNICALL OS_NATIVE(SignalHandler_1new) + (JNIEnv* aJniEnv, jclass, jint aWidget, jobject aPeer, jint aSignalId ) + { + SlotCallback* cb = NULL; + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_1("peer=%x", aPeer); + + HANDLE_TO_POINTER( QObject*, widget, aWidget ); + + // Widget takes ownership of the signal handler instance + cb = new SlotCallback( aJniEnv, aPeer, widget, aSignalId ); + } + SWT_CATCH + return POINTER_TO_HANDLE( cb ); + } + +JNIEXPORT jint JNICALL OS_NATIVE( JniUtils_1new ) + (JNIEnv* aJniEnv, jclass, jobject aDisplay) + { + // Note that JNI callbacks are not possible before first successfully creating jniUtils + JniUtils* jniUtils = NULL; + try { + jniUtils = new JniUtils(aJniEnv, aDisplay); + } + catch(...) + { + // Can't throw an exception because there's no jniUtils + } + return POINTER_TO_HANDLE( jniUtils ); + } + +JNIEXPORT jboolean JNICALL OS_NATIVE( JniUtils_1safeToDelete ) + (JNIEnv* aJniEnv, jclass, jint aHandle, jint aQObjectHandle) +{ + bool result = false; + SWT_TRY + { + SWT_LOG_JNI_CALL(); + SWT_LOG_DATA_2("handle=%x qobject=%x", aHandle, aQObjectHandle); + + HANDLE_TO_POINTER( JniUtils*, jniUtils, aHandle); + HANDLE_TO_POINTER( QObject*, object, aQObjectHandle ); + + result = jniUtils->safeToDelete(object); + } + SWT_CATCH + return result ? JNI_TRUE : JNI_FALSE; +} + +JNIEXPORT jint JNICALL OS_NATIVE( windowServer ) + (JNIEnv* aJniEnv , jclass) + { + SWT_TRY + { + SWT_LOG_JNI_CALL(); + } + SWT_CATCH +#ifndef Q_WS_X11 + return 1; +#else + return 2; +#endif + } + +JNIEXPORT jint JNICALL OS_NATIVE( initUiThread ) + (JNIEnv* +#ifdef __SYMBIAN32__ + aJniEnv +#endif + , jclass, jint +#ifdef __SYMBIAN32__ + aUid +#endif + ) + { + jint retVal = 0; +#ifdef __SYMBIAN32__ + retVal = static_cast(SymbianUtils::initUiThread(aJniEnv, static_cast(aUid))); +#endif + return retVal; + } + +JNIEXPORT void JNICALL OS_NATIVE( cleanUpUiThread ) + (JNIEnv*, jclass) + { +#ifdef __SYMBIAN32__ + SymbianUtils::cleanupUiThread(); +#endif + } + +JNIEXPORT void JNICALL OS_NATIVE( setSymbianAppName ) +#ifdef __SYMBIAN32__ + (JNIEnv* aJniEnv, jclass, jstring aName) +#else + (JNIEnv*, jclass, jstring) +#endif + { +#ifdef __SYMBIAN32__ + SymbianUtils::setAppName(aJniEnv, aName); +#endif + } + +JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_qt_s60_OS__1startUI +#ifdef __SYMBIAN32__ + (JNIEnv* aJniEnv, jclass, jobject aRunner, jint aUid) +#else +(JNIEnv*, jclass, jobject, jint) +#endif + { + jint retVal = 0; +#ifdef __SYMBIAN32__ + retVal = static_cast(SymbianUtils::startUI( aJniEnv, aRunner, aUid)); +#endif + return retVal; + } + +// Add new stuff above the category "Other", that is the last category #ifdef __cplusplus } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swt.pro --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swt.pro Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swt.pro Fri May 14 15:47:24 2010 +0300 @@ -51,15 +51,13 @@ INCLUDEPATH += \epoc32\include\middleware \ \epoc32\include\domain\middleware - # J9 stuff that Mikko knows about + # J9 VM specific definitions DEFINES+=J9EPOC32 # Std cpp requirements LIBS += -llibc LIBS += -leuser LIBS += -llibstdcpp - LIBS += -lxqservice - LIBS += -lQtContacts DEFINES+= MACRO_WCHAR_T_DECLARED QMAKE_CXXFLAGS.CW += -wchar_t on diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swtapplication.h --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swtapplication.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/library/swtapplication.h Fri May 14 15:47:24 2010 +0300 @@ -15,6 +15,7 @@ #include #include #include +#include #include #include "jniutils.h" diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/OS.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/OS.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/OS.java Fri May 14 15:47:24 2010 +0300 @@ -1638,13 +1638,10 @@ // public static final native int QChar_direction(char c); - // // SwtFontCache // - - /** * Ensures the font or another equal font is in the font cache and returns a * handle to the cached font. Takes ownership of the passed QFont handle. @@ -1667,16 +1664,14 @@ */ public static final native boolean SwtFontCache_isCached(int handle); - // // QInputContextFactory // public static final native int QInputContextFactory_create(String key, int parent); public static final native String QInputContextFactory_swt_key(String language ); - // - //MobileDevice, Screen, Input + // MobileDevice, Screen, Input // public static final native int MobileDevice_new(); public static final native void MobileDevice_createFlipWatch(int handle); @@ -1689,7 +1684,6 @@ public static final native int getScreenDeviceNumber(); public static final native int getColorDepth(); public static final native int getHwInputs(); - // // SwtApplication @@ -1728,7 +1722,6 @@ // CntServicesContactList // public static final native String[] CntServicesContactList_swt_contacts(int handle); - // // Other diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/WidgetState.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/WidgetState.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/internal/qt/WidgetState.java Fri May 14 15:47:24 2010 +0300 @@ -56,4 +56,7 @@ // If extension functionality is enabled public static final int IS_EXTENDED = 1<<29; + +// The widget is internal widget. +public static final int INTERNAL = 1<<30; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/widgets/Internal_PackageSupport.java --- a/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/widgets/Internal_PackageSupport.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/eswt_qt/org.eclipse.swt/Eclipse_SWT_PI/qt/org/eclipse/swt/widgets/Internal_PackageSupport.java Fri May 14 15:47:24 2010 +0300 @@ -31,9 +31,16 @@ public static int handle(Widget w) { return w.handle; } + +public static boolean isInternalWidget(Widget w) { + return w.isInternalWidget_pp(); +} public static void setHandle(Widget w, int handle) { w.handle = handle; } +public static void setWidgetInternalOnly(Widget w) { + w.setWidgetInternalOnly_pp(); +} public static int topHandle(Widget w) { return w.topHandle; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/javauis.pro --- a/javauis/javauis.pro Mon May 03 12:27:20 2010 +0300 +++ b/javauis/javauis.pro Fri May 14 15:47:24 2010 +0300 @@ -18,6 +18,7 @@ SUBDIRS += lcdui_qt/build/openlcdui.pro SUBDIRS += runtimeui_qt/build/javaruntimeui.pro SUBDIRS += nokiauiapi_qt/build/nokiauiapiqt.pro +SUBDIRS += mmapi_qt/build/javamobilemedia.pro SUBDIRS += javalegacyutils BLD_INF_RULES.prj_extensions += "$${LITERAL_HASH}include \"coreui/build/bld.inf\"" BLD_INF_RULES.prj_extensions += "prj_extensions" diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/build/javalcdui.pro --- a/javauis/lcdui_akn/javalcdui/build/javalcdui.pro Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/build/javalcdui.pro Fri May 14 15:47:24 2010 +0300 @@ -46,6 +46,7 @@ -lhwrmlightclient \ -lgfxtrans \ -lws32 \ + -lCentralRepository \ #ifdef RD_JAVA_NGA_ENABLED -llibegl \ -llibglesv1_cm diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/inc/CMIDToolkit.h --- a/javauis/lcdui_akn/javalcdui/inc/CMIDToolkit.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/inc/CMIDToolkit.h Fri May 14 15:47:24 2010 +0300 @@ -167,6 +167,11 @@ void HandleResourceChangeL(TInt aType); private: + /** + * Resets user inactivity timers + */ + void ResetInactivityTimeL(); + static TInt CreateToolkitL ( JNIEnv& aJni, diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/inc/lcdui.h --- a/javauis/lcdui_akn/javalcdui/inc/lcdui.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/inc/lcdui.h Fri May 14 15:47:24 2010 +0300 @@ -720,13 +720,6 @@ */ EDrwOpcBitBltRect = 1 #endif // RD_JAVA_NGA_ENABLED - - /** - * Indicates first ever canvas paint. - * Used to stop the splash screen. - * @since S60 9.2 - */ - ,EDrwOpcFirstPaint = 3 }; public: /** @@ -830,6 +823,8 @@ */ virtual void UpdateRect(const TRect& aRect) = 0; #endif // RD_JAVA_NGA_ENABLED + + virtual TBool ReadyToBlit() const = 0; }; /** diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/com/nokia/mid/ui/TextEditorImpl.java --- a/javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/com/nokia/mid/ui/TextEditorImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/com/nokia/mid/ui/TextEditorImpl.java Fri May 14 15:47:24 2010 +0300 @@ -10,7 +10,7 @@ * * Contributors: * - * Description: Package private class implementing the S40 and S60 interfaces + * Description: Package private class implementing the S60 interfaces * for TextEditor * */ @@ -34,9 +34,8 @@ * @since 1.4 */ class TextEditorImpl - extends com.nokia.mid.ui.TextEditor - implements com.nokia.mid.ui.S60TextEditor -{ + extends com.nokia.mid.ui.TextEditor + implements com.nokia.mid.ui.S60TextEditor { /* * Indicates that all input methods are available. *

            @@ -129,8 +128,7 @@ * if the width or height is less than one pixel */ TextEditorImpl(String aText, int aMaxSize, int aConstraints, int aWidth, - int aHeight) - { + int aHeight) { super(aText, aMaxSize, aConstraints, aWidth, aHeight, false); } @@ -173,11 +171,10 @@ * @throws IllegalArgumentException * if the width is less than one pixel */ - TextEditorImpl(int aMaxSize, int aConstraints, int aWidth, int aRows) - { + TextEditorImpl(int aMaxSize, int aConstraints, int aWidth, int aRows) { super(null, aMaxSize, aConstraints, aWidth, aRows, true); } - + /* * Set the parent object of this TextEditor. Typically in LCDUI the parent * object would be Canvas or CustomItem. Setting the parameter to null @@ -189,12 +186,10 @@ * if aParent is not a valid object with which a * TextEditor can be associated */ - public void setParent(Object aParent) - { - super.setParent(aParent); + public void setParent( Object aParent ) { + super.setParent( aParent ); // Update indicator location to their default position. - if (aParent != null) - { + if( aParent != null ) { setDefaultIndicators(); } } @@ -233,12 +228,10 @@ * the y coordinate of the anchor point, in pixels. * */ - public void setIndicatorLocation(int x, int y) - { - synchronized (iToolkit) - { + public void setIndicatorLocation(int x, int y) { + synchronized (iToolkit) { NativeError.check(_setIndicatorLocation(getToolkitHandle(), - iHandle, x, y)); + iHandle, x, y)); } } @@ -267,20 +260,17 @@ * If the TextEditor is not added to * Canvas */ - public void setDefaultIndicators() - { - synchronized (iToolkit) - { + public void setDefaultIndicators() { + synchronized (iToolkit) { Object parent = getParent(); boolean fullScreen = false; - if (parent instanceof Canvas) - { + if (parent instanceof Canvas) { fullScreen = iLCDUIPackageInvoker.isFullScreen((Canvas) parent); } NativeError.check(_setDefaultIndicators(getToolkitHandle(), - iHandle, fullScreen)); + iHandle, fullScreen)); } } @@ -304,12 +294,10 @@ * @see #setIndicatorLocation(int, int) * @see #setDefaultIndicators() */ - public void setIndicatorVisibility(boolean visible) - { - synchronized (iToolkit) - { + public void setIndicatorVisibility(boolean visible) { + synchronized (iToolkit) { NativeError.check(_setIndicatorVisibility(getToolkitHandle(), - iHandle, visible)); + iHandle, visible)); } } @@ -329,14 +317,12 @@ * @return the width and height of area needed for drawing input indicators * @see #setDefaultIndicators() */ - public int[] getIndicatorSize() - { + public int[] getIndicatorSize() { int[] size = new int[INDICATOR_SIZE_COUNT]; - synchronized (iToolkit) - { + synchronized (iToolkit) { NativeError.check(_getIndicatorSize(getToolkitHandle(), iHandle, - size)); + size)); } return size; } @@ -363,20 +349,17 @@ * @see #setPreferredTouchMode(int) * @see #getDisabledTouchInputModes() */ - public void setDisabledTouchInputModes(int touchInputModes) - { + public void setDisabledTouchInputModes(int touchInputModes) { // Validate touch input modes. There must not be additional modes // 0 is valid. // See com.nokia.mid.ui.s60.TextEditor.TOUCH_INPUT_ALL_AVAILABLE. - if ((touchInputModes & ~MASK) != 0) - { + if ((touchInputModes & ~MASK) != 0) { throw new IllegalArgumentException(); } - synchronized (iToolkit) - { + synchronized (iToolkit) { NativeError.check(_setDisabledTouchInputModes(getToolkitHandle(), - iHandle, touchInputModes)); + iHandle, touchInputModes)); } } @@ -395,12 +378,10 @@ * @see #setDisabledTouchInputModes(int) * @see #setPreferredTouchMode(int) */ - public int getDisabledTouchInputModes() - { + public int getDisabledTouchInputModes() { int disabled = 0; - synchronized (iToolkit) - { + synchronized (iToolkit) { disabled = _getDisabledTouchInputModes(getToolkitHandle(), iHandle); } @@ -429,20 +410,17 @@ * @see #getPreferredTouchMode() * */ - public void setPreferredTouchMode(int touchInputModes) - { + public void setPreferredTouchMode(int touchInputModes) { int mask = touchInputModes & MASK; // Validate touch input mode. if (touchInputModes == 0 || (touchInputModes & ~MASK) != 0 - || (mask & (mask - 1)) != 0) - { + || (mask & (mask - 1)) != 0) { throw new IllegalArgumentException(); } - synchronized (iToolkit) - { + synchronized (iToolkit) { NativeError.check(_setPreferredTouchMode(getToolkitHandle(), - iHandle, touchInputModes)); + iHandle, touchInputModes)); } } @@ -458,41 +436,37 @@ * @see #setPreferredTouchMode(int) * @see #setDisabledTouchInputModes(int) */ - public int getPreferredTouchMode() - { + public int getPreferredTouchMode() { int preferredMode = 0; - synchronized (iToolkit) - { + synchronized (iToolkit) { preferredMode = _getPreferredTouchMode(getToolkitHandle(), iHandle); } NativeError.check(preferredMode); return preferredMode; } - + /* * Sets the caret in the Editor at x, y location. - * + * * @param x * The x coordinate of the wanted caret position. * * @param y * The y coordinate of the wanted caret position. */ - public void setCaretXY(int x, int y) - { - synchronized (iToolkit) - { - NativeError.check(_setCaretXY(getToolkitHandle(), iHandle, x, y)); + public void setCaretXY(int x, int y) { + synchronized (iToolkit) { + NativeError.check(_setCaretXY(getToolkitHandle(), + iHandle, x, y)); } } /* * Hidden default constructor. */ - private TextEditorImpl() - { + private TextEditorImpl() { } // Private methods. diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/javax/microedition/lcdui/CanvasGraphicsItemPainter.java --- a/javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/javax/microedition/lcdui/CanvasGraphicsItemPainter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/javasrc.nokialcdui/javax/microedition/lcdui/CanvasGraphicsItemPainter.java Fri May 14 15:47:24 2010 +0300 @@ -154,7 +154,7 @@ if (iGraphics == null) { iGraphics = new Graphics( - (Toolkit)iToolkit, this, iHandle, + iToolkit, this, iHandle, iItem.getWidth(), iItem.getHeight()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/TextComponent.java --- a/javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/TextComponent.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/TextComponent.java Fri May 14 15:47:24 2010 +0300 @@ -84,11 +84,12 @@ final int modifier = (aConstraints & ~TextField.CONSTRAINT_MASK); if (modifier == 0 || (modifier >= 0x10000 && modifier <= 0x3F0000)) return; + else + throw new IllegalArgumentException(); } default: - break; + throw new IllegalArgumentException(); } - throw new IllegalArgumentException(); } } // class TextComponent diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/Toolkit.java --- a/javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/Toolkit.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/javasrc/javax/microedition/lcdui/Toolkit.java Fri May 14 15:47:24 2010 +0300 @@ -94,10 +94,7 @@ // NGA specific change private int iFlags = FLAG_NONE; - - // Splash screen specific - private boolean iFirstPaint = true; - + // // Event source : must keep in sync with TSourceType in lcdui.h // @@ -148,10 +145,7 @@ // NGA specific change. // Op code indicating M3G content start private static final int M3G_CONTENT_START = 2; - - // Splash screen specific. - private static final int SYNC_FIRST_PAINT = 3; - + Toolkit(ToolkitInvoker aInvoker) { iInvoker = aInvoker; @@ -666,13 +660,6 @@ final int y2=aY+aH; iBuffer.write(aDrawable, SYNC_RECT, aX, aY, x2, y2); iBuffer.sync(); - - if (iFirstPaint) - { - iFirstPaint = false; - iBuffer.write(aDrawable, SYNC_FIRST_PAINT); - iBuffer.sync(); - } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/javalcdui/src/CMIDToolkit.cpp --- a/javauis/lcdui_akn/javalcdui/src/CMIDToolkit.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/javalcdui/src/CMIDToolkit.cpp Fri May 14 15:47:24 2010 +0300 @@ -27,6 +27,10 @@ #include #include #include +#include +#include +#include +#include // to work with screensaver #include // For transition effects #include // For transition effects // @@ -427,6 +431,8 @@ ASSERT(oldDisplayable->Component()->Type() == MMIDComponent::EAlert); } + ResetInactivityTimeL(); + // Set it, revert will rollback if required. iCurrentDisplayable = newDisplayable; @@ -487,6 +493,57 @@ CleanupStack::Pop(); // revert } +void CMIDToolkit::ResetInactivityTimeL() +{ + TInt status = KErrNotFound; + RProperty::Get(KPSUidScreenSaver, KScreenSaverAllowScreenSaver,status); + + // If Screen Saver is enabled and is inactive reset timers + // Keep lights on and screensaver disabled. When status is >0 it means + // that screen saver is not allowed to be activated + if (!status) + { + TInt isTimeoutEnabled = KErrNone; + TInt errPCenrep = KErrNone; + CRepository* pCenrep = CRepository::NewLC(KCRUidPersonalizationSettings); + if (pCenrep) + { + errPCenrep = pCenrep->Get( + KSettingsScreensaverTimeoutItemVisibility, + isTimeoutEnabled); + } + CleanupStack::PopAndDestroy(pCenrep); + +#if defined(__WINSCW__) + if (!isTimeoutEnabled) + { + isTimeoutEnabled = 1; + } +#endif + + // Screen Saver Time out value + TInt screenSaverTimeout = KErrNone; + TInt errSCenrep = KErrNone; + CRepository* securityCenrep = CRepository::NewLC(KCRUidSecuritySettings); + if (securityCenrep) + { + errSCenrep = securityCenrep->Get( + KSettingsAutomaticKeyguardTime, screenSaverTimeout); + } + CleanupStack::PopAndDestroy(securityCenrep); + + // Inactivity time in seconds + TInt userInactivity = User::InactivityTime().Int(); + + // Check if screen saver is inactive, if so reset timers + if (errPCenrep == KErrNone && errSCenrep == KErrNone && + isTimeoutEnabled && userInactivity < screenSaverTimeout) + { + User::ResetInactivityTime(); + } + } +} + void CMIDToolkit::BringToForeground() { LCDUI_DEBUG("**RF**"); @@ -513,10 +570,25 @@ if (appUi && appUi->hasStartScreen()) { MMIDComponent* content = iCurrentDisplayable ? iCurrentDisplayable->Component() : NULL; - if (!content || content->Type() != MMIDComponent::ECanvas) + + TBool isCanvas = EFalse; + TBool isCanvasReadyToBlit = EFalse; + if (content) + { + if (content->Type() == MMIDComponent::ECanvas) + { + isCanvas = ETrue; + MMIDCanvas* canvas = static_cast(content); + isCanvasReadyToBlit = canvas->ReadyToBlit(); + } + } + + if (!content || !isCanvas || isCanvasReadyToBlit) { if (iCurrentDisplayable) + { iCurrentDisplayable->DrawNow(); + } appUi->stopStartScreen(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdgr/src/LcdGraphics.cpp --- a/javauis/lcdui_akn/lcdgr/src/LcdGraphics.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdgr/src/LcdGraphics.cpp Fri May 14 15:47:24 2010 +0300 @@ -845,7 +845,13 @@ iSurface->End(iCount); CHECK_BITMAP_LOCK(); - + + // MMIDCanvas::DrawBackground modifies settings of iContext. + // Reset pen and brush settings here, so they + // are re-applied again when needed. + iState = 0; + iContext->SetPenStyle(CGraphicsContext::ENullPen); + iContext->SetBrushStyle(CGraphicsContext::ENullBrush); } TInt CLcdGraphics::DrawPixels diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDCanvas.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDCanvas.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDCanvas.h Fri May 14 15:47:24 2010 +0300 @@ -382,6 +382,7 @@ MMIDTactileFeedbackComponent* TactileFeedbackComponent(); #endif // RD_TACTILE_FEEDBACK + TBool ReadyToBlit() const; // from base class MMIDBufferProcessor @@ -1039,9 +1040,27 @@ * returns EFalse. */ TBool IsNetworkIndicatorEnabledL() const; + +public: + /** + * Handles switching from foreground to + * background and vice versa. Mainly rendering + * context and surfaces need to be relased. + */ + void HandleForeground(TBool aForeground); + +private: + /** States of the first paint */ + enum TFirstPainState { + EFirstPaintNeverOccurred = 0, + EFirstPaintInitiated, + EFirstPaintPrepared, + EFirstPaintOccurred + }; #ifdef RD_JAVA_NGA_ENABLED +private: /** EGL surface types */ typedef enum { @@ -1049,8 +1068,7 @@ EEglWindow, EEglPbuffer } TEglType; - - + // from MAlfBufferProvider public: /** @@ -1080,14 +1098,6 @@ void ContextAboutToSuspend(); void OnActivation(); -public: - /** - * Handles switching from foreground to - * background and vice versa. Mainly rendering - * context and surfaces need to be relased. - */ - void HandleForeground(TBool aForeground); - // From MMIDComponentNgaExtension public: /** @@ -1550,9 +1560,7 @@ // Stores the control on which was press event generated MMIDCustomComponent* iPressedComponent; - -#ifdef RD_JAVA_NGA_ENABLED - + /** * Flag incdicating the foreground status of canvas. * Set to EFalse when some other displayable is made current @@ -1560,6 +1568,8 @@ */ TBool iForeground; +#ifdef RD_JAVA_NGA_ENABLED + /** * CAlfCompositionPixelSource is used for drawing canvas * content when only basic content is drawn @@ -1680,6 +1690,12 @@ * All events, which started outside the canvas have to be ignored. */ TBool iDragEventsStartedInside; + + /** + * Switched after any graphics have been sent to screen. + * Those graphics should be really drawn on the screen. + */ + TInt iFirstPaintState; }; #ifdef RD_JAVA_NGA_ENABLED diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupControl.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupControl.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupControl.h Fri May 14 15:47:24 2010 +0300 @@ -280,8 +280,7 @@ * @param aSelected The new selection state of the element * @param aPostEvent If true, itemStateChanged event is sent to the midlet */ - void CMIDChoiceGroupControl::SelectElementL(TInt aIndex, TBool aSelected, - TBool aPostEvent); + void SelectElementL(TInt aIndex, TBool aSelected, TBool aPostEvent); void UpdateMargins(); void UpdatePopupListAppearanceL(TChoiceGroupModelEvent aEvent); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupListBox.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupListBox.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDChoiceGroupListBox.h Fri May 14 15:47:24 2010 +0300 @@ -70,6 +70,14 @@ void HandlePointerEventL(const TPointerEvent& aPointerEvent); #endif +#ifdef RD_JAVA_S60_RELEASE_9_2 + /** + * Returns index of ChoiceGroup element, which is the first + * visible element in ChoiceGroup from top of Form. + */ + TInt TopVisibleItemIndex(); +#endif // RD_JAVA_S60_RELEASE_9_2 + #ifdef RD_TACTILE_FEEDBACK private: MTouchFeedback* iFeedback; @@ -84,11 +92,21 @@ private: void SetTextColors(); +#ifdef RD_JAVA_S60_RELEASE_9_2 + /** + * Fuction calculates index of element, which is the first + * visible element in ChoiceGroup from top of Form. + */ + void UpdateTopVisibleItemIndex(); +#endif // RD_JAVA_S60_RELEASE_9_2 + private: CMIDChoiceGroupControl* iChoiceControl; #ifdef RD_JAVA_S60_RELEASE_9_2 TBool iUpEventSent; + TBool iHighlight; + TInt iTopVisibleItemIndex; #endif // RD_JAVA_S60_RELEASE_9_2 }; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDCommandList.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDCommandList.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDCommandList.h Fri May 14 15:47:24 2010 +0300 @@ -44,9 +44,11 @@ void Remove(MMIDCommand* aCommand); TInt FindCommandIndex(MMIDCommand* aCommand); - TInt HighestNonMappedPriorityCommand(MMIDCommand::TCommandType aType) const; + TInt HighestNonMappedPriorityCommand(MMIDCommand::TCommandType aType, + TBool aIgnoreForImplicitList = EFalse) const; TInt HighestPriorityCommand(MMIDCommand::TCommandType aType) const; - TInt FindCommandForSoftKey(const CMIDSoftKey& aSoftKey) const; + TInt FindCommandForSoftKey(const CMIDSoftKey& aSoftKey, + TBool aIgnoreForImplicitList = EFalse) const; void UnMapCommands(); TInt Count() const; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDDisplayable.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDDisplayable.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDDisplayable.h Fri May 14 15:47:24 2010 +0300 @@ -428,7 +428,6 @@ void RenewFullscreenCanvasLabelCacheL(); -#ifdef RD_JAVA_NGA_ENABLED /** * In case content is Canvas, notifies it about changed * foreground status. @@ -438,7 +437,6 @@ * @since S60 9.2 */ void HandleCanvasForeground(TBool aForeground); -#endif // RD_JAVA_NGA_ENABLED void HideIndicator(CEikStatusPane* aSp, TInt aId); void HideIndicators(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDEdwin.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDEdwin.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDEdwin.h Fri May 14 15:47:24 2010 +0300 @@ -137,7 +137,7 @@ void ConstructL(const TDesC& aText,TInt aMaxSize); protected: - virtual void AddCommandsToEdwinL(RPointerArray& aArray) = 0; + virtual void AddCommandToEdwinL(MMIDCommand& aCommand) = 0; private: @@ -146,10 +146,10 @@ void SetFEPModeAndCharFormat(); virtual void CreateNonMidletCommandsL(); - void AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResId, TInt aCommandId); - void AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResIdShort, TInt aCommandResIdLong, TInt aCommandId); + void AddCommandToEdwinL(TInt aCommandResId, TInt aCommandId); + void AddCommandToEdwinL(TInt aCommandResIdShort, + TInt aCommandResIdLong, + TInt aCommandId); void RemoveNonMidletCommands(); /* diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDForm.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDForm.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDForm.h Fri May 14 15:47:24 2010 +0300 @@ -498,12 +498,13 @@ */ void DoFeedbackOnFocusChange(CMIDControlItem& aControlItem); +private: #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK /** - * Fuction does feedback when dragging/flicking the form content. + * Function for feedback on kinetic scrolling . */ - void DoFeedbackOnDraggingUp(); - void DoFeedbackOnDraggingDown(); + void UpdateTactileFeedbackDensity(); + void DoScrollingFeedback(); #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK private: //data @@ -579,6 +580,15 @@ * The startup trace should be done only once. */ mutable TBool iStartUpTraceDone; + +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + /** + * Kinetic scrolling tactile feedback + */ + TInt iLastTactileFeedbackPos; + TInt iTactileFeedbackDensity; + TInt iLastPointerEventType; +#endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK }; inline void CMIDForm::Dispose() diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDGaugeItem.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDGaugeItem.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDGaugeItem.h Fri May 14 15:47:24 2010 +0300 @@ -116,7 +116,7 @@ * from the foreground. * @note Animation of non-interactive gauges is started/stopped. */ - void HandleForegroundL(TBool aForeground); + virtual void HandleForegroundL(TBool aForeground); protected: /** @@ -130,13 +130,8 @@ void BaseConstructL(const TDesC& aLabel,TInt aMaxValue, TInt aInitialValue); - void SetStateL(TInt aMaxValue,TInt aValue); - - void DisposeTimer(); void FocusChanged(TDrawNow aDrawNow); - virtual void DoSafeDraw() = 0; - void CreateBitmapsIfNeededL(); /** @@ -226,10 +221,6 @@ /** An array of SVG bitmaps stored in the TLS so that it can be shared amongst gauge items*/ TGaugeFrameData* iGaugeFrameData; - CGaugeTimer* iTimer; - - TBool iIsInForeground; // is application in foreground? - friend class CGaugeTimer; }; @@ -275,6 +266,14 @@ // // From CMIDControlItem // + /** + * Handles event when application switches to/from the foreground. + * + * @param aForeground ETrue to switch to the foreground. EFalse to switch + * from the foreground. + * @note Animation of non-interactive gauges is started/stopped. + */ + void HandleForegroundL(TBool aForeground); void ResolutionChange(TInt aType); /** @@ -295,6 +294,7 @@ void ColorChange(TInt aType); void SetGaugeListenerFromAlert(MMIDGaugeToAlertListner* aGaugeToAlertListner); + private: /** * Ctor @@ -314,6 +314,12 @@ void UpdateMemberVariables(); /** + * Creats new instance of CAknBitmapAnimation for Gauge animation + * and sets it to iBitmapAnimation + */ + void CreateNewBitmapAnimationIfNeededL(); + + /** * setting of size of iBitmapAnimation */ void SetAnimationSize(); @@ -330,6 +336,28 @@ void ColorChangeL(TInt aType); + void DisposeTimer(); + + /** + * From CMIDGaugeItem. + * Starts animation timer (see iTimer) when needed. + * In case that timer is not needed, but has been created, + * it's disposed by this method. + * + * @since S60 v5.0 + */ + void InstallGaugeTimerWhenNeededL(); + + /** + * Indicates that the current skin contains the animation and + * the animation has been instantiated to iBitmapAnimation. + * + * @return ETrue iBitmapAnimation has been created + * and the animation is useful. + * @since S60 v5.0 + */ + TBool BitmapAnimationUsed() const; + private: CEikProgressInfo* iProgressInfo; MMIDGaugeToAlertListner* iGaugeToAlertListner; @@ -342,6 +370,9 @@ // Note that label height has to be added to the y coordinate TPoint iProgressInfoWithLabelHeightTl; // Top left point of the progress info CAknBitmapAnimation* iBitmapAnimation; // Animation for animated Gauge + CGaugeTimer* iTimer; + // Indicates that the application is in foreground + TBool iIsInForeground; }; NONSHARABLE_CLASS(CMIDInteractiveGauge) : public CMIDGaugeItem @@ -410,6 +441,7 @@ TBool iPhysicsScrollingTriggered; }; + #endif // CMIDGAUGEITEM_H // End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDTextBoxEdwin.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDTextBoxEdwin.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDTextBoxEdwin.h Fri May 14 15:47:24 2010 +0300 @@ -64,7 +64,7 @@ * @param aLayout multi line layout info */ virtual void DoLayout(const TRect& aRect); - void AddCommandsToEdwinL(RPointerArray& aArray); + void AddCommandToEdwinL(MMIDCommand& aCommand); private: // Constructors /** diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDTextBoxQueryDialog.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDTextBoxQueryDialog.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDTextBoxQueryDialog.h Fri May 14 15:47:24 2010 +0300 @@ -285,12 +285,12 @@ TPtrC Read() const; void CreateNonMidletCommandsL(); - void AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResIdShort, TInt aCommandResIdLong, TInt aCommandId); - void AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResId, TInt aCommandId); + void AddCommandToEdwinL(TInt aCommandResIdShort, + TInt aCommandResIdLong, + TInt aCommandId); + void AddCommandToEdwinL(TInt aCommandResId, TInt aCommandId); void RemoveNonMidletCommands(); - void AddCommandsToEdwinL(RPointerArray& aArray); + void AddCommandToEdwinL(MMIDCommand& aCommand); void CreatePhoneCallL(); void CreatePasswordTextL(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDTextEditorEdwinCustomDraw.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDTextEditorEdwinCustomDraw.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDTextEditorEdwinCustomDraw.h Fri May 14 15:47:24 2010 +0300 @@ -58,7 +58,7 @@ */ virtual ~CMIDTextEditorEdwinCustomDraw(); -public: // From +public: // From CLafEdwinCustomDrawBase /** * Called by the editor FW in order to draw the background for @@ -112,7 +112,35 @@ const TDesC& aText, const TPoint& aTextOrigin, TInt aExtraPixels) const; - + +#ifdef RD_JAVA_S60_RELEASE_9_2 + /** + * Called by the editor FW in order to draw the the content of + * the editor. + * + * Currently delegates the drawing to the parent custom drawer. + * + * @param aParam Drawing parameters. + * @param aLineInfo The line information. + * @param aFormat The current character format. + * @param aText The content to draw. + * @param aStart + * @param aEnd + * @param aTextOrigin The origin of the text. + * @param aExtraPixels The amount of extra pixels. + * @since S60 5.0 + */ + void DrawText( + const TParam& aParam, + const TLineInfo& aLineInfo, + const TCharFormat& aFormat, + const TDesC& aText, + const TInt aStart, + const TInt aEnd, + const TPoint& aTextOrigin, + TInt aExtraPixels) const; +#endif + /** * Retrieves the system color for the specified color index. * @@ -120,7 +148,7 @@ * @param aDefaultColor The default color for the specified index. * @return The system's (or custom) color for the specified color * index. - * @since S60 5.0 + * @since S60 5.0 */ TRgb SystemColor( TUint aColorIndex, diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/inc/CMIDTextFieldEdwin.h --- a/javauis/lcdui_akn/lcdui/inc/CMIDTextFieldEdwin.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/inc/CMIDTextFieldEdwin.h Fri May 14 15:47:24 2010 +0300 @@ -56,7 +56,7 @@ void PositionChanged(); protected: // from CMIDEdwin - void AddCommandsToEdwinL(RPointerArray& aArray); + void AddCommandToEdwinL(MMIDCommand& aCommand); private: // Constructors /** diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDCanvas.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDCanvas.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDCanvas.cpp Fri May 14 15:47:24 2010 +0300 @@ -119,7 +119,6 @@ #define KZeroSize TSize() - // --------------------------------------------------------------------------- // TBitBltData // BitBlt buffer data datatype. @@ -776,7 +775,7 @@ #ifdef RD_TACTILE_FEEDBACK // --------------------------------------------------------------------------- -// From MMIDCancas. +// From MMIDCanvas. // CMIDCanvas::TactileFeedbackComponent // Retutrns this as tactile feedback component. // --------------------------------------------------------------------------- @@ -787,6 +786,16 @@ } #endif // RD_TACTILE_FEEDBACK + +// --------------------------------------------------------------------------- +// From class MMIDCanvas. +// --------------------------------------------------------------------------- +// +TBool CMIDCanvas::ReadyToBlit() const +{ + return iFirstPaintState != EFirstPaintNeverOccurred; +} + #ifdef RD_JAVA_NGA_ENABLED // --------------------------------------------------------------------------- @@ -841,20 +850,25 @@ break; case EDrwOpcBitBltRect: { + if (iFirstPaintState == EFirstPaintNeverOccurred) + { + iFirstPaintState = EFirstPaintInitiated; + } + const TBitBltData& data = BitBltData(aRead); UpdateL(data.iRect); } break; case EDrwOpcBitBlt: { + if (iFirstPaintState == EFirstPaintNeverOccurred) + { + iFirstPaintState = EFirstPaintInitiated; + } + UpdateL(iViewRect); } break; - case EDrwOpcFirstPaint: - { - java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi()->stopStartScreen(); - } - break; default: User::Leave(KErrNotSupported); break; @@ -941,11 +955,6 @@ Update(rect); } break; - case EDrwOpcFirstPaint: - { - java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi()->stopStartScreen(); - } - break; default: User::Leave(KErrNotSupported); break; @@ -954,9 +963,26 @@ aRead += aRead->Size(); } #endif // CANVAS_DOUBLE_BUFFER - + + if (iFirstPaintState == EFirstPaintNeverOccurred) + { + if (iForeground) + { + // The canvas is current, therefore we can flush + // the graphics and take the start screen snapshot. + iFirstPaintState = EFirstPaintOccurred; + java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi()->stopStartScreen(); + } + else + { + // The window is not visible, the start screen snapshot + // will be taken when the canvas will be set current. + iFirstPaintState = EFirstPaintInitiated; + } + } + DEBUG("- CMIDCanvas::ProcessL"); - + return EFalse; } #endif // RD_JAVA_NGA_ENABLED @@ -1699,7 +1725,14 @@ ELOG1(EJavaUI, "eglSwapBuffers() failed, eglError=%d", eglGetError()); ASSERT(EFalse); } + SetCurrentEglType(EEglNone); + + if (iFirstPaintState != EFirstPaintOccurred) + { + iFirstPaintState = EFirstPaintOccurred; + java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi()->stopStartScreen(); + } } } #endif // RD_JAVA_NGA_ENABLED @@ -2160,6 +2193,7 @@ } if (!consumed && (iFocusedComponent != KComponentFocusedNone) && + (iFocusedComponent < iCustomComponents.Count()) && (iCustomComponents[iFocusedComponent]->IsTouchEnabled())) { consumed = HandlePointerEventInControlsL(aPointerEvent); @@ -2359,6 +2393,12 @@ CustomComponentControl(KComponentMainControl)-> SetFocus(EFalse); } + +#ifdef RD_JAVA_NGA_ENABLED + // Avoid the situation when the content is drawn over the menu + SuspendPixelSource(); +#endif // RD_JAVA_NGA_ENABLED + // Repaint to ensure that fading will be displayed correctly for Alert // or PopupTextBox when DSA is paused. DrawDeferred(); @@ -2762,8 +2802,8 @@ iPointerEventSuppressor->SetMaxTapMove(TSize(pointerMovementInPixels, pointerMovementInPixels)); + iForeground = EFalse; #ifdef RD_JAVA_NGA_ENABLED - iForeground = EFalse; iEglDisplay = EGL_NO_DISPLAY; iEglWindowSurface = EGL_NO_SURFACE; iEglWindowSurfaceContext = EGL_NO_CONTEXT; @@ -3358,8 +3398,6 @@ return enabled; } -#ifdef RD_JAVA_NGA_ENABLED - // --------------------------------------------------------------------------- // CMIDCanvas::HandleForeground // Relases resources in graphics HW (=pixel source or EGL resources) @@ -3369,8 +3407,10 @@ void CMIDCanvas::HandleForeground(TBool aForeground) { DEBUG_INT("CMIDCanvas::HandleForeground(%d) ++", aForeground); + iForeground = aForeground; +#ifdef RD_JAVA_NGA_ENABLED if (!iForeground) { if (IsEglAvailable()) @@ -3388,9 +3428,13 @@ SuspendPixelSource(); } +#endif // RD_JAVA_NGA_ENABLED + DEBUG("CMIDCanvas::HandleForeground --"); } +#ifdef RD_JAVA_NGA_ENABLED + // --------------------------------------------------------------------------- // CMIDCanvas::InitPixelSourceL() // --------------------------------------------------------------------------- @@ -3467,8 +3511,16 @@ return; } - iAlfCompositionPixelSource->ActivateSyncL(); + // ProduceNewFrameL() is called in some cases + // directly from ActivateSyncL(), need to set iFrameReady + // before ActivateSyncL() iFrameReady = ETrue; + TRAPD(err, iAlfCompositionPixelSource->ActivateSyncL()); + if (err != KErrNone) + { + iFrameReady = EFalse; + User::Leave(err); + } if (iPixelSourceSuspended) { @@ -3527,34 +3579,53 @@ // If iDirectContents.Count() > 0, canvas hasn't received // MdcNotifyContentAdded in LCDUI thread yet. + TBool res; if (!iFrameReady || iDirectContents.Count() > 0) { DEBUG("CMIDCanvas::ProduceNewFrameL - FRAME IS NOT READY --"); NotifyMonitor(); - return EFalse; + res = EFalse; } - - NotifyMonitor(); - - TUint8* from = (TUint8*)iFrameBuffer->DataAddress(); - - TBool downScaling = IsDownScaling(iContentSize, iViewRect); - TInt width = downScaling ? iViewRect.Width() : iContentSize.iWidth; - TInt height = downScaling ? iViewRect.Height() : iContentSize.iHeight; - - TUint bytes = width * KBytesPerPixel; - TInt scanLength = CFbsBitmap::ScanLineLength( - iFrameBuffer->SizeInPixels().iWidth, iFrameBuffer->DisplayMode()); - - for (TInt y = 0; y < height; ++y) + else { - Mem::Copy(aBuffer, from, bytes); - aBuffer += iAlfBufferAttributes.iStride; - from += scanLength; + NotifyMonitor(); + + TUint8* from = (TUint8*)iFrameBuffer->DataAddress(); + + TBool downScaling = IsDownScaling(iContentSize, iViewRect); + TInt width = downScaling ? iViewRect.Width() : iContentSize.iWidth; + TInt height = downScaling ? iViewRect.Height() : iContentSize.iHeight; + + TUint bytes = width * KBytesPerPixel; + TInt scanLength = CFbsBitmap::ScanLineLength( + iFrameBuffer->SizeInPixels().iWidth, iFrameBuffer->DisplayMode()); + + for (TInt y = 0; y < height; ++y) + { + Mem::Copy(aBuffer, from, bytes); + aBuffer += iAlfBufferAttributes.iStride; + from += scanLength; + } + + res = ETrue; } - + + if (iFirstPaintState == EFirstPaintInitiated || iFirstPaintState == EFirstPaintPrepared) + { + if (iFirstPaintState == EFirstPaintInitiated) + { + iFirstPaintState = EFirstPaintPrepared; + } + else + { + iFirstPaintState = EFirstPaintOccurred; + java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi()->stopStartScreen(); + } + } + DEBUG("CMIDCanvas::ProduceNewFrameL --"); - return ETrue; + + return res; } // --------------------------------------------------------------------------- @@ -4710,11 +4781,11 @@ glLoadIdentity(); // position texture screen coordinates - pos[0] = (GLshort)iViewRect.iTl.iX; + pos[0] = (GLshort)iViewRect.iTl.iX - iPositionRelativeToScreen.iX; pos[1] = (GLshort)iViewRect.Height() + (height - iViewRect.iBr.iY); pos[2] = pos[0]; pos[3] = (GLshort)height - iViewRect.iBr.iY; - pos[4] = (GLshort)iViewRect.iBr.iX; + pos[4] = (GLshort)iViewRect.iBr.iX - iPositionRelativeToScreen.iX; pos[5] = pos[1]; pos[6] = pos[4]; pos[7] = pos[3]; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupControl.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupControl.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupControl.cpp Fri May 14 15:47:24 2010 +0300 @@ -1254,8 +1254,24 @@ return; } + TInt currentItem = KErrNotFound; +#ifdef RD_JAVA_S60_RELEASE_9_2 + // First check if top visible item was set (only in case that + // ChoiceGroup was panned and now it is partially visible and + // got highlight by starting HW keys interaction). + // If item was set, do not scroll at all. + currentItem = iListBox->TopVisibleItemIndex(); + if (currentItem == KErrNotFound) + { + // Top visible item was not set, i.e. ChoiceGroup already + // have highlight or it is fully visible or it is fully invisible. + currentItem = iListBox->CurrentItemIndex(); + } +#else + currentItem = iListBox->CurrentItemIndex(); +#endif // RD_JAVA_S60_RELEASE_9_2 + // Calculate current listbox item rect - TInt currentItem = iListBox->CurrentItemIndex(); TRect lbitemRect = TRect( iListBox->View()->ItemPos(currentItem), iListBox->View()->ItemSize(currentItem)); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupListBox.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupListBox.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDChoiceGroupListBox.cpp Fri May 14 15:47:24 2010 +0300 @@ -42,7 +42,12 @@ CMIDChoiceGroupListBox::CMIDChoiceGroupListBox(CMIDChoiceGroupControl* aChoiceControl) - : CAknColumnListBox(), iChoiceControl(aChoiceControl) + : CAknColumnListBox() + , iChoiceControl(aChoiceControl) +#ifdef RD_JAVA_S60_RELEASE_9_2 + , iHighlight(EFalse) + , iTopVisibleItemIndex(KErrNotFound) +#endif // RD_JAVA_S60_RELEASE_9_2 { ASSERT(iChoiceControl); } @@ -109,20 +114,65 @@ // First save the currently selected item TInt oldCurrent = iView->CurrentItemIndex(); - // Let the listbox handle the key - TKeyResponse resp = - CAknColumnListBox::OfferKeyEventL(aKeyEvent, aType); + TKeyResponse resp = EKeyWasNotConsumed; - // If the key was up or down, and the current item did not change, - // we were apparently already on the first or last item. - // Return EKeyWasNotConsumed so that the form knows to transfer focus - // BUT ONLY if not used in a popup (otherwise the form will get it and - // move focus under the popup) +#ifdef RD_JAVA_S60_RELEASE_9_2 if (iChoiceControl->ChoiceType() != MMIDChoiceGroup::EPopup) { + if (aType != EEventKey || iHighlight) + { + // Do not pass the EEventKey to ListBox in case of first + // HW key action after highlight was disabled. + resp = CAknColumnListBox::OfferKeyEventL(aKeyEvent, aType); + } + else + { + // This is first HW key action after highlight was disabled: + // highlight should be enabled + UpdateTopVisibleItemIndex(); + if (iTopVisibleItemIndex > KErrNotFound) + { + // First top visible element should be highlighted + iView->SetCurrentItemIndex(iTopVisibleItemIndex); + // Item drawer must know, that highlight should be enabled + // from now. + CColumnListBoxItemDrawer* drawer = ItemDrawer(); + if (drawer) + { + drawer->ClearFlags( + CListItemDrawer::ESingleClickDisabledHighlight); + } + // Report, that current highlighted element changed + ReportEventL(MCoeControlObserver::EEventStateChanged); + resp = EKeyWasConsumed; + DrawNow(); + iTopVisibleItemIndex = KErrNotFound; + } + // Enable highlight flag for this ChoiceGroup, even if top visible + // element wasn't found (ChoiceGroup is now fully invisible). + iHighlight = ETrue; + } + } + else + { + // For popup ChoiceGroup, handle key events in usual way + resp = CAknColumnListBox::OfferKeyEventL(aKeyEvent, aType); + } +#else + // Let the ListBox handle the key + resp = CAknColumnListBox::OfferKeyEventL(aKeyEvent, aType); +#endif // RD_JAVA_S60_RELEASE_9_2 + + if (iChoiceControl->ChoiceType() != MMIDChoiceGroup::EPopup) + { + // If the key was up or down, and the current item did not change, + // we were apparently already on the first or last item. + // Return EKeyWasNotConsumed so that the form knows to transfer focus + // BUT ONLY if not used in a popup (otherwise the form will get it and + // move focus under the popup) TInt newCurrent = iView->CurrentItemIndex(); TBool change = oldCurrent != newCurrent; - TInt lastItemIdx = -1; + TInt lastItemIdx = KErrNotFound; if (iModel) { lastItemIdx = iModel->NumberOfItems() - 1; @@ -349,6 +399,8 @@ if (aPointerEvent.iType == TPointerEvent::EButton1Down) { iUpEventSent = EFalse; + iHighlight = EFalse; + UpdateTopVisibleItemIndex(); } #endif // RD_JAVA_S60_RELEASE_9_2 @@ -417,3 +469,65 @@ } } #endif + +#ifdef RD_JAVA_S60_RELEASE_9_2 +/** + * Returns index of ChoiceGroup element, which is the first + * visible element in ChoiceGroup from top of Form. + * Used in CMIDChoiceGroupControl, which needs to know + * current element for possible scrolling + * (@see CMIDChoiceGroupControl::RequestScrollIfNeededL()). + */ +TInt CMIDChoiceGroupListBox::TopVisibleItemIndex() +{ + return iTopVisibleItemIndex; +} + +/** + * Fuction calculates index of element, which is the first + * visible element in ChoiceGroup from top of Form. + */ +void CMIDChoiceGroupListBox::UpdateTopVisibleItemIndex() +{ + if (!iHighlight) + { + // There is touch interaction, so we need index for element, + // which will be highlighted, when user starts using HW keys + if (iPosition.iY < 0) + { + // ChoiceGroup is now partially visible and its top edge is + // above the Form top edge. + + // Calculate index of first (partially) visible element + iTopVisibleItemIndex = Abs(iPosition.iY) / iView->ItemHeight(); + TRect lbitemRect = TRect( + iView->ItemPos(iTopVisibleItemIndex), + iView->ItemSize(iTopVisibleItemIndex)); + if (lbitemRect.iTl.iY < 0) + { + // Item is really partially visible. + // Because we don't want index of partially visible item, + // move index to next item + iTopVisibleItemIndex++; + } + if (iTopVisibleItemIndex >= iModel->NumberOfItems()) + { + // ChoiceGroup is fully invisible (whole rect is above + // the Form top edge): no element is visible now + iTopVisibleItemIndex = KErrNotFound; + } + } + else + { + // Top item idge is lower than top edge of Form - is visible + iTopVisibleItemIndex = 0; + } + } + else + { + // In case of HW keys interaction, there is no highlight, + // so we don't need highlight any element + iTopVisibleItemIndex = KErrNotFound; + } +} +#endif // RD_JAVA_S60_RELEASE_9_2 diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDCommandList.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDCommandList.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDCommandList.cpp Fri May 14 15:47:24 2010 +0300 @@ -132,13 +132,20 @@ of a particular type that we find will be the highest priority command of that type. */ -TInt CMIDCommandList::HighestNonMappedPriorityCommand(MMIDCommand::TCommandType aType) const +TInt CMIDCommandList::HighestNonMappedPriorityCommand( + MMIDCommand::TCommandType aType, TBool aIgnoreForImplicitList) const { TInt numCommands = Count(); for (TInt i = 0; i < numCommands; i++) { CMIDCommand* cmd = At(i).iCommand; - if ((cmd->CommandType() == aType) && !cmd->IsMappedToSoftKey()) + // In case of IMPLICIT List without highlight, nor OK + // neither ITEM commands are mapped to soft keys. + TBool ignore = aIgnoreForImplicitList + && (cmd->CommandType() == MMIDCommand::EOk + || cmd->CommandType() == MMIDCommand::EItem); + if ((cmd->CommandType() == aType) && !cmd->IsMappedToSoftKey() + && !ignore) { return i; } @@ -151,12 +158,14 @@ Given a softkey, return the index of the highest priority command that is allowed for this softkey. */ -TInt CMIDCommandList::FindCommandForSoftKey(const CMIDSoftKey& aSoftKey) const +TInt CMIDCommandList::FindCommandForSoftKey(const CMIDSoftKey& aSoftKey, + TBool aIgnoreForImplicitList) const { TInt numTypes = aSoftKey.AllowedCommandTypes().Count(); for (TInt i = 0; i < numTypes; i++) { - TInt index = HighestNonMappedPriorityCommand(aSoftKey.AllowedCommandTypes()[i]); + TInt index = HighestNonMappedPriorityCommand( + aSoftKey.AllowedCommandTypes()[i], aIgnoreForImplicitList); if (index != KErrNotFound) { return index; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDDisplayable.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDDisplayable.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDDisplayable.cpp Fri May 14 15:47:24 2010 +0300 @@ -986,9 +986,7 @@ form->HandleForegroundL(aForeground); } -#ifdef RD_JAVA_NGA_ENABLED - HandleCanvasForeground(aForeground); -#endif // RD_JAVA_NGA_ENABLED + HandleCanvasForeground(aForeground); if (aForeground) { @@ -1236,13 +1234,15 @@ { canvasRect.LayoutRect(resultRect, AknLayoutScalable_Avkon::midp_canvas_pane(10).LayoutLine()); } - else //default mode:Softkeys bottom + else { - resultRect = TRect(80,0,560,360);//temp code here.LAF correction needed! - //canvasRect.LayoutRect( resultRect, AknLayoutScalable_Avkon::midp_canvas_pane(9).LayoutLine() ); - +#ifdef RD_JAVA_S60_RELEASE_9_2 + canvasRect.LayoutRect( resultRect, AknLayoutScalable_Avkon::midp_canvas_pane(9).LayoutLine() ); +#else + resultRect = TRect(80,0,560,360); // Layout data not defined in older releases. DEBUG("- CMIDDisplayable::GetCanvasRectFromLaf"); - return resultRect; //Temp code here.LAF correction needed! + return resultRect; +#endif // RD_JAVA_S60_RELEASE_9_2 } } } @@ -1368,9 +1368,7 @@ iActive = aCurrent; const TType type = iContent->Type(); -#ifdef RD_JAVA_NGA_ENABLED HandleCanvasForeground(aCurrent); -#endif // RD_JAVA_NGA_ENABLED if (aCurrent) { @@ -1585,13 +1583,22 @@ CEikStatusPane* pane = iAppUi->StatusPane(); pane->MakeVisible(!iIsFullScreenMode); - java::ui::CoreUiAvkonAppUi* appUi = java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi(); + java::ui::CoreUiAvkonAppUi* appUi = + java::ui::CoreUiAvkonLcdui::getInstance().getJavaUiAppUi(); if (!iIsFullScreenMode && appUi && appUi->hidesIndicators()) { HideIndicators(); } - iCba->MakeVisible(!iIsFullScreenMode); + if (iCba) + { + iCba->MakeVisible(!iIsFullScreenMode); + +#ifdef RD_JAVA_S60_RELEASE_9_2 + // To enable clock pane in landscape after MIDlet was started + iCba->SetBoundingRect(TRect(0, 0, 0, 0)); +#endif // RD_JAVA_S60_RELEASE_9_2 + } // Close fixed toolbar for full screen Canvas. CAknToolbar* toolbar = iAppUi->CurrentFixedToolbar(); @@ -1601,7 +1608,9 @@ } #ifdef RD_SCALABLE_UI_V2 - if ((iActive && iCanvasKeypad) || (!iActive && this->DrawableWindow()->IsFaded() && iCanvasKeypad)) + if ((iActive && iCanvasKeypad) + || (!iActive && this->DrawableWindow()->IsFaded() + && iCanvasKeypad)) { if (iUseOnScreenKeypad) { @@ -2213,6 +2222,21 @@ TInt numSoftKeys = iSoftKeys.Count(); ResetSoftKeysAndCommands(lists); + // Variable implicitList is used when mapping commands to soft keys + // In case of IMPLICIT List with only OK or ITEM commands, + // no command is mapped to soft key and these commands are not + // populated to Options menu + TBool implicitList = EFalse; +#ifdef RD_JAVA_S60_RELEASE_9_2 + if (iContent && iContent->Type() == EList && iContentControl) + { + CMIDList* list = static_cast(iContentControl); + // Important: Set to ETrue only if List is IMPLICIT and there is no highlight + implicitList = (list->ListChoiceType() == MMIDChoiceGroup::EImplicit) && + !list->IsHighlighted(); + } +#endif // RD_JAVA_S60_RELEASE_9_2 + // First map one command to every softkey if possible, // sks must have been ordered correctly, ie right key before // left key or else left key might get BACK cmd if not other @@ -2223,7 +2247,7 @@ { if (lists[j]) { - TInt index = lists[j]->FindCommandForSoftKey(*iSoftKeys[i]); + TInt index = lists[j]->FindCommandForSoftKey(*iSoftKeys[i], implicitList); if (index != KErrNotFound) { TInt commandId = lists[j]->CommandOffset() + index; @@ -2240,14 +2264,26 @@ // Then for the sk that can potentially accept an options menu, // see if the mapped command must be replaced by the options menu // when there is at least one command that has not been mapped to any sk. + // Important: Do not set Options menu in case of IMPLICIT List + // with only OK or ITEM commands TBool needToDisplayMenu = EFalse; for (TInt j = 0; j < numLists && !needToDisplayMenu; j++) { if (lists[j]) { + // Looping trough all commands for (TInt i = 0; i < lists[j]->Count() && !needToDisplayMenu; i++) { - needToDisplayMenu = !CommandIsMappedToSk(lists[j]->At(i).iCommand); + CMIDCommand* cmd = lists[j]->At(i).iCommand; + // In case that displayable is IMPLICIT List, we need to know, + // if it has only OK or ITEM commands + if (!(implicitList && (cmd->CommandType() == MMIDCommand::EOk || + cmd->CommandType() == MMIDCommand::EItem))) + { + // There is at least one command, which is not mapped yet, + // so it will be populated to Options menu. + needToDisplayMenu = !CommandIsMappedToSk(cmd); + } } } } @@ -3082,7 +3118,6 @@ DEBUG("- CMIDDisplayable::RenewFullscreenCanvasLabelCacheL"); } -#ifdef RD_JAVA_NGA_ENABLED void CMIDDisplayable::HandleCanvasForeground(TBool aForeground) { if (iContent && iContentControl && @@ -3093,7 +3128,6 @@ canvas->HandleForeground(aForeground); } } -#endif // RD_JAVA_NGA_ENABLED void CMIDDisplayable::HandleApplicationBackground() { @@ -3104,9 +3138,7 @@ iCanvasKeypad->HandleApplicationBackground(); } -#ifdef RD_JAVA_NGA_ENABLED - HandleCanvasForeground(EFalse); -#endif // RD_JAVA_NGA_ENABLED + HandleCanvasForeground(EFalse); } void CMIDDisplayable::ProcessMSKCommandL() diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDEdwin.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDEdwin.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDEdwin.cpp Fri May 14 15:47:24 2010 +0300 @@ -1189,35 +1189,30 @@ to either the displayable or to the item. Commands will be processed in ProcessCommandL(). */ void CMIDEdwin::CreateNonMidletCommandsL() { - RPointerArray array; - CleanupClosePushL(array); - if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EPhoneNumber) && !(iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_PB_FETCH_NUMBER_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_NUMBER_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchPhoneNumber); - AddCommandToArrayL(array, R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); + AddCommandToEdwinL(R_MIDP_PB_FETCH_NUMBER_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_NUMBER_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchPhoneNumber); + AddCommandToEdwinL(R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); } if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EPhoneNumber) && (iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); + AddCommandToEdwinL(R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); } if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EMailAddr) && !(iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_PB_FETCH_EMAIL_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_EMAIL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchEmailAddress); + AddCommandToEdwinL(R_MIDP_PB_FETCH_EMAIL_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_EMAIL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchEmailAddress); } - AddCommandsToEdwinL(array); - - CleanupStack::PopAndDestroy(&array); } /** -Creates and adds new command to array based on shot & long label resource ids +Creates and adds new command to edwin based on shot & long label resource ids and other parameters. */ -void CMIDEdwin::AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResIdShort, TInt aCommandResIdLong, TInt aCommandId) +void CMIDEdwin::AddCommandToEdwinL(TInt aCommandResIdShort, + TInt aCommandResIdLong, + TInt aCommandId) { TBuf<64> shortLabel; iEikonEnv->ReadResourceL(shortLabel, aCommandResIdShort); @@ -1230,17 +1225,16 @@ STATIC_CAST(CMIDCommand*,cmd)->SetObserver(this); - aArray.AppendL(cmd); + AddCommandToEdwinL(*cmd); CleanupStack::Pop(cmd); } /** -Creates and adds new command to array, short label is the same as long label. +Creates and adds new command to edwin, short label is the same as long label. */ -void CMIDEdwin::AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResId, TInt aCommandId) +void CMIDEdwin::AddCommandToEdwinL(TInt aCommandResId, TInt aCommandId) { - AddCommandToArrayL(aArray, aCommandResId, aCommandResId, aCommandId); + AddCommandToEdwinL(aCommandResId, aCommandResId, aCommandId); } /** This method is called from the destructor and removes diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDForm.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDForm.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDForm.cpp Fri May 14 15:47:24 2010 +0300 @@ -2328,7 +2328,11 @@ #ifdef RD_TACTILE_FEEDBACK iFeedback = MTouchFeedback::Instance(); -#endif +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + UpdateTactileFeedbackDensity(); +#endif // RD_JAVA_ADVANCED_TACTILE_FEEDBACK +#endif // RD_TACTILE_FEEDBACK + //index of pointed control is set to not active iIndexPointedControl=-1; @@ -3800,6 +3804,10 @@ } UpdatePhysics(); + +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + UpdateTactileFeedbackDensity(); +#endif // RD_JAVA_ADVANCED_TACTILE_FEEDBACK } TBool CMIDForm::TryDetectLongTapL(const TPointerEvent &aPointerEvent) @@ -4088,6 +4096,10 @@ void CMIDForm::HandlePhysicsPointerEventL(const TPointerEvent& aPointerEvent) { +#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK + iLastPointerEventType = aPointerEvent.iType; +#endif + if (iPhysics && iPhysics->CanBeStopped()) { switch (aPointerEvent.iType) @@ -4161,7 +4173,10 @@ if (!iPreventPhysicsScrolling && iPointedControl && iPointedControl->iMMidItem && iPointedControl->iMMidItem->Type() == MMIDComponent::ETextField) { - if ((Abs(dragX) > iPhysics->DragThreshold()) && (Abs(dragY) < iPhysics->DragThreshold())) + // If physics scrolling is not ongoing (abs(dragY) < DragTreshold) + // then stop flicking and forward event to the item (iPreventPhysicsScrolling = ETrue). + if ((Abs(dragX) > iPhysics->DragThreshold()) && (Abs(dragY) < iPhysics->DragThreshold() + && !iPanningOngoing)) { iPreventPhysicsScrolling = ETrue; } @@ -4172,8 +4187,9 @@ { iPanningOngoing = ETrue; iHighlightTimer->Cancel(); + // Start panning from aPointerEvent.iPosition with iPhysics->DragThreshold() margin + iLastDragPosition = aPointerEvent.iPosition; iPhysics->SetPanningPosition(iLastDragPosition - aPointerEvent.iPosition); - iLastDragPosition = aPointerEvent.iPosition; //Forward one drag event to the focused textField or Gauge when panning is triggered if ((iFocused != KErrNotFound) && IsTextFieldItem(ControlItem(iFocused))) @@ -4218,6 +4234,7 @@ { ForwardPointerEventToItemL(aPointerEvent); } + #endif // RD_JAVA_S60_RELEASE_9_2 break; } @@ -4225,24 +4242,22 @@ // EButton1Up case TPointerEvent::EButton1Up: { - TPoint distance = iStartPosition - aPointerEvent.iPosition; - if (Abs(distance.iY) > iPhysics->DragThreshold() && !iPreventPhysicsScrolling) + // If physics scrolling is ongoing then start flicking + // and forward event to the item. + if (iPanningOngoing && !iPreventPhysicsScrolling) { + TPoint distance = iStartPosition - aPointerEvent.iPosition; iFlickOngoing = iPhysics->StartFlick(distance, iStartTime); - if (!iUpEventSent) - { - ForwardPointerEventToItemL(aPointerEvent); - iUpEventSent = ETrue; - } } - else + + // If physics scrolling is not ongoing then only + // forward event to the item. + if (!iUpEventSent) { - if (!iUpEventSent) - { - ForwardPointerEventToItemL(aPointerEvent); - iUpEventSent = ETrue; - } + ForwardPointerEventToItemL(aPointerEvent); + iUpEventSent = ETrue; } + iPanningOngoing = EFalse; iCanDragFocus = EFalse; break; @@ -4290,21 +4305,6 @@ void CMIDForm::HandlePhysicsScroll(TInt aScroll, TBool aDrawNow, TUint /*aFlags*/) { -#ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK - //Dragging/flicking of Form content should give tactile feedback. - //This implementation is similar to native List: during dragging/flicking - //feedback is given when new item appears ont top/bottom of Form - //visible area. - // - //First we have to reset current visibility for all items in Form. - TInt count = iItems.Count(); - for (TInt i=0; i 0) - { - //scrolling up (pointer dragged down) - DoFeedbackOnDraggingUp(); - } - if (aScroll < 0) - { - //scrolling down (pointer dragged up) - DoFeedbackOnDraggingDown(); - } + DoScrollingFeedback(); #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK } @@ -4403,75 +4394,59 @@ } #ifdef RD_JAVA_ADVANCED_TACTILE_FEEDBACK -void CMIDForm::DoFeedbackOnDraggingUp() +void CMIDForm::UpdateTactileFeedbackDensity() { - TInt count = iItems.Count(); - //If dragging/flicking reaches the first/last item in Form, - //tactile feedback shouldn't be given. There should be only - //'bounce' effect, when first/last item goes back to to/bottom - //of screen. Flag firstOrLastItemReached determines this case. - //NOTE: feedback for 'bounce' is implemented in CAknPhysics. - TBool firstOrLastItemReached = EFalse; - for (TInt i = 0; i < count; i++) + TAknLayoutRect layoutRect; + layoutRect.LayoutRect(TRect(), AknLayoutScalable_Avkon:: + list_single_heading_pane(0).LayoutLine()); + iTactileFeedbackDensity = layoutRect.Rect().Height(); +} + +void CMIDForm::DoScrollingFeedback() +{ + TRect formRect(Rect()); + TInt topEdgePos = iScroll; + TInt bottomEdgePos = iScroll + HeightOfAllItems(); + // Calculate distance between current Form content position + // and previous position, where last feedback happened. + TInt lastFeedbackDistanceY = Abs(iLastTactileFeedbackPos - iScroll); + TTouchLogicalFeedback feedbackType(ETouchFeedbackNone); + if (lastFeedbackDistanceY >= iTactileFeedbackDensity) { - //Try find first item from top, which changed its visibility - CMIDControlItem& ci = ControlItem(i); - CMIDControlItem& last = ControlItem(count-1); - TBool visibility = RectPartiallyVisible(ci.Rect()); - //In case of 'bounce' effect, there shouldn't be any feedback - //on dragging/flicking (as in native side): - if (RectFullyVisible(last.Rect())) - { - firstOrLastItemReached = ETrue; - } - if (i == 0 && RectFullyVisible(ci.Rect())) + if ((topEdgePos < formRect.iTl.iY) + && (bottomEdgePos > formRect.iBr.iY)) { - firstOrLastItemReached = ETrue; - } - if (ci.GetVisibilityInForm() != visibility) - { - //item changed its visibility form invisible to visible - if (visibility && !firstOrLastItemReached) - { - //if there isn't 'bounce' effect, do feedback - iFeedback->InstantFeedback(ETouchFeedbackSensitiveList); - break; - } + // If top (or bottom) edge of the content is outside + // of visible area of Form, do feedback every time. + feedbackType = ETouchFeedbackSensitiveList; } + else if (iLastPointerEventType != TPointerEvent::EButton1Up) + { + // Begining or end of the content reached (i.e. top or bottom + // egde of the contont is now visible): feedback is given + // only if user do panning. No feedback, if touch release + // happened. + feedbackType = ETouchFeedbackSensitiveList; + } + // Store the position of the content. + iLastTactileFeedbackPos = iScroll; } -} - -void CMIDForm::DoFeedbackOnDraggingDown() -{ - TInt count = iItems.Count(); - //If dragging/flicking reaches the first/last item in Form, - //tactile feedback shouldn't be given. There should be only - //'bounce' effect, when first/last item goes back to to/bottom - //of screen. Flag firstOrLastItemReached determines this case. - //NOTE: feedback for 'bounce' is implemented in CAknPhysics. - TBool firstOrLastItemReached = EFalse; - for (TInt i = count-1; i >= 0; i--) + + if (iFeedback && feedbackType != ETouchFeedbackNone) { - CMIDControlItem& ci = ControlItem(i); - CMIDControlItem& first = ControlItem(0); - TBool visibility = RectPartiallyVisible(ci.Rect()); - if (RectFullyVisible(first.Rect())) + if (iLastPointerEventType != TPointerEvent::EButton1Up) { - firstOrLastItemReached = ETrue; + iFeedback->EnableFeedbackForControl(this, ETrue, ETrue); } - if (i == count-1 && RectFullyVisible(ci.Rect())) + else { - firstOrLastItemReached = ETrue; + // Disable audion feedback on flicking (i.e. user don't pan by + // touch input). + iFeedback->EnableFeedbackForControl(this, ETrue, EFalse); } - if (ci.GetVisibilityInForm() != visibility) - { - //item changed its visibility form invisible to visible - if (visibility && !firstOrLastItemReached) - { - iFeedback->InstantFeedback(ETouchFeedbackSensitiveList); - break; - } - } + // Do the feedback if needed. + iFeedback->InstantFeedback(this, feedbackType); } } #endif //RD_JAVA_ADVANCED_TACTILE_FEEDBACK + diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDGaugeItem.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDGaugeItem.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDGaugeItem.cpp Fri May 14 15:47:24 2010 +0300 @@ -133,11 +133,9 @@ CMIDGaugeItem::CMIDGaugeItem(CMIDUIManager* aUIManager) : CMIDControlItem(EDefault, aUIManager), iIndefiniteState(EIncrementalIdle), - iGaugeFrameData(NULL), - iTimer(NULL) + iGaugeFrameData(NULL) { iMMidItem = this; - iIsInForeground = ETrue; } CMIDGaugeItem::~CMIDGaugeItem() @@ -175,7 +173,13 @@ iMaxValue = aMaxValue; iValue = aInitialValue; - SetStateL(aMaxValue,aInitialValue); + iIndefinite = (aMaxValue == EIndefinite) ? ETrue : EFalse; + + if (iIndefinite) + { + iIndefiniteState = aInitialValue; + iValue = 0; + } DEBUG("CMIDGaugeItem::BaseConstructL >"); } @@ -698,7 +702,6 @@ } } - void CMIDGaugeItem::ColorChange(TInt aType) { // call default implementation @@ -720,62 +723,9 @@ } } -void CMIDGaugeItem::HandleForegroundL(TBool aForeground) -{ - // synchronize foreground flag - iIsInForeground = aForeground; - - // if continuous-running ni-gauge is in foreground and it's timer - // is not created then create it else if gauge is in background - // and if it is inserted in form then dispose it's timer - if (iIsInForeground) - { - if ((iIndefiniteState == EContinuousRunning) && (!iTimer)) - { - iTimer = CGaugeTimer::NewL(*this); - iTimer->After(TTimeIntervalMicroSeconds32(KDelayInMicroSeconds)); - } - } - else if (iForm) - { - DisposeTimer(); - } -} - -void CMIDGaugeItem::SetStateL(TInt aMaxValue,TInt aValue) +void CMIDGaugeItem::HandleForegroundL(TBool /*aForeground*/) { - iIndefinite = (aMaxValue == EIndefinite) ? ETrue : EFalse; - - if (iIndefinite) - { - iIndefiniteState = aValue; - iValue = 0; - switch (aValue) - { - case EContinuousIdle: - case EIncrementalIdle: - DisposeTimer(); - break; - case EContinuousRunning: - if (!iTimer) - { - iTimer = CGaugeTimer::NewL(*this); - iTimer->After(TTimeIntervalMicroSeconds32(KDelayInMicroSeconds)); - } - break; - case EIncrementalUpdating: - DisposeTimer(); - break; - default: - ASSERT(EFalse); - } - } - else - { - } - // - // We're now back in normal mode - // + // Empty implementation. Inherited by CMIDNonInteractiveGauge. } #ifdef RD_SCALABLE_UI_V2 @@ -801,14 +751,6 @@ return (iCommandList->Count() > 0 || !IsNonFocusing()); } -void CMIDGaugeItem::DisposeTimer() -{ - if (iTimer) - iTimer->Cancel(); - delete iTimer; - iTimer = NULL; -} - void CMIDGaugeItem::FocusChanged(TDrawNow aDrawNow) { CMIDControlItem::FocusChanged(aDrawNow); @@ -894,7 +836,9 @@ // CMIDNonInteractiveGauge::CMIDNonInteractiveGauge(CMIDUIManager* aUIManager) : CMIDGaugeItem(aUIManager), - iBitmapAnimation(NULL) + iBitmapAnimation(NULL), + iTimer(NULL), + iIsInForeground(ETrue) { SetFocusing(EFalse); } @@ -926,6 +870,30 @@ iWaitGaugeRect.Rect().iTl.iY - formRect.iTl.iY + ItemContentBottomMargin(); } + +// --------------------------------------------------------------------------- +// CMIDNonInteractiveGauge::InstallGaugeTimerWhenNeededL +// If continuous-running NonInteractiveGauge is in foreground, +// appended to form, bitmap animation is not used and +// animation timer is not created then create it. +// In all other cases the timer is not needed and disposed. +// --------------------------------------------------------------------------- +// +void CMIDNonInteractiveGauge::InstallGaugeTimerWhenNeededL() +{ + if (iForm && iIsInForeground && + iIndefiniteState == EContinuousRunning && + !BitmapAnimationUsed() && !iTimer) + { + iTimer = CGaugeTimer::NewL(*this); + iTimer->After(TTimeIntervalMicroSeconds32(KDelayInMicroSeconds)); + } + else + { + DisposeTimer(); + } +} + void CMIDNonInteractiveGauge::ConstructProgressInfoL() { ASSERT(!iProgressInfo); @@ -955,31 +923,36 @@ { // indefinite gauge will not be updated when it is inserted in form // and the form is sent to background - TBool updateGauge = (iForm) ? iIsInForeground : ETrue; + TBool updateGauge = (iForm) ? iIsInForeground : EFalse; // update gauge state TInt oldIndefiniteState = iIndefiniteState; iIndefiniteState = aValue; + DisposeTimer(); + + if (BitmapAnimationUsed() && aValue != EContinuousRunning) + { + // Stoping of animation. + iBitmapAnimation->CancelAnimation(); + delete iBitmapAnimation; + iBitmapAnimation = NULL; + } + else if (!BitmapAnimationUsed() && aValue == EContinuousRunning) + { + // Create new bitmap animation + CreateNewBitmapAnimationIfNeededL(); + } switch (iIndefiniteState) { case EContinuousIdle: - iValue = 0; - DisposeTimer(); - break; case EIncrementalIdle: iValue = 0; - DisposeTimer(); break; case EContinuousRunning: - if (!iTimer && updateGauge) - { - iTimer = CGaugeTimer::NewL(*this); - iTimer->After(TTimeIntervalMicroSeconds32(KDelayInMicroSeconds)); - } + InstallGaugeTimerWhenNeededL(); break; case EIncrementalUpdating: - DisposeTimer(); // update gauge's state if (updateGauge) @@ -1005,13 +978,13 @@ iGaugeToAlertListner->UpdateGaugeInAlertL(iValue); } - // eventually notify alert dialog that indefinite state changed + // Eventually notify alert dialog that indefinite state changed if (iGaugeToAlertListner && (iIndefiniteState != oldIndefiniteState)) { iGaugeToAlertListner->GaugeTypeInAlertChangedL(); } - // redraw gauge if it should be updated or if it's type changed + // Redraw gauge if it should be updated or if it's type changed if (updateGauge || (iIndefiniteState != oldIndefiniteState)) { DoSafeDraw(); @@ -1019,6 +992,15 @@ } else { + // Bitmap animation is used with indefinite only + if (BitmapAnimationUsed()) + { + // Stoping of animation. + iBitmapAnimation->CancelAnimation(); + delete iBitmapAnimation; + iBitmapAnimation = NULL; + } + iValue = aValue; if (iGaugeToAlertListner) @@ -1056,6 +1038,16 @@ } else { + // If old value was indefinite and new one is not + // recreate progress bar, otherwise progress bar wont be updated + if (iMaxValue == EIndefinite && iMaxValue != aMaxValue) + { + // update progressinfo + delete iProgressInfo; + iProgressInfo = NULL; + ConstructProgressInfoL(); + } + // no timer needed for definite gauge DisposeTimer(); @@ -1101,6 +1093,11 @@ { if (iIndefinite) { + if (BitmapAnimationUsed()) + { + return 2; // to be able to access iBitmapAnimation + } + return 1; // we will draw the gauge in our Draw() method } else @@ -1116,6 +1113,11 @@ case 0: return iLabelControl; case 1: + if (BitmapAnimationUsed()) + { + return iBitmapAnimation; + } + return iProgressInfo; default: return NULL; @@ -1141,8 +1143,7 @@ { // If Gauge animated in current skin, is drawn by iBitmapAnimation. // Otherwise is drawn in this block of code. - if ((!iBitmapAnimation) || (!(iBitmapAnimation->BitmapAnimData())) || - (!(iBitmapAnimation->BitmapAnimData()->FrameArray().Count()> 0))) + if (!BitmapAnimationUsed()) { CFbsBitmap* bitmap = NULL; CFbsBitmap* bitmapMask = NULL; @@ -1238,8 +1239,7 @@ CMIDControlItem::SizeChanged(); // If Gauge is animated, the animation will be resized. - if (iBitmapAnimation && iBitmapAnimation->BitmapAnimData() && - iBitmapAnimation->BitmapAnimData()->FrameArray().Count()> 0) + if (BitmapAnimationUsed()) { // Stoping of animation. iBitmapAnimation->CancelAnimation(); @@ -1281,6 +1281,14 @@ #endif //RD_SCALABLE_UI_V2 } +void CMIDNonInteractiveGauge::DisposeTimer() +{ + if (iTimer) + iTimer->Cancel(); + delete iTimer; + iTimer = NULL; +} + void CMIDNonInteractiveGauge::DoSafeDraw() { if (iForm && DrawableWindow()) @@ -1295,6 +1303,14 @@ } } +void CMIDNonInteractiveGauge::HandleForegroundL(TBool aForeground) +{ + // synchronize foreground flag + iIsInForeground = aForeground; + + InstallGaugeTimerWhenNeededL(); +} + #ifdef RD_SCALABLE_UI_V2 void CMIDNonInteractiveGauge::HandlePointerEventL(const TPointerEvent& aPointerEvent) { @@ -1387,48 +1403,40 @@ // Set aAnimation like iBitmapAnimation iBitmapAnimation = aBitmapAnimation; + + // Timer is not needed when iBitmapAnimation is used + DisposeTimer(); } + void CMIDNonInteractiveGauge::ItemAddedToFormL() { // call parent's implementation CMIDGaugeItem::ItemAddedToFormL(); - CAknBitmapAnimation* bitmapAnimation = CAknBitmapAnimation::NewL(); - CleanupStack::PushL(bitmapAnimation); - - TRect waitGaugeRect; - - // setting of window of bitmapAnimation to this - bitmapAnimation->SetContainerWindowL(*this); - - // costruction of bitmapAnimation by ID of Gauge - bitmapAnimation->ConstructFromSkinL(GetAknsItemID()); + // Creates new bitmapAnimation, it sets bitmapAnimation to IBitmapAnimation + CreateNewBitmapAnimationIfNeededL(); - CleanupStack::Pop(bitmapAnimation); - - // If bitmapAnimation exist, set bitmapAnimation to IBitmapAnimation. - if (bitmapAnimation && bitmapAnimation->BitmapAnimData()->FrameArray().Count() > 0) + // If bitmapAnimation does not exist create bitmap in TLS. + if (!BitmapAnimationUsed()) { - ConstructAnimation(bitmapAnimation); - } - // Else create Bitmap in TLS. - else - { + // Create Bitmap in TLS. CreateBitmapsIfNeededL(); } - // initially assume that gauge is in foreground so that indefinite ni-gauges - // can be updated and redrawn (gauge can be inserted into form after form - // is moved to foreground -> no notification to gauge) - HandleForegroundL(ETrue); + // Install timer when needed and able to be installed. + InstallGaugeTimerWhenNeededL(); } + void CMIDNonInteractiveGauge::ItemRemovedFromForm() { // call parent's implementation CMIDGaugeItem::ItemRemovedFromForm(); + // Timer is not needed when item is removed from form. + DisposeTimer(); + // if indefinite ni-gauge is removed from form then no notifications // about moving to foreground/background are sent and so in order to ensure // full functionality it is assumed that gauge is in foreground @@ -1436,7 +1444,8 @@ if (err != KErrNone) { - DEBUG_INT("CMIDNonInteractiveGauge::ItemRemovedFromForm() - Exception from HandleForegroundL. Error = %d ", err); + DEBUG_INT("CMIDNonInteractiveGauge::ItemRemovedFromForm() - \ + Exception from HandleForegroundL. Error = %d ", err); } // When NonInteractiveGauge was removed from form, then animation @@ -1448,6 +1457,35 @@ } } +void CMIDNonInteractiveGauge::CreateNewBitmapAnimationIfNeededL() +{ + if (iMaxValue == EIndefinite && iIndefiniteState == EContinuousRunning + && DrawableWindow()) + { + // creating new instance of CAknBitmapAnimation + // for Gauge animation in new skin + CAknBitmapAnimation* bitmapAnimation = CAknBitmapAnimation::NewL(); + CleanupStack::PushL(bitmapAnimation); + + // setting of window of bitmapAnimation to this + bitmapAnimation->SetContainerWindowL(*this); + + // costruction of bitmapAnimation by ID of Gauge + bitmapAnimation->ConstructFromSkinL(GetAknsItemID()); + CleanupStack::Pop(bitmapAnimation); + + TBool bitmapFrameCount = + bitmapAnimation ? + bitmapAnimation->BitmapAnimData()->FrameArray().Count() > 0 : EFalse; + + // If bitmapAnimation exist, set bitmapAnimation to IBitmapAnimation. + if (bitmapFrameCount) + { + ConstructAnimation(bitmapAnimation); + } + } +} + void CMIDNonInteractiveGauge::ColorChange(TInt aType) { // The original CMIDNonInteractiveGauge::ColorChange is using @@ -1456,57 +1494,30 @@ TRAPD(creatingErr, ColorChangeL(aType)); if (creatingErr != KErrNone) { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception. Error = %d ", creatingErr); + DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - \ + Exception. Error = %d ", creatingErr); } } void CMIDNonInteractiveGauge::ColorChangeL(TInt aType) { // stopping and deleting iBitmapAnimation - if (iBitmapAnimation && iBitmapAnimation->BitmapAnimData()->FrameArray().Count()> 0) + if (BitmapAnimationUsed()) { iBitmapAnimation->CancelAnimation(); delete iBitmapAnimation; iBitmapAnimation = NULL; } - // creating new instance of CAknBitmapAnimation for Gauge animation in new skin - CAknBitmapAnimation* bitmapAnimation = NULL; - TRAPD(creatingErr, bitmapAnimation = CAknBitmapAnimation::NewL()); - if (creatingErr != KErrNone) - { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception from CAknBitmapAnimation::NewL. Error = %d ", creatingErr); - } - - // CleanupStack::PushL can not be in TRAPD macro. - CleanupStack::PushL(bitmapAnimation); + // Creates new bitmapAnimation, it sets bitmapAnimation to IBitmapAnimation + CreateNewBitmapAnimationIfNeededL(); - // setting of window of bitmapAnimation to this - TRAPD(setErr, bitmapAnimation->SetContainerWindowL(*this)); - if (setErr != KErrNone) - { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception from CAknBitmapAnimation::SetContainerWindowL. Error = %d ", setErr); - } - - // costruction of bitmapAnimation by ID of Gauge - TRAPD(constructErr, bitmapAnimation->ConstructFromSkinL(GetAknsItemID())); - if (constructErr != KErrNone) - { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception from CAknBitmapAnimation::ConstructFromSkinL. Error = %d ", constructErr); - } - - CleanupStack::Pop(bitmapAnimation); - - // If bitmapAnimation exist, it sets bitmapAnimation to IBitmapAnimation and - // sets correct size iBitmapAnimation. - if (bitmapAnimation->BitmapAnimData()->FrameArray().Count()> 0) + // If bitmapAnimation exist sets correct size iBitmapAnimation. + if (BitmapAnimationUsed()) { // call of parent's implementation CMIDGaugeItem::ColorChange(aType); - // setting bitmapAnimation to IBitmapAnimation - ConstructAnimation(bitmapAnimation); - // settting correct size iBitmapAnimation SetAnimationSize(); @@ -1514,15 +1525,23 @@ TRAPD(errStart, iBitmapAnimation->StartAnimationL()); if (errStart != KErrNone) { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception from CAknBitmapAnimation::StartAnimationL(). Error = %d ", errStart); + DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - \ + Exception from CAknBitmapAnimation::StartAnimation. \ + Error = %d ", errStart); } // Setting of animation mode (cycle). - TRAPD(errSet, iBitmapAnimation->Animation().SetPlayModeL(CBitmapAnimClientData::ECycle)); + TRAPD(errSet, iBitmapAnimation->Animation().SetPlayModeL( + CBitmapAnimClientData::ECycle)); if (errSet != KErrNone) { - DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - Exception from RBitmapAnim::SetPlayModeL(). Error = %d ", errSet); + DEBUG_INT("CMIDNonInteractiveGauge::ColorChange() - \ + Exception from RBitmapAnim::SetPlayMode. \ + Error = %d ", errSet); } + + // Timer is useless when iBitmapAnimation is used + DisposeTimer(); } else { @@ -1614,6 +1633,12 @@ return KAknsIIDNone; } +TBool CMIDNonInteractiveGauge::BitmapAnimationUsed() const +{ + return iBitmapAnimation && iBitmapAnimation->BitmapAnimData() && + iBitmapAnimation->BitmapAnimData()->FrameArray().Count() > 0; +} + // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDList.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDList.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDList.cpp Fri May 14 15:47:24 2010 +0300 @@ -629,6 +629,21 @@ } DoDeleteElement(aIndex); + +#ifdef RD_JAVA_S60_RELEASE_9_2 + if (!iItems.Count()) + { + // Last element was deleted, highlight is removed at all. + // In case of IMPLICIT List without highlight, CBA has to be updated, + // so that no ITEM or OK commands are mapped to soft keys + // or populated to Options menu. + iHighlight = EFalse; + if (iChoiceType == MMIDChoiceGroup::EImplicit && iDisplayable) + { + iDisplayable->InitializeCbasL(); + } + } +#endif // RD_JAVA_S60_RELEASE_9_2 } /** @@ -659,6 +674,18 @@ iIconArray->Delete(firstIcon, iIconArray->Count() - firstIcon); SetMaxIconSize(); + +#ifdef RD_JAVA_S60_RELEASE_9_2 + // All items are deleted, highlight is removed. + // In case of IMPLICIT List without highlight, CBA has to be updated, + // so that no ITEM or OK commands are mapped to soft keys + // or populated to Options menu. + iHighlight = EFalse; + if (iChoiceType == MMIDChoiceGroup::EImplicit && iDisplayable) + { + iDisplayable->InitializeCbasL(); + } +#endif // RD_JAVA_S60_RELEASE_9_2 } /** @@ -1221,6 +1248,10 @@ iChoiceType == MMIDChoiceGroup::EImplicit) { iHighlight = ETrue; + if (iDisplayable) + { + iDisplayable->InitializeCbasL(); + } } #endif // RD_JAVA_S60_RELEASE_9_2 @@ -1334,6 +1365,10 @@ (iLongTapDetected && aPointerEvent.iType == TPointerEvent::EButton1Up))) { iHighlight = EFalse; + if (iDisplayable) + { + iDisplayable->InitializeCbasL(); + } } #endif // RD_JAVA_S60_RELEASE_9_2 @@ -1444,7 +1479,17 @@ if (iSelectCommandId == MMIDCommand::ENullCommand) { //setSelectCommand(null) has been called by application +#ifndef RD_JAVA_S60_RELEASE_9_2 iDisplayable->ShowOkOptionsMenuL(); +#else + // If ShowOkOptionsMenuL returned false then we can try to open screen(help) menu + if (iHighlight && iDisplayable && !iDisplayable->ShowOkOptionsMenuL() && + aEventType == MEikListBoxObserver::EEventEnterKeyPressed) + { + // Invoke the SCREEN or HELP command with the highest priority if exists + iDisplayable->HandleHighestPriorityScreenOrHelpCommandL(); + } +#endif // RD_JAVA_S60_RELEASE_9_2 } else { //either default select cmd - which we may not know @@ -1731,6 +1776,28 @@ listBox->SetListBoxObserver(this); listBox->ScrollBarFrame()->SetScrollBarFrameObserver(this); + // We need avoid stretching list's elements. This prevents problems + // with icon overlaying and bad wrapping. + if(type < EDouble2Style) + { + CEikColumnListBox* clb = + (static_cast(listBox)); + if(clb) + { + clb->EnableStretching(EFalse); + } + } + else + { + CEikFormattedCellListBox* fclb = + (static_cast(listBox)); + if(fclb) + { + fclb->EnableStretching(EFalse); + } + } + + if (iListBox) {//Remove icon array before deleting old list box if (iListBoxType < EDouble2Style) diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextBoxEdwin.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextBoxEdwin.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextBoxEdwin.cpp Fri May 14 15:47:24 2010 +0300 @@ -179,12 +179,9 @@ } -void CMIDTextBoxEdwin::AddCommandsToEdwinL(RPointerArray& aArray) +void CMIDTextBoxEdwin::AddCommandToEdwinL(MMIDCommand& aCommand) { - for (TInt i = 0; i < aArray.Count(); i++) - { - STATIC_CAST(CMIDDisplayable*, iDisplayable)->AddCommandL(aArray[i]); - } + STATIC_CAST(CMIDDisplayable*, iDisplayable)->AddCommandL(&aCommand); } // --------------------------------------------------------- diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextBoxQueryDialog.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextBoxQueryDialog.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextBoxQueryDialog.cpp Fri May 14 15:47:24 2010 +0300 @@ -1286,35 +1286,30 @@ to either the displayable or to the item. Commands will be processed in ProcessCommandL(). */ void CMIDTextBoxQueryDialog::CreateNonMidletCommandsL() { - RPointerArray array; - CleanupClosePushL(array); - if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EPhoneNumber) && !(iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_PB_FETCH_NUMBER_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_NUMBER_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchPhoneNumber); - AddCommandToArrayL(array, R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); + AddCommandToEdwinL(R_MIDP_PB_FETCH_NUMBER_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_NUMBER_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchPhoneNumber); + AddCommandToEdwinL(R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); } if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EPhoneNumber) && (iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); + AddCommandToEdwinL(R_MIDP_CREATE_CALL_SHORT_COMMAND_TEXT, R_MIDP_CREATE_CALL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandCreatePhoneCall); } if (((iConstraints & MMIDTextField::EConstraintMask) == MMIDTextField::EMailAddr) && !(iConstraints & MMIDTextField::EUneditable)) { - AddCommandToArrayL(array, R_MIDP_PB_FETCH_EMAIL_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_EMAIL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchEmailAddress); + AddCommandToEdwinL(R_MIDP_PB_FETCH_EMAIL_SHORT_COMMAND_TEXT, R_MIDP_PB_FETCH_EMAIL_COMMAND_TEXT, CMIDEdwinUtils::EMenuCommandFetchEmailAddress); } - AddCommandsToEdwinL(array); - - CleanupStack::PopAndDestroy(&array); } /** -Creates and adds new command to array based on shot & long label resource ids +Creates and adds new command to edwin based on shot & long label resource ids and other parameters. */ -void CMIDTextBoxQueryDialog::AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResIdShort, TInt aCommandResIdLong, TInt aCommandId) +void CMIDTextBoxQueryDialog::AddCommandToEdwinL(TInt aCommandResIdShort, + TInt aCommandResIdLong, + TInt aCommandId) { TBuf<64> shortLabel; iEikonEnv->ReadResourceL(shortLabel, aCommandResIdShort); @@ -1326,17 +1321,17 @@ STATIC_CAST(CMIDCommand*,cmd)->SetObserver(this); - aArray.AppendL(cmd); + AddCommandToEdwinL(*cmd); CleanupStack::Pop(cmd); } /** -Creates and adds new command to array, short label is the same as long label. +Creates and adds new command to edwin, short label is the same as long label. */ -void CMIDTextBoxQueryDialog::AddCommandToArrayL(RPointerArray& aArray, - TInt aCommandResId, TInt aCommandId) +void CMIDTextBoxQueryDialog::AddCommandToEdwinL(TInt aCommandResId, + TInt aCommandId) { - AddCommandToArrayL(aArray, aCommandResId, aCommandResId, aCommandId); + AddCommandToEdwinL(aCommandResId, aCommandResId, aCommandId); } /** This method is called from the destructor and removes @@ -1369,12 +1364,9 @@ } } -void CMIDTextBoxQueryDialog::AddCommandsToEdwinL(RPointerArray& aArray) +void CMIDTextBoxQueryDialog::AddCommandToEdwinL(MMIDCommand& aCommand) { - for (TInt i = 0; i < aArray.Count(); i++) - { - STATIC_CAST(CMIDDisplayable*, iDisplayable)->AddCommandL(aArray[i]); - } + STATIC_CAST(CMIDDisplayable*, iDisplayable)->AddCommandL(&aCommand); } void CMIDTextBoxQueryDialog::CreatePhoneCallL() diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextEditor.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextEditor.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextEditor.cpp Fri May 14 15:47:24 2010 +0300 @@ -526,13 +526,13 @@ } // --------------------------------------------------------------------------- -// CMIDTextEditor::SetCaretXY +// CMIDTextEditor::SetCaretXYL // (other items are commented in the header file) // --------------------------------------------------------------------------- // void CMIDTextEditor::SetCaretXYL(TInt aX, TInt aY) { - DEBUG_INT2("CMIDTextEditor::SetCaretXY +, aX=%d, aY=%d", aX, aY); + DEBUG_INT2("CMIDTextEditor::SetCaretXYL +, aX=%d, aY=%d", aX, aY); // Requested point should be already recalculated to be relative // to editor position on canvas. @@ -540,14 +540,14 @@ // If position will be found in formatted text, posInfo will be filled // with desired informations. TTmPosInfo2 posInfo; - + if (iTextEdwin->TextLayout()->FindXyPos(pos, posInfo)) { // Position was found. Try to set cursor to found position. iTextEdwin->SetCursorPosL(posInfo.iDocPos.iPos, EFalse); } - DEBUG("CMIDTextEditor::SetCaretXY -"); + DEBUG("CMIDTextEditor::SetCaretXYL -"); } // --------------------------------------------------------------------------- @@ -582,7 +582,7 @@ iTextEdwin->SetCursorVisible(EFalse); } else if (iEditingStateIndicator->EnabledState() == - CMIDEditingStateIndicator::EIndicatorStateRelative) + CMIDEditingStateIndicator::EIndicatorStateRelative) { // Enable the custom indicators as in Avkon if not controlled // by the client application @@ -1076,7 +1076,7 @@ // if the constraint modifier PASSWORD is set. Passwords are single // line editors due to CMIDEdwinUtils::CPasswordText implementation. if (aMultiline == iTextEdwin->IsWrapEnabled() || - iConstraints & MMIDTextField::EPassword) + iConstraints & MMIDTextField::EPassword) { DEBUG("CMIDTextEditor::SetMultilineL -, ignoring request"); @@ -1103,6 +1103,8 @@ // Text has been changed so inform the editor window that // it needs to redraw itself again. iTextEdwin->HandleTextChangedL(); + // Cursor position handling is done in CMIDTextEditorEdwin + iTextEdwin->SetCursorPosL(iTextEdwin->CursorPos(), EFalse); DEBUG("CMIDTextEditor::SetMultilineL -"); } @@ -1386,7 +1388,6 @@ { TSize size = EditorSize(); TInt newEditorWindowHeight = iTextEdwin->EditorWindowHeight(); - if (size.iHeight != newEditorWindowHeight) { SetEditorSize(size.iWidth, newEditorWindowHeight); @@ -1929,7 +1930,7 @@ DEBUG_INT2( "CMIDTextEditor::UpdateIndicatorPosition, indicatorPos.X=%d, \ -indicatorPos.Y=%d", x, y); + indicatorPos.Y=%d", x, y); iEditingStateIndicator->SetPosition(x, y); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwin.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwin.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwin.cpp Fri May 14 15:47:24 2010 +0300 @@ -257,11 +257,6 @@ // Part of transparency workaround. Set drawing not active. iDrawInvoked = EFalse; - if (iObserver) - { - iObserver->NotifyInputAction( - MMIDTextEditorObserver::EActionPaintRequest); - } DEBUG("CMIDTextEditorEdwin::Draw -"); } @@ -530,6 +525,7 @@ // void CMIDTextEditorEdwin::HandleResourceChange(TInt aType) { + CCoeControl::HandleResourceChange(aType); // Notification about language change if (aType == KEikInputLanguageChange) { @@ -584,8 +580,7 @@ // Check if cursor has moved. This must be done because // currently edwin does not report cursor position movement // when text is changed due to user input. - if ((iVisibleContentHeight != newVisiblecontentHeight) && - (iCursorPosForAction != CursorPos())) + if (iVisibleContentHeight != newVisiblecontentHeight) { event |= MMIDTextEditorObserver::EActionScrollbarChange; // Reported, reset here to avoid multiple notifications. diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwinCustomDraw.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwinCustomDraw.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextEditorEdwinCustomDraw.cpp Fri May 14 15:47:24 2010 +0300 @@ -122,6 +122,47 @@ aExtraPixels); } +#ifdef RD_JAVA_S60_RELEASE_9_2 +// --------------------------------------------------------------------------- +// CMIDTextEditorEdwinCustomDraw::DrawText +// (other items were commented in the header file) +// --------------------------------------------------------------------------- +// +void CMIDTextEditorEdwinCustomDraw::DrawText( + const TParam& aParam, + const TLineInfo& aLineInfo, + const TCharFormat& aFormat, + const TDesC& aText, + const TInt aStart, + const TInt aEnd, + const TPoint& aTextOrigin, + TInt aExtraPixels) const +{ + // If transparency is enabled, check that if draw has not been invoked + // yet and issue redraw in that case. This removes the issue with + // transparency so that the old content does not cause corruption to + // the new text drawn on top of the old content. Otherwise it is ok + // to draw the text because opaque background draws on top of the old + // content in the editor. + + if (iEdwin.IsTransparent() && !iEdwin.DrawOngoing()) + { + iEdwin.Redraw(); + return; + } + + iParentDraw.DrawText( + aParam, + aLineInfo, + aFormat, + aText, + aStart, + aEnd, + aTextOrigin, + aExtraPixels); +} +#endif + // --------------------------------------------------------------------------- // CMIDTextEditorEdwinCustomDraw::SystemColor // (other items were commented in the header file) diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_akn/lcdui/src/CMIDTextFieldEdwin.cpp --- a/javauis/lcdui_akn/lcdui/src/CMIDTextFieldEdwin.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_akn/lcdui/src/CMIDTextFieldEdwin.cpp Fri May 14 15:47:24 2010 +0300 @@ -252,10 +252,7 @@ } -void CMIDTextFieldEdwin::AddCommandsToEdwinL(RPointerArray& aArray) +void CMIDTextFieldEdwin::AddCommandToEdwinL(MMIDCommand& aCommand) { - for (TInt i = 0; i < aArray.Count(); i++) - { - STATIC_CAST(CMIDTextFieldItem*, iTextFieldItem)->AddCommandL(aArray[i]); - } + STATIC_CAST(CMIDTextFieldItem*, iTextFieldItem)->AddCommandL(&aCommand); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mid/ui/DirectGraphics.java --- a/javauis/lcdui_qt/src/com/nokia/mid/ui/DirectGraphics.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/com/nokia/mid/ui/DirectGraphics.java Fri May 14 15:47:24 2010 +0300 @@ -11,14 +11,15 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.mid.ui; import javax.microedition.lcdui.Image; -public interface DirectGraphics { +public interface DirectGraphics +{ /** * Constant for horizontal image flipping. @@ -286,7 +287,7 @@ * @since 1.0 */ public void drawImage(Image img, int x, int y, int anchor, - int manipulation); + int manipulation); /** * Copies or draws the pixel data directly to graphics context to specific @@ -331,8 +332,8 @@ * @since 1.0 */ public void drawPixels(byte[] pixels, byte[] transparencyMask, int offset, - int scanlength, int x, int y, int width, int height, - int manipulation, int format); + int scanlength, int x, int y, int width, int height, + int manipulation, int format); /** * Copies or draws the pixel data directly to graphics context to specific @@ -384,8 +385,8 @@ * @since 1.0 */ public void drawPixels(int[] pixels, boolean transparency, int offset, - int scanlength, int x, int y, int width, int height, - int manipulation, int format); + int scanlength, int x, int y, int width, int height, + int manipulation, int format); /** * Copies or draws the pixel data directly to graphics context to specific @@ -436,8 +437,8 @@ * @since 1.0 */ public void drawPixels(short[] pixels, boolean transparency, int offset, - int scanlength, int x, int y, int width, int height, - int manipulation, int format); + int scanlength, int x, int y, int width, int height, + int manipulation, int format); /** * Draws a closed polygon defined by arrays of x and y coordinates. Each @@ -459,7 +460,7 @@ * @since 1.0 */ public void drawPolygon(int[] xPoints, int xOffset, int[] yPoints, - int yOffset, int nPoints, int argbColor); + int yOffset, int nPoints, int argbColor); /** * Draws closed triangle defined by coordinates. @@ -481,7 +482,7 @@ * @since 1.0 */ public void drawTriangle(int x1, int y1, int x2, int y2, int x3, - int y3, int argbColor); + int y3, int argbColor); /** * Fills a closed polygon defined by arrays of x and y coordinates. @@ -505,7 +506,7 @@ * @since 1.0 */ public void fillPolygon(int[] xPoints, int xOffset, int[] yPoints, - int yOffset, int nPoints, int argbColor); + int yOffset, int nPoints, int argbColor); /** * Fills closed triangle defined by coordinates. @@ -527,7 +528,7 @@ * @since 1.0 */ public void fillTriangle(int x1, int y1, int x2, int y2, int x3, - int y3, int argbColor); + int y3, int argbColor); /** * Gets the alpha component of the current color. @@ -594,7 +595,7 @@ * @since 1.0 */ public void getPixels(byte[] pixels, byte[] transparencyMask, int offset, - int scanlength, int x, int y, int width, int height, int format); + int scanlength, int x, int y, int width, int height, int format); /** * Gets the pixel values of an image to an array defined by format @@ -637,7 +638,7 @@ * @since 1.0 */ public void getPixels(int[] pixels, int offset, int scanlength, int x, - int y, int width, int height, int format); + int y, int width, int height, int format); /** * Gets the pixel values of an image to an array of short values from @@ -683,7 +684,7 @@ * negative, or format is wrong or unsupported */ public void getPixels(short[] pixels, int offset, int scanlength, int x, - int y, int width, int height, int format); + int y, int width, int height, int format); /** * Sets the current color to the specified ARGB value. All subsequent diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mid/ui/DirectUtils.java --- a/javauis/lcdui_qt/src/com/nokia/mid/ui/DirectUtils.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/com/nokia/mid/ui/DirectUtils.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.mid.ui; @@ -25,9 +25,11 @@ /** * DirectUtils class contains utility methods for lcdui classes. */ -public final class DirectUtils { +public final class DirectUtils +{ - private DirectUtils() { + private DirectUtils() + { } /** @@ -39,7 +41,8 @@ * @return mutable image */ public static Image createImage(byte[] imageData, int imageOffset, - int imageLength) { + int imageLength) + { Image src = Image.createImage(imageData, imageOffset, imageLength); Image ret = Image.createImage(src.getWidth(), src.getHeight()); ret.getGraphics().drawImage(src, 0, 0, 0); @@ -54,7 +57,8 @@ * @param argbColor fill color * @return mutable image */ - public static Image createImage(int width, int height, int argbColor) { + public static Image createImage(int width, int height, int argbColor) + { Image ret = Image.createImage(width, height); Graphics g = ret.getGraphics(); LCDUIInvoker.getDirectGraphics(g).setARGBColor(argbColor); @@ -68,7 +72,8 @@ * @param g graphics object * @return DirectGraphics object */ - public static DirectGraphics getDirectGraphics(Graphics g) { + public static DirectGraphics getDirectGraphics(Graphics g) + { return LCDUIInvoker.getDirectGraphics(g); } @@ -80,7 +85,8 @@ * @param height font height * @return custom font */ - public static Font getFont(int face, int style, int height) { + public static Font getFont(int face, int style, int height) + { return LCDUIInvoker.getFreeSizedFont(face, style, height); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mid/ui/FullCanvas.java --- a/javauis/lcdui_qt/src/com/nokia/mid/ui/FullCanvas.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/com/nokia/mid/ui/FullCanvas.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.mid.ui; @@ -36,7 +36,8 @@ * normal key codes reported in Canvas are also reported. The keys tied with * Command area do not report any key events if the are is visible. */ -public abstract class FullCanvas extends Canvas { +public abstract class FullCanvas extends Canvas +{ private static final String FULLCANVAS_COMMAND_EXCEPTION = "Commands are not possible in FullCanvas."; @@ -96,7 +97,8 @@ * or higher, replaced by * javax.microedition.lcdui.Canvas.setFullScreenMode(boolean). */ - public FullCanvas() { + public FullCanvas() + { super(); super.setFullScreenMode(true); } @@ -104,7 +106,8 @@ /* (non-Javadoc) * @see javax.microedition.lcdui.Canvas#setFullScreenMode(boolean) */ - public void setFullScreenMode(boolean fullScreen) { + public void setFullScreenMode(boolean fullScreen) + { // ignore } @@ -116,7 +119,8 @@ * javax.microedition.lcdui.Canvas.addCommand(Command). * @throws IllegalStateException */ - public void addCommand(javax.microedition.lcdui.Command cmd) { + public void addCommand(javax.microedition.lcdui.Command cmd) + { throw new IllegalStateException(FULLCANVAS_COMMAND_EXCEPTION); } @@ -129,7 +133,8 @@ * @throws IllegalStateException */ public void setCommandListener( - javax.microedition.lcdui.CommandListener listener) { + javax.microedition.lcdui.CommandListener listener) + { throw new IllegalStateException(FULLCANVAS_COMMAND_EXCEPTION); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mj/impl/nokialcdui/ItemControlStateChangeListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/lcdui_qt/src/com/nokia/mj/impl/nokialcdui/ItemControlStateChangeListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package com.nokia.mj.impl.nokialcdui; + +import javax.microedition.lcdui.Item; +import org.eclipse.swt.widgets.Control; + +public interface ItemControlStateChangeListener +{ + + public void notifyControlAvailable(Control ctrl,Item item); + + public void notifyControlDisposed(Item item); + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mj/impl/nokialcdui/LCDUIInvoker.java --- a/javauis/lcdui_qt/src/com/nokia/mj/impl/nokialcdui/LCDUIInvoker.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/com/nokia/mj/impl/nokialcdui/LCDUIInvoker.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.mj.impl.nokialcdui; @@ -25,7 +25,8 @@ /** * Abstract class providing the interface to internal LCDUI resources. */ -public abstract class LCDUIInvoker { +public abstract class LCDUIInvoker +{ /** * Invoker instance. @@ -37,7 +38,8 @@ * * @param invoker In */ - public static void setInvoker(LCDUIInvoker invoker) { + public static void setInvoker(LCDUIInvoker invoker) + { invokerInstance = invoker; } @@ -46,10 +48,11 @@ * * @param runnable a runnable */ - public static void eSWTUIThreadRunnerSyncExec(Runnable runnable) { + public static void eSWTUIThreadRunnerSyncExec(Runnable runnable) + { invokerInstance.doESWTUIThreadRunnerSyncExec(runnable); - } - + } + /** * Returns main eSWT Control that is used by LCDUI Displayable or Item. * @@ -57,35 +60,67 @@ * @return eSWT Control that is used by Displayable/Item or null if no * Control is available. */ - public static org.eclipse.swt.widgets.Control getEswtControl(Object lcduiObject) { + public static org.eclipse.swt.widgets.Control getEswtControl(Object lcduiObject) + { return invokerInstance.doGetEswtControl(lcduiObject); } + public static void setItemControlStateChangeListener(ItemControlStateChangeListener listener,Item item) + { + invokerInstance.doSetItemControlStateChangeListener(listener,item); + } + /** * Returns eSWT Display that is used by LCDUI. * * @return eSWT Display that is used by LCDUI. */ - public static org.eclipse.swt.widgets.Display getEswtDisplay() { + public static org.eclipse.swt.widgets.Display getEswtDisplay() + { return invokerInstance.doGetEswtDisplay(); } - public static org.eclipse.swt.graphics.Image getEswtImage(Image img) { - return invokerInstance.doGetEswtImage(img); + /** + * Returns eSWT Image from an LCDUI Image. The returned object is an already + * existing eSWT Image object contained within the LCDUI Image, so calling + * this function is efficient. + * + * @param img - LCDUI Image object. + * @return eSWT Image. + */ + public static org.eclipse.swt.graphics.Image getEswtImage(Image img) + { + return invokerInstance.doGetEswtImage(img); } /** + * Creates LCDUI Image from an eSWT Image. The returned object is a new + * LCDUI Image object created from the eSWT Image, so this method is not + * as efficient as getEswtImage. + * + * @param img - eSWT Image object. + * @return LCDUI Image. + */ + public static Image createLcduiImage(org.eclipse.swt.graphics.Image img) + { + return invokerInstance.doGetLcduiImage(img); + } + + + /** * Get the DirectGraphics object associated with this Graphics object. * * @param g Graphics object * @return DirectGraphics object */ - public static DirectGraphics getDirectGraphics(Graphics g) { + public static DirectGraphics getDirectGraphics(Graphics g) + { return invokerInstance.doGetDirectGraphics(g); } - public static GraphicsContext getGc(Graphics g) { - return invokerInstance.doGetGc(g); + public static GraphicsContext getGc(Graphics g) + { + return invokerInstance.doGetGc(g); } /** @@ -96,7 +131,8 @@ * @param height font height * @return the requested Font */ - public static Font getFreeSizedFont(int face, int style, int height) { + public static Font getFreeSizedFont(int face, int style, int height) + { return invokerInstance.doGetFreeSizedFont(face, style, height); } @@ -107,7 +143,8 @@ * @param suppressKeys suppress game keys * @return framebuffer image */ - public static void initGameCanvas(Object canvas, boolean suppressKeys) { + public static void initGameCanvas(Object canvas, boolean suppressKeys) + { invokerInstance.doInitGameCanvas(canvas, suppressKeys); } @@ -117,21 +154,24 @@ * @param canvas GameCanvas object * @return Graphics object */ - public static Object getGraphics(Object canvas) { + public static Object getGraphics(Object canvas) + { return invokerInstance.doGetGraphics(canvas); } - public static Object getFlushLock(Object graphics) { - return invokerInstance.doGetFlushLock(graphics); + public static Object getFlushLock(Object graphics) + { + return invokerInstance.doGetFlushLock(graphics); } - + /** * Get game key states. * * @param canvas GameCanvas object * @return key states */ - public static int getKeyStates(Object canvas) { + public static int getKeyStates(Object canvas) + { return invokerInstance.doGetKeyStates(canvas); } @@ -141,7 +181,8 @@ * @param canvas GameCanvas object * @param graphics Graphics object */ - public static void renderGraphics(Object canvas, Object graphics) { + public static void renderGraphics(Object canvas, Object graphics) + { invokerInstance.doRenderGraphics(canvas, graphics); } @@ -155,7 +196,8 @@ * @param height clip height */ public static void flushGraphics(Object canvas, - int x, int y, int width, int height) { + int x, int y, int width, int height) + { invokerInstance.doFlushGraphics(canvas, x, y, width, height); } @@ -165,7 +207,8 @@ * @param key property key * @return property value */ - public static String getDynamicProperty(String key) { + public static String getDynamicProperty(String key) + { return invokerInstance.doGetDynamicProperty(key); } @@ -175,23 +218,27 @@ public static boolean detectCollision(Image image1, int transform1, int p1x, int p1y, int r1x1, int r1y1, int r1x2, int r1y2, Image image2, int transform2, int p2x, int p2y, - int r2x1, int r2y1, int r2x2, int r2y2) { + int r2x1, int r2y1, int r2x2, int r2y2) + { return invokerInstance.doDetectCollision(image1, transform1, p1x, p1y, - r1x1, r1y1, r1x2, r1y2, - image2, transform2, p2x, p2y, - r2x1, r2y1, r2x2, r2y2); + r1x1, r1y1, r1x2, r1y2, + image2, transform2, p2x, p2y, + r2x1, r2y1, r2x2, r2y2); } // MMAPI support protected abstract org.eclipse.swt.widgets.Control doGetEswtControl( - Object lcduiObj); + Object lcduiObj); protected abstract org.eclipse.swt.widgets.Display doGetEswtDisplay(); protected abstract org.eclipse.swt.graphics.Image doGetEswtImage(Image img); + protected abstract Image doGetLcduiImage(org.eclipse.swt.graphics.Image img); + + protected abstract void doSetItemControlStateChangeListener(ItemControlStateChangeListener listener,Item item); // DirectGraphics support @@ -207,7 +254,7 @@ boolean suppressKeys); protected abstract Object doGetGraphics(Object canvas); - + protected abstract Object doGetFlushLock(Object graphics); protected abstract int doGetKeyStates(Object canvas); @@ -215,7 +262,7 @@ protected abstract void doRenderGraphics(Object canvas, Object graphics); protected abstract void doFlushGraphics(Object canvas, - int x, int y, int width, int height); + int x, int y, int width, int height); protected abstract String doGetDynamicProperty(String key); @@ -223,9 +270,9 @@ int r1x1, int r1y1, int r1x2, int r1y2, Image image2, int transform2, int p2x, int p2y, int r2x1, int r2y1, int r2x2, int r2y2); - + // TactileFeedback support protected abstract void doESWTUIThreadRunnerSyncExec(Runnable runnable); - + } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/com/nokia/mj/impl/properties/lcduib/LcduiDynamicProperty.java --- a/javauis/lcdui_qt/src/com/nokia/mj/impl/properties/lcduib/LcduiDynamicProperty.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/com/nokia/mj/impl/properties/lcduib/LcduiDynamicProperty.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.mj.impl.properties.lcduib; @@ -26,12 +26,14 @@ * "com.nokia.key.scancode"
            * "com.nokia.key.modifier" */ -public final class LcduiDynamicProperty implements SystemPropertyProvider { +public final class LcduiDynamicProperty implements SystemPropertyProvider +{ /* (non-Javadoc) * @see com.nokia.mj.impl.rt.support.SystemPropertyProvider#getProperty(java.lang.String) */ - public String getProperty(String propertyName) { + public String getProperty(String propertyName) + { // Set the property value. return LCDUIInvoker.getDynamicProperty(propertyName); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Alert.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Alert.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Alert.java Fri May 14 15:47:24 2010 +0300 @@ -34,7 +34,8 @@ *

          • modal - user has to choose a command and dismiss the dialog * explicitly
          • */ -public class Alert extends Screen { +public class Alert extends Screen +{ /** * Timeout constant used for modal Alerts. @@ -47,7 +48,7 @@ * The default command triggered when dismissing an Alert. */ public static final Command DISMISS_COMMAND = - new Command("", Command.OK, 0); + new Command("", Command.OK, 0); /** * Default command listener. @@ -91,7 +92,8 @@ * * @param aTitle the title string */ - public Alert(String aTitle) { + public Alert(String aTitle) + { this(aTitle, null, null, null); } @@ -103,7 +105,8 @@ * @param image the image * @param type the alert type */ - public Alert(String title, String text, Image image, AlertType type) { + public Alert(String title, String text, Image image, AlertType type) + { super(title); construct(); this.type = type; @@ -119,7 +122,8 @@ * * @return custom eSWT dialog shell */ - Shell eswtConstructShell(int style) { + Shell eswtConstructShell(int style) + { topShell = super.eswtConstructShell(style); Shell dialogShell = new Shell(topShell, style | SWT.DIALOG_TRIM | SWT.RESIZE); return dialogShell; @@ -128,7 +132,8 @@ /** * Creates content Composite. */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { Composite comp = super.eswtConstructContent(SWT.VERTICAL); FormLayout layout = new FormLayout(); @@ -164,18 +169,20 @@ return comp; } - int eswtGetPreferredContentHeight() { + int eswtGetPreferredContentHeight() + { int ret = getContentComp().computeSize(SWT.DEFAULT, SWT.DEFAULT).y; // Point imgSize = (eswtImgLabel != null - // ? eswtImgLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT) : new Point(0, 0)); + // ? eswtImgLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT) : new Point(0, 0)); // int ret = Math.max( - // Math.min( - // eswtScrolledText.computeSize(topShell.getClientArea().width - imgSize.x, SWT.DEFAULT).y, - // topShell.getClientArea().height / 2), - // imgSize.y); + // Math.min( + // eswtScrolledText.computeSize(topShell.getClientArea().width - imgSize.x, SWT.DEFAULT).y, + // topShell.getClientArea().height / 2), + // imgSize.y); - if (eswtProgressBar != null && eswtProgressBar.isVisible()) { + if(eswtProgressBar != null && eswtProgressBar.isVisible()) + { ret += eswtProgressBar.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; } return ret; @@ -192,19 +199,23 @@ */ void eswtUpdateProgressbar(Composite parent, boolean indeterminate, - boolean visible) { + boolean visible) + { // Only dispose old ProgressBar if it has wrong style - if (eswtProgressBar != null) { + if(eswtProgressBar != null) + { boolean isIndeterminate = (eswtProgressBar.getStyle() & SWT.INDETERMINATE) != 0; - if (indeterminate != isIndeterminate) { + if(indeterminate != isIndeterminate) + { eswtProgressBar.setLayoutData(null); eswtProgressBar.dispose(); eswtProgressBar = null; } } // create new ProgressBar - if (eswtProgressBar == null) { + if(eswtProgressBar == null) + { int newStyle = indeterminate ? SWT.INDETERMINATE : SWT.NONE; eswtProgressBar = new ProgressBar(parent, newStyle); eswtProgressBar.setLayoutData(eswtProgbarLD); @@ -213,7 +224,8 @@ imageLD.bottom = new FormAttachment(eswtProgressBar); } // set Progressbar visibility - if (eswtProgressBar != null) { + if(eswtProgressBar != null) + { eswtProgbarLD.top = (visible ? null : new FormAttachment(100)); eswtProgressBar.setVisible(visible); } @@ -226,8 +238,10 @@ * @param maxValue the maximum value * @param selValue the value */ - void eswtSetProgressbarValues(int minValue, int maxValue, int selValue) { - if (eswtProgressBar != null) { + void eswtSetProgressbarValues(int minValue, int maxValue, int selValue) + { + if(eswtProgressBar != null) + { eswtProgressBar.setMinimum(minValue); eswtProgressBar.setMaximum(maxValue); eswtProgressBar.setSelection(selValue); @@ -237,24 +251,26 @@ /* (non-Javadoc) * @see javax.microedition.lcdui.Displayable#handleShowEvent() */ - void eswtHandleShowCurrentEvent() { + void eswtHandleShowCurrentEvent() + { super.eswtHandleShowCurrentEvent(); topShell.addListener(SWT.Resize, resizeListener); // add key filter for scrollable text composite org.eclipse.swt.widgets.Display.getCurrent().addFilter( - SWT.KeyDown, keyListener); + SWT.KeyDown, keyListener); org.eclipse.swt.widgets.Display.getCurrent().addFilter( - SWT.Traverse, keyListener); + SWT.Traverse, keyListener); org.eclipse.swt.widgets.Display.getCurrent().addFilter( - SWT.MouseUp, keyListener); + SWT.MouseUp, keyListener); resetTimerTask(true); } /* (non-Javadoc) * @see javax.microedition.lcdui.Displayable#handleHideEvent() */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { super.eswtHandleHideCurrentEvent(); topShell.removeListener(SWT.Resize, resizeListener); @@ -263,11 +279,11 @@ // remove key filter for scrollable text composite org.eclipse.swt.widgets.Display.getCurrent().removeFilter( - SWT.KeyDown, keyListener); + SWT.KeyDown, keyListener); org.eclipse.swt.widgets.Display.getCurrent().removeFilter( - SWT.Traverse, keyListener); + SWT.Traverse, keyListener); org.eclipse.swt.widgets.Display.getCurrent().removeFilter( - SWT.MouseUp, keyListener); + SWT.MouseUp, keyListener); } @@ -276,7 +292,8 @@ * * @param next next displayable */ - void setNextDisplayable(Displayable next) { + void setNextDisplayable(Displayable next) + { nextDisplayable = next; } @@ -286,23 +303,30 @@ * @param type the alert type * @return the default image based on the type or null if the type is null */ - private static int getDefaultImageType(final AlertType type) { - if (type == AlertType.ERROR) { - return LabelExtension.STANDARDICON_ERROR; + private static int getDefaultImageType(final AlertType type) + { + if(type == AlertType.ERROR) + { + return LabelExtension.STANDARDICON_ERROR; } - else if (type == AlertType.WARNING) { - return LabelExtension.STANDARDICON_WARNING; + else if(type == AlertType.WARNING) + { + return LabelExtension.STANDARDICON_WARNING; } - else if (type == AlertType.INFO) { - return LabelExtension.STANDARDICON_INFO; + else if(type == AlertType.INFO) + { + return LabelExtension.STANDARDICON_INFO; } - else if (type == AlertType.CONFIRMATION) { - return LabelExtension.STANDARDICON_CONFIRMATION; + else if(type == AlertType.CONFIRMATION) + { + return LabelExtension.STANDARDICON_CONFIRMATION; } - else if (type == AlertType.ALARM) { - return LabelExtension.STANDARDICON_ALARM; + else if(type == AlertType.ALARM) + { + return LabelExtension.STANDARDICON_ALARM; } - else { + else + { return LabelExtension.STANDARDICON_ALARM; } @@ -314,23 +338,30 @@ * @param type the alert type * @return the default text based on the type */ - private static String getDefaultText(final AlertType type) { - if (type == AlertType.ERROR) { + private static String getDefaultText(final AlertType type) + { + if(type == AlertType.ERROR) + { return MsgRepository.ALERT_DEFAULT_TEXT_ERROR; } - else if (type == AlertType.WARNING) { + else if(type == AlertType.WARNING) + { return MsgRepository.ALERT_DEFAULT_TEXT_WARNING; } - else if (type == AlertType.INFO) { + else if(type == AlertType.INFO) + { return MsgRepository.ALERT_DEFAULT_TEXT_INFO; } - else if (type == AlertType.CONFIRMATION) { + else if(type == AlertType.CONFIRMATION) + { return MsgRepository.ALERT_DEFAULT_TEXT_CONFIRMATION; } - else if (type == AlertType.ALARM) { + else if(type == AlertType.ALARM) + { return MsgRepository.ALERT_DEFAULT_TEXT_ALARM; } - else { + else + { return MsgRepository.ALERT_DEFAULT_TEXT_ALERT; } } @@ -338,7 +369,8 @@ /** * Returns if the Alert is modal. */ - private boolean isModal() { + private boolean isModal() + { return ((timeout == FOREVER) || (getNumCommands() > 1) || isTextScrolling()); @@ -350,14 +382,17 @@ * @param timeout the timeout value in milliseconds or FOREVER * @throws IllegalArgumentException if time is not positive nor FOREVER. */ - public void setTimeout(int timeout) { - if (timeout > 0 || timeout == FOREVER) { + public void setTimeout(int timeout) + { + if(timeout > 0 || timeout == FOREVER) + { this.timeout = timeout; setCommandsVisibility(isModal()); } - else { + else + { throw new IllegalArgumentException( - MsgRepository.ALERT_EXCEPTION_INVALID_TIMEOUT); + MsgRepository.ALERT_EXCEPTION_INVALID_TIMEOUT); } } @@ -366,11 +401,14 @@ * * @return timeout in milliseconds, or FOREVER */ - public int getTimeout() { - if (isModal()) { + public int getTimeout() + { + if(isModal()) + { return FOREVER; } - else { + else + { return timeout; } } @@ -380,7 +418,8 @@ * * @return default timeout in milliseconds */ - public int getDefaultTimeout() { + public int getDefaultTimeout() + { return Config.ALERT_DEFAULT_TIMEOUT; } @@ -389,13 +428,16 @@ * * @param type an AlertType or null if it doesn't have a specific type */ - public void setType(AlertType type) { + public void setType(AlertType type) + { this.type = type; - if (text == null) { + if(text == null) + { // show default text setString(text); } - if (image == null) { + if(image == null) + { // show default image setImage(image); } @@ -406,7 +448,8 @@ * * @return an AlertType or null if it doesn't have a specific type */ - public AlertType getType() { + public AlertType getType() + { return type; } @@ -415,74 +458,82 @@ * * @param newImage an Image, or null if there is no image */ - public void setImage(Image newImage) { + public void setImage(Image newImage) + { image = newImage; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Image temp = (image != null) ? image : null; //Get the image size from QT Style for scaling int scaleToSize = Style.pixelMetric(Style.QSTYLE_PM_MESSAGEBOXICONSIZE); - if (temp != null) { + if(temp != null) + { //calculate the aspect ratio float aspectRatio = (float)temp.getHeight()/temp.getWidth(); //check the image size - if ( ( temp.getWidth() > scaleToSize ) || - ( temp.getHeight() > scaleToSize ) ) + if((temp.getWidth() > scaleToSize) || + (temp.getHeight() > scaleToSize)) { // we need to scale down the image - if( temp.getWidth() > scaleToSize ) + if(temp.getWidth() > scaleToSize) { //Width is greater Image wScaled = Image.createImage(temp, - scaleToSize, - (int)(scaleToSize*aspectRatio)); + scaleToSize, + (int)(scaleToSize*aspectRatio)); //now check the new dimension against height - if(wScaled.getHeight() > scaleToSize ) + if(wScaled.getHeight() > scaleToSize) { //scale the image again Image whScaled = Image.createImage(temp, - scaleToSize, - scaleToSize ); + scaleToSize, + scaleToSize); eswtImgLabel.setImage(Image.getESWTImage(whScaled)); } - else { + else + { //height was ok after scaling on width eswtImgLabel.setImage(Image.getESWTImage(wScaled)); } } - else if( temp.getHeight() > scaleToSize ) + else if(temp.getHeight() > scaleToSize) { //Height is greater Image hScaled = Image.createImage(temp, (int)(scaleToSize/aspectRatio), - scaleToSize ); + scaleToSize); //now check the new dimension against width - if(hScaled.getWidth()> scaleToSize ) + if(hScaled.getWidth()> scaleToSize) { //scale the image again Image hwScaled = Image.createImage(temp, - scaleToSize, - scaleToSize ); + scaleToSize, + scaleToSize); eswtImgLabel.setImage(Image.getESWTImage(hwScaled)); } - else { + else + { //widh was ok after scaling using height eswtImgLabel.setImage(Image.getESWTImage(hScaled)); } } } - else { + else + { // image is right size eswtImgLabel.setImage(Image.getESWTImage(temp)); } } - else { + else + { // no image if(type != null) { @@ -502,7 +553,8 @@ * * @return an Image, or null if there is no image */ - public Image getImage() { + public Image getImage() + { return image; } @@ -511,9 +563,12 @@ * * @return true if the scrollbar is visible. */ - private boolean isTextScrolling() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private boolean isTextScrolling() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { textScrolling = eswtScrolledText.isTextScrolling(); } }); @@ -525,10 +580,13 @@ * * @param newText the Alert's text string, or null if there is no text */ - public void setString(String newText) { + public void setString(String newText) + { text = newText; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { String temp = (text != null) ? text : getDefaultText(type); eswtScrolledText.setText(temp); eswtSetPreferredContentSize(-1, eswtGetPreferredContentHeight()); @@ -543,7 +601,8 @@ * * @return the Alert's text string, or null if there is no text */ - public String getString() { + public String getString() + { return text; } @@ -555,19 +614,23 @@ * @throws IllegalArgumentException if indicator does not meet the * restrictions for its use in an Alert */ - public void setIndicator(Gauge newIndicator) { - if (newIndicator != null && !newIndicator.isSuitableForAlert()) { + public void setIndicator(Gauge newIndicator) + { + if(newIndicator != null && !newIndicator.isSuitableForAlert()) + { throw new IllegalArgumentException( - MsgRepository.ALERT_EXCEPTION_INVALID_INDICATOR); + MsgRepository.ALERT_EXCEPTION_INVALID_INDICATOR); } // remove old Gauge parent - if (indicator != null) { + if(indicator != null) + { indicator.setParent(null); } // store the indicator indicator = newIndicator; // set new Gauge parent - if (indicator != null) { + if(indicator != null) + { indicator.setParent(this); } updateIndicator(); @@ -578,55 +641,66 @@ * * @return the activity indicator of this Alert, or null if there is none */ - public Gauge getIndicator() { + public Gauge getIndicator() + { return indicator; } /** * Update indicator if it changed. */ - void updateIndicator() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - if (indicator != null) { + void updateIndicator() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + if(indicator != null) + { // show ProgressBar - if (indicator.isIndefinite()) { + if(indicator.isIndefinite()) + { // indefinite ProgressBar - switch (indicator.getValue()) { - case Gauge.CONTINUOUS_IDLE: - case Gauge.INCREMENTAL_IDLE: - // currently these are mapped to full progress bar - // TODO: eSWT support required - eswtUpdateProgressbar(getContentComp(), false, true); + switch(indicator.getValue()) + { + case Gauge.CONTINUOUS_IDLE: + case Gauge.INCREMENTAL_IDLE: + // currently these are mapped to full progress bar + // TODO: eSWT support required + eswtUpdateProgressbar(getContentComp(), false, true); + eswtSetProgressbarValues(0, 1, 1); + break; + case Gauge.CONTINUOUS_RUNNING: + eswtUpdateProgressbar(getContentComp(), true, true); + break; + case Gauge.INCREMENTAL_UPDATING: + // currently this are mapped to blinking + // empty and full progress bar + // TODO: eSWT support required + eswtUpdateProgressbar(getContentComp(), false, true); + if(eswtProgressBar.getSelection() > 0) + { + eswtSetProgressbarValues(0, 1, 0); + } + else + { eswtSetProgressbarValues(0, 1, 1); - break; - case Gauge.CONTINUOUS_RUNNING: - eswtUpdateProgressbar(getContentComp(), true, true); - break; - case Gauge.INCREMENTAL_UPDATING: - // currently this are mapped to blinking - // empty and full progress bar - // TODO: eSWT support required - eswtUpdateProgressbar(getContentComp(), false, true); - if (eswtProgressBar.getSelection() > 0) { - eswtSetProgressbarValues(0, 1, 0); - } - else { - eswtSetProgressbarValues(0, 1, 1); - } - break; - default: - break; + } + break; + default: + break; } } - else { + else + { // definite ProgressBar eswtUpdateProgressbar(getContentComp(), false, true); eswtSetProgressbarValues(0, indicator.getMaxValue(), - indicator.getValue()); + indicator.getValue()); } } - else { + else + { // hide ProgressBar eswtUpdateProgressbar(getContentComp(), false, false); } @@ -639,8 +713,10 @@ /* (non-Javadoc) * @see Displayable#addCommand(Command) */ - public void addCommand(Command command) { - if (command != DISMISS_COMMAND) { + public void addCommand(Command command) + { + if(command != DISMISS_COMMAND) + { super.addCommand(command); super.removeCommand(DISMISS_COMMAND); setCommandsVisibility(isModal()); @@ -650,10 +726,13 @@ /* (non-Javadoc) * @see Displayable#removeCommand(Command) */ - public void removeCommand(Command command) { - if (command != DISMISS_COMMAND) { + public void removeCommand(Command command) + { + if(command != DISMISS_COMMAND) + { super.removeCommand(command); - if (getNumCommands() == 0) { + if(getNumCommands() == 0) + { super.addCommand(DISMISS_COMMAND); } setCommandsVisibility(isModal()); @@ -663,19 +742,24 @@ /* (non-Javadoc) * @see Displayable#setCommandListener(CommandListener) */ - public void setCommandListener(CommandListener listener) { - if (listener == null) { + public void setCommandListener(CommandListener listener) + { + if(listener == null) + { listener = implicitListener; } super.setCommandListener(listener); } - void resetTimerTask(boolean reset) { - if (timerTask != null) { + void resetTimerTask(boolean reset) + { + if(timerTask != null) + { timerTask.cancel(); timerTask = null; } - if (reset && !isModal()) { + if(reset && !isModal()) + { // if not modal schedule new timer timerTask = new AlertTimerTask(); timer.schedule(timerTask, timeout); @@ -685,11 +769,14 @@ /** * Alert Timer task. Triggers the first command on the Alert. */ - class AlertTimerTask extends TimerTask { + class AlertTimerTask extends TimerTask + { - public void run() { + public void run() + { // trigger the first available command on the listener - if (!isModal()) { + if(!isModal()) + { callCommandAction(getCommand(0)); } } @@ -699,9 +786,11 @@ /** * Default (implicit) command listener. Any Commands close the Alert. */ - class AlertCommandListener implements CommandListener { + class AlertCommandListener implements CommandListener + { - public void commandAction(Command aCommand, Displayable aSource) { + public void commandAction(Command aCommand, Displayable aSource) + { final Alert alert = (Alert) aSource; Display.getDisplay().setCurrent(alert.nextDisplayable); } @@ -711,30 +800,39 @@ /** * Key listener. Also handles scrolling of text composite. */ - class KeyListener implements Listener { + class KeyListener implements Listener + { - public void handleEvent(Event e) { - if (e.type == SWT.Traverse) { + public void handleEvent(Event e) + { + if(e.type == SWT.Traverse) + { e.doit = false; } - else if (e.type == SWT.KeyDown) { - if (!isModal()) { + else if(e.type == SWT.KeyDown) + { + if(!isModal()) + { resetTimerTask(false); callCommandAction(getCommand(0)); } - else if (e.keyCode == SWT.ARROW_DOWN) { + else if(e.keyCode == SWT.ARROW_DOWN) + { Point p = eswtScrolledText.getOrigin(); eswtScrolledText.setOrigin(p.x, p.y - + Config.ALERT_TEXT_SCROLLING_DELTA); + + Config.ALERT_TEXT_SCROLLING_DELTA); } - else if (e.keyCode == SWT.ARROW_UP) { + else if(e.keyCode == SWT.ARROW_UP) + { Point p = eswtScrolledText.getOrigin(); eswtScrolledText.setOrigin(p.x, p.y - - Config.ALERT_TEXT_SCROLLING_DELTA); + - Config.ALERT_TEXT_SCROLLING_DELTA); } } - else if (e.type == SWT.MouseUp) { - if (!isModal()) { + else if(e.type == SWT.MouseUp) + { + if(!isModal()) + { resetTimerTask(false); callCommandAction(getCommand(0)); } @@ -747,9 +845,11 @@ * Resize listener which listens to bottom shell's resize events and * forwards them to top shell. */ - class ResizeListener implements Listener { + class ResizeListener implements Listener + { - public void handleEvent(Event event) { + public void handleEvent(Event event) + { // explicitly forward topShell resize events to dialogShell getShell().notifyListeners(SWT.Resize, event); } @@ -759,10 +859,13 @@ /** * Dispose Alert. */ - void dispose() { + void dispose() + { super.dispose(); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { topShell.dispose(); } }); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/AlertType.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/AlertType.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/AlertType.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,7 +19,8 @@ /** * Implementation of LCDUI AlertType class. */ -public class AlertType extends Object { +public class AlertType extends Object +{ /** * Alarm Alert type. @@ -49,7 +50,8 @@ /** * Protected constructor for subclasses. */ - protected AlertType() { + protected AlertType() + { } /** @@ -58,10 +60,12 @@ * @param display on which the sound should be played * @return true is the sound was played, false otherwise. */ - public boolean playSound(Display display) { - if (display == null) { + public boolean playSound(Display display) + { + if(display == null) + { throw new NullPointerException( - MsgRepository.ALERTTYPE_EXCEPTION_PLAYSOUND_NULL_POINTER); + MsgRepository.ALERTTYPE_EXCEPTION_PLAYSOUND_NULL_POINTER); } // TODO: eSWT support required return false; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Canvas.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Canvas.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Canvas.java Fri May 14 15:47:24 2010 +0300 @@ -38,7 +38,8 @@ * Canvas the abstract method paint(Graphics g) designed * to be implemented by the developer. */ -public abstract class Canvas extends Displayable { +public abstract class Canvas extends Displayable +{ /** * Constant for UP game action. @@ -198,19 +199,20 @@ private int timeout; private boolean disableTapDetection; - private boolean repaintPending; - private int repaintX1; - private int repaintY1; - private int repaintX2; - private int repaintY2; - private Object repaintLock; + private boolean repaintPending; + private int repaintX1; + private int repaintY1; + private int repaintX2; + private int repaintY2; + private Object repaintLock; - private boolean selectionKeyCompatibility; - private boolean finalMode; + private boolean selectionKeyCompatibility; + private boolean finalMode; /** * Constructs Canvas object. */ - public Canvas() { + public Canvas() + { super(null); repaintLock = new Object(); cleanupLock = new Object(); @@ -223,79 +225,91 @@ /* (non-Javadoc) * @see Displayable#eswtConstructShell(int) */ - Shell eswtConstructShell(int style) { + Shell eswtConstructShell(int style) + { return super.eswtConstructShell(style /*| SWT.RESIZE*/); } /* (non-Javadoc) * @see Displayable#eswtConstructContent(int) */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { // Get JAD attribute noBackground = JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_UI_ENHANCEMENT, - JadAttributeUtil.VALUE_CANVAS_HAS_BACKGROUND); - if (noBackground){ - style |= SWT.NO_BACKGROUND; + JadAttributeUtil.VALUE_CANVAS_HAS_BACKGROUND); + if(noBackground) + { + style |= SWT.NO_BACKGROUND; } // Get JAD attribute for S60 Selection Key Compatibility selectionKeyCompatibility = JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY, - JadAttributeUtil.VALUE_TRUE); + JadAttributeUtil.VALUE_TRUE); // Get JAD attribute for MIDlet Tap Detection String tapAttr = JadAttributeUtil.getValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_TAP_DETECTION_OPTIONS); - if(tapAttr != null) { - if(tapAttr.indexOf(',') == -1) { - setDefaultTapValues(); - } - else { - String twipString = tapAttr.substring(0, tapAttr.indexOf(',')).trim(); - String timeoutString = tapAttr.substring(tapAttr.indexOf(',') + 1, tapAttr.length()).trim(); + if(tapAttr != null) + { + if(tapAttr.indexOf(',') == -1) + { + setDefaultTapValues(); + } + else + { + String twipString = tapAttr.substring(0, tapAttr.indexOf(',')).trim(); + String timeoutString = tapAttr.substring(tapAttr.indexOf(',') + 1, tapAttr.length()).trim(); - try { - twips = Integer.parseInt(twipString); - timeout = Integer.parseInt(timeoutString); + try + { + twips = Integer.parseInt(twipString); + timeout = Integer.parseInt(timeoutString); - // Check for Negative Values - if( (twips < 0) && (timeout < 0) ) { - setDefaultTapValues(); - } + // Check for Negative Values + if((twips < 0) && (timeout < 0)) + { + setDefaultTapValues(); + } - if( (twips == 0) && (timeout == 0) ) { - disableTapDetection = true; - } + if((twips == 0) && (timeout == 0)) + { + disableTapDetection = true; + } - // if any one of the value is zero, set defaults - if( !((twips != 0) && (timeout != 0)) ) { - setDefaultTapValues(); - } - } - catch (NumberFormatException e) { - // Alpha Numeric Values of Timeouts and Timeout - setDefaultTapValues(); - } - } + // if any one of the value is zero, set defaults + if(!((twips != 0) && (timeout != 0))) + { + setDefaultTapValues(); + } + } + catch(NumberFormatException e) + { + // Alpha Numeric Values of Timeouts and Timeout + setDefaultTapValues(); + } + } } else { - setDefaultTapValues(); + setDefaultTapValues(); } Composite canvasComp = super.eswtConstructContent(style); - // Read the on screen keypad settings from the jad attribute - String oskAttr = JadAttributeUtil - .getValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD); - if (oskAttr != null - && (!oskAttr.equalsIgnoreCase(JadAttributeUtil.VALUE_NO)) - && ((oskAttr - .equalsIgnoreCase(JadAttributeUtil.VALUE_GAMEACTIONS)) || (oskAttr - .equalsIgnoreCase(JadAttributeUtil.VALUE_NAVIGATIONKEYS)))) { + // Read the on screen keypad settings from the jad attribute + String oskAttr = JadAttributeUtil + .getValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD); + if(oskAttr != null + && (!oskAttr.equalsIgnoreCase(JadAttributeUtil.VALUE_NO)) + && ((oskAttr + .equalsIgnoreCase(JadAttributeUtil.VALUE_GAMEACTIONS)) || (oskAttr + .equalsIgnoreCase(JadAttributeUtil.VALUE_NAVIGATIONKEYS)))) + { - // On screen keypad is required, On devices without keyboard it can - // be either navigation keys or navigation and game keys - onScreenkeypad = new CanvasKeypad(this, canvasComp, oskAttr); - } + // On screen keypad is required, On devices without keyboard it can + // be either navigation keys or navigation and game keys + onScreenkeypad = new CanvasKeypad(this, canvasComp, oskAttr); + } return canvasComp; @@ -304,7 +318,8 @@ /* (non-Javadoc) * @see Displayable#eswtHandleShowCurrentEvent() */ - void eswtHandleShowCurrentEvent() { + void eswtHandleShowCurrentEvent() + { super.eswtHandleShowCurrentEvent(); getContentComp().addPaintListener(paintListener); getContentComp().addMouseListener(mouseListener); @@ -314,7 +329,8 @@ /* (non-Javadoc) * @see Displayable#eswtHandleHideCurrentEvent() */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { super.eswtHandleHideCurrentEvent(); getContentComp().removePaintListener(paintListener); getContentComp().removeMouseListener(mouseListener); @@ -324,7 +340,8 @@ /** * Issues the request to repaint the whole Canvas. */ - public void repaint() { + public void repaint() + { repaint(0, 0, getWidth(), getHeight()); } @@ -337,32 +354,36 @@ * @param width - width of the rectangle to redraw. * @param height - height of the rectangle to redraw. */ - public void repaint(int x, int y, int width, int height) { - // Paint callback event is posted without any invalid area info. - // Invalid area info is kept in the member variables. Only one event - // per Canvas is added to the queue. If there are more repaint() calls - // before the already posted event has been served those are merged - // to the invalid area in the member variables without posting a new - // event. - synchronized(repaintLock) { - if (invalidate(x, y, width, height)) { - // Note that repaintPending doesn't mean that there's a repaint - // event in the queue. It means that the invalid area is going - // to be repainted and there's no need to add a new event. - // It's possible that the repaint event has already been - // removed from the queue but repaintPending is still true. In - // that case it's currently being processed and we can still - // add to the invalid area. - if (!repaintPending) { - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent( - LCDUIEvent.CANVAS_PAINT_MIDLET_REQUEST, this); - event.widget = getContentComp(); + public void repaint(int x, int y, int width, int height) + { + // Paint callback event is posted without any invalid area info. + // Invalid area info is kept in the member variables. Only one event + // per Canvas is added to the queue. If there are more repaint() calls + // before the already posted event has been served those are merged + // to the invalid area in the member variables without posting a new + // event. + synchronized(repaintLock) + { + if(invalidate(x, y, width, height)) + { + // Note that repaintPending doesn't mean that there's a repaint + // event in the queue. It means that the invalid area is going + // to be repainted and there's no need to add a new event. + // It's possible that the repaint event has already been + // removed from the queue but repaintPending is still true. In + // that case it's currently being processed and we can still + // add to the invalid area. + if(!repaintPending) + { + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent( + LCDUIEvent.CANVAS_PAINT_MIDLET_REQUEST, this); + event.widget = getContentComp(); eventDispatcher.postEvent(event); - repaintPending = true; - } - } - } + repaintPending = true; + } + } + } } /** @@ -370,13 +391,17 @@ * * @param mode - true switches the Canvas to the full-screen mode. */ - public void setFullScreenMode(boolean mode) { + public void setFullScreenMode(boolean mode) + { finalMode = mode; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { ((MobileShell) getShell()).setFullScreenMode(finalMode); //set the CanvasKeypad to the required mode - if(onScreenkeypad != null) { + if(onScreenkeypad != null) + { onScreenkeypad.setFullScreenMode(finalMode); } } @@ -386,8 +411,9 @@ /** * Processes all the issued paint requests. */ - public final void serviceRepaints() { - EventDispatcher.instance().serviceRepaints(this); + public final void serviceRepaints() + { + EventDispatcher.instance().serviceRepaints(this); } /** @@ -395,7 +421,8 @@ * * @return true if the Canvas supports pointer dragging, false otherwise. */ - public boolean hasPointerMotionEvents() { + public boolean hasPointerMotionEvents() + { return true; } @@ -404,7 +431,8 @@ * * @return true if the Canvas supports pointer events, false otherwise. */ - public boolean hasPointerEvents() { + public boolean hasPointerEvents() + { return true; } @@ -413,7 +441,8 @@ * * @return true if the Canvas is double buffered, false otherwise. */ - public boolean isDoubleBuffered() { + public boolean isDoubleBuffered() + { return true; } @@ -422,7 +451,8 @@ * * @return true if Canvas supports key repeat events, false otherwise. */ - public boolean hasRepeatEvents() { + public boolean hasRepeatEvents() + { return true; } @@ -433,7 +463,8 @@ * @return Game action for a a specified key code or * IllegalArgumentException. */ - public int getGameAction(int keyCode) { + public int getGameAction(int keyCode) + { return KeyTable.getGameAction(keyCode); } @@ -443,7 +474,8 @@ * @param gameAction - game action to be mapped to the key code. * @return Key code that is mapped to the specified game action. */ - public int getKeyCode(int gameAction) { + public int getKeyCode(int gameAction) + { return KeyTable.getKeyCode(gameAction); } @@ -454,7 +486,8 @@ * @return String that contains textual name of the key specified by the key * code. */ - public String getKeyName(int keyCode) { + public String getKeyName(int keyCode) + { return KeyTable.getKeyName(keyCode); } /** @@ -462,10 +495,14 @@ * * @return Height of the Displayable in pixels. */ - public int getHeight() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - if( onScreenkeypad != null ) { + public int getHeight() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + if(onScreenkeypad != null) + { oskHeight = onScreenkeypad.getHeight(); } } @@ -500,7 +537,8 @@ * * @param keyCode - key code of the key pressed. */ - protected void keyPressed(int keyCode) { + protected void keyPressed(int keyCode) + { } /** @@ -508,7 +546,8 @@ * * @param keyCode - key code of the key released. */ - protected void keyReleased(int keyCode) { + protected void keyReleased(int keyCode) + { } /** @@ -517,7 +556,8 @@ * * @param keyCode - key code of the key repeated. */ - protected void keyRepeated(int keyCode) { + protected void keyRepeated(int keyCode) + { } /** @@ -526,7 +566,8 @@ * @param x - X-coordinate of the tap point. * @param y - Y-coordinate of the tap point. */ - protected void pointerPressed(int x, int y) { + protected void pointerPressed(int x, int y) + { } /** @@ -535,7 +576,8 @@ * @param x - X-coordinate of the pointer release point. * @param y - Y-coordinate of the pointer release point. */ - protected void pointerReleased(int x, int y) { + protected void pointerReleased(int x, int y) + { } /** @@ -544,7 +586,8 @@ * @param x - X-coordinate of the pointer drag point. * @param y - Y-coordinate of the pointer drag point. */ - protected void pointerDragged(int x, int y) { + protected void pointerDragged(int x, int y) + { } /** @@ -553,21 +596,24 @@ * is switching between full-screen mode by calling * setFullScreenMode(). */ - protected void sizeChanged(int w, int h) { + protected void sizeChanged(int w, int h) + { } /** * showNotify() is the callback called before the Canvas is shown on the * screen. */ - protected void showNotify() { + protected void showNotify() + { } /** * hideNotify() is the callback called after the Canvas is removed from the * screen. */ - protected void hideNotify() { + protected void hideNotify() + { } /** @@ -576,15 +622,18 @@ * @param supressKeys suppress game keys * @return frame buffer */ - final void initGameCanvas(boolean suppressKeys) { + final void initGameCanvas(boolean suppressKeys) + { this.suppressGameKeys = suppressKeys; } /** * Update game buffer graphics. */ - final void eswtUpdateGameBufferGraphics() { - if (gameBufferGraphics == null) { + final void eswtUpdateGameBufferGraphics() + { + if(gameBufferGraphics == null) + { gameBufferGraphics = new Graphics(); gameBufferGraphics.initBuffered(this, 0, 0, getWidth(), getHeight()); flushLock = gameBufferGraphics.getLock(); @@ -594,23 +643,26 @@ /** * Get game canvas frame buffer graphics. */ - final Graphics getGameBufferGraphics() { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + final Graphics getGameBufferGraphics() + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtUpdateGameBufferGraphics(); } }); return gameBufferGraphics; } - + CanvasKeypad getCanvasKeypad() { - return onScreenkeypad; + return onScreenkeypad; } boolean IsFullScreenMode() { - return finalMode; + return finalMode; } /** @@ -618,17 +670,19 @@ * * @return game key states. */ - final int getGameKeyStates() { + final int getGameKeyStates() + { int ret = gameKeyState; gameKeyState = 0; return ret; } - void renderGraphics(final Graphics g) { - // Implementation missing. GameCanvas.paint() should by default render - // the the off-screen buffer at (0,0). Rendering of the buffer must be - // subject to the clip region and origin translation of the Graphics - // object. + void renderGraphics(final Graphics g) + { + // Implementation missing. GameCanvas.paint() should by default render + // the the off-screen buffer at (0,0). Rendering of the buffer must be + // subject to the clip region and origin translation of the Graphics + // object. } /** @@ -640,31 +694,37 @@ * @param height */ void flushGameBuffer(final int x, final int y, final int width, - final int height) { - synchronized( flushLock ) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - canvasMode = MODE_GAME_BUFFER_FLUSH; - ((CompositeExtension)getContentComp()).redrawNow(x, y, width, height); - gameBufferGraphics.resetCommandBuffer(); - canvasMode = MODE_NORMAL; - } - }); - } + final int height) + { + synchronized(flushLock) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + canvasMode = MODE_GAME_BUFFER_FLUSH; + ((CompositeExtension)getContentComp()).redrawNow(x, y, width, height); + gameBufferGraphics.resetCommandBuffer(); + canvasMode = MODE_NORMAL; + } + }); + } } /** * Called by ShellListener when shell gets activated. */ - void handleShellActivatedEvent() { + void handleShellActivatedEvent() + { super.handleShellActivatedEvent(); // reset the game key state gameKeyState = 0; canvasMode = MODE_NORMAL; - synchronized(cleanupLock) { - cleanupNeeded = true; - } + synchronized(cleanupLock) + { + cleanupNeeded = true; + } LCDUIEvent event = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_SHOWNOTIFY, this); EventDispatcher.instance().postEvent(event); @@ -673,7 +733,8 @@ /** * Called by ShellListener when shell gets de-activated. */ - void handleShellDeActivatedEvent() { + void handleShellDeActivatedEvent() + { super.handleShellDeActivatedEvent(); LCDUIEvent event = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_HIDENOTIFY, this); EventDispatcher.instance().postEvent(event); @@ -682,25 +743,30 @@ /* * UI thread calls */ - void eswtHandleResizeEvent(int width, int height) { + void eswtHandleResizeEvent(int width, int height) + { super.eswtHandleResizeEvent(width, height); - canvasMode = MODE_NORMAL; - synchronized(cleanupLock) { - cleanupNeeded = true; - } + canvasMode = MODE_NORMAL; + synchronized(cleanupLock) + { + cleanupNeeded = true; + } } /* * UI thread calls */ - void eswtHandleEvent(Event e) { + void eswtHandleEvent(Event e) + { super.eswtHandleEvent(e); - if (e.type == SWT.KeyDown) { - doKeyPressed(e.keyCode); + if(e.type == SWT.KeyDown) + { + doKeyPressed(e.keyCode); } - else if (e.type == SWT.KeyUp) { - doKeyReleased(e.keyCode); + else if(e.type == SWT.KeyUp) + { + doKeyReleased(e.keyCode); } } @@ -708,210 +774,241 @@ /* * UI thread calls. Paint listener of the eSWT widget. */ - class CanvasShellPaintListener implements PaintListener { - - public void paintControl(PaintEvent pe) { - switch (canvasMode) { - case MODE_BUFFER_FLUSH: - // Paint event initiated by us to paint the Canvas. - doBufferFlush(pe, canvasGraphics); - break; - case MODE_GAME_BUFFER_FLUSH: - // Paint event initiated by us to paint the GameCanvas. - doBufferFlush(pe, gameBufferGraphics); - break; - case MODE_NORMAL: - // Native toolkit is requesting an update of an area that has - // become invalid. Can't do anything here because the contents - // need to be queried from the MIDlet in another thread by - // a paint callback. For this a paint callback event is posted. - // For a moment the native toolkit thinks that the area has - // been validated when in truth it will be painted later after - // the paint callback has been executed. - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent( - LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST, - javax.microedition.lcdui.Canvas.this); - event.x = pe.x; - event.y = pe.y; - event.width = pe.width; - event.height = pe.height; - event.widget = pe.widget; - eventDispatcher.postEvent(event); - break; - } - } - } + class CanvasShellPaintListener implements PaintListener + { - /* - * Dispatcher thread or the serviceRepaints()-thread calls. - */ - final void doCallback(LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.CANVAS_PAINT_MIDLET_REQUEST: // fall through - case LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST: - doPaintCallback(event); - break; - case LCDUIEvent.CANVAS_HIDENOTIFY: - hideNotify(); - break; - case LCDUIEvent.CANVAS_KEYPRESSED: - keyPressed(event.keyCode); - break; - case LCDUIEvent.CANVAS_KEYREPEATED: - keyRepeated(event.keyCode); - break; - case LCDUIEvent.CANVAS_KEYRELEASED: - keyReleased(event.keyCode); - break; - case LCDUIEvent.CANVAS_POINTERDRAGGED: - pointerDragged(event.x, event.y); - break; - case LCDUIEvent.CANVAS_POINTERPRESSED: - pointerPressed(event.x, event.y); - break; - case LCDUIEvent.CANVAS_POINTERRELEASED: - pointerReleased(event.x, event.y); - break; - case LCDUIEvent.CANVAS_SHOWNOTIFY: - showNotify(); - break; - default: - super.doCallback(event); - break; - } - } + public void paintControl(PaintEvent pe) + { + switch(canvasMode) + { + case MODE_BUFFER_FLUSH: + // Paint event initiated by us to paint the Canvas. + doBufferFlush(pe, canvasGraphics); + break; + case MODE_GAME_BUFFER_FLUSH: + // Paint event initiated by us to paint the GameCanvas. + doBufferFlush(pe, gameBufferGraphics); + break; + case MODE_NORMAL: + // Native toolkit is requesting an update of an area that has + // become invalid. Can't do anything here because the contents + // need to be queried from the MIDlet in another thread by + // a paint callback. For this a paint callback event is posted. + // For a moment the native toolkit thinks that the area has + // been validated when in truth it will be painted later after + // the paint callback has been executed. + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent( + LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST, + javax.microedition.lcdui.Canvas.this); + event.x = pe.x; + event.y = pe.y; + event.width = pe.width; + event.height = pe.height; + event.widget = pe.widget; + eventDispatcher.postEvent(event); + break; + } + } + } /* * Dispatcher thread or the serviceRepaints()-thread calls. */ - private final void doPaintCallback(final LCDUIEvent event) { - // Decide the area going to be painted by the callback. - final int redrawNowX; - final int redrawNowY; - final int redrawNowW; - final int redrawNowH; - // Before this thread obtains the repaintLock any repaint() calls - // will still be adding to the invalid area that is going to be - // painted by this callback. - synchronized(repaintLock) { - if(event.type == LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST) { - // Merge with possibly existing repaint() requests + final void doCallback(LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.CANVAS_PAINT_MIDLET_REQUEST: // fall through + case LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST: + doPaintCallback(event); + break; + case LCDUIEvent.CANVAS_HIDENOTIFY: + hideNotify(); + break; + case LCDUIEvent.CANVAS_KEYPRESSED: + keyPressed(event.keyCode); + break; + case LCDUIEvent.CANVAS_KEYREPEATED: + keyRepeated(event.keyCode); + break; + case LCDUIEvent.CANVAS_KEYRELEASED: + keyReleased(event.keyCode); + break; + case LCDUIEvent.CANVAS_POINTERDRAGGED: + pointerDragged(event.x, event.y); + break; + case LCDUIEvent.CANVAS_POINTERPRESSED: + pointerPressed(event.x, event.y); + break; + case LCDUIEvent.CANVAS_POINTERRELEASED: + pointerReleased(event.x, event.y); + break; + case LCDUIEvent.CANVAS_SHOWNOTIFY: + showNotify(); + break; + default: + super.doCallback(event); + break; + } + } + + /* + * Dispatcher thread or the serviceRepaints()-thread calls. + */ + private final void doPaintCallback(final LCDUIEvent event) + { + // Decide the area going to be painted by the callback. + final int redrawNowX; + final int redrawNowY; + final int redrawNowW; + final int redrawNowH; + // Before this thread obtains the repaintLock any repaint() calls + // will still be adding to the invalid area that is going to be + // painted by this callback. + synchronized(repaintLock) + { + if(event.type == LCDUIEvent.CANVAS_PAINT_NATIVE_REQUEST) + { + // Merge with possibly existing repaint() requests invalidate(event.x, event.y, event.width, event.height); - } else { - // Need to add a new event to the queue in subsequent repaint() - // calls. - repaintPending = false; - } + } + else + { + // Need to add a new event to the queue in subsequent repaint() + // calls. + repaintPending = false; + } - // Store the current area to be painted - redrawNowX = repaintX1; - redrawNowY = repaintY1; - redrawNowW = repaintX2-repaintX1; - redrawNowH = repaintY2-repaintY1; + // Store the current area to be painted + redrawNowX = repaintX1; + redrawNowY = repaintY1; + redrawNowW = repaintX2-repaintX1; + redrawNowH = repaintY2-repaintY1; - // After releasing the lock the repaint() calls will start with - // new invalid area. - repaintX1 = repaintX2 = repaintY1 = repaintY2 = 0; + // After releasing the lock the repaint() calls will start with + // new invalid area. + repaintX1 = repaintX2 = repaintY1 = repaintY2 = 0; - // Don't do the callback if there's nothing to paint - if(!((redrawNowW > 0) && (redrawNowH > 0))) { - return; - } - } + // Don't do the callback if there's nothing to paint + if(!((redrawNowW > 0) && (redrawNowH > 0))) + { + return; + } + } - // Prepare the GC's buffer if not done yet - if (canvasGraphics.getCommandBuffer() == null) { - canvasGraphics.initBuffered(this, event.x, event.y, event.width, event.height); - } + // Prepare the GC's buffer if not done yet + if(canvasGraphics.getCommandBuffer() == null) + { + canvasGraphics.initBuffered(this, event.x, event.y, event.width, event.height); + } - // Clean the background if dirty, buffer the operations. - synchronized(cleanupLock) { - if (cleanupNeeded && noBackground) { - // UI thread can change the contentArea object reference at - // any time. Store the object reference locally to ensure it - // points to the same rectangle all the time. - Rectangle contentArea = getContentArea(); + // Clean the background if dirty, buffer the operations. + synchronized(cleanupLock) + { + if(cleanupNeeded && noBackground) + { + // UI thread can change the contentArea object reference at + // any time. Store the object reference locally to ensure it + // points to the same rectangle all the time. + Rectangle contentArea = getContentArea(); - canvasGraphics.setClip(contentArea.x, contentArea.y, - contentArea.width, contentArea.height); - canvasGraphics.cleanBackground(contentArea); - cleanupNeeded = false; - } - } + canvasGraphics.setClip(contentArea.x, contentArea.y, + contentArea.width, contentArea.height); + canvasGraphics.cleanBackground(contentArea); + cleanupNeeded = false; + } + } - // Clip must define the invalid area - canvasGraphics.setClip(redrawNowX, redrawNowY, redrawNowW, redrawNowH); + // Clip must define the invalid area + canvasGraphics.setClip(redrawNowX, redrawNowY, redrawNowW, redrawNowH); - // The callback + // The callback paint(canvasGraphics); - // Wait until the UI thread is available. Then in the UI thread - // synchronously send a paint event. - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if(event.widget.isDisposed()) { + // Wait until the UI thread is available. Then in the UI thread + // synchronously send a paint event. + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(event.widget.isDisposed()) + { return; } canvasMode = MODE_BUFFER_FLUSH; ((CompositeExtension) event.widget) - .redrawNow(redrawNowX, redrawNowY, redrawNowW, redrawNowH); + .redrawNow(redrawNowX, redrawNowY, redrawNowW, redrawNowH); canvasGraphics.resetCommandBuffer(); canvasMode = MODE_NORMAL; } - }); - } + }); + } /* * UI thread calls to flush the command buffer of a graphics context. */ - private final void doBufferFlush(PaintEvent event, Graphics graphics) { - event.gc.getGCData().internalGc.render(graphics.getCommandBuffer()); + private final void doBufferFlush(PaintEvent event, Graphics graphics) + { + event.gc.getGCData().internalGc.render(graphics.getCommandBuffer()); } /* * UI thread calls. */ - void doKeyPressed(int keyCode) { + void doKeyPressed(int keyCode) + { Logger.method(this, "doKeyPressed", String.valueOf(keyCode)); boolean sendCallback = false; - if (!(updateGameKeyState(keyCode, true) && suppressGameKeys)) { - if( (selectionKeyCompatibility == true) && (keyCode == -5) ) { - if(finalMode == true) { - if(!((getNumCommands() > 0) && hasCommandListener()) ) { + if(!(updateGameKeyState(keyCode, true) && suppressGameKeys)) + { + if((selectionKeyCompatibility == true) && (keyCode == -5)) + { + if(finalMode == true) + { + if(!((getNumCommands() > 0) && hasCommandListener())) + { sendCallback = true; } - else { + else + { sendCallback = false; } } - else { + else + { sendCallback = true; } } - else if( (selectionKeyCompatibility == false) && (keyCode == -5) ) { + else if((selectionKeyCompatibility == false) && (keyCode == -5)) + { sendCallback = false; } - else { + else + { sendCallback = true; } } - else { + else + { sendCallback = false; } - if(sendCallback == true) { + if(sendCallback == true) + { LCDUIEvent event; - if (keysPressed.contains(new Integer(keyCode))) { + if(keysPressed.contains(new Integer(keyCode))) + { event = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_KEYREPEATED, this); } - else { + else + { event = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_KEYPRESSED, this); } event.keyCode = keyCode; @@ -924,35 +1021,46 @@ /* * UI thread calls. */ - void doKeyReleased(int keyCode) { + void doKeyReleased(int keyCode) + { Logger.method(this, "doKeyReleased", String.valueOf(keyCode)); boolean sendCallback = false; - if (!(updateGameKeyState(keyCode, true) && suppressGameKeys)) { - if( (selectionKeyCompatibility == true) && (keyCode == -5) ) { - if(finalMode == true) { - if(!((getNumCommands() > 0) && hasCommandListener()) ) { + if(!(updateGameKeyState(keyCode, true) && suppressGameKeys)) + { + if((selectionKeyCompatibility == true) && (keyCode == -5)) + { + if(finalMode == true) + { + if(!((getNumCommands() > 0) && hasCommandListener())) + { sendCallback = true; } - else { + else + { sendCallback = false; } } - else { + else + { sendCallback = true; } } - else if( (selectionKeyCompatibility == false) && (keyCode == -5) ) { + else if((selectionKeyCompatibility == false) && (keyCode == -5)) + { sendCallback = false; } - else { + else + { sendCallback = true; } } - else { + else + { sendCallback = false; } - if(sendCallback == true) { + if(sendCallback == true) + { LCDUIEvent event = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_KEYRELEASED, this); event.keyCode = keyCode; @@ -964,46 +1072,56 @@ /** * Updates game key states and returns if the key was a game key. */ - private boolean updateGameKeyState(int keyCode, boolean addKeyState) { - // Ignore key repeat events - if (ESWTUIThreadRunner.getKeyRepeatCount() > 1) { + private boolean updateGameKeyState(int keyCode, boolean addKeyState) + { + // Ignore key repeat events + if(ESWTUIThreadRunner.getKeyRepeatCount() > 1) + { return true; - } - try { + } + try + { int gameAction = KeyTable.getGameAction(keyCode); - if (addKeyState) { + if(addKeyState) + { // set bitfield gameKeyState |= (1 << gameAction); } return true; } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { return false; } } - private void setDefaultTapValues() { - twips = DEFAULT_TWIPS; - timeout = DEFAULT_TIMEOUT; + private void setDefaultTapValues() + { + twips = DEFAULT_TWIPS; + timeout = DEFAULT_TIMEOUT; } class CanvasShellMouseListener implements - org.eclipse.swt.events.MouseListener, - org.eclipse.swt.events.MouseMoveListener { + org.eclipse.swt.events.MouseListener, + org.eclipse.swt.events.MouseMoveListener + { - public void mouseDoubleClick(MouseEvent arg0) { + public void mouseDoubleClick(MouseEvent arg0) + { } - public void mouseDown(MouseEvent event) { + public void mouseDown(MouseEvent event) + { LCDUIEvent e = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_POINTERPRESSED, - javax.microedition.lcdui.Canvas.this); + javax.microedition.lcdui.Canvas.this); e.x = event.x; e.y = event.y; EventDispatcher.instance().postEvent(e); - if(!disableTapDetection) { + if(!disableTapDetection) + { // Supress Drag events - suppressDragEvent = true; + suppressDragEvent = true; pointerDownX = event.x; pointerDownY = event.y; @@ -1011,49 +1129,56 @@ // Create and Schedule Timer timerTask = new CanvasTimerTask(); timer.schedule(timerTask, timeout); - } + } } - public void mouseUp(MouseEvent event) { + public void mouseUp(MouseEvent event) + { int pointerUpX = event.x; int pointerUpY = event.y; - if(!disableTapDetection) { - if (timerTask != null) { + if(!disableTapDetection) + { + if(timerTask != null) + { timerTask.cancel(); timerTask = null; } // If Timer not expired and Mouseup is withing rectangle assign // PointercDown to Pinter Up - if(suppressDragEvent && checkWithinRect(event.x, event.y)) { - pointerUpX = pointerDownX; - pointerUpY = pointerDownY; - suppressDragEvent = false; - } - } + if(suppressDragEvent && checkWithinRect(event.x, event.y)) + { + pointerUpX = pointerDownX; + pointerUpY = pointerDownY; + suppressDragEvent = false; + } + } LCDUIEvent e = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_POINTERRELEASED, - javax.microedition.lcdui.Canvas.this); + javax.microedition.lcdui.Canvas.this); e.x = pointerUpX; e.y = pointerUpY; EventDispatcher.instance().postEvent(e); } - public void mouseMove(MouseEvent event) { - // Check for timeout expiration and if PointerUp falls outside the rectangle - if( disableTapDetection || (!suppressDragEvent) || !checkWithinRect(event.x, event.y)) { + public void mouseMove(MouseEvent event) + { + // Check for timeout expiration and if PointerUp falls outside the rectangle + if(disableTapDetection || (!suppressDragEvent) || !checkWithinRect(event.x, event.y)) + { LCDUIEvent e = EventDispatcher.instance().newEvent(LCDUIEvent.CANVAS_POINTERDRAGGED, - javax.microedition.lcdui.Canvas.this); + javax.microedition.lcdui.Canvas.this); e.x = event.x; e.y = event.y; EventDispatcher.instance().postEvent(e); } } - boolean checkWithinRect(int x, int y) { - // Get pixel per inch - Point P = Display.getCurrent().getDPI(); + boolean checkWithinRect(int x, int y) + { + // Get pixel per inch + Point P = Display.getCurrent().getDPI(); float xPxielwidth = (twips * P.x) / 1440; float yPixelHeight = (twips * P.y) / 1440; @@ -1061,81 +1186,90 @@ int RightX = pointerDownX + (int) xPxielwidth; // If the rectange width falls outside the canvas area - if(RightX > getWidth()) { - RightX = getWidth(); + if(RightX > getWidth()) + { + RightX = getWidth(); } int LeftX = pointerDownX - (int) xPxielwidth; // If the rectange width falls outside the canvas area if(LeftX < 0) - LeftX = 0; + LeftX = 0; int TopY = pointerDownY - (int) yPixelHeight; // If the rectange height falls outside the canvas area - if( TopY < 0 ) - TopY = 0; + if(TopY < 0) + TopY = 0; int DownY = pointerDownY + (int) yPixelHeight; // If the rectange heightfalls outside the canvas area. - if( DownY > getHeight() ) - DownY = getHeight(); + if(DownY > getHeight()) + DownY = getHeight(); // Find the PointerUp is within rectange - if( (x >= LeftX ) && (x <= RightX) ) { - if( (y >= TopY ) && (y <= DownY) ) { - return true; + if((x >= LeftX) && (x <= RightX)) + { + if((y >= TopY) && (y <= DownY)) + { + return true; } } - return false; + return false; } } - private boolean invalidate(int x, int y, int width, int height) { - // Regularize bounds - final int x1 = x; - final int y1 = y; - final int x2 = x + width; - final int y2 = y + height; - - // Union the current and new damaged rects - final boolean valid = ((repaintX2 - repaintX1) <= 0) && ((repaintY2 - repaintY1) <= 0); - if (!valid) { - repaintX1 = Math.min(repaintX1, x1); - repaintY1 = Math.min(repaintY1, y1); - repaintX2 = Math.max(repaintX2, x2); - repaintY2 = Math.max(repaintY2, y2); - } else { - repaintX1 = x1; - repaintY1 = y1; - repaintX2 = x2; - repaintY2 = y2; - } + private boolean invalidate(int x, int y, int width, int height) + { + // Regularize bounds + final int x1 = x; + final int y1 = y; + final int x2 = x + width; + final int y2 = y + height; - // UI thread can change the the contentArea object reference at - // any time. Store the object reference locally to ensure it - // points to the same rectangle all the time. - Rectangle contentArea = getContentArea(); - if(contentArea == null) return valid; - final int w = contentArea.width; - final int h = contentArea.height; + // Union the current and new damaged rects + final boolean valid = ((repaintX2 - repaintX1) <= 0) && ((repaintY2 - repaintY1) <= 0); + if(!valid) + { + repaintX1 = Math.min(repaintX1, x1); + repaintY1 = Math.min(repaintY1, y1); + repaintX2 = Math.max(repaintX2, x2); + repaintY2 = Math.max(repaintY2, y2); + } + else + { + repaintX1 = x1; + repaintY1 = y1; + repaintX2 = x2; + repaintY2 = y2; + } - // Clip to bounds - repaintX1 = repaintX1 > 0 ? repaintX1 : 0; - repaintY1 = repaintY1 > 0 ? repaintY1 : 0; - repaintX2 = repaintX2 < w ? repaintX2 : w; - repaintY2 = repaintY2 < h ? repaintY2 : h; + // UI thread can change the the contentArea object reference at + // any time. Store the object reference locally to ensure it + // points to the same rectangle all the time. + Rectangle contentArea = getContentArea(); + if(contentArea == null) return valid; + final int w = contentArea.width; + final int h = contentArea.height; - return valid; - } + // Clip to bounds + repaintX1 = repaintX1 > 0 ? repaintX1 : 0; + repaintY1 = repaintY1 > 0 ? repaintY1 : 0; + repaintX2 = repaintX2 < w ? repaintX2 : w; + repaintY2 = repaintY2 < h ? repaintY2 : h; - class CanvasTimerTask extends TimerTask { + return valid; + } - public void run() { - suppressDragEvent = false; + class CanvasTimerTask extends TimerTask + { + + public void run() + { + suppressDragEvent = false; } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/CanvasKeypad.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/CanvasKeypad.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/CanvasKeypad.java Fri May 14 15:47:24 2010 +0300 @@ -37,7 +37,8 @@ -final class CanvasKeypad { +final class CanvasKeypad +{ /** * Constant for UP game action. @@ -63,12 +64,12 @@ * Constant for FIRE game action. */ private static final int FIRE = -5; - + /** * Constant for SLK game action. */ private static final int SLK = -6; - + /** * Constant for SRK game action. */ @@ -93,34 +94,34 @@ * Constant for general "D" game action. */ private static final int GAME_D = 35; - + /** * Constant for general invalid key code. */ private static final int INVALID_CODE = -99; - - /** - * Constant for long keypress timeout. - */ + + /** + * Constant for long keypress timeout. + */ private static final int KEYREPEAT_INTERVAL = 500; - + private BaseCSSEngine cssEngine; - /** - * keypad and game keys composites. - */ + /** + * keypad and game keys composites. + */ private Composite keypadComposite; private Composite gameKeysComposite; private Canvas canvas; - - /** - * Listener for receiving mouse events on the keypad buttons. - */ + + /** + * Listener for receiving mouse events on the keypad buttons. + */ private CanvasKeypadMouseListener mouseListener = new CanvasKeypadMouseListener(); - - /** - * Canvas keypad buttons. - */ + + /** + * Canvas keypad buttons. + */ private Button up; private Button down; private Button left; @@ -132,60 +133,66 @@ private Button gameB; private Button gameC; private Button gameD; - + private int keyPressed; - + private Timer timer = new Timer(); private CanvasKeypadTimerTask timerTask; - - /** + + /** * Constructs a canvas kepad based on the JAD attribute * * @param canvas - canvas for which the keypad is required. * @param canvasComp - Composite corresponding to the canvas. * @param mode- the jad attribute as a string. */ - CanvasKeypad(Canvas canvas, Composite canvasComp, String mode) { - - this.canvas = canvas; + CanvasKeypad(Canvas canvas, Composite canvasComp, String mode) + { + + this.canvas = canvas; cssEngine = new BaseCSSEngine(Display.getCurrent()); - + //Set form layout for the shell conatining the canvas. canvas.getShell().setLayout(new FormLayout()); - - //Create the Navigation keypad + + //Create the Navigation keypad createNavKeypad(); - + //check if game keys are needed - if( mode.equalsIgnoreCase("gameactions") ) { + if(mode.equalsIgnoreCase("gameactions")) + { //create the game key pad createGamePad(); } - - + + //Layout the game keys, navigation keys and the canvas on the shell using form layout - + FormData canvasData = new FormData(); canvasData.right = new FormAttachment(100); canvasData.left = new FormAttachment(0); canvasData.top = new FormAttachment(0); canvasData.bottom = new FormAttachment(keypadComposite); canvasComp.setLayoutData(canvasData); - + FormData navKeyData = new FormData(); navKeyData.right = new FormAttachment(100); navKeyData.left = new FormAttachment(0); - if(gameKeysComposite != null) { + if(gameKeysComposite != null) + { //game keypad was created above, so layout the game keys. navKeyData.bottom = new FormAttachment(gameKeysComposite); - } else { + } + else + { //game keys are not needed navKeyData.bottom = new FormAttachment(100); } keypadComposite.setLayoutData(navKeyData); - - - if(gameKeysComposite != null) { + + + if(gameKeysComposite != null) + { //layout the game keys FormData gameKeyData = new FormData(); gameKeyData.right = new FormAttachment(100); @@ -193,321 +200,328 @@ gameKeyData.bottom = new FormAttachment(100); gameKeysComposite.setLayoutData(gameKeyData); } - + //layout the shell canvas.getShell().layout(); - - - - } - + + + + } + /** * creates the navigation keypad - the directional keys and selctio key. */ - private void createNavKeypad() { - + private void createNavKeypad() + { + //Create the navigation key composite - + keypadComposite = new Composite(canvas.getShell(), SWT.NONE); - + //Create the buttons of the navigation keypad - + up = new Button(keypadComposite, SWT.PUSH); up.addMouseListener(mouseListener); - left = new Button(keypadComposite, SWT.PUSH); + left = new Button(keypadComposite, SWT.PUSH); left.addMouseListener(mouseListener); - - center = new Button(keypadComposite, SWT.PUSH); + + center = new Button(keypadComposite, SWT.PUSH); center.addMouseListener(mouseListener); - - right = new Button(keypadComposite, SWT.PUSH); + + right = new Button(keypadComposite, SWT.PUSH); right.addMouseListener(mouseListener); - - down = new Button(keypadComposite, SWT.PUSH); + + down = new Button(keypadComposite, SWT.PUSH); down.addMouseListener(mouseListener); - - //up.setStyleSheet( + + //up.setStyleSheet( cssEngine.applyCSS(up,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 2px; " + - "border-radius: 5px;" + - "border-top-right-radius: 27px;"+ - "border-top-left-radius: 27px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-width: 3em;" + - "min-height: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); - - cssEngine.applyCSS(down,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 2px; " + - "border-radius: 5px;" + - "border-bottom-right-radius: 27px;"+ - "border-bottom-left-radius: 27px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-width: 3em;" + - "min-height: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 2px; " + + "border-radius: 5px;" + + "border-top-right-radius: 27px;"+ + "border-top-left-radius: 27px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-width: 3em;" + + "min-height: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); + + cssEngine.applyCSS(down,"QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 2px; " + + "border-radius: 5px;" + + "border-bottom-right-radius: 27px;"+ + "border-bottom-left-radius: 27px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-width: 3em;" + + "min-height: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); - cssEngine.applyCSS(left,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 2px; " + - "border-radius: 5px;" + - "border-top-left-radius: 27px;"+ - "border-bottom-left-radius: 27px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-height: 3em;" + - "min-width: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); + cssEngine.applyCSS(left,"QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 2px; " + + "border-radius: 5px;" + + "border-top-left-radius: 27px;"+ + "border-bottom-left-radius: 27px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-height: 3em;" + + "min-width: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); - cssEngine.applyCSS(right,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 2px; " + - "border-radius: 5px;" + - "border-top-right-radius: 27px;"+ - "border-bottom-right-radius: 27px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-height: 3em;" + - "min-width: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); - - cssEngine.applyCSS(center, "QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 2px; " + - "border-radius: 27px;" + - "border-color: beige;" + - "font: bold 14px;" + - "min-height: 3em;" + - "min-width: 3em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); + cssEngine.applyCSS(right,"QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 2px; " + + "border-radius: 5px;" + + "border-top-right-radius: 27px;"+ + "border-bottom-right-radius: 27px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-height: 3em;" + + "min-width: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); - up.setText("^"); - center.setText("*"); - left.setText("<"); - right.setText(">"); - down.setText("v"); - - + cssEngine.applyCSS(center, "QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 2px; " + + "border-radius: 27px;" + + "border-color: beige;" + + "font: bold 14px;" + + "min-height: 3em;" + + "min-width: 3em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); + + up.setText("^"); + center.setText("*"); + left.setText("<"); + right.setText(">"); + down.setText("v"); + + //layout the navigation keys keypadComposite.setLayout(new FormLayout()); - - - FormData upFormData = new FormData(); - upFormData.top=new FormAttachment(0,10); - upFormData.left=new FormAttachment(40); - up.setLayoutData(upFormData); - - FormData centerFormData = new FormData(); - centerFormData.top=new FormAttachment(up,0,SWT.CENTER|SWT.TRAIL); - centerFormData.left=new FormAttachment(40); - center.setLayoutData(centerFormData); - - FormData downFormData = new FormData(); - downFormData.top = new FormAttachment(center,0,SWT.TRAIL); - downFormData.left=new FormAttachment(left); + + + FormData upFormData = new FormData(); + upFormData.top=new FormAttachment(0,10); + upFormData.left=new FormAttachment(40); + up.setLayoutData(upFormData); + + FormData centerFormData = new FormData(); + centerFormData.top=new FormAttachment(up,0,SWT.CENTER|SWT.TRAIL); + centerFormData.left=new FormAttachment(40); + center.setLayoutData(centerFormData); + + FormData downFormData = new FormData(); + downFormData.top = new FormAttachment(center,0,SWT.TRAIL); + downFormData.left=new FormAttachment(left); down.setLayoutData(downFormData); - - FormData rightFormData = new FormData(); - rightFormData.top=new FormAttachment(up,0,SWT.TRAIL); - rightFormData.left=new FormAttachment(center); - right.setLayoutData(rightFormData); - - FormData leftFormData = new FormData(); - leftFormData.top= new FormAttachment(up); - leftFormData.right = new FormAttachment(center); - left.setLayoutData(leftFormData); - - keypadComposite.layout(); + + FormData rightFormData = new FormData(); + rightFormData.top=new FormAttachment(up,0,SWT.TRAIL); + rightFormData.left=new FormAttachment(center); + right.setLayoutData(rightFormData); + + FormData leftFormData = new FormData(); + leftFormData.top= new FormAttachment(up); + leftFormData.right = new FormAttachment(center); + left.setLayoutData(leftFormData); + + keypadComposite.layout(); } - - + + /** * creates the game keypad - the game action keys A, B, C and D. */ - private void createGamePad() { + private void createGamePad() + { //create the game pad composite gameKeysComposite = new Composite(canvas.getShell(), SWT.NONE); gameKeysComposite.setLayout(new FormLayout()); - - //Add the game buttons + + //Add the game buttons gameA = new Button(gameKeysComposite, SWT.PUSH); gameA.addMouseListener(mouseListener); - - gameB = new Button(gameKeysComposite, SWT.PUSH); + + gameB = new Button(gameKeysComposite, SWT.PUSH); gameB.addMouseListener(mouseListener); - - gameC = new Button(gameKeysComposite, SWT.PUSH); + + gameC = new Button(gameKeysComposite, SWT.PUSH); gameC.addMouseListener(mouseListener); - - gameD = new Button(gameKeysComposite, SWT.PUSH); + + gameD = new Button(gameKeysComposite, SWT.PUSH); gameD.addMouseListener(mouseListener); - + //set the style sheet String gameKeysStylesheet = "QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 0px; " + - "border-color: beige;" + - "font: bold 14px;" + - "min-height: 2em;" + - "min-width: 5.5em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"; - - cssEngine.applyCSS(gameA,gameKeysStylesheet); - cssEngine.applyCSS(gameB,gameKeysStylesheet); - cssEngine.applyCSS(gameC,gameKeysStylesheet); - cssEngine.applyCSS(gameD,gameKeysStylesheet); - + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 0px; " + + "border-color: beige;" + + "font: bold 14px;" + + "min-height: 2em;" + + "min-width: 5.5em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"; + + cssEngine.applyCSS(gameA,gameKeysStylesheet); + cssEngine.applyCSS(gameB,gameKeysStylesheet); + cssEngine.applyCSS(gameC,gameKeysStylesheet); + cssEngine.applyCSS(gameD,gameKeysStylesheet); + gameA.setText("A"); - gameB.setText("B"); - gameC.setText("C"); - gameD.setText("D"); - - //layout the game Keys + gameB.setText("B"); + gameC.setText("C"); + gameD.setText("D"); + + //layout the game Keys FormData gameAFormData = new FormData(); - gameAFormData.bottom=new FormAttachment(100,0); - gameAFormData.left=new FormAttachment(0,0); - gameA.setLayoutData(gameAFormData); + gameAFormData.bottom=new FormAttachment(100,0); + gameAFormData.left=new FormAttachment(0,0); + gameA.setLayoutData(gameAFormData); - FormData gameBFormData = new FormData(); - gameBFormData.bottom=new FormAttachment(100,0); - gameBFormData.left=new FormAttachment(gameA,0); - gameB.setLayoutData(gameBFormData); - - FormData gameCFormData = new FormData(); - gameCFormData.bottom=new FormAttachment(100,0); - gameCFormData.left=new FormAttachment(gameB,0); - gameC.setLayoutData(gameCFormData); - - FormData gameDFormData = new FormData(); - gameDFormData.bottom=new FormAttachment(100,0); - gameDFormData.left=new FormAttachment(gameC,0); - gameD.setLayoutData(gameDFormData); - + FormData gameBFormData = new FormData(); + gameBFormData.bottom=new FormAttachment(100,0); + gameBFormData.left=new FormAttachment(gameA,0); + gameB.setLayoutData(gameBFormData); + + FormData gameCFormData = new FormData(); + gameCFormData.bottom=new FormAttachment(100,0); + gameCFormData.left=new FormAttachment(gameB,0); + gameC.setLayoutData(gameCFormData); + + FormData gameDFormData = new FormData(); + gameDFormData.bottom=new FormAttachment(100,0); + gameDFormData.left=new FormAttachment(gameC,0); + gameD.setLayoutData(gameDFormData); + gameKeysComposite.layout(); } - + /** * Handles orientation changes. */ - void handleOrientationChange(int mode) { + void handleOrientationChange(int mode) + { //change the layout as per orientation mode } - - + + /** * Adds LSk and RSK keys to navigation keypad if the canvas is set to full screen mode. * @param mode- Indicates if the canvas is in fullscreen mode or not. True if fullscreen, False otherwise. */ - void setFullScreenMode(boolean mode) { - + void setFullScreenMode(boolean mode) + { + //add the soft keys if the canvas is set to full screen mode/remove otherwise - if(mode == true) { - - if(keypadComposite != null) { - + if(mode == true) + { + + if(keypadComposite != null) + { + skright = new Button(keypadComposite, SWT.PUSH); skright.addMouseListener(mouseListener); - + skleft = new Button(keypadComposite, SWT.PUSH); skleft.addMouseListener(mouseListener); - + //Set the style sheet - cssEngine.applyCSS(skright,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 1px; " + - "border-bottom-left-radius: 22px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-width: 3em;" + - "min-height: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); + cssEngine.applyCSS(skright,"QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 1px; " + + "border-bottom-left-radius: 22px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-width: 3em;" + + "min-height: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); - cssEngine.applyCSS(skleft,"QPushButton" + - "{" + - "background-color:blue;" + - "border-style: outset;" + - "border-width: 1px; " + - "border-bottom-right-radius: 22px;"+ - "border-color: beige;" + - "font: bold 14px;" + - "min-width: 3em;" + - "min-height: 2em;" + - "}" + - "QPushButton:pressed { background-color: rgb(224, 0, 0);" + - " border-style: inset;" + - "}"); - + cssEngine.applyCSS(skleft,"QPushButton" + + "{" + + "background-color:blue;" + + "border-style: outset;" + + "border-width: 1px; " + + "border-bottom-right-radius: 22px;"+ + "border-color: beige;" + + "font: bold 14px;" + + "min-width: 3em;" + + "min-height: 2em;" + + "}" + + "QPushButton:pressed { background-color: rgb(224, 0, 0);" + + " border-style: inset;" + + "}"); + skright.setText("RSK"); skleft.setText("LSK"); - + FormData sklFormData = new FormData(); - sklFormData.top=new FormAttachment(0, 0); - sklFormData.left=new FormAttachment(0, 0); - skleft.setLayoutData(sklFormData); - - FormData skrFormData = new FormData(); - skrFormData.top=new FormAttachment(0, 0); - skrFormData.right=new FormAttachment(100, 0); - skright.setLayoutData(skrFormData); - + sklFormData.top=new FormAttachment(0, 0); + sklFormData.left=new FormAttachment(0, 0); + skleft.setLayoutData(sklFormData); + + FormData skrFormData = new FormData(); + skrFormData.top=new FormAttachment(0, 0); + skrFormData.right=new FormAttachment(100, 0); + skright.setLayoutData(skrFormData); + keypadComposite.layout(); } } - else { + else + { //LSK and RSK buttons are not needed, remove the buttons from navigation keypad if(skright != null) skright.dispose(); if(skleft != null) skleft.dispose(); } - + } Button getLeftSoftKey() { return skleft; } - + Button getRightSoftKey() { return skright; @@ -517,83 +531,114 @@ * returns the height of the canvas keypad in pixels. * @return Height of the canvas keypad in pixels. */ - int getHeight() { - + int getHeight() + { + int navKeyPadHeight = 0; int gameKeyPadHeight = 0; - - if(keypadComposite != null) { + + if(keypadComposite != null) + { //calculate the navigation keypad height navKeyPadHeight = keypadComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; } - - if(gameKeysComposite != null) { + + if(gameKeysComposite != null) + { //calculate the game keypad height gameKeyPadHeight = gameKeysComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; } - + //return the total height return (navKeyPadHeight + gameKeyPadHeight); } - + /** * returns the keycode corresponding to the canvas keypad button. * @return keycode. */ - private int getKeyCode(Widget w) { - + private int getKeyCode(Widget w) + { + int keyCode = INVALID_CODE; - + // Find out which osk button was pressed - if(w == up) { + if(w == up) + { keyCode = UP; - } else if(w == down) { + } + else if(w == down) + { keyCode = DOWN; - } else if(w == left) { + } + else if(w == left) + { keyCode = LEFT; - } else if(w == right) { + } + else if(w == right) + { keyCode = RIGHT; - } else if(w == center) { + } + else if(w == center) + { keyCode = FIRE; - } else if(w == skleft) { + } + else if(w == skleft) + { keyCode = SLK; - } else if(w == skright) { + } + else if(w == skright) + { keyCode = SRK; - } else if(w == gameA) { + } + else if(w == gameA) + { keyCode = GAME_A; - } else if(w == gameB) { + } + else if(w == gameB) + { keyCode = GAME_B; - } else if(w == gameC) { + } + else if(w == gameC) + { keyCode = GAME_C; - } else if(w == gameD) { + } + else if(w == gameD) + { keyCode = GAME_D; - } else { + } + else + { keyCode = INVALID_CODE;; } - + return keyCode; } - - + + /** * Mouse listener. */ - class CanvasKeypadMouseListener implements MouseListener { + class CanvasKeypadMouseListener implements MouseListener + { - public void mouseDown(MouseEvent e) { - + public void mouseDown(MouseEvent e) + { + canvas.doKeyPressed(getKeyCode(e.widget)); - - keyPressed = getKeyCode(e.widget); - + + keyPressed = getKeyCode(e.widget); + // Create and Schedule the long keypress timer timerTask = new CanvasKeypadTimerTask(); timer.schedule(timerTask, KEYREPEAT_INTERVAL); } - public void mouseUp(MouseEvent e) { - - if( timerTask != null ) { + public void mouseUp(MouseEvent e) + { + + if(timerTask != null) + { //cancel the long keypress timer if it is running timerTask.cancel(); timerTask = null; @@ -601,44 +646,51 @@ canvas.doKeyReleased(getKeyCode(e.widget)); } - public void mouseMove(MouseEvent e) { - - if( timerTask != null ) { + public void mouseMove(MouseEvent e) + { + + if(timerTask != null) + { timerTask.cancel(); timerTask = null; } - + canvas.doKeyPressed(getKeyCode(e.widget)); - + keyPressed = getKeyCode(e.widget); - + // Create and Schedule Timer timerTask = new CanvasKeypadTimerTask(); timer.schedule(timerTask, KEYREPEAT_INTERVAL); - + } - public void mouseDoubleClick(MouseEvent event) { + public void mouseDoubleClick(MouseEvent event) + { //do nothing } - + } - - class CanvasKeypadTimerTask extends TimerTask { + + class CanvasKeypadTimerTask extends TimerTask + { + + public void run() + { - public void run() { - - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - canvas.doKeyPressed(keyPressed); - } + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + canvas.doKeyPressed(keyPressed); + } }); - - + + } } - - + + } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Choice.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Choice.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Choice.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,7 +19,8 @@ /** * LCDUI Choice interface. */ -public interface Choice { +public interface Choice +{ /** * One element selected at a time. diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroup.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroup.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroup.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,7 +21,8 @@ /** * Item representing a Choice group. */ -public class ChoiceGroup extends Item implements Choice { +public class ChoiceGroup extends Item implements Choice +{ private ChoiceImpl choiceImpl; private int type; @@ -32,7 +33,8 @@ * @param label the label * @param type the type */ - public ChoiceGroup(String label, int type) { + public ChoiceGroup(String label, int type) + { this(label, type, new String[] {}, null); } @@ -51,27 +53,30 @@ * @throws NullPointerException if any of the text elements is null */ public ChoiceGroup(String label, int type, - String[] textElements, - Image[] imgElements) { - switch (type) { - case Choice.EXCLUSIVE: - case Choice.POPUP: - choiceImpl = new ChoiceImpl(false); - break; - case Choice.MULTIPLE: - choiceImpl = new ChoiceImpl(true); - break; - default: - throw new IllegalArgumentException( - MsgRepository.CHOICEGROUP_EXCEPTION_INVALID_TYPE); + String[] textElements, + Image[] imgElements) + { + switch(type) + { + case Choice.EXCLUSIVE: + case Choice.POPUP: + choiceImpl = new ChoiceImpl(false); + break; + case Choice.MULTIPLE: + choiceImpl = new ChoiceImpl(true); + break; + default: + throw new IllegalArgumentException( + MsgRepository.CHOICEGROUP_EXCEPTION_INVALID_TYPE); } choiceImpl.check(textElements, imgElements); setLabel(label != null ? label : ""); this.type = type; // append elements - for (int i = 0; i < textElements.length; i++) { + for(int i = 0; i < textElements.length; i++) + { append(textElements[i], imgElements != null - ? imgElements[i] : null); + ? imgElements[i] : null); } } @@ -82,7 +87,8 @@ * @param img the image * @return index of added item */ - public int append(String text, Image img) { + public int append(String text, Image img) + { int ret = choiceImpl.append(text, img); updateParent(UPDATE_SIZE_CHANGED); return ret; @@ -95,7 +101,8 @@ * @param text the text * @param img the image */ - public void insert(int position, String text, Image img) { + public void insert(int position, String text, Image img) + { choiceImpl.insert(position, text, img); updateParent(UPDATE_SIZE_CHANGED); } @@ -107,7 +114,8 @@ * @param text the text * @param img the image */ - public void set(int position, String text, Image img) { + public void set(int position, String text, Image img) + { choiceImpl.set(position, text, img); updateParent(UPDATE_CONTENT); } @@ -117,7 +125,8 @@ * * @param position the item index */ - public void delete(int position) { + public void delete(int position) + { choiceImpl.delete(position); updateParent(UPDATE_SIZE_CHANGED); } @@ -125,7 +134,8 @@ /** * Remove all items. */ - public void deleteAll() { + public void deleteAll() + { choiceImpl.deleteAll(); updateParent(UPDATE_SIZE_CHANGED); } @@ -135,7 +145,8 @@ * * @return the ChoiceGroup's fit policy */ - public int getFitPolicy() { + public int getFitPolicy() + { return choiceImpl.getFitPolicy(); } @@ -145,7 +156,8 @@ * @param position the index of the item * @return the items font */ - public Font getFont(int position) { + public Font getFont(int position) + { return choiceImpl.getFont(position); } @@ -155,7 +167,8 @@ * @param position the index of the item * @return the items image part */ - public Image getImage(int position) { + public Image getImage(int position) + { return choiceImpl.getImage(position); } @@ -165,7 +178,8 @@ * @param position the index of the item * @return the items string part */ - public String getString(int position) { + public String getString(int position) + { return choiceImpl.getString(position); } @@ -175,7 +189,8 @@ * @param selectedArray an array with selected items * @return selected flags */ - public int getSelectedFlags(boolean[] selectedArray) { + public int getSelectedFlags(boolean[] selectedArray) + { return choiceImpl.getSelectedFlags(selectedArray); } @@ -184,7 +199,8 @@ * * @return the selected index */ - public int getSelectedIndex() { + public int getSelectedIndex() + { return choiceImpl.getSelectedIndex(); } @@ -194,7 +210,8 @@ * @param position specified element index * @return true if its selected, false otherwise */ - public boolean isSelected(int position) { + public boolean isSelected(int position) + { return choiceImpl.isSelected(position); } @@ -203,7 +220,8 @@ * * @param newFitPolicy the new fit policy */ - public void setFitPolicy(int newFitPolicy) { + public void setFitPolicy(int newFitPolicy) + { choiceImpl.setFitPolicy(newFitPolicy); updateParent(UPDATE_SIZE_CHANGED); } @@ -214,7 +232,8 @@ * @param position the index of the item * @param font the desired font */ - public void setFont(int position, Font font) { + public void setFont(int position, Font font) + { choiceImpl.setFont(position, font); updateParent(UPDATE_SIZE_CHANGED); } @@ -224,7 +243,8 @@ * * @param selectedArray an array with selected items */ - public void setSelectedFlags(boolean[] selectedArray) { + public void setSelectedFlags(boolean[] selectedArray) + { choiceImpl.setSelectedFlags(selectedArray); updateParent(UPDATE_CONTENT); } @@ -235,7 +255,8 @@ * @param position the index of the item * @param select selected or not */ - public void setSelectedIndex(int position, boolean select) { + public void setSelectedIndex(int position, boolean select) + { choiceImpl.setSelected(position, select); updateParent(UPDATE_CONTENT); } @@ -245,7 +266,8 @@ * * @return the lists size */ - public int size() { + public int size() + { return choiceImpl.size(); } @@ -254,7 +276,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return ChoiceGroupLayouter.calculateMinimumBounds(this); } @@ -263,14 +286,16 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return ChoiceGroupLayouter.calculatePreferredBounds(this); } /** * Called by widget listeners to update Item value. */ - void internalSetSelectedIndex(int position, boolean select) { + void internalSetSelectedIndex(int position, boolean select) + { choiceImpl.setSelected(position, select); // notify item state listener notifyStateChanged(); @@ -281,21 +306,24 @@ * * @return layout directive */ - int internalGetLayout() { + int internalGetLayout() + { return super.internalGetLayout() | Item.LAYOUT_NEWLINE_BEFORE; } /** * Return the ChoiceGroup type. */ - final int getType() { + final int getType() + { return type; } /* (non-Javadoc) * @see javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return true; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroupLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroupLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceGroupLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,7 +25,8 @@ /** * Responsible for layouting ChoiceGroup item. */ -class ChoiceGroupLayouter extends ItemLayouter { +class ChoiceGroupLayouter extends ItemLayouter +{ /** * Key name for selection listener. @@ -38,13 +39,14 @@ private static Shell dialogShell; private static TableExtension popupTable; - + private MouseListener mouseListener = new MouseListener(); /** * Constructor. */ - ChoiceGroupLayouter(DefaultFormLayoutPolicy dflp) { + ChoiceGroupLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } @@ -53,14 +55,17 @@ * * @param numItems */ - static Table eswtGetStaticTable(int numItems) { - if (staticTable == null) { + static Table eswtGetStaticTable(int numItems) + { + if(staticTable == null) + { staticTable = new TableExtension(eswtGetStaticShell(), SWT.NONE); staticTable.getHorizontalBar().setVisible(false); staticTable.getVerticalBar().setVisible(false); } staticTable.removeAll(); - for (int i = 0; i < numItems; i++) { + for(int i = 0; i < numItems; i++) + { new TableItem(staticTable, SWT.NONE); } return staticTable; @@ -72,68 +77,82 @@ * @param table * @param choice */ - static void eswtSetTableContents(Table table, ChoiceGroup choice) { + static void eswtSetTableContents(Table table, ChoiceGroup choice) + { - if (choice.getType() == Choice.POPUP) { + if(choice.getType() == Choice.POPUP) + { // set the only TableItem to be the selected item TableItem ti = table.getItem(0); int sel = choice.getSelectedIndex(); - if (sel >= 0) { + if(sel >= 0) + { ti.setImage(0, Image.getESWTImage(choice.getImage(sel))); ti.setText(0, choice.getString(sel)); ti.setFont(0, Font.getESWTFont(choice.getFont(sel))); } - if( ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() - == dialogShell ) { - // The popup dialog is open, update and set the items in the popup dialog - popupTable.removeAll(); - popupTable.getHorizontalBar().setVisible(false); - popupTable.getVerticalBar().setVisible(false); + if(ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() + == dialogShell) + { + // The popup dialog is open, update and set the items in the popup dialog + popupTable.removeAll(); + popupTable.getHorizontalBar().setVisible(false); + popupTable.getVerticalBar().setVisible(false); - TableItem titem = null; - for (int i = 0; i < choice.size(); i++) { - titem= new TableItem(popupTable, SWT.NONE); - titem.setImage(0, Image.getESWTImage(choice.getImage(i))); - titem.setText(0, choice.getString(i)); - titem.setFont(0, Font.getESWTFont(choice.getFont(i))); - } + TableItem titem = null; + for(int i = 0; i < choice.size(); i++) + { + titem= new TableItem(popupTable, SWT.NONE); + titem.setImage(0, Image.getESWTImage(choice.getImage(i))); + titem.setText(0, choice.getString(i)); + titem.setFont(0, Font.getESWTFont(choice.getFont(i))); + } - // calculate table size, allow maximum dialogshell's height - // and enable vertical scroll bar if needed - Point compSize = popupTable.computeSize( - dialogShell.getClientArea().width, SWT.DEFAULT); - if (compSize.y > dialogShell.getClientArea().height) { - popupTable.getVerticalBar().setVisible(true); - int itemH = popupTable.getItemHeight() + 2; - // make height a multiple of item height - compSize.y = (dialogShell.getClientArea().height / itemH) * itemH; - } - popupTable.setSize(compSize); + // calculate table size, allow maximum dialogshell's height + // and enable vertical scroll bar if needed + Point compSize = popupTable.computeSize( + dialogShell.getClientArea().width, SWT.DEFAULT); + if(compSize.y > dialogShell.getClientArea().height) + { + popupTable.getVerticalBar().setVisible(true); + int itemH = popupTable.getItemHeight() + 2; + // make height a multiple of item height + compSize.y = (dialogShell.getClientArea().height / itemH) * itemH; + } + popupTable.setSize(compSize); } - + } - else { + else + { int size = choice.size(); - if (size == table.getItemCount()) { + if(size == table.getItemCount()) + { TableItem titem = null; - for (int i = 0; i < size; i++) { + for(int i = 0; i < size; i++) + { titem = table.getItem(i); titem.setImage(0, Image.getESWTImage(choice.getImage(i))); titem.setText(0, choice.getString(i)); titem.setFont(0, Font.getESWTFont(choice.getFont(i))); } // update selection - if (choice.getType() == Choice.EXCLUSIVE) { + if(choice.getType() == Choice.EXCLUSIVE) + { table.setSelection(choice.getSelectedIndex()); } - else { + else + { boolean[] sel = new boolean[size]; choice.getSelectedFlags(sel); - for (int i = 0; i < size; i++) { - if (sel[i]) { + for(int i = 0; i < size; i++) + { + if(sel[i]) + { table.select(i); } - else { + else + { table.deselect(i); } } @@ -145,7 +164,8 @@ /** * Creates the eSWT Table for this item. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { ChoiceGroup choice = (ChoiceGroup) item; // create Table TableExtension table = new TableExtension(parent, @@ -153,13 +173,16 @@ table.getHorizontalBar().setVisible(false); table.getVerticalBar().setVisible(false); table.setWordWrap(choice.getFitPolicy() == Choice.TEXT_WRAP_ON); - if (choice.getType() == Choice.POPUP) { + if(choice.getType() == Choice.POPUP) + { // create one TableItem new TableItem(table, SWT.NONE); } - else { + else + { // add all items to table - for (int i = 0; i < choice.size(); i++) { + for(int i = 0; i < choice.size(); i++) + { new TableItem(table, SWT.NONE, i); } } @@ -170,7 +193,8 @@ /** * Add listeners to Layouter specific control. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); Table table = (Table) control; SelectionListener sl = new ChoiceGroupSelectionListener((ChoiceGroup) item); @@ -187,21 +211,25 @@ /** * Remove listeners from Layouter specific control. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); Table table = (Table) control; SelectionListener sl = (SelectionListener) table.getData(SELECTION_LISTENER); - if (sl != null) { + if(sl != null) + { table.removeSelectionListener(sl); table.setData(SELECTION_LISTENER, null); } TraverseListener tl = (TraverseListener) table.getData(TRAVERSE_LISTENER); - if (tl != null) { + if(tl != null) + { table.removeTraverseListener(tl); table.setData(TRAVERSE_LISTENER, null); } FocusListener fl = (FocusListener) table.getData(FOCUS_LISTENER); - if (fl != null) { + if(fl != null) + { table.removeFocusListener(fl); table.setData(FOCUS_LISTENER, null); } @@ -210,14 +238,16 @@ /** * Returns if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { return (control instanceof TableExtension); } /** * Updates the values and selections of ChoiceGroup. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { eswtSetTableContents((Table) control, (ChoiceGroup) item); } @@ -227,21 +257,24 @@ * @param item ChoiceGroup. * @param key key code. */ - boolean eswtOfferKeyPressed(Item item, int key) { + boolean eswtOfferKeyPressed(Item item, int key) + { LayoutObject lo = dfi.getFirstLayoutObjectOfItem(item); TableExtension tempExt; ChoiceGroup chgr = (ChoiceGroup) item; tempExt = (TableExtension) eswtFindSpecificControl(item, - lo.getControl()); + lo.getControl()); boolean ret; - if (isPopupDialogOpen()) { + if(isPopupDialogOpen()) + { ret = true; } - else if ((tempExt.getFocusIndex() == 0 && key == SWT.ARROW_UP) + else if((tempExt.getFocusIndex() == 0 && key == SWT.ARROW_UP) || (tempExt.getFocusIndex() == (tempExt.getItemCount() - 1) - && key == SWT.ARROW_DOWN) + && key == SWT.ARROW_DOWN) || (chgr.getType() == Choice.POPUP - && !isPopupDialogOpen())) { + && !isPopupDialogOpen())) + { ret = false; } /*else if (tempExt.getFocusIndex() == (tempExt.getItemCount() - 1) @@ -251,10 +284,12 @@ if (chgr.getType() == Choice.POPUP && !isPopupDialogOpen()) { return false; } */ - else if (key == SWT.ARROW_UP || key == SWT.ARROW_DOWN) { + else if(key == SWT.ARROW_UP || key == SWT.ARROW_DOWN) + { ret = true; } - else { + else + { ret = false; } return ret; @@ -266,10 +301,13 @@ * @param choicegroup ChoiceGroup object. * @return Minimum area needed to display ChoiceGroup. */ - static Point calculateMinimumBounds(final ChoiceGroup choicegroup) { + static Point calculateMinimumBounds(final ChoiceGroup choicegroup) + { final Point minSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Table table = eswtGetStaticTable(1); minSize.x = getMaximumItemWidth(choicegroup); minSize.y = table.computeSize(minSize.x, SWT.DEFAULT).y; @@ -286,11 +324,14 @@ * @return Preferred area needed to display Item. x is width and y is * height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { final Point prefSize = new Point(0, 0); final ChoiceGroup cg = (ChoiceGroup) item; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { int numItem = (cg.getType() == Choice.POPUP ? 1 : cg.size()); Table table = eswtGetStaticTable(numItem); eswtSetTableContents(table, cg); @@ -305,22 +346,25 @@ /** * Get eSWT style based on List type. */ - private int getTableStyle(int listType) { + private int getTableStyle(int listType) + { int tableStyle = SWT.NONE; - switch (listType) { - case Choice.EXCLUSIVE: - tableStyle |= SWT.SINGLE | SWT.RADIO; - break; - case Choice.MULTIPLE: - tableStyle |= /*SWT.MULTI |*/ SWT.CHECK; - break; - default: - break; + switch(listType) + { + case Choice.EXCLUSIVE: + tableStyle |= SWT.SINGLE | SWT.RADIO; + break; + case Choice.MULTIPLE: + tableStyle |= /*SWT.MULTI |*/ SWT.CHECK; + break; + default: + break; } return tableStyle; } - private boolean isPopupDialogOpen() { + private boolean isPopupDialogOpen() + { return (ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() == dialogShell); } @@ -332,7 +376,8 @@ * @param control already layouted control */ private void eswtOpenPopupDialog(final ChoiceGroup choiceGroup, - final Control control) { + final Control control) + { final Shell parentShell = choiceGroup.getParent().getShell(); dialogShell = new Shell(parentShell, SWT.DIALOG_TRIM | SWT.SYSTEM_MODAL); @@ -350,7 +395,8 @@ popupTable.getVerticalBar().setVisible(false); TableItem ti = null; - for (int i = 0; i < choiceGroup.size(); i++) { + for(int i = 0; i < choiceGroup.size(); i++) + { ti = new TableItem(popupTable, SWT.NONE); ti.setImage(0, Image.getESWTImage(choiceGroup.getImage(i))); ti.setText(0, choiceGroup.getString(i)); @@ -360,8 +406,9 @@ // calculate table size, allow maximum dialogshell's height // and enable vertical scroll bar if needed Point compSize = popupTable.computeSize( - dialogShell.getClientArea().width, SWT.DEFAULT); - if (compSize.y > dialogShell.getClientArea().height) { + dialogShell.getClientArea().width, SWT.DEFAULT); + if(compSize.y > dialogShell.getClientArea().height) + { popupTable.getVerticalBar().setVisible(true); int itemH = popupTable.getItemHeight() + 2; // make height a multiple of item height @@ -369,21 +416,25 @@ } popupTable.setSize(compSize); - Listener disposeHandler = new Listener() { - public void handleEvent(Event se) { + Listener disposeHandler = new Listener() + { + public void handleEvent(Event se) + { dialogShell.close(); dialogShell.dispose(); dialogShell = null; org.eclipse.swt.widgets.Display.getCurrent(). - removeFilter(SWT.MouseDown, mouseListener); + removeFilter(SWT.MouseDown, mouseListener); } }; // if Back command is pressed - dispose backCommand.addListener(SWT.Selection, disposeHandler); - popupTable.addListener(SWT.DefaultSelection, new Listener() { - public void handleEvent(Event se) { + popupTable.addListener(SWT.DefaultSelection, new Listener() + { + public void handleEvent(Event se) + { int index = ((Table) se.widget).indexOf((TableItem) se.item); // if table gets selected - save selection and dispose dialog choiceGroup.internalSetSelectedIndex(index, true); @@ -392,7 +443,7 @@ dialogShell.dispose(); dialogShell = null; org.eclipse.swt.widgets.Display.getCurrent(). - removeFilter(SWT.MouseDown, mouseListener); + removeFilter(SWT.MouseDown, mouseListener); } }); @@ -404,13 +455,14 @@ dialogShell.open(); //Add a mouse listener to the display to listen to a screen tap org.eclipse.swt.widgets.Display.getCurrent(). - addFilter(SWT.MouseDown, mouseListener); + addFilter(SWT.MouseDown, mouseListener); } /** * Class that receives events from Table and updates ChoiceGroup's value. */ - class ChoiceGroupSelectionListener implements SelectionListener { + class ChoiceGroupSelectionListener implements SelectionListener + { private ChoiceGroup choiceGroup; @@ -419,43 +471,53 @@ * * @param choiceGroup ChoiceGroup to be updated. */ - public ChoiceGroupSelectionListener(ChoiceGroup choiceGroup) { + public ChoiceGroupSelectionListener(ChoiceGroup choiceGroup) + { this.choiceGroup = choiceGroup; } - private void update(SelectionEvent se) { + private void update(SelectionEvent se) + { //int vPosition = dfi.vPosition; int index = ((Table) se.widget).indexOf((TableItem) se.item); choiceGroup.internalSetSelectedIndex(index, - !choiceGroup.isSelected(index)); + !choiceGroup.isSelected(index)); eswtSetTableContents(eswtGetStaticTable(1), choiceGroup); - + } - public void widgetDefaultSelected(SelectionEvent se) { - if (choiceGroup.getType() == Choice.EXCLUSIVE) { + public void widgetDefaultSelected(SelectionEvent se) + { + if(choiceGroup.getType() == Choice.EXCLUSIVE) + { update(se); - + // because Table doesn't update our custom selection // we have to do it ourselves // eswtUpdateItem(choiceGroup, ((Table) se.widget), - // Item.UPDATE_NONE, null); + // Item.UPDATE_NONE, null); } - else if (choiceGroup.getType() == Choice.POPUP) { + else if(choiceGroup.getType() == Choice.POPUP) + { eswtOpenPopupDialog(choiceGroup, ((Table) se.widget)); } } - public void widgetSelected(SelectionEvent se) { - if (choiceGroup.getType() == Choice.MULTIPLE) { - if (se.detail == SWT.CHECK) { + public void widgetSelected(SelectionEvent se) + { + if(choiceGroup.getType() == Choice.MULTIPLE) + { + if(se.detail == SWT.CHECK) + { update(se); } } - else if(choiceGroup.getType() == Choice.EXCLUSIVE) { + else if(choiceGroup.getType() == Choice.EXCLUSIVE) + { update(se); //run the default command if it exists for a exclusive choice group upon selection - if( choiceGroup.getDefaultCommand()!= null) { + if(choiceGroup.getDefaultCommand()!= null) + { choiceGroup.callCommandAction(choiceGroup.getDefaultCommand()); } } @@ -466,30 +528,36 @@ * ChoiceGroupTraverseListener listens to KeyTraverseEvent and scrolls * ChoiceGroup if needed. */ - class ChoiceGroupTraverseListener implements TraverseListener { + class ChoiceGroupTraverseListener implements TraverseListener + { private ChoiceGroup choicegroup; - public ChoiceGroupTraverseListener(ChoiceGroup choiceGr) { + public ChoiceGroupTraverseListener(ChoiceGroup choiceGr) + { choicegroup = choiceGr; } - public void keyTraversed(TraverseEvent te) { + public void keyTraversed(TraverseEvent te) + { TableExtension table = (TableExtension) te.widget; int focusedIndex = table.getFocusIndex(); // compute focused item location int itemHeight = table.getItemHeight(); int topOfTable = table.getLocation().y; - if (choicegroup.hasLabel()) { + if(choicegroup.hasLabel()) + { LayoutObject lo = dfi.getFirstLayoutObjectOfItem(choicegroup); topOfTable += lo.getY(); } int topYOfSelectedItem = topOfTable + (focusedIndex * itemHeight); - if (te.keyCode == SWT.ARROW_DOWN) { + if(te.keyCode == SWT.ARROW_DOWN) + { topYOfSelectedItem += itemHeight; dfi.eswtScrollIfNeeded(topYOfSelectedItem, topYOfSelectedItem + itemHeight); } - else if (te.keyCode == SWT.ARROW_UP) { + else if(te.keyCode == SWT.ARROW_UP) + { topYOfSelectedItem -= itemHeight; dfi.eswtScrollIfNeeded(topYOfSelectedItem, topYOfSelectedItem + itemHeight); @@ -501,26 +569,34 @@ /** * ChoiceGroupFocusListener reacts on eSWT focusGained event. */ - class ChoiceGroupFocusListener implements FocusListener { + class ChoiceGroupFocusListener implements FocusListener + { private ChoiceGroup choicegroup; - ChoiceGroupFocusListener(ChoiceGroup cg) { + ChoiceGroupFocusListener(ChoiceGroup cg) + { choicegroup = cg; } - public void focusGained(FocusEvent focusEvent) { + public void focusGained(FocusEvent focusEvent) + { TableExtension te = (TableExtension) focusEvent.widget; int direction = dfi.getDirection(); - if (choicegroup.getType() != ChoiceGroup.POPUP) { - if (direction == -1) { - //do nothing + if(choicegroup.getType() != ChoiceGroup.POPUP) + { + if(direction == -1) + { + //do nothing } - else { - if (direction == SWT.ARROW_UP || direction == SWT.ARROW_LEFT) { + else + { + if(direction == SWT.ARROW_UP || direction == SWT.ARROW_LEFT) + { te.setFocusIndex(te.getItemCount() - 1); } - else if (direction == SWT.ARROW_DOWN || direction == SWT.ARROW_RIGHT) { + else if(direction == SWT.ARROW_DOWN || direction == SWT.ARROW_RIGHT) + { te.setFocusIndex(0); } } @@ -530,48 +606,57 @@ //compute focused item location int itemHeight = te.getItemHeight(); int topOfTable = te.getLocation().y; - if (choicegroup.hasLabel()) { + if(choicegroup.hasLabel()) + { LayoutObject lo = dfi.getFirstLayoutObjectOfItem(choicegroup); topOfTable += lo.getY(); } int topYOfSelectedItem = topOfTable + (focusedIndex * itemHeight); - if (direction == SWT.ARROW_DOWN || direction == SWT.ARROW_RIGHT) { + if(direction == SWT.ARROW_DOWN || direction == SWT.ARROW_RIGHT) + { topYOfSelectedItem += itemHeight; dfi.eswtScrollIfNeeded(topYOfSelectedItem, topYOfSelectedItem + itemHeight); } - else if (direction == SWT.ARROW_UP || direction == SWT.ARROW_LEFT) { + else if(direction == SWT.ARROW_UP || direction == SWT.ARROW_LEFT) + { topYOfSelectedItem -= itemHeight; dfi.eswtScrollIfNeeded(topYOfSelectedItem, topYOfSelectedItem + itemHeight); } } - public void focusLost(FocusEvent fe) { + public void focusLost(FocusEvent fe) + { } } - - /** - * Mouse listener for disposing popup choice group on screen tap. - */ - class MouseListener implements Listener { + + /** + * Mouse listener for disposing popup choice group on screen tap. + */ + class MouseListener implements Listener + { - public void handleEvent(Event e) { - if (e.type == SWT.MouseDown) { - //Mouse button pressed - if (isPopupDialogOpen()) { - //popup choice group popup is open - if( e.y < 0 ) { - //Tapping done outside of the popup dialog, close and dispose the popup - dialogShell.close(); - dialogShell.dispose(); - dialogShell = null; - //remove the listener as it is no more needed - org.eclipse.swt.widgets.Display.getCurrent().removeFilter( - SWT.MouseDown, mouseListener); - } + public void handleEvent(Event e) + { + if(e.type == SWT.MouseDown) + { + //Mouse button pressed + if(isPopupDialogOpen()) + { + //popup choice group popup is open + if(e.y < 0) + { + //Tapping done outside of the popup dialog, close and dispose the popup + dialogShell.close(); + dialogShell.dispose(); + dialogShell = null; + //remove the listener as it is no more needed + org.eclipse.swt.widgets.Display.getCurrent().removeFilter( + SWT.MouseDown, mouseListener); } + } } } }//end Listener diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceImpl.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ChoiceImpl.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -23,18 +23,21 @@ *
            List and ChoiceGroup class use this class as their member to implement * their own functionality. */ -final class ChoiceImpl { +final class ChoiceImpl +{ /** * Internal class for storing Choice data. */ - private class ChoiceData { + private class ChoiceData + { String text; Image img; Font font; boolean sel; - ChoiceData(String text, Image img, Font font, boolean sel) { + ChoiceData(String text, Image img, Font font, boolean sel) + { this.text = text; this.img = img; this.font = font; @@ -62,7 +65,8 @@ * * @param multiSel multi or single selection */ - ChoiceImpl(boolean multiSel) { + ChoiceImpl(boolean multiSel) + { this.multiSel = multiSel; } @@ -72,33 +76,39 @@ * @param textElements string array * @param imgElements image array */ - void check(String[] textElements, Image[] imgElements) { + void check(String[] textElements, Image[] imgElements) + { // check textElements - if (textElements == null) { + if(textElements == null) + { throw new NullPointerException( - MsgRepository.CHOICE_EXCEPTION_TEXT_ARRAY_NULL); + MsgRepository.CHOICE_EXCEPTION_TEXT_ARRAY_NULL); } // check every text element - for (int i = 0; i < textElements.length; i++) { - if (textElements[i] == null) { + for(int i = 0; i < textElements.length; i++) + { + if(textElements[i] == null) + { throw new NullPointerException( - MsgRepository.CHOICE_EXCEPTION_ITEM_NULL + i); + MsgRepository.CHOICE_EXCEPTION_ITEM_NULL + i); } } // check imgElements array length - if (imgElements != null && imgElements.length != textElements.length) { + if(imgElements != null && imgElements.length != textElements.length) + { throw new IllegalArgumentException( - MsgRepository.CHOICE_EXCEPTION_INVALID_ARRAY_LENGTHS); + MsgRepository.CHOICE_EXCEPTION_INVALID_ARRAY_LENGTHS); } } /** * Append item with specified text and image. */ - int append(String text, Image image) { + int append(String text, Image image) + { validateString(text); ChoiceData data = new ChoiceData(text, image, Font.getDefaultFont(), - (!multiSel && size() == 0)); + (!multiSel && size() == 0)); items.addElement(data); // return index of added element return size() - 1; @@ -107,18 +117,20 @@ /** * Insert item with specified text and image. */ - void insert(int elementNum, String text, Image image) { + void insert(int elementNum, String text, Image image) + { validateString(text); validatePosition(elementNum, size() + 1); ChoiceData data = new ChoiceData(text, image, Font.getDefaultFont(), - (!multiSel && size() == 0)); + (!multiSel && size() == 0)); items.insertElementAt(data, elementNum); } /** * Set item with specified text and image. */ - void set(int elementNum, String text, Image image) { + void set(int elementNum, String text, Image image) + { validateString(text); validatePosition(elementNum, size()); ChoiceData data = (ChoiceData) items.elementAt(elementNum); @@ -129,7 +141,8 @@ /** * Set item's font. */ - void setFont(int elementNum, Font font) { + void setFont(int elementNum, Font font) + { validatePosition(elementNum, size()); Font checkedFont = (font == null ? Font.getDefaultFont() : font); ((ChoiceData) items.elementAt(elementNum)).font = checkedFont; @@ -138,15 +151,19 @@ /** * Delete item from specified position. */ - void delete(int elementNum) { + void delete(int elementNum) + { validatePosition(elementNum, size()); - if (!multiSel && isSelected(elementNum) && size() > 1) { + if(!multiSel && isSelected(elementNum) && size() > 1) + { // we are removing the selected item and there are more - if (elementNum == size() - 1) { + if(elementNum == size() - 1) + { // select previous item setSelected(elementNum - 1, true); } - else { + else + { // select next item setSelected(elementNum + 1, true); } @@ -157,21 +174,24 @@ /** * Delete all items. */ - void deleteAll() { + void deleteAll() + { items.removeAllElements(); } /** * Get fit policy. */ - int getFitPolicy() { + int getFitPolicy() + { return fitPolicy; } /** * Get the Font of a given item. */ - Font getFont(int elementNum) { + Font getFont(int elementNum) + { validatePosition(elementNum, size()); return ((ChoiceData) items.elementAt(elementNum)).font; } @@ -179,7 +199,8 @@ /** * Get the image of a given item. */ - Image getImage(int elementNum) { + Image getImage(int elementNum) + { validatePosition(elementNum, size()); return ((ChoiceData) items.elementAt(elementNum)).img; } @@ -187,7 +208,8 @@ /** * Get the text of a given item. */ - String getString(int elementNum) { + String getString(int elementNum) + { validatePosition(elementNum, size()); return ((ChoiceData) items.elementAt(elementNum)).text; } @@ -195,16 +217,18 @@ /** * Set fit policy. */ - void setFitPolicy(int newFitPolicy) { - switch (newFitPolicy) { - case Choice.TEXT_WRAP_DEFAULT: - case Choice.TEXT_WRAP_OFF: - case Choice.TEXT_WRAP_ON: - fitPolicy = newFitPolicy; - break; - default: - throw new IllegalArgumentException( - MsgRepository.CHOICE_EXCEPTION_INVALID_FIT_POLICY); + void setFitPolicy(int newFitPolicy) + { + switch(newFitPolicy) + { + case Choice.TEXT_WRAP_DEFAULT: + case Choice.TEXT_WRAP_OFF: + case Choice.TEXT_WRAP_ON: + fitPolicy = newFitPolicy; + break; + default: + throw new IllegalArgumentException( + MsgRepository.CHOICE_EXCEPTION_INVALID_FIT_POLICY); } } @@ -212,11 +236,15 @@ * Get the selection index. Returns the first selection index if multiple * selection is allowed. */ - int getSelectedIndex() { + int getSelectedIndex() + { final int size = size(); - if (!multiSel) { - for (int i = 0; i < size; i++) { - if (isSelected(i)) { + if(!multiSel) + { + for(int i = 0; i < size; i++) + { + if(isSelected(i)) + { return i; } } @@ -227,7 +255,8 @@ /** * Checks if an item is selected. */ - boolean isSelected(int elementNum) { + boolean isSelected(int elementNum) + { validatePosition(elementNum, size()); return ((ChoiceData) items.elementAt(elementNum)).sel; } @@ -235,16 +264,21 @@ /** * Sets an item's selection. */ - void setSelected(int elementNum, boolean select) { + void setSelected(int elementNum, boolean select) + { validatePosition(elementNum, size()); - if (multiSel) { + if(multiSel) + { ((ChoiceData) items.elementAt(elementNum)).sel = select; } - else { - if (select) { + else + { + if(select) + { // clear all final int size = size(); - for (int i = 0; i < size; i++) { + for(int i = 0; i < size; i++) + { ((ChoiceData) items.elementAt(i)).sel = false; } // set just one @@ -256,16 +290,20 @@ /** * Get selection flags. */ - int getSelectedFlags(boolean[] selectedArray) { + int getSelectedFlags(boolean[] selectedArray) + { validateSelectedArray(selectedArray); final int size = size(); int numSelected = 0; - for (int i = 0; i < size; i++) { - if (((ChoiceData) items.elementAt(i)).sel) { + for(int i = 0; i < size; i++) + { + if(((ChoiceData) items.elementAt(i)).sel) + { selectedArray[i] = true; numSelected++; } - else { + else + { selectedArray[i] = false; } } @@ -275,19 +313,26 @@ /** * Set selection flags. */ - void setSelectedFlags(boolean[] selectedArray) { + void setSelectedFlags(boolean[] selectedArray) + { validateSelectedArray(selectedArray); final int size = size(); - if (size > 0) { - if (multiSel) { - for (int i = 0; i < size; i++) { + if(size > 0) + { + if(multiSel) + { + for(int i = 0; i < size; i++) + { ((ChoiceData) items.elementAt(i)).sel = selectedArray[i]; } } - else { + else + { int firstSelected = 0; - for (int i = 0; i < size; i++) { - if (selectedArray[i]) { + for(int i = 0; i < size; i++) + { + if(selectedArray[i]) + { firstSelected = i; break; } @@ -302,7 +347,8 @@ * * @return the lists size */ - int size() { + int size() + { return items.size(); } @@ -312,10 +358,12 @@ * @param position an index of the text array * @param upperBoundary upper boundary for position */ - private void validatePosition(int position, int upperBoundary) { - if (position < 0 || position >= upperBoundary) { + private void validatePosition(int position, int upperBoundary) + { + if(position < 0 || position >= upperBoundary) + { throw new IndexOutOfBoundsException( - MsgRepository.CHOICE_EXCEPTION_INVALID_ITEM_INDEX); + MsgRepository.CHOICE_EXCEPTION_INVALID_ITEM_INDEX); } } @@ -324,10 +372,12 @@ * * @param str string */ - private void validateString(String str) { - if (str == null) { + private void validateString(String str) + { + if(str == null) + { throw new NullPointerException( - MsgRepository.CHOICE_EXCEPTION_STRING_NULL); + MsgRepository.CHOICE_EXCEPTION_STRING_NULL); } } @@ -336,14 +386,17 @@ * * @param selectedArray selected array */ - private void validateSelectedArray(boolean[] selectedArray) { - if (selectedArray == null) { + private void validateSelectedArray(boolean[] selectedArray) + { + if(selectedArray == null) + { throw new NullPointerException( - MsgRepository.CHOICE_EXCEPTION_ARRAY_NULL); + MsgRepository.CHOICE_EXCEPTION_ARRAY_NULL); } - if (selectedArray.length < size()) { + if(selectedArray.length < size()) + { throw new IllegalArgumentException( - MsgRepository.CHOICE_EXCEPTION_INVALID_ARRAY_SIZE); + MsgRepository.CHOICE_EXCEPTION_INVALID_ARRAY_SIZE); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Command.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Command.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Command.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,7 +25,8 @@ /** * Implementation of LCDUI Command class. */ -public class Command { +public class Command +{ /** * Command type SCREEN. @@ -82,7 +83,8 @@ // are mapped to eSWT priorities. private static Hashtable priorities; - static { + static + { priorities = new Hashtable(); priorities.put(new Integer(Integer.MIN_VALUE), new Integer(0)); @@ -97,7 +99,8 @@ * @param type Type of command. * @param priority Priority of command. */ - public Command(String shortLabel, int type, int priority) { + public Command(String shortLabel, int type, int priority) + { this(shortLabel, null, type, priority); } @@ -112,14 +115,17 @@ public Command(String shortLabel, String longLabel, int type, - int priority) { - if (shortLabel == null) { + int priority) + { + if(shortLabel == null) + { throw new NullPointerException( - MsgRepository.COMMAND_EXCEPTION_LABEL_IS_NULL); + MsgRepository.COMMAND_EXCEPTION_LABEL_IS_NULL); } - if (type < SCREEN || type > ITEM) { + if(type < SCREEN || type > ITEM) + { throw new IllegalArgumentException( - MsgRepository.COMMAND_EXCEPTION_INVALID_TYPE); + MsgRepository.COMMAND_EXCEPTION_INVALID_TYPE); } this.type = type; @@ -127,7 +133,8 @@ this.longLabel = longLabel; this.priority = priority; - if (EMPTY_STRING.equals(this.shortLabel)) { + if(EMPTY_STRING.equals(this.shortLabel)) + { this.shortLabel = getDefaultLabel(this.type); } } @@ -137,7 +144,8 @@ * * @return Label of this command. */ - public String getLabel() { + public String getLabel() + { return shortLabel; } @@ -146,7 +154,8 @@ * * @return Long label of this command. */ - public String getLongLabel() { + public String getLongLabel() + { return longLabel; } @@ -155,7 +164,8 @@ * * @return Type of this command. */ - public int getCommandType() { + public int getCommandType() + { return type; } @@ -164,7 +174,8 @@ * * @return Priority of this command. */ - public int getPriority() { + public int getPriority() + { return priority; } @@ -174,10 +185,12 @@ * @param control the queried Control. * @return eSWT Command. */ - org.eclipse.ercp.swt.mobile.Command getESWTCommand(Control control) { - if (control != null) { + org.eclipse.ercp.swt.mobile.Command getESWTCommand(Control control) + { + if(control != null) + { return (org.eclipse.ercp.swt.mobile.Command) - eswtCommands.get(control); + eswtCommands.get(control); } return null; } @@ -190,10 +203,13 @@ * @param listener */ void eswtAddCommandSelectionListener(Control control, - SelectionListener listener) { - if (listener != null) { + SelectionListener listener) + { + if(listener != null) + { org.eclipse.ercp.swt.mobile.Command cmd = getESWTCommand(control); - if (cmd != null && !cmd.isDisposed()) { + if(cmd != null && !cmd.isDisposed()) + { // Remove listener if it is already added. Same listener // should be in same command only once: cmd.removeSelectionListener(listener); @@ -210,10 +226,13 @@ * @param listener */ void eswtRemoveCommandSelectionListener(Control control, - SelectionListener listener) { - if (listener != null) { + SelectionListener listener) + { + if(listener != null) + { org.eclipse.ercp.swt.mobile.Command cmd = getESWTCommand(control); - if (cmd != null && !cmd.isDisposed()) { + if(cmd != null && !cmd.isDisposed()) + { cmd.removeSelectionListener(listener); } } @@ -226,10 +245,13 @@ * Shell. * @param isDefault If true, created eSWT command is set to be default one. */ - void addESWTCommand(Control control, final boolean isDefault) { + void addESWTCommand(Control control, final boolean isDefault) + { final Control finalControl = control; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtAddESWTCommand(finalControl, isDefault); } }); @@ -241,19 +263,23 @@ * @param control eSWT control on which the command is created. * @param isDefault If true, created eSWT command is set to be default one. */ - void eswtAddESWTCommand(Control control, boolean isDefault) { - if (!eswtCommands.containsKey(control)) { + void eswtAddESWTCommand(Control control, boolean isDefault) + { + if(!eswtCommands.containsKey(control)) + { int eswtType = getEswtType(type); int eswtPriority = getESWTPriority(priority); org.eclipse.ercp.swt.mobile.Command eswtCommand = new org.eclipse.ercp.swt.mobile.Command( - control, eswtType, eswtPriority); + control, eswtType, eswtPriority); eswtCommand.setText(shortLabel); - if (longLabel != null) { + if(longLabel != null) + { eswtCommand.setLongLabel(longLabel); } - if (isDefault) { + if(isDefault) + { eswtCommand.setDefaultCommand(); } eswtCommands.put(control, eswtCommand); @@ -265,10 +291,13 @@ * * @param control The Control where eSWT Command is located. */ - void removeESWTCommand(Control control) { + void removeESWTCommand(Control control) + { final Control finalControl = control; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtRemoveESWTCommand(finalControl); } }); @@ -277,9 +306,12 @@ /** * eSWT callback to remove an eSWT Command to vector of eSWT Commands. */ - void eswtRemoveESWTCommand(Control control) { - if (eswtCommands.containsKey(control)) { - if (getESWTCommand(control) != null) { + void eswtRemoveESWTCommand(Control control) + { + if(eswtCommands.containsKey(control)) + { + if(getESWTCommand(control) != null) + { getESWTCommand(control).dispose(); } eswtCommands.remove(control); @@ -292,37 +324,39 @@ * @param cmdType LCDUI type * @return mapped eSWT command type. */ - private int getEswtType(int cmdType) { + private int getEswtType(int cmdType) + { int eswtType = 0; // There are no Command types SCREEN and ITEM in eSWT so // the eSWT type GENERAL is used for those types. - switch (cmdType) { - case SCREEN: - eswtType = org.eclipse.ercp.swt.mobile.Command.GENERAL; - break; - case BACK: - eswtType = org.eclipse.ercp.swt.mobile.Command.BACK; - break; - case CANCEL: - eswtType = org.eclipse.ercp.swt.mobile.Command.CANCEL; - break; - case OK: - eswtType = org.eclipse.ercp.swt.mobile.Command.OK; - break; - case HELP: - eswtType = org.eclipse.ercp.swt.mobile.Command.HELP; - break; - case STOP: - eswtType = org.eclipse.ercp.swt.mobile.Command.STOP; - break; - case EXIT: - eswtType = org.eclipse.ercp.swt.mobile.Command.EXIT; - break; - case ITEM: - eswtType = org.eclipse.ercp.swt.mobile.Command.GENERAL; - break; - default: - break; + switch(cmdType) + { + case SCREEN: + eswtType = org.eclipse.ercp.swt.mobile.Command.GENERAL; + break; + case BACK: + eswtType = org.eclipse.ercp.swt.mobile.Command.BACK; + break; + case CANCEL: + eswtType = org.eclipse.ercp.swt.mobile.Command.CANCEL; + break; + case OK: + eswtType = org.eclipse.ercp.swt.mobile.Command.OK; + break; + case HELP: + eswtType = org.eclipse.ercp.swt.mobile.Command.HELP; + break; + case STOP: + eswtType = org.eclipse.ercp.swt.mobile.Command.STOP; + break; + case EXIT: + eswtType = org.eclipse.ercp.swt.mobile.Command.EXIT; + break; + case ITEM: + eswtType = org.eclipse.ercp.swt.mobile.Command.GENERAL; + break; + default: + break; } return eswtType; } @@ -335,36 +369,38 @@ * * @return Default label. */ - static String getDefaultLabel(int type) { + static String getDefaultLabel(int type) + { String rValue; - switch (type) { - case SCREEN: - rValue = MsgRepository.COMMAND_LABEL_SCREEN; - break; - case BACK: - rValue = MsgRepository.COMMAND_LABEL_BACK; - break; - case CANCEL: - rValue = MsgRepository.COMMAND_LABEL_CANCEL; - break; - case OK: - rValue = MsgRepository.COMMAND_LABEL_OK; - break; - case HELP: - rValue = MsgRepository.COMMAND_LABEL_HELP; - break; - case STOP: - rValue = MsgRepository.COMMAND_LABEL_STOP; - break; - case EXIT: - rValue = MsgRepository.COMMAND_LABEL_EXIT; - break; - case ITEM: - rValue = MsgRepository.COMMAND_LABEL_ITEM; - break; - default: - rValue = EMPTY_STRING; - break; + switch(type) + { + case SCREEN: + rValue = MsgRepository.COMMAND_LABEL_SCREEN; + break; + case BACK: + rValue = MsgRepository.COMMAND_LABEL_BACK; + break; + case CANCEL: + rValue = MsgRepository.COMMAND_LABEL_CANCEL; + break; + case OK: + rValue = MsgRepository.COMMAND_LABEL_OK; + break; + case HELP: + rValue = MsgRepository.COMMAND_LABEL_HELP; + break; + case STOP: + rValue = MsgRepository.COMMAND_LABEL_STOP; + break; + case EXIT: + rValue = MsgRepository.COMMAND_LABEL_EXIT; + break; + case ITEM: + rValue = MsgRepository.COMMAND_LABEL_ITEM; + break; + default: + rValue = EMPTY_STRING; + break; } return rValue; } @@ -394,17 +430,21 @@ * @see OpenLCDUI design document for more detailed description of the * algorithm. */ - private int getESWTPriority(int c) { + private int getESWTPriority(int c) + { // Find out nearest values from keys (LCDUI priorities). "a" will // be nearest smaller value and "b" will be nearest larger value. Integer a = new Integer(Integer.MIN_VALUE); Integer b = new Integer(Integer.MAX_VALUE); - for (Enumeration e = priorities.keys(); e.hasMoreElements();) { + for(Enumeration e = priorities.keys(); e.hasMoreElements();) + { Integer i = (Integer) e.nextElement(); - if ((i.intValue() >= a.intValue()) && (i.intValue() <= c)) { + if((i.intValue() >= a.intValue()) && (i.intValue() <= c)) + { a = i; } - if ((i.intValue() <= b.intValue()) && (i.intValue() >= c)) { + if((i.intValue() <= b.intValue()) && (i.intValue() >= c)) + { b = i; } } @@ -426,29 +466,36 @@ // Decide whether to use candidate or one of the nearest values: int c1 = 0; - if (ac > cb) { - if (cb < a1x) { + if(ac > cb) + { + if(cb < a1x) + { // Use nearest larger value: - c1 = (int) (b1 - cb); + c1 = (int)(b1 - cb); } - else { + else + { // Use candidate: c1 = x; } } - else { - if (ac < a1x) { + else + { + if(ac < a1x) + { // Use nearest smaller value: - c1 = (int) (a1 + ac); + c1 = (int)(a1 + ac); } - else { + else + { // Use candidate: c1 = x; } } // Save new priority to the HashTable if not already exists. - if (!priorities.contains(new Integer(c1))) { + if(!priorities.contains(new Integer(c1))) + { priorities.put(new Integer(c), new Integer(c1)); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/CommandListener.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/CommandListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/CommandListener.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,11 +19,12 @@ /** * Classes which want to listen command events should implement this interface. */ -public interface CommandListener { +public interface CommandListener +{ /** * Called by underlying system when event occurs. - * + * * @param command a Command that occurred. * @param displayable The Displayable where event occurred. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Config.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Config.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Config.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,7 +19,8 @@ /** * Class containing static constants for OpenLCDUI. */ -final class Config { +final class Config +{ static final int DISPLAYABLE_DIALOGSHELL_HEIGHT_DISPLACEMENT = 10; @@ -99,7 +100,8 @@ static final int TICKER_DISPLAY_TIME = 7000; - private Config() { + private Config() + { super(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItem.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItem.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItem.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -26,7 +26,8 @@ /** * Implementation of LCDUI abstract CustomItem class. */ -public abstract class CustomItem extends Item { +public abstract class CustomItem extends Item +{ protected static final int NONE = 0; protected static final int TRAVERSE_HORIZONTAL = 1; @@ -49,28 +50,29 @@ private int contentWidth; private int contentHeight; - private boolean repaintPending; - private int repaintX1; - private int repaintY1; - private int repaintX2; - private int repaintY2; - private Object repaintLock; + private boolean repaintPending; + private int repaintX1; + private int repaintY1; + private int repaintX2; + private int repaintY2; + private Object repaintLock; private Object cleanupLock; private Object resizeLock; - boolean bufferFlush; - - CustomItemLayouter layouter; - + boolean bufferFlush; + + CustomItemLayouter layouter; + /** * Constructor. * * @param label Label of CustomItem. */ - protected CustomItem(String label) { - repaintLock = new Object(); - cleanupLock = new Object(); - resizeLock = new Object(); + protected CustomItem(String label) + { + repaintLock = new Object(); + cleanupLock = new Object(); + resizeLock = new Object(); setLabel(label); } @@ -80,7 +82,8 @@ * @param keyCode key code * @return game action bound to the key */ - public int getGameAction(int keyCode) { + public int getGameAction(int keyCode) + { return KeyTable.getGameAction(keyCode); } @@ -89,24 +92,27 @@ * * @return bitmask of available interaction modes. */ - protected final int getInteractionModes() { + protected final int getInteractionModes() + { // TODO: check final interaction modes return TRAVERSE_HORIZONTAL | TRAVERSE_VERTICAL - | KEY_PRESS | KEY_RELEASE - | POINTER_PRESS | POINTER_DRAG | POINTER_RELEASE; + | KEY_PRESS | KEY_RELEASE + | POINTER_PRESS | POINTER_DRAG | POINTER_RELEASE; } /** * Invalidates CustomItem. */ - protected final void invalidate() { + protected final void invalidate() + { updateParent(UPDATE_SIZE_CHANGED); } /** * Requests repainting of CustomItem. */ - protected final void repaint() { + protected final void repaint() + { repaint(0, 0, contentWidth, contentHeight); } @@ -118,7 +124,8 @@ * @param aWidth * @param aHeight */ - protected final void repaint(int aX, int aY, int aWidth, int aHeight) { + protected final void repaint(int aX, int aY, int aWidth, int aHeight) + { Rectangle rect = new Rectangle(aX, aY, aWidth, aHeight); // From here it goes to updateItem() updateParent(UPDATE_REPAINT_RECT, rect); @@ -135,68 +142,79 @@ * @return true if internal traversal has occurred, false otherwise */ protected boolean traverse(int direction, int viewportWidth, - int viewportHeight, int[] visRect) { + int viewportHeight, int[] visRect) + { return false; } /** * Callback method for traverse-out event. */ - protected void traverseOut() { + protected void traverseOut() + { } /** * Callback method for key pressed event. */ - protected void keyPressed(int aKeyCode) { + protected void keyPressed(int aKeyCode) + { } /** * Callback method for key released event. */ - protected void keyReleased(int aKeyCode) { + protected void keyReleased(int aKeyCode) + { } /** * Callback method for key repeated event. */ - protected void keyRepeated(int aKeyCode) { + protected void keyRepeated(int aKeyCode) + { } /** * Callback method for pointer pressed event. */ - protected void pointerPressed(int aX, int aY) { + protected void pointerPressed(int aX, int aY) + { } /** * Callback method for pointer released event. */ - protected void pointerReleased(int aX, int aY) { + protected void pointerReleased(int aX, int aY) + { } /** * Callback method for pointer dragged event. */ - protected void pointerDragged(int aX, int aY) { + protected void pointerDragged(int aX, int aY) + { } /** * Callback method when item gets shown. */ - protected void showNotify() { + protected void showNotify() + { } /** * Callback method when item gets hidden. */ - protected void hideNotify() { + protected void hideNotify() + { } /** * Callback method for content area size change event. */ - protected void sizeChanged(int aWidth, int aHeight) { + protected void sizeChanged(int aWidth, int aHeight) + { } /** @@ -233,7 +251,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return CustomItemLayouter.calculateMinimumBounds(this); } @@ -242,7 +261,8 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return CustomItemLayouter.calculatePreferredBounds(this); } @@ -252,253 +272,288 @@ * @param newWidth * @param newHeight */ - void internalHandleSizeChanged(int newWidth, int newHeight) { - if (contentWidth != newWidth || contentHeight != newHeight) { - synchronized(resizeLock) { - contentWidth = newWidth; - contentHeight = newHeight; - } - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_SIZECHANGED, layouter.dfi.getForm()); - event.item = this; - eventDispatcher.postEvent(event); - synchronized(cleanupLock) { - cleanupNeeded = true; + void internalHandleSizeChanged(int newWidth, int newHeight) + { + if(contentWidth != newWidth || contentHeight != newHeight) + { + synchronized(resizeLock) + { + contentWidth = newWidth; + contentHeight = newHeight; + } + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_SIZECHANGED, layouter.dfi.getForm()); + event.item = this; + eventDispatcher.postEvent(event); + synchronized(cleanupLock) + { + cleanupNeeded = true; } repaint(); } } - /* - * Note that if you call this and getContentHeight() from a non-UI thread - * then it must be made sure size doesn't change between the calls. - */ - int getContentWidth() { + /* + * Note that if you call this and getContentHeight() from a non-UI thread + * then it must be made sure size doesn't change between the calls. + */ + int getContentWidth() + { return contentWidth; } - /* - * Note that if you call this and getContentHeight() from a non-UI thread - * then it must be made sure size doesn't change between the calls. - */ - int getContentHeight() { + /* + * Note that if you call this and getContentHeight() from a non-UI thread + * then it must be made sure size doesn't change between the calls. + */ + int getContentHeight() + { return contentHeight; } - boolean isFocusable() { + boolean isFocusable() + { return true; } /* - * This gets called when Form contents are modified. + * This gets called when Form contents are modified. */ - void setParent(Screen parent) { + void setParent(Screen parent) + { super.setParent(parent); - if(parent == null) { - // Item was removed from a Form - layouter = null; - } else { - // Item was added to a Form - layouter = ((CustomItemLayouter)((Form)parent).getLayoutPolicy().getLayouter(this)); + if(parent == null) + { + // Item was removed from a Form + layouter = null; + } + else + { + // Item was added to a Form + layouter = ((CustomItemLayouter)((Form)parent).getLayoutPolicy().getLayouter(this)); } } - - private boolean invalidate(int x, int y, int width, int height) { - // Regularize bounds - final int x1 = x; - final int y1 = y; - final int x2 = x + width; - final int y2 = y + height; + + private boolean invalidate(int x, int y, int width, int height) + { + // Regularize bounds + final int x1 = x; + final int y1 = y; + final int x2 = x + width; + final int y2 = y + height; - // Union the current and new damaged rects - final boolean valid = ((repaintX2 - repaintX1) <= 0) && ((repaintY2 - repaintY1) <= 0); - if (!valid) { - repaintX1 = Math.min(repaintX1, x1); - repaintY1 = Math.min(repaintY1, y1); - repaintX2 = Math.max(repaintX2, x2); - repaintY2 = Math.max(repaintY2, y2); - } else { - repaintX1 = x1; - repaintY1 = y1; - repaintX2 = x2; - repaintY2 = y2; - } + // Union the current and new damaged rects + final boolean valid = ((repaintX2 - repaintX1) <= 0) && ((repaintY2 - repaintY1) <= 0); + if(!valid) + { + repaintX1 = Math.min(repaintX1, x1); + repaintY1 = Math.min(repaintY1, y1); + repaintX2 = Math.max(repaintX2, x2); + repaintY2 = Math.max(repaintY2, y2); + } + else + { + repaintX1 = x1; + repaintY1 = y1; + repaintX2 = x2; + repaintY2 = y2; + } - // UI thread can change the size at any time. Must make sure it doesn't - // change between reading the width and the height. - final int w; - final int h; - synchronized(resizeLock) { - w = contentWidth; - h = contentHeight; - } + // UI thread can change the size at any time. Must make sure it doesn't + // change between reading the width and the height. + final int w; + final int h; + synchronized(resizeLock) + { + w = contentWidth; + h = contentHeight; + } - // Clip to bounds - repaintX1 = repaintX1 > 0 ? repaintX1 : 0; - repaintY1 = repaintY1 > 0 ? repaintY1 : 0; - repaintX2 = repaintX2 < w ? repaintX2 : w; - repaintY2 = repaintY2 < h ? repaintY2 : h; + // Clip to bounds + repaintX1 = repaintX1 > 0 ? repaintX1 : 0; + repaintY1 = repaintY1 > 0 ? repaintY1 : 0; + repaintX2 = repaintX2 < w ? repaintX2 : w; + repaintY2 = repaintY2 < h ? repaintY2 : h; - return valid; - } - - /* - * Note the control passed as a parameter can change. It must not be stored - * to the CustomItem. Adding and removing Form item is blocked for the - * duration of the call. - */ - void updateItem(Rectangle rect, Control control) { - // Paint callback event is posted without any invalid area info. - // Invalid area info is kept in the member variables. Only one event - // per Canvas is added to the queue. If there are more repaint() calls - // before the already posted event has been served those are merged - // to the invalid area in the member variables without posting a new - // event. - synchronized(repaintLock) { - if (invalidate(rect.x, rect.y, rect.width, rect.height)) { - // Note that repaintPending doesn't mean that there's a repaint - // event in the queue. It means that the invalid area is going - // to be repainted and there's no need to add a new event. - // It's possible that the repaint event has already been - // removed from the queue but repaintPending is still true. In - // that case it's currently being processed and we can still - // add to the invalid area. - if (!repaintPending) { - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent( - LCDUIEvent.CUSTOMITEM_PAINT_MIDLET_REQUEST, layouter.dfi.getForm()); - event.widget = control; - event.item = this; - eventDispatcher.postEvent(event); - repaintPending = true; - } - } - } - } - + return valid; + } + + /* + * Note the control passed as a parameter can change. It must not be stored + * to the CustomItem. Adding and removing Form item is blocked for the + * duration of the call. + */ + void updateItem(Rectangle rect, Control control) + { + // Paint callback event is posted without any invalid area info. + // Invalid area info is kept in the member variables. Only one event + // per Canvas is added to the queue. If there are more repaint() calls + // before the already posted event has been served those are merged + // to the invalid area in the member variables without posting a new + // event. + synchronized(repaintLock) + { + if(invalidate(rect.x, rect.y, rect.width, rect.height)) + { + // Note that repaintPending doesn't mean that there's a repaint + // event in the queue. It means that the invalid area is going + // to be repainted and there's no need to add a new event. + // It's possible that the repaint event has already been + // removed from the queue but repaintPending is still true. In + // that case it's currently being processed and we can still + // add to the invalid area. + if(!repaintPending) + { + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent( + LCDUIEvent.CUSTOMITEM_PAINT_MIDLET_REQUEST, layouter.dfi.getForm()); + event.widget = control; + event.item = this; + eventDispatcher.postEvent(event); + repaintPending = true; + } + } + } + } + /* * Dispatcher thread thread calls. Operations changing Form content are * blocked for the duration of the method call. It has been checked that * the eSWT widget has not been disposed and that the CustomItem has not - * been removed from the Form. + * been removed from the Form. + */ + void doCallback(final LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.CUSTOMITEM_PAINT_MIDLET_REQUEST: + case LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST: + doPaintCallback(event); + break; + case LCDUIEvent.CUSTOMITEM_HIDENOTIFY: + hideNotify(); + break; + case LCDUIEvent.CUSTOMITEM_SHOWNOTIFY: + showNotify(); + break; + case LCDUIEvent.CUSTOMITEM_KEYPRESSED: + keyPressed(event.keyCode); + break; + case LCDUIEvent.CUSTOMITEM_KEYREPEATED: + keyRepeated(event.keyCode); + break; + case LCDUIEvent.CUSTOMITEM_KEYRELEASED: + keyReleased(event.keyCode); + break; + case LCDUIEvent.CUSTOMITEM_POINTERDRAGGED: + pointerDragged(event.x, event.y); + break; + case LCDUIEvent.CUSTOMITEM_POINTERPRESSED: + pointerPressed(event.x, event.y); + break; + case LCDUIEvent.CUSTOMITEM_POINTERRELEASED: + pointerReleased(event.x, event.y); + break; + case LCDUIEvent.CUSTOMITEM_SIZECHANGED: + sizeChanged(event.width, event.height); + break; + default: + super.doCallback(event); + } + } + + /* + * Dispatcher thread calls. */ - void doCallback(final LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.CUSTOMITEM_PAINT_MIDLET_REQUEST: - case LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST: - doPaintCallback(event); - break; - case LCDUIEvent.CUSTOMITEM_HIDENOTIFY: - hideNotify(); - break; - case LCDUIEvent.CUSTOMITEM_SHOWNOTIFY: - showNotify(); - break; - case LCDUIEvent.CUSTOMITEM_KEYPRESSED: - keyPressed(event.keyCode); - break; - case LCDUIEvent.CUSTOMITEM_KEYREPEATED: - keyRepeated(event.keyCode); - break; - case LCDUIEvent.CUSTOMITEM_KEYRELEASED: - keyReleased(event.keyCode); - break; - case LCDUIEvent.CUSTOMITEM_POINTERDRAGGED: - pointerDragged(event.x, event.y); - break; - case LCDUIEvent.CUSTOMITEM_POINTERPRESSED: - pointerPressed(event.x, event.y); - break; - case LCDUIEvent.CUSTOMITEM_POINTERRELEASED: - pointerReleased(event.x, event.y); - break; - case LCDUIEvent.CUSTOMITEM_SIZECHANGED: - sizeChanged(event.width, event.height); - break; - default: - super.doCallback(event); - } - } - - /* - * Dispatcher thread calls. - */ - void doPaintCallback(final LCDUIEvent event) { - // Decide the area going to be painted by the callback. - final int redrawNowX; - final int redrawNowY; - final int redrawNowW; - final int redrawNowH; - // Before this thread obtains the repaintLock any repaint() calls - // will still be adding to the invalid area that is going to be - // painted by this callback. - synchronized(repaintLock) { - if(event.type == LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST) { - // Merge with possibly existing repaint() requests - invalidate(event.x, event.y, event.width, event.height); - } else { - // Need to add a new event to the queue in subsequent repaint() - // calls. - repaintPending = false; - } - - // Store the current area to be painted - redrawNowX = repaintX1; - redrawNowY = repaintY1; - redrawNowW = repaintX2-repaintX1; - redrawNowH = repaintY2-repaintY1; - - // After releasing the lock the repaint() calls will start with - // new invalid area. - repaintX1 = repaintX2 = repaintY1 = repaintY2 = 0; - - // Don't do the callback if there's nothing to paint - if(!((redrawNowW > 0) && (redrawNowH > 0))) { - return; - } - } - - // Prepare the GC's buffer if not done yet - if (layouter.graphics.getCommandBuffer() == null) { - layouter.graphics.initBuffered(this, event.x, event.y, event.width, event.height); - } + void doPaintCallback(final LCDUIEvent event) + { + // Decide the area going to be painted by the callback. + final int redrawNowX; + final int redrawNowY; + final int redrawNowW; + final int redrawNowH; + // Before this thread obtains the repaintLock any repaint() calls + // will still be adding to the invalid area that is going to be + // painted by this callback. + synchronized(repaintLock) + { + if(event.type == LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST) + { + // Merge with possibly existing repaint() requests + invalidate(event.x, event.y, event.width, event.height); + } + else + { + // Need to add a new event to the queue in subsequent repaint() + // calls. + repaintPending = false; + } + + // Store the current area to be painted + redrawNowX = repaintX1; + redrawNowY = repaintY1; + redrawNowW = repaintX2-repaintX1; + redrawNowH = repaintY2-repaintY1; + + // After releasing the lock the repaint() calls will start with + // new invalid area. + repaintX1 = repaintX2 = repaintY1 = repaintY2 = 0; + + // Don't do the callback if there's nothing to paint + if(!((redrawNowW > 0) && (redrawNowH > 0))) + { + return; + } + } - // Clean the background if dirty, buffer the operations. - synchronized(cleanupLock) { - if (cleanupNeeded && layouter.noBackground) { - // Must be made sure that size doesn't change between reading - // the width and the height. - int contentWidth, contentHeight; - synchronized(resizeLock) { - contentWidth = this.contentWidth; - contentHeight = this.contentHeight; - } - - layouter.graphics.setClip(0, 0, contentWidth, contentHeight); - layouter.graphics.cleanBackground(new Rectangle(0, 0, contentWidth, contentHeight)); - cleanupNeeded = false; - } - } - - // Clip must define the invalid area - layouter.graphics.setClip(redrawNowX, redrawNowY, redrawNowW, redrawNowH); - - // The callback - paint(layouter.graphics, contentWidth, contentHeight); + // Prepare the GC's buffer if not done yet + if(layouter.graphics.getCommandBuffer() == null) + { + layouter.graphics.initBuffered(this, event.x, event.y, event.width, event.height); + } + + // Clean the background if dirty, buffer the operations. + synchronized(cleanupLock) + { + if(cleanupNeeded && layouter.noBackground) + { + // Must be made sure that size doesn't change between reading + // the width and the height. + int contentWidth, contentHeight; + synchronized(resizeLock) + { + contentWidth = this.contentWidth; + contentHeight = this.contentHeight; + } + + layouter.graphics.setClip(0, 0, contentWidth, contentHeight); + layouter.graphics.cleanBackground(new Rectangle(0, 0, contentWidth, contentHeight)); + cleanupNeeded = false; + } + } - // Wait until the UI thread is available. Then in the UI thread - // synchronously send a paint event. - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if(event.widget.isDisposed()) { - return; - } - bufferFlush = true; - ((CanvasExtension) event.widget) - .redrawNow(redrawNowX, redrawNowY, redrawNowW, redrawNowH); - layouter.graphics.resetCommandBuffer(); - bufferFlush = false; - } - }); - } + // Clip must define the invalid area + layouter.graphics.setClip(redrawNowX, redrawNowY, redrawNowW, redrawNowH); + + // The callback + paint(layouter.graphics, contentWidth, contentHeight); + + // Wait until the UI thread is available. Then in the UI thread + // synchronously send a paint event. + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(event.widget.isDisposed()) + { + return; + } + bufferFlush = true; + ((CanvasExtension) event.widget) + .redrawNow(redrawNowX, redrawNowY, redrawNowW, redrawNowH); + layouter.graphics.resetCommandBuffer(); + bufferFlush = false; + } + }); + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItemLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItemLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/CustomItemLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -32,7 +32,8 @@ /** * Responsible for layouting CustomItem. */ -class CustomItemLayouter extends ItemLayouter { +class CustomItemLayouter extends ItemLayouter +{ /** * Key name for paint listener. @@ -60,65 +61,75 @@ private int timeout; private boolean disableTapDetection; private boolean suppressDragEvent; - private boolean selectionKeyCompatibility; + private boolean selectionKeyCompatibility; /** * Constructor. * * @param dflp DefaultFormLayoutPolicy used for layouting. */ - public CustomItemLayouter(DefaultFormLayoutPolicy dflp) { + public CustomItemLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); noBackground = JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_UI_ENHANCEMENT, - JadAttributeUtil.VALUE_CANVAS_HAS_BACKGROUND); + JadAttributeUtil.VALUE_CANVAS_HAS_BACKGROUND); graphics = new Graphics(); selectionKeyCompatibility = JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY, - JadAttributeUtil.VALUE_TRUE); + JadAttributeUtil.VALUE_TRUE); String tapAttr = JadAttributeUtil.getValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_TAP_DETECTION_OPTIONS); - if(tapAttr != null) { - if(tapAttr.indexOf(',') == -1) { - setDefaultTapValues(); - } - else { - String twipString = tapAttr.substring(0, tapAttr.indexOf(',')).trim(); - String timeoutString = tapAttr.substring(tapAttr.indexOf(',') + 1, tapAttr.length()).trim(); - try { - twips = Integer.parseInt(twipString); - timeout = Integer.parseInt(timeoutString); + if(tapAttr != null) + { + if(tapAttr.indexOf(',') == -1) + { + setDefaultTapValues(); + } + else + { + String twipString = tapAttr.substring(0, tapAttr.indexOf(',')).trim(); + String timeoutString = tapAttr.substring(tapAttr.indexOf(',') + 1, tapAttr.length()).trim(); + try + { + twips = Integer.parseInt(twipString); + timeout = Integer.parseInt(timeoutString); - // Check for Negative Values - if( (twips < 0) && (timeout < 0) ) { - setDefaultTapValues(); - } + // Check for Negative Values + if((twips < 0) && (timeout < 0)) + { + setDefaultTapValues(); + } - if( (twips == 0) && (timeout == 0) ) { - disableTapDetection = true; - } + if((twips == 0) && (timeout == 0)) + { + disableTapDetection = true; + } - // if any one of the value is zero, set defaults - if( !((twips != 0) && (timeout != 0)) ) { - setDefaultTapValues(); - } - } - catch (NumberFormatException e) { - // Alpha Numeric Values of Timeouts and Timeout - setDefaultTapValues(); - } - } + // if any one of the value is zero, set defaults + if(!((twips != 0) && (timeout != 0))) + { + setDefaultTapValues(); + } + } + catch(NumberFormatException e) + { + // Alpha Numeric Values of Timeouts and Timeout + setDefaultTapValues(); + } + } } else { - setDefaultTapValues(); + setDefaultTapValues(); } } - private void setDefaultTapValues() { - twips = DEFAULT_TWIPS; - timeout = DEFAULT_TIMEOUT; + private void setDefaultTapValues() + { + twips = DEFAULT_TWIPS; + timeout = DEFAULT_TIMEOUT; } /** @@ -128,16 +139,18 @@ * @param item on which it is based. Must be CustomItem. * @return Control. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { Control ret = new CanvasExtension(parent, - (noBackground ? SWT.NO_BACKGROUND : SWT.NONE)); + (noBackground ? SWT.NO_BACKGROUND : SWT.NONE)); return ret; } /** * Set the size of the layouted Control. */ - void eswtResizeControl(Item item, Control control, int width, int height) { + void eswtResizeControl(Item item, Control control, int width, int height) + { super.eswtResizeControl(item, control, width, height); CustomItem customitem = (CustomItem) item; customitem.internalHandleSizeChanged(width, height); @@ -146,7 +159,8 @@ /** * Add listeners to Layouter specific control. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); CanvasExtension canvas = (CanvasExtension) control; CIPaintListener pl = new CIPaintListener((CustomItem) item); @@ -162,16 +176,19 @@ /** * Remove listeners from Layouter specific control. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); CanvasExtension canvas = (CanvasExtension) control; CIPaintListener pl = (CIPaintListener) canvas.getData(PAINT_LISTENER); - if (pl != null) { + if(pl != null) + { canvas.removePaintListener(pl); canvas.setData(PAINT_LISTENER, null); } CIMouseListener ml = (CIMouseListener) canvas.getData(MOUSE_LISTENER); - if (ml != null) { + if(ml != null) + { canvas.removeMouseListener(ml); canvas.removeMouseMoveListener(ml); canvas.setData(MOUSE_LISTENER, null); @@ -181,15 +198,18 @@ /** * Returns if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { return (control instanceof CanvasExtension); } /** * Updates the values of CustomItem. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { - if (reason == CustomItem.UPDATE_REPAINT_RECT) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { + if(reason == CustomItem.UPDATE_REPAINT_RECT) + { Rectangle rect = (Rectangle) param; ((CustomItem)item).updateItem(rect, control); } @@ -198,22 +218,24 @@ /** * Gets Canvas direction based on SWT arrows. */ - int getCanvasDirection(int key) { + int getCanvasDirection(int key) + { int ret = 0; - switch (key) { - case SWT.ARROW_DOWN: - ret = Canvas.DOWN; - break; - case SWT.ARROW_UP: - ret = Canvas.UP; - break; - case SWT.ARROW_LEFT: - ret = Canvas.LEFT; - break; - case SWT.ARROW_RIGHT: - ret = Canvas.RIGHT; - break; - default: + switch(key) + { + case SWT.ARROW_DOWN: + ret = Canvas.DOWN; + break; + case SWT.ARROW_UP: + ret = Canvas.UP; + break; + case SWT.ARROW_LEFT: + ret = Canvas.LEFT; + break; + case SWT.ARROW_RIGHT: + ret = Canvas.RIGHT; + break; + default: } return ret; } @@ -221,9 +243,11 @@ /** * Gets the specified visRect parameter needed for traverse. */ - int[] getVisRect(Control control) { + int[] getVisRect(Control control) + { final int[] visRect = new int[4]; - if (control != null) { + if(control != null) + { Point size = control.getSize(); visRect[0] = 0; visRect[1] = 0; @@ -239,27 +263,31 @@ * @param item CustomItem. * @param key key code. */ - boolean eswtOfferKeyPressed(Item item, int key) { + boolean eswtOfferKeyPressed(Item item, int key) + { CustomItem customItem = (CustomItem) item; - if( !((selectionKeyCompatibility == true) && (key == -5)) ) { + if(!((selectionKeyCompatibility == true) && (key == -5))) + { EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_KEYPRESSED, dfi.getForm()); e.item = customItem; e.keyCode = key; eventDispatcher.postEvent(e); - } + } boolean consumed = true; int direction = getCanvasDirection(key); - if (direction > 0) { + if(direction > 0) + { Control control = eswtGetFirstControl(item); Control ctrl = eswtFindSpecificControl(item, control); int[] visRect = getVisRect(ctrl); // Offer event for inner traversal consumed = customItem.traverse(direction, - dfi.getFormWidth(), dfi.getFormHeight(), visRect); - if (consumed) { + dfi.getFormWidth(), dfi.getFormHeight(), visRect); + if(consumed) + { // if inner focus is on - scroll to inner focus Point loc = new Point(0, 0); dfi.getControlPositionOnComposite(ctrl, loc); @@ -274,10 +302,12 @@ /* (non-Javadoc) * @see ItemLayouter#eswtOfferKeyReleased(Item, int) */ - boolean eswtOfferKeyReleased(Item item, int key) { + boolean eswtOfferKeyReleased(Item item, int key) + { CustomItem customItem = (CustomItem) item; - if( !((selectionKeyCompatibility == true) && (key == -5)) ) { + if(!((selectionKeyCompatibility == true) && (key == -5))) + { EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_KEYRELEASED, dfi.getForm()); e.item = customItem; @@ -285,7 +315,8 @@ eventDispatcher.postEvent(e); } - if (getCanvasDirection(key) > 0) { + if(getCanvasDirection(key) > 0) + { return true; } return false; @@ -294,15 +325,18 @@ /* (non-Javadoc) * @see ItemLayouter#eswtFocusGained(Item, int) */ - void eswtFocusGained(Item item, int swtDir) { + void eswtFocusGained(Item item, int swtDir) + { super.eswtFocusGained(item, swtDir); CustomItem customItem = (CustomItem) item; Control control = eswtGetFirstControl(item); - if (control != null) { + if(control != null) + { Control ctrl = eswtFindSpecificControl(item, control); int[] visRect = getVisRect(ctrl); - if (customItem.traverse(getCanvasDirection(swtDir), - dfi.getFormWidth(), dfi.getFormHeight(), visRect)) { + if(customItem.traverse(getCanvasDirection(swtDir), + dfi.getFormWidth(), dfi.getFormHeight(), visRect)) + { // if inner focus is on - scroll to inner focus Point loc = new Point(0, 0); dfi.getControlPositionOnComposite(ctrl, loc); @@ -316,7 +350,8 @@ /* (non-Javadoc) * @see ItemLayouter#eswtFocusLost(Item) */ - void eswtFocusLost(Item item) { + void eswtFocusLost(Item item) + { super.eswtFocusLost(item); CustomItem customItem = (CustomItem) item; customItem.traverseOut(); @@ -325,7 +360,8 @@ /* (non-Javadoc) * @see temLayouter#eswtHandleShow(Item) */ - void eswtHandleShow(Item item) { + void eswtHandleShow(Item item) + { EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_SHOWNOTIFY, dfi.getForm()); event.item = item; @@ -337,7 +373,8 @@ /* (non-Javadoc) * @see ItemLayouter#eswtHandleHide(Item) */ - void eswtHandleHide(Item item) { + void eswtHandleHide(Item item) + { EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_HIDENOTIFY, dfi.getForm()); event.item = item; @@ -350,9 +387,10 @@ * @param customitem CustomItem object. * @return Minimum area needed to display CustomItem. */ - static Point calculateMinimumBounds(final CustomItem customitem) { + static Point calculateMinimumBounds(final CustomItem customitem) + { Point minSize = new Point(customitem.getMinContentWidth(), - customitem.getMinContentHeight()); + customitem.getMinContentHeight()); applyMinMargins(customitem, minSize); return minSize; } @@ -363,11 +401,12 @@ * @param item CustomItem object. * @return preferred area needed to display CustomItem. */ - static Point calculatePreferredBounds(final Item item) { + static Point calculatePreferredBounds(final Item item) + { CustomItem customitem = (CustomItem) item; Point prefSize = new Point( - customitem.getPrefContentWidth(item.getLockedPreferredHeight()), - customitem.getPrefContentHeight(item.getLockedPreferredWidth())); + customitem.getPrefContentWidth(item.getLockedPreferredHeight()), + customitem.getPrefContentHeight(item.getLockedPreferredWidth())); applyPrefMargins(item, prefSize); return prefSize; } @@ -375,52 +414,61 @@ /** * Paint listener. */ - class CIPaintListener implements PaintListener { + class CIPaintListener implements PaintListener + { private CustomItem customItem; - CIPaintListener(CustomItem customItem) { + CIPaintListener(CustomItem customItem) + { this.customItem = customItem; } - public void paintControl(PaintEvent pe) { - if(customItem.bufferFlush) { - // Paint event initiated by us to paint the Canvas. - pe.gc.getGCData().internalGc.render(graphics.getCommandBuffer()); - } else { - // Native toolkit is requesting an update of an area that has - // become invalid. Can't do anything here because the contents - // need to be queried from the MIDlet in another thread by - // a paint callback. For this a paint callback event is posted. - // For a moment the native toolkit thinks that the area has - // been validated when in truth it will be painted later after - // the paint callback has been executed. - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent( - LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST, dfi.getForm()); - event.x = pe.x; - event.y = pe.y; - event.width = pe.width; - event.height = pe.height; - event.widget = pe.widget; - event.item = customItem; - eventDispatcher.postEvent(event); - } + public void paintControl(PaintEvent pe) + { + if(customItem.bufferFlush) + { + // Paint event initiated by us to paint the Canvas. + pe.gc.getGCData().internalGc.render(graphics.getCommandBuffer()); + } + else + { + // Native toolkit is requesting an update of an area that has + // become invalid. Can't do anything here because the contents + // need to be queried from the MIDlet in another thread by + // a paint callback. For this a paint callback event is posted. + // For a moment the native toolkit thinks that the area has + // been validated when in truth it will be painted later after + // the paint callback has been executed. + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent( + LCDUIEvent.CUSTOMITEM_PAINT_NATIVE_REQUEST, dfi.getForm()); + event.x = pe.x; + event.y = pe.y; + event.width = pe.width; + event.height = pe.height; + event.widget = pe.widget; + event.item = customItem; + eventDispatcher.postEvent(event); + } } } /** * Mouse listener. */ - class CIMouseListener implements MouseListener, MouseMoveListener { + class CIMouseListener implements MouseListener, MouseMoveListener + { private CustomItem customItem; - CIMouseListener(CustomItem customItem) { + CIMouseListener(CustomItem customItem) + { this.customItem = customItem; } - public void mouseDown(MouseEvent event) { + public void mouseDown(MouseEvent event) + { EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_POINTERPRESSED, dfi.getForm()); e.item = customItem; @@ -428,9 +476,10 @@ e.y = event.y; eventDispatcher.postEvent(e); - if(!disableTapDetection) { + if(!disableTapDetection) + { // Supress Drag events - suppressDragEvent = true; + suppressDragEvent = true; pointerDownX = event.x; pointerDownY = event.y; @@ -438,25 +487,28 @@ // Create and Schedule Timer timerTask = new CustomItemTimerTask(); timer.schedule(timerTask, timeout); - } + } } - public void mouseUp(MouseEvent event) { + public void mouseUp(MouseEvent event) + { int pointerUpX = event.x; int pointerUpY = event.y; - if(!disableTapDetection) { + if(!disableTapDetection) + { timerTask.cancel(); timerTask = null; // If Timer not expired and Mouseup is withing rectangle assign // PointercDown to Pinter Up - if(suppressDragEvent && checkWithinRect(event.x, event.y)) { - pointerUpX = pointerDownX; - pointerUpY = pointerDownY; - suppressDragEvent = false; - } - } + if(suppressDragEvent && checkWithinRect(event.x, event.y)) + { + pointerUpX = pointerDownX; + pointerUpY = pointerDownY; + suppressDragEvent = false; + } + } EventDispatcher eventDispatcher = EventDispatcher.instance(); LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_POINTERRELEASED, dfi.getForm()); e.item = customItem; @@ -465,24 +517,28 @@ eventDispatcher.postEvent(e); } - public void mouseMove(MouseEvent event) { - // Check for timeout expiry and PointerUp falls outside rectangle - if( disableTapDetection || (!suppressDragEvent) || !checkWithinRect(event.x, event.y)) { - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_POINTERDRAGGED, dfi.getForm()); - e.item = customItem; - e.x = event.x; - e.y = event.y; - eventDispatcher.postEvent(e); + public void mouseMove(MouseEvent event) + { + // Check for timeout expiry and PointerUp falls outside rectangle + if(disableTapDetection || (!suppressDragEvent) || !checkWithinRect(event.x, event.y)) + { + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent e = eventDispatcher.newEvent(LCDUIEvent.CUSTOMITEM_POINTERDRAGGED, dfi.getForm()); + e.item = customItem; + e.x = event.x; + e.y = event.y; + eventDispatcher.postEvent(e); } } - public void mouseDoubleClick(MouseEvent event) { + public void mouseDoubleClick(MouseEvent event) + { } - boolean checkWithinRect(int x, int y) { - // Get pixel per inch - Point P = Display.getCurrent().getDPI(); + boolean checkWithinRect(int x, int y) + { + // Get pixel per inch + Point P = Display.getCurrent().getDPI(); float xPxielwidth = (twips * P.x) / 1440; float yPixelHeight = (twips * P.y) / 1440; @@ -490,42 +546,47 @@ int RightX = pointerDownX + (int) xPxielwidth; // If the rectange width falls outside the custom area - if(RightX > customItem.getContentWidth()) { - RightX = customItem.getContentWidth(); + if(RightX > customItem.getContentWidth()) + { + RightX = customItem.getContentWidth(); } int LeftX = pointerDownX - (int) xPxielwidth; // If the rectange width falls outside the custom area if(LeftX < 0) - LeftX = 0; + LeftX = 0; int TopY = pointerDownY - (int) yPixelHeight; // If the rectange height falls outside the custom area - if( TopY < 0 ) - TopY = 0; + if(TopY < 0) + TopY = 0; int DownY = pointerDownY + (int) yPixelHeight; // If the rectange heightfalls outside the custom area. - if( DownY > customItem.getContentHeight() ) - DownY = customItem.getContentHeight(); + if(DownY > customItem.getContentHeight()) + DownY = customItem.getContentHeight(); // Find the PointerUp is withing rectange - if( (x >= LeftX ) && (x <= RightX) ) { - if( (y >= TopY ) && (y <= DownY) ) { - return true; + if((x >= LeftX) && (x <= RightX)) + { + if((y >= TopY) && (y <= DownY)) + { + return true; } } - return false; + return false; } } - class CustomItemTimerTask extends TimerTask { + class CustomItemTimerTask extends TimerTask + { - public void run() { - suppressDragEvent = false; + public void run() + { + suppressDragEvent = false; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DateField.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DateField.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DateField.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -23,7 +23,8 @@ /** * Implementation of LCDUI DateField class. */ -public class DateField extends Item { +public class DateField extends Item +{ /** * Input mode that displays only date. @@ -54,7 +55,8 @@ * @throws IllegalArgumentException if input mode is not one of the * constants defined in this class. */ - public DateField(String label, int mode) { + public DateField(String label, int mode) + { this(label, mode, null); } @@ -67,7 +69,8 @@ * @throws IllegalArgumentException if input mode is not one of the * constants defined in this class. */ - public DateField(String label, int mode, TimeZone timeZone) { + public DateField(String label, int mode, TimeZone timeZone) + { setLabel(label); setInputMode(mode); this.timeZone = timeZone; @@ -78,22 +81,26 @@ * * @return Date, or null if date not set. */ - public Date getDate() { - if (date == null) { - return null; - } - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - if (mode == TIME) { - calendar.set(Calendar.YEAR,Config.DATEFIELD_ZERO_EPOCH_YEAR); - calendar.set(Calendar.MONTH,Calendar.JANUARY); - calendar.set(Calendar.DAY_OF_MONTH,1); + public Date getDate() + { + if(date == null) + { + return null; } - else if (mode == DATE) { - calendar.set(Calendar.HOUR_OF_DAY,0); - calendar.set(Calendar.MINUTE,0); - calendar.set(Calendar.SECOND,0); - } + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + if(mode == TIME) + { + calendar.set(Calendar.YEAR,Config.DATEFIELD_ZERO_EPOCH_YEAR); + calendar.set(Calendar.MONTH,Calendar.JANUARY); + calendar.set(Calendar.DAY_OF_MONTH,1); + } + else if(mode == DATE) + { + calendar.set(Calendar.HOUR_OF_DAY,0); + calendar.set(Calendar.MINUTE,0); + calendar.set(Calendar.SECOND,0); + } return calendar.getTime();//date; } @@ -102,7 +109,8 @@ * * @param newDate New date. If null, current date is cleared. */ - public void setDate(Date newDate) { + public void setDate(Date newDate) + { internalSetDate(newDate); updateParent(UPDATE_CONTENT); } @@ -112,7 +120,8 @@ * * @return Input mode. */ - public int getInputMode() { + public int getInputMode() + { return mode; } @@ -124,12 +133,14 @@ * @throws IllegalArgumentException if input mode is not one of the * constants defined in this class. */ - public void setInputMode(int inputMode) { - if ((inputMode != DATE) + public void setInputMode(int inputMode) + { + if((inputMode != DATE) && (inputMode != TIME) - && (inputMode != DATE_TIME)) { + && (inputMode != DATE_TIME)) + { throw new IllegalArgumentException( - MsgRepository.DATEFIELD_EXCEPTION_INVALID_MODE); + MsgRepository.DATEFIELD_EXCEPTION_INVALID_MODE); } mode = inputMode; updateParent(UPDATE_SIZE_CHANGED); @@ -140,7 +151,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return DateFieldLayouter.calculateMinimumBounds(this); } @@ -149,7 +161,8 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return DateFieldLayouter.calculatePreferredBounds(this); } @@ -158,7 +171,8 @@ * * @return Timezone or null if no timezone set. */ - TimeZone getTimeZone() { + TimeZone getTimeZone() + { return timeZone; } @@ -167,38 +181,45 @@ * * @param newDate new date */ - void internalSetDate(Date newDate) { - if (newDate == null) { + void internalSetDate(Date newDate) + { + if(newDate == null) + { date = null; } - else { + else + { Calendar calendar = Calendar.getInstance(); - if (timeZone != null) { + if(timeZone != null) + { calendar.setTimeZone(timeZone); } calendar.setTime(newDate); - switch (mode) { - case TIME: - if ((calendar.get(Calendar.YEAR) != Config.DATEFIELD_ZERO_EPOCH_YEAR) - || (calendar.get(Calendar.MONTH) != Calendar.JANUARY) - || (calendar.get(Calendar.DAY_OF_MONTH) != 1)) { - date = null; - } - else { - date = calendar.getTime(); - } - break; - case DATE: - calendar.set(Calendar.HOUR_OF_DAY, 0); - calendar.set(Calendar.MINUTE, 0); + switch(mode) + { + case TIME: + if((calendar.get(Calendar.YEAR) != Config.DATEFIELD_ZERO_EPOCH_YEAR) + || (calendar.get(Calendar.MONTH) != Calendar.JANUARY) + || (calendar.get(Calendar.DAY_OF_MONTH) != 1)) + { + date = null; + } + else + { date = calendar.getTime(); - break; - case DATE_TIME: - date = calendar.getTime(); - break; - default: - break; + } + break; + case DATE: + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + date = calendar.getTime(); + break; + case DATE_TIME: + date = calendar.getTime(); + break; + default: + break; } } } @@ -208,14 +229,16 @@ * * @return layout directive. */ - int internalGetLayout() { + int internalGetLayout() + { return super.internalGetLayout() | Item.LAYOUT_NEWLINE_BEFORE; } /* (non-Javadoc) * @see javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return true; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DateFieldLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DateFieldLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DateFieldLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -30,7 +30,8 @@ * Super class for all DateField Layouters. Contains their common * functionality. */ -class DateFieldLayouter extends ItemLayouter { +class DateFieldLayouter extends ItemLayouter +{ /** * Key name for modify listener. @@ -44,17 +45,20 @@ * * @param dflp DefaultFormLayoutPolicy used for layouting. */ - DateFieldLayouter(DefaultFormLayoutPolicy dflp) { + DateFieldLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } /** * Get static eSWT DateEditor widget for size calculations. */ - static DateEditor eswtGetStaticDate() { - if (staticDate == null) { + static DateEditor eswtGetStaticDate() + { + if(staticDate == null) + { staticDate = new DateEditor(eswtGetStaticShell(), SWT.NONE, - DateEditor.DATE_TIME | DateEditor.COMPACT); + DateEditor.DATE_TIME | DateEditor.COMPACT); } return staticDate; } @@ -66,31 +70,35 @@ * @param item on which it is based. Must be DateField. * @return Control. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { DateField dateField = (DateField) item; DateEditor dateEditor = null; - switch (dateField.getInputMode()) { - case DateField.TIME: - dateEditor = new DateEditor(parent, SWT.NONE, - DateEditor.TIME | DateEditor.COMPACT); - break; - case DateField.DATE: - dateEditor = new DateEditor(parent, SWT.NONE, - DateEditor.DATE | DateEditor.COMPACT); - break; - case DateField.DATE_TIME: - dateEditor = new DateEditor(parent, SWT.NONE, - DateEditor.DATE_TIME | DateEditor.COMPACT); - break; - default: - break; + switch(dateField.getInputMode()) + { + case DateField.TIME: + dateEditor = new DateEditor(parent, SWT.NONE, + DateEditor.TIME | DateEditor.COMPACT); + break; + case DateField.DATE: + dateEditor = new DateEditor(parent, SWT.NONE, + DateEditor.DATE | DateEditor.COMPACT); + break; + case DateField.DATE_TIME: + dateEditor = new DateEditor(parent, SWT.NONE, + DateEditor.DATE_TIME | DateEditor.COMPACT); + break; + default: + break; } - if (dateField.getTimeZone() != null) { + if(dateField.getTimeZone() != null) + { dateEditor.setTimeZone(dateField.getTimeZone()); } - if (dateField.getDate() != null) { + if(dateField.getDate() != null) + { dateEditor.setDate(dateField.getDate()); } return dateEditor; @@ -99,7 +107,8 @@ /** * Add listeners to Layouter specific control. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); DateField dateField = (DateField) item; DateEditor de = (DateEditor) control; @@ -111,11 +120,13 @@ /** * Remove listeners from Layouter specific control. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); DateEditor de = (DateEditor) control; ModifyListener listener = (ModifyListener) de.getData(MODIFY_LISTENER); - if (listener != null) { + if(listener != null) + { de.removeModifyListener(listener); de.setData(MODIFY_LISTENER, null); } @@ -124,22 +135,26 @@ /** * Returns if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { return (control instanceof DateEditor); } /** * Updates the values of DateField. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { DateField dateField = (DateField) item; DateEditor dateEditor = (DateEditor) control; - if (dateField.getDate() != null) { + if(dateField.getDate() != null) + { dateEditor.setDate(dateField.getDate()); } - if (dateField.getTimeZone() != null) { + if(dateField.getTimeZone() != null) + { dateEditor.setTimeZone(dateField.getTimeZone()); } } @@ -150,8 +165,10 @@ * is changed. Otherwise method returns false and allows form to transfer * focus. */ - boolean eswtOfferKeyPressed(Item item, int key) { - if (key == SWT.ARROW_LEFT || key == SWT.ARROW_RIGHT) { + boolean eswtOfferKeyPressed(Item item, int key) + { + if(key == SWT.ARROW_LEFT || key == SWT.ARROW_RIGHT) + { return true; } return false; @@ -163,10 +180,13 @@ * @param datefield DateField object. * @return Minimum area needed to display DateField. */ - static Point calculateMinimumBounds(final DateField datefield) { + static Point calculateMinimumBounds(final DateField datefield) + { final Point minSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { DateEditor tempEditor = eswtGetStaticDate(); minSize.x = getMaximumItemWidth(datefield); minSize.y = tempEditor.computeSize(minSize.x, SWT.DEFAULT).y; @@ -183,11 +203,14 @@ * @return Preferred area needed to display Item. x is width and y is * height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { final Point prefSize = new Point(0, 0); final DateField datefield = (DateField) item; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { DateEditor tempEditor = eswtGetStaticDate(); prefSize.x = getMaximumItemWidth(datefield); prefSize.y = tempEditor.computeSize(prefSize.x, SWT.DEFAULT).y; @@ -195,13 +218,14 @@ } }); return prefSize; - // return calculateMinimumBounds((DateField) item); + // return calculateMinimumBounds((DateField) item); } /** * Class that receives events from DateEditor and updates DateField's value. */ - class DateEditorModifyListener implements ModifyListener { + class DateEditorModifyListener implements ModifyListener + { private DateField dateField; @@ -209,7 +233,8 @@ * Constructor. * @param dateField DateField to be updated. */ - public DateEditorModifyListener(DateField dateField) { + public DateEditorModifyListener(DateField dateField) + { this.dateField = dateField; } @@ -218,10 +243,12 @@ * * @param e Event. */ - public void modifyText(ModifyEvent e) { + public void modifyText(ModifyEvent e) + { // Actions needed only if value is adjusted. Compare values // depending of dateField's type and exit if values are same. - if (!isEqualDate(dateField, (DateEditor) e.getSource())) { + if(!isEqualDate(dateField, (DateEditor) e.getSource())) + { Logger.method(dateField, "modify", e); dateField.internalSetDate(((DateEditor) e.getSource()).getDate()); // notify item state listener @@ -240,40 +267,46 @@ * * @return true if values are equal. */ - private boolean isEqualDate(DateField dateField, DateEditor dateEditor) { + private boolean isEqualDate(DateField dateField, DateEditor dateEditor) + { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); - if (dateField.getDate() != null && dateEditor.getDate() != null) { + if(dateField.getDate() != null && dateEditor.getDate() != null) + { // set dates of calendars c1.setTime(dateField.getDate()); c2.setTime(dateEditor.getDate()); - switch (dateField.getInputMode()) { - case DateField.DATE: - if ((c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) - && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) - && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))) { - return true; - } - break; - case DateField.TIME: - if ((c1.get(Calendar.MINUTE) == c2.get(Calendar.MINUTE)) - && (c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY))) { - return true; - } - break; - case DateField.DATE_TIME: - if ((c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) - && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) - && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) - && (c1.get(Calendar.MINUTE) == c2.get(Calendar.MINUTE)) - && (c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY))) { - return true; - } - break; - default: - break; + switch(dateField.getInputMode()) + { + case DateField.DATE: + if((c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) + && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) + && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))) + { + return true; + } + break; + case DateField.TIME: + if((c1.get(Calendar.MINUTE) == c2.get(Calendar.MINUTE)) + && (c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY))) + { + return true; + } + break; + case DateField.DATE_TIME: + if((c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) + && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) + && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) + && (c1.get(Calendar.MINUTE) == c2.get(Calendar.MINUTE)) + && (c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY))) + { + return true; + } + break; + default: + break; } } return false; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormInteraction.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormInteraction.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormInteraction.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -24,7 +24,8 @@ /** * Responsible for implementing interaction in DefaultFormLayoutPolicy. */ -class DefaultFormInteraction extends DefaultFormLayoutPolicy { +class DefaultFormInteraction extends DefaultFormLayoutPolicy +{ private static final int NO_DIRECTION = -1; @@ -41,16 +42,19 @@ * * @param form where DFLP is applied. */ - DefaultFormInteraction(Form form) { + DefaultFormInteraction(Form form) + { super(form); } - final void handleShowCurrentEvent() { + final void handleShowCurrentEvent() + { super.handleShowCurrentEvent(); eswtApplyCurrentFocus(); } - final void handleHideCurrentEvent() { + final void handleHideCurrentEvent() + { super.handleHideCurrentEvent(); direction = NO_DIRECTION; } @@ -58,25 +62,30 @@ /* (non-Javadoc) * @see DefaultFormLayoutPolicy#eswtLayoutForm(int) */ - final void eswtLayoutForm(int startIndex) { + final void eswtLayoutForm(int startIndex) + { super.eswtLayoutForm(startIndex); // clear invalid selected item eswtCheckCurrentSelectedItem(); - if (currentSelectedItem != null - && (currentSelectedItem.isFocusable())) { + if(currentSelectedItem != null + && (currentSelectedItem.isFocusable())) + { eswtApplyCurrentFocus(); } - else { + else + { // If there's no item currently selected try to find first // focusable item and set it current (if found): Item found = eswtGetNextFocusableItem( - getItem(startIndex - 1), SWT.ARROW_RIGHT); - if (found != null) { + getItem(startIndex - 1), SWT.ARROW_RIGHT); + if(found != null) + { eswtSetCurrentSelectedItem(found, NO_DIRECTION); } - else { + else + { eswtApplyCurrentFocus(); } } @@ -85,9 +94,11 @@ /* (non-Javadoc) * @see DefaultFormLayoutPolicy#eswtSetCurrentItem(Item) */ - boolean eswtSetCurrentItem(Item item) { + boolean eswtSetCurrentItem(Item item) + { boolean ret = super.eswtSetCurrentItem(item); - if (ret && item != null && item.isFocusable()) { + if(ret && item != null && item.isFocusable()) + { eswtSetCurrentSelectedItem(item, NO_DIRECTION); Logger.info("eswtSetCurrentItem" + item); } @@ -103,40 +114,48 @@ * @param keyCode eSWT key code. * @param keyType eSWT key type. */ - final void handleKeyEvent(int keyCode, int keyType) { + final void handleKeyEvent(int keyCode, int keyType) + { Logger.method(this, "handleKeyEvent", currentSelectedItem, - String.valueOf(keyCode), String.valueOf(keyType)); + String.valueOf(keyCode), String.valueOf(keyType)); boolean isDirectionalKey = isDirectionKey(keyCode); - if (keyType == SWT.KeyDown && isDirectionalKey) { + if(keyType == SWT.KeyDown && isDirectionalKey) + { eswtCheckCurrentSelectedItem(); } - if (currentSelectedItem != null) { - if (getLayouter(currentSelectedItem).eswtOfferKeyEvent( - currentSelectedItem, keyCode, keyType)) { + if(currentSelectedItem != null) + { + if(getLayouter(currentSelectedItem).eswtOfferKeyEvent( + currentSelectedItem, keyCode, keyType)) + { // if the key has been consumed return; } } // scrolling/focus traverse only happens on directional key's down event - if (keyType == SWT.KeyDown && isDirectionalKey) { + if(keyType == SWT.KeyDown && isDirectionalKey) + { // try to find next focusable item Item next = eswtGetNextFocusableItem(currentSelectedItem, keyCode); // if no visible & focusable item was found to transfer focus - if (next == currentSelectedItem) { + if(next == currentSelectedItem) + { // try to scroll a bit eswtSetScrollingPosition(getNextScrollingPosition(keyCode), - true); + true); // find next focusable after scrolling next = eswtGetNextFocusableItem(currentSelectedItem, keyCode); } - if (next != currentSelectedItem) { + if(next != currentSelectedItem) + { //textfield always have to be fully visible when focused. - if (next instanceof TextField) { + if(next instanceof TextField) + { eswtScrollToItem(next); } eswtSetCurrentSelectedItem(next, keyCode); @@ -149,9 +168,10 @@ * * @param keyCode key code */ - private boolean isDirectionKey(int keyCode) { + private boolean isDirectionKey(int keyCode) + { return (keyCode == SWT.ARROW_DOWN || keyCode == SWT.ARROW_UP - || keyCode == SWT.ARROW_LEFT || keyCode == SWT.ARROW_RIGHT); + || keyCode == SWT.ARROW_LEFT || keyCode == SWT.ARROW_RIGHT); } /** @@ -162,9 +182,10 @@ * @param y coordinate relative to scrolledComposite * @param type event type: SWT.MouseDown, SWT.MouseMove, SWT.MouseUp */ - final void handlePointerEvent(int x, int y, int type) { + final void handlePointerEvent(int x, int y, int type) + { Logger.method(this, "handlePointerEvent", String.valueOf(x), - String.valueOf(y), String.valueOf(type)); + String.valueOf(y), String.valueOf(type)); // TODO: change when DirectUI style arrives. /* @@ -244,17 +265,22 @@ * @param y coordinate. * @return Item. */ - Item eswtFindItemUnderMouse(int x, int y) { + Item eswtFindItemUnderMouse(int x, int y) + { Row itemRow; - for (int i = 0; i < getRowCount(); i++) { + for(int i = 0; i < getRowCount(); i++) + { itemRow = getRow(i); - if (itemRow.getYShift() <= y && y <= itemRow.getBottomPosition()) { + if(itemRow.getYShift() <= y && y <= itemRow.getBottomPosition()) + { LayoutObject lo; - for (int j = 0; j < itemRow.size(); j++) { + for(int j = 0; j < itemRow.size(); j++) + { lo = itemRow.getLayoutObject(j); - if (lo.contains(x, y)) { + if(lo.contains(x, y)) + { Logger.info("Item under mouse: " - + lo.getOwningItem()); + + lo.getOwningItem()); currentlyUnderMouse = lo; return lo.getOwningItem(); } @@ -268,7 +294,8 @@ /* (non-Javadoc) * @see DefaultFormLayoutPolicy#eswtHandleVisibilityChanges() */ - protected void eswtHandleVisibilityChanges() { + protected void eswtHandleVisibilityChanges() + { super.eswtHandleVisibilityChanges(); eswtCheckCurrentSelectedItem(); } @@ -282,77 +309,93 @@ * * @return Nearest focusable item or null if no item found. */ - final Item eswtGetNextFocusableItem(Item fromItem, int dir) { + final Item eswtGetNextFocusableItem(Item fromItem, int dir) + { Item nextItem = fromItem; - switch (dir) { - case SWT.ARROW_RIGHT: { - LayoutObject obj = getLastLayoutObjectOfItem(fromItem); - while ((obj = getNextLayoutObjectOfItem(obj, null)) != null) { - Item owner = obj.getOwningItem(); - if (owner != null && owner != fromItem - && owner.isFocusable() - && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) { - nextItem = owner; - break; - } + switch(dir) + { + case SWT.ARROW_RIGHT: + { + LayoutObject obj = getLastLayoutObjectOfItem(fromItem); + while((obj = getNextLayoutObjectOfItem(obj, null)) != null) + { + Item owner = obj.getOwningItem(); + if(owner != null && owner != fromItem + && owner.isFocusable() + && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) + { + nextItem = owner; + break; } - break; } + break; + } - case SWT.ARROW_LEFT: { - LayoutObject obj = getFirstLayoutObjectOfItem(fromItem); - while ((obj = getPrevLayoutObjectOfItem(obj, null)) != null) { - Item owner = obj.getOwningItem(); - if (owner != null && owner != fromItem - && owner.isFocusable() - && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) { + case SWT.ARROW_LEFT: + { + LayoutObject obj = getFirstLayoutObjectOfItem(fromItem); + while((obj = getPrevLayoutObjectOfItem(obj, null)) != null) + { + Item owner = obj.getOwningItem(); + if(owner != null && owner != fromItem + && owner.isFocusable() + && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) + { + nextItem = owner; + break; + } + } + break; + } + + case SWT.ARROW_DOWN: + { + int minDist = Integer.MAX_VALUE; + LayoutObject start = getLastLayoutObjectOfItem(fromItem); + LayoutObject obj = start; + while((obj = getNextLayoutObjectOfItem(obj, null)) != null) + { + Item owner = obj.getOwningItem(); + if(owner != null && owner != fromItem + && owner.isFocusable() && obj.isBelow(start) + && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) + { + int dist = obj.distanceTo(start); + if(dist < minDist) + { + minDist = dist; nextItem = owner; - break; } } - break; } + break; + } - case SWT.ARROW_DOWN: { - int minDist = Integer.MAX_VALUE; - LayoutObject start = getLastLayoutObjectOfItem(fromItem); - LayoutObject obj = start; - while ((obj = getNextLayoutObjectOfItem(obj, null)) != null) { - Item owner = obj.getOwningItem(); - if (owner != null && owner != fromItem - && owner.isFocusable() && obj.isBelow(start) - && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) { - int dist = obj.distanceTo(start); - if (dist < minDist) { - minDist = dist; - nextItem = owner; - } + case SWT.ARROW_UP: + { + int minDist = Integer.MAX_VALUE; + LayoutObject start = getFirstLayoutObjectOfItem(fromItem); + LayoutObject obj = start; + while((obj = getPrevLayoutObjectOfItem(obj, null)) != null) + { + Item owner = obj.getOwningItem(); + if(owner != null && owner != fromItem + && owner.isFocusable() && obj.isAbove(start) + && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) + { + int dist = obj.distanceTo(start); + if(dist < minDist) + { + minDist = dist; + nextItem = owner; } } - break; } + break; + } - case SWT.ARROW_UP: { - int minDist = Integer.MAX_VALUE; - LayoutObject start = getFirstLayoutObjectOfItem(fromItem); - LayoutObject obj = start; - while ((obj = getPrevLayoutObjectOfItem(obj, null)) != null) { - Item owner = obj.getOwningItem(); - if (owner != null && owner != fromItem - && owner.isFocusable() && obj.isAbove(start) - && isPartiallyVisible(obj, Config.DFI_VISIBILITY_PERCENT)) { - int dist = obj.distanceTo(start); - if (dist < minDist) { - minDist = dist; - nextItem = owner; - } - } - } - break; - } - - default: + default: } return nextItem; @@ -362,10 +405,13 @@ * Check if the currentSelectedItem is valid and visible. If not then it * sets it to null. */ - final void eswtCheckCurrentSelectedItem() { - if (currentSelectedItem != null) { - if (currentSelectedItem.getParent() != getForm() - || !currentSelectedItem.isVisible()) { + final void eswtCheckCurrentSelectedItem() + { + if(currentSelectedItem != null) + { + if(currentSelectedItem.getParent() != getForm() + || !currentSelectedItem.isVisible()) + { // we need to find another Logger.method(this, "eswtCheckCurrentSelectedItem"); eswtSetCurrentSelectedItem(null, NO_DIRECTION); @@ -381,26 +427,30 @@ * @param item Item to set as current selected. If null, nothing happens. * @param dir Direction which is delivered to layouter. */ - void eswtSetCurrentSelectedItem(Item item, int dir) { - if (currentSelectedItem != item) { + void eswtSetCurrentSelectedItem(Item item, int dir) + { + if(currentSelectedItem != item) + { Logger.info(this + "::SelectedItem: " - + currentSelectedItem + " --(" + dir + ")--> " + item); + + currentSelectedItem + " --(" + dir + ")--> " + item); // Save direction direction = dir; // Remove focus from currentSelectedItem and notify its Layouter. - if (currentSelectedItem != null) { + if(currentSelectedItem != null) + { getLayouter(currentSelectedItem).eswtFocusLost( - currentSelectedItem); + currentSelectedItem); } // Set new currentSelectedItem, must be focusable or null currentSelectedItem = item; // Set focus to currentSelectedItem and notify its Layouter. - if (currentSelectedItem != null) { + if(currentSelectedItem != null) + { getLayouter(currentSelectedItem).eswtFocusGained( - currentSelectedItem, dir); + currentSelectedItem, dir); } // Apply eSWT focus to currentSelectedItem's control @@ -416,24 +466,28 @@ * @param item Item to set as current selected. If null, nothing happens. * @param dir Direction which is delivered to layouter. */ - void eswtSetCurrentSelectedItem(Item item) { - if (currentSelectedItem != item) { + void eswtSetCurrentSelectedItem(Item item) + { + if(currentSelectedItem != item) + { Logger.info(this + "::SelectedItem: " - + currentSelectedItem + " ---> " + item); + + currentSelectedItem + " ---> " + item); // Remove focus from currentSelectedItem and notify its Layouter. - if (currentSelectedItem != null) { + if(currentSelectedItem != null) + { getLayouter(currentSelectedItem).eswtFocusLost( - currentSelectedItem); + currentSelectedItem); } // Set new currentSelectedItem, must be focusable or null currentSelectedItem = item; // Set focus to currentSelectedItem and notify its Layouter. - if (currentSelectedItem != null) { + if(currentSelectedItem != null) + { getLayouter(currentSelectedItem).eswtFocusGained( - currentSelectedItem, NO_DIRECTION); + currentSelectedItem, NO_DIRECTION); } // Apply eSWT focus to currentSelectedItem's control @@ -451,14 +505,18 @@ * If currentSelectedItem is null or form is not shown, this method has no * effect. */ - void eswtApplyCurrentFocus() { - if (isFormCurrent()) { + void eswtApplyCurrentFocus() + { + if(isFormCurrent()) + { // if any of the Item's LayoutObjects is visible - if (isItemPartiallyVisible(currentSelectedItem)) { + if(isItemPartiallyVisible(currentSelectedItem)) + { Logger.method(this, "ApplyFocus", currentSelectedItem); eswtSetFocusToFirstControl(currentSelectedItem); } - else { + else + { Logger.method(this, "ApplyFocus", "dummy"); formComposite.forceFocus(); } @@ -471,10 +529,13 @@ * * @param item an item which first LayoutObject is set focused. */ - void eswtSetFocusToFirstControl(Item item) { - if (item != null && item.isFocusable()) { + void eswtSetFocusToFirstControl(Item item) + { + if(item != null && item.isFocusable()) + { LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { lo.getControl().forceFocus(); } } @@ -485,7 +546,8 @@ * * @return Current selected item. May also return null. */ - Item getCurrentSelectedItem() { + Item getCurrentSelectedItem() + { return currentSelectedItem; } @@ -494,34 +556,41 @@ * * @return direction of scrolling. */ - int getDirection() { + int getDirection() + { return direction; } /* (non-Javadoc) * @see DefaultFormLayoutPolicy#eswtResizeItemAndShift(Item) */ - int eswtResizeItemAndShift(Item item) { + int eswtResizeItemAndShift(Item item) + { // save the state of the last row before resizing and Shifting. boolean itemWasVisible = isItemPartiallyVisible(item); int newVPosition = super.eswtResizeItemAndShift(item); - if (item == currentSelectedItem) { - if (itemWasVisible) { + if(item == currentSelectedItem) + { + if(itemWasVisible) + { int itemTop = getItemTopPosition(item); int itemBottom = getItemBottomPosition(item); // currentSelectedItem has to be focused if it was focused // before resizing e.g TextField when it is resized by adding a // new row and it was in the bottom of the Screen. - if (newVPosition <= itemTop - && (newVPosition + getFormHeight()) >= itemBottom) { + if(newVPosition <= itemTop + && (newVPosition + getFormHeight()) >= itemBottom) + { // do not change vPosition; } - else if (newVPosition > itemTop) { + else if(newVPosition > itemTop) + { newVPosition = itemTop; } - else if ((newVPosition + getFormHeight()) < itemBottom) { + else if((newVPosition + getFormHeight()) < itemBottom) + { newVPosition = itemBottom - getFormHeight(); } } @@ -535,9 +604,12 @@ /** * Reset timer for do layout with a given start index. */ - private void resetEventTimer(boolean directionUp, int y) { - if (eventTimer != null) { - if (eventTask != null) { + private void resetEventTimer(boolean directionUp, int y) + { + if(eventTimer != null) + { + if(eventTask != null) + { eventTask.cancel(); eventTask = null; } @@ -550,22 +622,27 @@ /** * Form Timer task. Triggers the formComposite to Layout. */ - class EventGeneratorTask extends TimerTask { + class EventGeneratorTask extends TimerTask + { private boolean isUpDirection; private int localY; - public EventGeneratorTask(boolean direction, int y) { + public EventGeneratorTask(boolean direction, int y) + { isUpDirection = direction; localY = y; Logger.info("y is " + localY); } - public void run() { - if (isUpDirection) { + public void run() + { + if(isUpDirection) + { localY -= Config.DFI_EVENT_MOVE_DELTA; } - else { + else + { localY += Config.DFI_EVENT_MOVE_DELTA; } handlePointerEvent(0, localY, SWT.MouseMove); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormLayoutPolicy.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormLayoutPolicy.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DefaultFormLayoutPolicy.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -27,7 +27,8 @@ /** * DefaultFormLayoutPolciy implements form layout algorithm. */ -class DefaultFormLayoutPolicy extends FormLayoutPolicy { +class DefaultFormLayoutPolicy extends FormLayoutPolicy +{ /** * Form instance (not owned). @@ -79,14 +80,15 @@ * * @param form Form to perform layout on. */ - DefaultFormLayoutPolicy(Form form) { + DefaultFormLayoutPolicy(Form form) + { this.form = form; formComposite = form.getFormComposite(); imIL = new ImageItemLayouter(this); sIL = new StringItemLayouter(this); gL = new GaugeLayouter(this); dfL = new DateFieldLayouter(this); - tfL = new TextFieldLayouter (this); + tfL = new TextFieldLayouter(this); cgL = new ChoiceGroupLayouter(this); ciL = new CustomItemLayouter(this); sL = new SpacerLayouter(this); @@ -95,9 +97,12 @@ /** * Dispose and cleanup layouted items. */ - void dispose() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void dispose() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtClearRows(0, null); } }); @@ -106,16 +111,20 @@ /** * Log out a control with all its children at the given indentation level. */ - void logControl(int level, Control control) { - if (control != null) { + void logControl(int level, Control control) + { + if(control != null) + { String s2 = control.toString(); s2 = s2.substring(0, s2.indexOf('}') - 1); String s3 = control.getBounds().toString(); s3 = s3.substring(s3.indexOf('{')); Logger.verbose(Logger.indent(s2 + s3, level * 2)); - if (control instanceof Composite) { + if(control instanceof Composite) + { Control[] arr = ((Composite) control).getChildren(); - for (int i = 0; i < arr.length; i++) { + for(int i = 0; i < arr.length; i++) + { logControl(level + 1, arr[i]); } } @@ -125,17 +134,21 @@ /** * Log out all layoutobjects for each item. */ - void logFormLayout() { + void logFormLayout() + { Logger.verbose(form + " ---------------------------------------------"); LayoutObject lo = null; Item item = null; int line = -1; - while ((lo = getNextLayoutObjectOfItem(lo, null)) != null) { - if (lo.getOwningItem() != item) { + while((lo = getNextLayoutObjectOfItem(lo, null)) != null) + { + if(lo.getOwningItem() != item) + { item = lo.getOwningItem(); Logger.verbose(item.toString()); } - if (lo.getRowIdx() != line) { + if(lo.getRowIdx() != line) + { line = lo.getRowIdx(); } Logger.verbose(Logger.indent("Row:" + lo.getRowIdx(), 2)); @@ -148,7 +161,8 @@ * Called when Form is about to be shown.
            * NOTE: this is called from eSWT UI-thread */ - void handleShowCurrentEvent() { + void handleShowCurrentEvent() + { Logger.method(this, "handleShowCurrentEvent"); isCurrent = true; @@ -157,8 +171,10 @@ Item item = null; LayoutObject lo = null; - while ((lo = getNextLayoutObjectOfItem(lo, null)) != null) { - if (lo.getOwningItem() != item) { + while((lo = getNextLayoutObjectOfItem(lo, null)) != null) + { + if(lo.getOwningItem() != item) + { // item border item = lo.getOwningItem(); getLayouter(item).eswtAddListeners(item, lo); @@ -170,14 +186,17 @@ * Called when Form is about to be hidden.
            * NOTE: this is called from eSWT UI-thread */ - void handleHideCurrentEvent() { + void handleHideCurrentEvent() + { Logger.method(this, "handleHideCurrentEvent"); isCurrent = false; Item item = null; LayoutObject lo = null; - while ((lo = getNextLayoutObjectOfItem(lo, null)) != null) { - if (lo.getOwningItem() != item) { + while((lo = getNextLayoutObjectOfItem(lo, null)) != null) + { + if(lo.getOwningItem() != item) + { // item border item = lo.getOwningItem(); getLayouter(item).eswtRemoveListeners(item, lo); @@ -190,10 +209,12 @@ * Called when Form is beeing resized.
            * NOTE: this is called from eSWT UI-thread */ - void handleResizeEvent(int width, int height) { + void handleResizeEvent(int width, int height) + { // Logger.method(this, "handleResizeEvent"); int numitems = getItemCount(); - for (int i = 0; i < numitems; i++) { + for(int i = 0; i < numitems; i++) + { getItem(i).invalidateCachedSizes(); } ItemLayouter.eswtUpdateStaticShellSize(width, height); @@ -204,9 +225,12 @@ * * @param startItem - index of item which need to be layouted. */ - void layoutForm(final int startItem) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void layoutForm(final int startItem) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtLayoutForm(startItem); } }); @@ -215,20 +239,24 @@ /** * eSWT callback for doLayout(). */ - void eswtLayoutForm(int startItem) { + void eswtLayoutForm(int startItem) + { int numItems = getItemCount(); Logger.method(this, "eswtLayoutForm", startItem + " / " + numItems); eswtUpdateFormComposite(false); - if (numItems > 0) { + if(numItems > 0) + { Item previousItem = null; int startRowIndex = 0; - if (startItem > 0) { + if(startItem > 0) + { // Find row with previous item. previousItem = getItem(startItem - 1); Row prevItemRow = getLastRowOfItem(previousItem); - if (prevItemRow != null) { + if(prevItemRow != null) + { startRowIndex = rows.indexOf(prevItemRow); } } @@ -237,34 +265,40 @@ eswtClearRows(startRowIndex, previousItem); // Layout items - for (int i = startItem; i < numItems; i++) { + for(int i = startItem; i < numItems; i++) + { eswtLayoutItem(getItem(i)); } // Update last row eswtUpdateRow(getLastRow()); } - else { + else + { eswtClearRows(0, null); } // check if we need to scroll to a particular item - if (deferredScrollToItem != null) { + if(deferredScrollToItem != null) + { eswtSetCurrentItem(deferredScrollToItem); deferredScrollToItem = null; } eswtUpdateFormComposite(true); eswtHandleVisibilityChanges(); - if (Logger.isLogVerbose()) { + if(Logger.isLogVerbose()) + { logFormLayout(); } } - void handleKeyEvent(int keyCode, int keyType) { + void handleKeyEvent(int keyCode, int keyType) + { // Implemented in sub-class DefaultFormInteraction } - void handlePointerEvent(int x, int y, int type) { + void handlePointerEvent(int x, int y, int type) + { // Implemented in sub-class DefaultFormInteraction } @@ -274,10 +308,13 @@ * * @param item Item to set as current item. */ - void setCurrentItem(final Item item) { + void setCurrentItem(final Item item) + { Logger.method(this, "setCurrentItem", item); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSetCurrentItem(item); } }); @@ -286,51 +323,66 @@ /** * eSWT callback for setCurrentItem. */ - boolean eswtSetCurrentItem(Item item) { - if (item != null) { - if (isItemLayouted(item)) { + boolean eswtSetCurrentItem(Item item) + { + if(item != null) + { + if(isItemLayouted(item)) + { eswtScrollToItem(item); deferredScrollToItem = null; return true; } - else { + else + { deferredScrollToItem = item; } } return false; } - void eswtScrollToItem(Item item) { - if (item != null) { + void eswtScrollToItem(Item item) + { + if(item != null) + { int pos = getItemBottomPosition(item) - getFormHeight(); - if (!isItemPartiallyVisible(item)) { + if(!isItemPartiallyVisible(item)) + { eswtSetScrollingPosition(pos, true); } - else if (item instanceof TextField && !isItemFullyVisible(item)) { + else if(item instanceof TextField && !isItemFullyVisible(item)) + { eswtSetScrollingPosition(pos, true); } } } - void eswtScrolltoRegion(int yTop, int yBottom, int swtDir) { - if (yTop < vPosition || yBottom > vPosition + getFormHeight()) { + void eswtScrolltoRegion(int yTop, int yBottom, int swtDir) + { + if(yTop < vPosition || yBottom > vPosition + getFormHeight()) + { // if the region is somewhat outside the screen - if (swtDir == SWT.ARROW_DOWN || swtDir == SWT.ARROW_RIGHT) { + if(swtDir == SWT.ARROW_DOWN || swtDir == SWT.ARROW_RIGHT) + { // align to top eswtSetScrollingPosition(yTop, true); } - else { + else + { // align to bottom eswtSetScrollingPosition(yBottom - getFormHeight(), true); } } } - void eswtScrollIfNeeded(final int top, final int bottom) { - if (bottom > vPosition + getFormHeight()) { + void eswtScrollIfNeeded(final int top, final int bottom) + { + if(bottom > vPosition + getFormHeight()) + { eswtSetScrollingPosition(bottom - (getFormHeight() / 2), true); } - else if (top < vPosition) { + else if(top < vPosition) + { eswtSetScrollingPosition(bottom - (getFormHeight() / 2), true); } } @@ -338,8 +390,10 @@ /** * Get control's position relative to composite. */ - void getControlPositionOnComposite(Control control, Point location) { - if (control != formComposite) { + void getControlPositionOnComposite(Control control, Point location) + { + if(control != formComposite) + { Point rel = control.getLocation(); location.x += rel.x; location.y += rel.y; @@ -350,16 +404,20 @@ /** * eSWT specific calls to do update ScrolledComposite. */ - private void eswtUpdateFormComposite(boolean show) { - if (getRowCount() > 0) { - if (show) { + private void eswtUpdateFormComposite(boolean show) + { + if(getRowCount() > 0) + { + if(show) + { formComposite.updateScrollbar(getLastRow().getBottomPosition()); formComposite.pack(); } } // Could happen if changing item from very tall to very short. // so we have to update VPosition - if (getVPosition() > eswtGetMaxVPosition()) { + if(getVPosition() > eswtGetMaxVPosition()) + { eswtSetScrollingPosition(eswtGetMaxVPosition(), false); } @@ -373,25 +431,30 @@ * @param startIndex Start row from which to clean. * @param keepItem - item in a startRow which shouldn't be recreated. */ - private void eswtClearRows(int startIndex, Item keepItem) { + private void eswtClearRows(int startIndex, Item keepItem) + { Logger.method(this, "clearRows", String.valueOf(startIndex), keepItem); Row row = null; - for (int i = (getRowCount() - 1); i >= startIndex; i--) { + for(int i = (getRowCount() - 1); i >= startIndex; i--) + { row = getRow(i); - if (row.cleanRow(keepItem)) { + if(row.cleanRow(keepItem)) + { break; } - else { + else + { rows.removeElement(row); } } // one row always should be available. - if ((getRowCount() == 0)) { + if((getRowCount() == 0)) + { // rows.addElement(tempRow); currentHLayoutDirective = Item.LAYOUT_DEFAULT; Row newRow = new Row(ItemLayouter.getMaximumItemWidth(null), - getCurrentHLayoutDirective()); + getCurrentHLayoutDirective()); rows.addElement(newRow); } } @@ -401,8 +464,10 @@ * * @param row Row */ - private void eswtUpdateRow(Row row) { - if (row != null) { + private void eswtUpdateRow(Row row) + { + if(row != null) + { //Logger.verbose("updateRow start: " + row); int numShrink = row.getNumLayoutObjects(Item.LAYOUT_SHRINK); int numExpand = row.getNumLayoutObjects(Item.LAYOUT_EXPAND); @@ -412,25 +477,31 @@ // Expand items vertically with VSHRINK or VEXPAND layout directive LayoutObject lo = null; int maxHeight = row.getRowHeight(vMask); - while ((lo = row.getNextLayoutObject(lo, vMask)) != null) { - if (lo.getOwningItem().hasLayout(Item.LAYOUT_VSHRINK)) { + while((lo = row.getNextLayoutObject(lo, vMask)) != null) + { + if(lo.getOwningItem().hasLayout(Item.LAYOUT_VSHRINK)) + { int pref = lo.getOwningItem().getPreferredHeight(); getLayouter(lo.getOwningItem()).eswtResizeObject(lo, lo.getWidth(), Math.min(pref, maxHeight)); } - else if (lo.getOwningItem().hasLayout(Item.LAYOUT_VEXPAND)) { + else if(lo.getOwningItem().hasLayout(Item.LAYOUT_VEXPAND)) + { getLayouter(lo.getOwningItem()).eswtResizeObject(lo, lo.getWidth(), maxHeight); } } // Expand items with SHRINK layout directive - if (numShrink > 0) { + if(numShrink > 0) + { // Get extra space before shrink and expand int offset = row.getFreeSpace() / numShrink; // Logger.verbose("shrinkOffset: " + offset); - if (offset >= 0) { - while ((lo = row.getNextLayoutObject(lo, Item.LAYOUT_SHRINK)) != null) { + if(offset >= 0) + { + while((lo = row.getNextLayoutObject(lo, Item.LAYOUT_SHRINK)) != null) + { int pref = lo.getOwningItem().getPreferredWidth(); int min = lo.getOwningItem().getMinimumWidth(); int itemWidth = Math.min(pref, min + offset); @@ -441,12 +512,15 @@ } // Expand items with EXPAND layout directive - if (numExpand > 0) { + if(numExpand > 0) + { // Get extra space after shrink but before expand int offset = row.getFreeSpace(Item.LAYOUT_EXPAND) / numExpand; - if (offset >= 0) { + if(offset >= 0) + { // Logger.verbose("expandOffset: " + offset); - while ((lo = row.getNextLayoutObject(lo, Item.LAYOUT_EXPAND)) != null) { + while((lo = row.getNextLayoutObject(lo, Item.LAYOUT_EXPAND)) != null) + { int pref = lo.getOwningItem().getPreferredWidth(); getLayouter(lo.getOwningItem()).eswtResizeObject(lo, pref + offset, lo.getHeight()); @@ -466,13 +540,14 @@ /** * Add a new Row. */ - private Row eswtAddNewRow() { + private Row eswtAddNewRow() + { Row lastRow = getLastRow(); eswtUpdateRow(lastRow); int yShift = (lastRow == null ? 0 : lastRow.getBottomPosition()); // create new Row Row newRow = new Row(ItemLayouter.getMaximumItemWidth(null), - getCurrentHLayoutDirective()); + getCurrentHLayoutDirective()); newRow.setYShift(yShift); rows.addElement(newRow); return newRow; @@ -483,11 +558,13 @@ * * @param layoutObject the layout object */ - void eswtAddNewLayoutObject(LayoutObject layoutObject) { + void eswtAddNewLayoutObject(LayoutObject layoutObject) + { Row lastRow = getLastRow(); // check if the current Row is full - if (!lastRow.isEmpty() - && lastRow.getFreeSpace() < layoutObject.getWidth()) { + if(!lastRow.isEmpty() + && lastRow.getFreeSpace() < layoutObject.getWidth()) + { lastRow = eswtAddNewRow(); } lastRow.eswtAddLayoutObject(layoutObject); @@ -501,8 +578,10 @@ * @param newRow adds a new row if true. If false, adds new row only if * there's no space for layoutObject in current row. */ - void eswtAddNewLayoutObject(LayoutObject layoutObject, boolean newRow) { - if (newRow) { + void eswtAddNewLayoutObject(LayoutObject layoutObject, boolean newRow) + { + if(newRow) + { eswtAddNewRow(); } eswtAddNewLayoutObject(layoutObject); @@ -514,16 +593,20 @@ * @param row - where to startLayout. * @param item - Item to Layout */ - private void eswtLayoutItem(Item item) { + private void eswtLayoutItem(Item item) + { Row lastRow = getLastRow(); boolean hlChange = setCurrentHLayoutDirective(item.internalGetLayout()); - if (hlChange || getItemNewLineBefore(item)) { + if(hlChange || getItemNewLineBefore(item)) + { // newline directive or horizontal layout changed - if (lastRow.isEmpty()) { + if(lastRow.isEmpty()) + { // if the current/last row is empty - use that lastRow.setRowHLayout(getCurrentHLayoutDirective()); } - else { + else + { eswtAddNewRow(); } } @@ -531,14 +614,17 @@ // Use the specific layouter to layout item in the last row getLayouter(item).eswtLayoutItem(getLastRow(), item); - if (form.eswtIsShown()) { + if(form.eswtIsShown()) + { LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { getLayouter(item).eswtAddListeners(item, lo); } } - if (getItemNewLineAfter(item)) { + if(getItemNewLineAfter(item)) + { eswtAddNewRow(); } } @@ -550,10 +636,12 @@ * @param newLayoutDirective * @return true if a layout change has occured */ - private boolean setCurrentHLayoutDirective(int newLayoutDirective) { + private boolean setCurrentHLayoutDirective(int newLayoutDirective) + { int newHLayoutDirective = Item.getHorizontalLayout(newLayoutDirective); - if ((newHLayoutDirective != currentHLayoutDirective) - && (newHLayoutDirective != Item.LAYOUT_DEFAULT)) { + if((newHLayoutDirective != currentHLayoutDirective) + && (newHLayoutDirective != Item.LAYOUT_DEFAULT)) + { currentHLayoutDirective = newHLayoutDirective; return true; } @@ -565,8 +653,10 @@ * * @return current Layout directive for Form. */ - private int getCurrentHLayoutDirective() { - if (currentHLayoutDirective == Item.LAYOUT_DEFAULT) { + private int getCurrentHLayoutDirective() + { + if(currentHLayoutDirective == Item.LAYOUT_DEFAULT) + { return getLanguageSpecificLayoutDirective(); } return currentHLayoutDirective; @@ -577,31 +667,38 @@ * * @return LAYOUT_LEFT or LAYOUT_RIGHT. */ - int getLanguageSpecificLayoutDirective() { - if (form.getLeftRightLanguage()) { + int getLanguageSpecificLayoutDirective() + { + if(form.getLeftRightLanguage()) + { return Item.LAYOUT_LEFT; } - else { + else + { return Item.LAYOUT_RIGHT; } } - private boolean getItemNewLineBefore(Item item) { + private boolean getItemNewLineBefore(Item item) + { return ((item.internalGetLayout() & Item.LAYOUT_NEWLINE_BEFORE) != 0); } - private boolean getItemNewLineAfter(Item item) { + private boolean getItemNewLineAfter(Item item) + { return ((item.internalGetLayout() & Item.LAYOUT_NEWLINE_AFTER) != 0); } - boolean isItemLayouted(Item item) { + boolean isItemLayouted(Item item) + { return (getFirstLayoutObjectOfItem(item) != null); } /** * Returns if the form is shown. */ - boolean isFormCurrent() { + boolean isFormCurrent() + { return isCurrent; } @@ -612,10 +709,12 @@ * @param viewBottom viewPort's bottom position * @return true if visible */ - boolean isPartiallyVisible(int yTop, int yBottom) { + boolean isPartiallyVisible(int yTop, int yBottom) + { int vBottomPosition = vPosition + getFormHeight(); - if ((vPosition <= yTop && vBottomPosition <= yTop) - || (vPosition >= yBottom && vBottomPosition >= yBottom)) { + if((vPosition <= yTop && vBottomPosition <= yTop) + || (vPosition >= yBottom && vBottomPosition >= yBottom)) + { return false; } return true; @@ -624,9 +723,11 @@ /** * Returns if at least the region's given percentage is visible. */ - boolean isPartiallyVisible(int yTop, int yBottom, int minPercent) { + boolean isPartiallyVisible(int yTop, int yBottom, int minPercent) + { int visPercent = getVisibilityPercent(yTop, yBottom); - if (visPercent > minPercent) { + if(visPercent > minPercent) + { return true; } return false; @@ -635,8 +736,10 @@ /** * Returns the region's visibility percentage. */ - int getVisibilityPercent(int yTop, int yBottom) { - if (yTop >= yBottom) { + int getVisibilityPercent(int yTop, int yBottom) + { + if(yTop >= yBottom) + { return 0; } int vBottomPosition = vPosition + getFormHeight(); @@ -648,8 +751,10 @@ /** * Returns if the LayoutObject is partially visible. */ - boolean isPartiallyVisible(LayoutObject lo) { - if (lo != null) { + boolean isPartiallyVisible(LayoutObject lo) + { + if(lo != null) + { return isPartiallyVisible(lo.getY(), lo.getY() + lo.getHeight()); } return false; @@ -658,10 +763,12 @@ /** * Returns if at least the LayoutObject's given percentage is visible. */ - boolean isPartiallyVisible(LayoutObject lo, int minPercent) { - if (lo != null) { + boolean isPartiallyVisible(LayoutObject lo, int minPercent) + { + if(lo != null) + { return isPartiallyVisible(lo.getY(), lo.getY() + lo.getHeight(), - minPercent); + minPercent); } return false; } @@ -673,11 +780,15 @@ * @param item the Item * @return true if partially visible */ - boolean isItemPartiallyVisible(Item item) { - if (item != null) { + boolean isItemPartiallyVisible(Item item) + { + if(item != null) + { LayoutObject lo = null; - while ((lo = getNextLayoutObjectOfItem(lo, item)) != null) { - if (isPartiallyVisible(lo)) { + while((lo = getNextLayoutObjectOfItem(lo, item)) != null) + { + if(isPartiallyVisible(lo)) + { return true; } } @@ -693,11 +804,15 @@ * @param item the Item. * @return true if fully visible. */ - boolean isItemFullyVisible(Item item) { - if (item != null) { + boolean isItemFullyVisible(Item item) + { + if(item != null) + { LayoutObject lo = null; - while ((lo = getNextLayoutObjectOfItem(lo, item)) != null) { - if (!isLOFullyVisible(lo)) { + while((lo = getNextLayoutObjectOfItem(lo, item)) != null) + { + if(!isLOFullyVisible(lo)) + { return false; } } @@ -708,8 +823,10 @@ /** * Returns if the LayoutObject is fully visible. */ - boolean isLOFullyVisible(LayoutObject lo) { - if (lo != null) { + boolean isLOFullyVisible(LayoutObject lo) + { + if(lo != null) + { return isFullyVisible(lo.getY(), lo.getY() + lo.getHeight()); } return false; @@ -722,49 +839,61 @@ * @param viewBottom viewPort's bottom position * @return true if visible */ - boolean isFullyVisible(int yTop, int yBottom) { + boolean isFullyVisible(int yTop, int yBottom) + { int vBottomPosition = vPosition + getFormHeight(); - if ((vPosition <= yTop && vBottomPosition >= yBottom)) { + if((vPosition <= yTop && vBottomPosition >= yBottom)) + { return true; } return false; } - int getItemTopPosition(Item item) { + int getItemTopPosition(Item item) + { LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { return lo.getY(); } return 0; } - int getItemBottomPosition(Item item) { + int getItemBottomPosition(Item item) + { LayoutObject lo = getLastLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { return lo.getY() + lo.getHeight(); } return 0; } - int getItemCount() { + int getItemCount() + { return form.size(); } - Item getItem(int index) { - try { + Item getItem(int index) + { + try + { return (Item) form.getItems().elementAt(index); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Logger.exception(e); return null; } } - int getItemIndex(Item item) { + int getItemIndex(Item item) + { return form.getItems().indexOf(item); } - int getRowCount() { + int getRowCount() + { return rows.size(); } @@ -774,11 +903,14 @@ * @param index Row's index * @return a Row */ - Row getRow(int index) { - try { + Row getRow(int index) + { + try + { return (Row) rows.elementAt(index); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { Logger.exception("getRow", e); return null; } @@ -790,11 +922,14 @@ * @param lo LayoutObject * @return the owning Row */ - Row getRow(LayoutObject lo) { - try { + Row getRow(LayoutObject lo) + { + try + { return getRow(lo.getRowIdx()); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Logger.exception("getRow", e); return null; } @@ -803,11 +938,14 @@ /** * Returns the last row of the form. */ - Row getLastRow() { - try { + Row getLastRow() + { + try + { return (Row) rows.lastElement(); } - catch (NoSuchElementException nse) { + catch(NoSuchElementException nse) + { // Logger.exception("getLastRow", nse); return null; } @@ -819,7 +957,8 @@ * @param item Item in a Row. * @return Last Row with that item. */ - Row getLastRowOfItem(Item item) { + Row getLastRowOfItem(Item item) + { return getRow(getLastLayoutObjectOfItem(item)); } @@ -828,21 +967,24 @@ * * @return form. */ - Form getForm() { + Form getForm() + { return form; } /** * Form's content height. */ - int getFormHeight() { + int getFormHeight() + { return form.getHeight(); } /** * Form's content width. */ - int getFormWidth() { + int getFormWidth() + { return form.getWidth(); } @@ -853,12 +995,15 @@ * @param item specifies the parent Item; null means any Item * @return the next LayoutObject in the layout. */ - LayoutObject getNextLayoutObjectOfItem(LayoutObject lo, Item item) { + LayoutObject getNextLayoutObjectOfItem(LayoutObject lo, Item item) + { int startRow = (lo == null ? 0 : lo.getRowIdx()); LayoutObject temp = null; - for (int i = startRow; i < getRowCount(); i++) { + for(int i = startRow; i < getRowCount(); i++) + { temp = getRow(i).getNextLayoutObject(lo, item); - if (temp != null && temp != lo) { + if(temp != null && temp != lo) + { return temp; } } @@ -872,12 +1017,15 @@ * @param item specifies the parent Item; null means any Item * @return the previous LayoutObject in the layout. */ - LayoutObject getPrevLayoutObjectOfItem(LayoutObject lo, Item item) { + LayoutObject getPrevLayoutObjectOfItem(LayoutObject lo, Item item) + { int startRow = (lo == null ? rows.size() - 1 : lo.getRowIdx()); LayoutObject temp = null; - for (int i = startRow; i >= 0; i--) { + for(int i = startRow; i >= 0; i--) + { temp = getRow(i).getPrevLayoutObject(lo, item); - if (temp != null && temp != lo) { + if(temp != null && temp != lo) + { return temp; } } @@ -890,8 +1038,10 @@ * @param item * @return the LO, or NULL if the item is not layouted */ - LayoutObject getFirstLayoutObjectOfItem(Item item) { - if (item != null) { + LayoutObject getFirstLayoutObjectOfItem(Item item) + { + if(item != null) + { return getNextLayoutObjectOfItem(null, item); } return null; @@ -903,8 +1053,10 @@ * @param item * @return the LO, or NULL if the item is not layouted */ - LayoutObject getLastLayoutObjectOfItem(Item item) { - if (item != null) { + LayoutObject getLastLayoutObjectOfItem(Item item) + { + if(item != null) + { return getPrevLayoutObjectOfItem(null, item); } return null; @@ -917,51 +1069,63 @@ * @param updateReason * @param param additional parameter */ - void updateItemState(Item item, int updateReason, Object param) { + void updateItemState(Item item, int updateReason, Object param) + { Logger.method(this, "updateItemState", item, - String.valueOf(updateReason), param); + String.valueOf(updateReason), param); // Clean reason - without resizing flags int reason = updateReason & Item.UPDATE_REASON_MASK; - switch (reason) { - case Item.UPDATE_NONE: - break; - case Item.UPDATE_ADDCOMMAND: { - if (isFormCurrent() && param != null) { - LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null && param instanceof Command) { - lo.addCommand((Command) param); - } + switch(reason) + { + case Item.UPDATE_NONE: + break; + case Item.UPDATE_ADDCOMMAND: + { + if(isFormCurrent() && param != null) + { + LayoutObject lo = getFirstLayoutObjectOfItem(item); + if(lo != null && param instanceof Command) + { + lo.addCommand((Command) param); } - break; } - case Item.UPDATE_REMOVECOMMAND: { - if (isFormCurrent() && param != null) { - LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null && param instanceof Command) { - lo.removeCommand((Command) param); - } + break; + } + case Item.UPDATE_REMOVECOMMAND: + { + if(isFormCurrent() && param != null) + { + LayoutObject lo = getFirstLayoutObjectOfItem(item); + if(lo != null && param instanceof Command) + { + lo.removeCommand((Command) param); } - break; } - default: { - LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { - getLayouter(item).updateItem(item, lo.getControl(), reason, - param); - } - break; + break; + } + default: + { + LayoutObject lo = getFirstLayoutObjectOfItem(item); + if(lo != null) + { + getLayouter(item).updateItem(item, lo.getControl(), reason, + param); } + break; + } } // Check this always - because this is a flag - if ((updateReason & Item.UPDATE_HEIGHT_CHANGED) - == Item.UPDATE_HEIGHT_CHANGED) { + if((updateReason & Item.UPDATE_HEIGHT_CHANGED) + == Item.UPDATE_HEIGHT_CHANGED) + { resizeItemAndShift(item); } } - int eswtGetMaxVPosition() { + int eswtGetMaxVPosition() + { return formComposite.getSize().y - getFormHeight(); } @@ -972,30 +1136,37 @@ * @param swtDir scrolling direction. * @return New vertical position of Form's content. */ - protected int getNextScrollingPosition(int swtDir) { + protected int getNextScrollingPosition(int swtDir) + { boolean scrollDown = (swtDir == SWT.ARROW_DOWN - || swtDir == SWT.ARROW_RIGHT); + || swtDir == SWT.ARROW_RIGHT); int formHeight = getFormHeight(); int refPoint; int ret = vPosition; - if (scrollDown) { + if(scrollDown) + { ret += formHeight / 5; refPoint = (vPosition + 1) + formHeight; } - else { + else + { ret -= formHeight / 5; refPoint = (vPosition - 1); } Row row = null; - for (int i = 0; i < getRowCount(); i++) { + for(int i = 0; i < getRowCount(); i++) + { row = getRow(i); - if (row.isInsideRow(refPoint) - && (row.getRowHeight() < formHeight)) { - if (scrollDown) { + if(row.isInsideRow(refPoint) + && (row.getRowHeight() < formHeight)) + { + if(scrollDown) + { ret = row.getBottomPosition() - formHeight; } - else { + else + { ret = row.getYShift(); } break; @@ -1011,7 +1182,8 @@ * * @param position new position */ - void eswtSetScrollingPosition(int position, boolean keyNav) { + void eswtSetScrollingPosition(int position, boolean keyNav) + { // check constraints int newVPosition = position; int maxVPos = eswtGetMaxVPosition(); @@ -1030,23 +1202,28 @@ /** * Returns the scrolling position. */ - protected int getScrollingPosition() { + protected int getScrollingPosition() + { return vPosition; } /** * Updates visibility status of all items. */ - protected void eswtHandleVisibilityChanges() { + protected void eswtHandleVisibilityChanges() + { // Logger.method(this, "eswtHandleVisibilityChanges"); boolean shown = false; Item item = null; LayoutObject lo = null; // Go through all LayoutObjects and check/update visibilities - while ((lo = getNextLayoutObjectOfItem(lo, null)) != null) { + while((lo = getNextLayoutObjectOfItem(lo, null)) != null) + { // check if owning item is changing - if (lo.getOwningItem() != item) { - if (item != null) { + if(lo.getOwningItem() != item) + { + if(item != null) + { // set current item's visibility getLayouter(item).eswtHandleVisibilityChange(item, shown); } @@ -1056,13 +1233,15 @@ } // track current item's visibility - if (!shown && isFormCurrent() && isPartiallyVisible(lo)) { + if(!shown && isFormCurrent() && isPartiallyVisible(lo)) + { shown = true; } } // call it for last item - if (item != null) { + if(item != null) + { getLayouter(item).eswtHandleVisibilityChange(item, shown); } } @@ -1072,14 +1251,19 @@ * * @param item - item to changeSize. */ - void resizeItemAndShift(final Item item) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void resizeItemAndShift(final Item item) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { int newVPosition = eswtResizeItemAndShift(item); - if (newVPosition != vPosition) { + if(newVPosition != vPosition) + { eswtSetScrollingPosition(newVPosition, true); } - else { + else + { eswtHandleVisibilityChanges(); } } @@ -1092,14 +1276,16 @@ * @param item Item to be resized. * @return new scrolling vPosition */ - int eswtResizeItemAndShift(Item item) { + int eswtResizeItemAndShift(Item item) + { Row row = getLastRowOfItem(item); int deltaYShift = row.getRowHeight(); // if we un-comment this then when we set true, // focus will jump to first item. // eswtUpdateFormComposite(false); LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { getLayouter(item).eswtResizeObject(lo); } @@ -1119,8 +1305,10 @@ // row's height change - all remaining rows are shifted with this. Row lastRow = getLastRow(); - if (row != lastRow) { - for (int i = rows.indexOf(row) + 1; i < getRowCount(); i++) { + if(row != lastRow) + { + for(int i = rows.indexOf(row) + 1; i < getRowCount(); i++) + { row = getRow(i); row.setYShift(row.getYShift() + deltaYShift); eswtUpdateRow(row); @@ -1135,13 +1323,15 @@ int newVPosition = vPosition; // we need to scroll only if changes happened above the screen. - if (newVPosition >= itemRowYShift) { + if(newVPosition >= itemRowYShift) + { newVPosition = Math.max(0, newVPosition + deltaYShift); } // check to avoid gap in the bottom of the form - if (newVPosition + getFormHeight() > lastRow.getBottomPosition()) { + if(newVPosition + getFormHeight() > lastRow.getBottomPosition()) + { newVPosition = Math.max(0, - lastRow.getBottomPosition() - getFormHeight()); + lastRow.getBottomPosition() - getFormHeight()); } eswtUpdateFormComposite(true); @@ -1158,29 +1348,38 @@ * @param item Item to be layouted. * @return ItemLayouter or null if no Layouter found. */ - protected final ItemLayouter getLayouter(Item item) { - if (item instanceof StringItem) { + protected final ItemLayouter getLayouter(Item item) + { + if(item instanceof StringItem) + { return sIL; } - else if (item instanceof ImageItem) { + else if(item instanceof ImageItem) + { return imIL; } - else if (item instanceof Gauge) { + else if(item instanceof Gauge) + { return gL; } - else if (item instanceof TextField) { + else if(item instanceof TextField) + { return tfL; } - else if (item instanceof DateField) { + else if(item instanceof DateField) + { return dfL; } - else if (item instanceof ChoiceGroup) { + else if(item instanceof ChoiceGroup) + { return cgL; } - else if (item instanceof CustomItem) { + else if(item instanceof CustomItem) + { return ciL; } - else if (item instanceof Spacer) { + else if(item instanceof Spacer) + { return sL; } return null; @@ -1189,13 +1388,17 @@ /** * Returns eSWT Control that represents the item specified. */ - Control getItemControl(final Item item) { + Control getItemControl(final Item item) + { final LayoutObject lo = getFirstLayoutObjectOfItem(item); - if (lo != null) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + if(lo != null) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { itemMainControl = getLayouter(item) - .eswtFindSpecificControl(item, lo.getControl()); + .eswtFindSpecificControl(item, lo.getControl()); } }); return itemMainControl; @@ -1203,10 +1406,13 @@ return null; } - void updateScrolling(final int value, final boolean keyNav) { + void updateScrolling(final int value, final boolean keyNav) + { Logger.method("updateScrolling", String.valueOf(value)); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSetScrollingPosition(value, keyNav); @@ -1219,7 +1425,8 @@ * * @return vPosition. */ - int getVPosition() { + int getVPosition() + { return vPosition; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DirectGraphicsImpl.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DirectGraphicsImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DirectGraphicsImpl.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,7 +25,8 @@ * * @see DirectGraphics */ -class DirectGraphicsImpl implements DirectGraphics { +class DirectGraphicsImpl implements DirectGraphics +{ private static final int MANIPULATION_MASK = 0x0FFF; @@ -33,147 +34,179 @@ private int alpha; - DirectGraphicsImpl(Graphics g) { + DirectGraphicsImpl(Graphics g) + { graphics = g; } public void drawImage(Image img, int x, int y, int anchor, - int manipulation) { + int manipulation) + { int transform = getTransformation(manipulation); - if (transform < 0) { + if(transform < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); } graphics.drawRegion(img, 0, 0, img.getWidth(), img.getHeight(), - transform, x, y, anchor); + transform, x, y, anchor); } public void drawPixels(final int[] pixels, final boolean transparency, - final int offset, final int scanlength, final int x, final int y, - final int width, final int height, final int manipulation, - final int format) { + final int offset, final int scanlength, final int x, final int y, + final int width, final int height, final int manipulation, + final int format) + { int transform = getTransformation(manipulation); - if (transform < 0) { + if(transform < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); } - if (format != TYPE_INT_888_RGB && format != TYPE_INT_8888_ARGB) { + if(format != TYPE_INT_888_RGB && format != TYPE_INT_8888_ARGB) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } final boolean processAlpha = (format == TYPE_INT_8888_ARGB); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().drawRGB(pixels, offset, scanlength, - x, y, width, height, processAlpha, - getNativeTransformValue(manipulation)); + x, y, width, height, processAlpha, + getNativeTransformValue(manipulation)); } }); } public void drawPixels(final byte[] pixels, final byte[] transparencyMask, - final int offset, final int scanlength, final int x, final int y, - final int width, final int height, final int manipulation, - final int format) { + final int offset, final int scanlength, final int x, final int y, + final int width, final int height, final int manipulation, + final int format) + { int transform = getTransformation(manipulation); - if (transform < 0) { + if(transform < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); } - if (format != TYPE_BYTE_1_GRAY && format != TYPE_BYTE_2_GRAY) { + if(format != TYPE_BYTE_1_GRAY && format != TYPE_BYTE_2_GRAY) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().drawRGB(pixels, transparencyMask, offset, scanlength, - x, y, width, height, getNativeTransformValue(manipulation), - getNativeFormatValue(format)); + x, y, width, height, getNativeTransformValue(manipulation), + getNativeFormatValue(format)); } }); } public void drawPixels(final short[] pixels, final boolean transparency, - final int offset, final int scanlength, final int x, final int y, - final int width, final int height, final int manipulation, - final int format) { + final int offset, final int scanlength, final int x, final int y, + final int width, final int height, final int manipulation, + final int format) + { int transform = getTransformation(manipulation); - if (transform < 0) { + if(transform < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_MANIPULATION); } - if (format != TYPE_USHORT_4444_ARGB + if(format != TYPE_USHORT_4444_ARGB && format != TYPE_USHORT_444_RGB && format != TYPE_USHORT_565_RGB - && format != TYPE_USHORT_555_RGB) { + && format != TYPE_USHORT_555_RGB) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } final boolean processAlpha = (format == TYPE_USHORT_4444_ARGB); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().drawRGB(pixels, offset, scanlength, - x, y, width, height, processAlpha, - getNativeTransformValue(manipulation), - getNativeFormatValue(format)); + x, y, width, height, processAlpha, + getNativeTransformValue(manipulation), + getNativeFormatValue(format)); } }); } public void drawPolygon(int[] xPoints, int xOffset, int[] yPoints, - int yOffset, int nPoints, int argbColor) { + int yOffset, int nPoints, int argbColor) + { setARGBColor(argbColor); final int[] points = new int[nPoints * 2]; - for (int i = 0; i < nPoints; i++) { + for(int i = 0; i < nPoints; i++) + { points[i * 2] = xPoints[xOffset + i]; points[(i * 2) + 1] = yPoints[yOffset + i]; } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().drawPolygon(points); } }); } public void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, - int argbColor) { + int argbColor) + { setARGBColor(argbColor); final int[] points = {x1, y1, x2, y2, x3, y3}; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().drawPolygon(points); } }); } public void fillPolygon(int[] xPoints, int xOffset, int[] yPoints, - int yOffset, int nPoints, int argbColor) { + int yOffset, int nPoints, int argbColor) + { setARGBColor(argbColor); final int[] points = new int[nPoints * 2]; - for (int i = 0; i < nPoints; i++) { + for(int i = 0; i < nPoints; i++) + { points[i * 2] = xPoints[xOffset + i]; points[(i * 2) + 1] = yPoints[yOffset + i]; } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().fillPolygon(points); } }); } public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3, - int argbColor) { + int argbColor) + { setARGBColor(argbColor); final int[] points = {x1, y1, x2, y2, x3, y3}; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().fillPolygon(points); } }); @@ -181,30 +214,38 @@ public void getPixels(final int[] pixels, final int offset, - final int scanlength, final int x, final int y, final int width, - final int height, final int format) { - if (format != TYPE_INT_888_RGB) { + final int scanlength, final int x, final int y, final int width, + final int height, final int format) + { + if(format != TYPE_INT_888_RGB) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } - if (width < 0 || height < 0) { + if(width < 0 || height < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image cgImg; Object target = graphics.getGc().getBoundTarget(); - if (target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) { + if(target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) + { cgImg = (org.eclipse.swt.internal.qt.graphics.Image) target; } - else { + else + { cgImg = new org.eclipse.swt.internal.qt.graphics.Image(width, height); // TODO: in future the copyArea() signature will change graphics.getGc().copyArea(cgImg, x, y); } cgImg.getRGB(pixels, offset, scanlength, x, y, width, height); - if (target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) { + if(target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) + { cgImg.dispose(); } } @@ -212,30 +253,38 @@ } public void getPixels(final byte[] pixels, final byte[] transparencyMask, - final int offset, final int scanlength, final int x, final int y, - final int width, final int height, final int format) { - if (format != TYPE_BYTE_1_GRAY) { + final int offset, final int scanlength, final int x, final int y, + final int width, final int height, final int format) + { + if(format != TYPE_BYTE_1_GRAY) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } - if (width < 0 || height < 0) { + if(width < 0 || height < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image cgImg; Object target = graphics.getGc().getBoundTarget(); - if (target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) { + if(target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) + { cgImg = (org.eclipse.swt.internal.qt.graphics.Image) target; } - else { + else + { cgImg = new org.eclipse.swt.internal.qt.graphics.Image(width, height); graphics.getGc().copyArea(cgImg, x, y); } cgImg.getRGB(pixels, transparencyMask, offset, scanlength, x, y, width, - height, getNativeFormatValue(format)); - if (target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) { + height, getNativeFormatValue(format)); + if(target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) + { cgImg.dispose(); } } @@ -243,135 +292,159 @@ } public void getPixels(final short[] pixels, final int offset, - final int scanlength, final int x, final int y, final int width, - final int height, final int format) { - if (format != TYPE_USHORT_4444_ARGB - && format != TYPE_USHORT_444_RGB - && format != TYPE_USHORT_565_RGB - && format != TYPE_USHORT_555_RGB) { + final int scanlength, final int x, final int y, final int width, + final int height, final int format) + { + if(format != TYPE_USHORT_4444_ARGB + && format != TYPE_USHORT_444_RGB + && format != TYPE_USHORT_565_RGB + && format != TYPE_USHORT_555_RGB) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_FORMAT); } - if (width < 0 || height < 0) { + if(width < 0 || height < 0) + { throw new IllegalArgumentException( - MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.DIRECTGRAPHICS_EXCEPTION_INVALID_WIDTH_HEIGHT); } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image cgImg; Object target = graphics.getGc().getBoundTarget(); - if (target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) { + if(target != null && target instanceof org.eclipse.swt.internal.qt.graphics.Image) + { cgImg = (org.eclipse.swt.internal.qt.graphics.Image) target; } - else { + else + { cgImg = new org.eclipse.swt.internal.qt.graphics.Image(width, height); graphics.getGc().copyArea(cgImg, x, y); } cgImg.getRGB(pixels, offset, scanlength, 0, 0, width, height, getNativeFormatValue(format)); - if (target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) { + if(target == null || !(target instanceof org.eclipse.swt.internal.qt.graphics.Image)) + { cgImg.dispose(); } } }); } - public void setARGBColor(int argbColor) { + public void setARGBColor(int argbColor) + { alpha = (argbColor >> 24) & Graphics.COMPONENT_MASK; graphics.setColor(argbColor); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { graphics.getGc().setForegroundAlpha(alpha); graphics.getGc().setBackgroundAlpha(alpha); } }); } - public int getAlphaComponent() { + public int getAlphaComponent() + { return alpha; } - public int getNativePixelFormat() { + public int getNativePixelFormat() + { // TODO: is this the native pixel format ? return TYPE_INT_8888_ARGB; } - private static int getTransformation(int manipulation) { + private static int getTransformation(int manipulation) + { // manipulations are C-CW and sprite rotations are CW int ret = -1; int rotation = manipulation & MANIPULATION_MASK; - if ((manipulation & FLIP_HORIZONTAL) != 0) { - if ((manipulation & FLIP_VERTICAL) != 0) { + if((manipulation & FLIP_HORIZONTAL) != 0) + { + if((manipulation & FLIP_VERTICAL) != 0) + { // horiz and vertical flipping - switch (rotation) { - case 0: - ret = Sprite.TRANS_ROT180; - break; - case ROTATE_90: - ret = Sprite.TRANS_ROT90; - break; - case ROTATE_180: - ret = Sprite.TRANS_NONE; - break; - case ROTATE_270: - ret = Sprite.TRANS_ROT270; - break; - default: + switch(rotation) + { + case 0: + ret = Sprite.TRANS_ROT180; + break; + case ROTATE_90: + ret = Sprite.TRANS_ROT90; + break; + case ROTATE_180: + ret = Sprite.TRANS_NONE; + break; + case ROTATE_270: + ret = Sprite.TRANS_ROT270; + break; + default: } } - else { + else + { // horizontal flipping - switch (rotation) { - case 0: - ret = Sprite.TRANS_MIRROR_ROT180; - break; - case ROTATE_90: - ret = Sprite.TRANS_MIRROR_ROT90; - break; - case ROTATE_180: - ret = Sprite.TRANS_MIRROR; - break; - case ROTATE_270: - ret = Sprite.TRANS_MIRROR_ROT270; - break; - default: + switch(rotation) + { + case 0: + ret = Sprite.TRANS_MIRROR_ROT180; + break; + case ROTATE_90: + ret = Sprite.TRANS_MIRROR_ROT90; + break; + case ROTATE_180: + ret = Sprite.TRANS_MIRROR; + break; + case ROTATE_270: + ret = Sprite.TRANS_MIRROR_ROT270; + break; + default: } } } - else { - if ((manipulation & FLIP_VERTICAL) != 0) { + else + { + if((manipulation & FLIP_VERTICAL) != 0) + { // vertical flipping - switch (rotation) { - case 0: - ret = Sprite.TRANS_MIRROR; - break; - case ROTATE_90: - ret = Sprite.TRANS_MIRROR_ROT270; - break; - case ROTATE_180: - ret = Sprite.TRANS_MIRROR_ROT180; - break; - case ROTATE_270: - ret = Sprite.TRANS_MIRROR_ROT90; - break; - default: + switch(rotation) + { + case 0: + ret = Sprite.TRANS_MIRROR; + break; + case ROTATE_90: + ret = Sprite.TRANS_MIRROR_ROT270; + break; + case ROTATE_180: + ret = Sprite.TRANS_MIRROR_ROT180; + break; + case ROTATE_270: + ret = Sprite.TRANS_MIRROR_ROT90; + break; + default: } } - else { + else + { // no flipping - switch (rotation) { - case 0: - ret = Sprite.TRANS_NONE; - break; - case ROTATE_90: - ret = Sprite.TRANS_ROT270; - break; - case ROTATE_180: - ret = Sprite.TRANS_ROT180; - break; - case ROTATE_270: - ret = Sprite.TRANS_ROT90; - break; - default: + switch(rotation) + { + case 0: + ret = Sprite.TRANS_NONE; + break; + case ROTATE_90: + ret = Sprite.TRANS_ROT270; + break; + case ROTATE_180: + ret = Sprite.TRANS_ROT180; + break; + case ROTATE_270: + ret = Sprite.TRANS_ROT90; + break; + default: } } } @@ -385,29 +458,31 @@ * * @return corresponding native transformation value */ - private static int getNativeTransformValue(int manipulation) { + private static int getNativeTransformValue(int manipulation) + { int returnVal = 0; - switch (manipulation) { - case 0: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; - break; - case DirectGraphics.FLIP_HORIZONTAL: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_FLIP_HORIZONTAL; - break; - case DirectGraphics.FLIP_VERTICAL: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_FLIP_VERTICAL; - break; - case DirectGraphics.ROTATE_90: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT90; - break; - case DirectGraphics.ROTATE_180: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT180; - break; - case DirectGraphics.ROTATE_270: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT270; - break; - default: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; + switch(manipulation) + { + case 0: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; + break; + case DirectGraphics.FLIP_HORIZONTAL: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_FLIP_HORIZONTAL; + break; + case DirectGraphics.FLIP_VERTICAL: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_FLIP_VERTICAL; + break; + case DirectGraphics.ROTATE_90: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT90; + break; + case DirectGraphics.ROTATE_180: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT180; + break; + case DirectGraphics.ROTATE_270: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT270; + break; + default: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; } return returnVal; } @@ -419,35 +494,37 @@ * * @return corresponding native format value */ - private static int getNativeFormatValue(int format) { + private static int getNativeFormatValue(int format) + { int returnVal = 0; - switch (format) { - case 0: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_NONE; - break; - case DirectGraphics.TYPE_BYTE_1_GRAY: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_MONO; - break; - case DirectGraphics.TYPE_INT_8888_ARGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_ARGB32; - break; - case DirectGraphics.TYPE_INT_888_RGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB32; - break; - case DirectGraphics.TYPE_USHORT_4444_ARGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB4444PREMULTIPLIED; - break; - case DirectGraphics.TYPE_USHORT_444_RGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB444; - break; - case DirectGraphics.TYPE_USHORT_555_RGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB555; - break; - case DirectGraphics.TYPE_USHORT_565_RGB: - returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB16; - break; - default: - break; + switch(format) + { + case 0: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_NONE; + break; + case DirectGraphics.TYPE_BYTE_1_GRAY: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_MONO; + break; + case DirectGraphics.TYPE_INT_8888_ARGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_ARGB32; + break; + case DirectGraphics.TYPE_INT_888_RGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB32; + break; + case DirectGraphics.TYPE_USHORT_4444_ARGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB4444PREMULTIPLIED; + break; + case DirectGraphics.TYPE_USHORT_444_RGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB444; + break; + case DirectGraphics.TYPE_USHORT_555_RGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB555; + break; + case DirectGraphics.TYPE_USHORT_565_RGB: + returnVal = org.eclipse.swt.internal.qt.graphics.Image.FORMAT_IMG_RGB16; + break; + default: + break; } return returnVal; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Display.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Display.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Display.java Fri May 14 15:47:24 2010 +0300 @@ -18,10 +18,8 @@ import javax.microedition.lcdui.EventDispatcher.LCDUIEvent; import javax.microedition.midlet.MIDlet; - -import org.eclipse.ercp.swt.mobile.MobileDevice; -import org.eclipse.ercp.swt.mobile.Screen; - +import org.eclipse.ercp.swt.mobile.MobileDevice; +import org.eclipse.ercp.swt.mobile.Screen; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.internal.extension.DisplayExtension; @@ -30,7 +28,8 @@ /** * Display - represents device's display. */ -public class Display { +public class Display +{ /** * Type of image for List element. @@ -115,7 +114,8 @@ /** * Constructor. */ - private Display() { + private Display() + { } /** @@ -125,10 +125,12 @@ * @return display - unique display used by the midlet. note: current * implementation supports 1 Display. */ - public static Display getDisplay(MIDlet midlet) { - if (midlet == null) { + public static Display getDisplay(MIDlet midlet) + { + if(midlet == null) + { throw new NullPointerException( - MsgRepository.DISPLAY_EXCEPTION_MIDLET_IS_NULL); + MsgRepository.DISPLAY_EXCEPTION_MIDLET_IS_NULL); } // following code was removed to improve performance /*if (emptyForm == null) { @@ -148,15 +150,18 @@ /** * Returns the Display instance. */ - static Display getDisplay() { + static Display getDisplay() + { return instance; } /** * Propagate event to current displayable. */ - void eswtHandleEvent(Event e) { - if (currentDisplayable != null) { + void eswtHandleEvent(Event e) + { + if(currentDisplayable != null) + { currentDisplayable.eswtHandleEvent(e); } } @@ -167,7 +172,8 @@ * @return true if Display supports colors. false if black and white only * supported. */ - public boolean isColor() { + public boolean isColor() + { return true; } @@ -176,9 +182,12 @@ * * @return number of Colors supported by device. */ - public int numColors() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + public int numColors() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { numColors = eswtNumColors(); } }); @@ -190,31 +199,38 @@ * * @return numColors supported by device. */ - public int eswtNumColors() { - + public int eswtNumColors() + { + final int MAX_SHIFT = 30; Screen[] screens = MobileDevice.getMobileDevice().getScreens(); Screen activeScreen = null; int depth = 0; - if (screens != null) { - for (int i = 0; i < screens.length; i++) { - if (screens[i].isActive()) { + if(screens != null) + { + for(int i = 0; i < screens.length; i++) + { + if(screens[i].isActive()) + { activeScreen = screens[i]; } } depth = activeScreen.getColorDepth(); - if (depth > MAX_SHIFT) { + if(depth > MAX_SHIFT) + { numColors = Integer.MAX_VALUE; } - else { + else + { numColors = (1 << depth); } } - else { + else + { numColors = 0; } - + numColors = 2 << 16; return numColors; } @@ -224,9 +240,12 @@ * * @return current Displayable */ - public Displayable getCurrent() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + public Displayable getCurrent() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { getcurrent = eswtGetCurrent(); } }); @@ -238,9 +257,11 @@ * * @return current Displayable object which is active for Display */ - Displayable eswtGetCurrent() { - if (ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() - != null) { + Displayable eswtGetCurrent() + { + if(ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() + != null) + { return currentDisplayable; } return null; @@ -251,30 +272,38 @@ * * @param displayable new Displayable to be set active in midlet */ - public void setCurrent(Displayable displayable) { - if (displayable != null) { - if (displayable instanceof Alert) { + public void setCurrent(Displayable displayable) + { + if(displayable != null) + { + if(displayable instanceof Alert) + { Alert alert = (Alert) displayable; - if (currentDisplayable == null) { + if(currentDisplayable == null) + { // if Alert is the first Displayable alert.setNextDisplayable(null); doSetCurrent(alert); } - else { + else + { setCurrent(alert, currentDisplayable); } } - else { + else + { doSetCurrent(displayable); } } - else { + else + { /* * If parameter is null, nothing is required to happen, optionally * bringing Midlet to background/foreground. */ - if (currentDisplayable != null && currentDisplayable instanceof Alert) { + if(currentDisplayable != null && currentDisplayable instanceof Alert) + { // Restarts Alert timer if any Alert alert = (Alert) currentDisplayable; alert.resetTimerTask(true); @@ -291,18 +320,22 @@ * @throws NullPointerException if aAlert or aNextDisplayable is null * @throws IllegalArgumentException if aNextDisplayable is an Alert */ - public void setCurrent(Alert alert, Displayable nextDisplayable) { - if (alert == null) { + public void setCurrent(Alert alert, Displayable nextDisplayable) + { + if(alert == null) + { throw new NullPointerException( - MsgRepository.DISPLAY_EXCEPTION_ALERT_IS_NULL); + MsgRepository.DISPLAY_EXCEPTION_ALERT_IS_NULL); } - else if (nextDisplayable == null) { + else if(nextDisplayable == null) + { throw new NullPointerException( - MsgRepository.DISPLAY_EXCEPTION_NEXTDISP_IS_NULL); + MsgRepository.DISPLAY_EXCEPTION_NEXTDISP_IS_NULL); } - else if (nextDisplayable instanceof Alert) { + else if(nextDisplayable instanceof Alert) + { throw new IllegalArgumentException( - MsgRepository.DISPLAY_EXCEPTION_NEXTDISP_IS_ALERT); + MsgRepository.DISPLAY_EXCEPTION_NEXTDISP_IS_ALERT); } alert.setNextDisplayable(nextDisplayable); doSetCurrent(alert); @@ -318,18 +351,22 @@ * @throws IllegalStateException If The Item is owned by an Alert. * @throws NullPointerException If the Item is null. */ - public void setCurrentItem(Item item) { - if (item == null) { + public void setCurrentItem(Item item) + { + if(item == null) + { throw new NullPointerException( - MsgRepository.DISPLAY_EXCEPTION_ITEM_IS_NULL); + MsgRepository.DISPLAY_EXCEPTION_ITEM_IS_NULL); } - if (item.isContainedInAlert()) { + if(item.isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } - if (item.getParent() == null) { + if(item.getParent() == null) + { throw new IllegalStateException( - MsgRepository.DISPLAY_EXCEPTION_ITEM_HAS_NO_PARENT); + MsgRepository.DISPLAY_EXCEPTION_ITEM_HAS_NO_PARENT); } Logger.method(this, "setCurrentItem", item); ((Form) item.getParent()).setCurrentItem(item); @@ -341,10 +378,14 @@ * * @param displayable the Displayable to be set active */ - private void doSetCurrent(final Displayable displayable) { - if (currentDisplayable != displayable) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private void doSetCurrent(final Displayable displayable) + { + if(currentDisplayable != displayable) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtDoSetCurrent(displayable); } }); @@ -354,16 +395,19 @@ /** * eSWT callback for doSetCurrent */ - private void eswtDoSetCurrent(Displayable displayable) { + private void eswtDoSetCurrent(Displayable displayable) + { Logger.info("Display :: " + currentDisplayable + " -> " + displayable); // hide old Displayable - if (currentDisplayable != null) { + if(currentDisplayable != null) + { currentDisplayable.eswtHandleHideCurrentEvent(); } // change the current reference currentDisplayable = displayable; // show new Displayable - if (currentDisplayable != null) { + if(currentDisplayable != null) + { currentDisplayable.eswtHandleShowCurrentEvent(); } } @@ -373,8 +417,9 @@ * * @param runnable to serialize. */ - public void callSerially(Runnable runnable) { - eswtCallSerially(runnable); + public void callSerially(Runnable runnable) + { + eswtCallSerially(runnable); } /** @@ -382,11 +427,12 @@ * * @param runnable to serialize. */ - void eswtCallSerially(Runnable runnable) { - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.RUNNABLE_CALLSERIALLY, this); - event.runnable = runnable; - eventDispatcher.postEvent(event); + void eswtCallSerially(Runnable runnable) + { + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent(LCDUIEvent.RUNNABLE_CALLSERIALLY, this); + event.runnable = runnable; + eventDispatcher.postEvent(event); } /** @@ -397,13 +443,14 @@ * feature is not supported. * @throws IllegalArgumentException if duration is negative. */ - public boolean flashBacklight(int duration) { - if (duration < 0) { + public boolean flashBacklight(int duration) + { + if(duration < 0) + { throw new IllegalArgumentException( - MsgRepository.DISPLAY_EXCEPTION_NEGATIVE_DURATION); + MsgRepository.DISPLAY_EXCEPTION_NEGATIVE_DURATION); } - // TODO: eSWT support required - return false; + return DisplayExtension.flashLights(duration); } /** @@ -414,13 +461,14 @@ * or feature is not supported. * @throws IllegalArgumentException if duration is negative. */ - public boolean vibrate(int duration) { - if (duration < 0) { + public boolean vibrate(int duration) + { + if(duration < 0) + { throw new IllegalArgumentException( - MsgRepository.DISPLAY_EXCEPTION_NEGATIVE_DURATION); + MsgRepository.DISPLAY_EXCEPTION_NEGATIVE_DURATION); } - // TODO: eSWT support required - return false; + return DisplayExtension.startVibra(duration); } /** @@ -430,34 +478,38 @@ * @return color in RGB. currently only 2 constants supported: * COLOR_BACKGROUND and COLOR_FOREGROUND */ - public int getColor(int specifier) { + public int getColor(int specifier) + { // TODO: eSWT support required - for other color constants in LCDUI int constant = 0; - switch (specifier) { - case COLOR_BACKGROUND: - constant = SWT.COLOR_WIDGET_BACKGROUND; - break; - case COLOR_FOREGROUND: - constant = SWT.COLOR_WIDGET_FOREGROUND; - break; - case COLOR_HIGHLIGHTED_BACKGROUND: - break; - case COLOR_HIGHLIGHTED_FOREGROUND: - break; - case COLOR_BORDER: - break; - case COLOR_HIGHLIGHTED_BORDER: - break; - default: - throw new IllegalArgumentException( - MsgRepository.DISPLAY_EXCEPTION_INVALID_COLOR_IDENTIFIER); + switch(specifier) + { + case COLOR_BACKGROUND: + constant = SWT.COLOR_WIDGET_BACKGROUND; + break; + case COLOR_FOREGROUND: + constant = SWT.COLOR_WIDGET_FOREGROUND; + break; + case COLOR_HIGHLIGHTED_BACKGROUND: + break; + case COLOR_HIGHLIGHTED_FOREGROUND: + break; + case COLOR_BORDER: + break; + case COLOR_HIGHLIGHTED_BORDER: + break; + default: + throw new IllegalArgumentException( + MsgRepository.DISPLAY_EXCEPTION_INVALID_COLOR_IDENTIFIER); } final int finalConstant = constant; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtTempRgb = ESWTUIThreadRunner.getInstance().getDisplay() - .getSystemColor(finalConstant).getRGB(); + .getSystemColor(finalConstant).getRGB(); } }); @@ -475,7 +527,8 @@ * @param isHighlighted true if component is highlighted * @return Border style of a UI component. */ - public int getBorderStyle(boolean isHighlighted) { + public int getBorderStyle(boolean isHighlighted) + { return Graphics.SOLID; } @@ -484,7 +537,8 @@ * * @return number of supported alpha levels */ - public int numAlphaLevels() { + public int numAlphaLevels() + { // Number of alpha levels is always 256, this implementation does // not support monochrome or 2-bit transparency. return 256; @@ -496,7 +550,8 @@ * @param imgType Image type. * @return Best image width in pixels. */ - public int getBestImageWidth(int imgType) { + public int getBestImageWidth(int imgType) + { return DisplayExtension.getBestImageWidth(imgType); } @@ -506,18 +561,21 @@ * @param imgType Image type. * @return Best image height in pixels. */ - public int getBestImageHeight(int imgType) { + public int getBestImageHeight(int imgType) + { return DisplayExtension.getBestImageHeight(imgType); } /* * Dispatcher thread calls. */ - void doCallback(LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.RUNNABLE_CALLSERIALLY: - event.runnable.run(); - break; - } + void doCallback(LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.RUNNABLE_CALLSERIALLY: + event.runnable.run(); + break; + } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Displayable.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Displayable.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Displayable.java Fri May 14 15:47:24 2010 +0300 @@ -33,7 +33,8 @@ /** * Implementation of LCDUI Displayable class. */ -public abstract class Displayable { +public abstract class Displayable +{ private EswtCommandListener eswtCommandListener = new EswtCommandListener(); @@ -94,19 +95,24 @@ /** * Default Constructor. */ - Displayable(String title) { + Displayable(String title) + { this.title = title; finalizer = ((finalizer != null) ? finalizer - : new com.nokia.mj.impl.rt.support.Finalizer() { - public void finalizeImpl() { - if (finalizer != null) { - finalizer = null; - if (!ESWTUIThreadRunner.isDisposed()) { - dispose(); - } - } + : new com.nokia.mj.impl.rt.support.Finalizer() + { + public void finalizeImpl() + { + if(finalizer != null) + { + finalizer = null; + if(!ESWTUIThreadRunner.isDisposed()) + { + dispose(); } - }); + } + } + }); ESWTUIThreadRunner.update(getClass().getName(), 1); } @@ -114,9 +120,12 @@ * Performs eSWT construction of shell and content composite.
            * Should be called from child level constructors. */ - final void construct() { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + final void construct() + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { shell = eswtConstructShell(SWT.SYSTEM_MODAL); eswtSetTitle(); contentComp = eswtConstructContent(SWT.NONE); @@ -128,14 +137,19 @@ /** * Dispose Displayable. */ - void dispose() { - if (ticker != null) { + void dispose() + { + if(ticker != null) + { ticker.removeLabel(tickerLabel); } ESWTUIThreadRunner.update(getClass().getName(), -1); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (shell != null) { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(shell != null) + { shell.dispose(); } } @@ -150,7 +164,8 @@ * * @return eSWT shell */ - Shell eswtConstructShell(int style) { + Shell eswtConstructShell(int style) + { return new MobileShell(ESWTUIThreadRunner.getInstance().getDisplay(), style); } @@ -162,7 +177,8 @@ * * @return Composite where the content is placed. */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { Composite comp = new CompositeExtension(shell, style); return comp; } @@ -170,8 +186,10 @@ /** * Called by Display when Displayable should become visible. */ - void eswtHandleShowCurrentEvent() { - if (!shell.isDisposed()) { + void eswtHandleShowCurrentEvent() + { + if(!shell.isDisposed()) + { eswtUpdateSizes(); shell.addShellListener(eswtShellListener); shell.addDisposeListener(eswtDisposeListener); @@ -196,9 +214,11 @@ /** * Called by Display when Displayable should become hidden. */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { isLcduiVisible = false; - if (!shell.isDisposed()) { + if(!shell.isDisposed()) + { shell.removeShellListener(eswtShellListener); shell.removeDisposeListener(eswtDisposeListener); shell.removeControlListener(eswtControlListener); @@ -211,7 +231,8 @@ * * @param e eSWT event */ - void eswtHandleEvent(Event e) { + void eswtHandleEvent(Event e) + { // implementation in child classes // Logger.method(this, "eswtHandleEvent", e); } @@ -219,35 +240,42 @@ /** * Called by ShellListener when shell gets activated. */ - void handleShellActivatedEvent() { - // Implementation in child-classes - // Logger.method(this, "handleShellActivatedEvent"); - if (ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() - != null) { - if ( JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT, - JadAttributeUtil.VALUE_PAUSE)) { - ApplicationUtils.getInstance().resumeApplication(); - } - isShellActive = true; - } + void handleShellActivatedEvent() + { + // Implementation in child-classes + // Logger.method(this, "handleShellActivatedEvent"); + if(ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() + != null) + { + if(JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT, + JadAttributeUtil.VALUE_PAUSE)) + { + ApplicationUtils.getInstance().resumeApplication(); + } + isShellActive = true; + } } /** * Called by ShellListener when shell gets de-activated. */ - void handleShellDeActivatedEvent() { - // Implementation in child-classes - // Logger.method(this, "handleShellDeActivatedEvent"); - if(isShellActive) { - if (ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() - == null) { - if ( JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT, - JadAttributeUtil.VALUE_PAUSE)) { - ApplicationUtils.getInstance().pauseApplication(); - isShellActive = false; - } - } - } + void handleShellDeActivatedEvent() + { + // Implementation in child-classes + // Logger.method(this, "handleShellDeActivatedEvent"); + if(isShellActive) + { + if(ESWTUIThreadRunner.getInstance().getDisplay().getActiveShell() + == null) + { + if(JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT, + JadAttributeUtil.VALUE_PAUSE)) + { + ApplicationUtils.getInstance().pauseApplication(); + isShellActive = false; + } + } + } } /** @@ -257,9 +285,10 @@ * @param width new width of Displayable. * @param height new height of Displayable. */ - void eswtHandleResizeEvent(int width, int height) { + void eswtHandleResizeEvent(int width, int height) + { Logger.method(this, "eswtHandleResizeEvent", - String.valueOf(width), String.valueOf(height)); + String.valueOf(width), String.valueOf(height)); LCDUIEvent event = EventDispatcher.instance().newEvent(LCDUIEvent.DISPLAYABLE_SIZECHANGED, this); event.width = width; event.height = height; @@ -269,7 +298,8 @@ /** * Returns if the shell is Dialog styled. */ - private boolean isDialogShell() { + private boolean isDialogShell() + { return (shell.getStyle() & SWT.DIALOG_TRIM) == SWT.DIALOG_TRIM; } @@ -279,18 +309,21 @@ * @param aWidth required width or -1 to ignore * @param aHeight required height or -1 to ignore */ - void eswtSetPreferredContentSize(int aWidth, int aHeight) { - if (isDialogShell()) { + void eswtSetPreferredContentSize(int aWidth, int aHeight) + { + if(isDialogShell()) + { // aHeight += Config.DISPLAYABLE_DIALOGSHELL_HEIGHT_DISPLACEMENT; Logger.method(this, "eswtSetPreferredContentSize", - String.valueOf(aWidth), String.valueOf(aHeight)); + String.valueOf(aWidth), String.valueOf(aHeight)); Rectangle contentBounds = contentComp.getBounds(); int newWidth = (aWidth > 0 ? aWidth : contentBounds.width); int newHeight = (aHeight > 0 ? aHeight : contentBounds.height); - if (tickerLabel != null) { + if(tickerLabel != null) + { newHeight += tickerLabel.getBounds().height; } @@ -304,14 +337,17 @@ } } - Rectangle eswtLayoutShellContent() { + Rectangle eswtLayoutShellContent() + { Rectangle shellArea = shell.getClientArea(); - if (tickerLabel != null) { + if(tickerLabel != null) + { int tickerHeight = tickerLabel.getBounds().height; contentComp.setBounds(0, tickerHeight, - shellArea.width, shellArea.height - tickerHeight); + shellArea.width, shellArea.height - tickerHeight); } - else { + else + { contentComp.setBounds(0, 0, shellArea.width, shellArea.height); } return contentComp.getClientArea(); @@ -320,15 +356,18 @@ /** * Update internal size of Displayable. */ - void eswtUpdateSizes() { + void eswtUpdateSizes() + { Rectangle newArea = eswtLayoutShellContent(); // if the content size has changed or its not initialized - if (!initialized + if(!initialized || newArea.width != contentArea.width - || newArea.height != contentArea.height) { + || newArea.height != contentArea.height) + { contentArea = newArea; initialized = true; - if (ticker != null) { + if(ticker != null) + { ticker.updateSpeed(); } eswtHandleResizeEvent(contentArea.width, contentArea.height); @@ -340,9 +379,12 @@ * * @return true if this Displayable is currently visible. */ - public synchronized boolean isShown() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + public synchronized boolean isShown() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { isShownReturnValue = eswtIsShown(); } }); @@ -352,14 +394,17 @@ /** * eSWT call-back that verifies that the Displayable is shown. */ - boolean eswtIsShown() { - if (!isLcduiVisible || !isShellActive) { + boolean eswtIsShown() + { + if(!isLcduiVisible || !isShellActive) + { // shell.isVisible() doesn't return false if MIDlet // is in background. That's why isVisible-variable is // used instead. return false; } - if (shell.isDisposed() || !shell.isEnabled()) { + if(shell.isDisposed() || !shell.isEnabled()) + { return false; } return true; @@ -370,10 +415,12 @@ * * @param command a Command */ - void validateCommand(Command command) { - if (command == null) { + void validateCommand(Command command) + { + if(command == null) + { throw new NullPointerException( - MsgRepository.DISPLAYABLE_EXCEPTION_NULL_PARAMETER); + MsgRepository.DISPLAYABLE_EXCEPTION_NULL_PARAMETER); } } @@ -382,17 +429,24 @@ * * @param enableCmds visibility switch */ - void setCommandsVisibility(boolean enableCmds) { - if (enableCmds != isEnabledCmds) { + void setCommandsVisibility(boolean enableCmds) + { + if(enableCmds != isEnabledCmds) + { isEnabledCmds = enableCmds; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { int numCmd = getNumCommands(); - for (int i = 0; i < numCmd; i++) { - if (isEnabledCmds) { + for(int i = 0; i < numCmd; i++) + { + if(isEnabledCmds) + { eswtAddCommand(getCommand(i)); } - else { + else + { eswtRemoveCommand(getCommand(i)); } } @@ -408,15 +462,20 @@ * to this Displayable, nothing happens. * @throws NullPointerException If parameter is null. */ - public void addCommand(Command command) { + public void addCommand(Command command) + { validateCommand(command); - if (!commands.contains(command)) { + if(!commands.contains(command)) + { commands.addElement(command); // Command is not yet added to this Displayable. - if (isEnabledCmds) { + if(isEnabledCmds) + { final Command finalCommand = command; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtAddCommand(finalCommand); } }); @@ -427,9 +486,11 @@ /** * eSWT callback to add a Command. */ - void eswtAddCommand(Command cmd) { + void eswtAddCommand(Command cmd) + { cmd.eswtAddESWTCommand(shell, false); - if (eswtIsShown()) { + if(eswtIsShown()) + { cmd.eswtAddCommandSelectionListener(shell, eswtCommandListener); } } @@ -440,14 +501,19 @@ * @param command Command to be removed. If parameter is null or Command * isn't added to Displayable, nothing happens. */ - public void removeCommand(Command command) { - if (command != null && commands.contains(command)) { + public void removeCommand(Command command) + { + if(command != null && commands.contains(command)) + { // Remove command from iCommands-vector commands.removeElement(command); - if (isEnabledCmds) { + if(isEnabledCmds) + { final Command finalCommand = command; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtRemoveCommand(finalCommand); } }); @@ -458,8 +524,10 @@ /** * eSWT callback to remove a Command. */ - void eswtRemoveCommand(Command cmd) { - if (eswtIsShown()) { + void eswtRemoveCommand(Command cmd) + { + if(eswtIsShown()) + { cmd.eswtRemoveCommandSelectionListener(shell, eswtCommandListener); } cmd.eswtRemoveESWTCommand(shell); @@ -473,13 +541,16 @@ * CommandListener is removed. If null and no CommandListener * exists, nothing happens. */ - public void setCommandListener(CommandListener commandListener) { + public void setCommandListener(CommandListener commandListener) + { this.iCommandListener = commandListener; } - public boolean hasCommandListener() { - if(this.iCommandListener != null) { - return true; + public boolean hasCommandListener() + { + if(this.iCommandListener != null) + { + return true; } return false; } @@ -488,9 +559,11 @@ /** * Add command listener for all Commands added to this Displayable. */ - void eswtAddSelectionListenerForCommands() { + void eswtAddSelectionListenerForCommands() + { Command cmd = null; - for (Enumeration e = commands.elements(); e.hasMoreElements();) { + for(Enumeration e = commands.elements(); e.hasMoreElements();) + { cmd = (Command) e.nextElement(); cmd.eswtAddCommandSelectionListener(shell, eswtCommandListener); } @@ -499,9 +572,11 @@ /** * Remove command listener from Commands added to this Displayable. */ - void eswtRemoveSelectionListenerForCommands() { + void eswtRemoveSelectionListenerForCommands() + { Command cmd = null; - for (Enumeration e = commands.elements(); e.hasMoreElements();) { + for(Enumeration e = commands.elements(); e.hasMoreElements();) + { cmd = (Command) e.nextElement(); cmd.eswtRemoveCommandSelectionListener(shell, eswtCommandListener); } @@ -512,8 +587,10 @@ * * @param command the Command */ - final void callCommandAction(Command command) { - if (iCommandListener != null && command != null) { + final void callCommandAction(Command command) + { + if(iCommandListener != null && command != null) + { LCDUIEvent event = EventDispatcher.instance().newEvent(LCDUIEvent.DISPLAYABLE_COMMANDACTION, this); event.command = command; event.commandListener = iCommandListener; @@ -526,7 +603,8 @@ * * @return the number of commands in this Displayable */ - final int getNumCommands() { + final int getNumCommands() + { return commands.size(); } @@ -536,7 +614,8 @@ * @param index index of command * @return the command */ - final Command getCommand(int index) { + final Command getCommand(int index) + { return (Command) commands.elementAt(index); } @@ -545,7 +624,8 @@ * * @return Width of the Displayable in pixels. */ - public int getWidth() { + public int getWidth() + { return contentArea.width; } @@ -554,7 +634,8 @@ * * @return Height of the Displayable in pixels. */ - public int getHeight() { + public int getHeight() + { return contentArea.height; } @@ -565,33 +646,41 @@ * * @param newTicker New ticker. If null, current ticker is removed. */ - public void setTicker(Ticker newTicker) { - if (ticker == newTicker) { + public void setTicker(Ticker newTicker) + { + if(ticker == newTicker) + { return; } - if (ticker != null) { + if(ticker != null) + { // Ticker exists, removing it: ticker.removeLabel(getTickerLabel()); } ticker = newTicker; - if (ticker != null) { + if(ticker != null) + { ticker.addLabel(getTickerLabel()); } final Ticker finalTicker = ticker; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - if (finalTicker != null) { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + if(finalTicker != null) + { // Setting ticker: tickerLabel.setText(finalTicker.getFormattedString()); tickerLabel.pack(); // Avoid ticker flashing by setting it out of the // screen first: tickerLabel.setBounds(Integer.MIN_VALUE, 0, - tickerLabel.getBounds().width, - tickerLabel.getBounds().height); + tickerLabel.getBounds().width, + tickerLabel.getBounds().height); } - else { + else + { // Removing ticker: tickerLabel.setText(""); tickerLabel.setBounds(Integer.MIN_VALUE, 0, 0, 0); @@ -599,7 +688,8 @@ eswtUpdateSizes(); } }); - if (ticker != null) { + if(ticker != null) + { // Start to scroll the ticker. Ticker may be already running // if it exists in some other displayable already, but // calling this again wont do any harm: @@ -612,7 +702,8 @@ * * @return Current ticker or null if no ticker set. */ - public Ticker getTicker() { + public Ticker getTicker() + { return ticker; } @@ -621,7 +712,8 @@ * * @return The title of the Displayable, or null if no title set. */ - public String getTitle() { + public String getTitle() + { return title; } @@ -630,10 +722,13 @@ * * @param newTitle new title or null for no title. */ - public void setTitle(String newTitle) { + public void setTitle(String newTitle) + { this.title = newTitle; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSetTitle(); } }); @@ -642,7 +737,8 @@ /** * Sets shell's title. Nulls are not allowed. */ - void eswtSetTitle() { + void eswtSetTitle() + { // eSWT Shell doesn't take null value as title shell.setText((title != null ? title : "")); } @@ -650,12 +746,16 @@ /** * Creates singleton Label instance used by Ticker. */ - private Label getTickerLabel() { - if (tickerLabel == null) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private Label getTickerLabel() + { + if(tickerLabel == null) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { tickerLabel = new Label(shell, - SWT.SHADOW_NONE | SWT.HORIZONTAL | SWT.CENTER); + SWT.SHADOW_NONE | SWT.HORIZONTAL | SWT.CENTER); } }); } @@ -669,13 +769,15 @@ * @param width new width of Displayable. * @param height new height of Displayable. */ - protected void sizeChanged(int width, int height) { + protected void sizeChanged(int width, int height) + { } /** * eSWT callback to get the Shell of the Displayable. */ - final Shell getShell() { + final Shell getShell() + { return this.shell; } @@ -684,7 +786,8 @@ * * @return Composite. */ - Composite getContentComp() { + Composite getContentComp() + { return contentComp; } @@ -692,31 +795,36 @@ * The client area. It's ensured that after the construction this is always * set. */ - final Rectangle getContentArea() { - return contentArea; + final Rectangle getContentArea() + { + return contentArea; } /* * Dispatcher thread calls. */ - void doCallback(LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.DISPLAYABLE_SIZECHANGED: - sizeChanged(event.width, event.height); - break; - case LCDUIEvent.DISPLAYABLE_COMMANDACTION: - event.commandListener.commandAction(event.command, this); - break; - } + void doCallback(LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.DISPLAYABLE_SIZECHANGED: + sizeChanged(event.width, event.height); + break; + case LCDUIEvent.DISPLAYABLE_COMMANDACTION: + event.commandListener.commandAction(event.command, this); + break; + } } /** * Inner class which receives SelectionEvents from eSWT and convert and * forwards those events to LCDUI's CommandListener. */ - class EswtCommandListener implements SelectionListener { + class EswtCommandListener implements SelectionListener + { - public void widgetDefaultSelected(SelectionEvent e) { + public void widgetDefaultSelected(SelectionEvent e) + { } /** @@ -724,14 +832,17 @@ * Displayable's CommandListener if event source matches with the * Commands added to the Displayable. */ - public void widgetSelected(SelectionEvent event) { + public void widgetSelected(SelectionEvent event) + { // Go through all Commands added to this Displayable: - for (Enumeration e = commands.elements(); e.hasMoreElements();) { + for(Enumeration e = commands.elements(); e.hasMoreElements();) + { Command cmd = (Command) e.nextElement(); // Select eSWT Command from Command which is connected to // this Displayable and compare it to the widget which // launched the event: - if (cmd.getESWTCommand(shell) == event.widget) { + if(cmd.getESWTCommand(shell) == event.widget) + { callCommandAction(cmd); break; } @@ -743,52 +854,66 @@ * Every Displayable must listen shell events to be able to tell is the * MIDlet sent to background. */ - class EswtShellListener implements ShellListener { + class EswtShellListener implements ShellListener + { - public void shellActivated(ShellEvent e) { - if (!isShellActive) { - handleShellActivatedEvent(); - } + public void shellActivated(ShellEvent e) + { + if(!isShellActive) + { + handleShellActivatedEvent(); + } } - public void shellDeactivated(ShellEvent e) { - ESWTUIThreadRunner.getInstance().getDisplay() - .asyncExec(new Runnable() { - public void run() { - handleShellDeActivatedEvent(); - } - }); + public void shellDeactivated(ShellEvent e) + { + ESWTUIThreadRunner.getInstance().getDisplay() + .asyncExec(new Runnable() + { + public void run() + { + handleShellDeActivatedEvent(); + } + }); } - public void shellClosed(ShellEvent e) { + public void shellClosed(ShellEvent e) + { } - public void shellIconified(ShellEvent e) { + public void shellIconified(ShellEvent e) + { } - public void shellDeiconified(ShellEvent e) { + public void shellDeiconified(ShellEvent e) + { } } - class EswtDisposeListener implements DisposeListener { + class EswtDisposeListener implements DisposeListener + { - public void widgetDisposed(DisposeEvent e) { - isShellActive = false; - } + public void widgetDisposed(DisposeEvent e) + { + isShellActive = false; + } } /** * Displayable must listen resize-events to be able to call * sizeChanged()-method at the right time. */ - class EswtControlListener implements ControlListener { - public void controlResized(ControlEvent e) { + class EswtControlListener implements ControlListener + { + public void controlResized(ControlEvent e) + { eswtUpdateSizes(); } - public void controlMoved(ControlEvent e) { + public void controlMoved(ControlEvent e) + { } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/DisposeStorage.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/DisposeStorage.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/DisposeStorage.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -24,11 +24,13 @@ /** * Storage of objects which have to be disposed manually. */ -class DisposeStorage { +class DisposeStorage +{ private Vector storage; - DisposeStorage() { + DisposeStorage() + { storage = new Vector(); } @@ -37,21 +39,26 @@ * * @param obj object to add. */ - public void addObject(Object obj) { + public void addObject(Object obj) + { storage.addElement(obj); } /** * Dispose all objects from garbage. */ - public void dispose() { + public void dispose() + { Object tempObject = null; - for (int i = 0; i < storage.size(); i++) { + for(int i = 0; i < storage.size(); i++) + { tempObject = storage.elementAt(i); - if (tempObject instanceof Image) { + if(tempObject instanceof Image) + { ((Image) tempObject).dispose(); } - else if (tempObject instanceof Color) { + else if(tempObject instanceof Color) + { ((Color) tempObject).dispose(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ESWTUIThreadRunner.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ESWTUIThreadRunner.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ESWTUIThreadRunner.java Fri May 14 15:47:24 2010 +0300 @@ -41,7 +41,8 @@ * Also note that if the other thread which is running eSWT stops executing then * this class stops working too. */ -final class ESWTUIThreadRunner implements Listener, ShutdownListener, Runnable { +final class ESWTUIThreadRunner implements Listener, ShutdownListener, Runnable +{ private static final int NONE = 1; private static final int CREATING = 2; @@ -62,7 +63,8 @@ private Display display; private int state = NONE; - static { + static + { // Create LCDUIInvoker for MMAPI to access underlying eSWT widgets LCDUIInvokerImpl.createInvoker(); @@ -79,7 +81,8 @@ /** * Private Constructor. Singleton. */ - private ESWTUIThreadRunner() { + private ESWTUIThreadRunner() + { Logger.info("Starting up"); // TODO: check if the startUI throws RuntimeException on already @@ -97,16 +100,20 @@ * * @return Instance of this class. */ - public static ESWTUIThreadRunner getInstance() { - synchronized (ESWTUIThreadRunner.class) { - if (instance == null) { - instance = new ESWTUIThreadRunner(); - } + public static ESWTUIThreadRunner getInstance() + { + synchronized(ESWTUIThreadRunner.class) + { + if(instance == null) + { + instance = new ESWTUIThreadRunner(); + } } return instance; } - public static boolean isDisposed() { + public static boolean isDisposed() + { return getInstance().getDisplay().isDisposed(); } @@ -115,7 +122,8 @@ * * @param runnable a runnable */ - public static void syncExec(Runnable runnable) { + public static void syncExec(Runnable runnable) + { getInstance().getDisplay().syncExec(runnable); } @@ -126,16 +134,21 @@ * * @param runnable a Runnable */ - public static void safeSyncExec(Runnable runnable) { - try { + public static void safeSyncExec(Runnable runnable) + { + try + { getInstance().getDisplay().syncExec(runnable); } - catch (SWTException swte) { - if (swte.getCause() != null && swte.getCause() instanceof RuntimeException) { + catch(SWTException swte) + { + if(swte.getCause() != null && swte.getCause() instanceof RuntimeException) + { // if the cause is RuntimeException, throw it - throw (RuntimeException) swte.getCause(); + throw(RuntimeException) swte.getCause(); } - else { + else + { // throw forward as a RuntimeException throw new RuntimeException(swte.getMessage()); } @@ -145,19 +158,22 @@ /** * Return last key's scancode. */ - static int getLastKeyScancode() { + static int getLastKeyScancode() + { return lastKeyScancode; } /** * Return last key's modifier. */ - static int getLastKeyModifier() { + static int getLastKeyModifier() + { return lastKeyModifier; } - static int getKeyRepeatCount() { - return keyRepeatCount; + static int getKeyRepeatCount() + { + return keyRepeatCount; } /** @@ -165,45 +181,56 @@ * * @return eSWT Display. */ - public Display getDisplay() { + public Display getDisplay() + { // wait until display is created or re-created - while (isState(NONE | CREATING)) { + while(isState(NONE | CREATING)) + { doWait(); } return display; } - private static void doWait() { - try { + private static void doWait() + { + try + { Thread.sleep(1); } - catch (InterruptedException ex) { + catch(InterruptedException ex) + { // ignore } } - private void onStartup() { - if (isState(CREATING)) { + private void onStartup() + { + if(isState(CREATING)) + { display = Display.getDefault(); display.addListener(SWT.Close, this); display.addFilter(SWT.KeyDown, this); display.addFilter(SWT.KeyUp, this); display.addFilter(SWT.Traverse, this); - if (display != null) { + if(display != null) + { // We called Display.getDefault() first so we created the // Display which means that we are running the UI-thread // of this Display changeState(RUNNING); } - else { + else + { // We don't own the Display - we cannot run the UI-thread changeState(EXITING); } } } - private void onShutdown() { - if (isState(EXITING)) { + private void onShutdown() + { + if(isState(EXITING)) + { display.removeListener(SWT.Close, this); display.removeFilter(SWT.KeyDown, this); display.removeFilter(SWT.KeyUp, this); @@ -211,11 +238,13 @@ ds.dispose(); Font.disposeFonts(); listClassStat(); - try { + try + { // NullPointerException is simply caught and ignored display.dispose(); } - catch (Exception ex) { + catch(Exception ex) + { Logger.exception("Display dispose", ex); } } @@ -224,83 +253,105 @@ /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ - public void handleEvent(Event e) { - switch (e.type) { - case SWT.Close: { - Logger.info("Close event"); - // Check if the No-Exit attribute is set - if (JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_NO_EXIT, JadAttributeUtil.VALUE_TRUE)) { - // don't exit - e.doit = false; - } - break; + public void handleEvent(Event e) + { + switch(e.type) + { + case SWT.Close: + { + Logger.info("Close event"); + // Check if the No-Exit attribute is set + if(JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_MIDLET_NO_EXIT, JadAttributeUtil.VALUE_TRUE)) + { + // don't exit + e.doit = false; + } + break; + } + case SWT.KeyDown: + if(e.keyCode == lastKeyScancode || lastKeyScancode == 0) + { + keyRepeatCount++; } - case SWT.KeyDown: - if (e.keyCode == lastKeyScancode || lastKeyScancode == 0) { - keyRepeatCount++; - } else { - keyRepeatCount = 0; - } - handleKey(e); - break; - case SWT.KeyUp: { - keyRepeatCount = 0; - handleKey(e); - // After KeyUp event has been handled, clear stored values - lastKeyScancode = 0; - lastKeyModifier = 0; - break; + else + { + keyRepeatCount = 0; } - case SWT.Traverse: { - javax.microedition.lcdui.Display.getDisplay().eswtHandleEvent(e); - } - default: - break; + handleKey(e); + break; + case SWT.KeyUp: + { + keyRepeatCount = 0; + handleKey(e); + // After KeyUp event has been handled, clear stored values + lastKeyScancode = 0; + lastKeyModifier = 0; + break; + } + case SWT.Traverse: + { + javax.microedition.lcdui.Display.getDisplay().eswtHandleEvent(e); + } + default: + break; } } /* (non-Javadoc) * @see com.nokia.mj.impl.rt.support.ShutdownListener#shuttingDown() */ - public void shuttingDown() { + public void shuttingDown() + { Logger.info("Shutting Down"); - EventDispatcher.instance().terminate(new Runnable() { - public void run() { + EventDispatcher.instance().terminate(new Runnable() + { + public void run() + { changeState(EXITING); - } + } }); } /** * Creates new eSWT Display and runs eSWT UI-thread. */ - public void run() { + public void run() + { changeState(CREATING); onStartup(); - while (isState(ALL - EXITING)) { - try { + while(isState(ALL - EXITING)) + { + try + { // Execute the eSWT event loop. - while (isState(RUNNING)) { - if (!display.readAndDispatch()) { + while(isState(RUNNING)) + { + if(!display.readAndDispatch()) + { display.sleep(); } } } - catch (Exception ex) { - if (ex instanceof SWTException) { + catch(Exception ex) + { + if(ex instanceof SWTException) + { Throwable t = ((SWTException) ex).getCause(); - if (t != null && t instanceof RuntimeException) { + if(t != null && t instanceof RuntimeException) + { // this might be an expected exception of safeSyncExec Logger.warning("eSWT Thread Exception: " + ex); // t.printStackTrace(); } } - else { + else + { Logger.error("eSWT Thread Exception: " + ex); ex.printStackTrace(); } } - catch (Error er) { + catch(Error er) + { Logger.error("eSWT Thread Error" + er); er.printStackTrace(); } @@ -309,45 +360,55 @@ changeState(NONE); } - private boolean isState(int mask) { - synchronized (lock) { + private boolean isState(int mask) + { + synchronized(lock) + { return ((state & mask) != 0); } } - private void changeState(int newstate) { + private void changeState(int newstate) + { Logger.info(getStateString(state) + " --> " + getStateString(newstate)); - if (display != null) { - try { + if(display != null) + { + try + { display.wake(); } - catch (Exception e) { + catch(Exception e) + { // ignore } } - synchronized (lock) { + synchronized(lock) + { state = newstate; } } - private String getStateString(int aState) { - switch (aState) { - case NONE: - return "NONE"; - case CREATING: - return "CREATING"; - case RUNNING: - return "RUNNING"; - case EXITING: - return "EXITING"; - default: - return ""; + private String getStateString(int aState) + { + switch(aState) + { + case NONE: + return "NONE"; + case CREATING: + return "CREATING"; + case RUNNING: + return "RUNNING"; + case EXITING: + return "EXITING"; + default: + return ""; } } - private void handleKey(Event e) { - lastKeyScancode = e.keyCode; - /* + private void handleKey(Event e) + { + lastKeyScancode = e.keyCode; + /* * Left Shift = 1280 = 0x00000500 * Right Shift = 1536 = 0x00000600 * Left Ctrl = 160 = 0x000000A0 @@ -359,10 +420,12 @@ lastKeyModifier = 0; int modifiers = e.stateMask & SWT.MODIFIER_MASK; // TODO: eSWT support required - howto map (left/right) SWT.SHIFT and SWT.CTRL - if ((modifiers & SWT.SHIFT) != 0) { + if((modifiers & SWT.SHIFT) != 0) + { lastKeyModifier |= 0x00000500; //left shift } - if ((modifiers & SWT.CTRL) != 0) { + if((modifiers & SWT.CTRL) != 0) + { lastKeyModifier |= 0x000000A0; //left control } /*if ((modifiers & SWT.COMMAND) != 0) { @@ -371,17 +434,21 @@ javax.microedition.lcdui.Display.getDisplay().eswtHandleEvent(e); } - static void update(String className, int delta) { - if (finalizers.containsKey(className)) { + static void update(String className, int delta) + { + if(finalizers.containsKey(className)) + { delta += ((Integer) finalizers.get(className)).intValue(); } finalizers.put(className, new Integer(delta)); } - static void listClassStat() { + static void listClassStat() + { Logger.info("OpenLCDUI Unfinalized classes :"); Enumeration e = finalizers.keys(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { String key = (String) e.nextElement(); Logger.info(key + " : " + (finalizers.get(key))); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/EventDispatcher.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/EventDispatcher.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/EventDispatcher.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -22,337 +22,387 @@ /* * Event dispatcher singleton class. Takes care of dispatching the UI callbacks - * to the MIDlet in a dedicated dispatcher thread. Owns and encapsulates an - * event queue of callback events. + * to the MIDlet in a dedicated dispatcher thread. Owns and encapsulates an + * event queue of callback events. */ -final class EventDispatcher { +final class EventDispatcher +{ + + private static EventDispatcher singleton; + private static EventQueue eventQueue; + private static Thread dispatcherThread; + private static boolean terminated; + private static Object wakeLock; + private static Object callbackLock; + private static boolean pendingWake; + private static Runnable terminatedNotification; + private final static String logName = "LCDUI event dispatcher: "; + + /* + * LCDUI-internal event class for callback events. + */ + static final class LCDUIEvent + { + /* + * High bits of the event event type identifier are used to group the + * events that are handled the same way in the Event Dispatcher. + */ + static final int CANVASBIT = 0x80000000; + static final int CUSTOMITEMBIT = 0x40000000; + static final int DISPLAYABLEBIT = 0x20000000; + static final int EVENTTYPEMASK = CANVASBIT|CUSTOMITEMBIT|DISPLAYABLEBIT; - private static EventDispatcher singleton; - private static EventQueue eventQueue; - private static Thread dispatcherThread; - private static boolean terminated; - private static Object wakeLock; - private static Object callbackLock; - private static boolean pendingWake; - private static Runnable terminatedNotification; - private final static String logName = "LCDUI event dispatcher: "; + /* + * Event type identifiers. + */ + static final int CANVAS_HIDENOTIFY = 1|CANVASBIT; + static final int CANVAS_KEYPRESSED = 2|CANVASBIT; + static final int CANVAS_KEYREPEATED = 3|CANVASBIT; + static final int CANVAS_KEYRELEASED = 4|CANVASBIT; + static final int CANVAS_PAINT_NATIVE_REQUEST = 5|CANVASBIT; + static final int CANVAS_PAINT_MIDLET_REQUEST = 6|CANVASBIT; + static final int CANVAS_POINTERDRAGGED = 7|CANVASBIT; + static final int CANVAS_POINTERPRESSED = 8|CANVASBIT; + static final int CANVAS_POINTERRELEASED = 9|CANVASBIT; + static final int CANVAS_SHOWNOTIFY = 10|CANVASBIT; + static final int DISPLAYABLE_SIZECHANGED = 11|DISPLAYABLEBIT; + static final int DISPLAYABLE_COMMANDACTION = 12|DISPLAYABLEBIT; + static final int CUSTOMITEM_HIDENOTIFY = 13|CUSTOMITEMBIT; + static final int CUSTOMITEM_KEYPRESSED = 14|CUSTOMITEMBIT; + static final int CUSTOMITEM_KEYREPEATED = 15|CUSTOMITEMBIT; + static final int CUSTOMITEM_KEYRELEASED = 16|CUSTOMITEMBIT; + static final int CUSTOMITEM_PAINT_NATIVE_REQUEST = 17|CUSTOMITEMBIT; + static final int CUSTOMITEM_PAINT_MIDLET_REQUEST = 18|CUSTOMITEMBIT; + static final int CUSTOMITEM_POINTERDRAGGED = 19|CUSTOMITEMBIT; + static final int CUSTOMITEM_POINTERPRESSED = 20|CUSTOMITEMBIT; + static final int CUSTOMITEM_POINTERRELEASED = 21|CUSTOMITEMBIT; + static final int CUSTOMITEM_SHOWNOTIFY = 22|CUSTOMITEMBIT; + static final int CUSTOMITEM_SIZECHANGED = 23|CUSTOMITEMBIT; + static final int CUSTOMITEM_TRAVERSE = 24|CUSTOMITEMBIT; + static final int CUSTOMITEM_TRAVERSEOUT = 25|CUSTOMITEMBIT; + static final int ITEM_COMMANDACTION = 26; + static final int ITEMSTATELISTENER_ITEMSTATECHANGED = 27; + static final int RUNNABLE_CALLSERIALLY = 28; - /* - * LCDUI-internal event class for callback events. - */ - static final class LCDUIEvent { - /* - * High bits of the event event type identifier are used to group the - * events that are handled the same way in the Event Dispatcher. - */ - static final int CANVASBIT = 0x80000000; - static final int CUSTOMITEMBIT = 0x40000000; - static final int DISPLAYABLEBIT = 0x20000000; - static final int EVENTTYPEMASK = CANVASBIT|CUSTOMITEMBIT|DISPLAYABLEBIT; - - /* - * Event type identifiers. - */ - static final int CANVAS_HIDENOTIFY = 1|CANVASBIT; - static final int CANVAS_KEYPRESSED = 2|CANVASBIT; - static final int CANVAS_KEYREPEATED = 3|CANVASBIT; - static final int CANVAS_KEYRELEASED = 4|CANVASBIT; - static final int CANVAS_PAINT_NATIVE_REQUEST = 5|CANVASBIT; - static final int CANVAS_PAINT_MIDLET_REQUEST = 6|CANVASBIT; - static final int CANVAS_POINTERDRAGGED = 7|CANVASBIT; - static final int CANVAS_POINTERPRESSED = 8|CANVASBIT; - static final int CANVAS_POINTERRELEASED = 9|CANVASBIT; - static final int CANVAS_SHOWNOTIFY = 10|CANVASBIT; - static final int DISPLAYABLE_SIZECHANGED = 11|DISPLAYABLEBIT; - static final int DISPLAYABLE_COMMANDACTION = 12|DISPLAYABLEBIT; - static final int CUSTOMITEM_HIDENOTIFY = 13|CUSTOMITEMBIT; - static final int CUSTOMITEM_KEYPRESSED = 14|CUSTOMITEMBIT; - static final int CUSTOMITEM_KEYREPEATED = 15|CUSTOMITEMBIT; - static final int CUSTOMITEM_KEYRELEASED = 16|CUSTOMITEMBIT; - static final int CUSTOMITEM_PAINT_NATIVE_REQUEST = 17|CUSTOMITEMBIT; - static final int CUSTOMITEM_PAINT_MIDLET_REQUEST = 18|CUSTOMITEMBIT; - static final int CUSTOMITEM_POINTERDRAGGED = 19|CUSTOMITEMBIT; - static final int CUSTOMITEM_POINTERPRESSED = 20|CUSTOMITEMBIT; - static final int CUSTOMITEM_POINTERRELEASED = 21|CUSTOMITEMBIT; - static final int CUSTOMITEM_SHOWNOTIFY = 22|CUSTOMITEMBIT; - static final int CUSTOMITEM_SIZECHANGED = 23|CUSTOMITEMBIT; - static final int CUSTOMITEM_TRAVERSE = 24|CUSTOMITEMBIT; - static final int CUSTOMITEM_TRAVERSEOUT = 25|CUSTOMITEMBIT; - static final int ITEM_COMMANDACTION = 26; - static final int ITEMSTATELISTENER_ITEMSTATECHANGED = 27; - static final int RUNNABLE_CALLSERIALLY = 28; - - /* - * Event parameters. - */ - int type; - int x; - int y; - int width; - int height; - int keyCode; - Runnable runnable; - Command command; - CommandListener commandListener; - ItemCommandListener itemCommandListener; - Item item; + /* + * Event parameters. + */ + int type; + int x; + int y; + int width; + int height; + int keyCode; + Runnable runnable; + Command command; + CommandListener commandListener; + ItemCommandListener itemCommandListener; + Item item; + + /* + * Handler object. The object that the LCDUIEvent will be passed to + * when the event is dispatched. Based on the event type it's known + * what type of an object it must be. The handler object will + * implement how to do the actual callback. + */ + Object handlerObject; + + /* + * The associated eSWT widget. Used to store the eSWT widget which + * the original eSWT event was for. E.g. in Form the CustomItem's + * widget may change while the event is in the queue. + */ + Widget widget; + + /* + * Used by EventQueue. + */ + LCDUIEvent next; - /* - * Handler object. The object that the LCDUIEvent will be passed to - * when the event is dispatched. Based on the event type it's known - * what type of an object it must be. The handler object will - * implement how to do the actual callback. - */ - Object handlerObject; - - /* - * The associated eSWT widget. Used to store the eSWT widget which - * the original eSWT event was for. E.g. in Form the CustomItem's - * widget may change while the event is in the queue. - */ - Widget widget; - - /* - * Used by EventQueue. - */ - LCDUIEvent next; + private LCDUIEvent() + { + } + } + + /* + * The event loop executed in a dedicated dispatcher thread. Events are + * popped from the queue and dispatched oldest first until there are no + * more events. Then the thread sleeps until new events are posted or + * termination is requested. Any exceptions thrown from the event handlers + * are let through to the runtime which should lead into termination of + * all threads in the process. + */ + private static class EventLoop implements Runnable + { + private boolean noException; + public void run() + { + try + { + Logger.info(logName + "Dispatcher thread started"); + while(true) + { + LCDUIEvent event; + do + { + synchronized(wakeLock) + { + if(terminated) + { + cleanup(); + noException = true; + return; + } + event = eventQueue.pop(); + pendingWake = false; + } - private LCDUIEvent() { - } - } - - /* - * The event loop executed in a dedicated dispatcher thread. Events are - * popped from the queue and dispatched oldest first until there are no - * more events. Then the thread sleeps until new events are posted or - * termination is requested. Any exceptions thrown from the event handlers - * are let through to the runtime which should lead into termination of - * all threads in the process. - */ - private static class EventLoop implements Runnable { - private boolean noException; - public void run() { - try { - Logger.info(logName + "Dispatcher thread started"); - while(true) { - LCDUIEvent event; - do { - synchronized(wakeLock) { - if(terminated) { - cleanup(); - noException = true; - return; - } - event = eventQueue.pop(); - pendingWake = false; - } - - if(event != null) { - synchronized(callbackLock) { - // No callbacks are sent if already terminating - if(!terminated) { - handleEvent(event); - } - } - } - } while(event != null); - - // No more events - waitForWake(); - } - } finally { - if(noException) { - Logger.info(logName + "Dispatcher thread exiting normally"); - } else { - Logger.error(logName + "Dispatcher thread exiting abnormally"); - } - if(terminatedNotification != null) { - terminatedNotification.run(); - terminatedNotification = null; - } - } - } - } + if(event != null) + { + synchronized(callbackLock) + { + // No callbacks are sent if already terminating + if(!terminated) + { + handleEvent(event); + } + } + } + } + while(event != null); - private EventDispatcher() { - wakeLock = new Object(); - callbackLock = new Object(); - eventQueue = new EventQueue(); - dispatcherThread = new Thread(new EventLoop(), this.toString()); - dispatcherThread.start(); - } + // No more events + waitForWake(); + } + } + finally + { + if(noException) + { + Logger.info(logName + "Dispatcher thread exiting normally"); + } + else + { + Logger.error(logName + "Dispatcher thread exiting abnormally"); + } + if(terminatedNotification != null) + { + terminatedNotification.run(); + terminatedNotification = null; + } + } + } + } - /* - * Cleanup that is done when closing down in a controlled way. - */ - private static void cleanup() { - eventQueue = null; - dispatcherThread = null; - } + private EventDispatcher() + { + wakeLock = new Object(); + callbackLock = new Object(); + eventQueue = new EventQueue(); + dispatcherThread = new Thread(new EventLoop(), this.toString()); + dispatcherThread.start(); + } + + /* + * Cleanup that is done when closing down in a controlled way. + */ + private static void cleanup() + { + eventQueue = null; + dispatcherThread = null; + } + + /* + * Synchronized to the EventDispatcher class to synchronize with multiple + * clients requesting the instance concurrently. + */ + static synchronized EventDispatcher instance() + { + if(singleton == null) + { + singleton = new EventDispatcher(); + } + return singleton; + } - /* - * Synchronized to the EventDispatcher class to synchronize with multiple - * clients requesting the instance concurrently. - */ - static synchronized EventDispatcher instance() { - if(singleton == null) { - singleton = new EventDispatcher(); - } - return singleton; - } - - /* - * LCDUIEvent factory. - */ - LCDUIEvent newEvent(int type, Object handlerObject) { - LCDUIEvent event = new LCDUIEvent(); - event.type = type; - event.handlerObject = handlerObject; - return event; - } + /* + * LCDUIEvent factory. + */ + LCDUIEvent newEvent(int type, Object handlerObject) + { + LCDUIEvent event = new LCDUIEvent(); + event.type = type; + event.handlerObject = handlerObject; + return event; + } + + /* + * UI thread and the application threads call to add an event to the queue. + * Synchronized to the EventDispatcher instance to synchronize with queries about + * the queue content. + */ + synchronized void postEvent(LCDUIEvent event) + { + // New events ignored after terminate() has been called. + if(terminated) + { + return; + } + eventQueue.push(event); + wake(); + } - /* - * UI thread and the application threads call to add an event to the queue. - * Synchronized to the EventDispatcher instance to synchronize with queries about - * the queue content. - */ - synchronized void postEvent(LCDUIEvent event) { - // New events ignored after terminate() has been called. - if(terminated) { - return; - } - eventQueue.push(event); - wake(); - } - - /* - * Asynchronously terminates the event dispatcher. If it's currently - * executing a callback it will finish it but not execute any callbacks - * after it. Events possibly remaining in the queue are discarded. The - * method is synchronized to the EventDispatcher instance to synchronize - * with queue content manipulation and query operations. - * - * @param runnable Called when dispatcher is out of the final callback and - * is going to die. - */ - synchronized void terminate(Runnable runnable) { - synchronized(wakeLock) { - wake(); - terminatedNotification = runnable; - terminated = true; - } - } - - /* - * Canvas.serviceRepaints support is implemented in EventDispatcher so that - * it's possible to synchronize properly with termination and other - * callbacks without exposing the event dispatcher's internal - * implementation details to other classes. This method must be called - * directly in the application thread calling Canvas.serviceRepaints(). It - * can be either the dispatcher thread or any application thread. Never - * the UI thread. - */ - void serviceRepaints(Canvas canvas) { - // Synchronizing to callbackLock guarantees that dispatcher thread is - // not in a callback and is not going to make a callback until the lock - // is freed from here. If this is the dispatcher thread then it already - // holds the lock. - synchronized(callbackLock) { - // Synchronized to the EventDispatcher instance to synchronize with - // terminate() calls. Lock is freed before the callback so that - // it's possible to complete a terminate() call during the - // callback. Event loop is going to check after acquiring the - // callbackLock if terminate() was called during this callback. - synchronized(this) { - if(terminated) { - return; - } - } - // Canvas.paint() is called back directly in the thread that called - // serviceRepaints(). Event is not really needed but is created so - // that the same APIs can be used. + /* + * Asynchronously terminates the event dispatcher. If it's currently + * executing a callback it will finish it but not execute any callbacks + * after it. Events possibly remaining in the queue are discarded. The + * method is synchronized to the EventDispatcher instance to synchronize + * with queue content manipulation and query operations. + * + * @param runnable Called when dispatcher is out of the final callback and + * is going to die. + */ + synchronized void terminate(Runnable runnable) + { + synchronized(wakeLock) + { + wake(); + terminatedNotification = runnable; + terminated = true; + } + } + + /* + * Canvas.serviceRepaints support is implemented in EventDispatcher so that + * it's possible to synchronize properly with termination and other + * callbacks without exposing the event dispatcher's internal + * implementation details to other classes. This method must be called + * directly in the application thread calling Canvas.serviceRepaints(). It + * can be either the dispatcher thread or any application thread. Never + * the UI thread. + */ + void serviceRepaints(Canvas canvas) + { + // Synchronizing to callbackLock guarantees that dispatcher thread is + // not in a callback and is not going to make a callback until the lock + // is freed from here. If this is the dispatcher thread then it already + // holds the lock. + synchronized(callbackLock) + { + // Synchronized to the EventDispatcher instance to synchronize with + // terminate() calls. Lock is freed before the callback so that + // it's possible to complete a terminate() call during the + // callback. Event loop is going to check after acquiring the + // callbackLock if terminate() was called during this callback. + synchronized(this) + { + if(terminated) + { + return; + } + } + // Canvas.paint() is called back directly in the thread that called + // serviceRepaints(). Event is not really needed but is created so + // that the same APIs can be used. LCDUIEvent event = newEvent(LCDUIEvent.CANVAS_PAINT_MIDLET_REQUEST, canvas); event.widget = canvas.getContentComp(); - canvas.doCallback(event); - } - } - - private static void wake() { - synchronized(wakeLock) { - wakeLock.notify(); - pendingWake = true; - } - } - - private static void waitForWake() { - try { - synchronized(wakeLock) { - // If there has been a call to wake() then one more iteration - // must be executed before entering wait(). - if(!pendingWake) { - wakeLock.wait(); - } - } - } catch(InterruptedException interruptedException) { - } - } - - private static void handleEvent(LCDUIEvent event) { - switch(event.type & LCDUIEvent.EVENTTYPEMASK) { - case LCDUIEvent.CANVASBIT: - handleCanvasEvent(event); - break; - case LCDUIEvent.CUSTOMITEMBIT: - handleCustomItemEvent(event); - break; - case LCDUIEvent.DISPLAYABLEBIT: - handleDisplayableEvent(event); - break; - default: - handleOtherEvent(event); - break; - } - // When returning from here all the references to the event have been - // lost and the objects referenced by the event can be gc'd. No need - // to set the fields to null. - } - - private static void handleCanvasEvent(LCDUIEvent event) { - Canvas canvas = (Canvas)event.handlerObject; - canvas.doCallback(event); - } - - private static void handleCustomItemEvent(LCDUIEvent event) { - Form form = (Form)event.handlerObject; - form.doCallback(event); - } - - private static void handleDisplayableEvent(LCDUIEvent event) { - Displayable displayable = (Displayable)event.handlerObject; - displayable.doCallback(event); - } - - private static void handleOtherEvent(LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.RUNNABLE_CALLSERIALLY: - handleCallSerially(event); - break; - case LCDUIEvent.ITEM_COMMANDACTION: - handleItemCommandListenerCommandAction(event); - break; - default: - Logger.error(logName + "Unknown event type: " + event.type); - break; - } - } - - private static void handleCallSerially(LCDUIEvent event) { - Display display = (Display)event.handlerObject; - display.doCallback(event); - } - - private static void handleItemCommandListenerCommandAction(LCDUIEvent event) { - Item item = (Item)event.handlerObject; - item.doCallback(event); - } + canvas.doCallback(event); + } + } + + private static void wake() + { + synchronized(wakeLock) + { + wakeLock.notify(); + pendingWake = true; + } + } + + private static void waitForWake() + { + try + { + synchronized(wakeLock) + { + // If there has been a call to wake() then one more iteration + // must be executed before entering wait(). + if(!pendingWake) + { + wakeLock.wait(); + } + } + } + catch(InterruptedException interruptedException) + { + } + } + + private static void handleEvent(LCDUIEvent event) + { + switch(event.type & LCDUIEvent.EVENTTYPEMASK) + { + case LCDUIEvent.CANVASBIT: + handleCanvasEvent(event); + break; + case LCDUIEvent.CUSTOMITEMBIT: + handleCustomItemEvent(event); + break; + case LCDUIEvent.DISPLAYABLEBIT: + handleDisplayableEvent(event); + break; + default: + handleOtherEvent(event); + break; + } + // When returning from here all the references to the event have been + // lost and the objects referenced by the event can be gc'd. No need + // to set the fields to null. + } + + private static void handleCanvasEvent(LCDUIEvent event) + { + Canvas canvas = (Canvas)event.handlerObject; + canvas.doCallback(event); + } + + private static void handleCustomItemEvent(LCDUIEvent event) + { + Form form = (Form)event.handlerObject; + form.doCallback(event); + } + + private static void handleDisplayableEvent(LCDUIEvent event) + { + Displayable displayable = (Displayable)event.handlerObject; + displayable.doCallback(event); + } + + private static void handleOtherEvent(LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.RUNNABLE_CALLSERIALLY: + handleCallSerially(event); + break; + case LCDUIEvent.ITEM_COMMANDACTION: + handleItemCommandListenerCommandAction(event); + break; + default: + Logger.error(logName + "Unknown event type: " + event.type); + break; + } + } + + private static void handleCallSerially(LCDUIEvent event) + { + Display display = (Display)event.handlerObject; + display.doCallback(event); + } + + private static void handleItemCommandListenerCommandAction(LCDUIEvent event) + { + Item item = (Item)event.handlerObject; + item.doCallback(event); + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/EventQueue.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/EventQueue.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/EventQueue.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -19,38 +19,48 @@ import javax.microedition.lcdui.EventDispatcher.LCDUIEvent; -final class EventQueue { - - LCDUIEvent first; - LCDUIEvent last; - - EventQueue() { - } +final class EventQueue +{ - synchronized void push(LCDUIEvent event) { - event.next = null; - if(isEmpty()) { - first = last = event; - } else { - last.next = event; - last = event; - } - } + LCDUIEvent first; + LCDUIEvent last; + + EventQueue() + { + } - synchronized LCDUIEvent pop() { - if (isEmpty()) { - return null; - } - LCDUIEvent event = first; - first = first.next; - event.next = null; - if(isEmpty()) { - last = null; - } - return event; - } + synchronized void push(LCDUIEvent event) + { + event.next = null; + if(isEmpty()) + { + first = last = event; + } + else + { + last.next = event; + last = event; + } + } - synchronized boolean isEmpty() { - return first == null; - } + synchronized LCDUIEvent pop() + { + if(isEmpty()) + { + return null; + } + LCDUIEvent event = first; + first = first.next; + event.next = null; + if(isEmpty()) + { + last = null; + } + return event; + } + + synchronized boolean isEmpty() + { + return first == null; + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Font.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Font.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Font.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -28,7 +28,8 @@ /** * Implementation of LCDUI Font class. */ -public final class Font { +public final class Font +{ /** * System font face. @@ -115,7 +116,7 @@ public static final int FONT_STATIC_TEXT = 0; private static final int STYLE_ALL = STYLE_PLAIN | STYLE_BOLD - | STYLE_ITALIC | STYLE_UNDERLINED; + | STYLE_ITALIC | STYLE_UNDERLINED; private static final String FONTDATA_CONST = "|-1|-1|-1|-1|-1|-1|1|"; @@ -141,8 +142,10 @@ /** * Disposes all fonts created. */ - static void disposeFonts() { - for (Enumeration e = fontTable.elements(); e.hasMoreElements();) { + static void disposeFonts() + { + for(Enumeration e = fontTable.elements(); e.hasMoreElements();) + { Font font = (Font) e.nextElement(); font.eswtFont.dispose(); } @@ -152,8 +155,10 @@ /** * LCDUI Font --> eSWT Font */ - static org.eclipse.swt.graphics.Font getESWTFont(Font font) { - if (font != null) { + static org.eclipse.swt.graphics.Font getESWTFont(Font font) + { + if(font != null) + { return font.eswtFont; } return null; @@ -162,8 +167,10 @@ /** * eSWT Font --> LCDUI Font */ - static Font getFont(final org.eclipse.swt.graphics.Font font) { - if (font != null) { + static Font getFont(final org.eclipse.swt.graphics.Font font) + { + if(font != null) + { FontData fd = getFontData(font); return getFont(fd); } @@ -175,7 +182,8 @@ * * @return default system font. */ - public static Font getDefaultFont() { + public static Font getDefaultFont() + { return getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM); } @@ -185,13 +193,16 @@ * @param specifier font specifier * @return the font */ - public static Font getFont(int specifier) { - if (specifier == FONT_INPUT_TEXT || specifier == FONT_STATIC_TEXT) { + public static Font getFont(int specifier) + { + if(specifier == FONT_INPUT_TEXT || specifier == FONT_STATIC_TEXT) + { return getFont(getFontData(specifier)); } - else { + else + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_SPECIFIER); + MsgRepository.FONT_EXCEPTION_INVALID_SPECIFIER); } } @@ -203,25 +214,30 @@ * @param size font size * @return the font */ - public static Font getFont(int face, int style, int size) { - if (face != FACE_SYSTEM && face != FACE_MONOSPACE - && face != FACE_PROPORTIONAL) { + public static Font getFont(int face, int style, int size) + { + if(face != FACE_SYSTEM && face != FACE_MONOSPACE + && face != FACE_PROPORTIONAL) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_FACE); + MsgRepository.FONT_EXCEPTION_INVALID_FACE); } - if (style < STYLE_PLAIN || style > STYLE_ALL) { + if(style < STYLE_PLAIN || style > STYLE_ALL) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_STYLE); + MsgRepository.FONT_EXCEPTION_INVALID_STYLE); } - if (size != SIZE_SMALL && size != SIZE_MEDIUM && size != SIZE_LARGE) { + if(size != SIZE_SMALL && size != SIZE_MEDIUM && size != SIZE_LARGE) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_SIZE); + MsgRepository.FONT_EXCEPTION_INVALID_SIZE); } FontData fd = getFontData(face, style, size); Font font = getFont(fd); // We must handle underlining separately because it is not part of // eSWT's style. - if ((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) { + if((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) + { font.style |= Font.STYLE_UNDERLINED; } return font; @@ -235,25 +251,30 @@ * @param height font height * @return the font */ - static Font getFreeSizedFont(int face, int style, int height) { - if (face != FACE_SYSTEM && face != FACE_MONOSPACE - && face != FACE_PROPORTIONAL) { + static Font getFreeSizedFont(int face, int style, int height) + { + if(face != FACE_SYSTEM && face != FACE_MONOSPACE + && face != FACE_PROPORTIONAL) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_FACE); + MsgRepository.FONT_EXCEPTION_INVALID_FACE); } - if (style < STYLE_PLAIN || style > STYLE_ALL) { + if(style < STYLE_PLAIN || style > STYLE_ALL) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_STYLE); + MsgRepository.FONT_EXCEPTION_INVALID_STYLE); } - if (height < 0) { + if(height < 0) + { throw new IllegalArgumentException( - MsgRepository.FONT_EXCEPTION_INVALID_SIZE); + MsgRepository.FONT_EXCEPTION_INVALID_SIZE); } FontData fd = getFontData(face, style, height); Font font = getFont(fd); // We must handle underlining separately because it is not part of // eSWT's style. - if ((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) { + if((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) + { font.style |= Font.STYLE_UNDERLINED; } return font; @@ -265,13 +286,17 @@ * @param fontdata font's data * @return a font */ - private static Font getFont(FontData fontdata) { + private static Font getFont(FontData fontdata) + { Font ret = null; - if (fontdata != null) { - if (fontTable.containsKey(fontdata)) { + if(fontdata != null) + { + if(fontTable.containsKey(fontdata)) + { ret = (Font) fontTable.get(fontdata); } - else { + else + { ret = new Font(fontdata); } } @@ -283,9 +308,12 @@ * * @param reqFD the requested eSWT FontData */ - private Font(final FontData reqFD) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private Font(final FontData reqFD) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtFont = new org.eclipse.swt.graphics.Font(ESWTUIThreadRunner .getInstance().getDisplay(), reqFD); } @@ -304,7 +332,8 @@ * * @return style */ - public int getStyle() { + public int getStyle() + { return style; } @@ -313,7 +342,8 @@ * * @return size */ - public int getSize() { + public int getSize() + { return size; } @@ -322,7 +352,8 @@ * * @return face */ - public int getFace() { + public int getFace() + { return face; } @@ -331,7 +362,8 @@ * * @return true if the font is plain, false otherwise */ - public boolean isPlain() { + public boolean isPlain() + { return (style == Font.STYLE_PLAIN); } @@ -340,7 +372,8 @@ * * @return true if the font is bold, false otherwise */ - public boolean isBold() { + public boolean isBold() + { return ((style & Font.STYLE_BOLD) == Font.STYLE_BOLD); } @@ -349,7 +382,8 @@ * * @return true if the font is italic, false otherwise */ - public boolean isItalic() { + public boolean isItalic() + { return ((style & Font.STYLE_ITALIC) == Font.STYLE_ITALIC); } @@ -358,7 +392,8 @@ * * @return true if the font is underlined, false otherwise. */ - public boolean isUnderlined() { + public boolean isUnderlined() + { return ((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED); } @@ -367,10 +402,14 @@ * * @return height */ - public int getHeight() { - if (eswtTempFontHeight == 0) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + public int getHeight() + { + if(eswtTempFontHeight == 0) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { FontUtils fu = eswtGetFontUtils(eswtFont); eswtTempFontHeight = fu.getAscent() + fu.getDescent(); } @@ -384,10 +423,14 @@ * * @return the baseline position */ - public int getBaselinePosition() { - if (eswtTempFontAscent == 0) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + public int getBaselinePosition() + { + if(eswtTempFontAscent == 0) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtTempFontAscent = eswtGetFontUtils(eswtFont).getAscent(); } }); @@ -401,7 +444,8 @@ * @param c the character * @return the width */ - public int charWidth(char c) { + public int charWidth(char c) + { return stringWidth(String.valueOf(c)); } @@ -413,7 +457,8 @@ * @param length the length * @return the width */ - public int charsWidth(char[] c, int offset, int length) { + public int charsWidth(char[] c, int offset, int length) + { return stringWidth(new String(c, offset, length)); } @@ -423,15 +468,19 @@ * @param string the string * @return the width */ - public int stringWidth(String string) { - if (string == null) { + public int stringWidth(String string) + { + if(string == null) + { throw new NullPointerException( - MsgRepository.FONT_EXCEPTION_NULL_STRING); + MsgRepository.FONT_EXCEPTION_NULL_STRING); } final String finalString = string; eswtTempFontWidth = 0; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtGetFontUtils(eswtFont).getBoundingRect(tempFontRect, finalString); eswtTempFontWidth = tempFontRect[2]; } @@ -442,11 +491,14 @@ /** * Get the static FontUtils instance setup with given font. */ - private static FontUtils eswtGetFontUtils(org.eclipse.swt.graphics.Font font) { - if (fontUtils == null) { + private static FontUtils eswtGetFontUtils(org.eclipse.swt.graphics.Font font) + { + if(fontUtils == null) + { fontUtils = new FontUtils(font.handle); } - else { + else + { fontUtils.setFont(font.handle); } return fontUtils; @@ -460,7 +512,8 @@ * @param length the length * @return the width of the specified region */ - public int substringWidth(String string, int offset, int length) { + public int substringWidth(String string, int offset, int length) + { return stringWidth(string.substring(offset, offset + length)); } @@ -470,16 +523,21 @@ * @param control eSWT control * @return FontData */ - private static FontData getFontData(final int specifier) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private static FontData getFontData(final int specifier) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Control control = null; MobileShell shell = new MobileShell(ESWTUIThreadRunner - .getInstance().getDisplay(), SWT.NONE); - if (specifier == FONT_INPUT_TEXT) { + .getInstance().getDisplay(), SWT.NONE); + if(specifier == FONT_INPUT_TEXT) + { control = new Text(shell, SWT.NONE); } - else { + else + { control = new Label(shell, SWT.NONE); } eswtTempFontData = control.getFont().getFontData()[0]; @@ -497,9 +555,12 @@ * @return FontData */ private static FontData getFontData( - final org.eclipse.swt.graphics.Font font) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + final org.eclipse.swt.graphics.Font font) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtTempFontData = font.getFontData()[0]; } }); @@ -512,11 +573,15 @@ * @return FontData */ private static FontData getFontData(final int face, final int style, - final int size) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + final int size) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { int underlined = 0; - if ((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) { + if((style & Font.STYLE_UNDERLINED) == Font.STYLE_UNDERLINED) + { underlined = 1; } /* FontData constructor format: @@ -544,12 +609,16 @@ * * @return system FontData */ - private static FontData getSystemFontData() { - if (eswtSystemFontData == null) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private static FontData getSystemFontData() + { + if(eswtSystemFontData == null) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSystemFontData = ESWTUIThreadRunner.getInstance() - .getDisplay().getSystemFont().getFontData()[0]; + .getDisplay().getSystemFont().getFontData()[0]; } }); } @@ -562,14 +631,16 @@ * @param face font's face type * @return font name */ - private static String mapFaceToFontName(int face) { + private static String mapFaceToFontName(int face) + { // TODO: how to map face values to names - switch (face) { - case Font.FACE_MONOSPACE: - case Font.FACE_PROPORTIONAL: - case Font.FACE_SYSTEM: - default: - return getSystemFontData().getName(); + switch(face) + { + case Font.FACE_MONOSPACE: + case Font.FACE_PROPORTIONAL: + case Font.FACE_SYSTEM: + default: + return getSystemFontData().getName(); } } @@ -579,12 +650,15 @@ * @param eswtFontName font's name * @return font face */ - private static int mapFontNameToFace(String eswtFontName) { + private static int mapFontNameToFace(String eswtFontName) + { // TODO: how to map names to face values - if (eswtFontName.equals(getSystemFontData().getName())) { + if(eswtFontName.equals(getSystemFontData().getName())) + { return Font.FACE_SYSTEM; } - else { + else + { // Font.FACE_MONOSPACE: // Font.FACE_PROPORTIONAL: return 0; @@ -598,19 +672,23 @@ * @param size font's size * @return font height */ - private static int mapSizeToHeight(int size) { + private static int mapSizeToHeight(int size) + { //retreive the system default height int defHeight = getSystemFontData().getHeight(); - - if (size == Font.SIZE_SMALL) { + + if(size == Font.SIZE_SMALL) + { //calculate the small size height as a ratio of system default medium size and round off the value to an integer - return (int)Math.floor( (defHeight * ( 3f/4 )) + 0.5f ); + return (int)Math.floor((defHeight * (3f/4)) + 0.5f); } - else if (size == Font.SIZE_LARGE) { + else if(size == Font.SIZE_LARGE) + { //calculate the large height as a ratio of system default medium size and round off the value to an integer - return (int)Math.floor( (defHeight * ( 4.5f/4 )) + 0.5f ); + return (int)Math.floor((defHeight * (4.5f/4)) + 0.5f); } - else { + else + { //return the system default height for medium size which is generally 12 but 7 in symbian for qt return defHeight; } @@ -622,15 +700,19 @@ * @param height font's height * @return font size */ - private static int mapHeightToSize(int height) { + private static int mapHeightToSize(int height) + { int defHeight = getSystemFontData().getHeight(); - if (height < defHeight) { + if(height < defHeight) + { return Font.SIZE_SMALL; } - else if (height > defHeight) { + else if(height > defHeight) + { return Font.SIZE_LARGE; } - else { + else + { return Font.SIZE_MEDIUM; } } @@ -641,12 +723,15 @@ * @param style Font's LCDUI style. * @return Font's eSWT style. */ - private static int mapStyleToESWTStyle(int style) { + private static int mapStyleToESWTStyle(int style) + { int retStyle = SWT.NORMAL; - if ((style & Font.STYLE_BOLD) == Font.STYLE_BOLD) { + if((style & Font.STYLE_BOLD) == Font.STYLE_BOLD) + { retStyle |= SWT.BOLD; } - if ((style & Font.STYLE_ITALIC) == Font.STYLE_ITALIC) { + if((style & Font.STYLE_ITALIC) == Font.STYLE_ITALIC) + { retStyle |= SWT.ITALIC; } return retStyle; @@ -658,12 +743,15 @@ * @param eswtStyle Font's eSWT style. * @return Font's LCDUI style. */ - private static int mapESWTStyleToStyle(int eswtStyle) { + private static int mapESWTStyleToStyle(int eswtStyle) + { int retStyle = Font.STYLE_PLAIN; - if ((eswtStyle & SWT.BOLD) != 0) { + if((eswtStyle & SWT.BOLD) != 0) + { retStyle |= Font.STYLE_BOLD; } - if ((eswtStyle & SWT.ITALIC) != 0) { + if((eswtStyle & SWT.ITALIC) != 0) + { retStyle |= Font.STYLE_ITALIC; } return retStyle; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Form.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Form.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Form.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -28,7 +28,8 @@ /** * This class represents LCDUI Form. */ -public class Form extends Screen { +public class Form extends Screen +{ /** * Abstract layouting policy. @@ -64,7 +65,8 @@ * * @param title the title string */ - public Form(String title) { + public Form(String title) + { super(title); construct(); layoutPolicy = new DefaultFormInteraction(this); @@ -76,10 +78,13 @@ * @param title the title string * @param formItems array of items on the formComposite */ - public Form(String title, Item[] formItems) { + public Form(String title, Item[] formItems) + { this(title); - if (formItems != null) { - for (int i = 0; i < formItems.length; i++) { + if(formItems != null) + { + for(int i = 0; i < formItems.length; i++) + { this.append(formItems[i]); } } @@ -88,10 +93,12 @@ /* (non-Javadoc) * @see javax.microedition.lcdui.Displayable#eswtConstructContent(int) */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { Composite comp = super.eswtConstructContent(SWT.VERTICAL); ScrollBar vBar = comp.getVerticalBar(); - if (vBar != null) { + if(vBar != null) + { vBar.setVisible(true); vBar.setEnabled(true); } @@ -102,10 +109,12 @@ /* (non-Javadoc) * @see Displayable#eswtHandleShowCurrentEvent() */ - void eswtHandleShowCurrentEvent() { + void eswtHandleShowCurrentEvent() + { super.eswtHandleShowCurrentEvent(); ScrollBar vBar = getContentComp().getVerticalBar(); - if (vBar != null) { + if(vBar != null) + { vBar.addSelectionListener(fsbl); } layoutPolicy.handleShowCurrentEvent(); @@ -114,11 +123,13 @@ /* (non-Javadoc) * @see Displayable#eswtHandleHideCurrentEvent() */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { super.eswtHandleHideCurrentEvent(); ScrollBar vBar = getContentComp().getVerticalBar(); - if (vBar != null) { + if(vBar != null) + { vBar.removeSelectionListener(fsbl); } layoutPolicy.handleHideCurrentEvent(); @@ -127,9 +138,11 @@ /* (non-Javadoc) * @see Displayable#eswtHandleResizeEvent(int, int) */ - void eswtHandleResizeEvent(int width, int height) { + void eswtHandleResizeEvent(int width, int height) + { super.eswtHandleResizeEvent(width, height); - if (formComposite != null) { + if(formComposite != null) + { formComposite.setRedraw(false); formComposite.setOrigin(0, 0, true); formComposite.setSize(width, height); @@ -144,12 +157,15 @@ * * @param e eSWT event */ - void eswtHandleEvent(Event e) { + void eswtHandleEvent(Event e) + { super.eswtHandleEvent(e); - if (e.type == SWT.Traverse) { + if(e.type == SWT.Traverse) + { e.doit = false; } - else { + else + { layoutPolicy.handleKeyEvent(e.keyCode, e.type); } } @@ -160,17 +176,21 @@ * @param item Item to append to a Form. * @return index of Item in Form */ - public int append(Item item) { - if (item == null) { + public int append(Item item) + { + if(item == null) + { throw new NullPointerException( - MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); + MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); } - if (item.getParent() != null) { + if(item.getParent() != null) + { throw new IllegalStateException( - MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); + MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); } int returnValue = -1; - synchronized (layoutPolicy) { + synchronized(layoutPolicy) + { item.setParent(this); items.addElement(item); returnValue = items.indexOf(item); @@ -185,10 +205,12 @@ * @param text - text for StringItem. * @return index of StringITem in a Form. */ - public int append(String text) { - if (text == null) { + public int append(String text) + { + if(text == null) + { throw new NullPointerException( - MsgRepository.FORM_EXCEPTION_STRING_NULL_POINTER); + MsgRepository.FORM_EXCEPTION_STRING_NULL_POINTER); } return append(new StringItem(null, text, Item.LAYOUT_DEFAULT)); } @@ -199,10 +221,12 @@ * @param img - Image for ImageItem. * @return index of ImageItem in a Form. */ - public int append(Image img) { - if (img == null) { + public int append(Image img) + { + if(img == null) + { throw new NullPointerException( - MsgRepository.FORM_EXCEPTION_IMAGE_NULL_POINTER); + MsgRepository.FORM_EXCEPTION_IMAGE_NULL_POINTER); } return append(new ImageItem(null, img, Item.LAYOUT_DEFAULT, null)); } @@ -214,20 +238,25 @@ * @param item item insert. * @throws IndexOutOfBoundsException if position is incorrect. */ - public void insert(int position, Item item) { - if (item == null) { + public void insert(int position, Item item) + { + if(item == null) + { throw new NullPointerException( - MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); + MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); } - if (item.getParent() != null) { + if(item.getParent() != null) + { throw new IllegalStateException( - MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); + MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); } - if ((position < 0) || (position > (items.size() - 1))) { + if((position < 0) || (position > (items.size() - 1))) + { throw new IndexOutOfBoundsException( - MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); + MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); } - synchronized (layoutPolicy) { + synchronized(layoutPolicy) + { item.setParent(this); items.insertElementAt(item, position); resetLayoutTimer(items.indexOf(item)); @@ -240,12 +269,15 @@ * @param position - index of Item to delete from Form. * @throws IndexOutOfBoundsException if position is incorrect. */ - public void delete(int position) { - if ((position < 0) || (position > (items.size() - 1))) { + public void delete(int position) + { + if((position < 0) || (position > (items.size() - 1))) + { throw new IndexOutOfBoundsException( - MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); + MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); } - synchronized (layoutPolicy) { + synchronized(layoutPolicy) + { ((Item) items.elementAt(position)).setParent(null); items.removeElementAt(position); resetLayoutTimer(position - 1); @@ -255,9 +287,12 @@ /** * Delete all items from the formComposite. */ - public void deleteAll() { - synchronized (layoutPolicy) { - for (int i = 0; i < items.size(); i++) { + public void deleteAll() + { + synchronized(layoutPolicy) + { + for(int i = 0; i < items.size(); i++) + { ((Item) items.elementAt(i)).setParent(null); } items.removeAllElements(); @@ -272,20 +307,25 @@ * @param newItem new item to set. * @throws IndexOutOfBoundsException if position is incorrect. */ - public void set(int position, Item newItem) { - if (newItem == null) { + public void set(int position, Item newItem) + { + if(newItem == null) + { throw new NullPointerException( - MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); + MsgRepository.FORM_EXCEPTION_ITEM_NULL_POINTER); } - if (newItem.getParent() != null) { + if(newItem.getParent() != null) + { throw new IllegalStateException( - MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); + MsgRepository.FORM_EXCEPTION_ITEM_OWNED_BY_CONTAINER); } - if ((position < 0) || (position > (items.size() - 1))) { + if((position < 0) || (position > (items.size() - 1))) + { throw new IndexOutOfBoundsException( - MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); + MsgRepository.FORM_EXCEPTION_INVALID_ITEM_INDEX); } - synchronized (layoutPolicy) { + synchronized(layoutPolicy) + { newItem.setParent(this); // clear reference to a form for "old" item. get(position).setParent(null); @@ -301,13 +341,17 @@ * @return Item - specified by position * @throws IndexOutOfBoundsException if position is incorrect. */ - public Item get(int position) { + public Item get(int position) + { Item returnItem = null; - synchronized (layoutPolicy) { - try { + synchronized(layoutPolicy) + { + try + { returnItem = (Item) items.elementAt(position); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { throw new IndexOutOfBoundsException(e.getMessage()); } } @@ -319,7 +363,8 @@ * * @return number of Items in Form. */ - public int size() { + public int size() + { return items.size(); } @@ -328,7 +373,8 @@ * * @param itemStateListener New ItemStateListener. */ - public void setItemStateListener(ItemStateListener itemStateListener) { + public void setItemStateListener(ItemStateListener itemStateListener) + { this.itemStateListener = itemStateListener; } @@ -338,7 +384,8 @@ * * @param item The Item which should be set visible. */ - void setCurrentItem(Item item) { + void setCurrentItem(Item item) + { layoutPolicy.setCurrentItem(item); } @@ -347,15 +394,20 @@ * * @param item which triggered this event. */ - void notifyItemStateChanged(final Item item) { - if (item != null && item.getParent() == this) { - if (itemStateListener != null) { + void notifyItemStateChanged(final Item item) + { + if(item != null && item.getParent() == this) + { + if(itemStateListener != null) + { ESWTUIThreadRunner.getInstance().getDisplay().asyncExec( - new Runnable() { - public void run() { - itemStateListener.itemStateChanged(item); - } - }); + new Runnable() + { + public void run() + { + itemStateListener.itemStateChanged(item); + } + }); } } } @@ -367,18 +419,25 @@ * @param updateReason * @param param additional parameter */ - void updateItemState(Item item, int updateReason, Object param) { - if (item != null && item.getParent() == this) { - if ((updateReason & Item.UPDATE_WIDTH_CHANGED) != 0) { - synchronized (layoutPolicy) { + void updateItemState(Item item, int updateReason, Object param) + { + if(item != null && item.getParent() == this) + { + if((updateReason & Item.UPDATE_WIDTH_CHANGED) != 0) + { + synchronized(layoutPolicy) + { resetLayoutTimer(items.indexOf(item)); } } - else { - if (layoutPolicy instanceof DefaultFormInteraction) { - if (layoutTimer != null) { + else + { + if(layoutPolicy instanceof DefaultFormInteraction) + { + if(layoutTimer != null) + { ((DefaultFormInteraction) layoutPolicy) - .updateItemState(item, updateReason, param); + .updateItemState(item, updateReason, param); } } } @@ -390,14 +449,16 @@ * * @return Vector of items */ - Vector getItems() { + Vector getItems() + { return items; } /** * @return ScrolledComposite which represents Form */ - ScrolledComposite getFormComposite() { + ScrolledComposite getFormComposite() + { return formComposite; } @@ -407,7 +468,8 @@ * @return Reference to layout policy. * */ - FormLayoutPolicy getLayoutPolicy() { + FormLayoutPolicy getLayoutPolicy() + { return layoutPolicy; } @@ -416,7 +478,8 @@ private boolean layoutLR = true; - public Form(boolean leftRightLanguage, String title) { + public Form(boolean leftRightLanguage, String title) + { super(title); construct(); layoutLR = leftRightLanguage; @@ -428,16 +491,20 @@ /** * Returns if the language Left-to-Right. */ - boolean getLeftRightLanguage() { + boolean getLeftRightLanguage() + { return layoutLR; } /** * Reset timer for do layout with a given start index. */ - private void resetLayoutTimer(int newStartIndex) { - if (layoutTimer != null) { - if (formTimerTask != null) { + private void resetLayoutTimer(int newStartIndex) + { + if(layoutTimer != null) + { + if(formTimerTask != null) + { formTimerTask.cancel(); formTimerTask = null; } @@ -452,15 +519,18 @@ /** * Form Timer task. Triggers the formComposite to Layout. */ - class FormTimerTask extends TimerTask { + class FormTimerTask extends TimerTask + { private int index; - FormTimerTask(int newIndex) { + FormTimerTask(int newIndex) + { index = newIndex; } - public void run() { + public void run() + { Logger.method(Form.this, "layout"); layoutPolicy.layoutForm(index); startIndex = items.size(); @@ -488,12 +558,15 @@ /** * Scrollbar selection listener. */ - class FormScrollBarListener implements SelectionListener { + class FormScrollBarListener implements SelectionListener + { - public void widgetDefaultSelected(SelectionEvent se) { + public void widgetDefaultSelected(SelectionEvent se) + { } - public void widgetSelected(SelectionEvent se) { + public void widgetSelected(SelectionEvent se) + { ScrollBar sb = (ScrollBar) se.widget; layoutPolicy.updateScrolling(sb.getSelection(), false); } @@ -502,7 +575,8 @@ /** * Dispose Form. */ - void dispose() { + void dispose() + { super.dispose(); layoutTimer.cancel(); layoutTimer = null; @@ -512,27 +586,34 @@ } /* - * Dispatcher thread calls. + * Dispatcher thread calls. */ - void doCallback(LCDUIEvent event) { - if((event.type & LCDUIEvent.CUSTOMITEMBIT) != 0) { - // Synchronize with Form content modification operations. - synchronized(layoutPolicy) { - // If the eSWT widget has been explicitly disposed while the event - // was in the queue then ignore the event. - if(event.widget != null && event.widget.isDisposed()) { - return; - } - // Find out if the Item is still in this Form. If not then - // ignore the event. - if(!items.contains(event.item)) { - return; - } - // Perform the callback. Then allow Form modification again. - event.item.doCallback(event); - } - } else { - super.doCallback(event); - } + void doCallback(LCDUIEvent event) + { + if((event.type & LCDUIEvent.CUSTOMITEMBIT) != 0) + { + // Synchronize with Form content modification operations. + synchronized(layoutPolicy) + { + // If the eSWT widget has been explicitly disposed while the event + // was in the queue then ignore the event. + if(event.widget != null && event.widget.isDisposed()) + { + return; + } + // Find out if the Item is still in this Form. If not then + // ignore the event. + if(!items.contains(event.item)) + { + return; + } + // Perform the callback. Then allow Form modification again. + event.item.doCallback(event); + } + } + else + { + super.doCallback(event); + } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/FormLayoutPolicy.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/FormLayoutPolicy.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/FormLayoutPolicy.java Fri May 14 15:47:24 2010 +0300 @@ -11,12 +11,13 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; -abstract class FormLayoutPolicy { +abstract class FormLayoutPolicy +{ /** * Layouts the Form. @@ -84,5 +85,5 @@ * @param item Item to be layouted. * @return ItemLayouter or null if no Layouter found. */ - abstract ItemLayouter getLayouter(Item item); + abstract ItemLayouter getLayouter(Item item); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Gauge.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Gauge.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Gauge.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,7 +21,8 @@ /** * Class representing the Gauge item. */ -public class Gauge extends Item { +public class Gauge extends Item +{ /** * Indefinite constant. @@ -60,7 +61,8 @@ * @param maxVal the maximum value. * @param initVal the initial value. */ - public Gauge(String name, boolean interactive, int maxVal, int initVal) { + public Gauge(String name, boolean interactive, int maxVal, int initVal) + { setLabel(name); this.interactive = interactive; setMaxValue(maxVal); @@ -74,21 +76,25 @@ * @param maxVal the maximum value. * @return validated value. */ - private static int checkValue(int value, int maxVal) { - if (maxVal == INDEFINITE) { - switch (value) { - case CONTINUOUS_IDLE: - case INCREMENTAL_IDLE: - case CONTINUOUS_RUNNING: - case INCREMENTAL_UPDATING: - break; - default: - throw new IllegalArgumentException( - MsgRepository.GAUGE_EXCEPTION_INVALID_VALUE); + private static int checkValue(int value, int maxVal) + { + if(maxVal == INDEFINITE) + { + switch(value) + { + case CONTINUOUS_IDLE: + case INCREMENTAL_IDLE: + case CONTINUOUS_RUNNING: + case INCREMENTAL_UPDATING: + break; + default: + throw new IllegalArgumentException( + MsgRepository.GAUGE_EXCEPTION_INVALID_VALUE); } return value; } - else { + else + { // make sure the value is in [0, maxValue] range value = (value < 0 ? 0 : value); value = (value > maxVal ? maxVal : value); @@ -103,15 +109,19 @@ * @param interactive is interactive. * @return validated maximum value. */ - private static int checkMaxValue(int maxVal, boolean interactive) { - if (!interactive) { - if (maxVal == INDEFINITE) { + private static int checkMaxValue(int maxVal, boolean interactive) + { + if(!interactive) + { + if(maxVal == INDEFINITE) + { return maxVal; } } - if (maxVal <= 0) { + if(maxVal <= 0) + { throw new IllegalArgumentException( - MsgRepository.GAUGE_EXCEPTION_INVALID_MAXVALUE); + MsgRepository.GAUGE_EXCEPTION_INVALID_MAXVALUE); } return maxVal; } @@ -121,7 +131,8 @@ * * @param value New value. Must be between zero and maxvalue inclusive. */ - public void setValue(int value) { + public void setValue(int value) + { // TODO: eSWT support required /* * if Gauge state is incremental-updating and it is non-interactive and @@ -137,7 +148,8 @@ * * @return the value. */ - public int getValue() { + public int getValue() + { return value; } @@ -146,7 +158,8 @@ * * @param maxValue the maximum value. */ - public void setMaxValue(int maxValue) { + public void setMaxValue(int maxValue) + { this.maxValue = checkMaxValue(maxValue, interactive); this.value = checkValue(getValue(), this.maxValue); updateParent(UPDATE_CONTENT); @@ -157,7 +170,8 @@ * * @return the maximum value. */ - public int getMaxValue() { + public int getMaxValue() + { return maxValue; } @@ -166,7 +180,8 @@ * * @return true if the Gauge is interactive. */ - public boolean isInteractive() { + public boolean isInteractive() + { return interactive; } @@ -175,11 +190,14 @@ * * @see javax.microedition.lcdui.Item#updateParent(int) */ - void updateParent(int updateReason) { - if (isContainedInAlert()) { + void updateParent(int updateReason) + { + if(isContainedInAlert()) + { ((Alert) getParent()).updateIndicator(); } - else { + else + { super.updateParent(updateReason); } } @@ -189,7 +207,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return GaugeLayouter.calculateMinimumBounds(this); } @@ -198,14 +217,16 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return GaugeLayouter.calculatePreferredBounds(this); } /** * Called by widget listeners to update Item value. */ - void internalSetValue(int newValue) { + void internalSetValue(int newValue) + { this.value = checkValue(newValue, this.maxValue); // notify item state listener notifyStateChanged(); @@ -216,21 +237,24 @@ * * @return layout directive */ - int internalGetLayout() { + int internalGetLayout() + { return super.internalGetLayout() | Item.LAYOUT_NEWLINE_BEFORE; } /** * @return if the Gauge is indefinite. */ - boolean isIndefinite() { + boolean isIndefinite() + { return (maxValue == INDEFINITE); } /** * Returns if this indicator meets the restrictions for its use in an Alert. */ - boolean isSuitableForAlert() { + boolean isSuitableForAlert() + { return (!isInteractive() && getParent() == null && !hasLabel() @@ -243,7 +267,8 @@ /* (non-Javadoc) * @see javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return (isInteractive() || (getNumCommands() > 0)); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/GaugeLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/GaugeLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/GaugeLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -27,7 +27,8 @@ /** * Class for layouting gauges. */ -class GaugeLayouter extends ItemLayouter { +class GaugeLayouter extends ItemLayouter +{ /** * Key name for selection listener. @@ -39,42 +40,46 @@ * * @param dflp DefaultFormLayoutPolicy */ - GaugeLayouter(DefaultFormLayoutPolicy dflp) { + GaugeLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } /** * Creates the eSWT ProgressBar/Slider for this item. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { return eswtCreateControl(parent, item); } /** * Construts a gauge control surrounded with composite. */ - static Control eswtCreateControl(Composite parent, Item item) { + static Control eswtCreateControl(Composite parent, Item item) + { Gauge gauge = (Gauge) item; // create an owning composite every time Composite comp = new Composite(parent, SWT.NONE); - if (gauge.isInteractive()) { - FormLayout layout = new FormLayout(); + if(gauge.isInteractive()) + { + FormLayout layout = new FormLayout(); layout.marginBottom = Style.pixelMetric(Style.QSTYLE_PM_LAYOUTBOTTOMMARGIN); layout.marginTop = Style.pixelMetric(Style.QSTYLE_PM_LAYOUTTOPMARGIN); layout.marginLeft = Style.pixelMetric(Style.QSTYLE_PM_LAYOUTLEFTMARGIN); layout.marginRight = Style.pixelMetric(Style.QSTYLE_PM_LAYOUTRIGHTMARGIN); layout.spacing = Style.pixelMetric(Style.QSTYLE_PM_LAYOUTVERTICALSPACING); - comp.setLayout(layout); + comp.setLayout(layout); - // Current Value - Mutable Value + // Current Value - Mutable Value Label currentlabel = new Label(comp, SWT.WRAP); - currentlabel.setText(Integer.toString( gauge.getValue())); + currentlabel.setText(Integer.toString(gauge.getValue())); currentlabel.setAlignment(SWT.LEAD); - FormData currLabelData = new FormData(); + FormData currLabelData = new FormData(); currLabelData.left = new FormAttachment(0); - currentlabel.setLayoutData(currLabelData); + currentlabel.setLayoutData(currLabelData); Slider slider = new Slider(comp, SWT.HORIZONTAL); slider.setMinimum(0); @@ -83,67 +88,71 @@ slider.setIncrement(1); slider.setPageIncrement(1); - FormData SliderLayoutData = new FormData(); + FormData SliderLayoutData = new FormData(); SliderLayoutData.right = new FormAttachment(100); SliderLayoutData.left = new FormAttachment(currentlabel); - slider.setLayoutData(SliderLayoutData); + slider.setLayoutData(SliderLayoutData); // Min Value Label minlabel = new Label(comp, SWT.WRAP); minlabel.setText("0"); minlabel.setAlignment(SWT.LEAD); - FormData minLabelData = new FormData(); + FormData minLabelData = new FormData(); minLabelData.left = new FormAttachment(slider, 0, SWT.LEFT); minLabelData.top = new FormAttachment(slider); - minlabel.setLayoutData(minLabelData); + minlabel.setLayoutData(minLabelData); // Max Value - Label maxlabel = new Label(comp, SWT.WRAP); - maxlabel.setText(Integer.toString(gauge.getMaxValue()) ); + Label maxlabel = new Label(comp, SWT.WRAP); + maxlabel.setText(Integer.toString(gauge.getMaxValue())); maxlabel.setAlignment(SWT.LEAD); - FormData maxLabelData = new FormData(); + FormData maxLabelData = new FormData(); maxLabelData.right = new FormAttachment(slider, 0, SWT.RIGHT); maxLabelData.top = new FormAttachment(slider); - maxlabel.setLayoutData(maxLabelData); + maxlabel.setLayoutData(maxLabelData); } - else { + else + { ProgressBar progressBar = null; - if (gauge.isIndefinite()) { - switch (gauge.getValue()) { - case Gauge.CONTINUOUS_IDLE: - // TODO: eSWT support required - // Gauge like busy-state indicator with no activity: - progressBar = new ProgressBar(comp, - SWT.HORIZONTAL | SWT.INDETERMINATE); - break; - case Gauge.CONTINUOUS_RUNNING: - // Gauge like busy-state indicator: - progressBar = new ProgressBar(comp, - SWT.HORIZONTAL | SWT.INDETERMINATE); - break; - case Gauge.INCREMENTAL_IDLE: - // TODO: eSWT support required - // Gauge like INCREMENTAL_UPDATING, but no activity. - progressBar = new ProgressBar(comp, - SWT.HORIZONTAL | SWT.INDETERMINATE); - break; - case Gauge.INCREMENTAL_UPDATING: - // TODO: eSWT support required - // Gauge which is updated on calling Gauge.setValue(). - progressBar = new ProgressBar(comp, - SWT.HORIZONTAL | SWT.INDETERMINATE); - break; - default: - // This is error and will cause NullPointerException - // later in this method. Gauge-class takes care that - // this is never executed. - Logger.warning("Unexpected gauge value: " + gauge.getValue()); - break; + if(gauge.isIndefinite()) + { + switch(gauge.getValue()) + { + case Gauge.CONTINUOUS_IDLE: + // TODO: eSWT support required + // Gauge like busy-state indicator with no activity: + progressBar = new ProgressBar(comp, + SWT.HORIZONTAL | SWT.INDETERMINATE); + break; + case Gauge.CONTINUOUS_RUNNING: + // Gauge like busy-state indicator: + progressBar = new ProgressBar(comp, + SWT.HORIZONTAL | SWT.INDETERMINATE); + break; + case Gauge.INCREMENTAL_IDLE: + // TODO: eSWT support required + // Gauge like INCREMENTAL_UPDATING, but no activity. + progressBar = new ProgressBar(comp, + SWT.HORIZONTAL | SWT.INDETERMINATE); + break; + case Gauge.INCREMENTAL_UPDATING: + // TODO: eSWT support required + // Gauge which is updated on calling Gauge.setValue(). + progressBar = new ProgressBar(comp, + SWT.HORIZONTAL | SWT.INDETERMINATE); + break; + default: + // This is error and will cause NullPointerException + // later in this method. Gauge-class takes care that + // this is never executed. + Logger.warning("Unexpected gauge value: " + gauge.getValue()); + break; } } - else { + else + { progressBar = new ProgressBar(comp, SWT.HORIZONTAL); progressBar.setMaximum(gauge.getMaxValue() + 1); progressBar.setSelection(gauge.getValue()); @@ -156,21 +165,24 @@ /** * Set the size of the layouted Control. */ - void eswtResizeControl(Item item, Control control, int width, int height) { + void eswtResizeControl(Item item, Control control, int width, int height) + { super.eswtResizeControl(item, control, width, height); control.getParent().setSize(width, height); // This will move gauge to the center of the screen: control.setLocation((width - control.getBounds().width) / 2, - control.getLocation().y); + control.getLocation().y); } /** * Add listeners to Layouter specific control. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); Gauge gauge = (Gauge) item; - if (gauge.isInteractive()) { + if(gauge.isInteractive()) + { Slider slider = (Slider) control; SelectionListener listener = new GaugeSelectionListener(gauge); slider.addSelectionListener(listener); @@ -181,14 +193,17 @@ /** * Remove listeners from Layouter specific control. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); Gauge gauge = (Gauge) item; - if (gauge.isInteractive()) { + if(gauge.isInteractive()) + { Slider slider = (Slider) control; SelectionListener listener = (SelectionListener) slider - .getData(SELECTION_LISTENER); - if (listener != null) { + .getData(SELECTION_LISTENER); + if(listener != null) + { slider.removeSelectionListener(listener); slider.setData(SELECTION_LISTENER, null); } @@ -198,11 +213,14 @@ /** * Returns if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { - if (((Gauge) item).isInteractive()) { + boolean eswtIsSpecificControl(Item item, Control control) + { + if(((Gauge) item).isInteractive()) + { return (control instanceof Slider); } - else { + else + { return (control instanceof ProgressBar); } } @@ -210,13 +228,16 @@ /** * Updates the values of Gauge. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { Gauge gauge = (Gauge) item; - if (control instanceof ProgressBar) { + if(control instanceof ProgressBar) + { ((ProgressBar) control).setMaximum(gauge.getMaxValue() + 1); ((ProgressBar) control).setSelection(gauge.getValue()); } - else if (control instanceof Slider) { + else if(control instanceof Slider) + { ((Slider) control).setMaximum(gauge.getMaxValue() + 1); ((Slider) control).setSelection(gauge.getValue()); } @@ -225,17 +246,21 @@ /** * Returns true if that key was consumed by Gauge. */ - boolean eswtOfferKeyPressed(Item item, int key) { + boolean eswtOfferKeyPressed(Item item, int key) + { Gauge gauge = (Gauge) item; - if (gauge.isInteractive()) { - if (key == SWT.ARROW_RIGHT) { + if(gauge.isInteractive()) + { + if(key == SWT.ARROW_RIGHT) + { gauge.internalSetValue(gauge.getValue() + 1); - gauge.setLayout(gauge.internalGetLayout()); - + gauge.setLayout(gauge.internalGetLayout()); + } - else if(key == SWT.ARROW_LEFT) { - gauge.internalSetValue(gauge.getValue() -1); - gauge.setLayout(gauge.internalGetLayout()); + else if(key == SWT.ARROW_LEFT) + { + gauge.internalSetValue(gauge.getValue() -1); + gauge.setLayout(gauge.internalGetLayout()); } return true; } @@ -248,10 +273,13 @@ * @param gauge Gauge object. * @return Minimum area needed to display Gauge. */ - static Point calculateMinimumBounds(final Gauge gauge) { + static Point calculateMinimumBounds(final Gauge gauge) + { final Point minSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Control comp = eswtCreateControl(eswtGetStaticShell(), gauge); minSize.x = getMaximumItemWidth(gauge); minSize.y = ((Composite) comp).computeSize(minSize.x, SWT.DEFAULT).y; @@ -269,11 +297,14 @@ * @return Preferred area needed to display Item. x is width * and y is height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { final Point prefSize = new Point(0, 0); final Gauge gauge = (Gauge)item; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Control comp = eswtCreateControl(eswtGetStaticShell(), gauge); prefSize.x = getMaximumItemWidth(gauge); prefSize.y = ((Composite) comp).computeSize(prefSize.x, SWT.DEFAULT).y; @@ -287,7 +318,8 @@ /** * Class that receives events from slider and updates gauge's value. */ - class GaugeSelectionListener implements SelectionListener { + class GaugeSelectionListener implements SelectionListener + { private Gauge gauge; @@ -295,7 +327,8 @@ * Constructor. * @param gauge Gauge to be updated. */ - public GaugeSelectionListener(Gauge gauge) { + public GaugeSelectionListener(Gauge gauge) + { this.gauge = gauge; } @@ -305,10 +338,12 @@ * Called by eSWT when Slider's value is changed. * Updates Gauge's value. */ - public void widgetSelected(SelectionEvent e) { + public void widgetSelected(SelectionEvent e) + { int newValue = ((Slider) e.getSource()).getSelection(); // Actions needed only if value is adjusted: - if (newValue != gauge.getValue()) { + if(newValue != gauge.getValue()) + { // set Gauge value gauge.internalSetValue(newValue); gauge.setLayout(gauge.internalGetLayout()); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Graphics.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Graphics.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Graphics.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -28,7 +28,8 @@ /** * Implementation of LCDUI Graphics class. */ -public class Graphics { +public class Graphics +{ /** * Constant for horizontal center alignment of the text. @@ -111,96 +112,119 @@ private final Object flushLock = new Object(); private Canvas canvasParent; private CustomItem customItemParent; - + //Constructor - Graphics() { - finalizer = ((finalizer != null) ? finalizer - : new com.nokia.mj.impl.rt.support.Finalizer() { - public void finalizeImpl() { - if (finalizer != null) { - finalizer = null; - if (!ESWTUIThreadRunner.isDisposed()) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - dispose(); - } - }); - + Graphics() + { + finalizer = ((finalizer != null) ? finalizer + : new com.nokia.mj.impl.rt.support.Finalizer() + { + public void finalizeImpl() + { + if(finalizer != null) + { + finalizer = null; + if(!ESWTUIThreadRunner.isDisposed()) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + dispose(); } - } + }); + } - }); + } + } + }); } /** * Set the parent image of this Graphics. * * @param image an image */ - void eswtSetParentImage(final Image image) { - if(buffered) { + void eswtSetParentImage(final Image image) + { + if(buffered) + { return; } - if (parentImage != image) { + if(parentImage != image) + { parentImage = image; - if (gc == null) { + if(gc == null) + { gc = new GraphicsContext(); } - else { + else + { gc.releaseTarget(); } - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.graphics.Image eswtImage = Image.getESWTImage(image); - - if (eswtImage != null) { + + if(eswtImage != null) + { gc.bindTarget(Internal_GfxPackageSupport.getImage(eswtImage)); Rectangle clipRect = eswtImage.getBounds(); setClip(0, 0, clipRect.width, clipRect.height); } reset(); - }}); + } + }); } } /** * Initializes this instance of Graphics to use command buffer. - * - * Can be called in a non-UI thread. Not thread-safe. - * + * + * Can be called in a non-UI thread. Not thread-safe. + * * @param x The x-coordinate of clip * @param y The y-coordinate of clip * @param width The width of clip * @param height The height of clip */ - void initBuffered(final Canvas parent, final int x, final int y, final int width, final int height) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - cmdBuffer = new JavaCommandBuffer(); - if (gc == null) { - gc = new GraphicsContext(); - } - gc.bindTarget(cmdBuffer); - setClip(x, y, width, height); - reset(); - buffered = true; - javax.microedition.lcdui.Graphics.this.canvasParent = parent; - }}); + void initBuffered(final Canvas parent, final int x, final int y, final int width, final int height) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + cmdBuffer = new JavaCommandBuffer(); + if(gc == null) + { + gc = new GraphicsContext(); + } + gc.bindTarget(cmdBuffer); + setClip(x, y, width, height); + reset(); + buffered = true; + javax.microedition.lcdui.Graphics.this.canvasParent = parent; + } + }); } - + /** * Initializes this instance of Graphics to use command buffer. - * - * Can be called in a non-UI thread. Not thread-safe. - * + * + * Can be called in a non-UI thread. Not thread-safe. + * * @param x The x-coordinate of clip * @param y The y-coordinate of clip * @param width The width of clip * @param height The height of clip */ - void initBuffered(CustomItem parent, int x, int y, int width, int height) { + void initBuffered(CustomItem parent, int x, int y, int width, int height) + { cmdBuffer = new JavaCommandBuffer(); - if (gc == null) { + if(gc == null) + { gc = new GraphicsContext(); } gc.bindTarget(cmdBuffer); @@ -210,60 +234,69 @@ this.customItemParent = parent; } - /** - * Resets the command buffer contents. - * - * This is safe to call only in the UI thread. - */ - void resetCommandBuffer() { + /** + * Resets the command buffer contents. + * + * This is safe to call only in the UI thread. + */ + void resetCommandBuffer() + { gc.releaseTarget(); cmdBuffer.reset(); gc.bindTarget(cmdBuffer); - // write settings which were active before flush + // write settings which were active before flush // if they are not the same as defaults gc.setFont(Font.getESWTFont(currentFont).handle); gc.setBackgroundColor(currentColor, false); gc.setForegroundColor(currentColor, false); - if ((translateX != 0) || (translateY != 0)) { + if((translateX != 0) || (translateY != 0)) + { gc.translate(translateX, translateY); } - + // Note that if called in a non-UI thread then the size of the // Canvas or CustomItem can change between getting the height and // getting the width. Those are modified by the UI thread and there - // is no synchronization. + // is no synchronization. int w = 0; int h = 0; - if(canvasParent != null) { + if(canvasParent != null) + { w = canvasParent.getWidth(); h = canvasParent.getHeight(); - } else { + } + else + { w = customItemParent.getContentWidth(); h = customItemParent.getContentHeight(); } - - if((currentClip[0] != 0) && (currentClip[1] != 0) && - (currentClip[2] != w) && (currentClip[2] != h)) { + + if((currentClip[0] != 0) && (currentClip[1] != 0) && + (currentClip[2] != w) && (currentClip[2] != h)) + { gc.setClip(currentClip[0], currentClip[1], currentClip[2], currentClip[3], false); } - if (currentStrokeSyle != SOLID) { + if(currentStrokeSyle != SOLID) + { gc.setStrokeStyle(GraphicsContext.STROKE_DOT); } } - + /** - * Returns the current command buffer or null. - * - * This method is thread-safe. + * Returns the current command buffer or null. + * + * This method is thread-safe. */ - JavaCommandBuffer getCommandBuffer() { + JavaCommandBuffer getCommandBuffer() + { return cmdBuffer; } - + /** * Get the parent image of this Graphics. */ - Image getParentImage() { + Image getParentImage() + { return parentImage; } @@ -272,42 +305,55 @@ * * @param eswtGC */ - void eswtSetGC(final GC eswtGC) { - if(buffered) { + void eswtSetGC(final GC eswtGC) + { + if(buffered) + { return; } gc = eswtGC.getGCData().internalGc; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { Rectangle clipRect = eswtGC.getClipping(); setClip(clipRect.x, clipRect.y, clipRect.width, clipRect.height); reset(); - }}); + } + }); } /** * Disposes Graphics context resources. */ - void dispose() { - if (parentImage != null) { + void dispose() + { + if(parentImage != null) + { parentImage = null; } - if(gc != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(gc != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.dispose(); - }}); - gc = null; + } + }); + gc = null; } - if (cmdBuffer != null) { - cmdBuffer = null; + if(cmdBuffer != null) + { + cmdBuffer = null; } } /** * Resets Graphics state to initial. */ - void reset() { + void reset() + { setColor(0, 0, 0); setFont(Font.getDefaultFont()); setStrokeStyle(Graphics.SOLID); @@ -318,7 +364,8 @@ /** * Cleans the Canvas background. */ - void cleanBackground(Rectangle area) { + void cleanBackground(Rectangle area) + { int savedColor = currentColor; setColor(255, 255, 255); fillRect(area.x, area.y, area.width, area.height); @@ -328,7 +375,8 @@ /** * Cleans the Canvas background. */ - void cleanBackground(int x, int y, int w, int h) { + void cleanBackground(int x, int y, int w, int h) + { int savedColor = currentColor; setColor(255, 255, 255); fillRect(x, y, w, h); @@ -338,14 +386,16 @@ /** * Sets flag indicating that we are in Canvas.paint() callback */ - void beginPaint() { + void beginPaint() + { paintCallBack = true; } /** * Sets flag indicating that we are exiting Canvas.paint() callback */ - void endPaint() { + void endPaint() + { paintCallBack = false; } @@ -353,26 +403,35 @@ * Provides the serialization lock for buffer writing and flushing * @return lock used for synchronizing command buffer access */ - Object getLock() { + Object getLock() + { return flushLock; } - + /** * Sets coordinate translation. Translations are cumulative. * * @param xDelta x-shift for coordinates. * @param yDelta y-shift for coordinates. */ - public void translate(int xDelta, int yDelta) { - synchronized(flushLock) { - if(!buffered) { + public void translate(int xDelta, int yDelta) + { + synchronized(flushLock) + { + if(!buffered) + { final int xDelta_ = xDelta; final int yDelta_ = yDelta; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.translate(xDelta_, yDelta_); - }}); - } else { + } + }); + } + else + { gc.translate(xDelta, yDelta); } } @@ -385,7 +444,8 @@ * * @return Current X-shift of coordinate translation. */ - public int getTranslateX() { + public int getTranslateX() + { return translateX; } @@ -394,7 +454,8 @@ * * @return current Y-shift of coordinate translation. */ - public int getTranslateY() { + public int getTranslateY() + { return translateY; } @@ -403,7 +464,8 @@ * * @return Current color in 0x00RRGGBB format. */ - public int getColor() { + public int getColor() + { return currentColor; } @@ -412,7 +474,8 @@ * * @return Red component of current color in the range of 0-255. */ - public int getRedComponent() { + public int getRedComponent() + { return currentColor >> 16; } @@ -421,7 +484,8 @@ * * @return Green component of current color in the range of 0-255. */ - public int getGreenComponent() { + public int getGreenComponent() + { return (currentColor >> 8) & COMPONENT_MASK; } @@ -430,7 +494,8 @@ * * @return Blue component of current color in the range of 0-255. */ - public int getBlueComponent() { + public int getBlueComponent() + { return currentColor & COMPONENT_MASK; } @@ -439,7 +504,8 @@ * * @return Returns current grayscale color in the range 0-255. */ - public int getGrayScale() { + public int getGrayScale() + { return (getRedComponent() + getGreenComponent() + getBlueComponent()) / 3; } @@ -450,23 +516,32 @@ * @param g - green component of the color to be set. * @param b - blue component of the color to be set. */ - public void setColor(int r, int g, int b) { - if (r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 ) { - throw new IllegalArgumentException(); + public void setColor(int r, int g, int b) + { + if(r < 0 || r > 255 || + g < 0 || g > 255 || + b < 0 || b > 255) + { + throw new IllegalArgumentException(); } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int r_ = r; final int g_ = g; final int b_ = b; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setForegroundColor(r_, g_, b_); gc.setBackgroundColor(r_, g_, b_); - }}); - } else { + } + }); + } + else + { gc.setForegroundColor(r, g, b); gc.setBackgroundColor(r, g, b); } @@ -479,19 +554,27 @@ * * @param RGB - color to be set in the form of 0x00RRGGBB. */ - public void setColor(int RGB) { + public void setColor(int RGB) + { int maskedRGB = RGB & RGB_MASK; final int r = maskedRGB >> 16; final int g = (maskedRGB >> 8) & COMPONENT_MASK; final int b = maskedRGB & COMPONENT_MASK; - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setForegroundColor(r, g, b); gc.setBackgroundColor(r, g, b); - }}); - } else { + } + }); + } + else + { gc.setForegroundColor(r, g, b); gc.setBackgroundColor(r, g, b); } @@ -504,19 +587,28 @@ * * @param val - gray-scale value to be set in the range of 0-255. */ - public void setGrayScale(int val) { - if ( (val < 0) || (val > 255)) { - throw new IllegalArgumentException(); + public void setGrayScale(int val) + { + if((val < 0) || (val > 255)) + { + throw new IllegalArgumentException(); } final int col = val & COMPONENT_MASK; - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setForegroundColor(col, col, col); gc.setBackgroundColor(col, col, col); - }}); - } else { + } + }); + } + else + { gc.setForegroundColor(col, col, col); gc.setBackgroundColor(col, col, col); } @@ -529,7 +621,8 @@ * * @return Current font. */ - public Font getFont() { + public Font getFont() + { return currentFont; } @@ -538,15 +631,23 @@ * * @param newFont - the font to be used for string rendering. */ - public void setFont(Font newFont) { - synchronized(flushLock) { - if(!buffered) { + public void setFont(Font newFont) + { + synchronized(flushLock) + { + if(!buffered) + { final Font newFont_ = newFont; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setFont(Font.getESWTFont(newFont_).handle); - }}); - } else { + } + }); + } + else + { gc.setFont(Font.getESWTFont(newFont).handle); } } @@ -558,7 +659,8 @@ * * @return Left bound of clip rectangle. */ - public int getClipX() { + public int getClipX() + { return currentClip[0]; } @@ -567,7 +669,8 @@ * * @return Top bound of clip rectangle. */ - public int getClipY() { + public int getClipY() + { return currentClip[1]; } @@ -576,7 +679,8 @@ * * @return Width of clip rectangle. */ - public int getClipWidth() { + public int getClipWidth() + { return currentClip[2]; } @@ -585,7 +689,8 @@ * * @return Height of clip rectangle. */ - public int getClipHeight() { + public int getClipHeight() + { return currentClip[3]; } @@ -600,21 +705,29 @@ * @param h - height of the clip rectangle to intersect with the current * one. */ - public void clipRect(int x, int y, int w, int h) { - final int cx2 = Math.min( currentClip[0] + currentClip[2], x + w ); - final int cy2 = Math.min( currentClip[1] + currentClip[3], y + h ); + public void clipRect(int x, int y, int w, int h) + { + final int cx2 = Math.min(currentClip[0] + currentClip[2], x + w); + final int cy2 = Math.min(currentClip[1] + currentClip[3], y + h); // setting of clip to Java Graphics - currentClip[0] = Math.max( x, currentClip[0]); - currentClip[1] = Math.max( y, currentClip[1]); + currentClip[0] = Math.max(x, currentClip[0]); + currentClip[1] = Math.max(y, currentClip[1]); currentClip[2] = cx2 - currentClip[0]; currentClip[3] = cy2 - currentClip[1]; - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setClip(currentClip[0], currentClip[1], currentClip[2], currentClip[3], false); - }}); - } else { + } + }); + } + else + { gc.setClip(currentClip[0], currentClip[1], currentClip[2], currentClip[3], false); } } @@ -628,19 +741,27 @@ * @param w - width of the new clip rectangle. * @param h - height of the new clip rectangle. */ - public void setClip(int x, int y, int w, int h) { - synchronized(flushLock) { - if(!buffered) { + public void setClip(int x, int y, int w, int h) + { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setClip(x_, y_, w_, h_, false); - }}); - } else { + } + }); + } + else + { gc.setClip(x, y, w, h, false); } } @@ -658,19 +779,27 @@ * @param xEnd - X-coordinate of line end point. * @param yEnd - Y-coordinate of line end point. */ - public void drawLine(int xStart, int yStart, int xEnd, int yEnd) { - synchronized(flushLock) { - if(!buffered) { + public void drawLine(int xStart, int yStart, int xEnd, int yEnd) + { + synchronized(flushLock) + { + if(!buffered) + { final int xs_ = xStart; final int ys_ = yStart; final int xe_ = xEnd; final int ye_ = yEnd; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawLine(xs_, ys_, xe_, ye_); - }}); - } else { + } + }); + } + else + { gc.drawLine(xStart, yStart, xEnd, yEnd); } } @@ -684,22 +813,31 @@ * @param w - width of the rectangle * @param h - height of the rectangle */ - public void fillRect(int x, int y, int w, int h) { - if ((w < 0) || (h < 0)) { + public void fillRect(int x, int y, int w, int h) + { + if((w < 0) || (h < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.fillRect(x_, y_, w_, h_); - }}); - } else { + } + }); + } + else + { gc.fillRect(x, y, w, h); } } @@ -713,21 +851,30 @@ * @param w - width of the rectangle * @param h - height of the rectangle */ - public void drawRect(int x, int y, int w, int h) { - if ((w < 0) || (h < 0)) { + public void drawRect(int x, int y, int w, int h) + { + if((w < 0) || (h < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawRect(x_, y_, w_, h_); - }}); - } else { + } + }); + } + else + { gc.drawRect(x, y, w, h); } } @@ -743,24 +890,33 @@ * @param arcW - arc width for corner rounding. * @param arcH - arc height for corner rounding. */ - public void drawRoundRect(int x, int y, int w, int h, int arcW, int arcH) { - if ((w < 0) || (h < 0) || (arcW < 0) || (arcH < 0)) { + public void drawRoundRect(int x, int y, int w, int h, int arcW, int arcH) + { + if((w < 0) || (h < 0) || (arcW < 0) || (arcH < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; final int arcW_ = arcW; final int arcH_ = arcH; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawRoundRect(x_, y_, w_, h_, arcW_, arcH_); - }}); - } else { + } + }); + } + else + { gc.drawRoundRect(x, y, w, h, arcW, arcH); } } @@ -776,24 +932,33 @@ * @param arcW - arc width for corner rounding. * @param arcH - arc height for corner rounding. */ - public void fillRoundRect(int x, int y, int w, int h, int arcW, int arcH) { - if ((w < 0) || (h < 0) || (arcW < 0) || (arcH < 0)) { + public void fillRoundRect(int x, int y, int w, int h, int arcW, int arcH) + { + if((w < 0) || (h < 0) || (arcW < 0) || (arcH < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; final int arcW_ = arcW; final int arcH_ = arcH; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.fillRoundRect(x_, y_, w_, h_, arcW_, arcH_); - }}); - } else { + } + }); + } + else + { gc.fillRoundRect(x, y, w, h, arcW, arcH); } } @@ -811,24 +976,33 @@ * @param startAngle - starting angle of the arc in degrees. * @param arcAngle - angle to spread the arc in degrees. */ - public void fillArc(int x, int y, int w, int h, int startAngle, int arcAngle) { - if ((w < 0) || (h < 0)) { + public void fillArc(int x, int y, int w, int h, int startAngle, int arcAngle) + { + if((w < 0) || (h < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; final int startAngle_ = startAngle; final int arcAngle_ = arcAngle; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.fillArc(x_, y_, w_, h_, startAngle_, arcAngle_); - }}); - } else { + } + }); + } + else + { gc.fillArc(x, y, w, h, startAngle, arcAngle); } } @@ -846,24 +1020,33 @@ * @param startAngle - starting angle of the arc in degrees. * @param arcAngle - angle to spread the arc in degrees. */ - public void drawArc(int x, int y, int w, int h, int startAngle, int arcAngle) { - if ((w < 0) || (h < 0)) { + public void drawArc(int x, int y, int w, int h, int startAngle, int arcAngle) + { + if((w < 0) || (h < 0)) + { return; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; final int w_ = w; final int h_ = h; final int startAngle_ = startAngle; final int arcAngle_ = arcAngle; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawArc(x_, y_, w_, h_, startAngle_, arcAngle_); - }}); - } else { + } + }); + } + else + { gc.drawArc(x, y, w, h, startAngle, arcAngle); } } @@ -880,27 +1063,34 @@ * Graphics.BOTTOM, Graphics.BASELINE, Graphics.LEFT, * Graphics.RIGHT, Graphics.HCENTER. */ - public void drawString(String string, int xPos, int yPos, int anch) { - if (string == null) { + public void drawString(String string, int xPos, int yPos, int anch) + { + if(string == null) + { throw new NullPointerException( - MsgRepository.GRAPHICS_EXCEPTION_STRING_IS_NULL); + MsgRepository.GRAPHICS_EXCEPTION_STRING_IS_NULL); } - if (!checkTextAnchors(anch)) { + if(!checkTextAnchors(anch)) + { throw new IllegalArgumentException( - MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); + MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); } final int alignments = GraphicsContext.ALIGNMENT_TOP | GraphicsContext.ALIGNMENT_LEFT; final int[] boundingBox = new int[4]; final String localStr = string; - - if (paintCallBack) { + + if(paintCallBack) + { gc.getTextBoundingBox(boundingBox, string, alignments, 0); } - else { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + else + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { FontUtils fu = new FontUtils(Font.getESWTFont(currentFont).handle); fu.getBoundingRect(boundingBox, localStr); } @@ -914,36 +1104,48 @@ // Arrange vertical alignments int y = yPos; - if (isFlag(anch, Graphics.BOTTOM)) { + if(isFlag(anch, Graphics.BOTTOM)) + { y = yPos - boundingBox[GraphicsContext.RECT_HEIGHT]; } - if (isFlag(anch, Graphics.BASELINE)) { + if(isFlag(anch, Graphics.BASELINE)) + { y = yPos - currentFont.getBaselinePosition(); } // Arrange horizontal alignments int x = xPos; - if (isFlag(anch, Graphics.RIGHT)) { + if(isFlag(anch, Graphics.RIGHT)) + { x = xPos - boundingBox[GraphicsContext.RECT_WIDTH]; } - if (isFlag(anch, Graphics.HCENTER)) { + if(isFlag(anch, Graphics.HCENTER)) + { x = xPos - boundingBox[GraphicsContext.RECT_WIDTH] / 2; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawString(localStr, x_, y_, true); - }}); - } else { + } + }); + } + else + { gc.drawString(localStr, x, y, true); } } } - private static boolean isFlag(int anchor, int flag) { + private static boolean isFlag(int anchor, int flag) + { return (anchor & flag) != 0; } @@ -961,7 +1163,8 @@ * Graphics.RIGHT, Graphics.HCENTER. */ public void drawSubstring(java.lang.String string, int offset, int length, - int xPos, int yPos, int anch) { + int xPos, int yPos, int anch) + { drawString(string.substring(offset, length), xPos, yPos, anch); } @@ -976,7 +1179,8 @@ * Graphics.BOTTOM, Graphics.BASELINE, Graphics.LEFT, * Graphics.RIGHT, Graphics.HCENTER. */ - public void drawChar(char c, int xPos, int yPos, int anch) { + public void drawChar(char c, int xPos, int yPos, int anch) + { drawString(String.valueOf(c), xPos, yPos, anch); } @@ -994,18 +1198,22 @@ * Graphics.RIGHT, Graphics.HCENTER. */ public void drawChars(char[] ch, int offset, int length, - int xPos, int yPos, int anch) { - if (ch == null) { + int xPos, int yPos, int anch) + { + if(ch == null) + { throw new NullPointerException( - MsgRepository.GRAPHICS_EXCEPTION_ARRAY_IS_NULL); + MsgRepository.GRAPHICS_EXCEPTION_ARRAY_IS_NULL); } String str = null; - try { + try + { str = String.valueOf(ch, offset, length); } - catch (Exception e) { + catch(Exception e) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.GRAPHICS_EXCEPTION_ARRAY_OUT_OF_BOUNDS); + MsgRepository.GRAPHICS_EXCEPTION_ARRAY_OUT_OF_BOUNDS); } drawString(str, xPos, yPos, anch); @@ -1014,32 +1222,37 @@ /** * Checks if anchors combination is valid. */ - private boolean checkTextAnchors(int anch) { + private boolean checkTextAnchors(int anch) + { boolean retVal = false; int vertMask = Graphics.TOP | Graphics.BASELINE | Graphics.BOTTOM; int horMask = Graphics.LEFT | Graphics.RIGHT | Graphics.HCENTER; - if (anch == 0) { + if(anch == 0) + { return true; } - if ((anch & ~(vertMask | horMask)) != 0) { + if((anch & ~(vertMask | horMask)) != 0) + { return false; } int vertAchor = anch & vertMask; int horAchor = anch & horMask; - if ((vertAchor == Graphics.TOP) - || (vertAchor == Graphics.BASELINE) - || (vertAchor == Graphics.BOTTOM)) { + if((vertAchor == Graphics.TOP) + || (vertAchor == Graphics.BASELINE) + || (vertAchor == Graphics.BOTTOM)) + { retVal = true; } - if ((horAchor == Graphics.LEFT) + if((horAchor == Graphics.LEFT) || (vertAchor == Graphics.RIGHT) - || (vertAchor == Graphics.HCENTER)) { + || (vertAchor == Graphics.HCENTER)) + { retVal = true; } @@ -1055,44 +1268,58 @@ * @param anch - anchor value. */ public void drawImage(javax.microedition.lcdui.Image image, int xPos, - int yPos, int anch) { + int yPos, int anch) + { - if (image == null) { + if(image == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_IS_NULL); } - if (!checkImageAnchors(anch)) { + if(!checkImageAnchors(anch)) + { throw new IllegalArgumentException( - MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); + MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); } int y = yPos; - if (isFlag(anch, Graphics.VCENTER)) { + if(isFlag(anch, Graphics.VCENTER)) + { y = yPos - image.getHeight() / 2; } - if (isFlag(anch, Graphics.BOTTOM)) { + if(isFlag(anch, Graphics.BOTTOM)) + { y = yPos - image.getHeight(); } int x = xPos; - if (isFlag(anch, Graphics.HCENTER)) { + if(isFlag(anch, Graphics.HCENTER)) + { x = xPos - image.getWidth() / 2; } - if (isFlag(anch, Graphics.RIGHT)) { + if(isFlag(anch, Graphics.RIGHT)) + { x = xPos - image.getWidth(); } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x_ = x; final int y_ = y; - final org.eclipse.swt.internal.qt.graphics.Image image_ = + final org.eclipse.swt.internal.qt.graphics.Image image_ = Internal_GfxPackageSupport.getImage(Image.getESWTImage(image)); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawImage(image_, x_, y_); - }}); - } else { + } + }); + } + else + { gc.drawImage(Internal_GfxPackageSupport.getImage(Image.getESWTImage(image)), x, y); } } @@ -1101,32 +1328,37 @@ /** * Checks if anchors combination is valid. */ - private boolean checkImageAnchors(int anch) { + private boolean checkImageAnchors(int anch) + { boolean retVal = false; int vertMask = Graphics.TOP | Graphics.VCENTER | Graphics.BOTTOM; int horMask = Graphics.LEFT | Graphics.RIGHT | Graphics.HCENTER; - if (anch == 0) { + if(anch == 0) + { return true; } - if ((anch & ~(vertMask | horMask)) != 0) { + if((anch & ~(vertMask | horMask)) != 0) + { return false; } int vertAchor = anch & vertMask; int horAchor = anch & horMask; - if ((vertAchor == Graphics.TOP) - || (vertAchor == Graphics.VCENTER) - || (vertAchor == Graphics.BOTTOM)) { + if((vertAchor == Graphics.TOP) + || (vertAchor == Graphics.VCENTER) + || (vertAchor == Graphics.BOTTOM)) + { retVal = true; } - if ((horAchor == Graphics.LEFT) + if((horAchor == Graphics.LEFT) || (vertAchor == Graphics.RIGHT) - || (vertAchor == Graphics.HCENTER)) { + || (vertAchor == Graphics.HCENTER)) + { retVal = true; } @@ -1140,34 +1372,56 @@ * Graphics.DOTTED. * @throws IllegalArgumentException if the new style value is invalid. */ - public void setStrokeStyle(int newStyle) { - if (newStyle == currentStrokeSyle) { + public void setStrokeStyle(int newStyle) + { + if(newStyle == currentStrokeSyle) + { return; } - if (newStyle == SOLID) { - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(newStyle == SOLID) + { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setStrokeStyle(GraphicsContext.STROKE_SOLID); - }}); - } else { + } + }); + } + else + { gc.setStrokeStyle(GraphicsContext.STROKE_SOLID); } } - } else { - if (newStyle == DOTTED) { - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + } + else + { + if(newStyle == DOTTED) + { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.setStrokeStyle(GraphicsContext.STROKE_DOT); - }}); - } else { + } + }); + } + else + { gc.setStrokeStyle(GraphicsContext.STROKE_DOT); } } - } else { + } + else + { throw new IllegalArgumentException( MsgRepository.GRAPHICS_EXCEPTION_ILLEGAL_STROKE_STYLE); } @@ -1180,7 +1434,8 @@ * * @return Current stroke style. */ - public int getStrokeStyle() { + public int getStrokeStyle() + { return currentStrokeSyle; } @@ -1190,7 +1445,8 @@ * @param color - color to use in 0x00RRGGBB form. * @return Color that will be actually used in 0x00RRGGBB form. */ - public int getDisplayColor(int color) { + public int getDisplayColor(int color) + { return color & RGB_MASK; } @@ -1216,14 +1472,18 @@ int y, int w, int h, - boolean alpha) { + boolean alpha) + { - if (rgb == null) { + if(rgb == null) + { throw new NullPointerException( MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int[] rgb_ = rgb; final int offset_ = offset; final int scanlength_ = scanlength; @@ -1232,12 +1492,17 @@ final int w_ = w; final int h_ = h; final boolean alpha_ = alpha; - - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawRGB(rgb_, offset_, scanlength_, x_, y_, w_, h_, alpha_); - }}); - } else { + } + }); + } + else + { gc.drawRGB(rgb, offset, scanlength, x, y, w, h, alpha); } } @@ -1258,15 +1523,23 @@ int xPos2, int yPos2, int xPos3, - int yPos3) { + int yPos3) + { final int[] points = {xPos1, yPos1, xPos2, yPos2, xPos3, yPos3}; - synchronized(flushLock) { - if(!buffered) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + synchronized(flushLock) + { + if(!buffered) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.fillPolygon(points); - }}); - } else { + } + }); + } + else + { gc.fillPolygon(points); } } @@ -1289,40 +1562,49 @@ int h, int xTo, int yTo, - int anch) { + int anch) + { - if (this.parentImage == null) { + if(this.parentImage == null) + { // this Graphics belongs to a screen device. throw new IllegalStateException( MsgRepository.GRAPHICS_EXCEPTION_DESTINATION_IS_SCREEN); } - if (!javax.microedition.lcdui.Image.validateRegion(parentImage - .getWidth(), parentImage.getHeight(), xFrom, yFrom, w, h)) { + if(!javax.microedition.lcdui.Image.validateRegion(parentImage + .getWidth(), parentImage.getHeight(), xFrom, yFrom, w, h)) + { throw new IllegalArgumentException( MsgRepository.IMAGE_EXCEPTION_INVALID_REGION); } // Arrange vertical alignments int destY = yTo; - if (isFlag(anch, Graphics.BOTTOM)) { + if(isFlag(anch, Graphics.BOTTOM)) + { destY = yTo - h; } - if (isFlag(anch, Graphics.VCENTER)) { + if(isFlag(anch, Graphics.VCENTER)) + { destY = yTo - h / 2; } // Arrange horizontal alignments int destX = xTo; - if (isFlag(anch, Graphics.RIGHT)) { + if(isFlag(anch, Graphics.RIGHT)) + { destX = xTo - w; } - if (isFlag(anch, Graphics.HCENTER)) { + if(isFlag(anch, Graphics.HCENTER)) + { destX = xTo - w / 2; } - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int x1 = xFrom; final int y1 = yFrom; final int width = w; @@ -1330,11 +1612,16 @@ final int x2 = destX; final int y2 = destY; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.copyArea(x1, y1, width, height, x2, y2); - }}); - } else { + } + }); + } + else + { gc.copyArea(xFrom, yFrom, w, h, destX, destY); } } @@ -1363,65 +1650,82 @@ int transform, int xDst, int yDst, - int anch) { - - if (srcImage == null) { + int anch) + { + + if(srcImage == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_IS_NULL); } - if (srcImage == parentImage) { + if(srcImage == parentImage) + { throw new IllegalArgumentException( - MsgRepository.GRAPHICS_EXCEPTION_SAME_SOURCE_AND_DESTINATION); + MsgRepository.GRAPHICS_EXCEPTION_SAME_SOURCE_AND_DESTINATION); } - if (!javax.microedition.lcdui.Image.validateTransform(transform)) { + if(!javax.microedition.lcdui.Image.validateTransform(transform)) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_TRANSFORM); + MsgRepository.IMAGE_EXCEPTION_INVALID_TRANSFORM); } - if (!checkImageAnchors(anch)) { + if(!checkImageAnchors(anch)) + { throw new IllegalArgumentException( - MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); + MsgRepository.GRAPHICS_EXCEPTION_INVALID_ANCHOR); } - if (!javax.microedition.lcdui.Image.validateRegion(srcImage.getWidth(), - srcImage.getHeight(), xSrc, ySrc, width, height)) { + if(!javax.microedition.lcdui.Image.validateRegion(srcImage.getWidth(), + srcImage.getHeight(), xSrc, ySrc, width, height)) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_REGION); + MsgRepository.IMAGE_EXCEPTION_INVALID_REGION); } // Arrange vertical alignments int y = yDst; - if (isFlag(anch, Graphics.VCENTER)) { + if(isFlag(anch, Graphics.VCENTER)) + { y = yDst - srcImage.getHeight() / 2; } - if (isFlag(anch, Graphics.BOTTOM)) { + if(isFlag(anch, Graphics.BOTTOM)) + { y = yDst - srcImage.getHeight(); } // Arrange horizontal alignments int x = xDst; - if (isFlag(anch, Graphics.HCENTER)) { + if(isFlag(anch, Graphics.HCENTER)) + { x = xDst - srcImage.getWidth() / 2; } - if (isFlag(anch, Graphics.RIGHT)) { + if(isFlag(anch, Graphics.RIGHT)) + { x = xDst - srcImage.getWidth(); } - + final int gcTransform = Image.getCgTransformValue(transform); - synchronized(flushLock) { - if(!buffered) { + synchronized(flushLock) + { + if(!buffered) + { final int localXDst = x; final int localYDst = y; final int localW = width; final int localH = height; final int localXSrc = xSrc; final int localYSrc = ySrc; - final org.eclipse.swt.internal.qt.graphics.Image localImage = + final org.eclipse.swt.internal.qt.graphics.Image localImage = Internal_GfxPackageSupport.getImage(Image.getESWTImage(srcImage)); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { gc.drawImage(localImage, localXDst, localYDst, localW, localH, localXSrc, localYSrc, localW, localH, gcTransform); - }}); - } else { - gc.drawImage(Internal_GfxPackageSupport.getImage(Image.getESWTImage(srcImage)), + } + }); + } + else + { + gc.drawImage(Internal_GfxPackageSupport.getImage(Image.getESWTImage(srcImage)), x, y, width, height, xSrc, ySrc, width, height, gcTransform); } } @@ -1430,8 +1734,10 @@ /** * Return DirectGraphics associated with this instance. */ - DirectGraphics getDirectGraphics() { - if (directGraphics == null) { + DirectGraphics getDirectGraphics() + { + if(directGraphics == null) + { directGraphics = new DirectGraphicsImpl(this); } return directGraphics; @@ -1440,7 +1746,8 @@ /** * Return native graphic context. */ - GraphicsContext getGc() { + GraphicsContext getGc() + { return gc; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Image.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Image.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Image.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -29,7 +29,8 @@ * LCDUI accepts path "/TestMIDlets/images/100x100.png" but corresponding path * with this image-class must be "/100x100.png". */ -public class Image { +public class Image +{ private static Image createImageReturnValue; @@ -45,33 +46,42 @@ /** * Constructor. */ - Image(org.eclipse.swt.graphics.Image eswtImage, boolean isMutable) { + Image(org.eclipse.swt.graphics.Image eswtImage, boolean isMutable) + { this.eswtImage = eswtImage; this.mutable = isMutable; eswtImageWidth = eswtImage.getBounds().width; eswtImageHeight = eswtImage.getBounds().height; finalizer = ((finalizer != null) ? finalizer - : new com.nokia.mj.impl.rt.support.Finalizer() { - public void finalizeImpl() { - if (finalizer != null) { - finalizer = null; - if (!ESWTUIThreadRunner.isDisposed()) { - dispose(); - } - } + : new com.nokia.mj.impl.rt.support.Finalizer() + { + public void finalizeImpl() + { + if(finalizer != null) + { + finalizer = null; + if(!ESWTUIThreadRunner.isDisposed()) + { + dispose(); } - }); + } + } + }); ESWTUIThreadRunner.update(getClass().getName(), 1); } /** * Called by finalizer when Image is ready to free its resources. */ - void dispose() { + void dispose() + { ESWTUIThreadRunner.update(getClass().getName(), -1); - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (eswtImage != null) { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(eswtImage != null) + { eswtImage.dispose(); eswtImage = null; } @@ -82,7 +92,8 @@ /** * Return eSWT Image object. */ - org.eclipse.swt.graphics.Image getESWTImage() { + org.eclipse.swt.graphics.Image getESWTImage() + { return eswtImage; } @@ -92,8 +103,10 @@ * @param img Image * @return eSWT Image */ - static org.eclipse.swt.graphics.Image getESWTImage(Image img) { - if (img != null) { + static org.eclipse.swt.graphics.Image getESWTImage(Image img) + { + if(img != null) + { return img.eswtImage; } return null; @@ -107,23 +120,29 @@ * @return Image created. * @throws IllegalArgumentException if width or height are zero or less. */ - public static Image createImage(int w, int h) { - if (w <= 0 || h <= 0) { + public static Image createImage(int w, int h) + { + if(w <= 0 || h <= 0) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); + MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); } final int width = w; final int height = h; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.graphics.Image eswtImg = eswtCreateImage(width, height); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, true); } - else { + else + { createImageReturnValue = null; throw new OutOfMemoryError(); } @@ -142,23 +161,29 @@ * @return the resized Image. * @throws NullPointerException if aImage is null. */ - static Image createImage(Image srcImage, int width, int height) { - if (srcImage == null) { + static Image createImage(Image srcImage, int width, int height) + { + if(srcImage == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_IS_NULL); } final Image finalImage = srcImage; final int finalWidth = width; final int finalHeight = height; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.graphics.Image eswtImg = eswtCreateImage(finalImage.eswtImage, finalWidth, finalHeight); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, false); } - else { + else + { createImageReturnValue = null; throw new OutOfMemoryError(); } @@ -174,26 +199,33 @@ * @return Image created. * @throws NullPointerException if source image is null. */ - public static Image createImage(Image srcImage) { - if (srcImage == null) { + public static Image createImage(Image srcImage) + { + if(srcImage == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_IS_NULL); } - if (!srcImage.isMutable()) { + if(!srcImage.isMutable()) + { return srcImage; } final Image finalImage = srcImage; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.graphics.Image eswtImg = eswtCreateImage(finalImage.eswtImage); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, false); } - else { + else + { createImageReturnValue = null; throw new OutOfMemoryError(); } @@ -211,26 +243,32 @@ * @throws IOException If resource doesn't exist, data cannot be loaded or * data is invalid. */ - public static Image createImage(String name) throws IOException { - if (name == null) { + public static Image createImage(String name) throws IOException + { + if(name == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_FILE_NAME_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_FILE_NAME_IS_NULL); } String fileName = name; - if (!fileName.startsWith("/")) { + if(!fileName.startsWith("/")) + { fileName = "/" + fileName; } InputStream stream = Image.class.getResourceAsStream(fileName); - if (stream == null) { + if(stream == null) + { throw new IOException(MsgRepository.IMAGE_EXCEPTION_IO_ERROR); } Image image = createImage(stream); - try { + try + { stream.close(); } - catch (IOException e) { + catch(IOException e) + { // ignore } return image; @@ -246,25 +284,32 @@ * @throws java.io.IOException If I/O error occurs or data from stream is * invalid. */ - public static Image createImage(InputStream stream) throws java.io.IOException { - if (stream == null) { + public static Image createImage(InputStream stream) throws java.io.IOException + { + if(stream == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_FILE_STREAM_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_FILE_STREAM_IS_NULL); } final InputStream finalStream = stream; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.graphics.Image eswtImg = eswtCreateImage(finalStream); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, false); } - else { + else + { createImageReturnValue = null; } } }); - if (createImageReturnValue == null) { + if(createImageReturnValue == null) + { throw new IOException(MsgRepository.IMAGE_EXCEPTION_IO_ERROR); } return createImageReturnValue; @@ -282,33 +327,42 @@ * @throws NullPointerException if imgData is null. * @throws IllegalArgumentException if imgData content is invalid. */ - public static Image createImage(byte[] imgData, int imgOffset, int imgLength) { - if (imgData == null) { + public static Image createImage(byte[] imgData, int imgOffset, int imgLength) + { + if(imgData == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); } - if (imgOffset + imgLength > imgData.length) { + if(imgOffset + imgLength > imgData.length) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); + MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); } - if (imgOffset < 0 || imgLength < 0) { + if(imgOffset < 0 || imgLength < 0) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); + MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); } InputStream inputStream = new ByteArrayInputStream(imgData, imgOffset, imgLength); - try { + try + { createImageReturnValue = createImage(inputStream); } - catch (IOException e) { + catch(IOException e) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_DATA); + MsgRepository.IMAGE_EXCEPTION_INVALID_DATA); } - finally { - try { + finally + { + try + { inputStream.close(); } - catch (IOException e) { + catch(IOException e) + { // ignore } } @@ -337,22 +391,27 @@ int y, int w, int h, - int transform) { - if (srcImage == null) { + int transform) + { + if(srcImage == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_IS_NULL); } - if (w <= 0 || h <= 0) { + if(w <= 0 || h <= 0) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); + MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); } - if (!validateTransform(transform)) { + if(!validateTransform(transform)) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_TRANSFORM); + MsgRepository.IMAGE_EXCEPTION_INVALID_TRANSFORM); } - if (!validateRegion(srcImage.getWidth(), srcImage.getHeight(), x, y, w, h)) { + if(!validateRegion(srcImage.getWidth(), srcImage.getHeight(), x, y, w, h)) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_REGION); + MsgRepository.IMAGE_EXCEPTION_INVALID_REGION); } final Image fImage = srcImage; @@ -361,26 +420,30 @@ final int fw = w; final int fh = h; final int fTransform = transform; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image srcCgImage = Internal_GfxPackageSupport.getImage(fImage.getESWTImage()); org.eclipse.swt.internal.qt.graphics.Image cgImage = new org.eclipse.swt.internal.qt.graphics.Image( - srcCgImage, fx, fy, fw, fh); + srcCgImage, fx, fy, fw, fh); cgImage.transform(getCgTransformValue(fTransform)); org.eclipse.swt.graphics.Image eswtImg = Internal_GfxPackageSupport.new_Image( - ESWTUIThreadRunner.getInstance().getDisplay(), - cgImage); + ESWTUIThreadRunner.getInstance().getDisplay(), + cgImage); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, false); } - else { + else + { createImageReturnValue = null; throw new OutOfMemoryError(); } @@ -394,7 +457,8 @@ * bounds. Method is package-private, used by Graphics.drawRegion as well. */ static boolean validateRegion(int srcWidth, int srcHeight, int x, int y, - int w, int h) { + int w, int h) + { return x >= 0 && y >= 0 && w <= srcWidth && h <= srcHeight; } @@ -402,56 +466,59 @@ * Validates if transform has a valid value. Method is package-private, used * by Graphics.drawRegion as well. */ - static boolean validateTransform(int transform) { + static boolean validateTransform(int transform) + { return transform == Sprite.TRANS_NONE - || transform == Sprite.TRANS_MIRROR - || transform == Sprite.TRANS_MIRROR_ROT90 - || transform == Sprite.TRANS_MIRROR_ROT180 - || transform == Sprite.TRANS_MIRROR_ROT270 - || transform == Sprite.TRANS_ROT90 - || transform == Sprite.TRANS_ROT180 - || transform == Sprite.TRANS_ROT270; + || transform == Sprite.TRANS_MIRROR + || transform == Sprite.TRANS_MIRROR_ROT90 + || transform == Sprite.TRANS_MIRROR_ROT180 + || transform == Sprite.TRANS_MIRROR_ROT270 + || transform == Sprite.TRANS_ROT90 + || transform == Sprite.TRANS_ROT180 + || transform == Sprite.TRANS_ROT270; } /** * Maps LCDUI transform constants to Common Graphics. Method is package-private, used * by Graphics.drawRegion as well. */ - static int getCgTransformValue(int transform) { + static int getCgTransformValue(int transform) + { int retVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; - switch (transform) { - case Sprite.TRANS_NONE: - retVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; - break; - case Sprite.TRANS_ROT90: - retVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT90; - break; - case Sprite.TRANS_ROT180: - retVal = - org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT180; - break; - case Sprite.TRANS_ROT270: - retVal = - org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT270; - break; - case Sprite.TRANS_MIRROR: - retVal = - org.eclipse.swt.internal.qt.graphics.Image.TRANS_MIRROR; - break; - case Sprite.TRANS_MIRROR_ROT90: - retVal = org.eclipse.swt.internal.qt.graphics. - Image.TRANS_MIRROR_ROT90; - break; - case Sprite.TRANS_MIRROR_ROT180: - retVal = org.eclipse.swt.internal.qt.graphics. - Image.TRANS_MIRROR_ROT180; - break; - case Sprite.TRANS_MIRROR_ROT270: - retVal = org.eclipse.swt.internal.qt.graphics. - Image.TRANS_MIRROR_ROT270; - break; - default: - break; + switch(transform) + { + case Sprite.TRANS_NONE: + retVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_NONE; + break; + case Sprite.TRANS_ROT90: + retVal = org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT90; + break; + case Sprite.TRANS_ROT180: + retVal = + org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT180; + break; + case Sprite.TRANS_ROT270: + retVal = + org.eclipse.swt.internal.qt.graphics.Image.TRANS_ROT270; + break; + case Sprite.TRANS_MIRROR: + retVal = + org.eclipse.swt.internal.qt.graphics.Image.TRANS_MIRROR; + break; + case Sprite.TRANS_MIRROR_ROT90: + retVal = org.eclipse.swt.internal.qt.graphics. + Image.TRANS_MIRROR_ROT90; + break; + case Sprite.TRANS_MIRROR_ROT180: + retVal = org.eclipse.swt.internal.qt.graphics. + Image.TRANS_MIRROR_ROT180; + break; + case Sprite.TRANS_MIRROR_ROT270: + retVal = org.eclipse.swt.internal.qt.graphics. + Image.TRANS_MIRROR_ROT270; + break; + default: + break; } return retVal; } @@ -463,9 +530,11 @@ * @return new eSWT image. */ private static org.eclipse.swt.graphics.Image eswtCreateImage( - org.eclipse.swt.graphics.Image srcImage) { + org.eclipse.swt.graphics.Image srcImage) + { org.eclipse.swt.graphics.Image ret = null; - try { + try + { org.eclipse.swt.internal.qt.graphics.Image cgImage = Internal_GfxPackageSupport.getImage(srcImage); @@ -473,16 +542,19 @@ new org.eclipse.swt.internal.qt.graphics.Image(cgImage); ret = Internal_GfxPackageSupport.new_Image( - ESWTUIThreadRunner.getInstance().getDisplay(), cgImage2); + ESWTUIThreadRunner.getInstance().getDisplay(), cgImage2); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Device is null or there's no current device. ret = null; } - catch (org.eclipse.swt.SWTException ex) { + catch(org.eclipse.swt.SWTException ex) + { ret = null; } - catch (org.eclipse.swt.SWTError err) { + catch(org.eclipse.swt.SWTError err) + { ret = null; } return ret; @@ -492,21 +564,26 @@ * Creates eSWT image of the specified size from the given image. */ static org.eclipse.swt.graphics.Image eswtCreateImage( - org.eclipse.swt.graphics.Image image, int newWidth, int newHeight) { + org.eclipse.swt.graphics.Image image, int newWidth, int newHeight) + { org.eclipse.swt.graphics.Image ret = null; - try { + try + { ret = new org.eclipse.swt.graphics.Image( - ESWTUIThreadRunner.getInstance().getDisplay(), - image.getImageData().scaledTo(newWidth, newHeight)); + ESWTUIThreadRunner.getInstance().getDisplay(), + image.getImageData().scaledTo(newWidth, newHeight)); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Device is null or there's no current device. ret = null; } - catch (org.eclipse.swt.SWTException ex) { + catch(org.eclipse.swt.SWTException ex) + { ret = null; } - catch (org.eclipse.swt.SWTError err) { + catch(org.eclipse.swt.SWTError err) + { ret = null; } return ret; @@ -515,20 +592,25 @@ /** * Creates eSWT image of the specified size. */ - static org.eclipse.swt.graphics.Image eswtCreateImage(int width, int height) { + static org.eclipse.swt.graphics.Image eswtCreateImage(int width, int height) + { org.eclipse.swt.graphics.Image ret = null; - try { + try + { ret = new org.eclipse.swt.graphics.Image( - ESWTUIThreadRunner.getInstance().getDisplay(), width, height); + ESWTUIThreadRunner.getInstance().getDisplay(), width, height); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Device is null or there's no current device. ret = null; } - catch (org.eclipse.swt.SWTException ex) { + catch(org.eclipse.swt.SWTException ex) + { ret = null; } - catch (org.eclipse.swt.SWTError err) { + catch(org.eclipse.swt.SWTError err) + { ret = null; } return ret; @@ -537,20 +619,25 @@ /** * Creates and eSWT image out of the InputStream. */ - static org.eclipse.swt.graphics.Image eswtCreateImage(InputStream inputStream) { + static org.eclipse.swt.graphics.Image eswtCreateImage(InputStream inputStream) + { org.eclipse.swt.graphics.Image ret = null; - try { + try + { ret = new org.eclipse.swt.graphics.Image( - ESWTUIThreadRunner.getInstance().getDisplay(), inputStream); + ESWTUIThreadRunner.getInstance().getDisplay(), inputStream); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Device is null or there's no current device. ret = null; } - catch (org.eclipse.swt.SWTException ex) { + catch(org.eclipse.swt.SWTException ex) + { ret = null; } - catch (org.eclipse.swt.SWTError err) { + catch(org.eclipse.swt.SWTError err) + { ret = null; } return ret; @@ -573,38 +660,46 @@ public static Image createRGBImage(int[] rgbData, int width, int height, - boolean processAlpha) { + boolean processAlpha) + { - if (rgbData == null) { + if(rgbData == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); } - if (width <= 0 || height <= 0) { + if(width <= 0 || height <= 0) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); + MsgRepository.IMAGE_EXCEPTION_INVALID_DIMENSIONS); } - if (width * height > rgbData.length) { + if(width * height > rgbData.length) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); + MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); } final int[] rgb = rgbData; final int w = width; final int h = height; final boolean alpha = processAlpha; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image cgImage = new org.eclipse.swt.internal.qt.graphics.Image(rgb, w, h, alpha); org.eclipse.swt.graphics.Image eswtImg = Internal_GfxPackageSupport.new_Image( - ESWTUIThreadRunner.getInstance().getDisplay(), cgImage); + ESWTUIThreadRunner.getInstance().getDisplay(), cgImage); - if (eswtImg != null) { + if(eswtImg != null) + { createImageReturnValue = new Image(eswtImg, false); } - else { + else + { createImageReturnValue = null; throw new OutOfMemoryError(); } @@ -631,20 +726,24 @@ int xPos, int yPos, int width, - int height) { + int height) + { - if (rgbData == null) { + if(rgbData == null) + { throw new NullPointerException( - MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); + MsgRepository.IMAGE_EXCEPTION_DATA_IS_NULL); } - if (!validateRegion(this.getWidth(), this.getHeight(), - xPos, yPos, width, height)) { + if(!validateRegion(this.getWidth(), this.getHeight(), + xPos, yPos, width, height)) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); + MsgRepository.IMAGE_EXCEPTION_INVALID_BOUNDS); } - if (Math.abs(length) < width) { + if(Math.abs(length) < width) + { throw new IllegalArgumentException( - MsgRepository.IMAGE_EXCEPTION_INVALID_SCANLENGTH); + MsgRepository.IMAGE_EXCEPTION_INVALID_SCANLENGTH); } final int[] localRgbData = rgbData; @@ -654,11 +753,13 @@ final int localY = yPos; final int localW = width; final int localH = height; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { org.eclipse.swt.internal.qt.graphics.Image cgImage = Internal_GfxPackageSupport.getImage(eswtImage); cgImage.getRGB(localRgbData, localOffset, localLength, - localX, localY, localW, localH); + localX, localY, localW, localH); } }); } @@ -669,11 +770,16 @@ * @return New Graphics-object. * @throws IllegalStateException if image is immutable. */ - public Graphics getGraphics() { - if (mutable) { - if (imageGraphics == null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + public Graphics getGraphics() + { + if(mutable) + { + if(imageGraphics == null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { // instantiate the Graphics object imageGraphics = new Graphics(); // bind the GC to the Image target @@ -691,7 +797,8 @@ * * @return Image width. */ - public int getWidth() { + public int getWidth() + { return eswtImageWidth; } @@ -700,7 +807,8 @@ * * @return Image height. */ - public int getHeight() { + public int getHeight() + { return eswtImageHeight; } @@ -709,7 +817,8 @@ * * @return true, if image is mutable. */ - public boolean isMutable() { + public boolean isMutable() + { return mutable; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItem.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItem.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItem.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -24,7 +24,8 @@ * must call setImage()-method again if modifications need to appear in * ImageItem too. */ -public class ImageItem extends Item { +public class ImageItem extends Item +{ /** * Left here for source compatibility purposes. Use layout directives from @@ -76,7 +77,8 @@ * displayed for some reason. * @throws IllegalArgumentException if Layout is invalid. */ - public ImageItem(String label, Image image, int layout, String altText) { + public ImageItem(String label, Image image, int layout, String altText) + { this(label, image, layout, altText, Item.PLAIN); } @@ -93,12 +95,14 @@ * @throws IllegalArgumentException if Layout is invalid. */ public ImageItem(String label, Image image, int layout, String altText, - int appMode) { + int appMode) + { - if (appMode != Item.PLAIN && appMode != Item.BUTTON - && appMode != Item.HYPERLINK) { + if(appMode != Item.PLAIN && appMode != Item.BUTTON + && appMode != Item.HYPERLINK) + { throw new IllegalArgumentException( - MsgRepository.IMAGEITEM_EXCEPTION_INVALID_APPMODE); + MsgRepository.IMAGEITEM_EXCEPTION_INVALID_APPMODE); } setLabel(label); @@ -113,7 +117,8 @@ * * @return Image-object. */ - public Image getImage() { + public Image getImage() + { return image; } @@ -122,7 +127,8 @@ * * @param image Image to be set. */ - public void setImage(Image image) { + public void setImage(Image image) + { this.image = image; updateParent(UPDATE_SIZE_CHANGED); } @@ -132,7 +138,8 @@ * * @return Alternate text or null if no alternate text defined. */ - public String getAltText() { + public String getAltText() + { return alternateText; } @@ -141,7 +148,8 @@ * * @param newAltText Alternate text to be set. */ - public void setAltText(String newAltText) { + public void setAltText(String newAltText) + { alternateText = newAltText; updateParent(UPDATE_SIZE_CHANGED); } @@ -151,14 +159,16 @@ * * @return Appearance mode. */ - public int getAppearanceMode() { + public int getAppearanceMode() + { return appearanceMode; } /* (non-Javadoc) * @see javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return (getNumCommands() > 0); } @@ -167,7 +177,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return ImageItemLayouter.calculateMinimumBounds(this); } @@ -176,7 +187,8 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return ImageItemLayouter.calculatePreferredBounds(this); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItemLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItemLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ImageItemLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,58 +11,167 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.*; +import org.eclipse.ercp.swt.mobile.CaptionedControl; /** * Corresponds for correct layouting of ImageItems. */ -class ImageItemLayouter extends ItemLayouter { +class ImageItemLayouter extends ItemLayouter +{ /** * Constructor. * * @param dflp - DefaultFormLayoutPolicy used for layouting. */ - ImageItemLayouter(DefaultFormLayoutPolicy dflp) { + ImageItemLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } - int eswtGetLabelAlignmentDirective() { + int eswtGetLabelAlignmentDirective() + { return Item.LAYOUT_BOTTOM; } /** - * Creates the eSWT Button or Label for this item. + * Layout Item in a row. + * + * @param row current Row + * @param item Item to layout + */ + void eswtLayoutItem(Row row, Item item) + { + LayoutObject lo = new LayoutObject(item, eswtGetControl(formComposite, item)); + dfi.eswtAddNewLayoutObject(lo); + } + + /** + * Creates the eSWT CaptionedControl or Composite for this item. */ - Control eswtGetControl(Composite parent, Item item) { - ImageItem imgItem = (ImageItem) item; - if (item.getNumCommands() == 0) { - Label label = new Label(parent, SWT.NONE); - label.setImage(Image.getESWTImage(imgItem.getImage())); - label.pack(); - return label; + Control eswtGetControl(Composite parent, Item item) + { + Control ret = eswtCreateControl(parent, item); + Point size = new Point(0,0); + size.x = item.getLayoutWidth(); + size.y = item.getLayoutHeight(); + eswtCaptionedResize(item, ret, size.x, size.y); + return ret; + } + + /** + * Creates the eSWT CaptionedControl or Composite for this item. + */ + static Control eswtCreateControl(Composite parent, Item item) + { + if(item.hasLabel()) + { + CaptionedControl captioned = new CaptionedControl(parent, SWT.VERTICAL); + captioned.setText(item.getLabel()); + eswtSpecificControl(captioned, item); + return captioned; + } + else + { + Control ret = eswtSpecificControl(parent, item); + return ret; } - else { + } + + /** + * Creates the eSWT specific control for this item. + */ + static Control eswtSpecificControl(Composite parent, Item item) + { + ImageItem imgItem = (ImageItem) item; + + if(item.getNumCommands() == 0) + { + Label imageLabel = new Label(parent, SWT.CENTER); + imageLabel.setImage(Image.getESWTImage(imgItem.getImage())); + imageLabel.pack(); + int imageWidth = imageLabel.getBounds().width; + int imageHeight = imageLabel.getBounds().height; + int maxWidth = getMaximumItemWidth(item); + if(imageWidth > maxWidth) + { + Point size = imageLabel.computeSize(maxWidth, SWT.DEFAULT); + //Image Resize has to be done. + imageLabel.setSize(size.x, size.y); + imageWidth = size.x; + imageHeight = size.y; + } + + if(imgItem.hasLabel()) + { + int labelWidth = Font.getDefaultFont().stringWidth(imgItem.getLabel()); + + if(labelWidth > imageWidth) + { + Point size = parent.computeSize(Math.min(labelWidth, maxWidth), SWT.DEFAULT); + parent.setSize(size.x, size.y); + } + else + { + parent.pack(); + } + } + + return imageLabel; + } + else + { Button button; - switch (imgItem.getAppearanceMode()) { - case ImageItem.BUTTON: - button = new Button(parent, SWT.PUSH); - break; - case ImageItem.HYPERLINK: - case ImageItem.PLAIN: - default: - button = new Button(parent, SWT.FLAT); - break; + + switch(imgItem.getAppearanceMode()) + { + case ImageItem.BUTTON: + button = new Button(parent, SWT.PUSH | SWT.NONE); + break; + case ImageItem.HYPERLINK: + case ImageItem.PLAIN: + default: + button = new Button(parent, SWT.FLAT | SWT.NONE); + break; } button.setImage(Image.getESWTImage(imgItem.getImage())); button.pack(); + int buttonWidth = button.getBounds().width; + int buttonHeight = button.getBounds().height; + int maxWidth = getMaximumItemWidth(item); + if(buttonWidth > maxWidth) + { + Point size = button.computeSize(maxWidth, SWT.DEFAULT); + //Image Resize has to be done. + button.setSize(size.x, size.y); + buttonWidth = size.x; + buttonHeight = size.y; + } + + if(imgItem.hasLabel()) + { + int labelWidth = Font.getDefaultFont().stringWidth(imgItem.getLabel()); + + if(labelWidth > buttonWidth) + { + Point size = parent.computeSize(Math.min(labelWidth, maxWidth), SWT.DEFAULT); + parent.setSize(size.x, size.y); + } + else + { + parent.pack(); + } + } + return button; } } @@ -70,15 +179,17 @@ /** * Returns if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { // No implementation needed - return ((control instanceof Label) || (control instanceof Button)); // default + return ((control instanceof Label) || (control instanceof Button)); } /** * Updates the values of ImageItem. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { // No implementation needed } @@ -88,24 +199,53 @@ * @param imageItem ImageItem object. * @return Minimum area needed to display ImageItem. */ - static Point calculateMinimumBounds(ImageItem imageItem) { - Display disp = Display.getDisplay(); - final Point minSize = new Point( - disp.getBestImageWidth(Display.CHOICE_GROUP_ELEMENT), - disp.getBestImageHeight(Display.CHOICE_GROUP_ELEMENT)); - - Image image = imageItem.getImage(); - if (image != null) { - int actualImageWidth = image.getWidth(); - if ((actualImageWidth < minSize.x) || (minSize.x == 0)) { - minSize.x = actualImageWidth; + static Point calculateMinimumBounds(final ImageItem imageItem) + { + final Point minSize = new Point(0, 0); + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + Point size = null; + if(imageItem.getNumCommands() > 0) + { + Button button = new Button(eswtGetStaticShell(), SWT.PUSH); + button.setImage(Image.getESWTImage(imageItem.getImage())); + button.pack(); + int buttonWidth = button.getBounds().width; + int maxWidth = getMaximumItemWidth(imageItem); + if(buttonWidth > maxWidth) + { + size = button.computeSize(maxWidth, SWT.DEFAULT); + } + else + { + size = button.computeSize(SWT.DEFAULT, SWT.DEFAULT); + } + button.dispose(); + } + else + { + Label imageLabel = new Label(eswtGetStaticShell(), SWT.NONE); + imageLabel.setImage(Image.getESWTImage(imageItem.getImage())); + imageLabel.pack(); + int imageWidth = imageLabel.getBounds().width; + int maxWidth = getMaximumItemWidth(imageItem); + if(imageWidth > maxWidth) + { + size = imageLabel.computeSize(maxWidth, SWT.DEFAULT); + } + else + { + size = imageLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT); + } + imageLabel.dispose(); + } + minSize.x = size.x; + minSize.y = size.y; + applyMinMargins(imageItem, minSize); } - int actualImageHeight = image.getHeight(); - if ((actualImageHeight < minSize.y) || (minSize.y == 0)) { - minSize.y = actualImageHeight; - } - } - applyMinMargins(imageItem, minSize); + }); return minSize; } @@ -116,14 +256,20 @@ * @return Preferred area needed to display Item. x is width and y is * height. */ - static Point calculatePreferredBounds(final ImageItem imageItem) { + static Point calculatePreferredBounds(final ImageItem imageItem) + { final Point prefSize = new Point(0, 0); - Image image = imageItem.getImage(); - if (image != null) { - prefSize.x = image.getWidth(); - prefSize.y = image.getHeight(); - } - applyPrefMargins(imageItem, prefSize); + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + Control ctrl = eswtCreateControl(eswtGetStaticShell(), imageItem); + Point size = ctrl.getSize(); + ctrl.dispose(); + prefSize.x = size.x; + prefSize.y = size.y; + } + }); return prefSize; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Item.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Item.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Item.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,13 +19,14 @@ import java.util.Vector; import javax.microedition.lcdui.EventDispatcher.LCDUIEvent; - +import com.nokia.mj.impl.nokialcdui.ItemControlStateChangeListener; import org.eclipse.swt.graphics.Point; /** * Abstract class representing an item.
            */ -public abstract class Item { +public abstract class Item +{ /** * A layout directive. @@ -116,7 +117,7 @@ * Combination of all possible layout directives. */ private static final int LAYOUT_BITMASK = - LAYOUT_DEFAULT + LAYOUT_DEFAULT | LAYOUT_LEFT | LAYOUT_RIGHT | LAYOUT_CENTER @@ -173,6 +174,7 @@ */ private Vector commands = new Vector(); private ItemCommandListener itemCommandListener; + private ItemControlStateChangeListener controlListener; private Command defaultCommand; private Screen parent; @@ -191,7 +193,8 @@ * Sets the parent of this Item. * @param parent new Parent. If null, current parent is removed. */ - void setParent(Screen parent) { + void setParent(Screen parent) + { this.parent = parent; } @@ -200,7 +203,8 @@ * * @return the Item's parent or null if it has none. */ - Screen getParent() { + Screen getParent() + { return parent; } @@ -210,10 +214,12 @@ * @param newLabel New label to be set. * @throws IllegalStateException If this item is contained within an alert. */ - public void setLabel(String newLabel) { - if (isContainedInAlert()) { + public void setLabel(String newLabel) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } label = newLabel; updateParent(UPDATE_SIZE_CHANGED); @@ -224,14 +230,16 @@ * * @return The label of the item. */ - public String getLabel() { + public String getLabel() + { return label; } /** * Returns if this item has a valid label, not null and not empty. */ - boolean hasLabel() { + boolean hasLabel() + { return ((label != null) && (!label.equals(""))); } @@ -240,7 +248,8 @@ * * @return A combination of layout directives currently in use. */ - public int getLayout() { + public int getLayout() + { return layout; } @@ -252,15 +261,18 @@ * combination of layout directives spesified in this class. * @throws IllegalStateException If this Item is contained within an Alert. */ - public void setLayout(int newLayout) { - if (isContainedInAlert()) { + public void setLayout(int newLayout) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } - if (!isValidLayout(newLayout)) { + if(!isValidLayout(newLayout)) + { throw new IllegalArgumentException( - MsgRepository.ITEM_EXCEPTION_INVALID_LAYOUT); + MsgRepository.ITEM_EXCEPTION_INVALID_LAYOUT); } layout = newLayout; Logger.method(this, "setLayout", String.valueOf(layout)); @@ -275,24 +287,30 @@ * @throws NullPointerException if cmd is null. * @throws IllegalStateException If this Item is contained within an Alert. */ - public void addCommand(Command command) { - if (isContainedInAlert()) { + public void addCommand(Command command) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } - if (command == null) { + if(command == null) + { throw new NullPointerException( - MsgRepository.ITEM_EXCEPTION_NULL_COMMAND_ADDED); + MsgRepository.ITEM_EXCEPTION_NULL_COMMAND_ADDED); } - if (!commands.contains(command)) { + if(!commands.contains(command)) + { commands.addElement(command); int reason = UPDATE_ADDCOMMAND; - if (this instanceof StringItem && commands.size() == 1) { + if(this instanceof StringItem && commands.size() == 1) + { reason |= UPDATE_SIZE_CHANGED; } - if (this instanceof ImageItem && commands.size() == 1) { + if(this instanceof ImageItem && commands.size() == 1) + { reason |= UPDATE_SIZE_CHANGED; } @@ -306,19 +324,25 @@ * * @param command The command to be removed. */ - public void removeCommand(Command command) { + public void removeCommand(Command command) + { // It is not specified what should happen when this method is // called with null-parameter ! - if (command != null && commands.contains(command)) { + if(command != null && commands.contains(command)) + { // Remove command from commands-vector commands.removeElement(command); + defaultCommand = null; + int reason = UPDATE_REMOVECOMMAND; - if (this instanceof StringItem && commands.size() == 0) { + if(this instanceof StringItem && commands.size() == 0) + { reason |= UPDATE_SIZE_CHANGED; } - if (this instanceof ImageItem && commands.size() == 0) { + if(this instanceof ImageItem && commands.size() == 0) + { reason |= UPDATE_SIZE_CHANGED; } @@ -335,10 +359,12 @@ * listener is removed. * @throws IllegalStateException If this Item is contained within an Alert. */ - public void setItemCommandListener(ItemCommandListener newItemCmdListener) { - if (isContainedInAlert()) { + public void setItemCommandListener(ItemCommandListener newItemCmdListener) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } itemCommandListener = newItemCmdListener; } @@ -348,7 +374,8 @@ * * @return Minimum width. */ - public int getMinimumWidth() { + public int getMinimumWidth() + { return getCalculatedMinimumSize().x; } @@ -357,12 +384,15 @@ * * @return Minimum height. */ - public int getMinimumHeight() { + public int getMinimumHeight() + { return getCalculatedMinimumSize().y; } - private Point getCalculatedMinimumSize() { - if (calculatedMinSize == null) { + private Point getCalculatedMinimumSize() + { + if(calculatedMinSize == null) + { calculatedMinSize = calculateMinimumSize(); // Logger.method(this, "calculateMinimumSize", calculatedMinSize); } @@ -381,14 +411,18 @@ * * @return Preferred width. */ - public int getPreferredWidth() { - if (lockedPrefWidth >= 0) { - if (calculatedMinSize == null) { + public int getPreferredWidth() + { + if(lockedPrefWidth >= 0) + { + if(calculatedMinSize == null) + { checkLockedSizes(); } return lockedPrefWidth; } - else { + else + { return getCalculatedPreferredSize().x; } } @@ -398,33 +432,42 @@ * * @return Preferred height. */ - public int getPreferredHeight() { - if (lockedPrefHeight >= 0) { - if (calculatedMinSize == null) { + public int getPreferredHeight() + { + if(lockedPrefHeight >= 0) + { + if(calculatedMinSize == null) + { checkLockedSizes(); } return lockedPrefHeight; } - else { + else + { return getCalculatedPreferredSize().y; } } - private Point getCalculatedPreferredSize() { - if (calculatedPrefSize == null) { + private Point getCalculatedPreferredSize() + { + if(calculatedPrefSize == null) + { calculatedPrefSize = calculatePreferredSize(); // Logger.method(this, "calculatePreferredSize", calculatedPrefSize); } return calculatedPrefSize; } - void checkLockedSizes() { - if (lockedPrefWidth >= 0) { + void checkLockedSizes() + { + if(lockedPrefWidth >= 0) + { lockedPrefWidth = Math.min( - Math.max(lockedPrefWidth, getMinimumWidth()), - ItemLayouter.getMaximumItemWidth(null)); + Math.max(lockedPrefWidth, getMinimumWidth()), + ItemLayouter.getMaximumItemWidth(null)); } - if (lockedPrefHeight >= 0) { + if(lockedPrefHeight >= 0) + { lockedPrefHeight = Math.max(lockedPrefHeight, getMinimumHeight()); } } @@ -433,7 +476,8 @@ * Invalidates this Item's calculated preferred size. Forces the * implementation to calculate it again. */ - void invalidateCachedSizes() { + void invalidateCachedSizes() + { calculatedMinSize = null; calculatedPrefSize = null; } @@ -456,22 +500,25 @@ * @throws IllegalArgumentException if w or h is less than -1. * @throws IllegalStateException If this Item is contained within an Alert. */ - public synchronized void setPreferredSize(int w, int h) { - if (isContainedInAlert()) { + public synchronized void setPreferredSize(int w, int h) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } - if ((w < -1) || (h < -1)) { + if((w < -1) || (h < -1)) + { throw new IllegalArgumentException( - MsgRepository.ITEM_EXCEPTION_INVALID_DIMENSION); + MsgRepository.ITEM_EXCEPTION_INVALID_DIMENSION); } lockedPrefWidth = w; lockedPrefHeight = h; checkLockedSizes(); Logger.method(this, "setPrefSize", - String.valueOf(lockedPrefWidth), - String.valueOf(lockedPrefHeight)); + String.valueOf(lockedPrefWidth), + String.valueOf(lockedPrefHeight)); updateParent(UPDATE_SIZE_CHANGED); } @@ -484,13 +531,16 @@ * command at all after this call. * @throws IllegalStateException If this Item is contained within an Alert. */ - public void setDefaultCommand(Command cmd) { - if (isContainedInAlert()) { + public void setDefaultCommand(Command cmd) + { + if(isContainedInAlert()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); + MsgRepository.ITEM_EXCEPTION_OWNED_BY_ALERT); } defaultCommand = cmd; - if (cmd != null) { + if(cmd != null) + { // It is safe to call addCommand() even if command already exists // because the addCommand() wont create duplicates: addCommand(cmd); @@ -510,10 +560,12 @@ * * @throws IllegalStateException If the item is not owned by a form. */ - public void notifyStateChanged() { - if (!isContainedInForm()) { + public void notifyStateChanged() + { + if(!isContainedInForm()) + { throw new IllegalStateException( - MsgRepository.ITEM_EXCEPTION_NOT_OWNED_BY_FORM); + MsgRepository.ITEM_EXCEPTION_NOT_OWNED_BY_FORM); } // Notify item state listener ((Form) parent).notifyItemStateChanged(this); @@ -522,7 +574,8 @@ /** * Is this item's size locked. */ - boolean isSizeLocked() { + boolean isSizeLocked() + { return (lockedPrefWidth >= 0) || (lockedPrefHeight >= 0); } @@ -531,7 +584,8 @@ * * @return Locked preferred width. If width is not locked, returns -1. */ - int getLockedPreferredWidth() { + int getLockedPreferredWidth() + { return lockedPrefWidth; } @@ -540,15 +594,18 @@ * * @return Locked preferred height. If height is not locked, returns -1. */ - int getLockedPreferredHeight() { + int getLockedPreferredHeight() + { return lockedPrefHeight; } /** * Gets LAYOUT_2 width of this item. */ - int getLayoutWidth() { - if (hasLayout(LAYOUT_SHRINK)) { + int getLayoutWidth() + { + if(hasLayout(LAYOUT_SHRINK)) + { return getMinimumWidth(); } return getPreferredWidth(); @@ -557,8 +614,10 @@ /** * Gets LAYOUT_2 height of this item. */ - int getLayoutHeight() { - if (hasLayout(LAYOUT_VSHRINK)) { + int getLayoutHeight() + { + if(hasLayout(LAYOUT_VSHRINK)) + { return getMinimumHeight(); } return getPreferredHeight(); @@ -567,14 +626,16 @@ /** * If the item is owned by an Alert. */ - boolean isContainedInAlert() { + boolean isContainedInAlert() + { return (parent != null && parent instanceof Alert); } /** * If the item is owned by an Form. */ - boolean isContainedInForm() { + boolean isContainedInForm() + { return (parent != null && parent instanceof Form); } @@ -583,14 +644,16 @@ * * @return layout directive */ - int internalGetLayout() { + int internalGetLayout() + { return getLayout(); } /** * Updates the parent if it's a Form. */ - void updateParent(int updateReason) { + void updateParent(int updateReason) + { updateParent(updateReason, null); } @@ -599,16 +662,20 @@ * * @param param additional parameter */ - void updateParent(int updateReason, Object param) { - if ((updateReason & UPDATE_SIZE_CHANGED) != 0) { + void updateParent(int updateReason, Object param) + { + if((updateReason & UPDATE_SIZE_CHANGED) != 0) + { invalidateCachedSizes(); } - if (isContainedInForm()) { + if(isContainedInForm()) + { ((Form) parent).updateItemState(this, updateReason, param); } } - boolean hasLayout(int aLayout) { + boolean hasLayout(int aLayout) + { return (getLayout() & aLayout) != 0; } @@ -619,8 +686,10 @@ * @param layout Layout combination to be check. * @return true If provided layout is valid. */ - static boolean isValidLayout(int layout) { - if ((layout & (0xffffffff ^ LAYOUT_BITMASK)) != 0) { + static boolean isValidLayout(int layout) + { + if((layout & (0xffffffff ^ LAYOUT_BITMASK)) != 0) + { return false; } return true; @@ -633,7 +702,8 @@ * @param layout item Layout. * @return horizontal layout of an Item. */ - static int getHorizontalLayout(int layout) { + static int getHorizontalLayout(int layout) + { return layout & Item.LAYOUT_HORIZONTAL_MASK; } @@ -644,22 +714,26 @@ * @param layout item Layout. * @return vertical layout of an Item. */ - static int getVerticalLayout(int layout) { + static int getVerticalLayout(int layout) + { return layout & Item.LAYOUT_VERTICAL_MASK; } /** * Is item focusable. */ - boolean isFocusable() { + boolean isFocusable() + { return false; } /** * Sets current item as focused */ - void internalSetFocused(boolean isFocused) { - if (isFocusable()) { + void internalSetFocused(boolean isFocused) + { + if(isFocusable()) + { focused = isFocused; } } @@ -669,14 +743,16 @@ * * @return true if item has focus. */ - boolean isFocused() { + boolean isFocused() + { return focused; } /** * Sets current item visibility */ - void internalSetVisible(boolean isVisible) { + void internalSetVisible(boolean isVisible) + { this.visible = isVisible; } @@ -685,7 +761,8 @@ * * @return true if item is visible */ - boolean isVisible() { + boolean isVisible() + { return visible; } @@ -694,7 +771,8 @@ * * @return number of commands. */ - int getNumCommands() { + int getNumCommands() + { return commands.size(); } @@ -703,19 +781,23 @@ * * @return Default command or null if no default set. */ - Command getDefaultCommand() { + Command getDefaultCommand() + { return defaultCommand; } /** * Returns the Default Command or if not set, then the first Command. */ - Command getMSKCommand() { + Command getMSKCommand() + { Command ret = null; - if (defaultCommand != null) { + if(defaultCommand != null) + { ret = defaultCommand; } - else if (commands.elementAt(0) != null) { + else if(getNumCommands() == 1) + { ret = (Command) commands.elementAt(0); } return ret; @@ -726,15 +808,17 @@ * * @param command the Command */ - void callCommandAction(Command command) { - if (itemCommandListener != null && command != null) { - EventDispatcher eventDispatcher = EventDispatcher.instance(); - LCDUIEvent event = eventDispatcher.newEvent( - LCDUIEvent.ITEM_COMMANDACTION, - this); - event.command = command; - event.itemCommandListener = itemCommandListener; - eventDispatcher.postEvent(event); + void callCommandAction(Command command) + { + if(itemCommandListener != null && command != null) + { + EventDispatcher eventDispatcher = EventDispatcher.instance(); + LCDUIEvent event = eventDispatcher.newEvent( + LCDUIEvent.ITEM_COMMANDACTION, + this); + event.command = command; + event.itemCommandListener = itemCommandListener; + eventDispatcher.postEvent(event); } } @@ -744,7 +828,8 @@ * @return Vector of commands added to this item. * Vector may be empty but not null. */ - Vector getCommands() { + Vector getCommands() + { return commands; } @@ -753,18 +838,31 @@ * @return Current ItemCommandListener or null if * no listener set. */ - ItemCommandListener getItemCommandListener() { + ItemCommandListener getItemCommandListener() + { return itemCommandListener; } + void setItemControlStateChangeListener(ItemControlStateChangeListener listener) + { + controlListener = listener; + } + + ItemControlStateChangeListener getItemControlStateChangeListener() + { + return controlListener; + } + /* - * Dispatcher thread calls. + * Dispatcher thread calls. */ - void doCallback(LCDUIEvent event) { - switch(event.type) { - case LCDUIEvent.ITEM_COMMANDACTION: - event.itemCommandListener.commandAction(event.command, this); - break; - } + void doCallback(LCDUIEvent event) + { + switch(event.type) + { + case LCDUIEvent.ITEM_COMMANDACTION: + event.itemCommandListener.commandAction(event.command, this); + break; + } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ItemCommandListener.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemCommandListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemCommandListener.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,11 +19,12 @@ /** * Listener which receives events from commands associated with item. */ -public interface ItemCommandListener { +public interface ItemCommandListener +{ /** * Called when event occurred. - * + * * @param command Command which invoked the event. * @param item Item containing the command. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ItemLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,10 +25,13 @@ import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.*; +import com.nokia.mj.impl.nokialcdui.ItemControlStateChangeListener; + /** * Abstract base class for Item layouters. */ -abstract class ItemLayouter { +abstract class ItemLayouter +{ /** * Key name for paint listener. @@ -56,10 +59,12 @@ * * @return Static Shell. Never null. */ - static MobileShell eswtGetStaticShell() { - if (staticShell == null) { + static MobileShell eswtGetStaticShell() + { + if(staticShell == null) + { staticShell = new MobileShell(ESWTUIThreadRunner.getInstance() - .getDisplay(), SWT.SYSTEM_MODAL | SWT.VERTICAL); + .getDisplay(), SWT.SYSTEM_MODAL | SWT.VERTICAL); staticShell.getVerticalBar().setVisible(true); formWidth = staticShell.getClientArea().width; formHeigh = staticShell.getClientArea().height; @@ -70,8 +75,10 @@ /** * Gets static singleton off-screen Label control. */ - private static Label eswtGetStaticLabel() { - if (staticLabel == null) { + private static Label eswtGetStaticLabel() + { + if(staticLabel == null) + { staticLabel = new Label(eswtGetStaticShell(), SWT.NONE); } return staticLabel; @@ -80,8 +87,10 @@ /** * Gets static singleton off-screen Captioned control. */ - private static CaptionedControl eswtGetStaticCC() { - if (staticCC == null) { + private static CaptionedControl eswtGetStaticCC() + { + if(staticCC == null) + { staticCC = new CaptionedControl(eswtGetStaticShell(), SWT.VERTICAL); } return staticCC; @@ -90,8 +99,10 @@ /** * The static "layouting" shell's size is updated. */ - static void eswtUpdateStaticShellSize(int width, int height) { - if (staticShell != null) { + static void eswtUpdateStaticShellSize(int width, int height) + { + if(staticShell != null) + { staticShell.setBounds(staticShell.computeTrim(0, 0, width, height)); formWidth = width; formHeigh = height; @@ -103,11 +114,14 @@ * * @param dflp - DefaultFormLayoutPolicy used for layouting. */ - ItemLayouter(DefaultFormLayoutPolicy dflp) { + ItemLayouter(DefaultFormLayoutPolicy dflp) + { this.dfi = (DefaultFormInteraction) dflp; formComposite = dflp.getForm().getFormComposite(); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { ItemLayouter.eswtGetStaticShell(); } }); @@ -116,7 +130,8 @@ /** * Label alignment directive. */ - int eswtGetLabelAlignmentDirective() { + int eswtGetLabelAlignmentDirective() + { return dfi.getLanguageSpecificLayoutDirective(); } @@ -126,9 +141,19 @@ * @param row current Row * @param item Item to layout */ - void eswtLayoutItem(Row row, Item item) { + void eswtLayoutItem(Row row, Item item) + { LayoutObject lo = new LayoutObject(item, eswtGetCaptionedControl(item)); dfi.eswtAddNewLayoutObject(lo); + if(item instanceof CustomItem) + { + ItemControlStateChangeListener listener = item.getItemControlStateChangeListener(); + if(null != listener) + { + listener.notifyControlAvailable(lo.getControl(),item); + lo.getControl().addListener(SWT.Dispose, new EventListener(item)); + } + } } /** @@ -142,15 +167,18 @@ * * @param item Item to be layouted */ - final Control eswtGetCaptionedControl(Item item) { - if (item.hasLabel()) { + final Control eswtGetCaptionedControl(Item item) + { + if(item.hasLabel()) + { CaptionedControl captioned = new CaptionedControl(formComposite, SWT.VERTICAL); captioned.setText(item.getLabel()); eswtGetControl(captioned, item); eswtCaptionedResize(item, captioned, item.getLayoutWidth(), item.getLayoutHeight()); return captioned; } - else { + else + { Control ret = eswtGetControl(formComposite, item); eswtCaptionedResize(item, ret, item.getLayoutWidth(), item.getLayoutHeight()); return ret; @@ -169,7 +197,8 @@ /** * Update size of an LayoutObject. */ - final void eswtResizeObject(LayoutObject lo) { + final void eswtResizeObject(LayoutObject lo) + { Item item = lo.getOwningItem(); eswtCaptionedResize(item, lo.getControl(), item.getLayoutWidth(), item.getLayoutHeight()); lo.eswtUpdateSize(); @@ -182,22 +211,26 @@ * @param width * @param height */ - final void eswtResizeObject(LayoutObject lo, int width, int height) { + final void eswtResizeObject(LayoutObject lo, int width, int height) + { eswtCaptionedResize(lo.getOwningItem(), lo.getControl(), width, height); lo.eswtUpdateSize(); } - final void eswtCaptionedResize(Item item, Control control, int width, int height) { - if (control instanceof CaptionedControl) { + final void eswtCaptionedResize(Item item, Control control, int width, int height) + { + if(control instanceof CaptionedControl) + { CaptionedControl cc = (CaptionedControl) control; cc.setSize(width, height); Rectangle ccArea = cc.getClientArea(); eswtResizeControl(item, eswtFindSpecificControl(item, control), - ccArea.width, ccArea.height); + ccArea.width, ccArea.height); } - else { + else + { eswtResizeControl(item, eswtFindSpecificControl(item, control), - width, height); + width, height); } } @@ -209,7 +242,8 @@ * @param width item width. * @param height item height */ - void eswtResizeControl(Item item, Control control, int width, int height) { + void eswtResizeControl(Item item, Control control, int width, int height) + { control.setSize(width, height); } @@ -219,13 +253,16 @@ * @param item Item * @param lo LayoutObject */ - void eswtAddListeners(Item item, LayoutObject lo) { + void eswtAddListeners(Item item, LayoutObject lo) + { lo.eswtAddSelectionListenerForCommands(); Control specific = eswtFindSpecificControl(item, lo.getControl()); - if (specific != null) { + if(specific != null) + { eswtAddSpecificListeners(item, specific); } - else { + else + { Logger.warning(this + "::eswtAddListeners didnt find control for " + item); } } @@ -236,8 +273,10 @@ * @param item Item * @param control specific Control */ - void eswtAddSpecificListeners(Item item, Control control) { - if (item.isFocusable()) { + void eswtAddSpecificListeners(Item item, Control control) + { + if(item.isFocusable()) + { ItemFocusListener ifl = new ItemFocusListener(item); control.addFocusListener(ifl); control.setData(FOCUS_LISTENER, ifl); @@ -250,13 +289,16 @@ * @param item Item * @param lo LayoutObject */ - void eswtRemoveListeners(Item item, LayoutObject lo) { + void eswtRemoveListeners(Item item, LayoutObject lo) + { lo.eswtRemoveSelectionListenerForCommands(); Control specific = eswtFindSpecificControl(item, lo.getControl()); - if (specific != null) { + if(specific != null) + { eswtRemoveSpecificListeners(item, specific); } - else { + else + { Logger.warning(this + "::eswtRemoveListeners didnt find control for " + item); } } @@ -267,11 +309,14 @@ * @param item Item * @param control specific Control */ - void eswtRemoveSpecificListeners(Item item, Control control) { - if (item.isFocusable()) { + void eswtRemoveSpecificListeners(Item item, Control control) + { + if(item.isFocusable()) + { ItemFocusListener ifl = (ItemFocusListener) control - .getData(FOCUS_LISTENER); - if (ifl != null) { + .getData(FOCUS_LISTENER); + if(ifl != null) + { control.removeFocusListener(ifl); control.setData(FOCUS_LISTENER, null); } @@ -286,22 +331,29 @@ * @param param optional parameter */ final void updateItem(final Item item, final Control control, - final int reason, final Object param) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + final int reason, final Object param) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Control specific = eswtFindSpecificControl(item, control); - if (specific != null) { - if (!specific.isDisposed()) { + if(specific != null) + { + if(!specific.isDisposed()) + { eswtUpdateItem(item, specific, reason, param); } - else { + else + { Logger.warning(ItemLayouter.this - + "::updateItem found a disposed widget for " + item); + + "::updateItem found a disposed widget for " + item); } } - else { + else + { Logger.warning(ItemLayouter.this - + "::updateItem didnt find control for " + item); + + "::updateItem didnt find control for " + item); } } }); @@ -316,7 +368,7 @@ * @param param optional parameter */ abstract void eswtUpdateItem(Item item, Control control, int reason, - Object param); + Object param); /** * Finds the Layouter specific eSWT control in the eSWT Composite tree. @@ -325,16 +377,21 @@ * @param control eSWT control * @return a specific control or null if not found */ - final Control eswtFindSpecificControl(Item item, Control control) { + final Control eswtFindSpecificControl(Item item, Control control) + { Control ret = null; - if (eswtIsSpecificControl(item, control)) { + if(eswtIsSpecificControl(item, control)) + { ret = control; } - else if (control != null && control instanceof Composite) { + else if(control != null && control instanceof Composite) + { Control[] children = ((Composite) control).getChildren(); - for (int i = 0; i < children.length; i++) { + for(int i = 0; i < children.length; i++) + { Control result = eswtFindSpecificControl(item, children[i]); - if (result != null) { + if(result != null) + { ret = result; break; } @@ -351,7 +408,8 @@ * @return Preferred area needed to display Item. x is width * and y is height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { return new Point(0, 0); } @@ -370,9 +428,11 @@ * @param item Item * @return layouted Control */ - Control eswtGetFirstControl(Item item) { + Control eswtGetFirstControl(Item item) + { LayoutObject lo = dfi.getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { return lo.getControl(); } return null; @@ -384,11 +444,14 @@ * @param item Item * @return layouted specific Control */ - Control eswtGetFirstSpecificControl(Item item) { + Control eswtGetFirstSpecificControl(Item item) + { LayoutObject lo = dfi.getFirstLayoutObjectOfItem(item); - if (lo != null) { + if(lo != null) + { Control control = lo.getControl(); - if (control != null) { + if(control != null) + { return eswtFindSpecificControl(item, control); } } @@ -404,29 +467,36 @@ * @param type eSWT key type * @return if the key was consumed or not */ - boolean eswtOfferKeyEvent(Item item, int key, int type) { - if (type == SWT.KeyDown) { + boolean eswtOfferKeyEvent(Item item, int key, int type) + { + if(type == SWT.KeyDown) + { return eswtOfferKeyPressed(item, key); } - else if (type == SWT.KeyUp) { + else if(type == SWT.KeyUp) + { return eswtOfferKeyReleased(item, key); } - else { + else + { return eswtOfferKeyRepeated(item, key); } } - boolean eswtOfferKeyPressed(Item item, int key) { + boolean eswtOfferKeyPressed(Item item, int key) + { // Do not consume these by default return false; } - boolean eswtOfferKeyRepeated(Item item, int key) { + boolean eswtOfferKeyRepeated(Item item, int key) + { // Do not consume these by default return false; } - boolean eswtOfferKeyReleased(Item item, int key) { + boolean eswtOfferKeyReleased(Item item, int key) + { // Do not consume these by default return false; } @@ -437,7 +507,8 @@ * @param item * @param dir */ - void eswtFocusGained(Item item, int dir) { + void eswtFocusGained(Item item, int dir) + { Logger.method(item, "focusGained", String.valueOf(dir)); item.internalSetFocused(true); } @@ -447,18 +518,23 @@ * * @param item item which looses focus. */ - void eswtFocusLost(Item item) { + void eswtFocusLost(Item item) + { Logger.method(item, "focusLost"); item.internalSetFocused(false); } - final void eswtHandleVisibilityChange(Item item, boolean visible) { - if (item.isVisible() != visible) { + final void eswtHandleVisibilityChange(Item item, boolean visible) + { + if(item.isVisible() != visible) + { item.internalSetVisible(visible); - if (visible) { + if(visible) + { eswtHandleShow(item); } - else { + else + { eswtHandleHide(item); } } @@ -469,7 +545,8 @@ * * @param item which becomes visible. */ - void eswtHandleShow(Item item) { + void eswtHandleShow(Item item) + { // Implementation not needed. Subclasses may override. } @@ -478,29 +555,37 @@ * * @param item which becomes hidden. */ - void eswtHandleHide(Item item) { + void eswtHandleHide(Item item) + { // Implementation not needed. Subclasses may override. } - static void applyMinMargins(Item item, Point size) { - if (item.hasLabel()) { + static void applyMinMargins(Item item, Point size) + { + if(item.hasLabel()) + { applyCaptionedTrim(MIN_TEXT, size); } size.x = Math.min(size.x, formWidth); } - static void applyPrefMargins(Item item, Point size) { - if (item.hasLabel()) { + static void applyPrefMargins(Item item, Point size) + { + if(item.hasLabel()) + { applyCaptionedTrim(item.getLabel(), size); } size.x = Math.min(size.x, formWidth); } - static final void applyCaptionedTrim(final String text, Point size) { + static final void applyCaptionedTrim(final String text, Point size) + { final Point localSize = size; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { CaptionedControl cc = eswtGetStaticCC(); cc.setText(text); Rectangle rect = cc.computeTrim(0, 0, localSize.x, localSize.y); @@ -520,10 +605,13 @@ * @param item * Item containing the label. */ - static Point getLabelSize(final String labelStr) { + static Point getLabelSize(final String labelStr) + { final Point size = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Label label = eswtGetStaticLabel(); label.setText(labelStr); Point temp = label.computeSize(SWT.DEFAULT, SWT.DEFAULT); @@ -543,15 +631,17 @@ * @return x-position of object */ static final int getXLocation(int owningWidth, int objectWidth, - int horizontalLayout) { - switch (horizontalLayout) { - case Item.LAYOUT_RIGHT: - return owningWidth - objectWidth; - case Item.LAYOUT_CENTER: - return (owningWidth - objectWidth) / 2; - case Item.LAYOUT_LEFT: - default: - return 0; + int horizontalLayout) + { + switch(horizontalLayout) + { + case Item.LAYOUT_RIGHT: + return owningWidth - objectWidth; + case Item.LAYOUT_CENTER: + return (owningWidth - objectWidth) / 2; + case Item.LAYOUT_LEFT: + default: + return 0; } } @@ -564,16 +654,18 @@ * @return y-position of object */ static final int getYLocation(int owningHeight, int objectHeight, - int verticalLayout) { - switch (verticalLayout) { - case Item.LAYOUT_VCENTER: - return (owningHeight - objectHeight) / 2; - case Item.LAYOUT_TOP: - return 0; - case Item.LAYOUT_BOTTOM: - return owningHeight - objectHeight; - default: - return owningHeight - objectHeight; + int verticalLayout) + { + switch(verticalLayout) + { + case Item.LAYOUT_VCENTER: + return (owningHeight - objectHeight) / 2; + case Item.LAYOUT_TOP: + return 0; + case Item.LAYOUT_BOTTOM: + return owningHeight - objectHeight; + default: + return owningHeight - objectHeight; } } @@ -586,8 +678,10 @@ * use item's parent to calculate the width. * @return Maximum width of an item. */ - static int getMaximumItemWidth(final Item item) { - if (item != null && item.hasLabel()) { + static int getMaximumItemWidth(final Item item) + { + if(item != null && item.hasLabel()) + { Point temp = new Point(0, 0); applyCaptionedTrim("", temp); return formWidth - temp.x; @@ -598,24 +692,41 @@ /** * Item focus Listener reacts on eSWT focusGained event. */ - class ItemFocusListener implements FocusListener { + class ItemFocusListener implements FocusListener + { private Item item; - ItemFocusListener(Item item) { + ItemFocusListener(Item item) + { this.item = item; } - public void focusGained(FocusEvent focusEvent) { - if (!item.isFocused()) { + public void focusGained(FocusEvent focusEvent) + { + if(!item.isFocused()) + { // Logger.method(item, "focusGained"); dfi.eswtSetCurrentSelectedItem(item); } } - public void focusLost(FocusEvent fe) { + public void focusLost(FocusEvent fe) + { // Logger.method(item, "focusLost"); } } + class EventListener implements Listener + { + Item itm; + EventListener(Item item) + { + itm = item; + } + public void handleEvent(Event e) + { + (itm.getItemControlStateChangeListener()).notifyControlDisposed(itm); + } + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ItemStateListener.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemStateListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ItemStateListener.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -19,11 +19,12 @@ /** * Listener that receives events when item's state is changed. */ -public interface ItemStateListener { +public interface ItemStateListener +{ /** * Called when item state is changed. - * + * * @param item The item which state is changed. */ void itemStateChanged(Item item); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/JadAttributeUtil.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/JadAttributeUtil.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/JadAttributeUtil.java Fri May 14 15:47:24 2010 +0300 @@ -22,130 +22,145 @@ * Utilities for reading and checking the UI related JAD attributes. * */ -final class JadAttributeUtil { +final class JadAttributeUtil +{ - // ***** ATTRIBUTE CONSTANTS ****** - /** - * jad attribute Nokia-UI-Enhancement - */ - final static String ATTRIB_NOKIA_UI_ENHANCEMENT = "Nokia-UI-Enhancement"; + // ***** ATTRIBUTE CONSTANTS ****** + /** + * jad attribute Nokia-UI-Enhancement + */ + final static String ATTRIB_NOKIA_UI_ENHANCEMENT = "Nokia-UI-Enhancement"; - /** - * jad attribute Nokia-MIDlet-S60-Selection-Key-Compatibility - */ - final static String ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY = "Nokia-MIDlet-S60-Selection-Key-Compatibility"; - /** - * jad attribute Nokia-MIDlet-No-Exit - */ - final static String ATTRIB_NOKIA_MIDLET_NO_EXIT = "Nokia-MIDlet-No-Exit"; + /** + * jad attribute Nokia-MIDlet-S60-Selection-Key-Compatibility + */ + final static String ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY = "Nokia-MIDlet-S60-Selection-Key-Compatibility"; + /** + * jad attribute Nokia-MIDlet-No-Exit + */ + final static String ATTRIB_NOKIA_MIDLET_NO_EXIT = "Nokia-MIDlet-No-Exit"; - /** - * jad attribute Nokia-MIDlet-Background-Event - */ - final static String ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT = "Nokia-MIDlet-Background-Event"; + /** + * jad attribute Nokia-MIDlet-Background-Event + */ + final static String ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT = "Nokia-MIDlet-Background-Event"; - /** - * jad attribute Nokia-MIDlet-Tap-Detection-Options - */ - final static String ATTRIB_NOKIA_MIDLET_TAP_DETECTION_OPTIONS = "Nokia-MIDlet-Tap-Detection-Options"; + /** + * jad attribute Nokia-MIDlet-Tap-Detection-Options + */ + final static String ATTRIB_NOKIA_MIDLET_TAP_DETECTION_OPTIONS = "Nokia-MIDlet-Tap-Detection-Options"; - /** - * jad attribute Nokia-MIDlet-On-Screen-Keypad - */ - final static String ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD= "Nokia-MIDlet-On-Screen-Keypad"; + /** + * jad attribute Nokia-MIDlet-On-Screen-Keypad + */ + final static String ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD= "Nokia-MIDlet-On-Screen-Keypad"; - /** - * jad attribute Nokia-MIDlet-App-Orientation - */ - final static String ATTRIB_NOKIA_MIDLET_APP_ORIENTATION = "Nokia-MIDlet-App-Orientation"; + /** + * jad attribute Nokia-MIDlet-App-Orientation + */ + final static String ATTRIB_NOKIA_MIDLET_APP_ORIENTATION = "Nokia-MIDlet-App-Orientation"; - /** - * jad attribute Nokia-MIDlet-Flip-Close - */ - final static String ATTRIB_NOKIA_MIDLET_FLIP_CLOSE ="Nokia-MIDlet-Flip-Close"; + /** + * jad attribute Nokia-MIDlet-Flip-Close + */ + final static String ATTRIB_NOKIA_MIDLET_FLIP_CLOSE ="Nokia-MIDlet-Flip-Close"; - // ***** VALUE CONSTANTS ***** + // ***** VALUE CONSTANTS ***** + + /** + * value CanvasHasBackground used with Nokia-UI-Enhancement + * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT + */ + final static String VALUE_CANVAS_HAS_BACKGROUND= "CanvasHasBackground"; - /** - * value CanvasHasBackground used with Nokia-UI-Enhancement - * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT - */ - final static String VALUE_CANVAS_HAS_BACKGROUND= "CanvasHasBackground"; + /** + * value MusicKeysSupported + * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT + */ + final static String VALUE_MUSIC_KEYS_SUPPORTED = "MusicKeysSupported"; + /** + * value true + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_NO_EXIT + */ + final static String VALUE_TRUE = "true"; + /** + * value pause + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_FLIP_CLOSE + */ + final static String VALUE_PAUSE = "pause"; - /** - * value MusicKeysSupported - * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT - */ - final static String VALUE_MUSIC_KEYS_SUPPORTED = "MusicKeysSupported"; - /** - * value true - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_S60_SELECTION_KEY_COMPATIBILITY - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_NO_EXIT - */ - final static String VALUE_TRUE = "true"; - /** - * value pause - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_BACKGROUND_EVENT - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_FLIP_CLOSE - */ - final static String VALUE_PAUSE = "pause"; + /** + * value no + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD + */ + final static String VALUE_NO = "no"; + + /** + * value gameactions + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD + */ + final static String VALUE_GAMEACTIONS ="gameactions"; - /** - * value no - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD - */ - final static String VALUE_NO = "no"; + /** + * value navigationkeys + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD + */ + final static String VALUE_NAVIGATIONKEYS = "navigationkeys"; - /** - * value gameactions - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD - */ - final static String VALUE_GAMEACTIONS ="gameactions"; + /** + * value portrait + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_APP_ORIENTATION + */ + final static String VALUE_PORTRAIT = "portrait"; - /** - * value navigationkeys - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_ON_SCREEN_KEYPAD - */ - final static String VALUE_NAVIGATIONKEYS = "navigationkeys"; + /** + * value landscape + * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_APP_ORIENTATION + */ + final static String VALUE_LANDSCAPE = "landscape"; - /** - * value portrait - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_APP_ORIENTATION - */ - final static String VALUE_PORTRAIT = "portrait"; + /** + * value PopUpTextBox + * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT + */ + final static String VALUE_POPUP_TEXTBOX = "PopUpTextBox"; - /** - * value landscape - * @see JadAttributeUtil#ATTRIB_NOKIA_MIDLET_APP_ORIENTATION - */ - final static String VALUE_LANDSCAPE = "landscape"; + /** + * value FullScreenTextBox + * @see JadAttributeUtil#ATTRIB_NOKIA_UI_ENHANCEMENT + */ + final static String VALUE_FULLSCREEN_TEXTBOX = "FullScreenTextBox"; - /** - * Returns if the given value is set for the given midlet. - * Use one of the ATTRIB_ constants defined on {@link JadAttributeUtil} as - * the attribute. - * - * @param attribute - * @param value - * @return - */ - final static boolean isValue(final String attribute, final String value){ - if ( attribute == null || attribute.length() < 1) return false; - if ( value == null ) return false; - return value.equalsIgnoreCase(getValue(attribute)); - } + /** + * Returns if the given value is set for the given midlet. + * Use one of the ATTRIB_ constants defined on {@link JadAttributeUtil} as + * the attribute. + * + * @param attribute + * @param value + * @return + */ + final static boolean isValue(final String attribute, final String value) + { + if(attribute == null || attribute.length() < 1) return false; + if(value == null) return false; + return value.equalsIgnoreCase(getValue(attribute)); + } - /** - * Reads the value of the given attribute - * Use one of the ATTRIB_ constants defined on {@link JadAttributeUtil} as - * the attribute. - * @param attribute - * @return - */ - final static String getValue( final String attribute){ - return ApplicationInfo.getInstance().getAttribute(attribute); - } + /** + * Reads the value of the given attribute + * Use one of the ATTRIB_ constants defined on {@link JadAttributeUtil} as + * the attribute. + * @param attribute + * @return + */ + final static String getValue(final String attribute) + { + return ApplicationInfo.getInstance().getAttribute(attribute); + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/KeyTable.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/KeyTable.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/KeyTable.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,9 +21,11 @@ /** * Key table. */ -final class KeyTable { +final class KeyTable +{ - static final int[][] KEY_TO_GAME_TABLE = { + static final int[][] KEY_TO_GAME_TABLE = + { {-1, Canvas.UP}, {50, Canvas.UP}, {SWT.ARROW_UP, Canvas.UP}, @@ -53,33 +55,42 @@ /** * Private constructor. */ - private KeyTable() { + private KeyTable() + { } - static int getGameAction(int keyCode) { - for (int i = 0; i < KEY_TO_GAME_TABLE.length; i++) { - if (KEY_TO_GAME_TABLE[i][0] == keyCode) { + static int getGameAction(int keyCode) + { + for(int i = 0; i < KEY_TO_GAME_TABLE.length; i++) + { + if(KEY_TO_GAME_TABLE[i][0] == keyCode) + { return KEY_TO_GAME_TABLE[i][1]; } } throw new IllegalArgumentException( - MsgRepository.CANVAS_EXCEPTION_INVALID_KEY_CODE); + MsgRepository.CANVAS_EXCEPTION_INVALID_KEY_CODE); } - static int getKeyCode(int gameAction) { - for (int i = 0; i < KEY_TO_GAME_TABLE.length; i++) { - if (KEY_TO_GAME_TABLE[i][1] == gameAction) { + static int getKeyCode(int gameAction) + { + for(int i = 0; i < KEY_TO_GAME_TABLE.length; i++) + { + if(KEY_TO_GAME_TABLE[i][1] == gameAction) + { return KEY_TO_GAME_TABLE[i][0]; } } throw new IllegalArgumentException( - MsgRepository.CANVAS_EXCEPTION_INVALID_GAME_ACTION); + MsgRepository.CANVAS_EXCEPTION_INVALID_GAME_ACTION); } - static String getKeyName(int keyCode) { + static String getKeyName(int keyCode) + { - switch(keyCode) { + switch(keyCode) + { /*case Canvas.KEY_NUM0: return "0"; @@ -117,23 +128,23 @@ case Canvas.KEY_POUND: return "#"; */ - case -1: - return OpenLcduiLocalization.getMessage("key_up"); + case -1: + return OpenLcduiLocalization.getMessage("key_up"); - case -2: - return OpenLcduiLocalization.getMessage("key_down"); - - case -3: - return OpenLcduiLocalization.getMessage("key_left"); + case -2: + return OpenLcduiLocalization.getMessage("key_down"); + + case -3: + return OpenLcduiLocalization.getMessage("key_left"); - case -4: - return OpenLcduiLocalization.getMessage("key_right"); + case -4: + return OpenLcduiLocalization.getMessage("key_right"); - case -5: - return OpenLcduiLocalization.getMessage("key_select"); + case -5: + return OpenLcduiLocalization.getMessage("key_select"); - default: - return ""; + default: + return ""; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/LCDUIInvokerImpl.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/LCDUIInvokerImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/LCDUIInvokerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -23,23 +23,27 @@ import org.eclipse.swt.widgets.Button; import com.nokia.mid.ui.DirectGraphics; import com.nokia.mj.impl.nokialcdui.LCDUIInvoker; +import com.nokia.mj.impl.nokialcdui.ItemControlStateChangeListener; -final class LCDUIInvokerImpl extends LCDUIInvoker { +final class LCDUIInvokerImpl extends LCDUIInvoker +{ private boolean eswtReturn; - /** - * Constant for Soft Key Label Height - */ + /** + * Constant for Soft Key Label Height + */ public static final int LABEL_HEIGHT = 30; - - static void createInvoker() { + + static void createInvoker() + { LCDUIInvoker.setInvoker( - new javax.microedition.lcdui.LCDUIInvokerImpl()); + new javax.microedition.lcdui.LCDUIInvokerImpl()); } - - - protected void doESWTUIThreadRunnerSyncExec(Runnable runnable) { + + + protected void doESWTUIThreadRunnerSyncExec(Runnable runnable) + { ESWTUIThreadRunner.syncExec(runnable); } @@ -50,14 +54,18 @@ * @return eSWT Control that is used by Displayable/Item or null if no * Control is available. */ - protected Control doGetEswtControl(Object lcduiObject) { + protected Control doGetEswtControl(Object lcduiObject) + { Logger.method(this, "doGetEswtControl", lcduiObject); - if (lcduiObject instanceof Displayable) { + if(lcduiObject instanceof Displayable) + { return ((Displayable) lcduiObject).getShell(); } - else if (lcduiObject instanceof Item) { + else if(lcduiObject instanceof Item) + { Item item = (Item) lcduiObject; - if (item.isContainedInForm()) { + if(item.isContainedInForm()) + { Form parentForm = (Form) item.getParent(); return parentForm.getLayoutPolicy().getItemControl(item); } @@ -65,6 +73,13 @@ return null; } + + protected void doSetItemControlStateChangeListener(ItemControlStateChangeListener listener,Item item) + { + Logger.method(this, "doItemStateChangeListener",listener); + item.setItemControlStateChangeListener(listener); + } + /* * This method checks if the current Displayable exists * If yes, then the current Displayable is asked for the property @@ -76,25 +91,26 @@ Displayable disp = javax.microedition.lcdui.Display.getDisplay().getCurrent(); - if( ( disp != null) && (disp instanceof Canvas)) + if((disp != null) && (disp instanceof Canvas)) + { + if(((Canvas) disp).IsFullScreenMode()) { - if( ( (Canvas) disp).IsFullScreenMode()) { - if("com.nokia.softkey1.label.location".equals(softKeyId)) - { - SoftKeyLabelLocation = "0," + String.valueOf(( (Canvas) disp).getHeight()) + "," - + String.valueOf( (((Canvas) disp).getWidth())/2 ) + "," - + String.valueOf(LABEL_HEIGHT); - } - else if("com.nokia.softkey2.label.location".equals(softKeyId)) - { - SoftKeyLabelLocation = String.valueOf( (((Canvas) disp).getWidth())/2 ) + "," - + String.valueOf(( (Canvas) disp).getHeight()) + "," - + String.valueOf( (((Canvas) disp).getWidth())/2 ) + "," - + String.valueOf(LABEL_HEIGHT); - } - } + if("com.nokia.softkey1.label.location".equals(softKeyId)) + { + SoftKeyLabelLocation = "0," + String.valueOf(((Canvas) disp).getHeight()) + "," + + String.valueOf((((Canvas) disp).getWidth())/2) + "," + + String.valueOf(LABEL_HEIGHT); + } + else if("com.nokia.softkey2.label.location".equals(softKeyId)) + { + SoftKeyLabelLocation = String.valueOf((((Canvas) disp).getWidth())/2) + "," + + String.valueOf(((Canvas) disp).getHeight()) + "," + + String.valueOf((((Canvas) disp).getWidth())/2) + "," + + String.valueOf(LABEL_HEIGHT); + } } + } return SoftKeyLabelLocation; } @@ -110,94 +126,117 @@ Displayable disp = javax.microedition.lcdui.Display.getDisplay().getCurrent(); - if( ( disp != null) && (disp instanceof Canvas)) + if((disp != null) && (disp instanceof Canvas)) + { + if(null == ((Canvas) disp).getCanvasKeypad()) + { + SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.HCENTER); + } + else { - if( null == ((Canvas) disp).getCanvasKeypad()) - { - SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.HCENTER); - } - else - { - if("com.nokia.softkey1.label.anchor".equals(softKeyId)) - { - SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.LEFT); - } - else if("com.nokia.softkey2.label.anchor".equals(softKeyId)) - { - SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.RIGHT); - } - } + if("com.nokia.softkey1.label.anchor".equals(softKeyId)) + { + SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.LEFT); + } + else if("com.nokia.softkey2.label.anchor".equals(softKeyId)) + { + SoftKeyLabelAnchor = String.valueOf(Graphics.TOP | Graphics.RIGHT); + } } + } return SoftKeyLabelAnchor; } - protected Display doGetEswtDisplay() { + protected Display doGetEswtDisplay() + { Logger.method(this, "doGetEswtDisplay"); return ESWTUIThreadRunner.getInstance().getDisplay(); } - protected org.eclipse.swt.graphics.Image doGetEswtImage(Image img) { + protected org.eclipse.swt.graphics.Image doGetEswtImage(Image img) + { Logger.method(this, "doGetEswtImage", img); return Image.getESWTImage(img); } - protected DirectGraphics doGetDirectGraphics(Graphics g) { + protected Image doGetLcduiImage(org.eclipse.swt.graphics.Image img) + { + Logger.method(this, "doGetLcduiImage", img); + return new Image(img, true); + } + + protected DirectGraphics doGetDirectGraphics(Graphics g) + { Logger.method(this, "doGetDirectGraphics", g); - if (g != null) { + if(g != null) + { return g.getDirectGraphics(); } return null; } - protected GraphicsContext doGetGc(Graphics g) { + protected GraphicsContext doGetGc(Graphics g) + { Logger.method(this, "doGetGc", g); - if (g != null) { + if(g != null) + { return g.getGc(); } return null; } - protected Font doGetFreeSizedFont(int face, int style, int height) { + protected Font doGetFreeSizedFont(int face, int style, int height) + { Logger.method(this, "doGetFreeSizedFont"); return Font.getFreeSizedFont(face, style, height); } - protected void doInitGameCanvas(Object canvas, boolean suppressKeys) { + protected void doInitGameCanvas(Object canvas, boolean suppressKeys) + { Logger.method(canvas, "doInitGameCanvas", String.valueOf(suppressKeys)); ((Canvas) canvas).initGameCanvas(suppressKeys); } - protected Object doGetGraphics(Object canvas) { + protected Object doGetGraphics(Object canvas) + { return ((Canvas) canvas).getGameBufferGraphics(); } - protected Object doGetFlushLock(Object graphics) { - return ((Graphics) graphics).getLock(); + protected Object doGetFlushLock(Object graphics) + { + return ((Graphics) graphics).getLock(); } - - protected int doGetKeyStates(Object canvas) { + + protected int doGetKeyStates(Object canvas) + { return ((Canvas) canvas).getGameKeyStates(); } - protected void doRenderGraphics(Object canvas, Object graphics) { + protected void doRenderGraphics(Object canvas, Object graphics) + { ((Canvas) canvas).renderGraphics((Graphics) graphics); } protected void doFlushGraphics(Object canvas, - int x, int y, int width, int height) { + int x, int y, int width, int height) + { ((Canvas) canvas).flushGameBuffer(x, y, width, height); } - protected String doGetDynamicProperty(String key) { - if ("com.nokia.key.scancode".equals(key)) { + protected String doGetDynamicProperty(String key) + { + if("com.nokia.key.scancode".equals(key)) + { return String.valueOf(ESWTUIThreadRunner.getLastKeyScancode()); } - else if ("com.nokia.key.modifier".equals(key)) { + else if("com.nokia.key.modifier".equals(key)) + { return String.valueOf(ESWTUIThreadRunner.getLastKeyModifier()); } - else if ("com.nokia.keyboard.type".equals(key)) { + else if("com.nokia.keyboard.type".equals(key)) + { // TODO: eSWT support required /* No keypad (for example a touch device without keypad) - None @@ -213,19 +252,19 @@ } else if("com.nokia.softkey1.label.location".equals(key)) { - return getSoftKeyLabelLocationImpl(key); + return getSoftKeyLabelLocationImpl(key); } else if("com.nokia.softkey1.label.anchor".equals(key)) { - return getSoftKeyLabelAnchorImpl(key); + return getSoftKeyLabelAnchorImpl(key); } else if("com.nokia.softkey2.label.location".equals(key)) { - return getSoftKeyLabelLocationImpl(key); + return getSoftKeyLabelLocationImpl(key); } else if("com.nokia.softkey2.label.anchor".equals(key)) { - return getSoftKeyLabelAnchorImpl(key); + return getSoftKeyLabelAnchorImpl(key); } return "key not supported"; } @@ -233,7 +272,8 @@ protected boolean doDetectCollision(Image image1, int transform1, int p1x, int p1y, int r1x1, int r1y1, int r1x2, int r1y2, Image image2, int transform2, int p2x, int p2y, - int r2x1, int r2y1, int r2x2, int r2y2) { + int r2x1, int r2y1, int r2x2, int r2y2) + { final org.eclipse.swt.graphics.Image eswtImg1 = Image.getESWTImage(image1);; final int ftransform1 = transform1; @@ -254,13 +294,15 @@ final int fr2y2 = r2y2; eswtReturn = false; - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtReturn = org.eclipse.swt.internal.qt.graphics.Image.detectCollision( - Internal_GfxPackageSupport.getImage(eswtImg1), ftransform1, fp1x, fp1y, - fr1x1, fr1y1, fr1x2, fr1y2, - Internal_GfxPackageSupport.getImage(eswtImg2), ftransform2, fp2x, fp2y, - fr2x1, fr2y1, fr2x2, fr2y2); + Internal_GfxPackageSupport.getImage(eswtImg1), ftransform1, fp1x, fp1y, + fr1x1, fr1y1, fr1x2, fr1y2, + Internal_GfxPackageSupport.getImage(eswtImg2), ftransform2, fp2x, fp2y, + fr2x1, fr2y1, fr2x2, fr2y2); } }); return eswtReturn; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/LayoutObject.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/LayoutObject.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/LayoutObject.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -22,11 +22,14 @@ import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.*; +import org.eclipse.ercp.swt.mobile.CaptionedControl; + /** * Structure which represents Control stored in Form Row. */ -final class LayoutObject { +final class LayoutObject +{ /** * Control which is represented by this LayoutObject. @@ -59,7 +62,8 @@ * @param owningItem - Item which this LayoutObject corresponds to * @param control - Control for that LayoutObject */ - LayoutObject(Item owningItem, Control control) { + LayoutObject(Item owningItem, Control control) + { this.owningItem = owningItem; setControl(control); } @@ -69,9 +73,12 @@ * * @param newControl Control to set */ - private void setControl(final Control newControl) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private void setControl(final Control newControl) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { control = newControl; eswtUpdateSize(); Control temp = eswtGetCommandControl(control); @@ -79,7 +86,8 @@ Enumeration e = owningItem.getCommands().elements(); Command cmd = null; - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { cmd = (Command) e.nextElement(); eswtAddCommand(cmd); } @@ -95,17 +103,31 @@ * @param ctrl Control of this LayoutObject. * @return Control. */ - Control eswtGetCommandControl(Control ctrl) { + Control eswtGetCommandControl(Control ctrl) + { Control ret = null; - if (ctrl != null) { - if (ctrl instanceof Button) { + + //If the Control is focusable add the commands to the same. + if((ctrl instanceof CaptionedControl) || (ctrl.isFocusControl())) + { + return ctrl; + } + + + if(ctrl != null) + { + if(ctrl instanceof Button) + { ret = ctrl; } - else if (ctrl instanceof Composite) { + else if(ctrl instanceof Composite) + { Control[] children = ((Composite) ctrl).getChildren(); - for (int i = 0; i < children.length; i++) { + for(int i = 0; i < children.length; i++) + { Control result = eswtGetCommandControl(children[i]); - if (result != null) { + if(result != null) + { ret = result; break; } @@ -118,9 +140,12 @@ /** * Dispose LayoutObject. */ - void dispose() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void dispose() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { control.dispose(); control = null; commandControl = null; @@ -131,7 +156,8 @@ /** * Returns the Item's vertical layout. */ - int getVerticalLayout() { + int getVerticalLayout() + { return Item.getVerticalLayout(owningItem.getLayout()); } @@ -140,7 +166,8 @@ * * @return control */ - Control getControl() { + Control getControl() + { return control; } @@ -149,7 +176,8 @@ * * @return owning Item */ - Item getOwningItem() { + Item getOwningItem() + { return owningItem; } @@ -159,7 +187,8 @@ * @param xCoord x coordinate * @param yCoord y coordinate */ - void eswtSetLocation(int xCoord, int yCoord) { + void eswtSetLocation(int xCoord, int yCoord) + { x = xCoord; y = yCoord; control.setLocation(xCoord, yCoord); @@ -168,7 +197,8 @@ /** * Update LayoutObject width and height. */ - void eswtUpdateSize() { + void eswtUpdateSize() + { Rectangle bounds = control.getBounds(); width = bounds.width; height = bounds.height; @@ -179,7 +209,8 @@ * * @return xCoordinate of LayoutObject. */ - int getX() { + int getX() + { return x; } @@ -188,7 +219,8 @@ * * @return yCoordinate of LayoutObject. */ - int getY() { + int getY() + { return y; } @@ -197,7 +229,8 @@ * * @return width of a control */ - int getWidth() { + int getWidth() + { return width; } @@ -206,7 +239,8 @@ * * @return width of a control */ - int getHeight() { + int getHeight() + { return height; } @@ -215,7 +249,8 @@ * * @param row Row index. */ - void setRowIdx(int row) { + void setRowIdx(int row) + { layoutRowIdx = row; } @@ -224,11 +259,13 @@ * * @return Index of the row. */ - int getRowIdx() { + int getRowIdx() + { return layoutRowIdx; } - boolean contains(int xCoord, int yCoord) { + boolean contains(int xCoord, int yCoord) + { return (y <= yCoord && yCoord <= y + height && x <= xCoord && xCoord <= x + width); } @@ -236,8 +273,10 @@ /** * Returns if this LayoutObject is below the other. */ - boolean isBelow(LayoutObject other) { - if (other != null) { + boolean isBelow(LayoutObject other) + { + if(other != null) + { return (this.getRowIdx() > other.getRowIdx()); } return true; @@ -246,8 +285,10 @@ /** * Returns if this LayoutObject is above the other. */ - boolean isAbove(LayoutObject other) { - if (other != null) { + boolean isAbove(LayoutObject other) + { + if(other != null) + { return (this.getRowIdx() < other.getRowIdx()); } return true; @@ -258,7 +299,8 @@ * * @return x horizontal coordinate of the middle of LayoutObject. */ - private int getXMiddle() { + private int getXMiddle() + { return (x + width / 2); } @@ -267,7 +309,8 @@ * * @return y vertical coordinate of the middle of LayoutObject. */ - private int getYMiddle() { + private int getYMiddle() + { return (y + height / 2); } @@ -278,13 +321,16 @@ * @param other another LayoutObject * @return positive distance between the middles */ - int distanceTo(LayoutObject other) { - if (other != null) { + int distanceTo(LayoutObject other) + { + if(other != null) + { int xd = Math.abs(getXMiddle() - other.getXMiddle()); int yd = Math.abs(getYMiddle() - other.getYMiddle()); return (int) Math.sqrt(xd * xd + yd * yd); } - else { + else + { return Integer.MAX_VALUE - 1; } } @@ -292,46 +338,52 @@ /** * Activates commands associated with owning item. */ - void eswtAddSelectionListenerForCommands() { + void eswtAddSelectionListenerForCommands() + { // Logger.method(this, "eswtAddSelectionListenerForCommands"); commandsActivated = true; // Add new control to commands in owning item: Enumeration e = owningItem.getCommands().elements(); Command cmd = null; - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { cmd = (Command) e.nextElement(); cmd.eswtAddCommandSelectionListener(commandControl, - eswtItemCommandListener); + eswtItemCommandListener); } // Add SelectionListener to Button control. // Listener is activated when command mapped to MSK is clicked. - if (commandControl instanceof Button && !commandControl.isDisposed()) { + if(commandControl instanceof Button && !commandControl.isDisposed()) + { ((Button) commandControl) - .addSelectionListener(eswtItemCommandListener); + .addSelectionListener(eswtItemCommandListener); } } /** * DeActivates commands associated with owning item. */ - void eswtRemoveSelectionListenerForCommands() { + void eswtRemoveSelectionListenerForCommands() + { // Logger.method(this, "eswtRemoveSelectionListenerForCommands"); commandsActivated = false; // Add new control to commands in owning item: Enumeration e = owningItem.getCommands().elements(); Command cmd = null; - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { cmd = (Command) e.nextElement(); cmd.eswtRemoveCommandSelectionListener(commandControl, - eswtItemCommandListener); + eswtItemCommandListener); } // Remove SelectionListener from Button control. // Listener is activated when command mapped to MSK is clicked. - if (commandControl instanceof Button && !commandControl.isDisposed()) { + if(commandControl instanceof Button && !commandControl.isDisposed()) + { ((Button) commandControl) - .removeSelectionListener(eswtItemCommandListener); + .removeSelectionListener(eswtItemCommandListener); } } @@ -340,9 +392,12 @@ * * @param command The command to be added. */ - void addCommand(final Command command) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void addCommand(final Command command) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtAddCommand(command); } }); @@ -351,14 +406,17 @@ /** * eSWT callback to add a Command. */ - void eswtAddCommand(Command command) { + void eswtAddCommand(Command command) + { //Logger.method(this, "eswtAddCommand", command); - if (command != null && commandControl != null) { + if(command != null && commandControl != null) + { command.eswtAddESWTCommand(commandControl, - (command == owningItem.getDefaultCommand())); - if (commandsActivated) { + (command == owningItem.getDefaultCommand())); + if(commandsActivated) + { command.eswtAddCommandSelectionListener(commandControl, - eswtItemCommandListener); + eswtItemCommandListener); } } } @@ -368,9 +426,12 @@ * * @param command The command to be removed. */ - void removeCommand(final Command command) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void removeCommand(final Command command) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtRemoveCommand(command); } }); @@ -379,10 +440,13 @@ /** * eSWT callback to remove a Command. */ - private void eswtRemoveCommand(Command command) { + private void eswtRemoveCommand(Command command) + { //Logger.method(this, "eswtRemoveCommand", command); - if (command != null && commandControl != null) { - if (commandsActivated) { + if(command != null && commandControl != null) + { + if(commandsActivated) + { command.eswtRemoveCommandSelectionListener(commandControl, eswtItemCommandListener); } @@ -394,9 +458,11 @@ * Inner class which receives SelectionEvents from eSWT and convert and * forwards those events to LCDUI Item's ItemCommandListener. */ - class EswtItemCommandListener implements SelectionListener { + class EswtItemCommandListener implements SelectionListener + { - public void widgetDefaultSelected(SelectionEvent e) { + public void widgetDefaultSelected(SelectionEvent e) + { } /** @@ -404,23 +470,28 @@ * Item's ItemCommandListener if event source matches with the * Commands added to the Item. */ - public void widgetSelected(SelectionEvent event) { + public void widgetSelected(SelectionEvent event) + { // Go through all Commands added to owning item: Enumeration e = owningItem.getCommands().elements(); Command cmd = null; - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { cmd = (Command) e.nextElement(); // get eSWT Command of this Control from Command and compare // it to the widget which launched the event: - if (cmd.getESWTCommand(commandControl) == event.widget) { + if(cmd.getESWTCommand(commandControl) == event.widget) + { owningItem.callCommandAction(cmd); break; } // Handle MSK: Command mskCmd = owningItem.getMSKCommand(); - if (mskCmd != null && cmd == mskCmd) { - if (commandControl == event.widget) { + if(mskCmd != null && cmd == mskCmd) + { + if(commandControl == event.widget) + { owningItem.callCommandAction(cmd); break; } @@ -429,7 +500,8 @@ } } - public String toString() { + public String toString() + { return owningItem + " [line:" + layoutRowIdx + "]"; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/List.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/List.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/List.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,7 +25,8 @@ /** * Implementation of LCDUI List class. */ -public class List extends Screen implements Choice { +public class List extends Screen implements Choice +{ /** * The default command triggered when selecting an item on IMPLICIT lists. @@ -50,7 +51,8 @@ * @param title the list's title * @param type the type */ - public List(String title, int type) { + public List(String title, int type) + { this(title, type, new String[] {}, null); } @@ -68,35 +70,39 @@ * @throws NullPointerException if any of the text elements is null */ public List(String title, int type, String[] textElements, - Image[] imgElements) { + Image[] imgElements) + { super(title); - switch (type) { - case Choice.IMPLICIT: - case Choice.EXCLUSIVE: - choiceImpl = new ChoiceImpl(false); - break; - case Choice.MULTIPLE: - choiceImpl = new ChoiceImpl(true); - break; - default: - throw new IllegalArgumentException( - MsgRepository.LIST_EXCEPTION_INVALID_TYPE); + switch(type) + { + case Choice.IMPLICIT: + case Choice.EXCLUSIVE: + choiceImpl = new ChoiceImpl(false); + break; + case Choice.MULTIPLE: + choiceImpl = new ChoiceImpl(true); + break; + default: + throw new IllegalArgumentException( + MsgRepository.LIST_EXCEPTION_INVALID_TYPE); } choiceImpl.check(textElements, imgElements); this.selectCommand = SELECT_COMMAND; this.type = type; construct(); // append elements - for (int i = 0; i < textElements.length; i++) { + for(int i = 0; i < textElements.length; i++) + { append(textElements[i], imgElements != null - ? imgElements[i] : null); + ? imgElements[i] : null); } } /* (non-Javadoc) * @see Displayable#eswtConstructContent(int) */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { Composite comp = super.eswtConstructContent(style); eswtTable = new TableExtension(comp, getStyle(type)); eswtTable.getHorizontalBar().setVisible(false); @@ -106,7 +112,8 @@ /** * Called by Display when Displayable should become visible. */ - void eswtHandleShowCurrentEvent() { + void eswtHandleShowCurrentEvent() + { super.eswtHandleShowCurrentEvent(); eswtTable.addSelectionListener(eswtTableListener); } @@ -114,7 +121,8 @@ /** * Called by Display when Displayable should become hidden. */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { super.eswtHandleHideCurrentEvent(); eswtTable.removeSelectionListener(eswtTableListener); } @@ -122,7 +130,8 @@ /* (non-Javadoc) * @see Displayable#eswtHandleResizeEvent(int, int) */ - void eswtHandleResizeEvent(int width, int height) { + void eswtHandleResizeEvent(int width, int height) + { super.eswtHandleResizeEvent(width, height); eswtTable.setBounds(getContentComp().getClientArea()); } @@ -130,27 +139,32 @@ /** * Get Table style based on list type. */ - private int getStyle(int listType) { + private int getStyle(int listType) + { int tableStyle = SWT.NONE; - switch (listType) { - case Choice.IMPLICIT: - tableStyle |= SWT.SINGLE; - break; - case Choice.EXCLUSIVE: - tableStyle |= SWT.SINGLE | SWT.RADIO; - break; - case Choice.MULTIPLE: - tableStyle |= SWT.MULTI | SWT.CHECK; - break; - default: - break; + switch(listType) + { + case Choice.IMPLICIT: + tableStyle |= SWT.SINGLE; + break; + case Choice.EXCLUSIVE: + tableStyle |= SWT.SINGLE | SWT.RADIO; + break; + case Choice.MULTIPLE: + tableStyle |= SWT.MULTI | SWT.CHECK; + break; + default: + break; } return tableStyle; } - private void updateSelection() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + private void updateSelection() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtUpdateSelection(); } }); @@ -159,58 +173,71 @@ /** * Update eSWT Table selection. */ - private void eswtUpdateSelection() { - if (type == IMPLICIT || type == EXCLUSIVE) { + private void eswtUpdateSelection() + { + if(type == IMPLICIT || type == EXCLUSIVE) + { int sel = choiceImpl.getSelectedIndex(); - if ((sel == 0) || (eswtTable.getSelectionIndex() != sel)) { + if((sel == 0) || (eswtTable.getSelectionIndex() != sel)) + { eswtTable.setSelection(sel); } } - else { + else + { int size = choiceImpl.size(); - for (int i = 0; i < size; i++) { - if (choiceImpl.isSelected(i)) { + for(int i = 0; i < size; i++) + { + if(choiceImpl.isSelected(i)) + { eswtTable.select(i); } - else { + else + { eswtTable.deselect(i); } } } } - private void eswtInsertItem(int index) { + private void eswtInsertItem(int index) + { TableItem item = new TableItem(eswtTable, SWT.NONE, index); Image img = choiceImpl.getImage(index); item.setImage(0, Image.getESWTImage(img)); item.setText(0, choiceImpl.getString(index)); } - private void eswtSetItem(int index) { + private void eswtSetItem(int index) + { TableItem item = eswtTable.getItem(index); Image img = choiceImpl.getImage(index); item.setImage(0, Image.getESWTImage(img)); item.setText(0, choiceImpl.getString(index)); } - private void eswtDeleteItem(int index) { + private void eswtDeleteItem(int index) + { eswtTable.getItem(index).dispose(); choiceImpl.delete(index); } - private void eswtDeleteAllItems() { - for (int i = eswtTable.getItemCount() - 1; i >= 0; i--) { - if (type == Choice.IMPLICIT) + private void eswtDeleteAllItems() + { + for(int i = eswtTable.getItemCount() - 1; i >= 0; i--) + { + if(type == Choice.IMPLICIT) { - choiceImpl.delete(i); + choiceImpl.delete(i); } eswtTable.getItem(i).dispose(); } } - private void eswtSetItemFont(int index) { + private void eswtSetItemFont(int index) + { org.eclipse.swt.graphics.Font font = Font.getESWTFont(choiceImpl - .getFont(index)); + .getFont(index)); eswtTable.getItem(index).setFont(0, font); } @@ -221,10 +248,13 @@ * @param img the image * @return index of added item */ - public int append(String text, Image img) { + public int append(String text, Image img) + { final int index = choiceImpl.append(text, img); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtInsertItem(index); eswtUpdateSelection(); } @@ -239,11 +269,14 @@ * @param text the text * @param img the image */ - public void insert(int position, String text, Image img) { + public void insert(int position, String text, Image img) + { choiceImpl.insert(position, text, img); final int index = position; // index of added element - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtInsertItem(index); eswtUpdateSelection(); } @@ -257,11 +290,14 @@ * @param text the text * @param img the image */ - public void set(int position, String text, Image img) { + public void set(int position, String text, Image img) + { choiceImpl.set(position, text, img); final int index = position; // index of changed element - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSetItem(index); eswtUpdateSelection(); } @@ -273,11 +309,14 @@ * * @param position the item index */ - public void delete(int position) { + public void delete(int position) + { // choiceImpl.delete(position); final int index = position; // index of changed element - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtDeleteItem(index); eswtUpdateSelection(); } @@ -287,13 +326,16 @@ /** * Remove all items. */ - public void deleteAll() { - if (type != Choice.IMPLICIT) + public void deleteAll() + { + if(type != Choice.IMPLICIT) { - choiceImpl.deleteAll(); + choiceImpl.deleteAll(); } - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtDeleteAllItems(); } }); @@ -304,7 +346,8 @@ * * @return the lists fir policy */ - public int getFitPolicy() { + public int getFitPolicy() + { return choiceImpl.getFitPolicy(); } @@ -314,7 +357,8 @@ * @param position the index of the item * @return the items font */ - public Font getFont(int position) { + public Font getFont(int position) + { return choiceImpl.getFont(position); } @@ -324,7 +368,8 @@ * @param position the index of the item * @return the items image part */ - public Image getImage(int position) { + public Image getImage(int position) + { return choiceImpl.getImage(position); } @@ -334,7 +379,8 @@ * @param position the index of the item * @return the items string part */ - public String getString(int position) { + public String getString(int position) + { return choiceImpl.getString(position); } @@ -344,7 +390,8 @@ * @param selectedArray an array with selected items * @return selected flags */ - public int getSelectedFlags(boolean[] selectedArray) { + public int getSelectedFlags(boolean[] selectedArray) + { return choiceImpl.getSelectedFlags(selectedArray); } @@ -353,7 +400,8 @@ * * @return the selected index */ - public int getSelectedIndex() { + public int getSelectedIndex() + { return choiceImpl.getSelectedIndex(); } @@ -363,7 +411,8 @@ * @param position specified element index * @return true if its selected, false otherwise */ - public boolean isSelected(int position) { + public boolean isSelected(int position) + { return choiceImpl.isSelected(position); } @@ -372,12 +421,15 @@ * * @param newFitPolicy the new fit policy */ - public void setFitPolicy(int newFitPolicy) { + public void setFitPolicy(int newFitPolicy) + { choiceImpl.setFitPolicy(newFitPolicy); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtTable.setWordWrap(choiceImpl.getFitPolicy() - == Choice.TEXT_WRAP_ON); + == Choice.TEXT_WRAP_ON); } }); } @@ -388,11 +440,14 @@ * @param position the index of the item * @param font the desired font */ - public void setFont(int position, Font font) { + public void setFont(int position, Font font) + { choiceImpl.setFont(position, font); final int index = position; // index of added element - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtSetItemFont(index); } }); @@ -403,9 +458,12 @@ * * @param cmd a command. */ - public void setSelectCommand(Command cmd) { - if (type == Choice.IMPLICIT) { - if (cmd != SELECT_COMMAND) { + public void setSelectCommand(Command cmd) + { + if(type == Choice.IMPLICIT) + { + if(cmd != SELECT_COMMAND) + { addCommand(cmd); } selectCommand = cmd; @@ -417,8 +475,10 @@ * * @param cmd a command. */ - public void removeCommand(Command cmd) { - if (cmd == selectCommand) { + public void removeCommand(Command cmd) + { + if(cmd == selectCommand) + { selectCommand = null; } super.removeCommand(cmd); @@ -429,7 +489,8 @@ * * @param selectedArray an array with selected items */ - public void setSelectedFlags(boolean[] selectedArray) { + public void setSelectedFlags(boolean[] selectedArray) + { choiceImpl.setSelectedFlags(selectedArray); updateSelection(); } @@ -440,7 +501,8 @@ * @param position the index of the item * @param select selected or not */ - public void setSelectedIndex(int position, boolean select) { + public void setSelectedIndex(int position, boolean select) + { choiceImpl.setSelected(position, select); updateSelection(); } @@ -450,40 +512,52 @@ * * @return the lists size */ - public int size() { + public int size() + { return choiceImpl.size(); } /** * Table Default Selection listener. */ - class EswtTableSelectionListener implements SelectionListener { + class EswtTableSelectionListener implements SelectionListener + { - private void update(SelectionEvent se) { - if (se.widget != null && se.item != null) { + private void update(SelectionEvent se) + { + if(se.widget != null && se.item != null) + { int index = ((Table) se.widget).indexOf((TableItem) se.item); Logger.method(List.this, "updateSel", String.valueOf(index), - se); - if (index >= 0) { + se); + if(index >= 0) + { choiceImpl.setSelected(index, !isSelected(index)); } } } - public void widgetDefaultSelected(SelectionEvent se) { - if (type == Choice.IMPLICIT) { - if (size() > 0) { + public void widgetDefaultSelected(SelectionEvent se) + { + if(type == Choice.IMPLICIT) + { + if(size() > 0) + { callCommandAction(selectCommand); } } } - public void widgetSelected(SelectionEvent se) { - if (type == Choice.IMPLICIT || type == Choice.EXCLUSIVE) { + public void widgetSelected(SelectionEvent se) + { + if(type == Choice.IMPLICIT || type == Choice.EXCLUSIVE) + { update(se); } - else if (type == Choice.MULTIPLE) { - if (se.detail == SWT.CHECK) { + else if(type == Choice.MULTIPLE) + { + if(se.detail == SWT.CHECK) + { update(se); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Logger.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Logger.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Logger.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -20,13 +20,15 @@ /** * Logger utility class.
            */ -final class Logger { +final class Logger +{ private static StringBuffer methodSb = new StringBuffer(); private static boolean logVerbose = true; - private Logger() { + private Logger() + { } /** @@ -34,18 +36,22 @@ * * @param level logging level */ - static boolean isLogVerbose() { + static boolean isLogVerbose() + { return logVerbose; } - static void method(Object obj, String fn) { + static void method(Object obj, String fn) + { method(obj, fn, null, null, null); } - static void method(Object obj, String fn, Object p1) { + static void method(Object obj, String fn, Object p1) + { method(obj, fn, p1, null, null); } - static void method(Object obj, String fn, Object p1, Object p2) { + static void method(Object obj, String fn, Object p1, Object p2) + { method(obj, fn, p1, p2, null); } @@ -58,28 +64,33 @@ * @param p2 second parameter * @param p3 third parameter */ - static void method(Object obj, String fn, Object p1, Object p2, Object p3) { - if (logVerbose) { + static void method(Object obj, String fn, Object p1, Object p2, Object p3) + { + if(logVerbose) + { methodSb.setLength(0); methodSb.append(obj); methodSb.append("::"); methodSb.append(fn); methodSb.append("("); - if (p1 != null) { + if(p1 != null) + { methodSb.append(p1); } - if (p2 != null) { + if(p2 != null) + { methodSb.append(", "); methodSb.append(p2); } - if (p3 != null) { + if(p3 != null) + { methodSb.append(", "); methodSb.append(p3); } methodSb.append(")"); com.nokia.mj.impl.utils.Logger.LOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, - com.nokia.mj.impl.utils.Logger.EInfo, methodSb.toString()); + com.nokia.mj.impl.utils.Logger.EJavaUI, + com.nokia.mj.impl.utils.Logger.EInfo, methodSb.toString()); } } @@ -88,10 +99,11 @@ * * @param msg a message */ - static void verbose(String msg) { + static void verbose(String msg) + { com.nokia.mj.impl.utils.Logger.LOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, - com.nokia.mj.impl.utils.Logger.EInfo, msg); + com.nokia.mj.impl.utils.Logger.EJavaUI, + com.nokia.mj.impl.utils.Logger.EInfo, msg); } /** @@ -99,10 +111,11 @@ * * @param msg a message */ - static void info(String msg) { + static void info(String msg) + { com.nokia.mj.impl.utils.Logger.LOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, - com.nokia.mj.impl.utils.Logger.EInfo, msg); + com.nokia.mj.impl.utils.Logger.EJavaUI, + com.nokia.mj.impl.utils.Logger.EInfo, msg); } /** @@ -110,9 +123,10 @@ * * @param msg a message */ - static void warning(String msg) { + static void warning(String msg) + { com.nokia.mj.impl.utils.Logger.WLOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, msg); + com.nokia.mj.impl.utils.Logger.EJavaUI, msg); } /** @@ -120,9 +134,10 @@ * * @param msg a message */ - static void exception(String msg, Exception e) { + static void exception(String msg, Exception e) + { com.nokia.mj.impl.utils.Logger.ELOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, msg, e); + com.nokia.mj.impl.utils.Logger.EJavaUI, msg, e); // e.printStackTrace(); } @@ -131,17 +146,20 @@ * * @param msg a message */ - static void error(String msg) { + static void error(String msg) + { com.nokia.mj.impl.utils.Logger.ELOG( - com.nokia.mj.impl.utils.Logger.EJavaUI, msg); + com.nokia.mj.impl.utils.Logger.EJavaUI, msg); } /** * Indents a string with the given number of spaces. */ - static String indent(String str, int numSpacesBefore) { + static String indent(String str, int numSpacesBefore) + { String ret = (str == null ? "" : str); - for (int i = 0; i < numSpacesBefore; i++) { + for(int i = 0; i < numSpacesBefore; i++) + { ret = " " + ret; } return ret; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/MsgRepository.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/MsgRepository.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/MsgRepository.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -22,51 +22,52 @@ * class should begin with prefix "CLASSNAME_" where CLASSNAME is the name of * the class which is using the constant. */ -final class MsgRepository { +final class MsgRepository +{ // Command labels: public static final String COMMAND_LABEL_SCREEN = - OpenLcduiLocalization.getMessage("key_select"); + OpenLcduiLocalization.getMessage("key_select"); public static final String COMMAND_LABEL_BACK = - OpenLcduiLocalization.getMessage("back"); + OpenLcduiLocalization.getMessage("back"); public static final String COMMAND_LABEL_CANCEL = - SWT.getMessage("cancel"); + SWT.getMessage("cancel"); public static final String COMMAND_LABEL_OK = - SWT.getMessage("ok"); + SWT.getMessage("ok"); public static final String COMMAND_LABEL_HELP = - OpenLcduiLocalization.getMessage("help"); + OpenLcduiLocalization.getMessage("help"); public static final String COMMAND_LABEL_STOP = - OpenLcduiLocalization.getMessage("key_stop"); + OpenLcduiLocalization.getMessage("key_stop"); public static final String COMMAND_LABEL_EXIT = - OpenLcduiLocalization.getMessage("close"); + OpenLcduiLocalization.getMessage("close"); public static final String COMMAND_LABEL_ITEM = - OpenLcduiLocalization.getMessage("key_select"); + OpenLcduiLocalization.getMessage("key_select"); // Alert texts: public static final String ALERT_DEFAULT_TEXT_ERROR = - OpenLcduiLocalization.getMessage("alert_error"); + OpenLcduiLocalization.getMessage("alert_error"); public static final String ALERT_DEFAULT_TEXT_WARNING = - OpenLcduiLocalization.getMessage("alert_warning"); + OpenLcduiLocalization.getMessage("alert_warning"); public static final String ALERT_DEFAULT_TEXT_INFO = - OpenLcduiLocalization.getMessage("alert_info"); + OpenLcduiLocalization.getMessage("alert_info"); public static final String ALERT_DEFAULT_TEXT_CONFIRMATION = - OpenLcduiLocalization.getMessage("alert_conf"); + OpenLcduiLocalization.getMessage("alert_conf"); public static final String ALERT_DEFAULT_TEXT_ALARM = - OpenLcduiLocalization.getMessage("alert_alarm"); + OpenLcduiLocalization.getMessage("alert_alarm"); public static final String ALERT_DEFAULT_TEXT_ALERT = - OpenLcduiLocalization.getMessage("alert_null"); + OpenLcduiLocalization.getMessage("alert_null"); // Exceptions below - dont need translation !!! @@ -330,7 +331,7 @@ "Image data is null"; public static final String IMAGE_EXCEPTION_INVALID_BOUNDS = - "Invalid image array bounds"; + "Invalid image array bounds"; public static final String IMAGE_EXCEPTION_IS_NULL = "Image is null"; @@ -358,6 +359,7 @@ /** * Private Constructor. */ - private MsgRepository() { + private MsgRepository() + { } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Row.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Row.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Row.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,7 +21,8 @@ /** * Class which represents one row in the Form. */ -class Row { +class Row +{ private Vector layoutObjects = new Vector(); @@ -39,7 +40,8 @@ * @param rowWidth - total row width. * @param hLayout horizontal layout */ - Row(int rowWidth, int hLayout) { + Row(int rowWidth, int hLayout) + { this.rowWidth = rowWidth; setRowHLayout(hLayout); } @@ -49,9 +51,12 @@ * * @param layoutObj structure which represents Item or part Of Item. */ - void addLayoutObject(final LayoutObject layoutObj) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void addLayoutObject(final LayoutObject layoutObj) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { eswtAddLayoutObject(layoutObj); } }); @@ -62,7 +67,8 @@ * * @param lo structure which represents Item or part Of Item. */ - void eswtAddLayoutObject(LayoutObject lo) { + void eswtAddLayoutObject(LayoutObject lo) + { layoutObjects.addElement(lo); // update actual occupiedSpace occupiedSpace += lo.getWidth(); @@ -73,13 +79,16 @@ /** * Get the number of items with the given layout. */ - int getNumLayoutObjects(int layoutMask) { + int getNumLayoutObjects(int layoutMask) + { int ret = 0; int num = layoutObjects.size(); LayoutObject lo = null; - for (int i = 0; i < num; i++) { + for(int i = 0; i < num; i++) + { lo = (LayoutObject) layoutObjects.elementAt(i); - if (lo.getOwningItem().hasLayout(layoutMask)) { + if(lo.getOwningItem().hasLayout(layoutMask)) + { ret++; } } @@ -91,7 +100,8 @@ * * @return space available for Items on that Row in pixels. */ - int getFreeSpace() { + int getFreeSpace() + { return getFreeSpace(Item.LAYOUT_SHRINK | Item.LAYOUT_EXPAND); } @@ -102,11 +112,13 @@ * * @param layoutMask layout mask */ - int getFreeSpace(int layoutMask) { + int getFreeSpace(int layoutMask) + { int ret = 0; int num = layoutObjects.size(); LayoutObject lo = null; - for (int i = 0; i < num; i++) { + for(int i = 0; i < num; i++) + { lo = (LayoutObject) layoutObjects.elementAt(i); ret += getObjectWidth(lo, layoutMask); } @@ -120,33 +132,41 @@ * * @param layoutMask layout mask */ - int getRowHeight(int layoutMask) { + int getRowHeight(int layoutMask) + { int ret = 0; int num = layoutObjects.size(); LayoutObject lo = null; - for (int i = 0; i < num; i++) { + for(int i = 0; i < num; i++) + { lo = (LayoutObject) layoutObjects.elementAt(i); ret = Math.max(ret, getObjectHeight(lo, layoutMask)); } return ret; } - private int getObjectWidth(LayoutObject lo, int layoutMask) { - if (lo.getOwningItem().hasLayout(layoutMask)) { + private int getObjectWidth(LayoutObject lo, int layoutMask) + { + if(lo.getOwningItem().hasLayout(layoutMask)) + { // this returns the min/pref width return lo.getOwningItem().getLayoutWidth(); } - else { + else + { return lo.getWidth(); } } - private int getObjectHeight(LayoutObject lo, int layoutMask) { - if (lo.getOwningItem().hasLayout(layoutMask)) { + private int getObjectHeight(LayoutObject lo, int layoutMask) + { + if(lo.getOwningItem().hasLayout(layoutMask)) + { // this returns the min/pref width return lo.getOwningItem().getLayoutHeight(); } - else { + else + { return lo.getHeight(); } } @@ -156,15 +176,19 @@ * * @param keepItem Last Item to leave in a row. */ - boolean cleanRow(Item keepItem) { + boolean cleanRow(Item keepItem) + { LayoutObject lo = null; - for (int i = (layoutObjects.size() - 1); i >= 0; i--) { + for(int i = (layoutObjects.size() - 1); i >= 0; i--) + { lo = (LayoutObject) layoutObjects.elementAt(i); - if (keepItem != null && keepItem == lo.getOwningItem()) { + if(keepItem != null && keepItem == lo.getOwningItem()) + { updateRowInternals(); return true; } - else { + else + { layoutObjects.removeElement(lo); lo.dispose(); } @@ -178,25 +202,30 @@ * This method called by Layouters or FormLayoutPolicy when row is full and * ready for layout. */ - void updateRowLayout(boolean isLeftToRight) { + void updateRowLayout(boolean isLeftToRight) + { // update xShift xShift = ItemLayouter.getXLocation(rowWidth, occupiedSpace, rowHLayout); int xDelta = 0; LayoutObject lo = null; - if (isLeftToRight) { - for (int i = 0; i < layoutObjects.size(); i++) { + if(isLeftToRight) + { + for(int i = 0; i < layoutObjects.size(); i++) + { lo = (LayoutObject) layoutObjects.elementAt(i); int yDelta = ItemLayouter.getYLocation(rowHeight, - lo.getHeight(), lo.getVerticalLayout()); + lo.getHeight(), lo.getVerticalLayout()); lo.eswtSetLocation(xShift + xDelta, yShift + yDelta); xDelta += lo.getWidth(); } } - else { - for (int i = layoutObjects.size() - 1; i > 0; i--) { + else + { + for(int i = layoutObjects.size() - 1; i > 0; i--) + { lo = (LayoutObject) layoutObjects.elementAt(i); int yDelta = ItemLayouter.getYLocation(rowHeight, - lo.getHeight(), lo.getVerticalLayout()); + lo.getHeight(), lo.getVerticalLayout()); lo.eswtSetLocation(xShift + xDelta, yShift + yDelta); xDelta += lo.getWidth(); } @@ -207,12 +236,14 @@ * Update width and height of a row if some layout objects were removed or * changed. */ - void updateRowInternals() { + void updateRowInternals() + { int newRowHeight = 0; int newOccupiedSpace = 0; int num = layoutObjects.size(); LayoutObject lo = null; - for (int i = 0; i < num; i++) { + for(int i = 0; i < num; i++) + { lo = (LayoutObject) layoutObjects.elementAt(i); newRowHeight = Math.max(newRowHeight, lo.getHeight()); newOccupiedSpace += lo.getWidth(); @@ -227,7 +258,8 @@ * * @param aYShift yPosition of the row inside ScrolledComposite */ - void setYShift(int aYShift) { + void setYShift(int aYShift) + { yShift = aYShift; } @@ -236,7 +268,8 @@ * * @return yShift in pixels */ - int getYShift() { + int getYShift() + { return yShift; } @@ -245,7 +278,8 @@ * * @return - row's total width. */ - int getRowWidth() { + int getRowWidth() + { return rowWidth; } @@ -254,14 +288,16 @@ * * @return height of a row; */ - int getRowHeight() { + int getRowHeight() + { return rowHeight; } /** * Get the bottom (yPosition + rowHeight) of a Row . */ - int getBottomPosition() { + int getBottomPosition() + { return yShift + rowHeight; } @@ -271,7 +307,8 @@ * @param yPosition the y position * @return yShift + rowHeight in pixels */ - boolean isInsideRow(int yPosition) { + boolean isInsideRow(int yPosition) + { return (yShift <= yPosition && yPosition < yShift + rowHeight); } @@ -280,7 +317,8 @@ * * @param aRowHLayout - set new horizontal of the row. */ - void setRowHLayout(int aRowHLayout) { + void setRowHLayout(int aRowHLayout) + { rowHLayout = aRowHLayout; } @@ -289,60 +327,73 @@ * * @return horizontal Layout of a row; */ - int getRowHLayout() { + int getRowHLayout() + { return rowHLayout; } - boolean isEmpty() { + boolean isEmpty() + { return ((occupiedSpace == 0) && (layoutObjects.size() == 0)); } - LayoutObject getNextLayoutObject(LayoutObject lo, Item item) { + LayoutObject getNextLayoutObject(LayoutObject lo, Item item) + { int startIdx = layoutObjects.indexOf(lo); startIdx = (startIdx < 0 ? 0 : startIdx + 1); int num = layoutObjects.size(); LayoutObject temp = null; - for (int i = startIdx; i < num; i++) { + for(int i = startIdx; i < num; i++) + { temp = getLayoutObject(i); - if (item == null || item == temp.getOwningItem()) { + if(item == null || item == temp.getOwningItem()) + { return temp; } } return null; } - LayoutObject getPrevLayoutObject(LayoutObject lo, Item item) { + LayoutObject getPrevLayoutObject(LayoutObject lo, Item item) + { int startIdx = layoutObjects.indexOf(lo); startIdx = (startIdx < 0 ? layoutObjects.size() - 1 : startIdx - 1); LayoutObject temp = null; - for (int i = startIdx; i >= 0; i--) { + for(int i = startIdx; i >= 0; i--) + { temp = getLayoutObject(i); - if (item == null || item == temp.getOwningItem()) { + if(item == null || item == temp.getOwningItem()) + { return temp; } } return null; } - LayoutObject getNextLayoutObject(LayoutObject lo, int layoutMask) { + LayoutObject getNextLayoutObject(LayoutObject lo, int layoutMask) + { int startIdx = layoutObjects.indexOf(lo); startIdx = (startIdx < 0 ? 0 : startIdx + 1); int num = layoutObjects.size(); LayoutObject temp = null; - for (int i = startIdx; i < num; i++) { + for(int i = startIdx; i < num; i++) + { temp = getLayoutObject(i); - if (temp.getOwningItem().hasLayout(layoutMask)) { + if(temp.getOwningItem().hasLayout(layoutMask)) + { return temp; } } return null; } - LayoutObject getLayoutObject(int index) { + LayoutObject getLayoutObject(int index) + { return (LayoutObject) layoutObjects.elementAt(index); } - int size() { + int size() + { return layoutObjects.size(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Screen.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Screen.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Screen.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -20,12 +20,14 @@ * Super class for all high level UI classes e.g Form, TextBox. Appearance and * interaction is defined in subclasses. */ -public abstract class Screen extends Displayable { +public abstract class Screen extends Displayable +{ /** * Constructor. */ - Screen(String title) { + Screen(String title) + { super(title); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledComposite.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledComposite.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledComposite.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -25,7 +25,8 @@ * Implementation of ScrolledComposite control. */ class ScrolledComposite extends Composite implements FocusListener, - ControlListener { + ControlListener +{ private ScrollBar vBar; @@ -35,10 +36,12 @@ * @param parent * @param style */ - public ScrolledComposite(Composite parent, int style) { + public ScrolledComposite(Composite parent, int style) + { super(parent, style); vBar = parent.getVerticalBar(); - if (vBar != null) { + if(vBar != null) + { vBar.addSelectionListener(new ScrollBarListener()); } @@ -53,16 +56,20 @@ * @param x X-coordinate * @param y Y-coordinate */ - void setOrigin(int x, int y, boolean keyNavigation) { + void setOrigin(int x, int y, boolean keyNavigation) + { //setRedraw(false); - if (vBar != null) { - if (keyNavigation) { + if(vBar != null) + { + if(keyNavigation) + { vBar.setSelection(y); } y = -vBar.getSelection(); } - else { + else + { y = 0; } @@ -73,64 +80,81 @@ /** * Updates range and thumb size of the ScrollBars. */ - void updateScrollbar(int height) { + void updateScrollbar(int height) + { Rectangle clientArea = getParent().getClientArea(); - if (vBar != null) { + if(vBar != null) + { vBar.setMinimum(0); vBar.setMaximum(height); vBar.setThumb(clientArea.height); } } - private class ScrollBarListener implements SelectionListener { + private class ScrollBarListener implements SelectionListener + { - public void widgetDefaultSelected(SelectionEvent e) { + public void widgetDefaultSelected(SelectionEvent e) + { Logger.verbose(e.toString()); } - public void widgetSelected(SelectionEvent e) { + public void widgetSelected(SelectionEvent e) + { Logger.verbose(e.toString()); } } - private class ScrollKeyListener implements KeyListener { + private class ScrollKeyListener implements KeyListener + { - public void keyPressed(KeyEvent e) { + public void keyPressed(KeyEvent e) + { Logger.verbose(e.toString()); } - public void keyReleased(KeyEvent e) { + public void keyReleased(KeyEvent e) + { Logger.verbose(e.toString()); } } - private class ScrollTraverseListener implements TraverseListener { + private class ScrollTraverseListener implements TraverseListener + { - public void keyTraversed(TraverseEvent e) { + public void keyTraversed(TraverseEvent e) + { } } - private class ScrollControlListener implements ControlListener { + private class ScrollControlListener implements ControlListener + { - public void controlMoved(ControlEvent e) { + public void controlMoved(ControlEvent e) + { } - public void controlResized(ControlEvent e) { + public void controlResized(ControlEvent e) + { } } - public void focusGained(FocusEvent e) { + public void focusGained(FocusEvent e) + { // makeVisible((Control) e.widget); } - public void focusLost(FocusEvent e) { + public void focusLost(FocusEvent e) + { } - public void controlMoved(ControlEvent e) { + public void controlMoved(ControlEvent e) + { updateScrollbar(0); } - public void controlResized(ControlEvent e) { + public void controlResized(ControlEvent e) + { updateScrollbar(0); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledTextComposite.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledTextComposite.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/ScrolledTextComposite.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -29,7 +29,8 @@ /** * Composite control which is able to scroll text with a vertical scroll bar. */ -class ScrolledTextComposite extends Composite { +class ScrolledTextComposite extends Composite +{ private Label iESWTTextLabel; private ScrollBar vBar; @@ -39,7 +40,8 @@ /** * Constructor. */ - public ScrolledTextComposite(Composite parent, ScrollBar vertBar) { + public ScrolledTextComposite(Composite parent, ScrollBar vertBar) + { super(parent, 0); vBar = vertBar; vBar.setVisible(false); @@ -47,14 +49,18 @@ vBar.setThumb(0); vBar.setSelection(0); - vBar.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event e) { + vBar.addListener(SWT.Selection, new Listener() + { + public void handleEvent(Event e) + { vScroll(); } }); - addListener(SWT.Resize, new Listener() { - public void handleEvent(Event e) { + addListener(SWT.Resize, new Listener() + { + public void handleEvent(Event e) + { resize(); } }); @@ -63,26 +69,32 @@ iESWTTextLabel.setLocation(0, 0); layout(); - iESWTTextLabel.addListener(SWT.Resize, new Listener() { - public void handleEvent(Event e) { - if (e.type == SWT.Resize) { + iESWTTextLabel.addListener(SWT.Resize, new Listener() + { + public void handleEvent(Event e) + { + if(e.type == SWT.Resize) + { resize(); } } }); } - public void setText(String aText) { + public void setText(String aText) + { iESWTTextLabel.setText(aText); iESWTTextLabel.setSize(calculateTextSize()); } - private Point calculateTextSize() { + private Point calculateTextSize() + { iTextScrolling = false; vBar.setVisible(false); Point nextSize = iESWTTextLabel.computeSize(getClientArea().width, - SWT.DEFAULT); - if (nextSize.y > getClientArea().height) { + SWT.DEFAULT); + if(nextSize.y > getClientArea().height) + { iTextScrolling = true; vBar.setVisible(true); nextSize = iESWTTextLabel.computeSize(getClientArea().width, @@ -95,15 +107,18 @@ * Return if the text is scrolling. The vBar.isVisible() is not good, * because it depends on parent's visibility. */ - public boolean isTextScrolling() { + public boolean isTextScrolling() + { return iTextScrolling; } - public void setLayout(Layout layout) { + public void setLayout(Layout layout) + { // do not allow a layout to be set } - public void layout(boolean changed) { + public void layout(boolean changed) + { iESWTTextLabel.setSize(calculateTextSize()); Rectangle contentRect = iESWTTextLabel.getBounds(); @@ -112,8 +127,10 @@ vBar.setThumb(Math.min(contentRect.height, hostRect.height)); int vPage = contentRect.height - hostRect.height; int vSelection = vBar.getSelection(); - if (vSelection >= vPage) { - if (vPage <= 0) { + if(vSelection >= vPage) + { + if(vPage <= 0) + { vSelection = 0; vBar.setSelection(0); } @@ -122,37 +139,45 @@ iESWTTextLabel.setLocation(contentRect.x, contentRect.y); } - public Point computeSize(int wHint, int hHint, boolean changed) { + public Point computeSize(int wHint, int hHint, boolean changed) + { Point size = iESWTTextLabel.computeSize(wHint, hHint, changed); Rectangle trim = computeTrim(0, 0, size.x, size.y); return new Point(trim.width, trim.height); } - public Point getOrigin() { + public Point getOrigin() + { Point location = iESWTTextLabel.getLocation(); return new Point(-location.x, -location.y); } - public void setOrigin(Point origin) { + public void setOrigin(Point origin) + { setOrigin(origin.x, origin.y); } - public void setOrigin(int x, int y) { - if (iESWTTextLabel != null) { + public void setOrigin(int x, int y) + { + if(iESWTTextLabel != null) + { vBar.setSelection(y); iESWTTextLabel.setLocation(0, -vBar.getSelection()); } } - private void resize() { - if (!resizing) { + private void resize() + { + if(!resizing) + { resizing = true; layout(); resizing = false; } } - private void vScroll() { + private void vScroll() + { Point location = iESWTTextLabel.getLocation(); int vSelection = vBar.getSelection(); iESWTTextLabel.setLocation(location.x, -vSelection); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Spacer.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Spacer.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Spacer.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,69 +21,79 @@ /** * Class representing the Spacer item. */ -public class Spacer extends Item { +public class Spacer extends Item +{ private int minimumWidth = -1; private int minimumHeight = -1; /** * Constructor. - * + * * @param minW minimum width of the Spacer. * @param minH minimum height of the Spacer. */ - public Spacer(int minW, int minH) { + public Spacer(int minW, int minH) + { setMinimumSize(minW, minH); } /** * Overrides setLabel in Item class. - * + * * @param newLabel Spacer cannot have any label. */ - public void setLabel(String newLabel) { + public void setLabel(String newLabel) + { throw new IllegalStateException( - MsgRepository.SPACER_EXCEPTION_INVALID_STATE_LABEL); + MsgRepository.SPACER_EXCEPTION_INVALID_STATE_LABEL); } /** * Overrides method in Item class. - * + * * @param cmd Spacer cannot have command associated with. */ - public void addCommand(Command cmd) { + public void addCommand(Command cmd) + { throw new IllegalStateException( - MsgRepository.SPACER_EXCEPTION_INVALID_STATE_COMMAND); + MsgRepository.SPACER_EXCEPTION_INVALID_STATE_COMMAND); } /** * Overrides method in Item class. - * + * * @param newCmd Spacer cannot have command associated with. */ - public void setDefaultCommand(Command newCmd) { + public void setDefaultCommand(Command newCmd) + { throw new IllegalStateException( - MsgRepository.SPACER_EXCEPTION_INVALID_STATE_COMMAND); + MsgRepository.SPACER_EXCEPTION_INVALID_STATE_COMMAND); } /** * Set minimum size for a spacer. - * + * * @param minW new minimum width of spacer. * @param minH new minimum height of spacer. */ - public void setMinimumSize(int minW, int minH) { - if (minW < 0 || minH < 0) { + public void setMinimumSize(int minW, int minH) + { + if(minW < 0 || minH < 0) + { throw new IllegalArgumentException( - MsgRepository.SPACER_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.SPACER_EXCEPTION_INVALID_WIDTH_HEIGHT); } - else { + else + { int updateReason = Item.UPDATE_NONE; - if (minW != getMinimumWidth()) { + if(minW != getMinimumWidth()) + { minimumWidth = minW; updateReason |= Item.UPDATE_WIDTH_CHANGED; } - if (minH != getMinimumHeight()) { + if(minH != getMinimumHeight()) + { minimumHeight = minH; updateReason |= Item.UPDATE_HEIGHT_CHANGED; } @@ -93,19 +103,21 @@ /** * Calculates minimum size of this item. - * + * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return new Point(minimumWidth, minimumHeight); } /** * Calculates preferred size of this item. - * + * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return new Point(minimumWidth, minimumHeight); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/SpacerLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/SpacerLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/SpacerLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -23,14 +23,16 @@ /** * Class responsible for correct layout of Spacer item. */ -class SpacerLayouter extends ItemLayouter { +class SpacerLayouter extends ItemLayouter +{ /** * Constructor. * * @param dflp DefaultFormLayoutPolicy. */ - SpacerLayouter(DefaultFormLayoutPolicy dflp) { + SpacerLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } @@ -40,7 +42,8 @@ * @param parent for the control. * @param item Spacer item. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { Composite composite = new Composite(parent, SWT.NONE); composite.setSize(item.getMinimumWidth(), item.getMinimumHeight()); return composite; @@ -53,7 +56,8 @@ * @param control eSWT control. * @return true if this control is suitable for update */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { return true; } @@ -64,7 +68,8 @@ * @param control eSWT control. * @param reason reason to update. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { // no implementation needed. } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/StringItem.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/StringItem.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/StringItem.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,7 +21,8 @@ /** * Item representing a non-editable string. */ -public class StringItem extends Item { +public class StringItem extends Item +{ private String text; private int appearanceMode; @@ -33,7 +34,8 @@ * @param label Label of StringItem. * @param txt Text of StringItem. */ - public StringItem(String label, String txt) { + public StringItem(String label, String txt) + { this(label, txt, Item.PLAIN); } @@ -48,11 +50,13 @@ * @throws IllegalArgumentException If appearance mode is not one defined in * Item-class. */ - public StringItem(String label, String txt, int appMode) { - if ((appMode != Item.PLAIN) && (appMode != Item.BUTTON) - && (appMode != Item.HYPERLINK)) { + public StringItem(String label, String txt, int appMode) + { + if((appMode != Item.PLAIN) && (appMode != Item.BUTTON) + && (appMode != Item.HYPERLINK)) + { throw new IllegalArgumentException( - MsgRepository.STRINGITEM_EXCEPTION_INVALID_APPMODE); + MsgRepository.STRINGITEM_EXCEPTION_INVALID_APPMODE); } appearanceMode = appMode; @@ -66,7 +70,8 @@ * * @return Text of the item. Could return null if the text is empty. */ - public String getText() { + public String getText() + { return text; } @@ -75,11 +80,14 @@ * * @param newTxt Text to be set. If null, text is set to be empty. */ - public void setText(String newTxt) { - if ((newTxt == null) || (newTxt.equals(""))) { + public void setText(String newTxt) + { + if((newTxt == null) || (newTxt.equals(""))) + { text = null; } - else { + else + { text = newTxt; } updateParent(UPDATE_SIZE_CHANGED); @@ -90,7 +98,8 @@ * * @return The one of appearance modes defined in Item-class. */ - public int getAppearanceMode() { + public int getAppearanceMode() + { return appearanceMode; } @@ -101,7 +110,8 @@ * @param f Font to be used. If null, system will use default font for this * item. */ - public void setFont(Font f) { + public void setFont(Font f) + { font = (f == null ? Font.getDefaultFont() : f); updateParent(UPDATE_SIZE_CHANGED); } @@ -112,14 +122,16 @@ * * @return Font set by setFont()-method. */ - public Font getFont() { + public Font getFont() + { return font; } /* (non-Javadoc) * @see midp3javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return (getNumCommands() > 0); } @@ -128,7 +140,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return StringItemLayouter.calculateMinimumBounds(this); } @@ -137,7 +150,8 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return StringItemLayouter.calculatePreferredBounds(this); } @@ -146,11 +160,14 @@ * * @return layout directive */ - int internalGetLayout() { - if (hasLabel() && !isSizeLocked()) { + int internalGetLayout() + { + if(hasLabel() && !isSizeLocked()) + { return super.internalGetLayout() | Item.LAYOUT_NEWLINE_BEFORE; } - else { + else + { return super.internalGetLayout(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/StringItemLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/StringItemLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/StringItemLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -25,11 +25,14 @@ import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.*; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; /** * Layouter for StringItems. */ -class StringItemLayouter extends ItemLayouter { +class StringItemLayouter extends ItemLayouter +{ /** * Key name for hyperlink filter. @@ -38,14 +41,15 @@ private static final String LINE_CUT_INDICATOR = "..."; - private HyperLinkFilter hyperLinkFilter = new HyperLinkFilter(); + private HyperLinkListener hLinkListener = new HyperLinkListener(); /** * Constructor. * * @param dflp DefaultFormLayoutPolicy */ - StringItemLayouter(DefaultFormLayoutPolicy dflp) { + StringItemLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } @@ -59,27 +63,32 @@ * at least one command in it. * @return Control */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { StringItem stringItem = (StringItem) item; - if (stringItem.getAppearanceMode() == Item.BUTTON - && item.getNumCommands() > 0) { + if(stringItem.getAppearanceMode() == Item.BUTTON + && item.getNumCommands() > 0) + { Button button = new Button(parent, SWT.PUSH); button.setFont(Font.getESWTFont(stringItem.getFont())); int areaWidth = 0; String line = stringItem.getText(); - if ((areaWidth = item.getLockedPreferredWidth()) == -1) { + if((areaWidth = item.getLockedPreferredWidth()) == -1) + { areaWidth = getMaximumItemWidth(item); } line = truncateIfNewLine(line); - if (stringItem.getFont().stringWidth(line) > areaWidth) { + if(stringItem.getFont().stringWidth(line) > areaWidth) + { // Wrap string to find out how many lines it would take: Vector strings = StringWrapper.wrapString(line, - stringItem.getFont(), true, areaWidth, areaWidth); - if (strings != null && strings.size() > 1) { + stringItem.getFont(), true, areaWidth, areaWidth); + if(strings != null && strings.size() > 1) + { - line = (String) strings.elementAt(0); - line = line.substring(0, line.length()) - + LINE_CUT_INDICATOR; + line = (String) strings.elementAt(0); + line = line.substring(0, line.length()) + + LINE_CUT_INDICATOR; } } button.setText(line); @@ -91,48 +100,39 @@ /** * Add listeners to Layouter specific control. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); - if (isHyperlink(item)) { - Display disp = ESWTUIThreadRunner.getInstance().getDisplay(); - Listener listener = (Listener) disp.getData(HYPERLINK_FILTER); - if (listener == null) { - Logger.method(this, "eswtAddSpecificListener"); - disp.addFilter(SWT.KeyDown, hyperLinkFilter); - disp.setData(HYPERLINK_FILTER, hyperLinkFilter); - } - } + Logger.method(this, "eswtAddSpecificListener"); } /** * Remove listeners from Layouter specific control. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); - if (isHyperlink(item)) { - Display disp = ESWTUIThreadRunner.getInstance().getDisplay(); - Listener listener = (Listener) disp.getData(HYPERLINK_FILTER); - if (listener != null) { - Logger.method(this, "eswtRemoveSpecificListener"); - disp.removeFilter(SWT.KeyDown, hyperLinkFilter); - disp.setData(HYPERLINK_FILTER, null); - } - } + Logger.method(this, "eswtRemoveSpecificListener"); } /** * Returns true if this eSWT control is Layouter specific. */ - boolean eswtIsSpecificControl(Item item, Control control) { - if (item.getNumCommands() > 0) { + boolean eswtIsSpecificControl(Item item, Control control) + { + if(item.getNumCommands() > 0) + { int am = ((StringItem) item).getAppearanceMode(); - if (am == Item.BUTTON) { - if (control instanceof Button) { + if(am == Item.BUTTON) + { + if(control instanceof Button) + { return true; } return false; } - else if (am == Item.HYPERLINK) { + else if(am == Item.HYPERLINK) + { return true; } } @@ -143,7 +143,8 @@ /** * Updates the values of StringItem. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { // No implementation needed. } @@ -153,24 +154,30 @@ * @param row current Row * @param item Item to layout */ - void eswtLayoutItem(Row row, Item item) { + void eswtLayoutItem(Row row, Item item) + { StringItem stringItem = (StringItem) item; - if (stringItem.getNumCommands() > 0) { - if (stringItem.getAppearanceMode() == StringItem.BUTTON) { + if(stringItem.getNumCommands() > 0) + { + if(stringItem.getAppearanceMode() == StringItem.BUTTON) + { // BUTTON dfi.eswtAddNewLayoutObject( - new LayoutObject(item, eswtGetCaptionedControl(item))); + new LayoutObject(item, eswtGetCaptionedControl(item))); } - else { + else + { // HYPERLINK eswtLayoutPlainStringItem(row, stringItem, true); - if (item.isFocused()) { + if(item.isFocused()) + { // Highlight hyperlink if it is focused: eswtHighlightHyperlinkItem(item, true); } } } - else { + else + { // PLAIN eswtLayoutPlainStringItem(row, stringItem, false); } @@ -185,8 +192,10 @@ * Otherwise creates plain StringItem. */ private void eswtLayoutPlainStringItem(Row row, StringItem item, - boolean isHyperlink) { - if (item.isSizeLocked()) { + boolean isHyperlink) + { + if(item.isSizeLocked()) + { eswtLayoutLockedPlainStringItem(item, isHyperlink); return; } @@ -194,24 +203,26 @@ String label = item.getLabel(); Vector strings = StringWrapper.wrapString(item.getText(), - item.getFont(), dfi.getForm().getLeftRightLanguage(), - row.getRowWidth(), row.getFreeSpace()); + item.getFont(), dfi.getForm().getLeftRightLanguage(), + row.getRowWidth(), row.getFreeSpace()); - if (strings != null) { - for (int i = 0; i < strings.size(); i++) { + if(strings != null) + { + for(int i = 0; i < strings.size(); i++) + { // create primitive StringItem Control control = eswtCreateLabeledPrimitiveStringItem( - dfi.getForm().getFormComposite(), - (String) strings.elementAt(i), - label, item.getFont(), isHyperlink, - getMaximumItemWidth(item)); + dfi.getForm().getFormComposite(), + (String) strings.elementAt(i), + label, item.getFont(), isHyperlink, + getMaximumItemWidth(item)); // because add label to first primitive only: label = null; // layoutObject which represent primitive StringItem dfi.eswtAddNewLayoutObject( - new LayoutObject(item, control), i != 0); + new LayoutObject(item, control), i != 0); } } } @@ -228,20 +239,22 @@ * created. Otherwise creates plain StringItem. */ private void eswtLayoutLockedPlainStringItem(StringItem item, - boolean isHyperlink) { + boolean isHyperlink) + { int width = item.getPreferredWidth(); int height = item.getPreferredHeight(); Vector strings = StringWrapper.wrapString(item.getText(), - item.getFont(), dfi.getForm().getLeftRightLanguage(), - width, width); + item.getFont(), dfi.getForm().getLeftRightLanguage(), + width, width); // Create composite which will contain the lines of locked stringitem: Composite comp = new Composite(formComposite, SWT.NONE); comp.setSize(width, height); - if (strings != null) { + if(strings != null) + { // layout labels in vertical rows comp.setLayout(new RowLayout(SWT.VERTICAL)); @@ -251,25 +264,30 @@ // Calculate the index of last visible line: int spaceForRows = height; - if (item.hasLabel()) { + if(item.hasLabel()) + { spaceForRows -= getLabelSize(LINE_CUT_INDICATOR).y; } int indexOfLastVisibleRow = Math.max(spaceForRows / lineHeight - 1, 0); boolean lastLineReached = false; - for (int i = 0; !lastLineReached && i < strings.size(); i++) { + for(int i = 0; !lastLineReached && i < strings.size(); i++) + { String line = (String) strings.elementAt(i); // If there are rows left after this row but no more space ... - if ((i < strings.size() - 1) && (i == indexOfLastVisibleRow)) { + if((i < strings.size() - 1) && (i == indexOfLastVisibleRow)) + { // ... display three dots at the end of the line: - if (line.length() >= LINE_CUT_INDICATOR.length()) { + if(line.length() >= LINE_CUT_INDICATOR.length()) + { line = line.substring(0, line.length() - - LINE_CUT_INDICATOR.length()) - + LINE_CUT_INDICATOR; + - LINE_CUT_INDICATOR.length()) + + LINE_CUT_INDICATOR; } - else { + else + { line = LINE_CUT_INDICATOR; } lastLineReached = true; @@ -277,7 +295,7 @@ // create primitive StringItem eswtCreateLabeledPrimitiveStringItem(comp, line, label, item - .getFont(), isHyperlink,width); + .getFont(), isHyperlink,width); // because add label to first primitive only: label = null; @@ -299,11 +317,19 @@ */ private Control eswtCreateLabeledPrimitiveStringItem(Composite parent, String txt, String label, Font font, boolean hyperlink, - int availableWidth) { - if (label == null || label.length()<1) { - return eswtCreatePrimitiveStringItem(parent, txt, font, hyperlink); + int availableWidth) + { + if(label == null || label.length()<1) + { + Control text = eswtCreatePrimitiveStringItem(parent, txt, font, hyperlink); + if(hyperlink) + { + ((HyperLink) text).addSelectionListener(hLinkListener); + } + return text; } - else { + else + { Composite comp = new Composite(parent, SWT.NONE); Label header = new Label(comp, SWT.WRAP); @@ -311,25 +337,28 @@ header.pack(); int headerWidth = header.getBounds().width; - if (headerWidth > availableWidth) + if(headerWidth > availableWidth) { - Point size = header.computeSize(availableWidth,SWT.DEFAULT); - header.setBounds(0,0,size.x,size.y); - headerWidth = header.getBounds().width; + Point size = header.computeSize(availableWidth,SWT.DEFAULT); + header.setBounds(0,0,size.x,size.y); + headerWidth = header.getBounds().width; } Control text = eswtCreatePrimitiveStringItem(comp, txt, font, - hyperlink); - + hyperlink); + if(hyperlink) + { + ((HyperLink) text).addSelectionListener(hLinkListener); + } int textWidth = text.getBounds().width; int objectWidth = Math.max(textWidth, headerWidth); header.setLocation(ItemLayouter.getXLocation(objectWidth, - headerWidth, dfi.getLanguageSpecificLayoutDirective()), 0); + headerWidth, dfi.getLanguageSpecificLayoutDirective()), 0); text.setLocation(ItemLayouter.getXLocation(objectWidth, textWidth, - dfi.getLanguageSpecificLayoutDirective()), - header.getBounds().height); + dfi.getLanguageSpecificLayoutDirective()), + header.getBounds().height); comp.pack(); return comp; @@ -346,13 +375,16 @@ * @return */ private static Control eswtCreatePrimitiveStringItem(Composite parent, String txt, - Font font, boolean isHyperlink) { + Font font, boolean isHyperlink) + { Control text = null; - if (isHyperlink) { + if(isHyperlink) + { text = new HyperLink(parent, SWT.NONE, HyperLink.URL); ((HyperLink) text).setText(txt); } - else { + else + { text = new Label(parent, SWT.NONE); ((Label) text).setText(txt); } @@ -368,13 +400,18 @@ * @param stringItem StringItem object * @return Minimum area needed to display StringItem with specified Font. */ - static Point calculateMinimumBounds(final StringItem stringItem) { + static Point calculateMinimumBounds(final StringItem stringItem) + { final Point minSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Point size = null; - if (stringItem.getNumCommands() > 0) { - if (stringItem.getAppearanceMode() == StringItem.BUTTON) { + if(stringItem.getNumCommands() > 0) + { + if(stringItem.getAppearanceMode() == StringItem.BUTTON) + { // BUTTON: Button but = new Button(eswtGetStaticShell(), SWT.PUSH); but.setFont(Font.getESWTFont(stringItem.getFont())); @@ -384,39 +421,41 @@ but.dispose(); applyMinMargins(stringItem, size); } - else { + else + { // HYPERLINK: HyperLink hl = new HyperLink(eswtGetStaticShell(), - SWT.NONE, HyperLink.URL); + SWT.NONE, HyperLink.URL); hl.setFont(Font.getESWTFont(stringItem.getFont())); hl.setText(LINE_CUT_INDICATOR); hl.pack(); size = hl.computeSize(SWT.DEFAULT, SWT.DEFAULT); hl.dispose(); - if (stringItem.hasLabel()) + if(stringItem.hasLabel()) { - Label header = new Label(eswtGetStaticShell(),SWT.NONE); - header.setText(LINE_CUT_INDICATOR); - header.pack(); - size.y += (header.computeSize(SWT.DEFAULT,SWT.DEFAULT)).y; - header.dispose(); + Label header = new Label(eswtGetStaticShell(),SWT.NONE); + header.setText(LINE_CUT_INDICATOR); + header.pack(); + size.y += (header.computeSize(SWT.DEFAULT,SWT.DEFAULT)).y; + header.dispose(); } } } - else { + else + { Label text = new Label(eswtGetStaticShell(), SWT.NONE); // SWT.LEFT text.setFont(Font.getESWTFont(stringItem.getFont())); text.setText(LINE_CUT_INDICATOR); text.pack(); size = text.computeSize(SWT.DEFAULT, SWT.DEFAULT); text.dispose(); - if (stringItem.hasLabel()) + if(stringItem.hasLabel()) { - Label header = new Label(eswtGetStaticShell(),SWT.NONE); - header.setText(LINE_CUT_INDICATOR); - header.pack(); - size.y += (header.computeSize(SWT.DEFAULT,SWT.DEFAULT)).y; - header.dispose(); + Label header = new Label(eswtGetStaticShell(),SWT.NONE); + header.setText(LINE_CUT_INDICATOR); + header.pack(); + size.y += (header.computeSize(SWT.DEFAULT,SWT.DEFAULT)).y; + header.dispose(); } } minSize.x = size.x; @@ -433,19 +472,24 @@ * @return Preferred size needed to display Item. x is width and y is * height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { StringItem stringItem = (StringItem) item; - if (stringItem.getNumCommands() > 0) { - if (stringItem.getAppearanceMode() == StringItem.BUTTON) { + if(stringItem.getNumCommands() > 0) + { + if(stringItem.getAppearanceMode() == StringItem.BUTTON) + { // BUTTON return calculateButtonPreferredBounds(stringItem); } - else { + else + { // HYPERLINK return calculateStringItemPreferredBounds(stringItem, true); } } - else { + else + { // PLAIN return calculateStringItemPreferredBounds(stringItem, false); } @@ -458,21 +502,26 @@ * @param item Item. * @return Preferred size. */ - private static Point calculateButtonPreferredBounds(final StringItem item) { + private static Point calculateButtonPreferredBounds(final StringItem item) + { final Point prefSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { Button button = new Button(eswtGetStaticShell(), SWT.PUSH); button.setFont(Font.getESWTFont(item.getFont())); int areaWidth = 0; String line = item.getText(); - if ((areaWidth = item.getLockedPreferredWidth()) == -1) { + if((areaWidth = item.getLockedPreferredWidth()) == -1) + { areaWidth = getMaximumItemWidth(item); } line = truncateIfNewLine(line); - if (item.getFont().stringWidth(line) < areaWidth){ - areaWidth = SWT.DEFAULT; + if(item.getFont().stringWidth(line) < areaWidth) + { + areaWidth = SWT.DEFAULT; } button.setText(line); button.pack(); @@ -499,31 +548,37 @@ * @return Preferred size. */ private static Point calculateStringItemPreferredBounds( - final StringItem item, final boolean isHyperlink) { + final StringItem item, final boolean isHyperlink) + { final Point preferredSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { // Find out the width of the area where the StringItem should // be layouted: int areaWidth = 0; - if (item.getLockedPreferredWidth() != -1) { + if(item.getLockedPreferredWidth() != -1) + { areaWidth = item.getLockedPreferredWidth(); } - else { + else + { areaWidth = getMaximumItemWidth(item); } // Wrap string to find out how many lines it would take: Vector strings = StringWrapper.wrapString(item.getText(), - item.getFont(), true, areaWidth, areaWidth); + item.getFont(), true, areaWidth, areaWidth); - if (strings != null && strings.size() > 0) { + if(strings != null && strings.size() > 0) + { // Calculate the size of the first line: Control ctrl = eswtCreatePrimitiveStringItem( - eswtGetStaticShell(), - (String) strings.elementAt(0), - item.getFont(), - isHyperlink); + eswtGetStaticShell(), + (String) strings.elementAt(0), + item.getFont(), + isHyperlink); Point size = ctrl.computeSize(SWT.DEFAULT, SWT.DEFAULT); ctrl.dispose(); @@ -531,17 +586,18 @@ // be form's content area width or locked width and the // height would be the height of a line times number of // lines: - if (strings.size() > 1) { + if(strings.size() > 1) + { size.x = areaWidth; size.y *= strings.size(); } - if (item.hasLabel()) + if(item.hasLabel()) { - Label header = new Label(eswtGetStaticShell(),SWT.NONE); - header.setText(item.getLabel()); - header.pack(); - size.y += (header.computeSize(areaWidth,SWT.DEFAULT)).y; - header.dispose(); + Label header = new Label(eswtGetStaticShell(),SWT.NONE); + header.setText(item.getLabel()); + header.pack(); + size.y += (header.computeSize(areaWidth,SWT.DEFAULT)).y; + header.dispose(); } preferredSize.x = size.x; preferredSize.y = size.y; @@ -554,10 +610,12 @@ /** * Returns if this Item is hyperlink. */ - private boolean isHyperlink(Item item) { - if (item.getNumCommands() > 0 + private boolean isHyperlink(Item item) + { + if(item.getNumCommands() > 0 && item instanceof StringItem - && (((StringItem) item).getAppearanceMode() != Item.BUTTON)) { + && (((StringItem) item).getAppearanceMode() != Item.BUTTON)) + { return true; } return false; @@ -566,9 +624,11 @@ /** * Called when item gains focus. */ - void eswtFocusGained(Item item, int dir) { + void eswtFocusGained(Item item, int dir) + { super.eswtFocusGained(item, dir); - if (isHyperlink(item)) { + if(isHyperlink(item)) + { // Highlight hyperlink: eswtHighlightHyperlinkItem(item, true); } @@ -577,9 +637,11 @@ /** * Called when item losts focus. */ - void eswtFocusLost(Item item) { + void eswtFocusLost(Item item) + { super.eswtFocusLost(item); - if (isHyperlink(item)) { + if(isHyperlink(item)) + { // Remove hyperlink highlighting: eswtHighlightHyperlinkItem(item, false); } @@ -591,11 +653,14 @@ * @param item highlight StringItem * @param highlight enable or disable */ - private void eswtHighlightHyperlinkItem(Item item, boolean highlight) { + private void eswtHighlightHyperlinkItem(Item item, boolean highlight) + { LayoutObject lo = null; Control c = null; - while ((lo = dfi.getNextLayoutObjectOfItem(lo, item)) != null) { - if ((c = lo.getControl()) != null) { + while((lo = dfi.getNextLayoutObjectOfItem(lo, item)) != null) + { + if((c = lo.getControl()) != null) + { eswtHighlightHyperlink(c, highlight); } } @@ -604,19 +669,23 @@ private static Color fgColor; private static Color bgColor; - private static Color getFgColor() { - if (fgColor == null) { + private static Color getFgColor() + { + if(fgColor == null) + { fgColor = new Color(ESWTUIThreadRunner.getInstance().getDisplay(), - 0x99, 0x00, 0x00); + 0x99, 0x00, 0x00); ESWTUIThreadRunner.ds.addObject(fgColor); } return fgColor; } - private static Color getBgColor() { - if (bgColor == null) { + private static Color getBgColor() + { + if(bgColor == null) + { bgColor = new Color(ESWTUIThreadRunner.getInstance().getDisplay(), - 0xee, 0xee, 0xee); + 0xee, 0xee, 0xee); ESWTUIThreadRunner.ds.addObject(bgColor); } return bgColor; @@ -629,22 +698,28 @@ * * @param c Control where to start highlighting. */ - private void eswtHighlightHyperlink(Control c, boolean highlight) { + private void eswtHighlightHyperlink(Control c, boolean highlight) + { // TODO: eSWT support required - hyperlink highlighting. - if (c instanceof Composite) { + if(c instanceof Composite) + { Control[] children = ((Composite) c).getChildren(); - for (int i = 0; i < children.length; i++) { + for(int i = 0; i < children.length; i++) + { Control child = children[i]; - if (child instanceof Composite) { + if(child instanceof Composite) + { eswtHighlightHyperlink(child, highlight); } } } - if (highlight) { + if(highlight) + { c.setBackground(getBgColor()); c.setForeground(getFgColor()); } - else { + else + { c.setBackground(null); c.setForeground(null); } @@ -666,19 +741,23 @@ * @return truncated String if newline characters found. Otherwise returns * the string provided as parameter. */ - private static String truncateIfNewLine(String text) { + private static String truncateIfNewLine(String text) + { int indexOfFirstNewLineChar = -1; - for (int i = 0; i < text.length(); i++) { - if ((text.charAt(i) == '\r') + for(int i = 0; i < text.length(); i++) + { + if((text.charAt(i) == '\r') || (text.charAt(i) == '\n') - || (text.charAt(i) == '\u2028')) { + || (text.charAt(i) == '\u2028')) + { indexOfFirstNewLineChar = i; break; } } - if (indexOfFirstNewLineChar != -1) { + if(indexOfFirstNewLineChar != -1) + { return text.substring(0, indexOfFirstNewLineChar) - + LINE_CUT_INDICATOR; + + LINE_CUT_INDICATOR; } return text; } @@ -687,24 +766,20 @@ * Filter that blocks events if current selected item is a StringItem of * type HYPERLINK (or plain with commands). */ - class HyperLinkFilter implements Listener { + class HyperLinkListener implements SelectionListener + { - /** - * Handles event. - * - * @param event Event. - */ - public void handleEvent(Event event) { + public void widgetDefaultSelected(SelectionEvent e) + { + Logger.method(this, "widgetDefaultSelected"); + } + + public void widgetSelected(SelectionEvent e) + { + Logger.method(this, "widgetSelected"); + e.doit = false; Item item = dfi.getCurrentSelectedItem(); - if (event.keyCode == Config.STRINGITEM_MSK_KEYCODE) { - if (isHyperlink(item)) { - // Do not allow event to go forward because it will - // start browser and that's not how it should work: - event.doit = false; - // Instead activate command associated with MSK button: - item.callCommandAction(item.getMSKCommand()); - } - } + item.callCommandAction(item.getMSKCommand()); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/StringWrapper.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/StringWrapper.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/StringWrapper.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,11 +21,13 @@ /** * Utility class used to wrap a string for StringItem layout. */ -final class StringWrapper { +final class StringWrapper +{ private static final String DELIM_STR = " ,.;:!?-\n"; - private StringWrapper() { + private StringWrapper() + { super(); } @@ -43,13 +45,16 @@ Font stringItemFont, boolean leftToRightLayout, int fullWidth, - int freeWidth) { - if (leftToRightLayout) { + int freeWidth) + { + if(leftToRightLayout) + { // if left-to-right then just call wrapping method return doWrapString(inputString, stringItemFont, fullWidth, - freeWidth); + freeWidth); } - else { + else + { // if right-to-left then: // 1) reverse the string // 2) do wrapping @@ -58,9 +63,10 @@ StringBuffer temp = new StringBuffer(inputString); Vector ret = doWrapString(temp.reverse().toString(), - stringItemFont, fullWidth, freeWidth); + stringItemFont, fullWidth, freeWidth); - for (int i = 0; i < ret.size(); i++) { + for(int i = 0; i < ret.size(); i++) + { temp.setLength(0); temp.append((String) ret.elementAt(i)); ret.setElementAt(temp.reverse().toString(), i); @@ -81,11 +87,13 @@ private static Vector doWrapString(String inputString, Font font, int fullWidth, - int freeWidth) { + int freeWidth) + { Vector result = new Vector(); // Could happen if StringItem.setText(null) or StringItem.setText("") // was called - if (inputString == null) { + if(inputString == null) + { result.addElement(""); return result; } @@ -98,16 +106,20 @@ String str = inputString; String token = ""; - while (str.length() > 0) { + while(str.length() > 0) + { nextDelimiterPos = findNextDelimiter(str, nextDelimiterPos + 1); token = str.substring(0, nextDelimiterPos).trim(); tokenWidth = font.stringWidth(token); - if (tokenWidth > availableWidth) { - if (delimiterPos == 0) { + if(tokenWidth > availableWidth) + { + if(delimiterPos == 0) + { // even the first word in the string is too long to fit - if ((availableWidth < fullWidth) - && (tokenWidth <= fullWidth)) { + if((availableWidth < fullWidth) + && (tokenWidth <= fullWidth)) + { // the long word would fit to the next full row // result.addElement(""); availableWidth = fullWidth; @@ -116,7 +128,8 @@ continue; } - if (tokenWidth > fullWidth) { + if(tokenWidth > fullWidth) + { // the long word does not fit to a full row // do character-boundary wrapping delimiterPos = @@ -138,15 +151,17 @@ continue; } - if (nextDelimiterPos == str.length()) { + if(nextDelimiterPos == str.length()) + { result.addElement(token); availableWidth = fullWidth; str = str.substring(nextDelimiterPos); continue; } - if (nextDelimiterPos < str.length() - && str.charAt(nextDelimiterPos) == '\n') { + if(nextDelimiterPos < str.length() + && str.charAt(nextDelimiterPos) == '\n') + { result.addElement(token); availableWidth = fullWidth; str = str.substring(nextDelimiterPos + 1); @@ -166,9 +181,11 @@ * @param word - Word to break * @return Part of word that fits in the current available space */ - private static int findWordBreak(String word, Font font, int width) { + private static int findWordBreak(String word, Font font, int width) + { int breakPos = word.length(); - while (font.substringWidth(word, 0, breakPos) > width) { + while(font.substringWidth(word, 0, breakPos) > width) + { breakPos--; } return breakPos; @@ -182,13 +199,17 @@ * @param startPos Start position for search * @return The first delimiter found */ - private static int findNextDelimiter(String str, int startPos) { + private static int findNextDelimiter(String str, int startPos) + { int strLen = str.length(); int pos = startPos; - for (; pos < strLen; pos++) { + for(; pos < strLen; pos++) + { int delimiter = DELIM_STR.indexOf(str.charAt(pos)); - if (delimiter >= 0) { - if (delimiter < 8) { + if(delimiter >= 0) + { + if(delimiter < 8) + { // 8 is the '\n' character's index return pos + 1; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextBox.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextBox.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextBox.java Fri May 14 15:47:24 2010 +0300 @@ -11,11 +11,13 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; +import com.nokia.mj.impl.rt.support.ApplicationInfo; + import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; @@ -26,7 +28,8 @@ * The behavior of this editor may be different according * to applied constraints. */ -public class TextBox extends Screen { +public class TextBox extends Screen +{ private TextModifyListener modListener = new TextModifyListener(); @@ -42,7 +45,8 @@ * @param maxSize - maximum number of characters to insert * @param constraints - text constraint (e.g. URL, EMEAIL etc) */ - public TextBox(String title, String text, int maxSize, int constraints) { + public TextBox(String title, String text, int maxSize, int constraints) + { super(title); textWrapper = new TextWrapper(text, maxSize, constraints); construct(); @@ -53,22 +57,33 @@ * * @return custom eSWT dialog shell */ - Shell eswtConstructShell(int style) { + Shell eswtConstructShell(int style) + { Shell topShell = super.eswtConstructShell(style); // TextBox with null title and ANY constraint, should be Full-Screen - if (getTitle() == null && TextWrapper.getTypeConstraint( - textWrapper.getConstraints()) == TextField.ANY) { + if(getTitle() == null && TextWrapper.getTypeConstraint( + textWrapper.getConstraints()) == TextField.ANY) + { return topShell; } - else { - return new Shell(topShell, style | SWT.DIALOG_TRIM | SWT.RESIZE); + else + { + if(JadAttributeUtil.isValue(JadAttributeUtil.ATTRIB_NOKIA_UI_ENHANCEMENT, JadAttributeUtil.VALUE_FULLSCREEN_TEXTBOX)) + { + return topShell; + } + else + { + return new Shell(topShell, style | SWT.DIALOG_TRIM | SWT.RESIZE); + } } } /* (non-Javadoc) * @see Displayable#eswtConstructContent(int) */ - Composite eswtConstructContent(int style) { + Composite eswtConstructContent(int style) + { Composite ret = super.eswtConstructContent(style); textWrapper.eswtConstruct(ret, SWT.V_SCROLL); return ret; @@ -77,17 +92,19 @@ /* (non-Javadoc) * @see Displayable#eswtHandleShowCurrentEvent() */ - void eswtHandleShowCurrentEvent() { + void eswtHandleShowCurrentEvent() + { super.eswtHandleShowCurrentEvent(); textWrapper.setModifyListener(modListener); eswtSetPreferredContentSize(-1, textWrapper - .getPreferredHeight(Config.TEXTBOX_MAX_VISIBLE_LINES)); + .getPreferredHeight(Config.TEXTBOX_MAX_VISIBLE_LINES)); } /* (non-Javadoc) * @see Displayable#eswtHandleHideCurrentEvent() */ - void eswtHandleHideCurrentEvent() { + void eswtHandleHideCurrentEvent() + { super.eswtHandleHideCurrentEvent(); textWrapper.setModifyListener(null); } @@ -95,7 +112,8 @@ /* (non-Javadoc) * @see Displayable#eswtHandleResizeEvent(int, int) */ - void eswtHandleResizeEvent(int width, int height) { + void eswtHandleResizeEvent(int width, int height) + { super.eswtHandleResizeEvent(width, height); textWrapper.setBounds(getContentComp().getClientArea()); } @@ -105,7 +123,8 @@ * * @return current caret position */ - public int getCaretPosition() { + public int getCaretPosition() + { return textWrapper.getCaretPosition(); } @@ -114,7 +133,8 @@ * * @return String with TexBox content */ - public String getString() { + public String getString() + { return textWrapper.getContent(); } @@ -123,7 +143,8 @@ * * @param newText - String to set into TextBox */ - public void setString(String newText) { + public void setString(String newText) + { textWrapper.setContent(newText); } @@ -133,14 +154,17 @@ * @param charData array where to copy TextBox content * @return number of copied characters. */ - public int getChars(char[] charData) { - if (charData == null) { + public int getChars(char[] charData) + { + if(charData == null) + { throw new NullPointerException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); } - if (charData.length < getString().length()) { + if(charData.length < getString().length()) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_TOO_SHORT); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_TOO_SHORT); } String content = textWrapper.getContent(); content.getChars(0, content.length(), charData, 0); @@ -155,13 +179,17 @@ * @param offset start index in charData. * @param length how many characters to copy. */ - public void setChars(char[] charData, int offset, int length) { + public void setChars(char[] charData, int offset, int length) + { String extractedString = null; - if (charData != null) { - try { + if(charData != null) + { + try + { extractedString = new String(charData, offset, length); } - catch (IndexOutOfBoundsException e) { + catch(IndexOutOfBoundsException e) + { throw new ArrayIndexOutOfBoundsException(); } } @@ -174,7 +202,8 @@ * @param text text to insert, must not be null. * @param position where to insert. */ - public void insert(String text, int position) { + public void insert(String text, int position) + { textWrapper.insert(text, position); } @@ -186,16 +215,20 @@ * @param length number of characters to copy. * @param position in TextBox where to insert. */ - public void insert(char[] charData, int offset, int length, int position) { - if (charData == null) { + public void insert(char[] charData, int offset, int length, int position) + { + if(charData == null) + { throw new NullPointerException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); } String extractedString = null; - try { + try + { extractedString = new String(charData, offset, length); } - catch (IndexOutOfBoundsException e) { + catch(IndexOutOfBoundsException e) + { throw new ArrayIndexOutOfBoundsException(); } textWrapper.insert(extractedString, position); @@ -207,7 +240,8 @@ * @param offset - start index in TextBox to delete from. * @param length number of characters to delete. */ - public void delete(int offset, int length) { + public void delete(int offset, int length) + { textWrapper.delete(offset, length); } @@ -216,7 +250,8 @@ * * @return number of characters allowed for the TextBox. */ - public int getMaxSize() { + public int getMaxSize() + { return textWrapper.getMaxSize(); } @@ -227,7 +262,8 @@ * @param newMaxSize sets the capacity of TextBox. * @return maxSize that was set. */ - public int setMaxSize(int newMaxSize) { + public int setMaxSize(int newMaxSize) + { textWrapper.setMaxSize(newMaxSize); return textWrapper.getMaxSize(); } @@ -237,7 +273,8 @@ * * @return number if inputed Characters. */ - public int size() { + public int size() + { return textWrapper.getSize(); } @@ -246,7 +283,8 @@ * * @param newConstraints constraint to apply to TextBox */ - public void setConstraints(int newConstraints) { + public void setConstraints(int newConstraints) + { textWrapper.setConstraints(newConstraints); } @@ -255,7 +293,8 @@ * * @return current applied constraints */ - public int getConstraints() { + public int getConstraints() + { return textWrapper.getConstraints(); } @@ -264,24 +303,26 @@ * * @param inputMode input mode to set. */ - public void setInitialInputMode(String inputMode) { + public void setInitialInputMode(String inputMode) + { textWrapper.setInputMode(inputMode); } /** * Text modify listener. */ - class TextModifyListener implements ModifyListener { + class TextModifyListener implements ModifyListener + { - public void modifyText(ModifyEvent me) { + public void modifyText(ModifyEvent me) + { int lines = TextWrapper.eswtGetLineCount((Control) me.widget); - if (numLines != lines) { + if(numLines != lines) + { // the number of lines changed numLines = lines; eswtSetPreferredContentSize(-1, textWrapper - .getPreferredHeight(Config.TEXTBOX_MAX_VISIBLE_LINES)); - // hide/show vertical scrollbar automatically - TextWrapper.eswtUpdateVScrollbar((Control) me.widget); + .getPreferredHeight(Config.TEXTBOX_MAX_VISIBLE_LINES)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditor.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditor.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditor.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ /* @@ -110,7 +110,8 @@ * @since 3.0 */ -public class TextEditor { +public class TextEditor +{ private static final int BITSPERPIXEL8 = 255; @@ -152,7 +153,8 @@ * @throws IllegalArgumentException if the width or height is less than zero */ public TextEditor(String text, int maxSize, int constraints, int width, - int height) { + int height) + { textWrapper = new TextWrapper(text, maxSize, constraints); textWrapper.setFocused(false); textWrapper.setModifyListener(modListener); @@ -166,16 +168,20 @@ * * @param newParent parent */ - public void setParent(Object newParent) { - if (newParent != null) { - if (newParent instanceof Canvas) { + public void setParent(Object newParent) + { + if(newParent != null) + { + if(newParent instanceof Canvas) + { // constructing on another composite disposes the old one textWrapper.construct(((Canvas) newParent).getContentComp(), - SWT.NONE); + SWT.NONE); parent = newParent; } } - else { + else + { textWrapper.dispose(); parent = newParent; } @@ -198,7 +204,8 @@ * length do not specify a valid range within the * content of the TextEditor */ - public void delete(int offset, int length) { + public void delete(int offset, int length) + { textWrapper.delete(offset, length); } @@ -211,7 +218,8 @@ * * @return the x and y coordinates of the current caret position */ - public int[] getCaretPixelPosition() { + public int[] getCaretPixelPosition() + { // TODO: implement this return null; } @@ -221,7 +229,8 @@ * * @return the current caret position, 0 if at the beginning */ - public int getCaretPosition() { + public int getCaretPosition() + { return textWrapper.getCaretPosition(); } @@ -231,7 +240,8 @@ * @return the current constraints value (see input constraints) */ - public int getConstraints() { + public int getConstraints() + { return textWrapper.getConstraints(); } @@ -243,10 +253,11 @@ * @param length the number of the characters to be returned * @return the editor current content */ - public String getContent(int index, int length) { + public String getContent(int index, int length) + { String content = textWrapper.getContent(); return content.substring(Math.max(0, index), - Math.min(index + length, content.length())); + Math.min(index + length, content.length())); } /** @@ -256,7 +267,8 @@ * * @return the height of the whole content in the editor in pixels */ - public int getContentHeight() { + public int getContentHeight() + { return textWrapper.getLineCount() * textWrapper.getLineHeight(); } @@ -265,7 +277,8 @@ * * @return height in pixels */ - public int getHeight() { + public int getHeight() + { return textWrapper.getHeight(); } @@ -278,7 +291,8 @@ * * @return the width and height of area needed for drawing input indicators */ - public int[] getIndicatorSize() { + public int[] getIndicatorSize() + { // TODO: implement this return null; } @@ -288,7 +302,8 @@ * * @return the line height in pixels */ - public int getLineHeight() { + public int getLineHeight() + { return textWrapper.getLineHeight(); } @@ -298,7 +313,8 @@ * * @return the maximum size in characters */ - public int getMaxSize() { + public int getMaxSize() + { return textWrapper.getMaxSize(); } @@ -307,7 +323,8 @@ * * @return the number of visible rows in the editor */ - public int getRows() { + public int getRows() + { return textWrapper.getHeight() / textWrapper.getLineHeight(); } @@ -317,7 +334,8 @@ * * @return the currently selected content */ - public String getSelection() { + public String getSelection() + { return textWrapper.getSelectedContent(); } @@ -326,7 +344,8 @@ * * @return width in pixels */ - public int getWidth() { + public int getWidth() + { return textWrapper.getWidth(); } @@ -340,7 +359,8 @@ * * @return the topmost pixel position of the visible content */ - public int getVisibleContentPosition() { + public int getVisibleContentPosition() + { return textWrapper.getTopPixelPosition(); } @@ -355,7 +375,8 @@ * CustomItem * @see #show() */ - public void hide() { + public void hide() + { textWrapper.setVisible(false); } @@ -379,7 +400,8 @@ * current maximum capacity * @throws NullPointerException if text is null */ - public void insert(String text, int position) { + public void insert(String text, int position) + { textWrapper.insert(text, position); } @@ -397,7 +419,8 @@ * * @see #setFocus() */ - public void removeFocus() { + public void removeFocus() + { textWrapper.setFocused(false); } @@ -418,11 +441,13 @@ * @throws IllegalArgumentException if any parameter is outside of the range * 0-255 */ - public void setBackgroundColor(int alpha, int red, int green, int blue) { - if ((alpha < 0 || alpha > BITSPERPIXEL8) + public void setBackgroundColor(int alpha, int red, int green, int blue) + { + if((alpha < 0 || alpha > BITSPERPIXEL8) || (red < 0 || red > BITSPERPIXEL8) || (green < 0 || green > BITSPERPIXEL8) - || (blue < 0 || blue > BITSPERPIXEL8)) { + || (blue < 0 || blue > BITSPERPIXEL8)) + { throw new IllegalArgumentException(); } textWrapper.setBackgroundColor(alpha, red, green, blue); @@ -434,7 +459,8 @@ * * @param index the character index before which to place the caret */ - public void setCaret(int index) { + public void setCaret(int index) + { textWrapper.setCaretposition(index); } @@ -448,7 +474,8 @@ * @throws IllegalArgumentException if the value of the constraints * parameter is invalid */ - public void setConstraints(int constraints) { + public void setConstraints(int constraints) + { textWrapper.setConstraints(constraints); } @@ -463,7 +490,8 @@ * @throws IllegalArgumentException if the given text would exceed the * current maximum capacity of the editor */ - public void setContent(String text) { + public void setContent(String text) + { textWrapper.setContent(text); } @@ -516,8 +544,10 @@ * CustomItem * @see #removeFocus() */ - public void setFocus() { - if (parent == null) { + public void setFocus() + { + if(parent == null) + { throw new IllegalStateException(); } textWrapper.setFocused(true); @@ -534,7 +564,8 @@ * * @param font the application preferred font to be used in this TextEditor */ - public void setFont(Font font) { + public void setFont(Font font) + { textWrapper.setFont(font); } @@ -554,11 +585,13 @@ * @throws IllegalArgumentException if any parameter is outside of the range * 0-255 */ - public void setForegroundColor(int alpha, int red, int green, int blue) { - if ((alpha < 0 || alpha > BITSPERPIXEL8) + public void setForegroundColor(int alpha, int red, int green, int blue) + { + if((alpha < 0 || alpha > BITSPERPIXEL8) || (red < 0 || red > BITSPERPIXEL8) || (green < 0 || green > BITSPERPIXEL8) - || (blue < 0 || blue > BITSPERPIXEL8)) { + || (blue < 0 || blue > BITSPERPIXEL8)) + { throw new IllegalArgumentException(); } textWrapper.setForegroundColor(alpha, red, green, blue); @@ -578,7 +611,8 @@ * @param x the x coordinate of the anchor point, in pixels. * @param y the y coordinate of the anchor point, in pixels. */ - public void setIndicatorLocation(int x, int y) { + public void setIndicatorLocation(int x, int y) + { // TODO: implement this } @@ -594,7 +628,8 @@ * @param inputMode a string naming a Unicode character subset, or * null */ - public void setInitialInputMode(String inputMode) { + public void setInitialInputMode(String inputMode) + { textWrapper.setInputMode(inputMode); } @@ -611,7 +646,8 @@ * @throws IllegalArgumentException if the contents after truncation would * be illegal for the current input constraints */ - public int setMaxSize(int maxSize) { + public int setMaxSize(int maxSize) + { textWrapper.setMaxSize(maxSize); return textWrapper.getMaxSize(); } @@ -623,7 +659,8 @@ * @param x the x coordinate of the anchor point, in pixels. * @param y the y coordinate of the anchor point, in pixels. */ - public void setPosition(int x, int y) { + public void setPosition(int x, int y) + { textWrapper.setPosition(x, y); } @@ -634,12 +671,14 @@ * @param rows the number of visible rows in the editor * @throws IllegalArgumentException if rows is zero or less */ - public void setRows(int rows) { - if (rows <= 0) { + public void setRows(int rows) + { + if(rows <= 0) + { throw new IllegalArgumentException(); } textWrapper.setSize(textWrapper.getWidth(), - textWrapper.getLineHeight() * rows); + textWrapper.getLineHeight() * rows); } /** @@ -651,7 +690,8 @@ * @param index the index of the first character to be selected. * @param length the length of the selection in characters. */ - public void setSelection(int index, int length) { + public void setSelection(int index, int length) + { textWrapper.setSelection(index, index + length); } @@ -662,7 +702,8 @@ * @param height height in pixels * @throws IllegalArgumentException if the width or height is less than zero */ - public void setSize(int width, int height) { + public void setSize(int width, int height) + { textWrapper.setSize(width, height); } @@ -676,7 +717,8 @@ * @param aChangelistener the new listener, or null */ public void setTextEditorChangeListener( - TextEditorChangeListener aChangelistener) { + TextEditorChangeListener aChangelistener) + { changelistener = aChangelistener; } @@ -693,8 +735,10 @@ * CustomItem * @see #hide() */ - public void show() { - if (parent == null) { + public void show() + { + if(parent == null) + { throw new IllegalStateException(); } textWrapper.setVisible(true); @@ -706,17 +750,21 @@ * * @return the number of characters */ - public int size() { + public int size() + { return textWrapper.getSize(); } /** * Text modify listener. */ - class TextModifyListener implements ModifyListener { + class TextModifyListener implements ModifyListener + { - public void modifyText(ModifyEvent me) { - if (changelistener != null) { + public void modifyText(ModifyEvent me) + { + if(changelistener != null) + { changelistener.textChanged(0, textWrapper.getSize()); } } @@ -726,13 +774,16 @@ /** * Text selection listener. */ - class TextSelectionListener implements SelectionListener { + class TextSelectionListener implements SelectionListener + { - public void widgetDefaultSelected(SelectionEvent se) { + public void widgetDefaultSelected(SelectionEvent se) + { Logger.verbose("TE - DefSel: " + se); } - public void widgetSelected(SelectionEvent se) { + public void widgetSelected(SelectionEvent se) + { Logger.verbose("TE - Sel: " + se); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditorChangeListener.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditorChangeListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextEditorChangeListener.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -27,7 +27,8 @@ * {@link TextEditor#setTextEditorChangeListener setTextEditorChangeListener()}. */ -public interface TextEditorChangeListener { +public interface TextEditorChangeListener +{ /** * Constant indicating the caret movement direction up. @@ -55,7 +56,7 @@ * external front end processors for advanced input methods. The parameters * indicate the range of the new modified text. The length parameter is * always > 0. - * + * * @param index the index of the first character that is selected. * @param length the length of selection as number of characters. */ @@ -65,7 +66,7 @@ * Called by the implementation to indicate that the caret has been moved. * The parameters indicate the new caret index and the movement direction in * relation the previous caret position. - * + * * @param newIndex the character index before which the caret is placed * after the movement * @param movementDirection the caret movement direction; must be one of @@ -78,7 +79,7 @@ * the TextEditor has been selected. The selection have been set with * programmatically or by user interaction. The parameters indicate the * range of the current selection. - * + * * @param index the index of the first character that is selected. * @param length the length of selection as number of characters. */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextField.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextField.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextField.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -21,7 +21,8 @@ /** * Item representing an editable TextField. */ -public class TextField extends Item { +public class TextField extends Item +{ /** * Constant value shows that any text is allowed. */ @@ -96,7 +97,8 @@ * @param maxSize maximum number of characters allowed. * @param constraints TextField constraints. */ - public TextField(String header, String txt, int maxSize, int constraints) { + public TextField(String header, String txt, int maxSize, int constraints) + { setLabel(header); textWrapper = new TextWrapper(txt, maxSize, constraints); } @@ -106,7 +108,8 @@ * * @return index in TextField where caret is. */ - public int getCaretPosition() { + public int getCaretPosition() + { return textWrapper.getCaretPosition(); } @@ -115,7 +118,8 @@ * * @return String which represents content of TextField; */ - public String getString() { + public String getString() + { return textWrapper.getContent(); } @@ -124,7 +128,8 @@ * * @param newTxt text to set. */ - public void setString(String newTxt) { + public void setString(String newTxt) + { textWrapper.setContent(newTxt); linesCount = 0; updateParent(Item.UPDATE_CONTENT | Item.UPDATE_HEIGHT_CHANGED); @@ -136,14 +141,17 @@ * @param charData array where to copy. * @return number of copied characters. */ - public int getChars(char[] charData) { - if (charData == null) { + public int getChars(char[] charData) + { + if(charData == null) + { throw new NullPointerException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); } - if (charData.length < getString().length()) { + if(charData.length < getString().length()) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_TOO_SHORT); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_TOO_SHORT); } String content = textWrapper.getContent(); content.getChars(0, content.length(), charData, 0); @@ -157,15 +165,19 @@ * @param offset index in charData to start copy from. * @param length number of character to copy into TextField. */ - public void setChars(char[] charData, int offset, int length) { + public void setChars(char[] charData, int offset, int length) + { String extractedString = null; - if (charData != null) { - try { + if(charData != null) + { + try + { extractedString = new String(charData, offset, length); } - catch (IndexOutOfBoundsException e) { + catch(IndexOutOfBoundsException e) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); + MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); } } textWrapper.setContent(extractedString); @@ -179,7 +191,8 @@ * @param newTxt string to insert. * @param position where to insert. */ - public void insert(String newTxt, int position) { + public void insert(String newTxt, int position) + { textWrapper.insert(newTxt, position); linesCount = 0; updateParent(Item.UPDATE_CONTENT | Item.UPDATE_HEIGHT_CHANGED); @@ -193,18 +206,22 @@ * @param length number of characters to copy. * @param position index in TextField where to insert to. */ - public void insert(char[] charData, int offset, int length, int position) { - if (charData == null) { + public void insert(char[] charData, int offset, int length, int position) + { + if(charData == null) + { throw new NullPointerException( - MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); + MsgRepository.TEXT_EXCEPTION_ARRAY_IS_NULL); } String extractedString = null; - try { + try + { extractedString = new String(charData, offset, length); } - catch (IndexOutOfBoundsException e) { + catch(IndexOutOfBoundsException e) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); + MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); } textWrapper.insert(extractedString, position); linesCount = 0; @@ -217,7 +234,8 @@ * @param offset start index where to start deletion. * @param length number of characters to delete. */ - public void delete(int offset, int length) { + public void delete(int offset, int length) + { textWrapper.delete(offset, length); linesCount = 0; updateParent(Item.UPDATE_CONTENT | Item.UPDATE_HEIGHT_CHANGED); @@ -228,7 +246,8 @@ * * @return number of characters which TextField can contain. */ - public int getMaxSize() { + public int getMaxSize() + { return textWrapper.getMaxSize(); } @@ -239,7 +258,8 @@ * @return max size that was set, depending on implementation may be smaller * then requested. */ - public int setMaxSize(int newMaxSize) { + public int setMaxSize(int newMaxSize) + { textWrapper.setMaxSize(newMaxSize); linesCount = 0; updateParent(Item.UPDATE_CONTENT | Item.UPDATE_HEIGHT_CHANGED); @@ -251,7 +271,8 @@ * * @return current content length. */ - public int size() { + public int size() + { return textWrapper.getSize(); } @@ -260,7 +281,8 @@ * * @param newConstraints constraints to set. */ - public void setConstraints(int newConstraints) { + public void setConstraints(int newConstraints) + { textWrapper.setConstraints(newConstraints); updateParent(Item.UPDATE_CONTENT | Item.UPDATE_SIZE_CHANGED); } @@ -270,7 +292,8 @@ * * @return current constraints. */ - public int getConstraints() { + public int getConstraints() + { return textWrapper.getConstraints(); } @@ -279,7 +302,8 @@ * * @param inputMode input mode to set. */ - public void setInitialInputMode(String inputMode) { + public void setInitialInputMode(String inputMode) + { textWrapper.setInputMode(inputMode); updateParent(UPDATE_INITIAL_INPUT_MODE); } @@ -289,7 +313,8 @@ * * @return inputMode currently set for TextField. */ - String getInitialInputMode() { + String getInitialInputMode() + { return textWrapper.getInputMode(); } @@ -298,7 +323,8 @@ * * @return Minimum size. */ - Point calculateMinimumSize() { + Point calculateMinimumSize() + { return TextFieldLayouter.calculateMinimumBounds(this); } @@ -307,7 +333,8 @@ * * @return Preferred size. */ - Point calculatePreferredSize() { + Point calculatePreferredSize() + { return TextFieldLayouter.calculatePreferredBounds(this); } @@ -316,14 +343,16 @@ * * @return layout directive */ - int internalGetLayout() { + int internalGetLayout() + { return super.internalGetLayout(); // | Item.LAYOUT_NEWLINE_BEFORE; } /** * @see javax.microedition.lcdui.Item#isFocusable() */ - boolean isFocusable() { + boolean isFocusable() + { return true; } @@ -332,7 +361,8 @@ * * @param newPosition new caret position. */ - void internalSetCaretPosition(int newPosition) { + void internalSetCaretPosition(int newPosition) + { textWrapper.setCaretposition(newPosition); } @@ -342,8 +372,10 @@ * @param newText new text. * @return true if this resulted in a change */ - boolean internalSetString(String newText) { - if (textWrapper.getContent() != newText) { + boolean internalSetString(String newText) + { + if(!textWrapper.getContent().equals(newText)) + { textWrapper.setContent(newText); return true; } @@ -355,7 +387,8 @@ * * @param newLinesCount new number lines. */ - void internalSetLinesCount(int newLinesCount) { + void internalSetLinesCount(int newLinesCount) + { linesCount = newLinesCount; } @@ -364,7 +397,8 @@ * * @return lines count. */ - int internalGetLinesCount() { + int internalGetLinesCount() + { return linesCount; } @@ -373,7 +407,8 @@ * * @param newMax maximum visible lines allowed for TextField. */ - void internalSetMaxVisibleLines(int newMax) { + void internalSetMaxVisibleLines(int newMax) + { maxVisibleLines = newMax; } @@ -382,7 +417,8 @@ * * @return number of maximum visible lines to display on the Form. */ - int internalGetMaxVisibleLines() { + int internalGetMaxVisibleLines() + { return maxVisibleLines; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextFieldLayouter.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextFieldLayouter.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextFieldLayouter.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -27,7 +27,8 @@ /** * Responsible for correct layout of TextField in a Form. */ -class TextFieldLayouter extends ItemLayouter { +class TextFieldLayouter extends ItemLayouter +{ /** * Key name for modify listener. @@ -66,7 +67,8 @@ * * @param dflp DefaultFormLayoutPolicy` */ - TextFieldLayouter(DefaultFormLayoutPolicy dflp) { + TextFieldLayouter(DefaultFormLayoutPolicy dflp) + { super(dflp); } @@ -75,7 +77,8 @@ * * @param constraint */ - static Control eswtGetStaticTextControl(int constraint) { + static Control eswtGetStaticTextControl(int constraint) + { Control ret = null; /* @@ -88,31 +91,39 @@ } */ - if (constraint == TextField.NUMERIC) { - if (numeric == null) { + if(constraint == TextField.NUMERIC) + { + if(numeric == null) + { numeric = new ConstrainedText(eswtGetStaticShell(), SWT.SINGLE, - ConstrainedText.NUMERIC); + ConstrainedText.NUMERIC); } ret = numeric; } - else if (constraint == TextField.DECIMAL) { - if (decimal == null) { + else if(constraint == TextField.DECIMAL) + { + if(decimal == null) + { decimal = new ConstrainedText(eswtGetStaticShell(), SWT.SINGLE, - ConstrainedText.DECIMAL); + ConstrainedText.DECIMAL); } ret = decimal; } - else if (constraint == TextField.PHONENUMBER) { - if (phonenr == null) { + else if(constraint == TextField.PHONENUMBER) + { + if(phonenr == null) + { phonenr = new ConstrainedText(eswtGetStaticShell(), SWT.SINGLE, - ConstrainedText.PHONENUMBER); + ConstrainedText.PHONENUMBER); } ret = phonenr; } - else { + else + { // TODO: eSWT support required - text validation on EMAIL and URL constraints // default - if (any == null) { + if(any == null) + { any = new TextExtension(eswtGetStaticShell(), SWT.MULTI | SWT.WRAP); } ret = any; @@ -127,15 +138,20 @@ * @param constraint TextField.NUMERIC etc. * @return true if text is correct for specified constraint. */ - static boolean checkText(final int constraint, final String text) { + static boolean checkText(final int constraint, final String text) + { isCorrectText = true; - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - try { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + try + { TextWrapper.eswtSetContent( - eswtGetStaticTextControl(constraint), text); + eswtGetStaticTextControl(constraint), text); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { isCorrectText = false; } } @@ -149,19 +165,21 @@ * @param parent for the control. * @param item TextField item. */ - Control eswtGetControl(Composite parent, Item item) { + Control eswtGetControl(Composite parent, Item item) + { TextField textfield = (TextField) item; Control te = TextWrapper.eswtConstructText(parent, - SWT.WRAP | SWT.MULTI, textfield.getConstraints()); + SWT.WRAP | SWT.MULTI, textfield.getConstraints()); TextWrapper.eswtSetMaxSize(te, textfield.getMaxSize()); TextWrapper.eswtSetContent(te, textfield.getString()); TextWrapper.eswtSetSelection(te, - textfield.getCaretPosition(), textfield.getCaretPosition()); + textfield.getCaretPosition(), textfield.getCaretPosition()); - if (textfield.getInitialInputMode() != null) { + if(textfield.getInitialInputMode() != null) + { eswtUpdateItem(textfield, te, TextField.UPDATE_INITIAL_INPUT_MODE, - null); + null); } return te; } @@ -174,7 +192,8 @@ * * @return true if this control is suitable for update */ - boolean eswtIsSpecificControl(Item item, Control control) { + boolean eswtIsSpecificControl(Item item, Control control) + { return (control instanceof TextExtension || control instanceof ConstrainedText); } @@ -186,15 +205,18 @@ * @param control eSWT control. * @param reason reason to update. */ - void eswtUpdateItem(Item item, Control control, int reason, Object param) { + void eswtUpdateItem(Item item, Control control, int reason, Object param) + { TextField textfield = (TextField) item; - if (reason == Item.UPDATE_CONTENT) { + if(reason == Item.UPDATE_CONTENT) + { TextWrapper.eswtSetContent(control, textfield.getString()); } - else if (reason == TextField.UPDATE_INITIAL_INPUT_MODE) { + else if(reason == TextField.UPDATE_INITIAL_INPUT_MODE) + { TextWrapper.eswtSetInputMode(control, - textfield.getInitialInputMode(), - textfield.getConstraints()); + textfield.getInitialInputMode(), + textfield.getConstraints()); } } @@ -205,9 +227,11 @@ * @param control Control which represents TextField. * @param width which control must occupy. */ - void eswtResizeControl(Item item, Control control, int width, int height) { + void eswtResizeControl(Item item, Control control, int width, int height) + { super.eswtResizeControl(item, control, width, height); - if (control instanceof TextExtension) { + if(control instanceof TextExtension) + { TextExtension te = (TextExtension) control; ((TextField) item).internalSetLinesCount(te.getLineCount()); } @@ -219,20 +243,24 @@ * @param item TextField. * @param key keyCode. */ - boolean eswtOfferKeyPressed(Item item, int key) { + boolean eswtOfferKeyPressed(Item item, int key) + { TextField tf = (TextField) item; - if (item.hasLayout(Item.LAYOUT_SHRINK)) { - if ((key == SWT.ARROW_LEFT + if(item.hasLayout(Item.LAYOUT_SHRINK)) + { + if((key == SWT.ARROW_LEFT && tf.getCaretPosition() == 0) - || (key == SWT.ARROW_RIGHT - && tf.getCaretPosition() == tf.size())) { + || (key == SWT.ARROW_RIGHT + && tf.getCaretPosition() == tf.size())) + { return false; } } - if (((key == SWT.ARROW_UP) - && (tf.getCaretPosition() == 0)) - || ((key == SWT.ARROW_DOWN) - && (tf.getCaretPosition() == tf.size()))) { + if(((key == SWT.ARROW_UP) + && (tf.getCaretPosition() == 0)) + || ((key == SWT.ARROW_DOWN) + && (tf.getCaretPosition() == tf.size()))) + { return false; } return true; @@ -246,14 +274,15 @@ * @param dir direction from which focus came, in case if it was set with * setCurrentItem() default direction is used (-1). */ - void eswtFocusGained(Item item, int dir) { + void eswtFocusGained(Item item, int dir) + { super.eswtFocusGained(item, dir); TextField tf = (TextField) item; // direction = dir; resetCaretPosition(tf, dir); Control control = eswtGetFirstSpecificControl(item); TextWrapper.eswtSetSelection(control, - tf.getCaretPosition(), tf.getCaretPosition()); + tf.getCaretPosition(), tf.getCaretPosition()); } /** @@ -262,10 +291,13 @@ * @param textField TextField object * @return Minimum area needed to display TextField. */ - static Point calculateMinimumBounds(final TextField textField) { + static Point calculateMinimumBounds(final TextField textField) + { final Point minSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { TextExtension tempExt = (TextExtension) eswtGetStaticTextControl(TextField.ANY); tempExt.setText(ItemLayouter.MIN_TEXT); tempExt.pack(); @@ -284,23 +316,26 @@ * @return Preferred area needed to display Item. x is width and y is * height. */ - static Point calculatePreferredBounds(Item item) { + static Point calculatePreferredBounds(Item item) + { final TextField textfield = (TextField) item; final Point prefSize = new Point(0, 0); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { TextExtension te = (TextExtension) eswtGetStaticTextControl(TextField.ANY); te.setText(textfield.getString()); int maxHeight = (formHeigh - * Config.TEXTFIELD_MAX_SCREEN_PERCENTAGE / TOTAL_PERCENTAGE) - - Config.TEXTFIELD_MARGIN; + * Config.TEXTFIELD_MAX_SCREEN_PERCENTAGE / TOTAL_PERCENTAGE) + - Config.TEXTFIELD_MARGIN; textfield.internalSetMaxVisibleLines(maxHeight - / te.getLineHeight()); + / te.getLineHeight()); prefSize.x = getMaximumItemWidth(textfield); prefSize.y = Config.TEXTFIELD_MARGIN + Math.min( - te.computeSize(prefSize.x, SWT.DEFAULT).y, maxHeight); + te.computeSize(prefSize.x, SWT.DEFAULT).y, maxHeight); // prefSize.y = Math.min(calc.y, maxHeight) + MARGIN; applyPrefMargins(textfield, prefSize); } @@ -314,22 +349,24 @@ * @param textfield TextField for which to update caret position. * @param dir direction of scrolling. */ - private void resetCaretPosition(TextField textfield, int dir) { - switch (dir) { - case SWT.ARROW_DOWN: - textfield.internalSetCaretPosition(0); - break; - case SWT.ARROW_RIGHT: - textfield.internalSetCaretPosition(0); - break; - case SWT.ARROW_UP: - textfield.internalSetCaretPosition(textfield.size()); - break; - case SWT.ARROW_LEFT: - textfield.internalSetCaretPosition(textfield.size()); - break; - default: - break; + private void resetCaretPosition(TextField textfield, int dir) + { + switch(dir) + { + case SWT.ARROW_DOWN: + textfield.internalSetCaretPosition(0); + break; + case SWT.ARROW_RIGHT: + textfield.internalSetCaretPosition(0); + break; + case SWT.ARROW_UP: + textfield.internalSetCaretPosition(textfield.size()); + break; + case SWT.ARROW_LEFT: + textfield.internalSetCaretPosition(textfield.size()); + break; + default: + break; } } @@ -339,7 +376,8 @@ * @param item TextField. * @param control Control which represents TextField. */ - void eswtAddSpecificListeners(Item item, Control control) { + void eswtAddSpecificListeners(Item item, Control control) + { super.eswtAddSpecificListeners(item, control); TextField textfield = (TextField) item; ModifyListener listener = new TextFieldModifyListener(textfield); @@ -359,20 +397,24 @@ * @param item TextField. * @param control Control which represents TextField. */ - void eswtRemoveSpecificListeners(Item item, Control control) { + void eswtRemoveSpecificListeners(Item item, Control control) + { super.eswtRemoveSpecificListeners(item, control); ModifyListener l1 = (ModifyListener) control.getData(MODIFY_LISTENER); - if (l1 != null) { + if(l1 != null) + { TextWrapper.eswtRemoveModListener(control, l1); control.setData(MODIFY_LISTENER, null); } KeyListener l2 = (KeyListener) control.getData(KEY_LISTENER); - if (l2 != null) { + if(l2 != null) + { control.removeKeyListener(l2); control.setData(KEY_LISTENER, null); } MouseListener l4 = (MouseListener) control.getData(MOUSE_LISTENER); - if (l4 != null) { + if(l4 != null) + { control.removeMouseListener(l4); control.setData(MOUSE_LISTENER, null); } @@ -382,45 +424,56 @@ * Class that receives ModifyEvents from TextExtension and updates values of * TextField. */ - class TextFieldModifyListener implements ModifyListener { + class TextFieldModifyListener implements ModifyListener + { private TextField textfield; - TextFieldModifyListener(TextField textField) { + TextFieldModifyListener(TextField textField) + { this.textfield = textField; } - private void handleLinesChange(TextExtension te) { + private void handleLinesChange(TextExtension te) + { int lines = te.getLineCount(); int visibleLines = te.getSize().y / te.getLineHeight(); - if (lines != textfield.internalGetLinesCount()) { + if(lines != textfield.internalGetLinesCount()) + { textfield.internalSetLinesCount(lines); Control control = eswtGetFirstControl(textfield); - if (control.getSize().y + te.getLineHeight() - + Config.TEXTFIELD_MARGIN <= dfi.getFormHeight()) { + if(control.getSize().y + te.getLineHeight() + + Config.TEXTFIELD_MARGIN <= dfi.getFormHeight()) + { textfield.updateParent(Item.UPDATE_HEIGHT_CHANGED); } - if (textfield.internalGetLinesCount() > lines) { - if ((te.getTopIndex() + visibleLines) > lines) { + if(textfield.internalGetLinesCount() > lines) + { + if((te.getTopIndex() + visibleLines) > lines) + { te.setTopIndex(Math.max(0, lines - visibleLines)); } - if (visibleLines > lines) { + if(visibleLines > lines) + { textfield.updateParent(Item.UPDATE_HEIGHT_CHANGED); } } te.setTopIndex(Math.max(te.getCaretLineNumber() + 1 - - textfield.internalGetMaxVisibleLines(), 0)); + - textfield.internalGetMaxVisibleLines(), 0)); } } - public void modifyText(ModifyEvent modifyEvent) { + public void modifyText(ModifyEvent modifyEvent) + { Control te = (Control) modifyEvent.widget; - if (textfield.internalSetString(TextWrapper.eswtGetContent(te))) { + if(textfield.internalSetString(TextWrapper.eswtGetContent(te))) + { Logger.method(textfield, "modify", modifyEvent); textfield.internalSetCaretPosition( - TextWrapper.eswtGetCaretPosition(te)); - if (te instanceof TextExtension) { + TextWrapper.eswtGetCaretPosition(te)); + if(te instanceof TextExtension) + { handleLinesChange((TextExtension) te); } textfield.notifyStateChanged(); @@ -432,25 +485,30 @@ * Class that receives KeyEvents from TextExtension and updates * caret position for TextField. */ - class TextFieldKeyListener implements KeyListener { + class TextFieldKeyListener implements KeyListener + { private TextField textfield; - TextFieldKeyListener(TextField textField) { + TextFieldKeyListener(TextField textField) + { this.textfield = textField; } - public void keyPressed(KeyEvent keyEvent) { - Control te = (Control) keyEvent.widget; + public void keyPressed(KeyEvent keyEvent) + { + Control te = (Control) keyEvent.widget; int caretPos = TextWrapper.eswtGetCaretPosition(te); int caretLine = TextWrapper.eswtGetCaretLine(te); - if (keyEvent.keyCode == SWT.ARROW_UP && caretLine == 0) { + if(keyEvent.keyCode == SWT.ARROW_UP && caretLine == 0) + { caretPos = 0; TextWrapper.eswtSetSelection(te, caretPos, caretPos); } - else if (keyEvent.keyCode == SWT.ARROW_DOWN - && (caretLine == (TextWrapper.eswtGetLineCount(te) - 1))) { + else if(keyEvent.keyCode == SWT.ARROW_DOWN + && (caretLine == (TextWrapper.eswtGetLineCount(te) - 1))) + { caretPos = textfield.size(); TextWrapper.eswtSetSelection(te, caretPos, caretPos); } @@ -458,46 +516,56 @@ textfield.internalSetCaretPosition(caretPos); } - public void keyReleased(KeyEvent keyEvent) { + public void keyReleased(KeyEvent keyEvent) + { // this is needed if focus was changed with touch. // so ne scrolling was done in DFI. - if (!dfi.isItemFullyVisible(textfield)) { + if(!dfi.isItemFullyVisible(textfield)) + { dfi.eswtScrollToItem(textfield); } textfield.internalSetCaretPosition( - TextWrapper.eswtGetCaretPosition((Control) keyEvent.widget)); + TextWrapper.eswtGetCaretPosition((Control) keyEvent.widget)); } } - class AllMouseListener implements MouseListener, MouseMoveListener { + class AllMouseListener implements MouseListener, MouseMoveListener + { private TextField textfield; private boolean isEnabled; - AllMouseListener(TextField tf) { + AllMouseListener(TextField tf) + { textfield = tf; } - public void enable(boolean enabled) { + public void enable(boolean enabled) + { isEnabled = enabled; } - public void mouseUp(MouseEvent me) { - if (isEnabled) { + public void mouseUp(MouseEvent me) + { + if(isEnabled) + { // } } - public void mouseDown(MouseEvent me) { + public void mouseDown(MouseEvent me) + { textfield.internalSetCaretPosition( - TextWrapper.eswtGetCaretPosition((Control) me.widget)); + TextWrapper.eswtGetCaretPosition((Control) me.widget)); } - public void mouseMove(MouseEvent me) { + public void mouseMove(MouseEvent me) + { } - public void mouseDoubleClick(MouseEvent me) { + public void mouseDoubleClick(MouseEvent me) + { } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/TextWrapper.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/TextWrapper.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/TextWrapper.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; @@ -29,7 +29,8 @@ * Dynamic Text component implementation over the TextExtension/ConstrainedText * widgets as a wrapper. */ -class TextWrapper { +class TextWrapper +{ private String text; private String inputMode; @@ -65,7 +66,8 @@ * @param aMaxSize * @param aConstraints */ - TextWrapper(String aText, int aMaxSize, int aConstraints) { + TextWrapper(String aText, int aMaxSize, int aConstraints) + { setMaxSize(aMaxSize); setConstraints(aConstraints); setContent(aText); @@ -77,9 +79,12 @@ * @param parent composite to create on * @param addStyle additional style */ - void construct(final Composite parent, final int addStyle) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + void construct(final Composite parent, final int addStyle) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtConstruct(parent, addStyle); } }); @@ -91,13 +96,16 @@ * @param parent composite to create on * @param addStyle additional style */ - void eswtConstruct(Composite parent, int addStyle) { + void eswtConstruct(Composite parent, int addStyle) + { style = addStyle | SWT.MULTI | SWT.WRAP; - if (parent != null) { + if(parent != null) + { eswtStoreStateAndDispose(); eswtRestoreStateAndCreate(parent); } - else { + else + { Logger.warning("Trying to construct TextWrapper with null parent"); } } @@ -108,10 +116,12 @@ * @param offset * @param length */ - void delete(int offset, int length) { - if ((offset + length) > getSize()) { + void delete(int offset, int length) + { + if((offset + length) > getSize()) + { throw new StringIndexOutOfBoundsException( - MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); + MsgRepository.TEXT_EXCEPTION_ARRAY_INDEX_OUT_OF_BOUNDS); } StringBuffer sb = new StringBuffer(getContent()); sb.delete(offset, offset + length); @@ -121,10 +131,14 @@ /** * Dispose eSWT control. */ - void dispose() { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + void dispose() + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtStoreStateAndDispose(); } }); @@ -134,10 +148,14 @@ /** * Get caret position. */ - int getCaretPosition() { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + int getCaretPosition() + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { caret = eswtGetCaretPosition(control); } }); @@ -148,17 +166,22 @@ /** * Get constraints. */ - int getConstraints() { + int getConstraints() + { return constraints; } /** * Get text content. */ - String getContent() { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + String getContent() + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { text = eswtGetContent(control); } }); @@ -169,25 +192,31 @@ /** * Gets the height of this Text control in pixels. */ - int getHeight() { + int getHeight() + { return height; } /** * Get input mode. */ - String getInputMode() { + String getInputMode() + { return inputMode; } /** * Get line count. */ - int getLineCount() { + int getLineCount() + { retLineCount = 1; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { retLineCount = eswtGetLineCount(control); } }); @@ -198,11 +227,15 @@ /** * Get line height (in pixels). */ - int getLineHeight() { + int getLineHeight() + { retLineHeight = 1; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { retLineHeight = eswtGetLineHeight(control); } }); @@ -213,10 +246,14 @@ /** * Get maximum size (in characters). */ - int getMaxSize() { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + int getMaxSize() + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { maxSize = eswtGetMaxSize(control); } }); @@ -229,20 +266,25 @@ * * @param maxVisibleLines maximum visible lines */ - int getPreferredHeight(int maxVisibleLines) { + int getPreferredHeight(int maxVisibleLines) + { // lineCount (1 .. max) * lineHeight return Math.min(Math.max(1, getLineCount()), maxVisibleLines) - * getLineHeight(); + * getLineHeight(); } /** * Get selected text content. */ - String getSelectedContent() { + String getSelectedContent() + { retSelectedStr = ""; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { retSelectedStr = eswtGetSelectedContent(control); } }); @@ -253,10 +295,14 @@ /** * Get content's length. */ - int getSize() { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + int getSize() + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { size = eswtGetSize(control); } }); @@ -267,12 +313,17 @@ /** * Get visible top pixel position relative to whole content. */ - int getTopPixelPosition() { + int getTopPixelPosition() + { retTopPixel = 0; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (control instanceof TextExtension) { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(control instanceof TextExtension) + { retTopPixel = ((TextExtension) control).getTopPixel(); } // ConstrainedText does not scroll -> value is 0 @@ -285,7 +336,8 @@ /** * Gets the width of this Text control (in pixels). */ - int getWidth() { + int getWidth() + { return width; } @@ -295,19 +347,24 @@ * @param aText text * @param aPosition position where to instert */ - void insert(String aText, int aPosition) { - if (aText == null) { + void insert(String aText, int aPosition) + { + if(aText == null) + { throw new NullPointerException( - MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); + MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); } StringBuffer sb = new StringBuffer(getContent()); - if (aPosition < 0) { + if(aPosition < 0) + { sb.insert(0, aText); } - else if (aPosition > sb.length()) { + else if(aPosition > sb.length()) + { sb.append(aText); } - else { + else + { sb.insert(aPosition, aText); } setContent(sb.toString()); @@ -321,15 +378,19 @@ * @param green color component * @param blue color component */ - void setBackgroundColor(final int alpha, final int red, final int green, final int blue) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (bgCol != null) { + void setBackgroundColor(final int alpha, final int red, final int green, final int blue) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(bgCol != null) + { bgCol.dispose(); bgCol = null; } bgCol = new Color(ESWTUIThreadRunner.getInstance().getDisplay(), - red, green, blue); + red, green, blue); } }); } @@ -339,18 +400,23 @@ * * @param aBounds bounding rectangle */ - void setBounds(Rectangle aBounds) { - if (aBounds.width < 0 || aBounds.height < 0) { + void setBounds(Rectangle aBounds) + { + if(aBounds.width < 0 || aBounds.height < 0) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_INVALID_SIZE); + MsgRepository.TEXT_EXCEPTION_INVALID_SIZE); } x = aBounds.x; y = aBounds.y; width = aBounds.width; height = aBounds.height; - if (control != null && width >= 0 && height >= 0) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null && width >= 0 && height >= 0) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { control.setBounds(x, y, width, height); } }); @@ -362,11 +428,15 @@ * * @param aPosition position */ - void setCaretposition(int aPosition) { + void setCaretposition(int aPosition) + { caret = aPosition; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetSelection(control, caret, caret); } }); @@ -378,15 +448,20 @@ * * @param aConstraints text input constraints */ - void setConstraints(int aConstraints) { - if (!isValidConstraints(aConstraints)) { + void setConstraints(int aConstraints) + { + if(!isValidConstraints(aConstraints)) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_INVALID_CONSTRAINTS); + MsgRepository.TEXT_EXCEPTION_INVALID_CONSTRAINTS); } constraints = aConstraints; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtRestoreStateAndCreate(eswtStoreStateAndDispose()); } }); @@ -398,26 +473,34 @@ * * @param aText new content */ - void setContent(String aText) { - if (aText == null) { + void setContent(String aText) + { + if(aText == null) + { text = ""; } - else { - if (aText.length() > maxSize) { + else + { + if(aText.length() > maxSize) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_MAX_SIZE_EXCEEDED); + MsgRepository.TEXT_EXCEPTION_MAX_SIZE_EXCEEDED); } - if (!isValidText(aText, constraints)) { + if(!isValidText(aText, constraints)) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_WRONG_TEXT); + MsgRepository.TEXT_EXCEPTION_WRONG_TEXT); } text = aText; } size = text.length(); caret = text.length(); - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetContent(control, text); eswtSetSelection(control, caret, caret); } @@ -430,19 +513,25 @@ * * @param aFont new font */ - void setFont(Font aFont) { + void setFont(Font aFont) + { font = aFont; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (font != null) { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(font != null) + { // set custom font control.setFont(Font.getESWTFont(font)); } - else { + else + { // set default font control.setFont( - Font.getESWTFont(Font.getDefaultFont())); + Font.getESWTFont(Font.getDefaultFont())); } } }); @@ -454,11 +543,15 @@ * * @param aFocused */ - void setFocused(boolean aFocused) { + void setFocused(boolean aFocused) + { focused = aFocused; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetFocused(control, focused); } }); @@ -473,15 +566,19 @@ * @param green color component * @param blue color component */ - void setForegroundColor(final int alpha, final int red, final int green, final int blue) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { - if (fgCol != null) { + void setForegroundColor(final int alpha, final int red, final int green, final int blue) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { + if(fgCol != null) + { fgCol.dispose(); fgCol = null; } fgCol = new Color(ESWTUIThreadRunner.getInstance().getDisplay(), - red, green, blue); + red, green, blue); } }); } @@ -491,11 +588,15 @@ * * @param inputMode */ - void setInputMode(String aInputMode) { + void setInputMode(String aInputMode) + { inputMode = aInputMode; - if (control != null && control instanceof TextExtension) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null && control instanceof TextExtension) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetInputMode(control, inputMode, constraints); } }); @@ -507,22 +608,28 @@ * * @param aMaxSize */ - void setMaxSize(int aMaxSize) { - if (aMaxSize < 1) { + void setMaxSize(int aMaxSize) + { + if(aMaxSize < 1) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_INVALID_MAX_SIZE); + MsgRepository.TEXT_EXCEPTION_INVALID_MAX_SIZE); } String content = getContent(); - if (content != null && aMaxSize < content.length()) { + if(content != null && aMaxSize < content.length()) + { // we have to truncate content - validates the new text setContent(content.substring(0, aMaxSize)); } maxSize = aMaxSize; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetMaxSize(control, maxSize); } }); @@ -534,10 +641,14 @@ * * @param aListener modify listener */ - void setModifyListener(final ModifyListener aListener) { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + void setModifyListener(final ModifyListener aListener) + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtRemoveModListener(control, modifyListener); eswtAddModListener(control, aListener); } @@ -551,10 +662,14 @@ * * @param aListener selection listener */ - void setSelectionListener(final SelectionListener aListener) { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + void setSelectionListener(final SelectionListener aListener) + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtRemoveSelListener(control, selectionListener); eswtAddSelListener(control, aListener); } @@ -569,12 +684,16 @@ * @param aX * @param aY */ - void setPosition(int aX, int aY) { + void setPosition(int aX, int aY) + { x = aX; y = aY; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { control.setLocation(x, y); } }); @@ -587,10 +706,14 @@ * @param sta selection start * @param end selection end */ - void setSelection(final int sta, final int end) { - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + void setSelection(final int sta, final int end) + { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { eswtSetSelection(control, sta, end); } }); @@ -603,16 +726,21 @@ * @param width * @param height */ - void setSize(int aWidth, int aHeight) { - if (aWidth < 0 || aHeight < 0) { + void setSize(int aWidth, int aHeight) + { + if(aWidth < 0 || aHeight < 0) + { throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_INVALID_SIZE); + MsgRepository.TEXT_EXCEPTION_INVALID_SIZE); } width = aWidth; height = aHeight; - if (control != null && width >= 0 && height >= 0) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null && width >= 0 && height >= 0) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { control.setSize(width, height); } }); @@ -622,11 +750,15 @@ /** * Set the visibility of the eSWT control. */ - void setVisible(boolean aVisible) { + void setVisible(boolean aVisible) + { visible = aVisible; - if (control != null) { - ESWTUIThreadRunner.safeSyncExec(new Runnable() { - public void run() { + if(control != null) + { + ESWTUIThreadRunner.safeSyncExec(new Runnable() + { + public void run() + { control.setVisible(visible); } }); @@ -638,23 +770,29 @@ * * @param parent parent composite */ - private void eswtRestoreStateAndCreate(Composite parent) { - if (control == null) { + private void eswtRestoreStateAndCreate(Composite parent) + { + if(control == null) + { control = eswtConstructText(parent, style, constraints); eswtSetInputMode(control, inputMode, constraints); eswtSetMaxSize(control, maxSize); eswtSetContent(control, text); eswtSetSelection(control, caret, caret); - if (width >= 0 && height >= 0) { + if(width >= 0 && height >= 0) + { control.setBounds(x, y, width, height); } - if (fgCol != null) { + if(fgCol != null) + { control.setForeground(fgCol); } - if (bgCol != null) { + if(bgCol != null) + { control.setBackground(bgCol); } - if (font != null) { + if(font != null) + { control.setFont(Font.getESWTFont(font)); } control.setVisible(visible); @@ -669,9 +807,11 @@ * * @return the control's parent composite. */ - private Composite eswtStoreStateAndDispose() { + private Composite eswtStoreStateAndDispose() + { Composite parent = null; - if (control != null) { + if(control != null) + { parent = control.getParent(); text = eswtGetContent(control); caret = eswtGetCaretPosition(control); @@ -689,12 +829,16 @@ * @param control text control * @param ltnr listener */ - static void eswtAddModListener(Control control, ModifyListener ltnr) { - if (control != null && ltnr != null) { - if (control instanceof TextExtension) { + static void eswtAddModListener(Control control, ModifyListener ltnr) + { + if(control != null && ltnr != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).addModifyListener(ltnr); } - else { + else + { ((ConstrainedText) control).addModifyListener(ltnr); } } @@ -706,12 +850,16 @@ * @param control text control * @param ltnr listener */ - static void eswtAddSelListener(Control control, SelectionListener ltnr) { - if (control != null && ltnr != null) { - if (control instanceof TextExtension) { + static void eswtAddSelListener(Control control, SelectionListener ltnr) + { + if(control != null && ltnr != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).addSelectionListener(ltnr); } - else { + else + { ((ConstrainedText) control).addSelectionListener(ltnr); } } @@ -725,31 +873,44 @@ * @param aConstraints * @return */ - static Control eswtConstructText(Composite parent, int aStyle, int aConstraints) { + static Control eswtConstructText(Composite parent, int aStyle, int aConstraints) + { Control ret = null; int style = aStyle; int extractedFlag = aConstraints & ~TextField.CONSTRAINT_MASK; int extractedConstraint = aConstraints & TextField.CONSTRAINT_MASK; - if ((extractedFlag & TextField.PASSWORD) == TextField.PASSWORD) { + if((extractedFlag & TextField.PASSWORD) == TextField.PASSWORD) + { // Text class will remove incompatible flags for SINGLE style |= SWT.SINGLE | SWT.PASSWORD; } - if ((extractedFlag & TextField.UNEDITABLE) == TextField.UNEDITABLE) { + if((extractedFlag & TextField.UNEDITABLE) == TextField.UNEDITABLE) + { style |= SWT.READ_ONLY; } - if (extractedConstraint == TextField.NUMERIC) { + if(extractedConstraint == TextField.NUMERIC) + { ret = new ConstrainedText(parent, style, ConstrainedText.NUMERIC); } - else if (extractedConstraint == TextField.DECIMAL) { + else if(extractedConstraint == TextField.DECIMAL) + { ret = new ConstrainedText(parent, style, ConstrainedText.DECIMAL); } - else if (extractedConstraint == TextField.PHONENUMBER) { + else if(extractedConstraint == TextField.PHONENUMBER) + { ret = new ConstrainedText(parent, style, ConstrainedText.PHONENUMBER); } - else { + else if(extractedConstraint == TextField.NON_PREDICTIVE + || extractedConstraint == TextField.SENSITIVE) + { + // We treat non-predictive and sensitive to be equal + ret = new TextExtension(parent, style, TextExtension.NON_PREDICTIVE); + } + else + { ret = new TextExtension(parent, style); } return ret; @@ -760,13 +921,17 @@ * * @param control text control */ - static int eswtGetCaretPosition(Control control) { + static int eswtGetCaretPosition(Control control) + { int ret = 0; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getCaretPosition(); } - else { + else + { ret = ((ConstrainedText) control).getCaretPosition(); } } @@ -778,10 +943,13 @@ * * @param control text control */ - static int eswtGetCaretLine(Control control) { + static int eswtGetCaretLine(Control control) + { int ret = 0; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getCaretLineNumber(); } } @@ -793,13 +961,17 @@ * * @param control text control */ - static String eswtGetContent(Control control) { + static String eswtGetContent(Control control) + { String ret = ""; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getText(); } - else { + else + { ret = ((ConstrainedText) control).getText(); } } @@ -811,10 +983,13 @@ * * @param control text control */ - static int eswtGetLineCount(Control control) { + static int eswtGetLineCount(Control control) + { int ret = 1; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getLineCount(); } } @@ -826,13 +1001,17 @@ * * @param control text control */ - static int eswtGetLineHeight(Control control) { + static int eswtGetLineHeight(Control control) + { int ret = 0; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getLineHeight(); } - else { + else + { ret = ((ConstrainedText) control).getSize().y; } } @@ -844,13 +1023,17 @@ * * @param control text control */ - static int eswtGetMaxSize(Control control) { + static int eswtGetMaxSize(Control control) + { int ret = 0; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getTextLimit(); } - else { + else + { ret = ((ConstrainedText) control).getTextLimit(); } } @@ -862,13 +1045,17 @@ * * @param control text control */ - static String eswtGetSelectedContent(Control control) { + static String eswtGetSelectedContent(Control control) + { String ret = ""; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getSelectionText(); } - else { + else + { // TODO: eSWT support required - get selection in ConstrainedText ret = ((ConstrainedText) control).getText(); } @@ -881,13 +1068,17 @@ * * @param control text control */ - static int eswtGetSize(Control control) { + static int eswtGetSize(Control control) + { int ret = 0; - if (control != null) { - if (control instanceof TextExtension) { + if(control != null) + { + if(control instanceof TextExtension) + { ret = ((TextExtension) control).getCharCount(); } - else { + else + { ret = ((ConstrainedText) control).getCharCount(); } } @@ -900,12 +1091,16 @@ * @param control text control * @param ltnr listener */ - static void eswtRemoveModListener(Control control, ModifyListener ltnr) { - if (control != null && ltnr != null) { - if (control instanceof TextExtension) { + static void eswtRemoveModListener(Control control, ModifyListener ltnr) + { + if(control != null && ltnr != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).removeModifyListener(ltnr); } - else { + else + { ((ConstrainedText) control).removeModifyListener(ltnr); } } @@ -917,12 +1112,16 @@ * @param control text control * @param ltnr listener */ - static void eswtRemoveSelListener(Control control, SelectionListener ltnr) { - if (control != null && ltnr != null) { - if (control instanceof TextExtension) { + static void eswtRemoveSelListener(Control control, SelectionListener ltnr) + { + if(control != null && ltnr != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).removeSelectionListener(ltnr); } - else { + else + { ((ConstrainedText) control).removeSelectionListener(ltnr); } } @@ -934,12 +1133,16 @@ * @param control text control * @param text content */ - static void eswtSetContent(Control control, String text) { - if (control != null) { - if (control instanceof TextExtension) { + static void eswtSetContent(Control control, String text) + { + if(control != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).setText(text); } - else { + else + { ((ConstrainedText) control).setText(text); } } @@ -951,12 +1154,16 @@ * @param control text control * @param focus */ - static void eswtSetFocused(Control control, boolean focus) { - if (control != null) { - if (focus) { + static void eswtSetFocused(Control control, boolean focus) + { + if(control != null) + { + if(focus) + { control.setFocus(); } - else { + else + { control.getParent().forceFocus(); } } @@ -970,33 +1177,43 @@ * @param aConstraints constraints */ static void eswtSetInputMode(Control control, String inputMode, - int aConstraints) { - if (control != null && control instanceof TextExtension) { + int aConstraints) + { + if(control != null && control instanceof TextExtension) + { TextExtension te = (TextExtension) control; int capitalize = getCapitalize(aConstraints); - if (inputMode == null) { + if(inputMode == null) + { te.setInitialInputMode(TextExtension.TEXTCASE, - "UCB_BASIC_LATIN"); + "UCB_BASIC_LATIN"); } - else if (inputMode.equals("MIDP_UPPERCASE_LATIN")) { - if (capitalize > 0 && !isUrlEmailSet(aConstraints)) { + else if(inputMode.equals("MIDP_UPPERCASE_LATIN")) + { + if(capitalize > 0 && !isUrlEmailSet(aConstraints)) + { te.setInitialInputMode(capitalize, "UCB_BASIC_LATIN"); } - else { + else + { te.setInitialInputMode(TextExtension.UPPERCASE, - "UCB_BASIC_LATIN"); + "UCB_BASIC_LATIN"); } } - else if (inputMode.equals("MIDP_LOWERCASE_LATIN")) { - if (capitalize > 0 && !isUrlEmailSet(aConstraints)) { + else if(inputMode.equals("MIDP_LOWERCASE_LATIN")) + { + if(capitalize > 0 && !isUrlEmailSet(aConstraints)) + { te.setInitialInputMode(capitalize, "UCB_BASIC_LATIN"); } - else { + else + { te.setInitialInputMode(TextExtension.LOWERCASE, - "UCB_BASIC_LATIN"); + "UCB_BASIC_LATIN"); } } - else { + else + { te.setInitialInputMode(TextExtension.TEXTCASE, inputMode); } } @@ -1008,12 +1225,16 @@ * @param control text control * @param maxSize maximum size */ - static void eswtSetMaxSize(Control control, int maxSize) { - if (control != null) { - if (control instanceof TextExtension) { + static void eswtSetMaxSize(Control control, int maxSize) + { + if(control != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).setTextLimit(maxSize); } - else { + else + { ((ConstrainedText) control).setTextLimit(maxSize); } } @@ -1026,12 +1247,16 @@ * @param sta start index * @param end end index */ - static void eswtSetSelection(Control control, int sta, int end) { - if (control != null) { - if (control instanceof TextExtension) { + static void eswtSetSelection(Control control, int sta, int end) + { + if(control != null) + { + if(control instanceof TextExtension) + { ((TextExtension) control).setSelection(sta, end); } - else { + else + { ((ConstrainedText) control).setSelection(sta, end); } } @@ -1042,13 +1267,18 @@ * * @param control text control */ - static void eswtUpdateVScrollbar(Control control) { - if (control != null) { - if ((control.getStyle() & SWT.V_SCROLL) == SWT.V_SCROLL) { - if (control instanceof TextExtension) { + static void eswtUpdateVScrollbar(Control control) + { + if(control != null) + { + if((control.getStyle() & SWT.V_SCROLL) == SWT.V_SCROLL) + { + if(control instanceof TextExtension) + { TextExtension te = (TextExtension) control; ScrollBar sb = te.getVerticalBar(); - if (sb != null) { + if(sb != null) + { int height = te.getLineCount() * te.getLineHeight(); sb.setVisible(te.getSize().y < height); } @@ -1062,15 +1292,18 @@ * * @param aConstraints constraints */ - static int getCapitalize(int aConstraints) { + static int getCapitalize(int aConstraints) + { int ret = 0; int extractedFlag = aConstraints & ~TextField.CONSTRAINT_MASK; - if ((extractedFlag & TextField.INITIAL_CAPS_WORD) - == TextField.INITIAL_CAPS_WORD) { + if((extractedFlag & TextField.INITIAL_CAPS_WORD) + == TextField.INITIAL_CAPS_WORD) + { ret = TextExtension.TITLECASE; } - if ((extractedFlag & TextField.INITIAL_CAPS_SENTENCE) - == TextField.INITIAL_CAPS_SENTENCE) { + if((extractedFlag & TextField.INITIAL_CAPS_SENTENCE) + == TextField.INITIAL_CAPS_SENTENCE) + { ret = TextExtension.TEXTCASE; } return ret; @@ -1081,7 +1314,8 @@ * * @param aConstraints constraints */ - static boolean isUrlEmailSet(int aConstraints) { + static boolean isUrlEmailSet(int aConstraints) + { int extractedConstraint = aConstraints & TextField.CONSTRAINT_MASK; return (extractedConstraint == TextField.EMAILADDR || extractedConstraint == TextField.URL); @@ -1093,26 +1327,29 @@ * @param aConstraints constraints to check. * @return true if constraints are OK, false otherwise. */ - static boolean isValidConstraints(int aConstraints) { + static boolean isValidConstraints(int aConstraints) + { int smallestFlag; int highestFlag; smallestFlag = TextField.PASSWORD - 1; highestFlag = TextField.PASSWORD + TextField.UNEDITABLE - + TextField.SENSITIVE + TextField.NON_PREDICTIVE - + TextField.INITIAL_CAPS_WORD + TextField.INITIAL_CAPS_SENTENCE - + 1; + + TextField.SENSITIVE + TextField.NON_PREDICTIVE + + TextField.INITIAL_CAPS_WORD + TextField.INITIAL_CAPS_SENTENCE + + 1; int typeConstraint = getTypeConstraint(aConstraints); - if (typeConstraint == TextField.ANY + if(typeConstraint == TextField.ANY || typeConstraint == TextField.EMAILADDR || typeConstraint == TextField.NUMERIC || typeConstraint == TextField.PHONENUMBER || typeConstraint == TextField.DECIMAL - || typeConstraint == TextField.URL) { + || typeConstraint == TextField.URL) + { int extractedFlag = aConstraints & ~TextField.CONSTRAINT_MASK; - if (extractedFlag == 0 + if(extractedFlag == 0 || ((extractedFlag > smallestFlag) - && (extractedFlag < highestFlag))) { + && (extractedFlag < highestFlag))) + { return true; } } @@ -1124,7 +1361,8 @@ * * @param aConstraints constraints */ - static int getTypeConstraint(int aConstraints) { + static int getTypeConstraint(int aConstraints) + { return aConstraints & TextField.CONSTRAINT_MASK; } @@ -1134,7 +1372,8 @@ * @param aText * @return */ - static boolean isValidText(String aText, int aConstraints) { + static boolean isValidText(String aText, int aConstraints) + { return TextFieldLayouter.checkText(aConstraints, aText); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/Ticker.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/Ticker.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/Ticker.java Fri May 14 15:47:24 2010 +0300 @@ -24,7 +24,8 @@ /** * Implementation of LCDUI Ticker class. */ -public class Ticker { +public class Ticker +{ /** * How many pixels the ticker will move after every delay. @@ -60,7 +61,8 @@ * * @param txt Displayed string. If null, throws NullPointerException. */ - public Ticker(String txt) { + public Ticker(String txt) + { setString(txt); } @@ -69,21 +71,27 @@ * * @param txt Displayed string. If null, throws NullPointerException. */ - public void setString(String txt) { - if (txt == null) { + public void setString(String txt) + { + if(txt == null) + { throw new NullPointerException( - MsgRepository.TICKER_EXCEPTION_NULL_STRING); + MsgRepository.TICKER_EXCEPTION_NULL_STRING); } text = txt; updateDirection(); - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - for (int i = 0; i < labels.size(); i++) { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + for(int i = 0; i < labels.size(); i++) + { Label label = ((Label) labels.elementAt(i)); - if (!label.isDisposed()) { - label.setText(getFormattedString()); - label.pack(); - } + if(!label.isDisposed()) + { + label.setText(getFormattedString()); + label.pack(); + } } } }); @@ -94,7 +102,8 @@ * * @return the displayed string. */ - public String getString() { + public String getString() + { return text; } @@ -105,17 +114,22 @@ * * @return String where newline characters are replaced with spaces. */ - String getFormattedString() { + String getFormattedString() + { StringBuffer formattedText = new StringBuffer(text.length()); - for (int i = 0; i < text.length(); i++) { - if (text.charAt(i) == '\r') { + for(int i = 0; i < text.length(); i++) + { + if(text.charAt(i) == '\r') + { continue; } - else if ((text.charAt(i) == '\n') - || (text.charAt(i) == '\u2028')) { + else if((text.charAt(i) == '\n') + || (text.charAt(i) == '\u2028')) + { formattedText.append(" "); } - else { + else + { formattedText.append(text.charAt(i)); } } @@ -130,10 +144,14 @@ * * @param label Label to add. */ - void addLabel(final Label label) { - if (label != null) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void addLabel(final Label label) + { + if(label != null) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { labels.addElement(label); } }); @@ -146,10 +164,14 @@ * * @param label Label to be removed. If null, nothing happens. */ - void removeLabel(final Label label) { - if (label != null) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void removeLabel(final Label label) + { + if(label != null) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { labels.removeElement(label); } }); @@ -163,12 +185,16 @@ * Ticker speed is adjusted so that it takes about 7 seconds * for every character to run across the screen. */ - void updateSpeed() { - if (labels.size() > 0) { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { + void updateSpeed() + { + if(labels.size() > 0) + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { screenWidth = ((Label) labels.elementAt(0)).getParent() - .getBounds().width; + .getBounds().width; } }); stepSize = (screenWidth * Config.TICKER_MOVEMENT_DELAY) / Config.TICKER_DISPLAY_TIME; @@ -187,8 +213,10 @@ * It is ok to call this method even if Ticker is already running. * In that case the method will just return. */ - void start() { - if (isRunning) { + void start() + { + if(isRunning) + { // Ticker already running. return; } @@ -198,16 +226,21 @@ - if (timer == null) { + if(timer == null) + { timer = new Timer(); } - timerTask = new TimerTask() { - public void run() { - if (isRunning) { + timerTask = new TimerTask() + { + public void run() + { + if(isRunning) + { updateLocation(); } - else { + else + { timerTask.cancel(); } } @@ -216,37 +249,47 @@ timer.schedule(timerTask, 0, Config.TICKER_MOVEMENT_DELAY); } - private void updateDirection() { - leftToRight = StringUtil.isRightToLeftText(text); - if (leftToRight) { + private void updateDirection() + { + leftToRight = StringUtil.isRightToLeftText(text); + if(leftToRight) + { tickerX = Integer.MAX_VALUE; } - else { + else + { tickerX = Integer.MIN_VALUE; } - } + } /** * Updates ticker location. */ - private void updateLocation() { - ESWTUIThreadRunner.syncExec(new Runnable() { - public void run() { - if (labels.size() <= 0) { + private void updateLocation() + { + ESWTUIThreadRunner.syncExec(new Runnable() + { + public void run() + { + if(labels.size() <= 0) + { // Ticker is removed from all displayables // so it is ok to stop it. isRunning = false; return; } - for (int i = 0; i < labels.size(); i++) { + for(int i = 0; i < labels.size(); i++) + { Label label = ((Label) labels.elementAt(i)); - if (!label.isDisposed()) { + if(!label.isDisposed()) + { label.setLocation((int) tickerX, 0); } } - if (((Label) labels.elementAt(0)).isDisposed()) { + if(((Label) labels.elementAt(0)).isDisposed()) + { // Label is disposed. This may happen only // when MIDlet is closing and in that case // this method would throw exception without @@ -256,23 +299,29 @@ } int labelWidth = ((Label) labels.elementAt(0)). - getBounds().width; + getBounds().width; - if (leftToRight) { + if(leftToRight) + { // Scrolling from left to right: - if (tickerX > screenWidth) { + if(tickerX > screenWidth) + { tickerX = -labelWidth; } - else { + else + { tickerX += stepSize; } } - else { + else + { // Scrolling from right to left: - if (tickerX < -labelWidth) { + if(tickerX < -labelWidth) + { tickerX = screenWidth; } - else { + else + { tickerX -= stepSize; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/GameCanvas.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/GameCanvas.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/GameCanvas.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui.game; @@ -23,7 +23,8 @@ /** * GameCanvas class. */ -public abstract class GameCanvas extends javax.microedition.lcdui.Canvas { +public abstract class GameCanvas extends javax.microedition.lcdui.Canvas +{ /** * Bit representing UP key. (1 << Canvas.UP) @@ -75,7 +76,8 @@ * * @param suppressKeyEvents supress game key events. */ - protected GameCanvas(boolean suppressKeyEvents) { + protected GameCanvas(boolean suppressKeyEvents) + { super(); LCDUIInvoker.initGameCanvas(this, suppressKeyEvents); } @@ -85,7 +87,8 @@ * * @return frameBuffer's Graphics */ - protected Graphics getGraphics() { + protected Graphics getGraphics() + { return (Graphics) LCDUIInvoker.getGraphics(this); } @@ -94,7 +97,8 @@ * * @return game key states */ - public int getKeyStates() { + public int getKeyStates() + { return LCDUIInvoker.getKeyStates(this); } @@ -103,7 +107,8 @@ * * @param g Graphics object */ - public void paint(javax.microedition.lcdui.Graphics g) { + public void paint(javax.microedition.lcdui.Graphics g) + { // If the Graphics doesn't belong to the frame buffer LCDUIInvoker.renderGraphics(this, g); } @@ -116,8 +121,10 @@ * @param w clip width * @param h clip height */ - public void flushGraphics(int x, int y, int w, int h) { - if (w > 0 && h > 0) { + public void flushGraphics(int x, int y, int w, int h) + { + if(w > 0 && h > 0) + { LCDUIInvoker.flushGraphics(this, x, y, w, h); } } @@ -125,7 +132,8 @@ /** * Flushes the frameBuffer to the display. */ - public void flushGraphics() { + public void flushGraphics() + { LCDUIInvoker.flushGraphics(this, 0, 0, getWidth(), getHeight()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/Layer.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/Layer.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/Layer.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui.game; @@ -22,7 +22,8 @@ /** * LCDUI Layer class. */ -public abstract class Layer { +public abstract class Layer +{ int x; int y; @@ -40,12 +41,14 @@ * Package level constructor prevents Layer being subclassed. This is * consistent with the MIDP 2.0 RI. */ - Layer(Image tileImage, int frameWidth, int frameHeight) { + Layer(Image tileImage, int frameWidth, int frameHeight) + { visible = true; setTileImage(tileImage, frameWidth, frameHeight); } - Layer(Layer from) { + Layer(Layer from) + { x = from.x; y = from.y; visible = from.visible; @@ -56,37 +59,45 @@ tileColumns = from.tileColumns; } - public void setPosition(int x, int y) { + public void setPosition(int x, int y) + { this.x = x; this.y = y; } - public void move(int deltaX, int deltaY) { + public void move(int deltaX, int deltaY) + { x += deltaX; y += deltaY; } - public final int getX() { + public final int getX() + { return x; } - public final int getY() { + public final int getY() + { return y; } - public final int getWidth() { + public final int getWidth() + { return getLayerWidth(); } - public final int getHeight() { + public final int getHeight() + { return getLayerHeight(); } - public void setVisible(boolean visible) { + public void setVisible(boolean visible) + { this.visible = visible; } - public final boolean isVisible() { + public final boolean isVisible() + { return visible; } @@ -100,8 +111,10 @@ * Set the source image and tile size. checks that the image is completely * tiled. computes the tile count. */ - void setTileImage(Image tileImage, int tileWidth, int tileHeight) { - if (tileWidth > 0 && tileHeight > 0) { + void setTileImage(Image tileImage, int tileWidth, int tileHeight) + { + if(tileWidth > 0 && tileHeight > 0) + { final int imageWidth = tileImage.getWidth(); final int imageHeight = tileImage.getHeight(); @@ -111,7 +124,8 @@ int totalHeight = rows * tileHeight; int totalWidth = cols * tileWidth; - if (totalHeight == imageHeight && totalWidth == imageWidth) { + if(totalHeight == imageHeight && totalWidth == imageWidth) + { this.tileImage = tileImage; this.tileWidth = tileWidth; this.tileHeight = tileHeight; @@ -121,13 +135,14 @@ } } throw new IllegalArgumentException( - MsgRepository.LAYER_EXCEPTION_INVALID_TILE_WIDTH_HEIGHT); + MsgRepository.LAYER_EXCEPTION_INVALID_TILE_WIDTH_HEIGHT); } /** * Is Layer visible in Graphics clip region. */ - final boolean isVisible(Graphics graphics, int pX, int pY) { + final boolean isVisible(Graphics graphics, int pX, int pY) + { int x1 = x + pX; int y1 = y + pY; int x2 = x1 + getWidth(); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/LayerManager.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/LayerManager.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/LayerManager.java Fri May 14 15:47:24 2010 +0300 @@ -23,7 +23,8 @@ /** * LayerManager class. */ -public class LayerManager { +public class LayerManager +{ private Vector layers; @@ -33,52 +34,64 @@ private int viewWidth = Integer.MAX_VALUE; private int viewHeight = Integer.MAX_VALUE; - public LayerManager() { + public LayerManager() + { layers = new Vector(); } - public void append(Layer aLayer) { + public void append(Layer aLayer) + { remove(aLayer); layers.addElement(aLayer); } - public void insert(Layer layer, int index) { - if (layer == null) { + public void insert(Layer layer, int index) + { + if(layer == null) + { throw new NullPointerException( - MsgRepository.LAYERMANAGER_EXCEPTION_LAYER_NULL); + MsgRepository.LAYERMANAGER_EXCEPTION_LAYER_NULL); } - if (index < 0 || index > layers.size()) { + if(index < 0 || index > layers.size()) + { throw new IndexOutOfBoundsException( - MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_LAYER_INDEX); + MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_LAYER_INDEX); } - if (index > layers.size() - 1 && layers.contains(layer)) { + if(index > layers.size() - 1 && layers.contains(layer)) + { throw new IndexOutOfBoundsException( - MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_LAYER_INDEX); + MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_LAYER_INDEX); } remove(layer); layers.insertElementAt(layer, index); } - public void remove(Layer layer) { - if (layer == null) { + public void remove(Layer layer) + { + if(layer == null) + { throw new NullPointerException( - MsgRepository.LAYERMANAGER_EXCEPTION_LAYER_NULL); + MsgRepository.LAYERMANAGER_EXCEPTION_LAYER_NULL); } layers.removeElement(layer); } - public Layer getLayerAt(int index) { + public Layer getLayerAt(int index) + { return (Layer) layers.elementAt(index); } - public int getSize() { + public int getSize() + { return layers.size(); } - public void setViewWindow(int x, int y, int width, int height) { - if (width < 0 || height < 0) { + public void setViewWindow(int x, int y, int width, int height) + { + if(width < 0 || height < 0) + { throw new IllegalArgumentException( - MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.LAYERMANAGER_EXCEPTION_INVALID_WIDTH_HEIGHT); } viewX = x; viewY = y; @@ -86,7 +99,8 @@ viewHeight = height; } - public void paint(Graphics graphics, int x, int y) { + public void paint(Graphics graphics, int x, int y) + { // save Graphics clip and translate final int oldClipX = graphics.getClipX(); final int oldClipY = graphics.getClipY(); @@ -106,9 +120,11 @@ // paint visible Layers Layer layer = null; - for (int i = layers.size() - 1; i >= 0; i--) { + for(int i = layers.size() - 1; i >= 0; i--) + { layer = getLayerAt(i); - if (layer.isVisible(graphics, x, y)) { + if(layer.isVisible(graphics, x, y)) + { graphics.translate(x, y); layer.paint(graphics); graphics.translate(-x, -y); @@ -118,7 +134,7 @@ // restore Graphics translation because translation is concatenated // need to translate back to 0,0 first graphics.translate(-graphics.getTranslateX(), - -graphics.getTranslateY()); + -graphics.getTranslateY()); // restore Graphics translate and clip graphics.translate(oldTransX, oldTransY); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/MsgRepository.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/MsgRepository.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/MsgRepository.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui.game; @@ -21,7 +21,8 @@ * constants in this class should begin with prefix "CLASSNAME_" where CLASSNAME * is the name of the class which is using the constant. */ -final class MsgRepository { +final class MsgRepository +{ public static final String SPRITE_EXCEPTION_INVALID_WIDTH_HEIGHT = "Width and height cannot be negative"; @@ -73,7 +74,8 @@ /** * Private Constructor. */ - private MsgRepository() { + private MsgRepository() + { } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/Sprite.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/Sprite.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/Sprite.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui.game; @@ -22,7 +22,8 @@ /** * LCDUI Sprite class. */ -public class Sprite extends Layer { +public class Sprite extends Layer +{ /** * Transform constant. @@ -103,7 +104,8 @@ * @param frameWidth Frame's width. * @param frameHeight Frame's height. */ - public Sprite(Image image, int frameWidth, int frameHeight) { + public Sprite(Image image, int frameWidth, int frameHeight) + { super(image, frameWidth, frameHeight); this.collisionWidth = frameWidth; this.collisionHeight = frameHeight; @@ -115,7 +117,8 @@ * * @param image Image. */ - public Sprite(Image image) { + public Sprite(Image image) + { this(image, image.getWidth(), image.getHeight()); } @@ -124,7 +127,8 @@ * * @param from source Sprite */ - public Sprite(Sprite from) { + public Sprite(Sprite from) + { super(from); this.frameIndex = from.frameIndex; this.frameCount = from.frameCount; @@ -148,23 +152,27 @@ * @param frameWidth Frame's width. * @param frameHeight Frame's height. */ - public void setImage(Image image, int frameWidth, int frameHeight) { + public void setImage(Image image, int frameWidth, int frameHeight) + { int oldTileCound = tileCount; int oldTileWidth = tileWidth; int oldTileHeight = tileHeight; setTileImage(image, frameWidth, frameHeight); this.transform &= TRANSFORM_MASK; - if (tileCount < oldTileCound) { + if(tileCount < oldTileCound) + { frameIndex = 0; frameArray = null; } - if (frameArray == null) { + if(frameArray == null) + { frameCount = tileCount; } // If image's dimension has changed: - if ((tileWidth != oldTileWidth) || (tileHeight != oldTileHeight)) { + if((tileWidth != oldTileWidth) || (tileHeight != oldTileHeight)) + { updateTransRefPixel(true); defineCollisionRectangle(0, 0, tileWidth, tileHeight); } @@ -175,23 +183,26 @@ * * @param transform Transform mask. */ - public void setTransform(int transform) { - if ((this.transform & TRANSFORM_MASK) != transform) { + public void setTransform(int transform) + { + if((this.transform & TRANSFORM_MASK) != transform) + { // flags have changed - switch (transform) { - case TRANS_NONE: - case TRANS_ROT90: - case TRANS_ROT180: - case TRANS_ROT270: - case TRANS_MIRROR: - case TRANS_MIRROR_ROT90: - case TRANS_MIRROR_ROT180: - case TRANS_MIRROR_ROT270: - // Ok - break; - default: - throw new IllegalArgumentException( - MsgRepository.SPRITE_EXCEPTION_INVALID_TRANSFORM); + switch(transform) + { + case TRANS_NONE: + case TRANS_ROT90: + case TRANS_ROT180: + case TRANS_ROT270: + case TRANS_MIRROR: + case TRANS_MIRROR_ROT90: + case TRANS_MIRROR_ROT180: + case TRANS_MIRROR_ROT270: + // Ok + break; + default: + throw new IllegalArgumentException( + MsgRepository.SPRITE_EXCEPTION_INVALID_TRANSFORM); } this.transform = transform; @@ -205,10 +216,12 @@ * * @param frameIndex Index. */ - public void setFrame(int frameIndex) { - if (frameIndex < 0 || frameIndex >= frameCount) { + public void setFrame(int frameIndex) + { + if(frameIndex < 0 || frameIndex >= frameCount) + { throw new IndexOutOfBoundsException( - MsgRepository.SPRITE_EXCEPTION_INVALID_FRAME_INDEX); + MsgRepository.SPRITE_EXCEPTION_INVALID_FRAME_INDEX); } this.frameIndex = frameIndex; } @@ -218,21 +231,24 @@ * * @return Index of current frame. */ - public int getFrame() { + public int getFrame() + { return frameIndex; } /** * Switches to the next frame. */ - public void nextFrame() { + public void nextFrame() + { frameIndex = (frameIndex + frameCount + 1) % frameCount; } /** * Switches to the previous frame. */ - public void prevFrame() { + public void prevFrame() + { frameIndex = (frameIndex + frameCount - 1) % frameCount; } @@ -241,7 +257,8 @@ * * @return Length of frame sequence. */ - public int getFrameSequenceLength() { + public int getFrameSequenceLength() + { return frameCount; } @@ -250,7 +267,8 @@ * * @return Number of raw frames. */ - public int getRawFrameCount() { + public int getRawFrameCount() + { return tileCount; } @@ -259,26 +277,32 @@ * * @param frameArray Array of frame indexes. */ - public void setFrameSequence(int[] frameArray) { + public void setFrameSequence(int[] frameArray) + { int[] tempArray; int tempCount; - if (frameArray == null) { + if(frameArray == null) + { // no sequence tempCount = tileCount; tempArray = null; } - else { + else + { tempCount = frameArray.length; - if (tempCount == 0) { + if(tempCount == 0) + { throw new IllegalArgumentException( - MsgRepository.SPRITE_EXCEPTION_INVALID_SEQUENCE_LENGTH); + MsgRepository.SPRITE_EXCEPTION_INVALID_SEQUENCE_LENGTH); } tempArray = new int[tempCount]; // check and copy the sequence - for (int i = 0; i < tempCount; i++) { - if (frameArray[i] < 0 || frameArray[i] >= tileCount) { + for(int i = 0; i < tempCount; i++) + { + if(frameArray[i] < 0 || frameArray[i] >= tileCount) + { throw new ArrayIndexOutOfBoundsException( - MsgRepository.SPRITE_EXCEPTION_INVALID_FRAME + i); + MsgRepository.SPRITE_EXCEPTION_INVALID_FRAME + i); } tempArray[i] = frameArray[i]; } @@ -294,7 +318,8 @@ * @param x X coordinate of reference pixel. * @param y Y coordinate of reference pixel. */ - public void defineReferencePixel(int x, int y) { + public void defineReferencePixel(int x, int y) + { referenceX = x; referenceY = y; updateTransRefPixel(false); @@ -305,7 +330,8 @@ * * @return X coordinate. */ - public int getRefPixelX() { + public int getRefPixelX() + { return getX() + transReferenceX; } @@ -314,7 +340,8 @@ * * @return Y coordinate. */ - public int getRefPixelY() { + public int getRefPixelY() + { return getY() + transReferenceY; } @@ -324,7 +351,8 @@ * @param x X-coordinate. * @param y Y-coordinate. */ - public void setRefPixelPosition(int x, int y) { + public void setRefPixelPosition(int x, int y) + { setPosition(x - transReferenceX, y - transReferenceY); } @@ -336,10 +364,12 @@ * @param width Width of the rectangle. * @param height Height of the rectangle. */ - public void defineCollisionRectangle(int x, int y, int width, int height) { - if (width < 0 || height < 0) { + public void defineCollisionRectangle(int x, int y, int width, int height) + { + if(width < 0 || height < 0) + { throw new IllegalArgumentException( - MsgRepository.SPRITE_EXCEPTION_INVALID_WIDTH_HEIGHT); + MsgRepository.SPRITE_EXCEPTION_INVALID_WIDTH_HEIGHT); } collisionX = x; @@ -355,24 +385,29 @@ * * @param moveLayer if the layer movement is needed based on transRef pixel change */ - private void updateTransRefPixel(boolean moveLayer) { + private void updateTransRefPixel(boolean moveLayer) + { int tempX = referenceX; int tempY = referenceY; - if ((transform & TRANSFORM_REFLECT_V) != 0) { + if((transform & TRANSFORM_REFLECT_V) != 0) + { tempY = tileHeight - 1 - tempY; } - if ((transform & TRANSFORM_REFLECT_H) != 0) { + if((transform & TRANSFORM_REFLECT_H) != 0) + { tempX = tileWidth - 1 - tempX; } - if ((transform & TRANSFORM_TRANSPOSE) != 0) { + if((transform & TRANSFORM_TRANSPOSE) != 0) + { // xor swap tempX ^= tempY; tempY ^= tempX; tempX ^= tempY; } - if (moveLayer) { + if(moveLayer) + { move(transReferenceX - tempX, transReferenceY - tempY); } @@ -380,26 +415,34 @@ transReferenceY = tempY; } - int getLayerHeight() { - if ((transform & TRANSFORM_TRANSPOSE) == 0) { + int getLayerHeight() + { + if((transform & TRANSFORM_TRANSPOSE) == 0) + { return tileHeight; } - else { + else + { return tileWidth; } } - int getLayerWidth() { - if ((transform & TRANSFORM_TRANSPOSE) == 0) { + int getLayerWidth() + { + if((transform & TRANSFORM_TRANSPOSE) == 0) + { return tileWidth; } - else { + else + { return tileHeight; } } - int getTileIndex() { - if (this.frameArray != null) { + int getTileIndex() + { + if(this.frameArray != null) + { return frameArray[frameIndex]; } return frameIndex; @@ -410,19 +453,21 @@ * * @param graphics Graphics. */ - public final void paint(Graphics graphics) { - if (visible) { + public final void paint(Graphics graphics) + { + if(visible) + { int index = getTileIndex(); int row = index / tileColumns; int col = index % tileColumns; graphics.drawRegion(tileImage, - col * tileWidth, - row * tileHeight, - tileWidth, - tileHeight, - transform & TRANSFORM_MASK, - x, y, - 0); + col * tileWidth, + row * tileHeight, + tileWidth, + tileHeight, + transform & TRANSFORM_MASK, + x, y, + 0); } } @@ -436,8 +481,10 @@ * * @return true if Image and this Sprite collides. */ - public boolean collidesWith(Image image, int x, int y, boolean pixelLevel) { - if (!visible) { + public boolean collidesWith(Image image, int x, int y, boolean pixelLevel) + { + if(!visible) + { return false; } @@ -457,12 +504,14 @@ int crY2 = this.y + collisionRect[1][1]; // Check boundary collision first: - if (!(x1 < crX2 && x2 > crX1 && y1 < crY2 && y2 > crY1)) { + if(!(x1 < crX2 && x2 > crX1 && y1 < crY2 && y2 > crY1)) + { return false; } // Rectangles intersect, can return a hit if not pixel level: - if (!pixelLevel) { + if(!pixelLevel) + { return true; } @@ -473,7 +522,8 @@ crX2 = Math.min(crX2, this.x + getLayerWidth()); crY2 = Math.min(crY2, this.y + getLayerHeight()); - if (!(x1 < crX2 && x2 > crX1 && y1 < crY2 && y2 > crY1)) { + if(!(x1 < crX2 && x2 > crX1 && y1 < crY2 && y2 > crY1)) + { // All overlapping pixels are outside the bounds of the Sprite // frame and only in the collision rect and are considered to // be transparent for pixel-level collision detection. @@ -507,10 +557,10 @@ sy2 += tempY; return com.nokia.mj.impl.nokialcdui.LCDUIInvoker.detectCollision( - tileImage, transform & TRANSFORM_MASK, crX1, crY1, - sx1, sy1, sx2, sy2, - image, TRANS_NONE, x, y, - 0, 0, image.getWidth(), image.getHeight()); + tileImage, transform & TRANSFORM_MASK, crX1, crY1, + sx1, sy1, sx2, sy2, + image, TRANS_NONE, x, y, + 0, 0, image.getWidth(), image.getHeight()); } /** @@ -520,9 +570,11 @@ * @param pixelLevel Is collision detected in pixel level. * @return True if sprites collide. */ - public boolean collidesWith(Sprite otherSprite, boolean pixelLevel) { + public boolean collidesWith(Sprite otherSprite, boolean pixelLevel) + { // Both Sprites must be visible in order for a collision to be detected: - if (!(visible && otherSprite.visible)) { + if(!(visible && otherSprite.visible)) + { return false; } @@ -543,12 +595,14 @@ int cr2y2 = otherSprite.y + collisionRect2[1][1]; // Check boundary collision first: - if (!(cr2x1 < cr1x2 && cr2x2 > cr1x1 && cr2y1 < cr1y2 && cr2y2 > cr1y1)) { + if(!(cr2x1 < cr1x2 && cr2x2 > cr1x1 && cr2y1 < cr1y2 && cr2y2 > cr1y1)) + { return false; } // Bounding rectangles collide, can return hit if not pixel level. - if (!pixelLevel) { + if(!pixelLevel) + { return true; } @@ -566,7 +620,8 @@ cr2x2 = Math.min(cr2x2, otherSprite.x + otherSprite.getLayerWidth()); cr2y2 = Math.min(cr2y2, otherSprite.y + otherSprite.getLayerHeight()); - if (!(cr1x1 < cr2x2 && cr1x2 > cr2x1 && cr1y1 < cr2y2 && cr1y2 > cr2y1)) { + if(!(cr1x1 < cr2x2 && cr1x2 > cr2x1 && cr1y1 < cr2y2 && cr1y2 > cr2y1)) + { // All overlapping pixels are outside the bounds of the // Sprite frame and only in the collision rect and are // considered to be transparent for pixel-level collision detection. @@ -624,15 +679,15 @@ s2y2 += y2; return com.nokia.mj.impl.nokialcdui.LCDUIInvoker.detectCollision( - tileImage, transform & TRANSFORM_MASK, - cr1x1, cr1y1, - s1x1, s1y1, s1x2, s1y2, + tileImage, transform & TRANSFORM_MASK, + cr1x1, cr1y1, + s1x1, s1y1, s1x2, s1y2, - otherSprite.tileImage, - otherSprite.transform & TRANSFORM_MASK, - cr2x1, cr2y1, - s2x1, s2y1, s2x2, s2y2 - ); + otherSprite.tileImage, + otherSprite.transform & TRANSFORM_MASK, + cr2x1, cr2y1, + s2x1, s2y1, s2x2, s2y2 + ); } /** @@ -642,10 +697,12 @@ * @param pixelLevel Is collision detected in pixel level. * @return True if collision occurs. */ - public boolean collidesWith(TiledLayer tiledLayer, boolean pixelLevel) { + public boolean collidesWith(TiledLayer tiledLayer, boolean pixelLevel) + { // The Sprite and TiledLayer must both be visible // in order for a collision to be detected: - if (!visible || !tiledLayer.isVisible()) { + if(!visible || !tiledLayer.isVisible()) + { return false; } @@ -657,7 +714,8 @@ int crX2 = this.x + collisionRect[1][0]; int crY2 = this.y + collisionRect[1][1]; - if (!pixelLevel) { + if(!pixelLevel) + { return tiledLayer.collidesCell(crX1, crY1, crX2, crY2); } @@ -707,18 +765,22 @@ crX2 = Math.min(crX2, this.x + getLayerWidth()); crY2 = Math.min(crY2, this.y + getLayerHeight()); - for (int row = startRow; row <= endRow; row++) { - for (int col = startCol; col <= endCol; col++) { + for(int row = startRow; row <= endRow; row++) + { + for(int col = startCol; col <= endCol; col++) + { int tile = tiledLayer.getCell(col, row); - if (tile != 0) { //non clear cell + if(tile != 0) //non clear cell + { // cell rect in painter's coordinates final int cellX1 = tiledLayer.getX() + col * cellWidth; final int cellY1 = tiledLayer.getY() + row * cellHeight; final int cellX2 = cellX1 + cellWidth; final int cellY2 = cellY1 + cellHeight; - if (!(cellX1 < crX2 && cellX2 > crX1 - && cellY1 < crY2 && cellY2 > crY1)) { + if(!(cellX1 < crX2 && cellX2 > crX1 + && cellY1 < crY2 && cellY2 > crY1)) + { // All overlapping pixels are outside the bounds of the // Sprite frame and only in the collision rect and // are considered to be transparent for pixel-level @@ -726,7 +788,8 @@ break; //no collision, move on to next cell } - if (tile < 0) { + if(tile < 0) + { tile = tiledLayer.getAnimatedTile(tile); } @@ -740,16 +803,17 @@ final int cx2 = cx1 + cellWidth; final int cy2 = cy1 + cellHeight; - if (com.nokia.mj.impl.nokialcdui.LCDUIInvoker.detectCollision( - tileImage, - transform & TRANSFORM_MASK, - crX1, crY1, - sx1, sy1, sx2, sy2, + if(com.nokia.mj.impl.nokialcdui.LCDUIInvoker.detectCollision( + tileImage, + transform & TRANSFORM_MASK, + crX1, crY1, + sx1, sy1, sx2, sy2, - tiledLayer.tileImage, - TRANS_NONE, - cellX1, cellY1, - cx1, cy1, cx2, cy2)) { + tiledLayer.tileImage, + TRANS_NONE, + cellX1, cellY1, + cx1, cy1, cx2, cy2)) + { return true; } // else no pixel collision, move on to next cell @@ -763,9 +827,12 @@ /** * Calculate transformed collision rectange in sprite co-ordinates. */ - private int[][] getTransCollisionRect() { - if ((transform & TRANSFORM_COLLISION) == 0) { - if (transCollision == null) { + private int[][] getTransCollisionRect() + { + if((transform & TRANSFORM_COLLISION) == 0) + { + if(transCollision == null) + { transCollision = new int[2][2]; } @@ -774,48 +841,51 @@ int w = 0; int h = 0; - switch(transform & TRANSFORM_MASK) { - case TRANS_NONE: - x = collisionX; - y = collisionY; - break; - case TRANS_ROT90: - x = tileHeight - collisionY - collisionHeight; - y = collisionX; - break; - case TRANS_ROT180: - x = tileWidth - collisionX - collisionWidth; - y = tileHeight - collisionY - collisionHeight; - break; - case TRANS_ROT270: - x = collisionY; - y = tileWidth - collisionX - collisionWidth; - break; - case TRANS_MIRROR: - x = tileWidth - collisionX - collisionWidth; - y = collisionY; - break; - case TRANS_MIRROR_ROT90: - x = tileHeight - collisionY - collisionHeight; - y = tileWidth - collisionX - collisionWidth; - break; - case TRANS_MIRROR_ROT180: - x = collisionX; - y = tileHeight - collisionY - collisionHeight; - break; - case TRANS_MIRROR_ROT270: - x = collisionY; - y = collisionX; - break; - default: - break; + switch(transform & TRANSFORM_MASK) + { + case TRANS_NONE: + x = collisionX; + y = collisionY; + break; + case TRANS_ROT90: + x = tileHeight - collisionY - collisionHeight; + y = collisionX; + break; + case TRANS_ROT180: + x = tileWidth - collisionX - collisionWidth; + y = tileHeight - collisionY - collisionHeight; + break; + case TRANS_ROT270: + x = collisionY; + y = tileWidth - collisionX - collisionWidth; + break; + case TRANS_MIRROR: + x = tileWidth - collisionX - collisionWidth; + y = collisionY; + break; + case TRANS_MIRROR_ROT90: + x = tileHeight - collisionY - collisionHeight; + y = tileWidth - collisionX - collisionWidth; + break; + case TRANS_MIRROR_ROT180: + x = collisionX; + y = tileHeight - collisionY - collisionHeight; + break; + case TRANS_MIRROR_ROT270: + x = collisionY; + y = collisionX; + break; + default: + break; } - if ((transform & TRANSFORM_TRANSPOSE) == 0) { + if((transform & TRANSFORM_TRANSPOSE) == 0) + { w = collisionWidth; h = collisionHeight; } - else { + else + { w = collisionHeight; h = collisionWidth; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src/javax/microedition/lcdui/game/TiledLayer.java --- a/javauis/lcdui_qt/src/javax/microedition/lcdui/game/TiledLayer.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src/javax/microedition/lcdui/game/TiledLayer.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui.game; @@ -19,7 +19,8 @@ import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; -public class TiledLayer extends Layer { +public class TiledLayer extends Layer +{ // Animated tile array increment private static final int ANIM_ARRAY_INCREMENT = 4; @@ -31,12 +32,14 @@ private int[] animArray; private int animCount; - public TiledLayer(int cols, int rows, Image tileImage, int tileWidth, int tileHeight) { + public TiledLayer(int cols, int rows, Image tileImage, int tileWidth, int tileHeight) + { super(tileImage, tileWidth, tileHeight); - if (cols < 1 || rows < 1) { + if(cols < 1 || rows < 1) + { throw new IllegalArgumentException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_DIMENSIONS); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_DIMENSIONS); } this.cols = cols; @@ -46,7 +49,8 @@ animCount = 0; } - public void setStaticTileSet(Image tileImage, int tileWidth, int tileHeight) { + public void setStaticTileSet(Image tileImage, int tileWidth, int tileHeight) + { final int oldTileCount = tileCount; setTileImage(tileImage, tileWidth, tileHeight); @@ -56,44 +60,54 @@ // If not, the contents of the grid will be cleared (all cells will // contain index 0) and all animated tiles will be deleted. // - if (tileCount < oldTileCount) { + if(tileCount < oldTileCount) + { fillCells(0, 0, cols, rows, 0); animCount = 0; } } - public void setCell(int col, int row, int aTileIndex) { + public void setCell(int col, int row, int aTileIndex) + { validateTileIndex(aTileIndex); cells[row][col] = aTileIndex; } - public int getCell(int col, int row) { + public int getCell(int col, int row) + { return cells[row][col]; } - public void fillCells(int col, int row, int numCols, int numRows, int tileIndex) { - if (numCols < 0) { + public void fillCells(int col, int row, int numCols, int numRows, int tileIndex) + { + if(numCols < 0) + { throw new IllegalArgumentException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_NUMBER_OF_COLUMNS); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_NUMBER_OF_COLUMNS); } - if (numRows < 0) { + if(numRows < 0) + { throw new IllegalArgumentException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_NUMBER_OF_ROWS); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_NUMBER_OF_ROWS); } validateTileIndex(tileIndex); - for (int i = col + numCols; --i >= col;) { + for(int i = col + numCols; --i >= col;) + { cells[row][i] = tileIndex; } - for (int i = row + numRows; --i > row;) { + for(int i = row + numRows; --i > row;) + { System.arraycopy(cells[row], col, cells[i], col, numCols); } } - public int createAnimatedTile(int tileIndex) { - if (tileIndex < 0 || tileIndex > tileCount) { + public int createAnimatedTile(int tileIndex) + { + if(tileIndex < 0 || tileIndex > tileCount) + { throw new IndexOutOfBoundsException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); } final int index = animCount; @@ -106,55 +120,68 @@ /** * Grows the animated tile array if required. */ - private void checkCapacity(int requiredLength) { + private void checkCapacity(int requiredLength) + { int length = animArray.length; - if (requiredLength > length) { + if(requiredLength > length) + { int[] array = new int[length + ANIM_ARRAY_INCREMENT]; System.arraycopy(animArray, 0, array, 0, length); animArray = array; } } - public void setAnimatedTile(int animIndex, int tileIndex) { + public void setAnimatedTile(int animIndex, int tileIndex) + { final int index = ~animIndex; - if (index >= animCount) { + if(index >= animCount) + { throw new IndexOutOfBoundsException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_ANIMTILE_INDEX); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_ANIMTILE_INDEX); } - if (tileIndex < 0 || tileIndex > tileCount) { + if(tileIndex < 0 || tileIndex > tileCount) + { throw new IndexOutOfBoundsException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); } animArray[index] = tileIndex; } - public int getAnimatedTile(int animIndex) { + public int getAnimatedTile(int animIndex) + { final int index = ~animIndex; - if (index >= animCount) { + if(index >= animCount) + { throw new IndexOutOfBoundsException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_ANIMTILE_INDEX); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_ANIMTILE_INDEX); } return animArray[index]; } - public final int getCellWidth() { + public final int getCellWidth() + { return tileWidth; } - public final int getCellHeight() { + public final int getCellHeight() + { return tileHeight; } - public final int getColumns() { + public final int getColumns() + { return cols; } - public final int getRows() { + public final int getRows() + { return rows; } - public final void paint(Graphics aGraphics) { - if (visible) { + public final void paint(Graphics aGraphics) + { + if(visible) + { aGraphics.translate(x, y); int clipX1 = aGraphics.getClipX(); @@ -182,10 +209,13 @@ int dx; int dy; - for (int row = begRow; row <= endRow; row++) { - for (int col = begCol; col <= endCol; col++) { + for(int row = begRow; row <= endRow; row++) + { + for(int col = begCol; col <= endCol; col++) + { final int index = validateTileIndex(cells[row][col]); - if (index >= 0) { + if(index >= 0) + { // Future performace improvement suggestion: accumulate // region // @@ -211,10 +241,10 @@ sy = tr * th; aGraphics.drawRegion(tileImage, - sx, sy, - tw, th, - Sprite.TRANS_NONE, - dx, dy, 0); + sx, sy, + tw, th, + Sprite.TRANS_NONE, + dx, dy, 0); } } } @@ -223,20 +253,24 @@ } } - private int validateTileIndex(int tileIndex) { - if (tileIndex > tileCount) { + private int validateTileIndex(int tileIndex) + { + if(tileIndex > tileCount) + { throw new IndexOutOfBoundsException( - MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); + MsgRepository.TILEDLAYER_EXCEPTION_INVALID_TILE_INDEX); } // check createAnimatedTile has been called, getAnimatedTile will throw // exception if hasn't. - if (tileIndex < 0) { + if(tileIndex < 0) + { tileIndex = getAnimatedTile(tileIndex); } return tileIndex - 1; } - boolean collidesCell(int aX1, int aY1, int aX2, int aY2) { + boolean collidesCell(int aX1, int aY1, int aX2, int aY2) + { // tiled layer rect in painter's coordinates int tlX1 = x; int tlY1 = y; @@ -251,7 +285,8 @@ tlY2 = Math.min(tlY2, aY2); // return false if empty intersection. - if (!((tlX1 < tlX2) && (tlY1 < tlY2))) { + if(!((tlX1 < tlX2) && (tlY1 < tlY2))) + { return false; } @@ -266,9 +301,12 @@ int endRow = (tlY2 - 1) / tileHeight; int endCol = (tlX2 - 1) / tileWidth; - for (int row = startRow; row <= endRow; row++) { - for (int col = startCol; col <= endCol; col++) { - if (cells[row][col] != 0) { + for(int row = startRow; row <= endRow; row++) + { + for(int col = startCol; col <= endCol; col++) + { + if(cells[row][col] != 0) + { // at least one cell is not empty return true; } @@ -279,11 +317,13 @@ return false; } - int getLayerWidth() { + int getLayerWidth() + { return cols * tileWidth; } - int getLayerHeight() { + int getLayerHeight() + { return rows * tileHeight; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2me/javax/microedition/lcdui/OpenLcduiLocalization.java --- a/javauis/lcdui_qt/src_j2me/javax/microedition/lcdui/OpenLcduiLocalization.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2me/javax/microedition/lcdui/OpenLcduiLocalization.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -20,126 +20,150 @@ import com.nokia.mj.impl.utils.ResourceLoader; import org.eclipse.swt.SWT; -final class OpenLcduiLocalization { - - private static ResourceLoader iRes; - - public static String getMessage(String key) { - - if (key == null) throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); - - if(key.equals("key_up")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("key_down")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("key_left")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("key_right")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("key_select")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("key_stop")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("alert_error")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("alert_warning")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("alert_info")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("alert_conf")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); +final class OpenLcduiLocalization +{ + + private static ResourceLoader iRes; + + public static String getMessage(String key) + { + + if(key == null) throw new IllegalArgumentException( + MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); + + if(key.equals("key_up")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("key_down")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("key_left")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("key_right")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("key_select")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("key_stop")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_error")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_warning")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_info")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_conf")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_alarm")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("alert_null")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); + return iRes.format(key).toString(); + } + + if(key.equals("pb_fetch_number")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("pb_fetch_number_short")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("pb_fetch_email")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("pb_fetch_email_short")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("create_call")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("create_call_short")) + { + iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); + return iRes.format(key).toString(); + } + + if(key.equals("back")) + { + iRes = ResourceLoader.getInstance("lcduiavkon", "text_softkey_"); + return iRes.format(key).toString(); + } + + if(key.equals("close")) + { + iRes = ResourceLoader.getInstance("lcduiavkon", "text_softkey_"); + return iRes.format(key).toString(); + } + + if(key.equals("empty_list")) + { + iRes = ResourceLoader.getInstance("lcduiavkon", "qtn_selec_"); + return iRes.format(key).toString(); + } + + if(key.equals("help")) + { + iRes = ResourceLoader.getInstance("lcduiavkon", "qtn_options_"); + return iRes.format(key).toString(); + } + + return SWT.getMessage(key); } - - if(key.equals("alert_alarm")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("alert_null")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_"); - return iRes.format(key).toString(); - } - - if(key.equals("pb_fetch_number")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("pb_fetch_number_short")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("pb_fetch_email")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("pb_fetch_email_short")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("create_call")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("create_call_short")){ - iRes = ResourceLoader.getInstance("lcdui", "qtn_midp_option_"); - return iRes.format(key).toString(); - } - - if(key.equals("back")){ - iRes = ResourceLoader.getInstance("lcduiavkon", "text_softkey_"); - return iRes.format(key).toString(); - } - - if(key.equals("close")){ - iRes = ResourceLoader.getInstance("lcduiavkon", "text_softkey_"); - return iRes.format(key).toString(); - } - - if(key.equals("empty_list")){ - iRes = ResourceLoader.getInstance("lcduiavkon", "qtn_selec_"); - return iRes.format(key).toString(); - } - - if(key.equals("help")){ - iRes = ResourceLoader.getInstance("lcduiavkon", "qtn_options_"); - return iRes.format(key).toString(); - } - - return SWT.getMessage(key); - } - + } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicProperty.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicProperty.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicProperty.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -24,7 +24,8 @@ * com.nokia.mj.impl.rt.properties + . hierarchy. * */ -public interface DynamicProperty { +public interface DynamicProperty +{ /** * Sets the dynamic system property based on the received argument. diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicPropertyInfo.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicPropertyInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/DynamicPropertyInfo.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -26,7 +26,8 @@ * value. */ -public class DynamicPropertyInfo { +public class DynamicPropertyInfo +{ /** * Tells whether the dynamic parameter does not change during the lifetime @@ -47,7 +48,8 @@ /** * Constructor of DynamicPropertyInfo class. */ - public DynamicPropertyInfo (String aPropertyName) { + public DynamicPropertyInfo(String aPropertyName) + { iPropertyName = aPropertyName; iIsPropertyValueStatic = false; } @@ -56,7 +58,8 @@ * Getter method for the name of the system property. * @return The name of the system property. */ - public String getPropertyName () { + public String getPropertyName() + { return iPropertyName; } @@ -64,7 +67,8 @@ * Setter method for the value of the system property. * @param aPropertyValue the value of the system property. */ - public void setPropertyValue (String aPropertyValue) { + public void setPropertyValue(String aPropertyValue) + { iPropertyValue = aPropertyValue; } @@ -72,7 +76,8 @@ * Getter method for the value of the system property. * @return The value of the system property. */ - public String getPropertyValue () { + public String getPropertyValue() + { return iPropertyValue; } @@ -81,7 +86,8 @@ * not change during the lifetime of the application. * @param aIsPropertyValueStatic boolean info. */ - public void setIsPropertyValueStatic (boolean aIsPropertyValueStatic) { + public void setIsPropertyValueStatic(boolean aIsPropertyValueStatic) + { iIsPropertyValueStatic = aIsPropertyValueStatic; } @@ -90,7 +96,8 @@ * not change during the lifetime of the application. * @return Boolean info. */ - public boolean getIsPropertyValueStatic () { + public boolean getIsPropertyValueStatic() + { return iIsPropertyValueStatic; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationInfo.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationInfo.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -23,14 +23,14 @@ * ApplicationInfo is an abstract base class for API implementations, * which allows getting application related static information. *

            - * The class provides a static getter method for getting an instance of + * The class provides a static getter method for getting an instance of * the running application. In those runtimes that are always running only - * one instance (like MIDP) returns always the same instance of the + * one instance (like MIDP) returns always the same instance of the * ApplicationInfo. However those runtimes (like eRCP), that may run several * application in the same JVM instance, will return an application specific * instance. *

            - * The runtime implementation hides the solving of the correct application + * The runtime implementation hides the solving of the correct application * when method getInstace is called. However it must be noted * that if the call is made some common thread, the getInstace * might not able to solve the correct application. @@ -78,78 +78,79 @@ * @version 1.0 */ -public class ApplicationInfo +public class ApplicationInfo { - public ApplicationInfo() { + public ApplicationInfo() + { } /** - * A constant representing the manufacturer domain when returned from the - * method {@link ApplicationInfo#getProtectionDomain + * A constant representing the manufacturer domain when returned from the + * method {@link ApplicationInfo#getProtectionDomain * getProtectionDomain} - */ + */ public static final String MANUFACTURER_DOMAIN = "MFD"; /** - * A constant representing the identified third party domain when returned - * from the method {@link ApplicationInfo#getProtectionDomain + * A constant representing the identified third party domain when returned + * from the method {@link ApplicationInfo#getProtectionDomain * getProtectionDomain} - */ + */ public static final String IDENTIFIED_THIRD_PARTY_DOMAIN = "ITPD"; /** - * A constant representing the operator domain when returned from the + * A constant representing the operator domain when returned from the * method {@link ApplicationInfo#getProtectionDomain getProtectionDomain} - */ + */ public static final String OPERATOR_DOMAIN = "OPD"; /** - * A constant representing the unidentified third party domain when - * returned from the method {@link ApplicationInfo#getProtectionDomain + * A constant representing the unidentified third party domain when + * returned from the method {@link ApplicationInfo#getProtectionDomain * getProtectionDomain} - */ + */ public static final String UNIDENTIFIED_THIRD_PARTY_DOMAIN = "UTPD"; /** - * A constant representing the MIDP runtime when - * returned from the method {@link ApplicationInfo#getRuntimeType + * A constant representing the MIDP runtime when + * returned from the method {@link ApplicationInfo#getRuntimeType * getRuntimeType} - */ + */ public static final String RUNTIME_MIDP = "MIDP"; /** - * A constant representing the non managed runtime when - * returned from the method {@link ApplicationInfo#getRuntimeType + * A constant representing the non managed runtime when + * returned from the method {@link ApplicationInfo#getRuntimeType * getRuntimeType}. - */ + */ public static final String RUNTIME_NON_MANAGED = "NON_MANAGED"; /** - * A constant representing the eRCP runtime when - * returned from the method {@link ApplicationInfo#getRuntimeType + * A constant representing the eRCP runtime when + * returned from the method {@link ApplicationInfo#getRuntimeType * getRuntimeType}. - */ + */ public static final String RUNTIME_ERCP = "ERCP"; - /** + /** * Property name of the runtime implementation package end. It * should be noted that ApplicationUtils class uses the same * property for similar purposes as ApplicationInfo class does. - */ + */ static final String PACKAGE_END_PROPERTY_NAME = "com.nokia.rt.port"; - /** - * Runtime implmentation package prefix. It should be noted that - * ApplicationUtils class uses the same property for similar purposes + /** + * Runtime implmentation package prefix. It should be noted that + * ApplicationUtils class uses the same property for similar purposes * as ApplicationInfo class does. - */ + */ static final String PACKAGE_PREFIX = "com.nokia.mj.impl.rt."; - /** + /** * Name of the runtime specific class that extends this base class. - */ + */ private static final String PORTCLASS = ".ApplicationInfoImpl"; /** @@ -158,36 +159,36 @@ */ private static ApplicationInfo sInstance = null; - /** - * When the class is first loaded the static initializer will create a + /** + * When the class is first loaded the static initializer will create a * singleton instance of runtime dependent instance of class extending the - * ApplicationInfo base class. The class is created using dynamic - * instantiation (Class.forname & Class.newInstance) and - * the name of the class is a combination of PACKAGE_PREFIX + + * ApplicationInfo base class. The class is created using dynamic + * instantiation (Class.forname & Class.newInstance) and + * the name of the class is a combination of PACKAGE_PREFIX + * <value of system property PACKAGE_END_PROPERTY_NAME > * + .<value of PORTCLASS member variable >. */ - static + static { //Get the system proptery defining the end of package. /*String packageEnd = System.getProperty(PACKAGE_END_PROPERTY_NAME); - if(packageEnd == null) + if(packageEnd == null) { - throw new RuntimeException + throw new RuntimeException ("Not able to load " + PORTCLASS + "class since " + - PACKAGE_END_PROPERTY_NAME + + PACKAGE_END_PROPERTY_NAME + " system property is undefined"); } //Construct the class String className = PACKAGE_PREFIX + packageEnd + PORTCLASS; - try + try { Class clazz = Class.forName(className); sInstance = (ApplicationInfo)clazz.newInstance(); } - catch (Exception e) + catch (Exception e) { e.printStackTrace(); throw new RuntimeException ("Not able to instantiate class " + @@ -197,57 +198,58 @@ } /** - * Returns an instace of ApplicationInfo class which provides access to + * Returns an instace of ApplicationInfo class which provides access to * application related static information. * - * @return the ApplicationInfo object, null if the construction of the + * @return the ApplicationInfo object, null if the construction of the * object has faild */ - public static ApplicationInfo getInstance() + public static ApplicationInfo getInstance() { return sInstance; } /** - * Returns the type of the runtime where in the application is run. There - * are three predefined runtime types that are represented by constants - * + * Returns the type of the runtime where in the application is run. There + * are three predefined runtime types that are represented by constants + * * @see #RUNTIME_MIDP * @see #RUNTIME_NON_MANAGED - * @see #RUNTIME_ERCP + * @see #RUNTIME_ERCP * * - * @return the runtime type as String. The return value should never be + * @return the runtime type as String. The return value should never be * null */ //public abstract String getRuntimeType(); /** - * Returns the protection domain of the application. There are four predefined - * protection domains that are represented by constants - * + * Returns the protection domain of the application. There are four predefined + * protection domains that are represented by constants + * * @see #MANUFACTURER_DOMAIN * @see #IDENTIFIED_THIRD_PARTY_DOMAIN - * @see #OPERATOR_DOMAIN - * @see #UNIDENTIFIED_THIRD_PARTY_DOMAIN - * + * @see #OPERATOR_DOMAIN + * @see #UNIDENTIFIED_THIRD_PARTY_DOMAIN + * * @return protection domain as String */ //public abstract String getProtectionDomain(); /** * Returns an unique application identifier. - * + * * @return the Uid. The return value should never be null */ - public Uid getUid() { + public Uid getUid() + { return Uid.createUid("OpenLCDUI_Test"); } /** - * Returns a unique application suite identifier. The suite concept may be - * different in different runtimes and some of them might not support the + * Returns a unique application suite identifier. The suite concept may be + * different in different runtimes and some of them might not support the * concept at all. *

            * Note: Please consider carefully if GetUid() would be enough for your @@ -259,8 +261,8 @@ //public abstract Uid getSuiteUid(); /** - * Returns the suite name of the application. The suite concept may be - * different in different runtimes and some of them migth not support the + * Returns the suite name of the application. The suite concept may be + * different in different runtimes and some of them migth not support the * concept at all. *

            * In MIDP this method returns the name of the MIDlet Suite. @@ -299,8 +301,8 @@ /** * Returns the version of the application. The format of the version is - * <main>.<major>.<minor> where - * main, major and minor are in + * <main>.<major>.<minor> where + * main, major and minor are in * decimal format. *

            * Some runtime implmentations might not return the value at all. @@ -313,7 +315,7 @@ /** * Returns the root path of the application. The root path means an - * application specific directory where the different API implementations + * application specific directory where the different API implementations * are able to write their files. No other applications are able access * files under the root path. *

            @@ -336,15 +338,16 @@ //public abstract String getMainClass(); /** - * Returns the attribute whose name is given as parameter. The attribute - * value is obtained from the JAR manifest file and/or some other + * Returns the attribute whose name is given as parameter. The attribute + * value is obtained from the JAR manifest file and/or some other * descriptor (e.g. JAD file) using the runtime specific override rules. * * @param key Attribute key value. * * @return the attribute value as String if found, otherwise null. */ - public String getAttribute(String key) { + public String getAttribute(String key) + { return null; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationUtils.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationUtils.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ApplicationUtils.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -73,7 +73,8 @@ public class ApplicationUtils { - public ApplicationUtils() { + public ApplicationUtils() + { } /** @@ -176,7 +177,8 @@ * and the runtime itself. * */ - public void notifyExitCmd() { + public void notifyExitCmd() + { doShutdown(); }; @@ -208,7 +210,7 @@ public abstract void checkPermission(Uid appUid,Permission p) throws AccessControlException, NullPointerException; -*/ + */ /** * Adds a shutdown notifications listener to receive notifications when * the application is about to close. @@ -239,17 +241,17 @@ * This method can be used for pre-warming features. If the runtime is in * pre-warmed state where the application to be launched is not yet known, * this method will block. It is safe to call this method if the application - * is already known - in that case the method won't block. Once the - * application is known all the waiters will be released. Knowing the - * application doesn't necessarily mean that the application it self - * has been created (might happen later). The method will provide info + * is already known - in that case the method won't block. Once the + * application is known all the waiters will be released. Knowing the + * application doesn't necessarily mean that the application it self + * has been created (might happen later). The method will provide info * whether to continue or cancel the start up as a return value. * @return true if the user should continue starting, otherwise the user * should do the required shut down proceures. */ public boolean waitStart() { - synchronized (mApplicationStartLock) + synchronized(mApplicationStartLock) { if(mStartCmd == null) { @@ -257,7 +259,7 @@ { mApplicationStartLock.wait(); } - catch (InterruptedException ie) + catch(InterruptedException ie) { } } @@ -290,7 +292,7 @@ { if(mApplicationStartLock != null) { - synchronized (mApplicationStartLock) + synchronized(mApplicationStartLock) { mStartCmd = new Boolean(doStart); mApplicationStartLock.notifyAll(); @@ -306,10 +308,10 @@ if(mListeners != null) { Enumeration enumer = mListeners.elements(); - while ( enumer.hasMoreElements()) + while(enumer.hasMoreElements()) { ShutdownListener listener = - (ShutdownListener)enumer.nextElement(); + (ShutdownListener)enumer.nextElement(); listener.shuttingDown(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/Finalizer.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/Finalizer.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/Finalizer.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -26,48 +26,48 @@ /** * Some public APIs are defined so that they do not define any explicit method - * for informing when the object has become oblsolete - - * javax.microedition.lcdui.Image is good example. Image contains native - * resources and the class doesn't contain any close method. Native resources - * can be very large and those must be freed when the Java object is garbage + * for informing when the object has become oblsolete - + * javax.microedition.lcdui.Image is good example. Image contains native + * resources and the class doesn't contain any close method. Native resources + * can be very large and those must be freed when the Java object is garbage * collected. This leads to need to use finalization feature which is not part * of CLDC. *

            - * As the finalization itself is a problem in CLDC, there must be a VM vendor - * specific proprietary solution available. When using this class the - * finalization can be used in any configuration using same implementation. + * As the finalization itself is a problem in CLDC, there must be a VM vendor + * specific proprietary solution available. When using this class the + * finalization can be used in any configuration using same implementation. * This class hides possible differences between different configurations. *

            - * There are some issues that should be taken into account when taking + * There are some issues that should be taken into account when taking * finalization into use: *

              - *
            • Finalizers should be used in public APIs to ensure that resources are - * freed. This is the only option when there is no close() functionality on - * public API. Even if public API has close() funtionality, finalization - * should be used to ensure that resources are freed when MIDlet developer + *
            • Finalizers should be used in public APIs to ensure that resources are + * freed. This is the only option when there is no close() functionality on + * public API. Even if public API has close() funtionality, finalization + * should be used to ensure that resources are freed when MIDlet developer * forgets to use close().
            • - *
            • In our internal/implementation code finalization should not be used, + *
            • In our internal/implementation code finalization should not be used, * as it is inaccurate and "slow" way of handling resource relase.
            • - *
            • The class using finalization feature must not contain finalize() - * method - not even protected/private one. This is because in MIDP the - * application developer might have overridden the class and implemented the + *
            • The class using finalization feature must not contain finalize() + * method - not even protected/private one. This is because in MIDP the + * application developer might have overridden the class and implemented the * own finalize() method for some total other purposes.
            • *
            *

            - *

            How to add a class to be finalized

            + *

            How to add a class to be finalized

            * When a class needs the finalization support it must implement an inner class - * that extends the com.nokia.mj.impl.rt.support.Finalizer class. The inner - * class must implement abstract method - * {@link Finalizer#finalizeImpl}, which is called by the JVMwhen the object + * that extends the com.nokia.mj.impl.rt.support.Finalizer class. The inner + * class must implement abstract method + * {@link Finalizer#finalizeImpl}, which is called by the JVMwhen the object * is finalized. - * It is not recommended to do the actual finalization actions in the - * {@link Finalizer#finalizeImpl} method - instead there should be a dedicated - * finalize method in the API class which is called from the {@link - * Finalizer#finalizeImpl} method. It should be noted that the dedicated + * It is not recommended to do the actual finalization actions in the + * {@link Finalizer#finalizeImpl} method - instead there should be a dedicated + * finalize method in the API class which is called from the {@link + * Finalizer#finalizeImpl} method. It should be noted that the dedicated * finalize method name must be other than finalize (e.g. - * doFinalize). + * doFinalize). *

            - * The class needing the finalization support must store one instance of + * The class needing the finalization support must store one instance of * the inner class into a private member variable. It is recommended to do * the initialization of the member variable directly in the definition part * as it is done in the example below. When doing this, it should be noted @@ -77,24 +77,24 @@ * Once the class is enabled for finalization, the finalization support can't * be cancelled. *

            - * It is not relevant whether the inner class is anonymous or not, but it is + * It is not relevant whether the inner class is anonymous or not, but it is * easier to use anonymous approach. *

            - *

            Example

            + *

            Example

            *
              * package com.nokia.mj.impl.example;
            - * 
            + *
              * import com.nokia.mj.impl.rt.support.Finalizer;
            - * 
            + *
              * public final class FinalizerExample
              * {
              *     // A reference to Finalizer class. Copy these two lines to your class.
              *     private Finalizer mFinalizer = new Finalizer() {
              *                                    public void finalizeImpl() {doFinalize();}};
            - * 
            + *
              *     // Clears the resources. Copy this method to your class and implement
              *     // the needed cleaning actions into this method
            - *     private void doFinalize() 
            + *     private void doFinalize()
              *     {
              *         //Do the necessary finalizations
              *     }
            @@ -108,7 +108,7 @@
             public abstract class Finalizer
             {
             
            -    /*static 
            +    /*static
                 {
                     // Enable finalization of this class
                     JvmInternal.enableFinalization(Finalizer.class);
            @@ -118,10 +118,10 @@
                  * Called by the JVM when the finalization of the object happens.
                  * When the object is finalized the JVM will call the finalize
                  * method of the com.nokia.mj.impl.rt.support.Finalizer class which leads
            -     * to call of this abstract method. It is guaranteed that this method is 
            +     * to call of this abstract method. It is guaranteed that this method is
                  * called only once.
                  * 

            - * If some exception happens during the execution of + * If some exception happens during the execution of * finalizeImpl the Finalizer class will catch it and print it * to stderr. */ @@ -131,25 +131,25 @@ { debugFinalizeCreated(); } - + /** * Finalization method, which the JVM calls when finalizing the object. */ protected final void finalize() - { - try + { + try { debugFinalize(); finalizeImpl(); } - catch (Throwable t) - { + catch(Throwable t) + { // Print first the exception as such, in case the stack trace will // crash or take large amount of time (e.g. in stack overflow case) System.err.println("Exception caught in finalizer: " + t); - + t.printStackTrace(); - } + } } @@ -160,32 +160,32 @@ private static Hashtable references; // Set up debug finalizers - static + static { String s = System.getProperty("com.nokia.mj.impl.rt.support.FinalizerDump"); - if (s != null) + if(s != null) { // Default = 60 seconds, if value is non-integer int delay = 60; - try + try { delay = Integer.parseInt(s); } - catch (NumberFormatException ex) + catch(NumberFormatException ex) { // Ignore, and use default } System.out.println("Finalizer debug will dump finalize classes every " + delay + " seconds"); - + references = new Hashtable(); new Timer().schedule(new DumpReferred(), 1000 * delay, 1000 * delay); } s = System.getProperty("com.nokia.mj.impl.rt.support.FinalizerTrace"); - if (s != null) + if(s != null) { System.out.println("Finalizer debug will trace each allocation/free"); traceFinalizers = true; @@ -193,7 +193,7 @@ } /** Class to keep count of finalizable objects */ - static private class Refcount + static private class Refcount { /** Total number of objects of the class */ int total; @@ -228,13 +228,13 @@ { sb.append("Finalizable objects\n"); Enumeration e = references.elements(); - while (e.hasMoreElements()) + while(e.hasMoreElements()) { Refcount r = (Refcount)e.nextElement(); - if (r != null) + if(r != null) { sb.append( - " count=" + r.count + + " count=" + r.count + " max=" + r.max + " total=" + r.total + " class=" + r.clazz + @@ -250,28 +250,28 @@ private void debugFinalizeCreated() { - if ((traceFinalizers || references != null) == false) + if((traceFinalizers || references != null) == false) { return; } - + String clazz = this.getClass().getName(); - if (traceFinalizers) + if(traceFinalizers) { System.out.println("Finalizable created: " + clazz); } - if (references != null) + if(references != null) { // Add reference to hash - synchronized (references) + synchronized(references) { Refcount r = (Refcount)references.get(clazz); - if (r != null) + if(r != null) { r.total++; r.count++; - if (r.count > r.max) + if(r.count > r.max) { r.max = r.count; } @@ -288,19 +288,19 @@ * Finalization debug method, which the subclasses override. */ private void debugFinalize() - { - if ((traceFinalizers || references != null) == false) + { + if((traceFinalizers || references != null) == false) { return; } String clazz = this.getClass().getName(); - if (traceFinalizers) + if(traceFinalizers) { System.out.println("Finalizable destroyed " + clazz); } - - if (references != null) + + if(references != null) { // Reduce reference synchronized(references) diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ShutdownListener.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ShutdownListener.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/rt/support/ShutdownListener.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -24,7 +24,7 @@ * @version 1.0 */ -public interface ShutdownListener +public interface ShutdownListener { /** * JAVADOCS ARE UNDER CONSTRUCTION!! diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfo.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfo.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfo.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -26,24 +26,24 @@ public interface RuntimeInfo { /** - * Defined constant for manufacturer domain - */ + * Defined constant for manufacturer domain + */ final String MANUFACTURER_DOMAIN = "MFD"; /** - * Defined constant for identified third party domain - */ + * Defined constant for identified third party domain + */ final String IDENTIFIED_THIRD_PARTY_DOMAIN = "ITPD"; /** - * Defined constant for operator domain - */ + * Defined constant for operator domain + */ final String OPERATOR_DOMAIN = "OPD"; /** - * Defined constant for unidentified third party domain - */ + * Defined constant for unidentified third party domain + */ final String UNIDENTIFIED_THIRD_PARTY_DOMAIN = "UTPD"; - + /** * Gets the UI toolkit register for this runtime environment */ @@ -71,21 +71,21 @@ * @return UID of the caller, or -1 if no UID is associated */ public int getApplicationUid(); - + /** * Returns protection domain of current application as String. - * + * * Currently there are four defined domains - * + * * @see #MANUFACTURER_DOMAIN * @see #IDENTIFIED_THIRD_PARTY_DOMAIN - * @see #OPERATOR_DOMAIN - * @see #UNIDENTIFIED_THIRD_PARTY_DOMAIN - * + * @see #OPERATOR_DOMAIN + * @see #UNIDENTIFIED_THIRD_PARTY_DOMAIN + * * @return protection domain as String */ public String getApplicationDomain(); - + /** * Notifies the runtime that exit command has been received. * It is runtime's responsibility to ensure that the application diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoFactory.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoFactory.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoFactory.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -19,12 +19,12 @@ package com.nokia.mj.impl.runtime.rtport; /** - * Factory to get the RuntimeInfo implementation. + * Factory to get the RuntimeInfo implementation. * * The RuntimeInfo implementation class is searched and dynamically loaded - * based on the value of "nokia.rt.port" system property. + * based on the value of "nokia.rt.port" system property. * - * The class named "com.nokia.mj.impl.runtime.rtport..RuntimeInfoImpl" + * The class named "com.nokia.mj.impl.runtime.rtport..RuntimeInfoImpl" * is tried to be loaded first, and if that is not found the value is tried to * be used as a full class name. * diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoImpl.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/RuntimeInfoImpl.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -24,7 +24,7 @@ public class RuntimeInfoImpl implements RuntimeInfo { - + UiToolkitRegisterImpl tk = new UiToolkitRegisterImpl(); public UiToolkitRegister getUiToolkitRegister() @@ -40,12 +40,12 @@ public int getApplicationUid() { - try + try { String u = ApplicationInfo.getInstance().getUid().getStringValue(); return Integer.parseInt(u.substring(1,u.length()-1), 16); } - catch (Throwable t) + catch(Throwable t) { } System.out.println("RuntimeInfoImpl.getApplicationUid(): USING DEFAULT"); @@ -54,7 +54,7 @@ public String getApplicationDomain() { - /*try + /*try { return ApplicationInfo.getInstance().getProtectionDomain(); } @@ -64,16 +64,16 @@ System.out.println("RuntimeInfoImpl.getApplicationDomain(): USING DEFAULT"); return RuntimeInfo.MANUFACTURER_DOMAIN; } - + public void notifyExitCmd(int aUid) { - try + try { - ApplicationUtils.getInstance().notifyExitCmd(); + ApplicationUtils.getInstance().notifyExitCmd(); } - catch (Throwable t) + catch(Throwable t) { - System.out.println("RuntimeInfoImpl.notifyExitCmd(): Failed"); + System.out.println("RuntimeInfoImpl.notifyExitCmd(): Failed"); } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegister.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegister.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegister.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegisterImpl.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegisterImpl.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/runtime/rtport/UiToolkitRegisterImpl.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -27,7 +27,7 @@ { private String mRegisteredToolkit; private String[] mRegisteredToolkits; - + public void registerUiToolkit(String toolkitId) { if(mRegisteredToolkit != null) @@ -50,9 +50,9 @@ public String[] getRegisteredUiToolkits() { - if (mRegisteredToolkits == null) + if(mRegisteredToolkits == null) { - return new String[0]; + return new String[0]; } return mRegisteredToolkits; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Logger.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Logger.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Logger.java Fri May 14 15:47:24 2010 +0300 @@ -61,7 +61,7 @@ public static final int EJavaContactless = 28; public static final int EJavaConverters = 29; public static final int EMidp2CenrepWrapper = 30; - public static final int EJavawebservices = 31; + public static final int EJavawebservices = 31; // add name of new components here @@ -69,7 +69,8 @@ // list of component's logger enablers // ----------------------------------------------------- - public static final boolean Activated[] = { + public static final boolean Activated[] = + { false, //undefined false, //EJavaCaptain = 1; @@ -142,9 +143,10 @@ * @param level id level of tracing information (EInfo, EInfoHEavyLoad, EError, EWarning) * @param str emiting information */ - public static void LOG(int component, int level, String str) { + public static void LOG(int component, int level, String str) + { - if (Activated[component]) + if(Activated[component]) _logging(component, level, str); } @@ -156,9 +158,11 @@ * @param str emiting information * @param thrown exception object */ - public static void LOG(int component, int level, String str, Throwable thrown) { + public static void LOG(int component, int level, String str, Throwable thrown) + { - if (Activated[component]) { + if(Activated[component]) + { ByteArrayOutputStream byte_stream = new ByteArrayOutputStream(); PrintStream print_stream = new PrintStream(byte_stream); @@ -172,7 +176,8 @@ * @param component a unique id of component * @param str emiting information */ - public static void ELOG(int component, String str) { + public static void ELOG(int component, String str) + { _logging(component, EError, str); } @@ -183,7 +188,8 @@ * @param str emiting information * @param thrown exception object */ - public static void ELOG(int component, String str, Throwable thrown) { + public static void ELOG(int component, String str, Throwable thrown) + { ByteArrayOutputStream byte_stream = new ByteArrayOutputStream(); PrintStream print_stream = new PrintStream(byte_stream); @@ -197,7 +203,8 @@ * @param component a unique id of component * @param str emiting information */ - public static void WLOG(int component, String str) { + public static void WLOG(int component, String str) + { _logging(component, EWarning, str); } @@ -207,7 +214,8 @@ * @param str emiting information * @param thrown exception object */ - public static void WLOG(int component, String str, Throwable thrown) { + public static void WLOG(int component, String str, Throwable thrown) + { ByteArrayOutputStream byte_stream = new ByteArrayOutputStream(); PrintStream print_stream = new PrintStream(byte_stream); @@ -216,12 +224,14 @@ } - private static void _logging(int component, int level, String str) { + private static void _logging(int component, int level, String str) + { System.out.println(str); } private static void _loggingException(int component, int level, String str, Throwable thrown, - ByteArrayOutputStream byte_stream, PrintStream print_stream) { + ByteArrayOutputStream byte_stream, PrintStream print_stream) + { System.out.println(str+" "+thrown.toString()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Uid.java --- a/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Uid.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/com/nokia/mj/impl/utils/Uid.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -23,19 +23,22 @@ *

            * Unique identifier. */ -public class Uid { +public class Uid +{ private String iValue = null; /** * Default constructor. */ - protected Uid() { + protected Uid() + { } /** * Constructor. */ - protected Uid(String aValue) { + protected Uid(String aValue) + { iValue = aValue; } @@ -43,8 +46,10 @@ * Creates a new Uid object from given string. * If given string is not a valid Uid, returns null. */ - public static Uid createUid(String aValue) { - if (aValue == null || aValue.length() == 0) { + public static Uid createUid(String aValue) + { + if(aValue == null || aValue.length() == 0) + { return null; } return new Uid(aValue); @@ -53,26 +58,31 @@ /** * Returns string value for this Uid. */ - public String getStringValue() { + public String getStringValue() + { return iValue; } /** * Returns a hash code value for the object. */ - public int hashCode() { + public int hashCode() + { return iValue.hashCode(); } /** * Indicates whether given object is equal to this one. */ - public boolean equals(Object aObj) { - if (!(aObj instanceof Uid)) { + public boolean equals(Object aObj) + { + if(!(aObj instanceof Uid)) + { return false; } Uid uid = (Uid)aObj; - if (this.getStringValue().equals(uid.getStringValue())) { + if(this.getStringValue().equals(uid.getStringValue())) + { return true; } return false; @@ -84,14 +94,16 @@ * if this instance is less than, equal to, or greater than * the given Uid. */ - public int compareTo(Uid aUid) { + public int compareTo(Uid aUid) + { return toString().compareTo(aUid.toString()); } /** * Returns string representation of this object. */ - public String toString() { + public String toString() + { return getStringValue(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/javax/microedition/lcdui/OpenLcduiLocalization.java --- a/javauis/lcdui_qt/src_j2se/javax/microedition/lcdui/OpenLcduiLocalization.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/javax/microedition/lcdui/OpenLcduiLocalization.java Fri May 14 15:47:24 2010 +0300 @@ -11,108 +11,132 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.lcdui; -final class OpenLcduiLocalization { - - public static String getMessage(String key) { - - if (key == null) throw new IllegalArgumentException( - MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); - - if(key.equals("key_up")){ - return "Navigation key up"; - } - - if(key.equals("key_down")){ - return "Navigation key down"; - } - - if(key.equals("key_left")){ - return "Navigation key left"; - } - - if(key.equals("key_right")){ - return "Navigation key right"; - } - - if(key.equals("key_select")){ - return "Select"; - } - - if(key.equals("key_stop")){ - return "Stop"; - } - - if(key.equals("alert_error")){ - return "Error"; - } - - if(key.equals("alert_warning")){ - return "Warning"; - } - - if(key.equals("alert_info")){ - return "Information"; - } - - if(key.equals("alert_conf")){ - return "OK"; - } - - if(key.equals("alert_alarm")){ - return "Alarm"; - } - - if(key.equals("alert_null")){ - return "Alert"; - } - - if(key.equals("pb_fetch_number")){ - return "Add from Contacts"; - } - - if(key.equals("pb_fetch_number_short")){ - return "Add"; - } - - if(key.equals("pb_fetch_email")){ - return "Add from Contacts"; - } - - if(key.equals("pb_fetch_email_short")){ - return "Add"; - } - - if(key.equals("create_call")){ - return "Call"; - } - - if(key.equals("create_call_short")){ - return "Call"; - } - - if(key.equals("back")){ - return "Back"; - } - - if(key.equals("close")){ - return "Close"; - } - - if(key.equals("empty_list")){ - return "(no data)"; - } - - if(key.equals("help")){ - return "Help"; - } +final class OpenLcduiLocalization +{ + + public static String getMessage(String key) + { + + if(key == null) throw new IllegalArgumentException( + MsgRepository.TEXT_EXCEPTION_TXT_IS_NULL); + + if(key.equals("key_up")) + { + return "Navigation key up"; + } + + if(key.equals("key_down")) + { + return "Navigation key down"; + } + + if(key.equals("key_left")) + { + return "Navigation key left"; + } + + if(key.equals("key_right")) + { + return "Navigation key right"; + } + + if(key.equals("key_select")) + { + return "Select"; + } + + if(key.equals("key_stop")) + { + return "Stop"; + } + + if(key.equals("alert_error")) + { + return "Error"; + } + + if(key.equals("alert_warning")) + { + return "Warning"; + } + + if(key.equals("alert_info")) + { + return "Information"; + } + + if(key.equals("alert_conf")) + { + return "OK"; + } + + if(key.equals("alert_alarm")) + { + return "Alarm"; + } + + if(key.equals("alert_null")) + { + return "Alert"; + } + + if(key.equals("pb_fetch_number")) + { + return "Add from Contacts"; + } + + if(key.equals("pb_fetch_number_short")) + { + return "Add"; + } + + if(key.equals("pb_fetch_email")) + { + return "Add from Contacts"; + } + + if(key.equals("pb_fetch_email_short")) + { + return "Add"; + } + + if(key.equals("create_call")) + { + return "Call"; + } + + if(key.equals("create_call_short")) + { + return "Call"; + } + + if(key.equals("back")) + { + return "Back"; + } + + if(key.equals("close")) + { + return "Close"; + } + + if(key.equals("empty_list")) + { + return "(no data)"; + } + + if(key.equals("help")) + { + return "Help"; + } return key; - } - + } + } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDlet.java --- a/javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDlet.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDlet.java Fri May 14 15:47:24 2010 +0300 @@ -11,14 +11,15 @@ * * Contributors: * -* Description: +* Description: * */ package javax.microedition.midlet; -public abstract class MIDlet { - +public abstract class MIDlet +{ + protected abstract void destroyApp(boolean unconditional) throws MIDletStateChangeException; protected abstract void pauseApp(); protected abstract void startApp() throws MIDletStateChangeException; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDletStateChangeException.java --- a/javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDletStateChangeException.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/src_j2se/javax/microedition/midlet/MIDletStateChangeException.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -19,12 +19,15 @@ import java.lang.Exception; -public class MIDletStateChangeException extends Exception { - public MIDletStateChangeException() { +public class MIDletStateChangeException extends Exception +{ + public MIDletStateChangeException() + { super(); } - - public MIDletStateChangeException(String s) { + + public MIDletStateChangeException(String s) + { super(s); } } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/mj/impl/installer/utils/InstallerMain.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/mj/impl/installer/utils/InstallerMain.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/mj/impl/installer/utils/InstallerMain.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -22,6 +22,7 @@ * Interface with main() method. Any object that is executed * with installer "test" command must implement this interface. */ -public interface InstallerMain { +public interface InstallerMain +{ public void installerMain(String[] aArgs); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/AllTests.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/AllTests.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/AllTests.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt; @@ -33,202 +33,238 @@ * A simple main application for conveniently executing all of the eSWT tests * with text JUnit UI runner. */ -public class AllTests extends TestSuite implements InstallerMain { +public class AllTests extends TestSuite implements InstallerMain +{ - static boolean runningMain = false; - static boolean resultPrinter = true; - static Vector disabledTests = SWTTestCase.getDisabledTests(); + static boolean runningMain = false; + static boolean resultPrinter = true; + static Vector disabledTests = SWTTestCase.getDisabledTests(); + + boolean started; + + boolean enableUIRobotTests = false; - boolean started; - - boolean enableUIRobotTests = false; - - public void installerMain(String[] args) { - if (!started) { - started = true; - - Thread uiThread = new Thread(new Runnable() { - public void run() { - runMainUI(); - }}); - - uiThread.start(); - try { - uiThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); + public void installerMain(String[] args) + { + if(!started) + { + started = true; + + Thread uiThread = new Thread(new Runnable() + { + public void run() + { + runMainUI(); } + }); + + uiThread.start(); + try + { + uiThread.join(); } - } - - public static void runMainUI() { - resultPrinter = false; - java.io.PrintStream stream = null; - final com.nokia.mj.impl.utils.OmjTestRunner runner; - try { - Test suite = suite(); - runner = new com.nokia.mj.impl.utils.OmjTestRunner(suite); - - class eSWTPrinter extends ResultPrinter { - public eSWTPrinter() { - super(System.out); - } - public void startTest(Test test) { - System.out.println(test.toString()); - } - //public void addFailure(Test t, junit.framework.AssertionFailedError e) {} - //public void addError(Test t, Throwable e) {} - public void endTest(Test test) { - runner.endTest(test); - super.endTest(test); - } - public void printDefect(TestFailure testfailure, int i) - { - printDefectHeader(testfailure, i); - super.printDefect(testfailure, i); - } - //protected void printErrors(TestResult result) {} - }; - runner.setPrinter(new eSWTPrinter()); - TestResult result = runner.doRun(suite); - - /* Test results will be written to: - * - fileconn.dir.photos\results (c:\data\images\results) on S60, - * - JAVA_BIN_ROOT/results on Linux - */ - runner.writeResultFile(result); - - } catch (Exception e) { - e.printStackTrace(System.out); - - } finally { - if (stream != null) stream.close(); - } - } - - public static void main(String[] args) { - runningMain = true; - - Thread uiThread = new Thread(new Runnable() { - public void run() { - runMainUI(); - }}); - - uiThread.start(); - try { - uiThread.join(); - } catch (InterruptedException e) { + catch(InterruptedException e) + { e.printStackTrace(); } - - // Exit forcefully when running outside of MIDP environment, this causes - // also OpenLCDUI thread to close. - System.exit(0); + } + } + + public static void runMainUI() + { + resultPrinter = false; + java.io.PrintStream stream = null; + final com.nokia.mj.impl.utils.OmjTestRunner runner; + try + { + Test suite = suite(); + runner = new com.nokia.mj.impl.utils.OmjTestRunner(suite); + + class eSWTPrinter extends ResultPrinter + { + public eSWTPrinter() + { + super(System.out); + } + public void startTest(Test test) + { + System.out.println(test.toString()); + } + //public void addFailure(Test t, junit.framework.AssertionFailedError e) {} + //public void addError(Test t, Throwable e) {} + public void endTest(Test test) + { + runner.endTest(test); + super.endTest(test); + } + public void printDefect(TestFailure testfailure, int i) + { + printDefectHeader(testfailure, i); + super.printDefect(testfailure, i); + } + //protected void printErrors(TestResult result) {} + }; + runner.setPrinter(new eSWTPrinter()); + TestResult result = runner.doRun(suite); + + /* Test results will be written to: + * - fileconn.dir.photos\results (c:\data\images\results) on S60, + * - JAVA_BIN_ROOT/results on Linux + */ + runner.writeResultFile(result); + } - - public static junit.framework.Test suite() { - return new AllTests(); + catch(Exception e) + { + e.printStackTrace(System.out); + + } + finally + { + if(stream != null) stream.close(); } - - public void init() { - + } + + public static void main(String[] args) + { + runningMain = true; + + Thread uiThread = new Thread(new Runnable() + { + public void run() + { + runMainUI(); + } + }); + + uiThread.start(); + try + { + uiThread.join(); } - - public AllTests() { - init(); + catch(InterruptedException e) + { + e.printStackTrace(); + } + + // Exit forcefully when running outside of MIDP environment, this causes + // also OpenLCDUI thread to close. + System.exit(0); + } + + public static junit.framework.Test suite() + { + return new AllTests(); + } + + public void init() + { + + } + + public AllTests() + { + init(); - addTest(com.nokia.openlcdui.mt.alert.AlertTest.suite()); - addTest(com.nokia.openlcdui.mt.canvas.CanvasTest.suite()); - addTest(com.nokia.openlcdui.mt.choicegroup.ChoiceGroupTest.suite()); - addTest(com.nokia.openlcdui.mt.command.CommandTest.suite()); - addTest(com.nokia.openlcdui.mt.command.ItemCommandTest.suite()); - addTest(com.nokia.openlcdui.mt.datefield.DateFieldTest.suite()); - addTest(com.nokia.openlcdui.mt.display.DisplayTest.suite()); - addTest(com.nokia.openlcdui.mt.displayable.DisplayableTest.suite()); - addTest(com.nokia.openlcdui.mt.font.FontTest.suite()); - addTest(com.nokia.openlcdui.mt.form.FormTest.suite()); - addTest(com.nokia.openlcdui.mt.fullcanvas.FullCanvasTest.suite()); - addTest(com.nokia.openlcdui.mt.game.CollisionDetectionTest.suite()); - addTest(com.nokia.openlcdui.mt.game.GameCanvasTest.suite()); - addTest(com.nokia.openlcdui.mt.game.LayerManagerTest.suite()); - addTest(com.nokia.openlcdui.mt.game.LayerTest.suite()); - addTest(com.nokia.openlcdui.mt.game.SpriteTest.suite()); - addTest(com.nokia.openlcdui.mt.game.TiledLayerTest.suite()); - addTest(com.nokia.openlcdui.mt.gauge.GaugeTest.suite()); - addTest(com.nokia.openlcdui.mt.graphics.DirectGraphicsTest.suite()); - addTest(com.nokia.openlcdui.mt.graphics.GraphicsTest.suite()); - addTest(com.nokia.openlcdui.mt.image.ImageTest.suite()); - addTest(com.nokia.openlcdui.mt.imageitem.ImageItemTest.suite()); - addTest(com.nokia.openlcdui.mt.item.ItemTest.suite()); - addTest(com.nokia.openlcdui.mt.list.ListTest.suite()); - addTest(com.nokia.openlcdui.mt.spacer.SpacerTest.suite()); - addTest(com.nokia.openlcdui.mt.stringitem.StringItemTest.suite()); - addTest(com.nokia.openlcdui.mt.textbox.TextBoxTest.suite()); - addTest(com.nokia.openlcdui.mt.textfield.TextFieldTest.suite()); - addTest(com.nokia.openlcdui.mt.ticker.TickerTest.suite()); - addTest(com.nokia.openlcdui.mt.devicecontrol.DeviceControlTest.suite()); - if (enableUIRobotTests) { - addTest(com.nokia.openlcdui.mt_uirobot.alert.AlertUITest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.choicegroup.ChoiceGroupCommandTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.choicegroup.ChoiceGroupPopupTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.command.DynamicUpdateTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.command.ItemCommandUIRobotTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.customitem.CustomItemTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.datefield.DateFieldUIRobotTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.display.FlashAndVibrateTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.display.SetCurrentItemTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.displayable.AddCommandTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.displayable.SendBackgroundTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.displayable.SizeChangedTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.form.FormItemTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.gauge.GaugeCommandsTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.imageitem.ImageItemHyperLinkTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.item.ItemUITest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.list.ListUITest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.spacer.SpacerTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.stringitem.HyperLinkTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.stringitem.StringItemUIRobotTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.textbox.TestUITextBox.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.textbox.TextBoxInputModeUITest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.textfield.FormChangeFocusCheckTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.textfield.TextFieldCommandTest.suite()); - addTest(com.nokia.openlcdui.mt_uirobot.textfield.TextFieldSetInitialInputModeTest.suite()); - } - + addTest(com.nokia.openlcdui.mt.alert.AlertTest.suite()); + addTest(com.nokia.openlcdui.mt.canvas.CanvasTest.suite()); + addTest(com.nokia.openlcdui.mt.choicegroup.ChoiceGroupTest.suite()); + addTest(com.nokia.openlcdui.mt.command.CommandTest.suite()); + addTest(com.nokia.openlcdui.mt.command.ItemCommandTest.suite()); + addTest(com.nokia.openlcdui.mt.datefield.DateFieldTest.suite()); + addTest(com.nokia.openlcdui.mt.display.DisplayTest.suite()); + addTest(com.nokia.openlcdui.mt.displayable.DisplayableTest.suite()); + addTest(com.nokia.openlcdui.mt.font.FontTest.suite()); + addTest(com.nokia.openlcdui.mt.form.FormTest.suite()); + addTest(com.nokia.openlcdui.mt.fullcanvas.FullCanvasTest.suite()); + addTest(com.nokia.openlcdui.mt.game.CollisionDetectionTest.suite()); + addTest(com.nokia.openlcdui.mt.game.GameCanvasTest.suite()); + addTest(com.nokia.openlcdui.mt.game.LayerManagerTest.suite()); + addTest(com.nokia.openlcdui.mt.game.LayerTest.suite()); + addTest(com.nokia.openlcdui.mt.game.SpriteTest.suite()); + addTest(com.nokia.openlcdui.mt.game.TiledLayerTest.suite()); + addTest(com.nokia.openlcdui.mt.gauge.GaugeTest.suite()); + addTest(com.nokia.openlcdui.mt.graphics.DirectGraphicsTest.suite()); + addTest(com.nokia.openlcdui.mt.graphics.GraphicsTest.suite()); + addTest(com.nokia.openlcdui.mt.image.ImageTest.suite()); + addTest(com.nokia.openlcdui.mt.imageitem.ImageItemTest.suite()); + addTest(com.nokia.openlcdui.mt.item.ItemTest.suite()); + addTest(com.nokia.openlcdui.mt.list.ListTest.suite()); + addTest(com.nokia.openlcdui.mt.spacer.SpacerTest.suite()); + addTest(com.nokia.openlcdui.mt.stringitem.StringItemTest.suite()); + addTest(com.nokia.openlcdui.mt.textbox.TextBoxTest.suite()); + addTest(com.nokia.openlcdui.mt.textfield.TextFieldTest.suite()); + addTest(com.nokia.openlcdui.mt.ticker.TickerTest.suite()); + addTest(com.nokia.openlcdui.mt.devicecontrol.DeviceControlTest.suite()); + if(enableUIRobotTests) + { + addTest(com.nokia.openlcdui.mt_uirobot.alert.AlertUITest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.choicegroup.ChoiceGroupCommandTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.choicegroup.ChoiceGroupPopupTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.command.DynamicUpdateTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.command.ItemCommandUIRobotTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.customitem.CustomItemTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.datefield.DateFieldUIRobotTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.display.FlashAndVibrateTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.display.SetCurrentItemTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.displayable.AddCommandTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.displayable.SendBackgroundTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.displayable.SizeChangedTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.form.FormItemTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.gauge.GaugeCommandsTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.imageitem.ImageItemHyperLinkTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.item.ItemUITest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.list.ListUITest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.spacer.SpacerTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.stringitem.HyperLinkTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.stringitem.StringItemUIRobotTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.textbox.TestUITextBox.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.textbox.TextBoxInputModeUITest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.textfield.FormChangeFocusCheckTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.textfield.TextFieldCommandTest.suite()); + addTest(com.nokia.openlcdui.mt_uirobot.textfield.TextFieldSetInitialInputModeTest.suite()); + } - // If tests are executed by some runner as a suite then it won't clean up the UI - // before it let's the thread to terminate. This is executed as the last test - // to clean up in the UI thread before it exits. - /*if(!runningMain) { - addTest(new TestCase() { - protected void runTest() throws Throwable { - Display display = Display.getCurrent(); - if(display != null) display.dispose(); - } - public String getName() { - return "CleanUpQtBeforeGUIThreadExits"; + + // If tests are executed by some runner as a suite then it won't clean up the UI + // before it let's the thread to terminate. This is executed as the last test + // to clean up in the UI thread before it exits. + /*if(!runningMain) { + addTest(new TestCase() { + protected void runTest() throws Throwable { + Display display = Display.getCurrent(); + if(display != null) display.dispose(); + } + public String getName() { + return "CleanUpQtBeforeGUIThreadExits"; + } + }); + }*/ + // If some tests were disabled then generate a warning about them. + if(disabledTests != null) + { + addTest(new TestCase() + { + protected void runTest() throws Throwable + { + if(!disabledTests.isEmpty()) + { + String list = new String(); + list += "Warning: There are " + disabledTests.size() + " disabled tests that were marked as passing: \r\n"; + for(int i = 0; i < disabledTests.size(); ++i) + { + list += disabledTests.elementAt(i); + list += "\r\n"; + } + throw new Exception(list); } - }); - }*/ - // If some tests were disabled then generate a warning about them. - if(disabledTests != null) { - addTest(new TestCase() { - protected void runTest() throws Throwable { - if(!disabledTests.isEmpty()) { - String list = new String(); - list += "Warning: There are " + disabledTests.size() + " disabled tests that were marked as passing: \r\n"; - for(int i = 0; i < disabledTests.size(); ++i) { - list += disabledTests.elementAt(i); - list += "\r\n"; - } - throw new Exception(list); - } - } - public String getName() { - return "DisabledTestsCheck"; - } - }); - } - } + } + public String getName() + { + return "DisabledTestsCheck"; + } + }); + } + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/SWTTestCase.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/SWTTestCase.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/SWTTestCase.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt; @@ -35,7 +35,8 @@ import org.eclipse.swt.widgets.Display; -public class SWTTestCase extends TestCase { +public class SWTTestCase extends TestCase +{ public static final Point POINTER_LSK = new Point(10, 470); public static final Point POINTER_MSK = new Point(160, 470); @@ -48,33 +49,39 @@ public static final Point POINTER_MENU_ITEM_5 = new Point(160, 240); public static final Point POINTER_MESSAGE_BOX = new Point(160, 375); - public class TestDisabledException extends RuntimeException { - private static final long serialVersionUID = 3005532374213580596L; - } - + public class TestDisabledException extends RuntimeException + { + private static final long serialVersionUID = 3005532374213580596L; + } + static Vector disabledTests = new Vector(); private UITestUtils uiTestUtils; - - private class TestMIDlet extends MIDlet { + + private class TestMIDlet extends MIDlet + { - protected void destroyApp(boolean arg0) throws MIDletStateChangeException { - } + protected void destroyApp(boolean arg0) throws MIDletStateChangeException + { + } - protected void pauseApp() { - } + protected void pauseApp() + { + } - protected void startApp() throws MIDletStateChangeException { - }}; - - private static TestMIDlet midlet; + protected void startApp() throws MIDletStateChangeException + { + }}; - /** + private static TestMIDlet midlet; + + /** * Constructor. */ - public SWTTestCase() { - super(); - uiTestUtils = new UITestUtils(); - if (midlet == null) midlet = new TestMIDlet(); + public SWTTestCase() + { + super(); + uiTestUtils = new UITestUtils(); + if(midlet == null) midlet = new TestMIDlet(); } /** @@ -83,10 +90,11 @@ * @param name * @param method */ - public SWTTestCase(String name) { + public SWTTestCase(String name) + { super(name); uiTestUtils = new UITestUtils(); - if (midlet == null) midlet = new TestMIDlet(); + if(midlet == null) midlet = new TestMIDlet(); } /** @@ -96,10 +104,11 @@ * * @return A vector of test case names of disabled tests */ - static public Vector getDisabledTests() { + static public Vector getDisabledTests() + { return disabledTests; } - + /** * Call this in the beginning of a test case to temporarily disable it. I.e. * test will be skipped and it will show as passed. There will be a warning @@ -107,10 +116,11 @@ * to temporarily hide the known issues so that it's easier to spot the real * failures that are not being worked on yet. */ - protected void DISABLE_TEST() { + protected void DISABLE_TEST() + { throw new TestDisabledException(); } - + /** * Block execution for the given time without blocking the UI Thread. This * method should be used instead of the Thread.sleep, which will block the @@ -118,11 +128,14 @@ * * @param miliseconds */ - protected void block(int milliseconds) { - try { + protected void block(int milliseconds) + { + try + { Thread.sleep(milliseconds); } - catch (InterruptedException e) { + catch(InterruptedException e) + { e.printStackTrace(); } } @@ -130,15 +143,19 @@ /** * Convenience method for dispatching all events for the current UI thread. */ - protected void flush() { + protected void flush() + { Display display = Display.getCurrent(); - if (display != null) { - while (display.readAndDispatch()) { + if(display != null) + { + while(display.readAndDispatch()) + { } } } - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { super.tearDown(); flush(); @@ -160,15 +177,17 @@ /** * System out print. */ - public void log(String aLogString) { + public void log(String aLogString) + { System.out.println(aLogString); } /** * MIDlet instance. */ - public MIDlet getMIDlet() { - return midlet; + public MIDlet getMIDlet() + { + return midlet; } /** @@ -181,7 +200,8 @@ /** * Emulate key event. */ - public void key(int aKeyCode) { + public void key(int aKeyCode) + { //spede().triggerKeyPressEvent(new Key(aKeyCode)); block(500); } @@ -189,9 +209,11 @@ /** * Emulate key event with delay after. */ - public void key(int aKeyCode, int aTimeout) { + public void key(int aKeyCode, int aTimeout) + { //spede().triggerKeyPressEvent(new Key(aKeyCode)); - if (aTimeout > 0) { + if(aTimeout > 0) + { block(aTimeout); } } @@ -199,23 +221,26 @@ /** * Takes a reference screenshot and writes results to a file. */ - public boolean takeScreenshot(String screenShotName) { - //return spede().takeScreenshot(screenShotName); - return false; + public boolean takeScreenshot(String screenShotName) + { + //return spede().takeScreenshot(screenShotName); + return false; } /** * Add comment to test results log. */ - public void print(String s) { + public void print(String s) + { uiTestUtils.log(s); } /** * Add exception to test results log. */ - public void print(Throwable t) { - uiTestUtils.log(t.toString()); + public void print(Throwable t) + { + uiTestUtils.log(t.toString()); } /** @@ -223,7 +248,8 @@ * cases to take screenshots so that waiting for the screen to paint can be * handled efficiently. */ - public boolean screen(String title) { + public boolean screen(String title) + { return screen(title, new Rectangle(0, 0, 0, 0)); } @@ -234,7 +260,8 @@ * corresponding area in reference image. If given rectangle area is empty, * the whole screen is compared. */ - public boolean screen(String title, Rectangle compareArea) { + public boolean screen(String title, Rectangle compareArea) + { final int DEFAULT_MAXWAITTIME = 1000; return screen(title, DEFAULT_MAXWAITTIME, compareArea); } @@ -244,7 +271,8 @@ * time to stabilise, for example in a complex layout test case, then this * method should be used and a longer wait time given. */ - public boolean screen(String title, int maxWaitTime) { + public boolean screen(String title, int maxWaitTime) + { return screen(title, maxWaitTime, new Rectangle(0, 0, 0, 0)); } @@ -255,7 +283,8 @@ * area of screenshot to corresponding area in reference image. If given * rectangle area is empty, the whole screen is compared. */ - public boolean screen(String title, int maxWaitTime, Rectangle compareArea) { + public boolean screen(String title, int maxWaitTime, Rectangle compareArea) + { final int WAIT_INITIAL = 100; final int WAIT_RETRY = 100; @@ -264,13 +293,15 @@ boolean screenMatchesReferenceImage = false; boolean finalAttempt = false; - while (waitSum < maxWaitTime && !screenMatchesReferenceImage) { - if (!(waitSum + WAIT_RETRY < maxWaitTime)) + while(waitSum < maxWaitTime && !screenMatchesReferenceImage) + { + if(!(waitSum + WAIT_RETRY < maxWaitTime)) finalAttempt = true; screenMatchesReferenceImage = doTakeScreenShot(title, finalAttempt, - compareArea); + compareArea); - if (!screenMatchesReferenceImage) { + if(!screenMatchesReferenceImage) + { block(WAIT_RETRY); waitSum += WAIT_RETRY; } @@ -288,7 +319,8 @@ * If false then results will be written only after successful * comparison to the reference image. */ - protected boolean doTakeScreenShot(String title, boolean finalAttempt) { + protected boolean doTakeScreenShot(String title, boolean finalAttempt) + { return doTakeScreenShot(title, finalAttempt, new Rectangle(0, 0, 0, 0)); } @@ -304,9 +336,11 @@ * comparison to the reference image. */ protected boolean doTakeScreenShot(String title, boolean finalAttempt, - Rectangle compareArea) { + Rectangle compareArea) + { String actualTitle = getName(); - if (title != "") { + if(title != "") + { actualTitle += "_" + title; } //return spede().takeScreenshot(actualTitle, finalAttempt, compareArea); @@ -316,28 +350,32 @@ /** * Take screenshot. */ - public boolean screen() { + public boolean screen() + { return screen(""); } /** * Take screenshot. */ - public boolean screen(int maxWaitTime) { + public boolean screen(int maxWaitTime) + { return screen("", maxWaitTime); } /** * Take screenshot. */ - public boolean screen(Rectangle compareArea) { + public boolean screen(Rectangle compareArea) + { return screen("", compareArea); } /** * Take screenshot. */ - public void screenAssert() { + public void screenAssert() + { boolean res = true; res = screen(); assertTrue("Screenshot mismatch", res); @@ -346,7 +384,8 @@ /** * Take screenshot. */ - public void screenAssert(String title) { + public void screenAssert(String title) + { boolean res = true; res = screen(title); assertTrue("Screenshot " + title + " mismatch", res); @@ -356,7 +395,8 @@ /** * Emulate pointer event. */ - public void pointerTap(int x, int y) { + public void pointerTap(int x, int y) + { uiTestUtils.triggerPointerDownEvent(x, y); uiTestUtils.triggerPointerUpEvent(x, y); } @@ -364,7 +404,8 @@ /** * Emulate pointer event. */ - public void pointerLongTap(int x, int y) { + public void pointerLongTap(int x, int y) + { //spede().longTap(x, y); //block(500); } @@ -372,21 +413,24 @@ /** * Emulate pointer event. */ - public void pointerDown(int x, int y) { + public void pointerDown(int x, int y) + { uiTestUtils.triggerPointerDownEvent(x, y); } /** * Emulate pointer event. */ - public void pointerUp(int x, int y) { + public void pointerUp(int x, int y) + { uiTestUtils.triggerPointerUpEvent(x, y); } /** * Emulate pointer event. */ - public void pointerDrag(int x1, int y1, int x2, int y2) { + public void pointerDrag(int x1, int y1, int x2, int y2) + { //spede().pointerDrag(x1, y1, x2, y2); //block(500); //uiTestUtils.triggerPointerDragEvent(arg0, arg1) @@ -395,79 +439,87 @@ /** * Emulate pointer event. */ - public void pointerTap(Point p) { + public void pointerTap(Point p) + { pointerTap(p.x, p.y); } /** * Emulate pointer event. */ - public void pointerLongTap(Point p) { + public void pointerLongTap(Point p) + { pointerLongTap(p.x, p.y); } /** * Emulate pointer event. */ - public void pointerDown(Point p) { + public void pointerDown(Point p) + { pointerDown(p.x, p.y); } /** * Emulate pointer event. */ - public void pointerUp(Point p) { + public void pointerUp(Point p) + { pointerUp(p.x, p.y); } /** * Emulate pointer event. */ - public void pointerDrag(Point p1, Point p2) { + public void pointerDrag(Point p1, Point p2) + { pointerDrag(p1.x, p1.y, p2.x, p2.y); } /** * Control tapping target. */ - public Point pointerTarget(Control aCtrl, int aType) { + public Point pointerTarget(Control aCtrl, int aType) + { assertTrue(aCtrl.getSize().x > 0 && aCtrl.getSize().y > 0); Point res = new Point(0, 0); Rectangle rect = aCtrl.getBounds(); - switch (aType) { - case SWT.CENTER: - res = new Point(rect.x + rect.width / 2, rect.y + rect.height - / 2); - break; - case SWT.TOP: - res = new Point(rect.x + rect.width / 2, rect.y); - break; - case SWT.BOTTOM: - res = new Point(rect.x + rect.width / 2, rect.y + rect.height); - break; - case SWT.LEFT: - res = new Point(rect.x, rect.y + rect.height / 2); - break; - case SWT.RIGHT: - res = new Point(rect.x + rect.width, rect.y + rect.height / 2); - break; - case SWT.TOP | SWT.LEFT: - res = new Point(rect.x, rect.y); - break; - case SWT.TOP | SWT.RIGHT: - res = new Point(rect.x + rect.width, rect.y); - break; - case SWT.BOTTOM | SWT.LEFT: - res = new Point(rect.x, rect.y + rect.height); - break; - case SWT.BOTTOM | SWT.RIGHT: - res = new Point(rect.x + rect.width, rect.y + rect.height); - break; - default: - assertTrue("No such pointer target type", false); - break; + switch(aType) + { + case SWT.CENTER: + res = new Point(rect.x + rect.width / 2, rect.y + rect.height + / 2); + break; + case SWT.TOP: + res = new Point(rect.x + rect.width / 2, rect.y); + break; + case SWT.BOTTOM: + res = new Point(rect.x + rect.width / 2, rect.y + rect.height); + break; + case SWT.LEFT: + res = new Point(rect.x, rect.y + rect.height / 2); + break; + case SWT.RIGHT: + res = new Point(rect.x + rect.width, rect.y + rect.height / 2); + break; + case SWT.TOP | SWT.LEFT: + res = new Point(rect.x, rect.y); + break; + case SWT.TOP | SWT.RIGHT: + res = new Point(rect.x + rect.width, rect.y); + break; + case SWT.BOTTOM | SWT.LEFT: + res = new Point(rect.x, rect.y + rect.height); + break; + case SWT.BOTTOM | SWT.RIGHT: + res = new Point(rect.x + rect.width, rect.y + rect.height); + break; + default: + assertTrue("No such pointer target type", false); + break; } - if (aCtrl.getParent() != null) { + if(aCtrl.getParent() != null) + { res = aCtrl.getParent().toDisplay(res); } return res; @@ -476,32 +528,41 @@ /** * Control tapping target. */ - public Point pointerTarget(Control aCtrl) { + public Point pointerTarget(Control aCtrl) + { return pointerTarget(aCtrl, SWT.CENTER); } - public boolean isTouchEnabled() { + public boolean isTouchEnabled() + { //return spede().isTouchEnabled(); - return true; + return true; } - public void runBare() throws Throwable { + public void runBare() throws Throwable + { long startMillis = 0; - try { + try + { startMillis = System.currentTimeMillis(); setUp(); runTest(); - } catch (TestDisabledException e) { - if(disabledTests == null) throw new Exception("Test " + getName() + " is disabled"); + } + catch(TestDisabledException e) + { + if(disabledTests == null) throw new Exception("Test " + getName() + " is disabled"); disabledTests.addElement(getName() + " (" + getClass().getName() + ")"); - } finally { + } + finally + { tearDown(); - if (startMillis > 0) { - long totalTime = System.currentTimeMillis() - startMillis; - print("Total test case execution time: " - + (Float.valueOf(Long.toString(totalTime)).floatValue() / 1000) - + " s"); - } + if(startMillis > 0) + { + long totalTime = System.currentTimeMillis() - startMillis; + print("Total test case execution time: " + + (Float.valueOf(Long.toString(totalTime)).floatValue() / 1000) + + " s"); + } // Requests disposing all resources javax.microedition.lcdui.Display.getDisplay(getMIDlet()).setCurrent(null); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/alert/AlertTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/alert/AlertTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/alert/AlertTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.alert; @@ -30,29 +30,30 @@ *

          • Collection of tests to test Alert's API functionality.
            *
            */ -public class AlertTest extends SWTTestCase { +public class AlertTest extends SWTTestCase +{ private static String shortString = "Lorem ipsum"; private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue." - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue." - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue." + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue." + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; private static final int INVALID_ALERT_TIMEOUT = -3000; @@ -62,7 +63,8 @@ /** * Constructor. */ - public AlertTest() { + public AlertTest() + { } /** @@ -71,7 +73,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public AlertTest(String sTestName) { + public AlertTest(String sTestName) + { super(sTestName); } @@ -81,23 +84,26 @@ * * @return New testsuite. */ - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = AlertTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new AlertTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = AlertTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new AlertTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testSetGetTimeout"); @@ -108,40 +114,48 @@ methodNames.addElement("testCommands"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testSetGetTimeout")) testSetGetTimeout(); - else if (getName().equals("testSetGetType")) testSetGetType(); - else if (getName().equals("testSetGetImage")) testSetGetImage(); - else if (getName().equals("testSetGetTexts")) testSetGetTexts(); - else if (getName().equals("testSetGetIndicators")) testSetGetIndicators(); - else if (getName().equals("testCommands")) testCommands(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testSetGetTimeout")) testSetGetTimeout(); + else if(getName().equals("testSetGetType")) testSetGetType(); + else if(getName().equals("testSetGetImage")) testSetGetImage(); + else if(getName().equals("testSetGetTexts")) testSetGetTexts(); + else if(getName().equals("testSetGetIndicators")) testSetGetIndicators(); + else if(getName().equals("testCommands")) testCommands(); else super.runTest(); - } - + } + /** * Tests the constructors. */ - public void testConstructors() { - try { + public void testConstructors() + { + try + { new Alert(null); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - Constructor with null title - " + e.getMessage()); } - try { + try + { new Alert(shortString); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - Constructor with short text - " + e.getMessage()); } - try { + try + { new Alert(shortString, longString, null, null); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - Constructor with long text - " + e.getMessage()); } } @@ -149,18 +163,21 @@ /** * Tests setter and getter t. */ - public void testSetGetTimeout() { + public void testSetGetTimeout() + { Alert alert = new Alert(shortString); alert.setTimeout(VALID_ALERT_TIMEOUT); assertEquals("Timeouts don't match.", VALID_ALERT_TIMEOUT, alert - .getTimeout()); + .getTimeout()); alert.setTimeout(Alert.FOREVER); assertEquals("Timeouts don't match.", Alert.FOREVER, alert.getTimeout()); - try { + try + { alert.setTimeout(INVALID_ALERT_TIMEOUT); fail("IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } } @@ -168,7 +185,8 @@ /** * Tests set and get type. */ - public void testSetGetType() { + public void testSetGetType() + { Alert alert = new Alert(shortString); alert.setType(AlertType.ALARM); @@ -176,7 +194,7 @@ alert.setType(AlertType.CONFIRMATION); assertEquals("Types don't match.", AlertType.CONFIRMATION, alert - .getType()); + .getType()); alert.setType(AlertType.ERROR); assertEquals("Types don't match.", AlertType.ERROR, alert.getType()); @@ -191,8 +209,10 @@ /** * Tests set and get image. */ - public void testSetGetImage() { - try { + public void testSetGetImage() + { + try + { Alert alert = new Alert(shortString); alert.setImage(null); assertEquals("Images don't match.", null, alert.getImage()); @@ -201,7 +221,8 @@ alert.setImage(param); assertEquals("Images don't match.", param, alert.getImage()); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } } @@ -209,7 +230,8 @@ /** * Tests set and get texts. */ - public void testSetGetTexts() { + public void testSetGetTexts() + { Alert alert = new Alert(shortString); alert.setString(null); assertEquals("String don't match.", null, alert.getString()); @@ -217,76 +239,93 @@ alert.setString(shortString); assertEquals("Strings dont match.", shortString, alert.getString()); assertTrue("Alert with short text is modal", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setString(longString); assertEquals("Strings dont match", longString, alert.getString()); assertTrue("Alert with long text is not modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); } /** * Tests set and get indicator methods and Gauge-Alert interaction related * Item methods. */ - public void testSetGetIndicators() { + public void testSetGetIndicators() + { Alert alert = new Alert(shortString); Gauge param1 = new Gauge(null, false, 10, 0); alert.setIndicator(param1); assertEquals("Indicators don't match.", param1, alert.getIndicator()); - try { + try + { Gauge param2 = new Gauge("Label", true, 10, 0); alert.setIndicator(param2); fail("1. IllegalArgumentException expected"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { } - try { + try + { param1.addCommand(new Command("Comm1", Command.ITEM, 0)); fail("2. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } - try { + try + { param1.setDefaultCommand(new Command("Comm1", Command.ITEM, 0)); fail("3. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } - try { - ItemCommandListener icl = new ItemCommandListener() { - public void commandAction(Command command, Item item) { + try + { + ItemCommandListener icl = new ItemCommandListener() + { + public void commandAction(Command command, Item item) + { } }; param1.setItemCommandListener(icl); fail("4. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } - try { + try + { param1.setLabel("Label"); fail("5. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } - try { + try + { param1.setLayout(Item.LAYOUT_BOTTOM); fail("6. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } - try { + try + { param1.setPreferredSize(10, 10); fail("7. IllegalStateException expected"); } - catch (IllegalStateException ise) { + catch(IllegalStateException ise) + { } alert.setIndicator(null); @@ -295,42 +334,51 @@ /** * Tests commands on Alert. */ - public void testCommands() { - try { + public void testCommands() + { + try + { Alert alert = new Alert(shortString); - CommandListener param = new CommandListener() { - public void commandAction(Command c, Displayable d) { + CommandListener param = new CommandListener() + { + public void commandAction(Command c, Displayable d) + { } }; alert.setCommandListener(param); alert.setCommandListener(null); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - Setting and removing CommandListener - " - + e.getMessage()); + + e.getMessage()); } - try { + try + { Alert alert = new Alert(shortString); // adding null command alert.addCommand(null); fail("NullPointerException expected - NULL command added to Alert"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Wrong exception is thrown instead of NullPointerException - " - + "NULL command added to Alert" + e.getMessage()); + + "NULL command added to Alert" + e.getMessage()); } - try { + try + { Alert alert = new Alert(shortString); // test default command alert.addCommand(Alert.DISMISS_COMMAND); assertTrue("Default Alert shouldn't be modal", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.removeCommand(Alert.DISMISS_COMMAND); Command c1 = new Command("Comm1", Command.ITEM, 0); @@ -342,30 +390,31 @@ // add commands alert.addCommand(c1); assertTrue("Default Alert with 1 command shouldn't be modal", alert - .getTimeout() != Alert.FOREVER); + .getTimeout() != Alert.FOREVER); alert.addCommand(c2); assertTrue("Default Alert with 2 commands should be modal", alert - .getTimeout() == Alert.FOREVER); + .getTimeout() == Alert.FOREVER); alert.addCommand(c3); alert.addCommand(c4); alert.addCommand(c5); assertTrue("Default Alert with 5 commands should be modal", alert - .getTimeout() == Alert.FOREVER); + .getTimeout() == Alert.FOREVER); // remove commands alert.removeCommand(c5); alert.removeCommand(c4); alert.removeCommand(c3); assertTrue("Default Alert with 2 commands should be modal", alert - .getTimeout() == Alert.FOREVER); + .getTimeout() == Alert.FOREVER); alert.removeCommand(c2); assertTrue("Default Alert with 1 command shouldn't be modal", alert - .getTimeout() != Alert.FOREVER); + .getTimeout() != Alert.FOREVER); alert.removeCommand(c1); assertTrue("Default Alert shouldn't be modal", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - Adding 5 commands - " + e.getMessage()); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/canvas/CanvasTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/canvas/CanvasTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/canvas/CanvasTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.canvas; @@ -25,11 +25,13 @@ /** * CanvasTest. */ -public class CanvasTest extends SWTTestCase { +public class CanvasTest extends SWTTestCase +{ private TestCanvas testCanvas; - final int[][] refKeyToGameTable = { + final int[][] refKeyToGameTable = + { {50, Canvas.UP}, {-1, Canvas.UP}, {56, Canvas.DOWN}, @@ -47,7 +49,8 @@ {35, Canvas.GAME_D}, }; - final int[][] refGameToKeyTable = { + final int[][] refGameToKeyTable = + { {-1, Canvas.UP}, {-2, Canvas.DOWN}, {-3, Canvas.LEFT}, @@ -62,7 +65,8 @@ /** * Constructor. */ - public CanvasTest() { + public CanvasTest() + { } /** @@ -71,14 +75,16 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public CanvasTest(String sTestName) { + public CanvasTest(String sTestName) + { super(sTestName); } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); System.out.println("CanvasTest setup enter"); testCanvas = new TestCanvas(); @@ -89,7 +95,8 @@ /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { super.tearDown(); System.out.println("CanvasTest teadDown"); testCanvas = null; @@ -101,23 +108,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = CanvasTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new CanvasTest((String)e.nextElement())); - } + // Add widget tests + methodNames = CanvasTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new CanvasTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCreateCanvas"); methodNames.addElement("testIsDoubleBuffered"); @@ -132,149 +142,177 @@ methodNames.addElement("testGraphicsProperties"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testCreateCanvas")) testCreateCanvas(); - else if (getName().equals("testIsDoubleBuffered")) testIsDoubleBuffered(); - else if (getName().equals("testHasPointerEvents")) testHasPointerEvents(); - else if (getName().equals("testHasPointerMotionEvents")) testHasPointerMotionEvents(); - else if (getName().equals("testHasRepeatEvents")) testHasRepeatEvents(); - else if (getName().equals("testSetFullScreenMode")) testSetFullScreenMode(); - else if (getName().equals("testGetGameAction")) testGetGameAction(); - else if (getName().equals("testGetKeyCode")) testGetKeyCode(); - else if (getName().equals("testGetKeyName")) testGetKeyName(); - else if (getName().equals("testServiceRepaints")) testServiceRepaints(); - else if (getName().equals("testGraphicsProperties")) testGraphicsProperties(); + + protected void runTest() throws Throwable + { + if(getName().equals("testCreateCanvas")) testCreateCanvas(); + else if(getName().equals("testIsDoubleBuffered")) testIsDoubleBuffered(); + else if(getName().equals("testHasPointerEvents")) testHasPointerEvents(); + else if(getName().equals("testHasPointerMotionEvents")) testHasPointerMotionEvents(); + else if(getName().equals("testHasRepeatEvents")) testHasRepeatEvents(); + else if(getName().equals("testSetFullScreenMode")) testSetFullScreenMode(); + else if(getName().equals("testGetGameAction")) testGetGameAction(); + else if(getName().equals("testGetKeyCode")) testGetKeyCode(); + else if(getName().equals("testGetKeyName")) testGetKeyName(); + else if(getName().equals("testServiceRepaints")) testServiceRepaints(); + else if(getName().equals("testGraphicsProperties")) testGraphicsProperties(); else super.runTest(); } - - public void testCreateCanvas() { + + public void testCreateCanvas() + { Canvas canv = new TestCanvas(); canv.isDoubleBuffered(); } - public void testShowNotify() { + public void testShowNotify() + { fail("Canvas.showNotify is not supported due to not implemented ShellListener.shellActivated"); } - public void testHideNotify() { + public void testHideNotify() + { fail("Canvas.hideNotify is not supported due to not implemented ShellListener.shellDeactivated"); } - public void testIsDoubleBuffered() { + public void testIsDoubleBuffered() + { assertTrue("Canvas.isDoubleBuffered returned false", testCanvas.isDoubleBuffered()); } - public void testHasPointerEvents() { + public void testHasPointerEvents() + { assertTrue("Canvas.hasPointerEvents returned false", testCanvas.hasPointerEvents()); } - public void testHasPointerMotionEvents() { + public void testHasPointerMotionEvents() + { assertTrue("Canvas.hasPointerMotionEvents returned false", testCanvas.hasPointerMotionEvents()); } - public void testHasRepeatEvents() { + public void testHasRepeatEvents() + { assertTrue("Canvas.hasRepeatEvents returned false", testCanvas.hasRepeatEvents()); } - public void testSetFullScreenMode() { + public void testSetFullScreenMode() + { testCanvas.setFullScreenMode(true); testCanvas.setFullScreenMode(false); } - public void testGetGameAction() { - for (int i = 0; i < refGameToKeyTable.length; i++) { + public void testGetGameAction() + { + for(int i = 0; i < refGameToKeyTable.length; i++) + { int refKeyCode = refGameToKeyTable[i][0]; int refGameAction = refGameToKeyTable[i][1]; int testGameAction = testCanvas.getGameAction(refKeyCode); assertTrue("Game action for keycode " + refKeyCode + " invalid. Returned: " - + testGameAction + ", expected: " + refGameAction, - refGameAction == testGameAction); + + testGameAction + ", expected: " + refGameAction, + refGameAction == testGameAction); } // now test for invalid input - try { - testCanvas.getGameAction(0); - fail("IllegalArgumentException not throw for invalid input"); - } - catch (IllegalArgumentException e) { - // Ok - } + try + { + testCanvas.getGameAction(0); + fail("IllegalArgumentException not throw for invalid input"); + } + catch(IllegalArgumentException e) + { + // Ok + } } - public void testGetKeyCode() { - for (int i = 0; i < refGameToKeyTable.length; i++) { + public void testGetKeyCode() + { + for(int i = 0; i < refGameToKeyTable.length; i++) + { int refKeyCode = refGameToKeyTable[i][0]; int refGameAction = refGameToKeyTable[i][1]; int testKeyCode = testCanvas.getKeyCode(refGameAction); assertTrue("Key code for game action " + refGameAction + " invalid. Returned: " - + testKeyCode + ", expected: " + refKeyCode, - refKeyCode == testKeyCode); + + testKeyCode + ", expected: " + refKeyCode, + refKeyCode == testKeyCode); } // now test for invalid input - try { + try + { testCanvas.getKeyCode(-111); fail("IllegalArgumentException not throw for invalid input"); - } - catch (IllegalArgumentException e) { - // Ok - } + } + catch(IllegalArgumentException e) + { + // Ok + } } - public void testGetKeyName() { - for (int i = 0; i < refKeyToGameTable.length; i++) { + public void testGetKeyName() + { + for(int i = 0; i < refKeyToGameTable.length; i++) + { int refKeyCode = refKeyToGameTable[i][0]; String testKeyName = testCanvas.getKeyName(refKeyCode); assertTrue("Canvas.getKeyName() returned null", testKeyName != null); } } - public void testServiceRepaints() { + public void testServiceRepaints() + { testCanvas.repaint(); testCanvas.serviceRepaints(); } - public void testGraphicsProperties() { + public void testGraphicsProperties() + { testCanvas.reset(); testCanvas.repaint(); testCanvas.serviceRepaints(); assertTrue(testCanvas.failMsg, testCanvas.passed); } - class TestCanvas extends Canvas { + class TestCanvas extends Canvas + { public boolean passed; public String failMsg; - public TestCanvas() { + public TestCanvas() + { reset(); }; - public void reset() { + public void reset() + { passed = true; failMsg = ""; } - protected void paint(Graphics g) { - if (g.getClipWidth() <= 0) { + protected void paint(Graphics g) + { + if(g.getClipWidth() <= 0) + { failMsg = "Graphics.getClipWidth() returns <= 0 in Canvas.paint()"; passed = false; return; } - if (g.getClipHeight() <= 0) { + if(g.getClipHeight() <= 0) + { failMsg = "Graphics.getClipHeight() returns <= 0 in Canvas.paint()"; passed = false; return; } - if (g.getColor() != 0x0000000) { + if(g.getColor() != 0x0000000) + { failMsg = "Graphics.getColor() returns not black in Canvas.paint()"; passed = false; return; @@ -283,29 +321,33 @@ Font graphicsFont = g.getFont(); Font defaultFont = Font.getDefaultFont(); - if (graphicsFont.getFace() != defaultFont.getFace() + if(graphicsFont.getFace() != defaultFont.getFace() || graphicsFont.getStyle() != defaultFont.getStyle() - || graphicsFont.getSize() != defaultFont.getSize()) { + || graphicsFont.getSize() != defaultFont.getSize()) + { failMsg = "Graphics.getFont() returns not default font in Canvas.paint()"; passed = false; return; } - if (g.getStrokeStyle() != Graphics.SOLID) { + if(g.getStrokeStyle() != Graphics.SOLID) + { failMsg = "Graphics.getStrokeStyle() returns not SOLID in Canvas.paint()"; passed = false; return; } - if (g.getTranslateX() != 0 - || g.getTranslateY() != 0) { + if(g.getTranslateX() != 0 + || g.getTranslateY() != 0) + { failMsg = "Graphics.getTranslateX() and getTranslateY() " - + "return not (0,0) in Canvas.paint()"; + + "return not (0,0) in Canvas.paint()"; passed = false; return; } - if (!isShown()) { + if(!isShown()) + { failMsg = "Canvas.isShown returns false in Canvas.paint()"; passed = false; return; @@ -313,7 +355,7 @@ g.setColor(255, 255, 0); g.setFont(Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_ITALIC, - Font.SIZE_LARGE)); + Font.SIZE_LARGE)); g.setStrokeStyle(Graphics.DOTTED); g.translate(20, 30); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/choicegroup/ChoiceGroupTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/choicegroup/ChoiceGroupTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/choicegroup/ChoiceGroupTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.choicegroup; @@ -32,7 +32,8 @@ * * @created 1.8.2008 */ -public class ChoiceGroupTest extends SWTTestCase { +public class ChoiceGroupTest extends SWTTestCase +{ private static final int NUMITEMS = 10; @@ -41,7 +42,8 @@ /** * Constructor. */ - public ChoiceGroupTest() { + public ChoiceGroupTest() + { } /** @@ -50,18 +52,22 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public ChoiceGroupTest(String sTestName) { + public ChoiceGroupTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - try { + protected void setUp() throws Exception + { + try + { itemImage = Image.createImage("32x32.jpg"); } - catch (IOException ioe) { + catch(IOException ioe) + { ioe.printStackTrace(); } } @@ -72,23 +78,26 @@ * * @return New TestSuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ChoiceGroupTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ChoiceGroupTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ChoiceGroupTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ChoiceGroupTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testAccessors1"); @@ -98,26 +107,30 @@ methodNames.addElement("testMoveBetweenForms"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testAccessors1")) testAccessors(false); - else if (getName().equals("testAccessors2")) testAccessors(true); - else if (getName().equals("testMultiple1")) testMultiple(false); - else if (getName().equals("testMultiple2")) testMultiple(true); - else if (getName().equals("testMoveBetweenForms")) testMoveBetweenForms(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testAccessors1")) testAccessors(false); + else if(getName().equals("testAccessors2")) testAccessors(true); + else if(getName().equals("testMultiple1")) testMultiple(false); + else if(getName().equals("testMultiple2")) testMultiple(true); + else if(getName().equals("testMoveBetweenForms")) testMoveBetweenForms(); else super.runTest(); - } - + } + /** * Test method for constructors. */ - public void testConstructors() { - try { + public void testConstructors() + { + try + { new ChoiceGroup(null, 0); fail("IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -127,43 +140,52 @@ new ChoiceGroup(null, Choice.POPUP); - try { + try + { new ChoiceGroup(null, Choice.IMPLICIT); fail("IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } - try { + try + { new ChoiceGroup(null, Choice.EXCLUSIVE, null, null); fail("NullPointerException should be thrown"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } String[] goodStrArr = new String[] { "1", "2", "3", "4" }; String[] badStrArr = new String[] { "1", null, "2", "3" }; Image[] goodImgArr = new Image[] { itemImage, itemImage, itemImage, - itemImage, }; + itemImage, + }; Image[] badImgArr = new Image[] { itemImage, itemImage, itemImage, }; - try { + try + { new ChoiceGroup(null, Choice.EXCLUSIVE, badStrArr, null); fail("NullPointerException should be thrown - " - + "for null item in text array"); + + "for null item in text array"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } - try { + try + { new ChoiceGroup(null, Choice.EXCLUSIVE, goodStrArr, badImgArr); fail("IllegalArgumentException should be thrown - " - + "text and image array length mismatch"); + + "text and image array length mismatch"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -174,101 +196,117 @@ /** * Test method for different accessor method (add/remove/fonts/selections). */ - public void testAccessors(boolean inForm) { + public void testAccessors(boolean inForm) + { ChoiceGroup choicegroup = new ChoiceGroup(null, Choice.EXCLUSIVE); - if (inForm) { + if(inForm) + { Form form = new Form(getName()); form.append(choicegroup); } choicegroup.setFitPolicy(Choice.TEXT_WRAP_DEFAULT); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_DEFAULT, - choicegroup.getFitPolicy()); + choicegroup.getFitPolicy()); choicegroup.setFitPolicy(Choice.TEXT_WRAP_ON); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_ON, choicegroup - .getFitPolicy()); + .getFitPolicy()); choicegroup.setFitPolicy(Choice.TEXT_WRAP_OFF); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_OFF, choicegroup - .getFitPolicy()); + .getFitPolicy()); - try { + try + { choicegroup.setFitPolicy(Choice.TEXT_WRAP_OFF + 1); fail("IllegalArgumentException not thrown - " - + "for invalid fit policy"); + + "for invalid fit policy"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_OFF, - choicegroup.getFitPolicy()); + choicegroup.getFitPolicy()); } // append - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.append("item" + i, itemImage); } assertEquals("ChoiceGroup size - after append", NUMITEMS, choicegroup - .size()); + .size()); // invalid append - try { + try + { choicegroup.append(null, itemImage); fail("NullPointerException not thrown - " - + "for invalid string append"); + + "for invalid string append"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Fall-through } // delete - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.delete(0); } assertEquals("ChoiceGroup size - after delete", 0, choicegroup.size()); // insert - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.insert(0, "item" + i, itemImage); } assertEquals("ChoiceGroup size - after insert", NUMITEMS, choicegroup - .size()); + .size()); // invalid insert - try { + try + { choicegroup.insert(NUMITEMS * 2, "item" + NUMITEMS * 2, itemImage); fail("IndexOutOfBoundsException not thrown - " - + "for invalid insert index"); + + "for invalid insert index"); } - catch (IndexOutOfBoundsException iobe) { + catch(IndexOutOfBoundsException iobe) + { // Fall-through } // set - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.set(i, "item" + i * 2, itemImage); } assertEquals("ChoiceGroup size - after set", NUMITEMS, choicegroup - .size()); + .size()); // check item strings individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertEquals("Item " + i + " mismatch", "item" + i * 2, choicegroup - .getString(i)); + .getString(i)); } // create fonts to plain=0, bold=1, italic=2 Font[] fonts = new Font[3]; - for (int i = 0; i < 3; i++) { + for(int i = 0; i < 3; i++) + { fonts[i] = Font.getFont(Font.FACE_SYSTEM, i, Font.SIZE_MEDIUM); } // set list fonts - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.setFont(i, fonts[i % 3]); } // check item fonts individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertEquals("Font " + i + " mismatch", fonts[i % 3], choicegroup - .getFont(i)); + .getFont(i)); } int selIndex = choicegroup.getSelectedIndex(); @@ -277,52 +315,60 @@ // test multi-selection flags on single selection Choicegroup boolean[] setSelArr = new boolean[NUMITEMS]; // select every 3rd item - for (int i = 1; i < NUMITEMS; i++) { + for(int i = 1; i < NUMITEMS; i++) + { setSelArr[i] = (i % 3 == 0); } choicegroup.setSelectedFlags(setSelArr); assertTrue("Selected item mismatch - after multisel array", - choicegroup.isSelected(3)); + choicegroup.isSelected(3)); // delete all choicegroup.deleteAll(); assertEquals("ChoiceGroup size - after delete all", 0, choicegroup - .size()); + .size()); } /** * Test method for checking multiple selection functionality. */ - public void testMultiple(boolean inForm) { + public void testMultiple(boolean inForm) + { ChoiceGroup choicegroup = new ChoiceGroup(null, Choice.MULTIPLE); - if (inForm) { + if(inForm) + { Form form = new Form("Form"); form.append(choicegroup); } // append - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.append("item" + i, itemImage); } assertEquals("ChoiceGroup size - after append", NUMITEMS, choicegroup - .size()); + .size()); - try { + try + { choicegroup.setSelectedFlags(null); fail("NullPointerException not thrown - " - + "for null selected array"); + + "for null selected array"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } - try { + try + { boolean[] badSelArr = new boolean[NUMITEMS / 2]; choicegroup.setSelectedFlags(badSelArr); fail("IllegalArgumentException not thrown - " - + "for invalid selected array size"); + + "for invalid selected array size"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -330,26 +376,30 @@ boolean[] getSelArr = new boolean[NUMITEMS * 2]; // select odd items - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { setSelArr[i] = (i % 2 == 0); } choicegroup.setSelectedFlags(setSelArr); choicegroup.getSelectedFlags(getSelArr); // check each item individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - setSelArr[i] == getSelArr[i]); + setSelArr[i] == getSelArr[i]); } // flip each item - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.setSelectedIndex(i, !setSelArr[i]); } // check each item individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - setSelArr[i] != choicegroup.isSelected(i)); + setSelArr[i] != choicegroup.isSelected(i)); } } @@ -357,65 +407,75 @@ * Test method for moving a ChoiceGroup between two forms, * while keeping its internal state. */ - public void testMoveBetweenForms() { + public void testMoveBetweenForms() + { Form form1 = new Form("Form1"); Form form2 = new Form("Form2"); ChoiceGroup choicegroup = new ChoiceGroup(null, Choice.MULTIPLE); form1.append(choicegroup); // append1 - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.append("form1 item" + i, itemImage); } assertEquals("ChoiceGroup size - after 1. append ", NUMITEMS, - choicegroup.size()); + choicegroup.size()); // flip selection - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.setSelectedIndex(i, !choicegroup.isSelected(i)); } form1.deleteAll(); // append 2 - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.append("noform item" + i, itemImage); } assertEquals("ChoiceGroup size - after 2. append ", 2 * NUMITEMS, - choicegroup.size()); + choicegroup.size()); // flip selection - for (int i = 0; i < 2 * NUMITEMS; i++) { + for(int i = 0; i < 2 * NUMITEMS; i++) + { choicegroup.setSelectedIndex(i, !choicegroup.isSelected(i)); } form2.append(choicegroup); // append 3 - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { choicegroup.append("form2 item" + i, itemImage); } assertEquals("ChoiceGroup size - after 3. append ", 3 * NUMITEMS, - choicegroup.size()); + choicegroup.size()); // flip selection - for (int i = 0; i < 3 * NUMITEMS; i++) { + for(int i = 0; i < 3 * NUMITEMS; i++) + { choicegroup.setSelectedIndex(i, !choicegroup.isSelected(i)); } // Check selection ( - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - choicegroup.isSelected(i)); + choicegroup.isSelected(i)); } - for (int i = NUMITEMS; i < 2 * NUMITEMS; i++) { + for(int i = NUMITEMS; i < 2 * NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - !choicegroup.isSelected(i)); + !choicegroup.isSelected(i)); } - for (int i = 2 * NUMITEMS; i < 3 * NUMITEMS; i++) { + for(int i = 2 * NUMITEMS; i < 3 * NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - choicegroup.isSelected(i)); + choicegroup.isSelected(i)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/CommandTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/CommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/CommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.command; @@ -33,7 +33,8 @@ * Created: 2008-05-02 * */ -public class CommandTest extends SWTTestCase { +public class CommandTest extends SWTTestCase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; private static final int TEST_INVALID_TYPE = 43242; @@ -44,14 +45,16 @@ /** * Constructor. */ - public CommandTest() { + public CommandTest() + { } /** * @param sTestName Test name. * @param rTestMethod Test method. */ - public CommandTest(String sTestName) { + public CommandTest(String sTestName) + { super(sTestName); } @@ -60,23 +63,26 @@ * any new test methods, otherwise they won't be run. * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = CommandTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new CommandTest((String)e.nextElement())); - } + // Add widget tests + methodNames = CommandTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new CommandTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testAccessors"); @@ -84,46 +90,58 @@ methodNames.addElement("testEmptyLabel"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testNegativePriority")) testNegativePriority(); - else if (getName().equals("testEmptyLabel")) testEmptyLabel(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testNegativePriority")) testNegativePriority(); + else if(getName().equals("testEmptyLabel")) testEmptyLabel(); else super.runTest(); } - - + + /** * Tests the functionality of constructors. */ - public void testConstructors() { + public void testConstructors() + { // Try to create Command with null label: - try { + try + { new Command(null, Command.OK, 0); fail("Command constructor didn't throw NullPointerException when label was null."); - } catch (NullPointerException ex) { + } + catch(NullPointerException ex) + { } // Try to create Command with null short label: - try { + try + { new Command(null, "long label", Command.OK, 0); fail("Command constructor didn't throw NullPointerException when short label was null."); - } catch (NullPointerException ex) { + } + catch(NullPointerException ex) + { } // Try to create Command with illegal type: - try { + try + { new Command("label", TEST_INVALID_TYPE, 0); fail("Command constructor didn't throw IllegalArgumentException when type was illegal."); - } catch (IllegalArgumentException ex) { + } + catch(IllegalArgumentException ex) + { } } /** * Tests the functionality of basic accessors methods. */ - public void testAccessors() { + public void testAccessors() + { String label1 = "label1"; String longLabel1 = "long label 1"; int type1 = Command.BACK; @@ -166,7 +184,8 @@ * are handled without problems. This is important to test because OpenLCDUI * is built on top of eSWT which doesn't allow negative priority values. */ - public void testNegativePriority() { + public void testNegativePriority() + { TextBox textBox = new TextBox(getName(), "content", MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command c1 = new Command("label1", null, Command.ITEM, -1); Command c2 = new Command("label2", null, Command.ITEM, Integer.MAX_VALUE); @@ -193,7 +212,8 @@ * instead of empty string. So this test creates a new Command with empty * label, and verifies the label is the default one. */ - public void testEmptyLabel() { + public void testEmptyLabel() + { Command c = new Command("", "", Command.BACK, 0); TextBox textBox = new TextBox(getName(), "content", MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); textBox.addCommand(c); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/ItemCommandTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/ItemCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/command/ItemCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.command; @@ -32,19 +32,22 @@ * Created: 2008-08-04 * */ -public class ItemCommandTest extends SWTTestCase { +public class ItemCommandTest extends SWTTestCase +{ /** * Constructor. */ - public ItemCommandTest() { + public ItemCommandTest() + { } /** * @param sTestName Test name. * @param rTestMethod Test method. */ - public ItemCommandTest(String sTestName) { + public ItemCommandTest(String sTestName) + { super(sTestName); } @@ -53,39 +56,44 @@ * any new test methods, otherwise they won't be run. * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = ItemCommandTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ItemCommandTest((String)e.nextElement())); - } + // Add widget tests + methodNames = ItemCommandTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ItemCommandTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAddCommand"); methodNames.addElement("testRemoveCommand"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAddCommand")) testAddCommand(); - else if (getName().equals("testRemoveCommand")) testRemoveCommand(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAddCommand")) testAddCommand(); + else if(getName().equals("testRemoveCommand")) testRemoveCommand(); else super.runTest(); } - + /** * Tests to add command to form item. */ - public void testAddCommand() { + public void testAddCommand() + { Form form = new Form("form"); StringItem button1 = new StringItem("", "click!", Item.BUTTON); Command ok = new Command("Ok", "", Command.OK, 0); @@ -96,7 +104,8 @@ /** * Tests to remove command from form item. */ - public void testRemoveCommand() { + public void testRemoveCommand() + { Form form = new Form("form"); StringItem button1 = new StringItem("", "click!", Item.BUTTON); StringItem button2 = new StringItem("", "click2!", Item.BUTTON); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/datefield/DateFieldTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/datefield/DateFieldTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/datefield/DateFieldTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.datefield; @@ -36,7 +36,8 @@ * Created: 2008-09-30 * */ -public class DateFieldTest extends SWTTestCase { +public class DateFieldTest extends SWTTestCase +{ //2008-10-07 11:30:35 is 1223368235775 in millis. private static final long TEST_DATE_IN_MILLIS = 1223368235775L; @@ -46,14 +47,16 @@ /** * Constructor. */ - public DateFieldTest() { + public DateFieldTest() + { } /** * @param testName Test name. * @param testMethod Test method. */ - public DateFieldTest(String testName) { + public DateFieldTest(String testName) + { super(testName); } @@ -62,39 +65,44 @@ * any new test methods, otherwise they won't be run. * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = DateFieldTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DateFieldTest((String)e.nextElement())); - } + // Add widget tests + methodNames = DateFieldTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DateFieldTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } - + /** * Tests the functionality of constructors. */ - public void testConstructors() { + public void testConstructors() + { // DateField with label: DateField dateField = new DateField("label", DateField.DATE); assertNotNull("Label was null.", dateField.getLabel()); @@ -111,15 +119,17 @@ assertEquals("Invalid mode.", DateField.TIME, dateField.getInputMode()); dateField = new DateField(null, DateField.DATE_TIME); assertEquals("Invalid mode.", DateField.DATE_TIME, - dateField.getInputMode()); + dateField.getInputMode()); // DateField with invalid mode: - try { + try + { dateField = new DateField(null, 0); fail("No illegalArgumentException when creating DateField with" - + " invalid mode."); + + " invalid mode."); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } // DateField with null timezone: @@ -127,13 +137,14 @@ // DateField with timezone: dateField = new DateField(null, DateField.DATE_TIME, - TimeZone.getTimeZone("GMT")); + TimeZone.getTimeZone("GMT")); } /** * Tests the functionality of basic accessors methods. */ - public void testAccessors() { + public void testAccessors() + { DateField dateField = new DateField(null, DateField.DATE); DateField dateField2 = new DateField(null, DateField.TIME); DateField dateField3 = new DateField(null, DateField.DATE_TIME); @@ -152,9 +163,9 @@ dateCalendar.setTime(dateField.getDate()); assertEquals("Hour not zero in DateField of type DATE.", - 0, dateCalendar.get(Calendar.HOUR_OF_DAY)); + 0, dateCalendar.get(Calendar.HOUR_OF_DAY)); assertEquals("Minute not zero in DateField of type DATE.", - 0, dateCalendar.get(Calendar.MINUTE)); + 0, dateCalendar.get(Calendar.MINUTE)); // Set Time: Calendar timeCalendar = Calendar.getInstance(); @@ -169,25 +180,27 @@ // and make sure the returned Date is null after that: dateField2.setDate(testDate); assertNull("Date not null when setting time and date-part" - + " not 1970-01-01", dateField2.getDate()); + + " not 1970-01-01", dateField2.getDate()); // Set DateTime: dateField3.setDate(testDate); checkSameDateTime("DateTime set failed.", - testDate, dateField3.getDate()); + testDate, dateField3.getDate()); // Set Mode: dateField.setInputMode(DateField.DATE_TIME); assertEquals("Mode set failed.", - DateField.DATE_TIME, dateField.getInputMode()); + DateField.DATE_TIME, dateField.getInputMode()); // Set invalid mode: - try { + try + { dateField.setInputMode(0); fail("No illegalArgumentException when setting" - + " invalid mode."); + + " invalid mode."); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } } @@ -198,16 +211,18 @@ * @param expected First Date to be compared. * @param actual Second Date. */ - private void checkSameDate(String msg, Date expected, Date actual) { + private void checkSameDate(String msg, Date expected, Date actual) + { Calendar c1 = Calendar.getInstance(); c1.setTime(expected); Calendar c2 = Calendar.getInstance(); c2.setTime(actual); - if ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) - || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) - || (c1.get(Calendar.DAY_OF_MONTH) != c2.get(Calendar.DAY_OF_MONTH)) - ) { + if((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) + || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) + || (c1.get(Calendar.DAY_OF_MONTH) != c2.get(Calendar.DAY_OF_MONTH)) + ) + { fail(msg + " expected: " + c1 + " actual: " + c2); } } @@ -220,15 +235,17 @@ * @param expected First Date to be compared. * @param actual Second Date. */ - private void checkSameTime(String msg, Date expected, Date actual) { + private void checkSameTime(String msg, Date expected, Date actual) + { Calendar c1 = Calendar.getInstance(); c1.setTime(expected); Calendar c2 = Calendar.getInstance(); c2.setTime(actual); - if ((c1.get(Calendar.HOUR_OF_DAY) != c2.get(Calendar.HOUR_OF_DAY)) - || (c1.get(Calendar.MINUTE) != c2.get(Calendar.MINUTE)) - ) { + if((c1.get(Calendar.HOUR_OF_DAY) != c2.get(Calendar.HOUR_OF_DAY)) + || (c1.get(Calendar.MINUTE) != c2.get(Calendar.MINUTE)) + ) + { fail(msg + " expected: " + c1 + " actual: " + c2); } } @@ -240,7 +257,8 @@ * @param expected First Date to be compared. * @param actual Second Date. */ - private void checkSameDateTime(String msg, Date expected, Date actual) { + private void checkSameDateTime(String msg, Date expected, Date actual) + { checkSameDate(msg, expected, actual); checkSameTime(msg, expected, actual); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/devicecontrol/DeviceControlTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/devicecontrol/DeviceControlTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/devicecontrol/DeviceControlTest.java Fri May 14 15:47:24 2010 +0300 @@ -22,37 +22,42 @@ import com.nokia.mid.ui.DeviceControl; -public class DeviceControlTest extends SWTTestCase { - - /** - * Constructor. - */ +public class DeviceControlTest extends SWTTestCase +{ + + /** + * Constructor. + */ /** * @param testName Test name. * @param testMethod Test method. */ - public DeviceControlTest(String testName) { + public DeviceControlTest(String testName) + { super(testName); } - - public static Test suite() { - TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + public static Test suite() + { + TestSuite suite = new TestSuite(); + + java.util.Vector methodNames; + java.util.Enumeration e; - // Add tests - methodNames = DeviceControlTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DeviceControlTest((String)e.nextElement())); - } + // Add tests + methodNames = DeviceControlTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DeviceControlTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("test_getUserInactivityTime"); methodNames.addElement("test_resetUserInactivityTime"); @@ -62,218 +67,326 @@ methodNames.addElement("test_stopVibra"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("test_getUserInactivityTime")) test_getUserInactivityTime(); - else if (getName().equals("test_resetUserInactivityTime")) test_resetUserInactivityTime(); - else if (getName().equals("test_setLights")) test_setLights(); - else if (getName().equals("test_flashLights")) test_flashLights(); - else if (getName().equals("test_startVibra")) test_startVibra(); - else if (getName().equals("test_stopVibra")) test_stopVibra(); + + protected void runTest() throws Throwable + { + if(getName().equals("test_getUserInactivityTime")) test_getUserInactivityTime(); + else if(getName().equals("test_resetUserInactivityTime")) test_resetUserInactivityTime(); + else if(getName().equals("test_setLights")) test_setLights(); + else if(getName().equals("test_flashLights")) test_flashLights(); + else if(getName().equals("test_startVibra")) test_startVibra(); + else if(getName().equals("test_stopVibra")) test_stopVibra(); else super.runTest(); } - - public void test_getUserInactivityTime(){ - org.eclipse.swt.widgets.Display.getDefault(); - try{ - assertTrue(DeviceControl.getUserInactivityTime()>=0); - } catch (Exception e) { - fail("Exception - in getUserInactivityTime - " + e.getMessage()); - } - - new Thread(new Runnable() { - public void run() { - try{ - DeviceControl.getUserInactivityTime(); - } catch (Exception e) { - fail("Exception - in getUserInactivityTime - " + e.getMessage()); - } - }}).start(); + + public void test_getUserInactivityTime() + { + org.eclipse.swt.widgets.Display.getDefault(); + try + { + assertTrue(DeviceControl.getUserInactivityTime()>=0); + } + catch(Exception e) + { + fail("Exception - in getUserInactivityTime - " + e.getMessage()); + } + + new Thread(new Runnable() + { + public void run() + { + try + { + DeviceControl.getUserInactivityTime(); + } + catch(Exception e) + { + fail("Exception - in getUserInactivityTime - " + e.getMessage()); + } + } + }).start(); } - - public void test_resetUserInactivityTime(){ - try{ - DeviceControl.resetUserInactivityTime(); - } catch (Exception e) { + + public void test_resetUserInactivityTime() + { + try + { + DeviceControl.resetUserInactivityTime(); + } + catch(Exception e) + { fail("Exception - in resetUserInactivityTime - " + e.getMessage()); } - new Thread(new Runnable() { - public void run() { - try{ - DeviceControl.resetUserInactivityTime(); - } catch (Exception e) { - fail("Exception - in resetUserInactivityTime - " + e.getMessage()); - } - }}).start(); + new Thread(new Runnable() + { + public void run() + { + try + { + DeviceControl.resetUserInactivityTime(); + } + catch(Exception e) + { + fail("Exception - in resetUserInactivityTime - " + e.getMessage()); + } + } + }).start(); } - - public void test_setLights(){ - - try { - DeviceControl.setLights(-1, 50); - fail ("Expected exception not thrown setLights with -1 aNum"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown is not expected","Light num is not supported", e.getMessage()); + + public void test_setLights() + { + + try + { + DeviceControl.setLights(-1, 50); + fail("Expected exception not thrown setLights with -1 aNum"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown is not expected","Light num is not supported", e.getMessage()); + } + + try + { + DeviceControl.setLights(2, 50); + fail("Expected exception not thrown setLights with 2 aNum"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown is not expected","Light num is not supported", e.getMessage()); + } + + try + { + DeviceControl.setLights(0, 50); + } + catch(Exception e) + { + fail("Exception - in setLights - " + e.getMessage()); } - - try { - DeviceControl.setLights(2, 50); - fail ("Expected exception not thrown setLights with 2 aNum"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown is not expected","Light num is not supported", e.getMessage()); + + try + { + DeviceControl.setLights(0, -1); + fail("Expected exception not thrown setLights with -1 aLevel"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown is not expected","Level not between 0 and 100", e.getMessage()); + } + + try + { + DeviceControl.setLights(0, 101); + fail("Expected exception not thrown setLights with 101 aLevel"); } - - try { - DeviceControl.setLights(0, 50); - } catch (Exception e) { + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown is not expected","Level not between 0 and 100", e.getMessage()); + } + + try + { + DeviceControl.setLights(0, 100); + } + catch(Exception e) + { + fail("Exception - in setLights - " + e.getMessage()); + } + + try + { + DeviceControl.setLights(0, 0); + } + catch(Exception e) + { fail("Exception - in setLights - " + e.getMessage()); } - - try { - DeviceControl.setLights(0, -1); - fail ("Expected exception not thrown setLights with -1 aLevel"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown is not expected","Level not between 0 and 100", e.getMessage()); + + new Thread(new Runnable() + { + public void run() + { + try + { + DeviceControl.setLights(0, 0); + } + catch(Exception e) + { + fail("Exception - in setLights - " + e.getMessage()); + } + } + }).start(); + } + + public void test_flashLights() + { + + try + { + DeviceControl.flashLights(-1); + fail("Expected exception not thrown setLights with -1 duration"); } - - try { - DeviceControl.setLights(0, 101); - fail ("Expected exception not thrown setLights with 101 aLevel"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown is not expected","Level not between 0 and 100", e.getMessage()); - } - - try { - DeviceControl.setLights(0, 100); - } catch (Exception e) { - fail("Exception - in setLights - " + e.getMessage()); - } - - try { - DeviceControl.setLights(0, 0); - } catch (Exception e) { - fail("Exception - in setLights - " + e.getMessage()); + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown is not expected","Negative duration", e.getMessage()); } - - new Thread(new Runnable() { - public void run() { - try { - DeviceControl.setLights(0, 0); - } catch (Exception e) { - fail("Exception - in setLights - " + e.getMessage()); - } - }}).start(); - } - - public void test_flashLights(){ - - try { - DeviceControl.flashLights(-1); - fail ("Expected exception not thrown setLights with -1 duration"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown is not expected","Negative duration", e.getMessage()); - } - - try { - DeviceControl.flashLights(0); - } catch (Exception e) { - fail("Exception - in flashLights - " + e.getMessage()); - } - - try { - DeviceControl.flashLights(3000); - } catch (Exception e) { - fail("Exception - in flashLights - " + e.getMessage()); - } + + try + { + DeviceControl.flashLights(0); + } + catch(Exception e) + { + fail("Exception - in flashLights - " + e.getMessage()); + } - new Thread(new Runnable() { - public void run() { - try { - DeviceControl.flashLights(3000); - } catch (Exception e) { - fail("Exception - in flashLights - " + e.getMessage()); - } - }}).start(); + try + { + DeviceControl.flashLights(3000); + } + catch(Exception e) + { + fail("Exception - in flashLights - " + e.getMessage()); + } + + new Thread(new Runnable() + { + public void run() + { + try + { + DeviceControl.flashLights(3000); + } + catch(Exception e) + { + fail("Exception - in flashLights - " + e.getMessage()); + } + } + }).start(); } - - public void test_startVibra(){ - try { - DeviceControl.startVibra(-1, 10); - fail ("Expected exception not thrown setLights with -1 aFreq"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown expected",null, e.getMessage()); - } - try { - DeviceControl.startVibra(101, 10); - fail ("Expected exception not thrown setLights with 101 aFreq"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown expected",null, e.getMessage()); - } - - try { - DeviceControl.startVibra(0, 10); - } catch (IllegalStateException e) { - assertEquals ("Exception thrown expected only in emulator",null, e.getMessage()); - //fail("Exception - in startVibra - " + e.getMessage()); - }catch (Exception e){ - fail("Exception - in startVibra - " + e.getMessage()); - } - - try { - DeviceControl.startVibra(100, 10); - } catch (IllegalStateException e) { - assertEquals ("Exception thrown expected only in emulator",null, e.getMessage()); - //fail("Exception - in startVibra - " + e.getMessage()); - }catch (Exception e){ - fail("Exception - in startVibra - " + e.getMessage()); - } - - try { - DeviceControl.startVibra(10, -1); - fail ("Expected exception not thrown setLights with -1 aDuration"); - } catch (IllegalArgumentException e){ - assertEquals ("Exception thrown expected",null, e.getMessage()); + + public void test_startVibra() + { + try + { + DeviceControl.startVibra(-1, 10); + fail("Expected exception not thrown setLights with -1 aFreq"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown expected",null, e.getMessage()); + } + try + { + DeviceControl.startVibra(101, 10); + fail("Expected exception not thrown setLights with 101 aFreq"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown expected",null, e.getMessage()); + } + + try + { + DeviceControl.startVibra(0, 10); + } + catch(IllegalStateException e) + { + assertEquals("Exception thrown expected only in emulator",null, e.getMessage()); + //fail("Exception - in startVibra - " + e.getMessage()); + } + catch(Exception e) + { + fail("Exception - in startVibra - " + e.getMessage()); + } + + try + { + DeviceControl.startVibra(100, 10); + } + catch(IllegalStateException e) + { + assertEquals("Exception thrown expected only in emulator",null, e.getMessage()); + //fail("Exception - in startVibra - " + e.getMessage()); + } + catch(Exception e) + { + fail("Exception - in startVibra - " + e.getMessage()); + } + + try + { + DeviceControl.startVibra(10, -1); + fail("Expected exception not thrown setLights with -1 aDuration"); + } + catch(IllegalArgumentException e) + { + assertEquals("Exception thrown expected",null, e.getMessage()); + } + + try + { + DeviceControl.startVibra(10, 3000); + } + catch(IllegalStateException e) + { + assertEquals("Exception thrown expected only in emulator",null, e.getMessage()); + //fail("Exception - in startVibra - " + e.getMessage()); + } + catch(Exception e) + { + fail("Exception - in startVibra - " + e.getMessage()); + } + + new Thread(new Runnable() + { + public void run() + { + try + { + DeviceControl.startVibra(10, 3000); + } + catch(IllegalStateException e) + { + assertEquals("Exception thrown expected only in emulator",null, e.getMessage()); + //fail("Exception - in startVibra - " + e.getMessage()); + } + catch(Exception e) + { + fail("Exception - in startVibra - " + e.getMessage()); + } } - - try { - DeviceControl.startVibra(10, 3000); - } catch (IllegalStateException e) { - assertEquals ("Exception thrown expected only in emulator",null, e.getMessage()); - //fail("Exception - in startVibra - " + e.getMessage()); - } catch (Exception e){ - fail("Exception - in startVibra - " + e.getMessage()); - } + }).start(); + } + + public void test_stopVibra() + { + try + { + DeviceControl.stopVibra(); + } + catch(Exception e) + { + fail("Exception - in stopVibra - " + e.getMessage()); + } - new Thread(new Runnable() { - public void run() { - try { - DeviceControl.startVibra(10, 3000); - } catch (IllegalStateException e) { - assertEquals ("Exception thrown expected only in emulator",null, e.getMessage()); - //fail("Exception - in startVibra - " + e.getMessage()); - }catch (Exception e){ - fail("Exception - in startVibra - " + e.getMessage()); - } - }}).start(); + new Thread(new Runnable() + { + public void run() + { + try + { + //DeviceControl.startVibra(10, 3000); + DeviceControl.stopVibra(); + } + catch(Exception e) + { + fail("Exception - in stopVibra - " + e.getMessage()); + } + } + }).start(); } - - public void test_stopVibra(){ - try { - DeviceControl.stopVibra(); - } catch (Exception e) { - fail("Exception - in stopVibra - " + e.getMessage()); - } - new Thread(new Runnable() { - public void run() { - try { - //DeviceControl.startVibra(10, 3000); - DeviceControl.stopVibra(); - } catch (Exception e) { - fail("Exception - in stopVibra - " + e.getMessage()); - } - }}).start(); - } - } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/display/DisplayTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/display/DisplayTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/display/DisplayTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.display; @@ -32,7 +32,8 @@ *
            * Created: 2008-04-15 */ -public class DisplayTest extends SWTTestCase { +public class DisplayTest extends SWTTestCase +{ private Display display; @@ -45,7 +46,8 @@ /** * Constructor.. */ - public DisplayTest() { + public DisplayTest() + { } /** @@ -54,14 +56,16 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public DisplayTest(String sTestName) { + public DisplayTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here. */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { display = Display.getDisplay(getMIDlet()); } @@ -71,23 +75,26 @@ * * @return suite */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = DisplayTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DisplayTest((String)e.nextElement())); - } + // Add widget tests + methodNames = DisplayTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DisplayTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testGetDisplayException"); methodNames.addElement("testGetDisplay"); @@ -102,26 +109,28 @@ methodNames.addElement("testNumAlphaLevels"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testGetDisplayException")) testGetDisplayException(); - else if (getName().equals("testGetDisplay")) testGetDisplay(); - else if (getName().equals("testGetCurrentSetCurrent")) testGetCurrentSetCurrent(); - else if (getName().equals("testSetCurrentNull")) testSetCurrentNull(); - else if (getName().equals("testCallSeriallyWithCanvas")) testCallSeriallyWithCanvas(); - else if (getName().equals("testVibrateAndFlashBacklights")) testVibrateAndFlashBacklights(); - else if (getName().equals("testNumColors")) testNumColors(); - else if (getName().equals("testIsColor")) testIsColor(); - else if (getName().equals("testGetColorException")) testGetColorException(); - else if (getName().equals("testGetColor")) testGetColor(); - else if (getName().equals("testNumAlphaLevels")) testNumAlphaLevels(); + + protected void runTest() throws Throwable + { + if(getName().equals("testGetDisplayException")) testGetDisplayException(); + else if(getName().equals("testGetDisplay")) testGetDisplay(); + else if(getName().equals("testGetCurrentSetCurrent")) testGetCurrentSetCurrent(); + else if(getName().equals("testSetCurrentNull")) testSetCurrentNull(); + else if(getName().equals("testCallSeriallyWithCanvas")) testCallSeriallyWithCanvas(); + else if(getName().equals("testVibrateAndFlashBacklights")) testVibrateAndFlashBacklights(); + else if(getName().equals("testNumColors")) testNumColors(); + else if(getName().equals("testIsColor")) testIsColor(); + else if(getName().equals("testGetColorException")) testGetColorException(); + else if(getName().equals("testGetColor")) testGetColor(); + else if(getName().equals("testNumAlphaLevels")) testNumAlphaLevels(); else super.runTest(); } /** * This method tests that Display.getDisplay(MIDlet m) returns not null. */ - public void testGetDisplay() { + public void testGetDisplay() + { Display getDisplay = Display.getDisplay(getMIDlet()); assertNotNull("Display.getDisplay(midlet) is null", getDisplay); } @@ -130,12 +139,15 @@ * This method tests that getDisplay(MIDlet midlet) method throws * NullPointerException if midlet is null. */ - public void testGetDisplayException() { - try { + public void testGetDisplayException() + { + try + { Display.getDisplay(null); fail("Display.getDisplay(null) NullPointerException expected."); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } } @@ -144,12 +156,15 @@ * This method tests that getColor(int specifier) method throws * IllegalArgumentException specifier is not valid. */ - public void testGetColorException() { - try { + public void testGetColorException() + { + try + { display.getColor(INVALID_SPECIFIER); fail("getColor(invSpecifier) IllegalArgumentException expected."); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } } @@ -158,15 +173,18 @@ * This method test that setCurrent(Alert alert, Displayable displayable) * method throws NullPointerException if alert is null. */ - public void testSetCurrentException1() { + public void testSetCurrentException1() + { Alert alert = null; TextBox nextDisplayable = new TextBox(getName(), "", LENGTH, TextField.ANY); - try { + try + { display.setCurrent(alert, nextDisplayable); fail("Display.setCurrent(null, nextDisplayable). " + - "NullPointerException expected."); + "NullPointerException expected."); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } } @@ -175,15 +193,18 @@ * This method test that setCurrent(Alert alert, Displayable displayable) * method throws NullPointerException if displayable is null. */ - public void testSetCurrentException2() { + public void testSetCurrentException2() + { Alert alert = new Alert(getName()); TextBox nextDisplayable = null; - try { + try + { display.setCurrent(alert, nextDisplayable); fail("Display.setCurrent(alert, null). " + - "NullPointerException expected."); + "NullPointerException expected."); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } } @@ -192,15 +213,18 @@ * This method test that setCurrent(Alert alert, Displayable displayable) * method throws NullPointerException if next displayable is Alert. */ - public void testSetCurrentException3() { + public void testSetCurrentException3() + { Alert alert = new Alert("alert1"); Alert nextAlert = new Alert("alert2"); - try { + try + { display.setCurrent(alert, nextAlert); fail("Display.setCurrent(alert, null). " + - "IllegalArgumentException expected."); + "IllegalArgumentException expected."); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } } @@ -209,7 +233,8 @@ * This method tests that Display.getCurrent() returns current Displayable. * And Display.setCurrent(Displayable d) */ - public void testGetCurrentSetCurrent() { + public void testGetCurrentSetCurrent() + { TextBox currentDisplayable = new TextBox(getName(), "", LENGTH, TextField.ANY); Displayable getDisplayable; @@ -222,7 +247,8 @@ /** * This method tests that Display.setCurrent(null) behaves correctly. */ - public void testSetCurrentNull() { + public void testSetCurrentNull() + { TextBox currentDisplayable = new TextBox(getName(), "", LENGTH, TextField.ANY); Displayable getDisplayable; @@ -235,7 +261,8 @@ /** * Test CallSerially method. */ - public void testCallSeriallyWithCanvas() { + public void testCallSeriallyWithCanvas() + { long paintTime = 0; long threadTime = 0; boolean passed = true; @@ -245,15 +272,17 @@ // screen.setTitle("Canvas"); // canvas's title cannot be set MyThreadClass runnable = new MyThreadClass(); - for (int i = 1; i <= LENGTH; i++) { + for(int i = 1; i <= LENGTH; i++) + { screen.setWH(i, i); screen.repaint(); display.callSerially(runnable); // runnable.run(); paintTime = screen.getTimestamp(); threadTime = runnable.getRunTimeStamp(); - if ((paintTime > threadTime) - && (screen.getCounter() <= runnable.getCounter())) { + if((paintTime > threadTime) + && (screen.getCounter() <= runnable.getCounter())) + { passed = false; message = "CallSerially fails on iteration: " + i; } @@ -265,26 +294,31 @@ /** * Dummy Runnable to check Call serially */ - class MyThreadClass implements Runnable { + class MyThreadClass implements Runnable + { private long runTimestamp; private int counter; - public void run() { + public void run() + { runTimestamp = new Date().getTime(); counter++; } - public int getCounter() { + public int getCounter() + { return counter; } - public long getRunTimeStamp() { + public long getRunTimeStamp() + { return runTimestamp; } } - class MoveShapeTCanvas extends Canvas { + class MoveShapeTCanvas extends Canvas + { private Display display; private long paintTimestamp; private int w; @@ -296,7 +330,8 @@ * * @param aDisplay display to be set for the Canvas */ - public MoveShapeTCanvas(Display aDisplay) { + public MoveShapeTCanvas(Display aDisplay) + { display = aDisplay; display.setCurrent(this); } @@ -307,18 +342,21 @@ * @param aW * @param aH */ - public void setWH(int aW, int aH) { + public void setWH(int aW, int aH) + { w = aW; h = aH; } - public void paint(Graphics g) { + public void paint(Graphics g) + { g.fillRect(0, 0, w, h); paintTimestamp = new Date().getTime(); counter++; } - public int getCounter() { + public int getCounter() + { return counter; } @@ -327,7 +365,8 @@ * * @return timestamp */ - public long getTimestamp() { + public long getTimestamp() + { return paintTimestamp; } } @@ -336,20 +375,25 @@ * Tests to call vibrate and flashbacklights methods with illegal parameter * values and verify an exception is thrown. */ - public void testVibrateAndFlashBacklights() { - try { + public void testVibrateAndFlashBacklights() + { + try + { display.vibrate(-1); fail("display.vibrate(-1). IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Ok } - try { + try + { display.flashBacklight(-1); fail("display.flashBacklight(-1);. IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // Ok } } @@ -357,41 +401,45 @@ /** * Test Display.numColors(). */ - public void testNumColors() { + public void testNumColors() + { int numColors = 0; numColors = display.numColors(); assertTrue("Display.numColors(). " + - "Expected return not 0, but returned " + numColors, numColors != 0); + "Expected return not 0, but returned " + numColors, numColors != 0); } /** * Test Display.isColor(). note: to pass this test you need to have non * black and white screen device */ - public void testIsColor() { + public void testIsColor() + { boolean passed = false; passed = display.isColor(); assertTrue("Display.isColor(). Expected return true, but returned " - + passed, passed); + + passed, passed); } /** * Display.getColor(int specifier) test. */ - public void testGetColor() { + public void testGetColor() + { int color = 0; color = display.getColor(Display.COLOR_BACKGROUND); assertTrue("Display.getColor(COLOR_BACKGROUND). " + - "Expected returns not 0 but returned " + color, color != 0); + "Expected returns not 0 but returned " + color, color != 0); } /** * Display.numAlphaLevels() test. */ - public void testNumAlphaLevels() { + public void testNumAlphaLevels() + { int numAlpha = display.numAlphaLevels(); assertTrue("Display.numAlphaLevels(). " + - "Expected returns not 0 but returned "+ numAlpha, numAlpha != 0); + "Expected returns not 0 but returned "+ numAlpha, numAlpha != 0); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/displayable/DisplayableTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/displayable/DisplayableTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/displayable/DisplayableTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.displayable; @@ -30,7 +30,8 @@ *
            * Created: 2008-04-21 */ -public class DisplayableTest extends SWTTestCase { +public class DisplayableTest extends SWTTestCase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; @@ -39,7 +40,8 @@ /** * Constructor. */ - public DisplayableTest() { + public DisplayableTest() + { } /** @@ -48,12 +50,14 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public DisplayableTest(String sTestName) { + public DisplayableTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { - display = Display.getDisplay(getMIDlet()); + protected void setUp() throws Exception + { + display = Display.getDisplay(getMIDlet()); } /** @@ -62,23 +66,26 @@ * * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = DisplayableTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DisplayableTest((String)e.nextElement())); - } + // Add widget tests + methodNames = DisplayableTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DisplayableTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAddNullCommand"); methodNames.addElement("testRemoveCommandCrash"); @@ -87,29 +94,33 @@ methodNames.addElement("testAddRemoveCommandWithoutListener"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAddNullCommand")) testAddNullCommand(); - else if (getName().equals("testRemoveCommandCrash")) testRemoveCommandCrash(); - else if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testNullAndEmptyTitle")) testNullAndEmptyTitle(); - else if (getName().equals("testAddRemoveCommandWithoutListener")) testAddRemoveCommandWithoutListener(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAddNullCommand")) testAddNullCommand(); + else if(getName().equals("testRemoveCommandCrash")) testRemoveCommandCrash(); + else if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testNullAndEmptyTitle")) testNullAndEmptyTitle(); + else if(getName().equals("testAddRemoveCommandWithoutListener")) testAddRemoveCommandWithoutListener(); else super.runTest(); } - - + + /** * Test that addCommand throws NullPointerException if parameter is null. */ - public void testAddNullCommand() { + public void testAddNullCommand() + { TextBox textBox = new TextBox(getName(), "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); - try { + try + { textBox.addCommand(null); fail("NullPointerException should be thrown"); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { // Ok } } @@ -117,9 +128,10 @@ /** * Make some tests for invalid operations on Commands. */ - public void testRemoveCommandCrash() { + public void testRemoveCommandCrash() + { TextBox textBox = new TextBox(getName(), "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command c1 = new Command("item1", Command.ITEM, 0); Command c2 = new Command("item2", Command.ITEM, 0); @@ -144,38 +156,44 @@ /** * Tests the basic functionality of the accessor methods. */ - public void testAccessors() { + public void testAccessors() + { TextBox textBox = new TextBox(getName(), "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Ticker ticker = new Ticker("test ticker"); // No ticker should exist by default: - if (textBox.getTicker() != null) { + if(textBox.getTicker() != null) + { fail("getTicker() returned non-null value by default."); } // Test to set ticker and verify that the correct ticker is returned // when queried. textBox.setTicker(ticker); - if (textBox.getTicker() != ticker) { + if(textBox.getTicker() != ticker) + { fail("getTicker() returned null or wrong ticker."); } // Test title set in constructor: - if (!textBox.getTitle().equals(getName())) { + if(!textBox.getTitle().equals(getName())) + { fail("Invalid initial title returned."); } // Test to set title and verify results: textBox.setTitle("newTitle"); - if (!textBox.getTitle().equals("newTitle")) { + if(!textBox.getTitle().equals("newTitle")) + { fail("Invalid title returned."); } // Test to remove title and verify results: textBox.setTitle(null); - if (textBox.getTitle() != null) { + if(textBox.getTitle() != null) + { fail("title not removed."); } @@ -184,7 +202,8 @@ display.setCurrent(textBox); block(200); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { fail("isShown() returned false even when displayable is visible."); } textBox.setTicker(null); @@ -194,19 +213,22 @@ * Tests to set and get null and empty string to title and verifies that * returned value is always what was set. */ - public void testNullAndEmptyTitle() { + public void testNullAndEmptyTitle() + { TextBox textBox = new TextBox(getName(), "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); // Use empty string as title and verify getTitle()'s return value: textBox.setTitle(""); - if (!textBox.getTitle().equals("")) { + if(!textBox.getTitle().equals("")) + { fail("failed to use empty string as title."); } // Test to set title to null and verify results: textBox.setTitle(null); - if (textBox.getTitle() != null) { + if(textBox.getTitle() != null) + { fail("title not null when expected."); } } @@ -215,9 +237,10 @@ * Test to add command to displayable and then remove it without setting * command listener before or after. */ - public void testAddRemoveCommandWithoutListener() { + public void testAddRemoveCommandWithoutListener() + { TextBox textBox = new TextBox(getName(), "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command c1 = new Command("CommandForDisplayable", Command.CANCEL, 1); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/font/FontTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/font/FontTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/font/FontTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.font; @@ -28,14 +28,16 @@ *
          • Collection of tests to test Font's functionality.
            *
            */ -public class FontTest extends SWTTestCase { +public class FontTest extends SWTTestCase +{ private static String shortString = "Lorem ipsum"; /** * Constructor. */ - public FontTest() { + public FontTest() + { } /** @@ -44,7 +46,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FontTest(String sTestName) { + public FontTest(String sTestName) + { super(sTestName); } @@ -53,47 +56,54 @@ * * @return New TestSuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = FontTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FontTest((String)e.nextElement())); - } + // Add widget tests + methodNames = FontTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FontTest((String)e.nextElement())); + } - return suite; + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } - - + + /** * Test method. */ - public void testConstructors() { + public void testConstructors() + { Font.getDefaultFont(); - try { + try + { Font.getFont(-1); fail("1. IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -101,35 +111,43 @@ Font.getFont(Font.FONT_INPUT_TEXT); - try { + try + { Font.getFont(2); fail("2. IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } - try { + try + { Font.getFont(-1, 0, 0); fail("3. IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } - try { + try + { Font.getFont(0, -1, 0); fail("4. IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } - try { + try + { Font.getFont(0, 0, -1); fail("5. IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } } @@ -137,18 +155,20 @@ /** * Test method. */ - public void testAccessors() { + public void testAccessors() + { Font font = Font.getDefaultFont(); assertNotNull("Default font shouldn't be null", font); assertTrue("Default font height shouldn't be null", - font.getHeight() != 0); + font.getHeight() != 0); int prevWidth = -1; - for (int i = 0; i < shortString.length(); i++) { + for(int i = 0; i < shortString.length(); i++) + { int witdh = font.substringWidth(shortString, 0, i); assertTrue("String width should increase width at pos " + i, - (witdh > prevWidth)); + (witdh > prevWidth)); prevWidth = witdh; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/form/FormTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/form/FormTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/form/FormTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.form; @@ -30,7 +30,8 @@ *
            * Created: 2008-07-10 */ -public class FormTest extends SWTTestCase { +public class FormTest extends SWTTestCase +{ private static final int INVALID_APPEARANCE_MODE = 3; private static final int INVALID_LAYOUT = 4; @@ -38,7 +39,8 @@ /** * Constructor. */ - public FormTest() { + public FormTest() + { } /** @@ -47,7 +49,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FormTest(String sTestName) { + public FormTest(String sTestName) + { super(sTestName); } @@ -57,22 +60,25 @@ * * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = FormTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FormTest((String)e.nextElement())); - } - return suite; + // Add widget tests + methodNames = FormTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FormTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testFormException"); methodNames.addElement("testAppendException"); @@ -96,36 +102,38 @@ methodNames.addElement("testFormConstructor"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testFormException")) testFormException(); - else if (getName().equals("testAppendException")) testAppendException(); - else if (getName().equals("testInsertException")) testInsertException(); - else if (getName().equals("testDeleteException")) testDeleteException(); - else if (getName().equals("testSetException")) testSetException(); - else if (getName().equals("testGetException")) testGetException(); - else if (getName().equals("testSize")) testSize(); - else if (getName().equals("testDeleteAll")) testDeleteAll(); - else if (getName().equals("testGetWidthGetHeight")) testGetWidthGetHeight(); - else if (getName().equals("testFormSetIOOBExceptions")) testFormSetIOOBExceptions(); - else if (getName().equals("testFormSetNPExceptions")) testFormSetNPExceptions(); - else if (getName().equals("testFormSetISExceptions")) testFormSetISExceptions(); - else if (getName().equals("testFormInsertIOOBExceptions")) testFormInsertIOOBExceptions(); - else if (getName().equals("testFormInsertNPExceptions")) testFormInsertNPExceptions(); - else if (getName().equals("testFormInsertISExceptions")) testFormInsertISExceptions(); - else if (getName().equals("testFormGetIOOBExceptions")) testFormGetIOOBExceptions(); - else if (getName().equals("testFormDeleteIOOBExceptions")) testFormDeleteIOOBExceptions(); - else if (getName().equals("testFormAppend")) testFormAppend(); - else if (getName().equals("testFormAppendImage")) testFormAppendImage(); - else if (getName().equals("testFormConstructor")) testFormConstructor(); + + protected void runTest() throws Throwable + { + if(getName().equals("testFormException")) testFormException(); + else if(getName().equals("testAppendException")) testAppendException(); + else if(getName().equals("testInsertException")) testInsertException(); + else if(getName().equals("testDeleteException")) testDeleteException(); + else if(getName().equals("testSetException")) testSetException(); + else if(getName().equals("testGetException")) testGetException(); + else if(getName().equals("testSize")) testSize(); + else if(getName().equals("testDeleteAll")) testDeleteAll(); + else if(getName().equals("testGetWidthGetHeight")) testGetWidthGetHeight(); + else if(getName().equals("testFormSetIOOBExceptions")) testFormSetIOOBExceptions(); + else if(getName().equals("testFormSetNPExceptions")) testFormSetNPExceptions(); + else if(getName().equals("testFormSetISExceptions")) testFormSetISExceptions(); + else if(getName().equals("testFormInsertIOOBExceptions")) testFormInsertIOOBExceptions(); + else if(getName().equals("testFormInsertNPExceptions")) testFormInsertNPExceptions(); + else if(getName().equals("testFormInsertISExceptions")) testFormInsertISExceptions(); + else if(getName().equals("testFormGetIOOBExceptions")) testFormGetIOOBExceptions(); + else if(getName().equals("testFormDeleteIOOBExceptions")) testFormDeleteIOOBExceptions(); + else if(getName().equals("testFormAppend")) testFormAppend(); + else if(getName().equals("testFormAppendImage")) testFormAppendImage(); + else if(getName().equals("testFormConstructor")) testFormConstructor(); else super.runTest(); } - - + + /** * Constructor Exception test. */ - public void testFormException() { + public void testFormException() + { Form formContainer = new Form("Form Title"); StringItem itemOwned = new StringItem("label", "text", 0); formContainer.append(itemOwned); @@ -133,65 +141,78 @@ Item[] items1 = {new StringItem(null, "body", 0), itemOwned, }; Item[] items2 = {new StringItem(null, "body2", 0), null, }; - try { + try + { Form formEx = new Form("header", items1); fail("IllegalStateException not thrown"); } - catch (IllegalStateException ise) { - // Ok + catch(IllegalStateException ise) + { + // Ok } - try { + try + { Form formEx = new Form("header", items2); fail("NullPointerException not thrown"); } - catch (NullPointerException npe) { - // OK + catch(NullPointerException npe) + { + // OK } } /** * Tests that append throws correct exceptions in case of incorrect input. */ - public void testAppendException() { + public void testAppendException() + { Form appendExForm = new Form("form title"); - Form container = new Form ("Form"); + Form container = new Form("Form"); String appendString = null; Image appendImage = null; StringItem appendStringItem = null; - try { + try + { appendExForm.append(appendString); fail("NullPointerException not thrown if string is null"); } - catch (NullPointerException npe) { - // Ok + catch(NullPointerException npe) + { + // Ok } - try { + try + { appendExForm.append(appendImage); fail("NullPointerException not thrown if image is null"); } - catch (NullPointerException npe) { - // Ok + catch(NullPointerException npe) + { + // Ok } - try { + try + { appendExForm.append(appendStringItem); fail("NullPointerException not thrown if item is null"); } - catch (NullPointerException npe) { - // Ok + catch(NullPointerException npe) + { + // Ok } appendStringItem = new StringItem("turur", "tururu", 0); container.append(appendStringItem); - try { + try + { appendExForm.append(appendStringItem); fail("IllegalStateException not thrown if item is already owned"); } - catch (IllegalStateException npe) { - // Ok + catch(IllegalStateException npe) + { + // Ok } } @@ -200,7 +221,8 @@ * Tests that insert() throws correct exceptions * in case of incorrect input. */ - public void testInsertException() { + public void testInsertException() + { Form insertException = new Form("insertEx"); Form formContainer = new Form("Form Title"); StringItem itemOwned = new StringItem("label", "text", 0); @@ -208,28 +230,34 @@ insertException.append("one item"); insertException.append("second item"); - try { + try + { insertException.insert(3, new StringItem(null, "text", 0)); fail("IndexOutOfBoundsException not thrown"); } - catch (IndexOutOfBoundsException iob) { - // Ok + catch(IndexOutOfBoundsException iob) + { + // Ok } - try { + try + { insertException.insert(1, itemOwned); fail("IllegalStateException not thrown if Item is owned"); } - catch (IllegalStateException ise) { - // Ok + catch(IllegalStateException ise) + { + // Ok } - try { + try + { insertException.insert(1, null); fail("NullPointerException not thrown if Item is null"); } - catch (NullPointerException npe) { - // Ok + catch(NullPointerException npe) + { + // Ok } } @@ -238,16 +266,19 @@ * Tests that delete() throws correct exception * in case of incorrect input. */ - public void testDeleteException() { + public void testDeleteException() + { Form deleteExForm = new Form("heder"); deleteExForm.append("string1"); deleteExForm.append("String2"); - try { + try + { deleteExForm.delete(2); fail("IndexOutOfBoundsException not thrown"); } - catch (IndexOutOfBoundsException e) { - // Ok + catch(IndexOutOfBoundsException e) + { + // Ok } } @@ -256,36 +287,43 @@ * Tests that set() throws correct exceptions * in case of incorrect input. */ - public void testSetException() { - Form setForm = new Form ("set Form"); + public void testSetException() + { + Form setForm = new Form("set Form"); setForm.append("string 1"); setForm.append("string 2"); Form formContainer = new Form("Form Title"); StringItem itemOwned = new StringItem("label", "text", 0); formContainer.append(itemOwned); - try { + try + { setForm.set(3, new StringItem(null, "text", 0)); fail("IndexOutOfBoundsException not thrown"); } - catch (IndexOutOfBoundsException e) { - // Ok + catch(IndexOutOfBoundsException e) + { + // Ok } - try { + try + { setForm.set(1, itemOwned); fail("IllegalStateException not thrown if Item is owned"); } - catch (IllegalStateException e) { - // Ok + catch(IllegalStateException e) + { + // Ok } - try { + try + { setForm.set(1, null); fail("NullPointerException not thrown if Item is null"); } - catch (NullPointerException npe) { - // Ok + catch(NullPointerException npe) + { + // Ok } } @@ -293,15 +331,18 @@ * Form.get() test. * Tests that get() throws correct exceptions in case of incorrect input. */ - public void testGetException () { + public void testGetException() + { Form getForm = new Form("getForm"); getForm.append("string1"); getForm.append("String2"); - try { + try + { getForm.get(2); fail("IndexOutOfBoundsException not thrown"); } - catch (IndexOutOfBoundsException e) { + catch(IndexOutOfBoundsException e) + { // Ok } } @@ -310,63 +351,72 @@ *Form.size() test. *Tests that size() returns correct result. */ - public void testSize() { + public void testSize() + { Form formSize = new Form("form header"); formSize.append("String 1"); formSize.append("String 2"); assertTrue("Form.size(). Expected return 2 but returned" - + formSize.size(), formSize.size() == 2); + + formSize.size(), formSize.size() == 2); } /** * Form deleteAll() test. * Tests that deleteAll() working properly */ - public void testDeleteAll() { + public void testDeleteAll() + { Form formDeleteAll = new Form("deleteaAll"); formDeleteAll.append("String 1"); formDeleteAll.append("String 2"); formDeleteAll.deleteAll(); assertTrue("Form.deleteAll(). Expected size() returns 0 but returned" - + formDeleteAll.size(), formDeleteAll.size() == 0); + + formDeleteAll.size(), formDeleteAll.size() == 0); } /** *Form.getWidth(),Form.getHeight() test. * */ - public void testGetWidthGetHeight () { - Form formGetWidthHeight = new Form ("getWidth() getHeight()"); + public void testGetWidthGetHeight() + { + Form formGetWidthHeight = new Form("getWidth() getHeight()"); int getWidth = 0; int getHeight = 0; getWidth = formGetWidthHeight.getWidth(); getHeight = formGetWidthHeight.getHeight(); assertTrue("Form.getWidth(),getHeight(). Expected return not 0 but" - + " returned width " + getWidth + " and height " + getHeight, - (getWidth != 0) && (getHeight != 0)); + + " returned width " + getWidth + " and height " + getHeight, + (getWidth != 0) && (getHeight != 0)); } /** * Enhanced test for IndexOutOfBoundsExceptions for Form.set(). */ - public void testFormSetIOOBExceptions () { + public void testFormSetIOOBExceptions() + { int []positions = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -256, -255, -1, 1, 255, 256, Integer.MAX_VALUE - 1, - Integer.MAX_VALUE, }; + Integer.MAX_VALUE, + }; Form f = new Form("Test"); f.append("stub"); - for (int i = 0; i < positions.length; i++) { - try { - f.set(positions[i], new StringItem("0", "1")); - fail("IndexOutOfBoundsException not thrown for value" - + positions[i]); - } - catch (IndexOutOfBoundsException e1) { - // Ok + for(int i = 0; i < positions.length; i++) + { + try + { + f.set(positions[i], new StringItem("0", "1")); + fail("IndexOutOfBoundsException not thrown for value" + + positions[i]); } - catch (Exception e) { + catch(IndexOutOfBoundsException e1) + { + // Ok + } + catch(Exception e) + { fail("Unexpected " + e); break; } @@ -376,17 +426,20 @@ /** * Enhanced test for NullPointerException in Form.set(). */ - public void testFormSetNPExceptions() { + public void testFormSetNPExceptions() + { Item[] items = {new StringItem("label", "text") }; Form f1 = null; f1 = new Form("Form 1", items); // Assign items to f1 - try { + try + { f1.set(0, null); fail("NullPointerException not thrown"); } - catch (NullPointerException e1) { + catch(NullPointerException e1) + { // Ok } } @@ -394,7 +447,8 @@ /** * enhanced test for IllegalStateException in Form.set(). */ - public void testFormSetISExceptions () { + public void testFormSetISExceptions() + { Item []items = {new StringItem("label", "text")}; Form f1 = null; Form f2 = null; @@ -403,11 +457,13 @@ f1 = new Form("Form 1"); f1.append("some"); - try { + try + { f1.set(0, items[0]); fail("IllegalStateException not thrown"); } - catch (IllegalStateException e1) { + catch(IllegalStateException e1) + { // Ok } } @@ -415,24 +471,29 @@ /** * Enhanced test for IndexOutOfBoundsException for Form.insert(). */ - public void testFormInsertIOOBExceptions () { + public void testFormInsertIOOBExceptions() + { int []positions = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -256, - -255, -1, 255, 256, Integer.MAX_VALUE - 1, - Integer.MAX_VALUE, - }; + -255, -1, 255, 256, Integer.MAX_VALUE - 1, + Integer.MAX_VALUE, + }; Form f = new Form("Test"); f.append("stub"); - for (int i = 0; i < positions.length; i++) { - try { + for(int i = 0; i < positions.length; i++) + { + try + { f.insert(positions[i], new StringItem("0", "1")); fail("IndexOutOfBoundsException not thrown for value" - + positions[i]); + + positions[i]); } - catch (IndexOutOfBoundsException e1) { - // Ok + catch(IndexOutOfBoundsException e1) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected " + e); } } @@ -441,17 +502,20 @@ /** * Enhanced test for NullPointerException for Form.insert(). */ - public void testFormInsertNPExceptions () { + public void testFormInsertNPExceptions() + { Item []items = {new StringItem("label", "text")}; Form f1 = null; f1 = new Form("Form 1", items); // Assign items to f1 - try { + try + { f1.insert(0, null); fail("NullPointerException not thrown"); } - catch (NullPointerException e1) { + catch(NullPointerException e1) + { // Ok } } @@ -459,7 +523,8 @@ /** * Enhanced test for IllegalStateException for Form.insert(). */ - public void testFormInsertISExceptions() { + public void testFormInsertISExceptions() + { Item []items = {new StringItem("label", "text")}; Form f1 = null; Form f2 = null; @@ -468,11 +533,13 @@ f1 = new Form("Form 1"); f1.append("stub"); - try { + try + { f1.insert(0, items[0]); fail("IllegalStateException not thrown"); } - catch (IllegalStateException e1) { + catch(IllegalStateException e1) + { // Ok } } @@ -480,24 +547,29 @@ /** * Enhanced test for IndexOutOfBoundsException for Form.get(). */ - public void testFormGetIOOBExceptions() { + public void testFormGetIOOBExceptions() + { int []positions = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -256, - -255, -1, 1, 255, 256, Integer.MAX_VALUE - 1, - Integer.MAX_VALUE, - }; + -255, -1, 1, 255, 256, Integer.MAX_VALUE - 1, + Integer.MAX_VALUE, + }; Form f = new Form("Test"); f.append("stub"); - for (int i = 0; i < positions.length; i++) { - try { + for(int i = 0; i < positions.length; i++) + { + try + { f.get(positions[i]); fail("IndexOutOfBoundsException not thrown for value" - + positions[i]); + + positions[i]); } - catch (IndexOutOfBoundsException e1) { - // Ok + catch(IndexOutOfBoundsException e1) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected " + e); } } @@ -506,24 +578,29 @@ /** * Enhanced test for IndexOutOfboundsException for form.delete(). */ - public void testFormDeleteIOOBExceptions () { + public void testFormDeleteIOOBExceptions() + { int []positions = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -256, - -255, -1, 1, 255, 256, Integer.MAX_VALUE - 1, - Integer.MAX_VALUE, - }; + -255, -1, 1, 255, 256, Integer.MAX_VALUE - 1, + Integer.MAX_VALUE, + }; Form form = new Form("Test"); form.append("stub"); - for (int i = 0; i < positions.length; i++) { - try { + for(int i = 0; i < positions.length; i++) + { + try + { form.delete(positions[i]); fail("IndexOutOfBoundsException not thrown for value" - + positions[i]); + + positions[i]); } - catch (IndexOutOfBoundsException e1) { - // Ok + catch(IndexOutOfBoundsException e1) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected " + e); } } @@ -532,7 +609,8 @@ /** * Enhanced test for IllegalStateException for form.delete(). */ - public void testFormAppendISExceptions () { + public void testFormAppendISExceptions() + { Item []items = {new StringItem("label", "text")}; Form f1 = null; Form f2 = null; @@ -540,11 +618,13 @@ f1 = new Form("Form 1", items); // Assign items to f1 f2 = new Form("Form 2"); // Assign items to f1 - try { + try + { f2.append(items[0]); fail("IllegalStateException not thrown"); } - catch (IllegalStateException e1) { + catch(IllegalStateException e1) + { // Ok } } @@ -552,15 +632,18 @@ /** * Enhanced Form.append() test. */ - public void testFormAppend() { + public void testFormAppend() + { String[] strings = {"string1", "string2", "string3" }; Form form = new Form("Title"); int ind = 0; - for (int j = 0; j < strings.length; j++) { + for(int j = 0; j < strings.length; j++) + { ind = form.append(strings[j]); - if (!(((StringItem) form.get(ind)).getText().equals(strings[j]))) { + if(!(((StringItem) form.get(ind)).getText().equals(strings[j]))) + { fail("Failed at " + j); } } @@ -570,18 +653,22 @@ * Enhanced test for Form.append(). * appending image to a form */ - public void testFormAppendImage() { + public void testFormAppendImage() + { Image image = null; - try { + try + { image = Image.createImage("100x100.png"); } - catch (Exception e) { + catch(Exception e) + { e.printStackTrace(); } Form form = new Form("Title"); int index = 0; index = form.append(image); - if (!(((ImageItem) form.get(index)).getImage() == image)) { + if(!(((ImageItem) form.get(index)).getImage() == image)) + { fail("Failed to append image"); } } @@ -589,20 +676,25 @@ /** * Enhanced test for Form (String title, Item [] items. */ - public void testFormConstructor() { + public void testFormConstructor() + { String title = "Title"; Item[][] items = {{}, null, }; Form form = null; - for (int j = 0; j < items.length; j++) { - try { + for(int j = 0; j < items.length; j++) + { + try + { form = new Form(title, items[j]); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected " + e); } - if (!(form.size() == 0)) { + if(!(form.size() == 0)) + { fail("Failed"); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/fullcanvas/FullCanvasTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/fullcanvas/FullCanvasTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/fullcanvas/FullCanvasTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.fullcanvas; @@ -31,12 +31,14 @@ *
            * Created: 2009-02-10 */ -public class FullCanvasTest extends SWTTestCase implements CommandListener { +public class FullCanvasTest extends SWTTestCase implements CommandListener +{ /** * Constructor. */ - public FullCanvasTest() { + public FullCanvasTest() + { } /** @@ -45,7 +47,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FullCanvasTest(String sTestName) { + public FullCanvasTest(String sTestName) + { super(sTestName); } @@ -55,64 +58,76 @@ * * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = FullCanvasTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FullCanvasTest((String)e.nextElement())); - } + // Add widget tests + methodNames = FullCanvasTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FullCanvasTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } - - public void commandAction(Command com, Displayable d) { + + public void commandAction(Command com, Displayable d) + { } /** * Tests basic functionality of FullCanvas methods. */ - public void testAccessors() { + public void testAccessors() + { TestFullCanvas fc = new TestFullCanvas(); Command c = new Command("test", "", Command.ITEM, 0); - try { + try + { fc.addCommand(c); fail("No IllegalStateException is thrown."); } - catch (IllegalStateException ex) { + catch(IllegalStateException ex) + { // OK } // Set null string and make sure an exception is thrown: - try { + try + { fc.setCommandListener(this); fail("No IllegalStateException is thrown."); } - catch (IllegalStateException ex) { + catch(IllegalStateException ex) + { } } } -class TestFullCanvas extends FullCanvas { - public void paint(Graphics g) { +class TestFullCanvas extends FullCanvas +{ + public void paint(Graphics g) + { // } } \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/CollisionDetectionTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/CollisionDetectionTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/CollisionDetectionTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -27,12 +27,14 @@ /** * Unit tests for LCDUI Sprite collision detection. */ -public class CollisionDetectionTest extends SWTTestCase { +public class CollisionDetectionTest extends SWTTestCase +{ /** * Constructor. */ - public CollisionDetectionTest() { + public CollisionDetectionTest() + { } /** @@ -41,7 +43,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public CollisionDetectionTest(String sTestName) { + public CollisionDetectionTest(String sTestName) + { super(sTestName); } @@ -51,23 +54,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = CollisionDetectionTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new CollisionDetectionTest((String)e.nextElement())); - } + // Add widget tests + methodNames = CollisionDetectionTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new CollisionDetectionTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testSpriteImageCollision"); methodNames.addElement("testSpriteSpriteCollision"); @@ -75,27 +81,31 @@ methodNames.addElement("testCollisionTransform"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testSpriteImageCollision")) testSpriteImageCollision(); - else if (getName().equals("testSpriteSpriteCollision")) testSpriteSpriteCollision(); - else if (getName().equals("testSpriteTiledLayerCollision")) testSpriteTiledLayerCollision(); - else if (getName().equals("testCollisionTransform")) testCollisionTransform(); + + protected void runTest() throws Throwable + { + if(getName().equals("testSpriteImageCollision")) testSpriteImageCollision(); + else if(getName().equals("testSpriteSpriteCollision")) testSpriteSpriteCollision(); + else if(getName().equals("testSpriteTiledLayerCollision")) testSpriteTiledLayerCollision(); + else if(getName().equals("testCollisionTransform")) testCollisionTransform(); else super.runTest(); } - + /** Tests collision between sprite and image. */ - public void testSpriteImageCollision() { + public void testSpriteImageCollision() + { Image image1 = null; Image image2 = null; - try { + try + { //100x100, 0,0, -> 50,50 full opaque, 0,50 -> 50,70 partially //transparent, other area full transparent. image1 = Image.createImage("opaqueTest.png"); image2 = Image.createImage("opaqueTest.png"); } - catch (java.io.IOException e) { + catch(java.io.IOException e) + { System.out.println(e); fail("" + e); } @@ -175,16 +185,19 @@ /** Tests collision between two sprites. */ - public void testSpriteSpriteCollision() { + public void testSpriteSpriteCollision() + { Image image1 = null; Image image2 = null; - try { + try + { //100x100, 0,0, -> 50,50 full opaque, 0,50 -> 50,70 partially //transparent, other area full transparent. image1 = Image.createImage("opaqueTest.png"); image2 = Image.createImage("opaqueTest.png"); } - catch (java.io.IOException e) { + catch(java.io.IOException e) + { System.out.println(e); fail("" + e); } @@ -278,17 +291,20 @@ /** Tests collision between sprite and TiledLayer. */ - public void testSpriteTiledLayerCollision() { + public void testSpriteTiledLayerCollision() + { Image image1 = null; Image image2 = null; TiledLayer tiledLayer = null; - try { + try + { //100x100, 0,0, -> 50,50 full opaque, 0,50 -> 50,70 partially //transparent, other area full transparent. image1 = Image.createImage("opaqueTest.png"); image2 = Image.createImage("opaqueTest.png"); } - catch (java.io.IOException e) { + catch(java.io.IOException e) + { fail(e.toString()); } @@ -372,9 +388,11 @@ } - public void testCollisionTransform() { + public void testCollisionTransform() + { int[] rgb1 = { 0xFF00FF00, 0xFF00FF00, 0x0000FF00, - 0x0000FF00, 0x0000FF00, 0xFF00FF00 }; + 0x0000FF00, 0x0000FF00, 0xFF00FF00 + }; // O O T // T T O @@ -384,7 +402,8 @@ int[] rgb2 = { 0xFF0000FF, 0x000000FF, 0x000000FF, 0xFF0000FF, - 0xFF0000FF, 0x000000FF, }; + 0xFF0000FF, 0x000000FF, + }; // O T // T O // O T @@ -395,13 +414,16 @@ sprite2.defineCollisionRectangle(1, 0, 1, 1); // should not get collision - one transparent, one opaque - for (int transform1 = 0; transform1 < 8; transform1++) { + for(int transform1 = 0; transform1 < 8; transform1++) + { sprite1.setTransform(transform1); - for (int transform2 = 0; transform2 < 8; transform2++) { + for(int transform2 = 0; transform2 < 8; transform2++) + { sprite2.setTransform(transform2); sprite2.setRefPixelPosition(0, 0); boolean result = !sprite1.collidesWith(sprite2, true); - if (!result) { + if(!result) + { print("1. Sprite should't collide with Sprite - frame 1"); fail("transform1=" + transform1 + " transform2=" + transform2); } @@ -411,12 +433,15 @@ sprite1.nextFrame(); // frame 2 sprite2.nextFrame(); // frame 2 // should always get collision - both opaque - for (int transform1 = 0; transform1 < 8; transform1++) { + for(int transform1 = 0; transform1 < 8; transform1++) + { sprite1.setTransform(transform1); - for (int transform2 = 0; transform2 < 8; transform2++) { + for(int transform2 = 0; transform2 < 8; transform2++) + { sprite2.setTransform(transform2); boolean result = sprite1.collidesWith(sprite2, true); - if (!result) { + if(!result) + { print("2. Sprite should collide with Sprite - frame 2"); fail("transform1=" + transform1 + " transform2=" + transform2); } @@ -426,12 +451,15 @@ sprite1.nextFrame(); // frame 3 sprite2.nextFrame(); // frame 3 // should not get collision - both transparent - for (int transform1 = 0; transform1 < 8; transform1++) { + for(int transform1 = 0; transform1 < 8; transform1++) + { sprite1.setTransform(transform1); - for (int transform2 = 0; transform2 < 8; transform2++) { + for(int transform2 = 0; transform2 < 8; transform2++) + { sprite2.setTransform(transform2); boolean result = !sprite1.collidesWith(sprite2, true); - if (!result) { + if(!result) + { print("3. Sprite should't collide with Sprite - frame 3"); fail("transform1=" + transform1 + " transform2=" + transform2); } @@ -443,11 +471,13 @@ Image image = Image.createRGBImage(rgb1, 1, 2, true); sprite2.setFrame(0); // should not get collision - sprite transparent - for (int transform = 0; transform < 8; transform++) { + for(int transform = 0; transform < 8; transform++) + { sprite2.setTransform(transform); sprite2.setRefPixelPosition(0, 0); boolean result = !sprite2.collidesWith(image, 0, 0, true); - if (!result) { + if(!result) + { print("4. Sprite should't collide with Image - frame 1"); fail("transform=" + transform); } @@ -455,11 +485,13 @@ sprite2.setFrame(1); // should get collision - sprite opaque - for (int transform = 0; transform < 8; transform++) { + for(int transform = 0; transform < 8; transform++) + { sprite2.setTransform(transform); sprite2.setRefPixelPosition(0, 0); boolean result = sprite2.collidesWith(image, 0, 0, true); - if (!result) { + if(!result) + { print("5. Sprite should collide with Image - frame 2"); fail("transform=" + transform); } @@ -476,11 +508,13 @@ sprite2.setFrame(0); // should not get collision - sprite transparent - for (int transform = 0; transform < 8; transform++) { + for(int transform = 0; transform < 8; transform++) + { sprite2.setTransform(transform); sprite2.setRefPixelPosition(0, 0); boolean result = !sprite2.collidesWith(tiledLayer, true); - if (!result) { + if(!result) + { print("6. Sprite should't collide with TiledLayer - frame 1"); fail("transform=" + transform); } @@ -488,11 +522,13 @@ sprite2.setFrame(1); // should get collision - sprite opaque - for (int transform = 0; transform < 8; transform++) { + for(int transform = 0; transform < 8; transform++) + { sprite2.setTransform(transform); sprite2.setRefPixelPosition(0, 0); boolean result = sprite2.collidesWith(tiledLayer, true); - if (!result) { + if(!result) + { print("7. Sprite should collide with TiledLayer - frame 2"); fail("transform=" + transform); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/GameCanvasTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/GameCanvasTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/GameCanvasTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -27,21 +27,23 @@ /** * GameCanvas non-interactive test. */ -public class GameCanvasTest extends SWTTestCase { +public class GameCanvasTest extends SWTTestCase +{ - Sprite iSprite = null; - int [] iRGB = - { - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF - }; + Sprite iSprite = null; + int [] iRGB = + { + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF + }; /** * Constructor. */ - public GameCanvasTest() { + public GameCanvasTest() + { } /** @@ -50,11 +52,13 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public GameCanvasTest(String sTestName) { + public GameCanvasTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); iSprite = new Sprite(Image.createRGBImage(iRGB, 4, 4, true)); } @@ -65,42 +69,47 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = GameCanvasTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new GameCanvasTest((String)e.nextElement())); - } + // Add widget tests + methodNames = GameCanvasTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new GameCanvasTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testGraphics"); methodNames.addElement("testPaint"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testGraphics")) testGraphics(); - else if (getName().equals("testPaint")) testPaint(); + + protected void runTest() throws Throwable + { + if(getName().equals("testGraphics")) testGraphics(); + else if(getName().equals("testPaint")) testPaint(); else super.runTest(); } /** - * Tests following methods:
            - * {@link javax.microedition.lcdui.game.GameCanvas#getGraphics}
            - * {@link javax.microedition.lcdui.game.GameCanvas#flushGraphics()}
            - * {@link javax.microedition.lcdui.game.GameCanvas#flushGraphics(int,int,int,int)}
            - */ - public void testGraphics() { + * Tests following methods:
            + * {@link javax.microedition.lcdui.game.GameCanvas#getGraphics}
            + * {@link javax.microedition.lcdui.game.GameCanvas#flushGraphics()}
            + * {@link javax.microedition.lcdui.game.GameCanvas#flushGraphics(int,int,int,int)}
            + */ + public void testGraphics() + { GameCanvasWithoutKeys canvas = new GameCanvasWithoutKeys(); Graphics g = canvas.getBufferGraphics(); @@ -111,7 +120,7 @@ assertEquals("Current color should be black", 0, g.getColor()); assertTrue("Font should be Font.getDefaultFont", (g.getFont()) - .equals(Font.getDefaultFont())); + .equals(Font.getDefaultFont())); assertEquals("Stroke should be SOLID", Graphics.SOLID, g.getStrokeStyle()); @@ -119,12 +128,13 @@ assertEquals("translateY should be 0", 0, g.getTranslateY()); } - /** - * Tests following methods:
            - * {@link javax.microedition.lcdui.game.GameCanvas#paint(javax.microedition.lcdui.Graphics)}
            - */ - public void testPaint() { - + /** + * Tests following methods:
            + * {@link javax.microedition.lcdui.game.GameCanvas#paint(javax.microedition.lcdui.Graphics)}
            + */ + public void testPaint() + { + // This test hangs (hang probably caused by GameCanvas command buffering), backlog item has been created. DISABLE_TEST(); @@ -148,11 +158,13 @@ imageGraphics = image.getGraphics(); // clip imageGraphics.setClip(0, 0, 1, 4); // first column is in, rest is out - int[] compare2 = { - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}; + int[] compare2 = + { + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF + }; testPaint("paint with clip", canvas, image, imageGraphics, compare2); // testing paint - using external mutable image as screen @@ -161,11 +173,13 @@ imageGraphics = image.getGraphics(); // clip imageGraphics.translate(0, -1); - int[] compare3 = { - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,}; + int[] compare3 = + { + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + }; testPaint("paint with translation", canvas, image, imageGraphics, compare3); // testing paint - using external mutable image as screen @@ -175,32 +189,35 @@ // clip imageGraphics.translate(0, -1); imageGraphics.setClip(0, 0, 2, 4); // first two columns are in, rest is out - int[] compare4 = { - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,}; + int[] compare4 = + { + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + }; testPaint("paint with translation and clip", - canvas, image, imageGraphics, compare4); + canvas, image, imageGraphics, compare4); } - /** - * Checks the painted image against provided rgb array. - * - * The area of interest is four by four pixels located at 0,0. - * - * Note that the buffer background in the area of interest will be initialized - * to white before painting {@link #iSprite} into it at 0,0. This should be - * taken into account when generating the array for comparison. - * - * @param screenGraphics The graphics object to paint the GameCanvas to. This - * graphics may have clip and translation set - * @param screen The image object that aScreenGraphics paints to. - * @param checkRGB An array of integers with expected values for the - * area of interest. - */ - private void testPaint(String msg, GameCanvasWithoutKeys canvas, - Image screen, Graphics screenGraphics, int[] expectedRGB) { + /** + * Checks the painted image against provided rgb array. + * + * The area of interest is four by four pixels located at 0,0. + * + * Note that the buffer background in the area of interest will be initialized + * to white before painting {@link #iSprite} into it at 0,0. This should be + * taken into account when generating the array for comparison. + * + * @param screenGraphics The graphics object to paint the GameCanvas to. This + * graphics may have clip and translation set + * @param screen The image object that aScreenGraphics paints to. + * @param checkRGB An array of integers with expected values for the + * area of interest. + */ + private void testPaint(String msg, GameCanvasWithoutKeys canvas, + Image screen, Graphics screenGraphics, int[] expectedRGB) + { Graphics bufferGraphics = canvas.getBufferGraphics(); @@ -219,8 +236,10 @@ screen.getRGB(actualRGB, 0, 4, 0, 0, 4, 4); // compare to the sprite image - for (int i = 0; i < 16; i++) { - if (actualRGB[i] != expectedRGB[i]) { + for(int i = 0; i < 16; i++) + { + if(actualRGB[i] != expectedRGB[i]) + { printRGB(actualRGB, 4, 4); printRGB(expectedRGB, 4, 4); fail(msg); @@ -228,70 +247,82 @@ } } - /** + /** * Prints out the image to standard output. If an image contains unexpected * colours, i.e. not those used to form images, this method will throw an * exception. This behaviour provides protection against hiding colour * discretization problem and reporting test error. */ - private void printRGB(int[] data, int w, int h) { + private void printRGB(int[] data, int w, int h) + { int odd = 0; - for (int i = 0; i < h; i++) { - for (int j = 0; j < w; j++) { + for(int i = 0; i < h; i++) + { + for(int j = 0; j < w; j++) + { int ind = i * w + j; String cha = " "; - switch (data[ind]) { - case 0xFFFFFFFF: - cha = "W"; - break; - case 0x00FFFFFF: - cha = "w"; - break; - case 0xFF000000: - cha = "B"; - break; - case 0x00000000: - cha = "b"; - break; - case 0xFF888888: - cha = "."; - break; - case 0x00888888: - cha = ","; - break; - default: { - cha = "U"; - odd = data[ind]; - } + switch(data[ind]) + { + case 0xFFFFFFFF: + cha = "W"; + break; + case 0x00FFFFFF: + cha = "w"; + break; + case 0xFF000000: + cha = "B"; + break; + case 0x00000000: + cha = "b"; + break; + case 0xFF888888: + cha = "."; + break; + case 0x00888888: + cha = ","; + break; + default: + { + cha = "U"; + odd = data[ind]; + } } System.out.print(cha); } System.out.println(""); } System.out.println(""); - if (odd != 0) { + if(odd != 0) + { fail("Unexpected colour in test image : 0x" + Integer.toHexString(odd)); } } - class GameCanvasWithKeys extends GameCanvas { + class GameCanvasWithKeys extends GameCanvas + { - public GameCanvasWithKeys() { + public GameCanvasWithKeys() + { super(false); } - public Graphics getTheGraphics() { + public Graphics getTheGraphics() + { return getGraphics(); } } - class GameCanvasWithoutKeys extends GameCanvas { + class GameCanvasWithoutKeys extends GameCanvas + { - public GameCanvasWithoutKeys() { + public GameCanvasWithoutKeys() + { super(true); } - public Graphics getBufferGraphics() { + public Graphics getBufferGraphics() + { return getGraphics(); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerManagerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerManagerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerManagerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -28,72 +28,74 @@ * Performs series of non-interactive tests on * {@link javax.microedition.lcdui.game.LayerManager} . */ -public class LayerManagerTest extends SWTTestCase { +public class LayerManagerTest extends SWTTestCase +{ - /** - * Layer manager to be used for all tests. - * Constructed during the first test, destroyed at cleanup. - */ - LayerManager iLayerManager = null; + /** + * Layer manager to be used for all tests. + * Constructed during the first test, destroyed at cleanup. + */ + LayerManager iLayerManager = null; - // image data - int [] iArgbDataWhite = new int[400]; - int [] iArgbDataBlack = new int[400]; + // image data + int [] iArgbDataWhite = new int[400]; + int [] iArgbDataBlack = new int[400]; - Sprite iSpriteWhite = null; - Sprite iSpriteBlack = null; + Sprite iSpriteWhite = null; + Sprite iSpriteBlack = null; - private static final int BLACK = 0xFF000000; - private static final int WHITE = 0xFFFFFFFF; - private static final int GREEN = 0xFF00FF00; + private static final int BLACK = 0xFF000000; + private static final int WHITE = 0xFFFFFFFF; + private static final int GREEN = 0xFF00FF00; - // Image data for creating a sprite - private byte[] iImgData40x30 = - { - 71, 73, 70, 56, 57, 97, 40, 0, 30, 0, -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, - 85, 0, 0, -86, 0, 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, - 0, 0, 44, 0, 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, 11, - -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, -23, 121, 33, 51, - 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, -96, -50, 117, 62, 93, -121, -29, - 9, 26, 63, -68, -59, 102, -71, 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, - -21, 104, -101, 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, - -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, -122, 124, 90, - 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, 76, 69, 66, 63, -111, 70, - -111, -116, 67, -114, 125, 114, -110, -103, 62, 57, 115, 60, 49, 108, 118, 119, - 120, 74, 55, -117, 60, 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, - -76, 72, -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, 28, - 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, -55, -72, -55, -112, - -115, -63, -60, 100, -47, -83, -120, -53, 80, 73, 21, -107, -108, 10, 77, -103, - -33, 17, 102, 10, -61, 78, 11, 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, - -10, -49, 1, -45, -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, - 35, 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, 115, -96, - -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, -109, -10, -96, 11, 49, - 66, 64, 2, 0, 59, 0, - }; + // Image data for creating a sprite + private byte[] iImgData40x30 = + { + 71, 73, 70, 56, 57, 97, 40, 0, 30, 0, -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, + 85, 0, 0, -86, 0, 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, + 0, 0, 44, 0, 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, 11, + -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, -23, 121, 33, 51, + 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, -96, -50, 117, 62, 93, -121, -29, + 9, 26, 63, -68, -59, 102, -71, 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, + -21, 104, -101, 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, + -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, -122, 124, 90, + 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, 76, 69, 66, 63, -111, 70, + -111, -116, 67, -114, 125, 114, -110, -103, 62, 57, 115, 60, 49, 108, 118, 119, + 120, 74, 55, -117, 60, 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, + -76, 72, -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, 28, + 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, -55, -72, -55, -112, + -115, -63, -60, 100, -47, -83, -120, -53, 80, 73, 21, -107, -108, 10, 77, -103, + -33, 17, 102, 10, -61, 78, 11, 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, + -10, -49, 1, -45, -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, + 35, 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, 115, -96, + -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, -109, -10, -96, 11, 49, + 66, 64, 2, 0, 59, 0, + }; - private byte[] iImgData120x10 = - { - 71, 73, 70, 56, 57, 97, 120, 0, 10, 0, -14, 0, 0, -128, -128, -128, 36, 0, - -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, - -7, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, - -36, -2, 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, - 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, -118, -73, - 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, -16, -104, 68, -51, -98, - -115, -99, 107, 74, -83, -18, -82, 60, 29, 78, 91, -69, 109, 7, -46, 87, 119, - 0, -115, -115, 70, -95, -13, -7, 82, 102, 28, -117, -110, -73, 114, 72, 23, - -74, -37, 97, -25, -3, 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, - 63, 37, 24, -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, - 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, -92, 6, -114, - 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, -124, -104, 99, 43, -82, 7, - 97, -85, 15, 85, 98, -77, -79, 100, -73, 13, -118, 108, -63, 21, 97, -90, 17, - -90, -56, 68, 111, 17, 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0 - }; + private byte[] iImgData120x10 = + { + 71, 73, 70, 56, 57, 97, 120, 0, 10, 0, -14, 0, 0, -128, -128, -128, 36, 0, + -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, + -7, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, + -36, -2, 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, + 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, -118, -73, + 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, -16, -104, 68, -51, -98, + -115, -99, 107, 74, -83, -18, -82, 60, 29, 78, 91, -69, 109, 7, -46, 87, 119, + 0, -115, -115, 70, -95, -13, -7, 82, 102, 28, -117, -110, -73, 114, 72, 23, + -74, -37, 97, -25, -3, 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, + 63, 37, 24, -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, + 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, -92, 6, -114, + 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, -124, -104, 99, 43, -82, 7, + 97, -85, 15, 85, 98, -77, -79, 100, -73, 13, -118, 108, -63, 21, 97, -90, 17, + -90, -56, 68, 111, 17, 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0 + }; /** * Constructor. */ - public LayerManagerTest() { + public LayerManagerTest() + { } /** @@ -102,13 +104,16 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public LayerManagerTest(String sTestName) { + public LayerManagerTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - for (int i = 0; i < 400; i++) { + for(int i = 0; i < 400; i++) + { iArgbDataWhite[i] = WHITE; // fully opaque white iArgbDataBlack[i] = BLACK; // fully opaque black } @@ -116,15 +121,16 @@ // Images are black and white inline with spec to allow tests // for devices without color capabilities iSpriteWhite = new Sprite(Image.createRGBImage(iArgbDataWhite, 20, 20, - true)); + true)); iSpriteBlack = new Sprite(Image.createRGBImage(iArgbDataBlack, 20, 20, - true)); + true)); // set sprite positions iSpriteWhite.setPosition(0, 0); iSpriteBlack.setPosition(10, 10); } - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { super.tearDown(); iLayerManager = null; iArgbDataBlack = null; @@ -139,96 +145,112 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = LayerManagerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new LayerManagerTest((String)e.nextElement())); - } + // Add widget tests + methodNames = LayerManagerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new LayerManagerTest((String)e.nextElement())); + } - return suite; - } - - public static java.util.Vector methodNames() { + return suite; + } + + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testLayers"); methodNames.addElement("testViewWindow"); methodNames.addElement("testPaint"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testLayers")) testLayers(); - else if (getName().equals("testViewWindow")) testViewWindow(); - else if (getName().equals("testPaint")) testPaint(); + + protected void runTest() throws Throwable + { + if(getName().equals("testLayers")) testLayers(); + else if(getName().equals("testViewWindow")) testViewWindow(); + else if(getName().equals("testPaint")) testPaint(); else super.runTest(); } /** - * Tests construction and Layer management methods. Specifically these - * methods are tested:
            - * {@link javax.microedition.lcdui.game.LayerManager#LayerManager} (trivial)
            - * {@link javax.microedition.lcdui.game.LayerManager#append}
            - * {@link javax.microedition.lcdui.game.LayerManager#insert}
            - * {@link javax.microedition.lcdui.game.LayerManager#remove}
            - * {@link javax.microedition.lcdui.game.LayerManager#getLayerAt}
            - * {@link javax.microedition.lcdui.game.LayerManager#getSize}
            - */ - public void testLayers() { + * Tests construction and Layer management methods. Specifically these + * methods are tested:
            + * {@link javax.microedition.lcdui.game.LayerManager#LayerManager} (trivial)
            + * {@link javax.microedition.lcdui.game.LayerManager#append}
            + * {@link javax.microedition.lcdui.game.LayerManager#insert}
            + * {@link javax.microedition.lcdui.game.LayerManager#remove}
            + * {@link javax.microedition.lcdui.game.LayerManager#getLayerAt}
            + * {@link javax.microedition.lcdui.game.LayerManager#getSize}
            + */ + public void testLayers() + { // make a layer (sprite) for testing Image img = Image.createImage(iImgData40x30, 0, iImgData40x30.length); Image img2 = Image.createImage(iImgData120x10, 0, iImgData120x10.length); Sprite sprite = new Sprite(img); Sprite anotherSprite = new Sprite(img2); - try { + try + { iLayerManager = new LayerManager(); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } - try { + try + { iLayerManager.insert(null, 0); fail("NullPointerException expected"); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.03 Insert layer - invalid index "); - try { + try + { iLayerManager.insert(sprite, -1); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.04 Insert layer - invalid index"); - try { + try + { iLayerManager.insert(sprite, 0); assertEquals(1, iLayerManager.getSize()); // sprite should not be removed if insert fails iLayerManager.insert(sprite, -1); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } @@ -236,81 +258,97 @@ assertEquals(1, iLayerManager.getSize()); // checking("Test 1.05 Insert layer - invalid index"); - try { + try + { iLayerManager.insert(sprite, 0); assertEquals(1, iLayerManager.getSize()); // sprite should not be removed if insert fails iLayerManager.insert(sprite, 2); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.05 Insert layer - layer not removed"); assertEquals(1, iLayerManager.getSize()); // checking("Test 1.06 Insert layer / getSize composite test"); - try { + try + { iLayerManager.insert(sprite, 0); // verify size assertEquals(1, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.07 Remove layer / getSize composite test"); - try { + try + { iLayerManager.remove(sprite); // verify size assertEquals(0, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.08 Append / getSize"); - try { + try + { iLayerManager.append(sprite); // verify size assertEquals(1, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.09 Insert same layer / remove composite test"); - try { + try + { iLayerManager.insert(sprite, 0); // verify size assertEquals(1, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.10 getLayerAt test - invalid index"); - try { + try + { iLayerManager.getLayerAt(-1); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.11 getLayerAt test "); - try { + try + { iLayerManager.append(anotherSprite); Layer layer = iLayerManager.getLayerAt(1); assertTrue(anotherSprite.equals(layer)); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } @@ -324,91 +362,111 @@ Sprite theLastSprite = new Sprite(img5); // Add some more layers - try { + try + { iLayerManager.append(yetAnotherSprite); iLayerManager.append(andAnotherSprite); assertEquals(4, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // Try to add a layer at one index too high - try { + try + { iLayerManager.insert(theLastSprite, 5); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // Try to add it at the end - try { + try + { iLayerManager.insert(theLastSprite, 4); assertEquals(5, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // Try to move anotherSprite past the end - try { + try + { iLayerManager.insert(anotherSprite, 5); fail("IndexOutOfBoundsException expected"); } - catch (IndexOutOfBoundsException ex) { + catch(IndexOutOfBoundsException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // Try to move anotherSprite to the end - try { + try + { iLayerManager.insert(anotherSprite, 4); assertEquals(5, iLayerManager.getSize()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } } - /** + /** * Checks for implementation specific issues in * {@link javax.microedition.lcdui.game.LayerManager#setViewWindow}. */ - public void testViewWindow() { + public void testViewWindow() + { iLayerManager = new LayerManager(); // checking("Test 2.01 Invoking with invalid parameter values - aWidth"); - try { + try + { iLayerManager.setViewWindow(10, 10, -1, 10); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 2.02 Invoking with invalid parameter values - aHeight"); - try { + try + { iLayerManager.setViewWindow(10, 10, 10, -1); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 2.03 View window"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -443,13 +501,15 @@ checkRGB("10,9", rgbData[10 + 9 * 20], WHITE, g); checkRGB("10,10", rgbData[10 + 10 * 20], BLACK, g); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 2.04 Test clipping - are layers outside the view window painted"); iLayerManager = new LayerManager(); - try { + try + { // This will be our background, mutable image for painting Image target = Image.createImage(50, 50); @@ -487,13 +547,15 @@ // black checkRGB("14,14", rgbData[14 + 14 * 20], WHITE, g); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 2.05 Preservation of Graphics translation during paint"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -520,13 +582,15 @@ assertEquals(-20, g.getTranslateX()); assertEquals(10, g.getTranslateY()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 2.06 Preservation of Graphics clipping during paint"); iLayerManager = new LayerManager(); - try { + try + { // This will be our background, mutable image for painting Image target = Image.createImage(50, 50); @@ -552,13 +616,15 @@ assertEquals(25, g.getClipX()); assertEquals(26, g.getClipY()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 2.07 Preservation of Graphics translation and clipping during paint"); iLayerManager = new LayerManager(); - try { + try + { // This will be our background, mutable image for painting Image target = Image.createImage(50, 50); @@ -584,7 +650,8 @@ assertEquals(-20, g.getTranslateX()); assertEquals(10, g.getTranslateY()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } } @@ -593,25 +660,30 @@ * Checks for implementation specific issues in * {@link javax.microedition.lcdui.game.LayerManager#paint}. */ - public void testPaint() { + public void testPaint() + { // make sure we use clean instance of LayerManager iLayerManager = new LayerManager(); // checking("Test 3.01 Testing invocation with invalid parameter values - g==null"); - try { + try + { iLayerManager.paint(null, 0, 10); fail("NullPointerException expected"); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { // pass } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 3.02 Z order"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -643,14 +715,16 @@ checkRGB("10,9", rgbData[10 + 9 * 20], WHITE, g); checkRGB("10,10", rgbData[10 + 10 * 20], BLACK, g); } - catch (Exception ex) { + catch(Exception ex) + { ex.printStackTrace(); fail("Exception " + ex); } // checking("Test 3.03 Graphics context translation"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -682,13 +756,15 @@ checkRGB("10,9", rgbData[10 + 9 * 20], WHITE, g); checkRGB("10,10", rgbData[10 + 10 * 20], BLACK, g); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 3.04 Preservation of Graphics translation during paint"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -712,13 +788,15 @@ assertEquals(-20, g.getTranslateX()); assertEquals(10, g.getTranslateY()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 3.05 Preservation of Graphics clipping during paint"); iLayerManager = new LayerManager(); - try { + try + { // This will be our background, mutable image for painting Image target = Image.createImage(50, 50); @@ -741,13 +819,15 @@ assertEquals(5, g.getClipX()); assertEquals(6, g.getClipY()); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 3.06 Test clipping - are layers outside the clip painted"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. @@ -788,13 +868,15 @@ // black checkRGB("14,14", rgbData[14 + 14 * 20], BLACK, g); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking("Test 3.07 Test clipping - are layers outside the view window painted"); iLayerManager = new LayerManager(); - try { + try + { // Paint few one-color sprites, then analyse the pixels to test // Z-order. // This will be our background, mutable image for painting @@ -835,7 +917,8 @@ // black // checkRGB("14,14", rgbData[14 + 14 * 20], BLACK, g); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } @@ -877,43 +960,52 @@ checkRGB("5,5", rgbData[5 + 5 * 20], BLACK, g); } - private void checkRGB(String aMsg, int aActualColor, int aExpectedColor, - Graphics aGraphics) { + private void checkRGB(String aMsg, int aActualColor, int aExpectedColor, + Graphics aGraphics) + { int expected = aGraphics.getDisplayColor(aExpectedColor); int actual = aActualColor & 0x00FFFFFF; - if (actual != expected) { + if(actual != expected) + { assertEquals(aMsg, Integer.toHexString(expected), - Integer.toHexString(actual)); + Integer.toHexString(actual)); } } - /** + /** * Prints out the image to standard output. If an image contains unexpected * colours, i.e. not those used to form images, this method will throw an * exception. This behaviour provides protection against hiding colour * discretization problem and reporting test error. */ - private void printRGB(int[] data, int w, int h, Graphics g) { + private void printRGB(int[] data, int w, int h, Graphics g) + { final int white = g.getDisplayColor(WHITE); final int black = g.getDisplayColor(BLACK); final int green = g.getDisplayColor(GREEN); int odd = 0; - for (int i = 0; i < h; i++) { - for (int j = 0; j < w; j++) { + for(int i = 0; i < h; i++) + { + for(int j = 0; j < w; j++) + { int ind = i * w + j; String cha = " "; int actual = data[ind] & 0x00FFFFFF; - if (actual == white) { + if(actual == white) + { cha = "W"; } - else if (actual == black) { + else if(actual == black) + { cha = "B"; } - else if (actual == green) { + else if(actual == green) + { cha = "."; } - else { + else + { cha = "U"; odd = data[ind]; } @@ -922,7 +1014,8 @@ System.out.println(""); } System.out.println(""); - if (odd != 0) { + if(odd != 0) + { fail("Unexpected color in test image : 0x" + Integer.toHexString(odd)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/LayerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -27,7 +27,8 @@ * Layer non-interactive tests.
            * Tests Layer methods visible through Sprite. */ -public class LayerTest extends SWTTestCase { +public class LayerTest extends SWTTestCase +{ Image iImage = null; @@ -36,7 +37,8 @@ /** * Constructor. */ - public LayerTest() { + public LayerTest() + { } /** @@ -45,17 +47,21 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public LayerTest(String sTestName) { + public LayerTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - int[] rgb = { - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF}; + int[] rgb = + { + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF + }; iImage = Image.createRGBImage(rgb, 4, 4, true); iSprite = new Sprite(iImage); } @@ -66,37 +72,42 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = LayerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new LayerTest((String)e.nextElement())); - } + // Add widget tests + methodNames = LayerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new LayerTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testSprites"); methodNames.addElement("testVisible"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testSprites")) testSprites(); - else if (getName().equals("testVisible")) testVisible(); + + protected void runTest() throws Throwable + { + if(getName().equals("testSprites")) testSprites(); + else if(getName().equals("testVisible")) testVisible(); else super.runTest(); } - - - public void testSprites() { + + + public void testSprites() + { // checking("Test 1.01 getWidth"); assertEquals(4, iSprite.getWidth()); @@ -133,7 +144,8 @@ /** * 4.0 visible test. This is in addition to */ - public void testVisible() { + public void testVisible() + { // checking("Test 4.0 set/isVisible test"); iSprite = new Sprite(iImage); assertTrue("Is the sprite visible by default?", iSprite.isVisible()); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/SpriteTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/SpriteTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/SpriteTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -30,7 +30,8 @@ * @resource com/symbian/tests/javax/microedition/lcdui/game/fly_small.png * @resource com/symbian/tests/javax/microedition/lcdui/game/fly_large.png */ -public class SpriteTest extends SWTTestCase { +public class SpriteTest extends SWTTestCase +{ // data used to create Sprite with 6 frames. int iFrameCount6 = 6; @@ -51,116 +52,123 @@ int iFrameWidth24 = 5; int iFrameHeight24 = 10; int[] iDefaultSeq24 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23}; + 15, 16, 17, 18, 19, 20, 21, 22, 23 + }; int[] iCustomSeq24 = {0, 1, 1}; // data used to create Images // image has width 40, height 30 private byte[] iImgData40x30 = {71, 73, 70, 56, 57, 97, 40, 0, 30, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, - 11, -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, - -23, 121, 33, 51, 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, - -96, -50, 117, 62, 93, -121, -29, 9, 26, 63, -68, -59, 102, -71, - 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, -21, 104, -101, - 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, - -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, - -122, 124, 90, 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, - 76, 69, 66, 63, -111, 70, -111, -116, 67, -114, 125, 114, -110, - -103, 62, 57, 115, 60, 49, 108, 118, 119, 120, 74, 55, -117, 60, - 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, -76, 72, - -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, - 28, 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, - -55, -72, -55, -112, -115, -63, -60, 100, -47, -83, -120, -53, 80, - 73, 21, -107, -108, 10, 77, -103, -33, 17, 102, 10, -61, 78, 11, - 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, -10, -49, 1, -45, - -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, 35, - 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, - 115, -96, -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, - -109, -10, -96, 11, 49, 66, 64, 2, 0, 59, 0,}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, + 11, -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, + -23, 121, 33, 51, 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, + -96, -50, 117, 62, 93, -121, -29, 9, 26, 63, -68, -59, 102, -71, + 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, -21, 104, -101, + 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, + -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, + -122, 124, 90, 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, + 76, 69, 66, 63, -111, 70, -111, -116, 67, -114, 125, 114, -110, + -103, 62, 57, 115, 60, 49, 108, 118, 119, 120, 74, 55, -117, 60, + 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, -76, 72, + -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, + 28, 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, + -55, -72, -55, -112, -115, -63, -60, 100, -47, -83, -120, -53, 80, + 73, 21, -107, -108, 10, 77, -103, -33, 17, 102, 10, -61, 78, 11, + 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, -10, -49, 1, -45, + -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, 35, + 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, + 115, -96, -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, + -109, -10, -96, 11, 49, 66, 64, 2, 0, 59, 0, + }; // image has width 120, height 10 private byte[] iImgData120x10 = {71, 73, 70, 56, 57, 97, 120, 0, 10, 0, - -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, - 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, - 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, -36, -2, - 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, - 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, - -118, -73, 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, - -16, -104, 68, -51, -98, -115, -99, 107, 74, -83, -18, -82, 60, 29, - 78, 91, -69, 109, 7, -46, 87, 119, 0, -115, -115, 70, -95, -13, -7, - 82, 102, 28, -117, -110, -73, 114, 72, 23, -74, -37, 97, -25, -3, - 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, 63, 37, 24, - -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, - 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, - -92, 6, -114, 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, - -124, -104, 99, 43, -82, 7, 97, -85, 15, 85, 98, -77, -79, 100, - -73, 13, -118, 108, -63, 21, 97, -90, 17, -90, -56, 68, 111, 17, - 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0}; + -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, + 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, + 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, -36, -2, + 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, + 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, + -118, -73, 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, + -16, -104, 68, -51, -98, -115, -99, 107, 74, -83, -18, -82, 60, 29, + 78, 91, -69, 109, 7, -46, 87, 119, 0, -115, -115, 70, -95, -13, -7, + 82, 102, 28, -117, -110, -73, 114, 72, 23, -74, -37, 97, -25, -3, + 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, 63, 37, 24, + -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, + 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, + -92, 6, -114, 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, + -124, -104, 99, 43, -82, 7, 97, -85, 15, 85, 98, -77, -79, 100, + -73, 13, -118, 108, -63, 21, 97, -90, 17, -90, -56, 68, 111, 17, + 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0 + }; // image has width 20, height 60 private byte[] iImgData20x60 = {71, 73, 70, 56, 57, 97, 20, 0, 60, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 20, 0, 60, 0, 2, 3, -1, 120, -86, 102, 87, -123, -60, 89, - -122, 24, -117, 57, 40, 59, -76, 88, -42, 60, -109, 87, 93, -39, - 49, 114, -27, -121, -118, 91, 43, -99, -31, -78, -54, 110, -83, - -111, -34, 12, 10, -126, -44, -31, 2, -4, -3, -128, 66, 34, -47, 8, - 12, -90, -108, 76, 11, -14, 41, -115, 54, -109, -43, -91, -46, - -103, -127, 106, 45, -103, 14, 97, 17, 48, -108, 71, 66, 49, -39, - -36, 112, -92, 35, 99, 69, -7, -20, 78, -87, -27, 108, -76, 29, - -66, -90, 11, 15, 119, 7, 115, 109, 11, 46, 11, 87, 10, 2, 115, - -123, 39, -121, 83, 67, -117, 10, -122, -119, -113, -118, 102, - -116, 96, -108, 92, -106, 1, -104, -101, -107, -111, 36, -103, 67, - -96, -105, 127, 23, 3, -87, 69, -85, 68, 84, -87, 89, 94, -82, -86, - 94, -83, 93, -81, -80, 89, -78, -72, -85, -70, -84, -71, 67, 53, - 117, -108, -65, 47, 42, 79, -79, -64, 54, -57, -60, -63, -53, -68, - -55, 12, -50, -75, -59, -62, -92, -52, 11, -86, -77, 22, 13, 1, 5, - -119, 53, -39, 89, -36, -34, -48, 7, -31, -85, -29, -33, -40, 32, - -30, 102, -28, -59, -25, 68, -23, -27, -15, -37, -18, 93, 40, -38, - 25, 16, -53, -26, 85, -5, -28, 28, 97, -48, -57, -88, 31, 65, 73, - 1, -121, -7, 43, 2, -48, -32, -65, -126, 84, 24, -46, 57, 83, 38, - 34, -118, -119, -36, -86, 65, 17, -44, -122, 45, -94, -58, 127, 24, - -39, 88, -60, 16, -78, -94, 45, -119, 29, 51, 118, -103, 19, 105, - 64, 27, 110, 43, -51, -76, 124, 105, 42, 17, 75, 83, 46, 95, 118, - 58, 116, 115, 103, -50, -114, 49, 3, -52, -44, -103, 0, 0, 59, 0}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 20, 0, 60, 0, 2, 3, -1, 120, -86, 102, 87, -123, -60, 89, + -122, 24, -117, 57, 40, 59, -76, 88, -42, 60, -109, 87, 93, -39, + 49, 114, -27, -121, -118, 91, 43, -99, -31, -78, -54, 110, -83, + -111, -34, 12, 10, -126, -44, -31, 2, -4, -3, -128, 66, 34, -47, 8, + 12, -90, -108, 76, 11, -14, 41, -115, 54, -109, -43, -91, -46, + -103, -127, 106, 45, -103, 14, 97, 17, 48, -108, 71, 66, 49, -39, + -36, 112, -92, 35, 99, 69, -7, -20, 78, -87, -27, 108, -76, 29, + -66, -90, 11, 15, 119, 7, 115, 109, 11, 46, 11, 87, 10, 2, 115, + -123, 39, -121, 83, 67, -117, 10, -122, -119, -113, -118, 102, + -116, 96, -108, 92, -106, 1, -104, -101, -107, -111, 36, -103, 67, + -96, -105, 127, 23, 3, -87, 69, -85, 68, 84, -87, 89, 94, -82, -86, + 94, -83, 93, -81, -80, 89, -78, -72, -85, -70, -84, -71, 67, 53, + 117, -108, -65, 47, 42, 79, -79, -64, 54, -57, -60, -63, -53, -68, + -55, 12, -50, -75, -59, -62, -92, -52, 11, -86, -77, 22, 13, 1, 5, + -119, 53, -39, 89, -36, -34, -48, 7, -31, -85, -29, -33, -40, 32, + -30, 102, -28, -59, -25, 68, -23, -27, -15, -37, -18, 93, 40, -38, + 25, 16, -53, -26, 85, -5, -28, 28, 97, -48, -57, -88, 31, 65, 73, + 1, -121, -7, 43, 2, -48, -32, -65, -126, 84, 24, -46, 57, 83, 38, + 34, -118, -119, -36, -86, 65, 17, -44, -122, 45, -94, -58, 127, 24, + -39, 88, -60, 16, -78, -94, 45, -119, 29, 51, 118, -103, 19, 105, + 64, 27, 110, 43, -51, -76, 124, 105, 42, 17, 75, 83, 46, 95, 118, + 58, 116, 115, 103, -50, -114, 49, 3, -52, -44, -103, 0, 0, 59, 0 + }; // image has width 60, height 20 private byte[] iImgData60x20 = {71, 73, 70, 56, 57, 97, 60, 0, 20, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 60, 0, 20, 0, 2, 3, -26, 120, -70, -52, -10, -113, -107, - 57, -119, -91, -27, 82, 75, 112, 30, -96, 32, -128, -125, -48, - -100, 14, 100, 72, 24, -41, 118, -101, -74, -111, 34, 125, -120, - 56, -86, 47, 120, 88, -9, 37, 96, -112, 6, -60, -115, -116, -90, - -99, -114, -60, 108, -42, 66, 68, 90, 20, -86, -28, -64, 50, -42, - -62, 46, -64, 125, 112, 3, -86, -16, 74, -71, -77, -102, 93, 59, - -79, 58, -84, 108, 17, 119, 72, 35, -68, -10, -11, 118, -73, -28, - -59, -76, -76, 31, -7, -92, 127, 80, -127, 32, 121, 60, 79, 77, 76, - 113, 126, 61, 69, 63, 79, 61, 55, -112, -123, 86, 107, 98, 117, - 108, 75, 54, 12, 64, 105, 16, -123, -111, 71, -113, -114, -117, 63, - 13, -100, 58, 117, -97, -128, 67, -126, -84, 124, -90, 79, 59, -85, - -121, 126, 65, 70, 68, 16, 96, 118, 30, -80, 126, 115, 72, 62, -75, - -82, -75, 34, -107, -68, -65, -74, -124, 122, -119, -93, -54, 100, - -57, -97, -122, 66, -60, 73, 10, -105, 106, 93, -107, 16, -43, 100, - -115, -95, -66, 11, -41, 94, -71, -70, 6, -27, -39, -26, -74, -33, - -50, -47, -107, 86, -86, -102, 58, 61, -105, 117, -12, 119, 12, 76, - -38, 42, -11, 74, -13, -39, -11, -24, 60, 109, -86, -95, 111, 77, - 2, 0, 59, 0}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 60, 0, 20, 0, 2, 3, -26, 120, -70, -52, -10, -113, -107, + 57, -119, -91, -27, 82, 75, 112, 30, -96, 32, -128, -125, -48, + -100, 14, 100, 72, 24, -41, 118, -101, -74, -111, 34, 125, -120, + 56, -86, 47, 120, 88, -9, 37, 96, -112, 6, -60, -115, -116, -90, + -99, -114, -60, 108, -42, 66, 68, 90, 20, -86, -28, -64, 50, -42, + -62, 46, -64, 125, 112, 3, -86, -16, 74, -71, -77, -102, 93, 59, + -79, 58, -84, 108, 17, 119, 72, 35, -68, -10, -11, 118, -73, -28, + -59, -76, -76, 31, -7, -92, 127, 80, -127, 32, 121, 60, 79, 77, 76, + 113, 126, 61, 69, 63, 79, 61, 55, -112, -123, 86, 107, 98, 117, + 108, 75, 54, 12, 64, 105, 16, -123, -111, 71, -113, -114, -117, 63, + 13, -100, 58, 117, -97, -128, 67, -126, -84, 124, -90, 79, 59, -85, + -121, 126, 65, 70, 68, 16, 96, 118, 30, -80, 126, 115, 72, 62, -75, + -82, -75, 34, -107, -68, -65, -74, -124, 122, -119, -93, -54, 100, + -57, -97, -122, 66, -60, 73, 10, -105, 106, 93, -107, 16, -43, 100, + -115, -95, -66, 11, -41, 94, -71, -70, 6, -27, -39, -26, -74, -33, + -50, -47, -107, 86, -86, -102, 58, 61, -105, 117, -12, 119, 12, 76, + -38, 42, -11, 74, -13, -39, -11, -24, 60, 109, -86, -95, 111, 77, + 2, 0, 59, 0 + }; // create images from byte array data - private Image[] iImages = { - Image.createImage(iImgData60x20, 0, iImgData60x20.length), // grid - Image.createImage(iImgData40x30, 0, iImgData40x30.length), // grid - Image.createImage(iImgData120x10, 0, iImgData120x10.length), // vertical - Image.createImage(iImgData20x60, 0, iImgData20x60.length), // horizontal + private Image[] iImages = + { + Image.createImage(iImgData60x20, 0, iImgData60x20.length), // grid + Image.createImage(iImgData40x30, 0, iImgData40x30.length), // grid + Image.createImage(iImgData120x10, 0, iImgData120x10.length), // vertical + Image.createImage(iImgData20x60, 0, iImgData20x60.length), // horizontal }; /** * Constructor. */ - public SpriteTest() { + public SpriteTest() + { } /** @@ -169,7 +177,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SpriteTest(String sTestName) { + public SpriteTest(String sTestName) + { super(sTestName); } @@ -179,23 +188,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = SpriteTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SpriteTest((String)e.nextElement())); - } + // Add widget tests + methodNames = SpriteTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SpriteTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testFrameSequences"); @@ -204,76 +216,91 @@ methodNames.addElement("testChangeImage"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testFrameSequences")) testFrameSequences(); - else if (getName().equals("testFrameSequenceRotation")) testFrameSequenceRotation(); - else if (getName().equals("testRotations")) testRotations(); - else if (getName().equals("testChangeImage")) testChangeImage(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testFrameSequences")) testFrameSequences(); + else if(getName().equals("testFrameSequenceRotation")) testFrameSequenceRotation(); + else if(getName().equals("testRotations")) testRotations(); + else if(getName().equals("testChangeImage")) testChangeImage(); else super.runTest(); } - - + + /** * 1.0 Sprite - Construction Test */ - public void testConstructors() { + public void testConstructors() + { Image image = iImages[0]; int frameWidth = iFrameWidth6; int frameHeight = iFrameHeight6; Sprite sprite; // checking("Test 1.01 Construct with frame width=0"); - try { + try + { sprite = new Sprite(image, 0, frameHeight); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.02 Construct with frame height=0"); - try { + try + { sprite = new Sprite(image, frameWidth, 0); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.03 Construct with incorrect frame width for image"); - try { + try + { // image width is not an integer multiple of the frameWidth int wrongWidth = image.getWidth() / 2 + 1; sprite = new Sprite(image, wrongWidth, frameHeight); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.04 Construct with incorrect frame height for image"); - try { + try + { // image height is not an integer multiple of the frameHeight int wrongHeight = image.getHeight() / 2 + 1; sprite = new Sprite(image, frameWidth, wrongHeight); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.05 Construct with correct frame size"); - for (int i = 0; i < iImages.length; i++) { + for(int i = 0; i < iImages.length; i++) + { Image img = iImages[i]; // single frame runConstructTest(img, img.getWidth(), img.getHeight(), 1); @@ -303,17 +330,18 @@ assertEquals("getY()", clone.getY(), sprite.getY()); assertTrue("isVisible()", clone.isVisible() == sprite.isVisible()); assertEquals("getRawFrameCount ", clone.getRawFrameCount(), sprite - .getRawFrameCount()); + .getRawFrameCount()); assertEquals("getFrame()", clone.getFrame(), sprite.getFrame()); assertEquals("getFrameSequenceLength()", - clone.getFrameSequenceLength(), sprite.getFrameSequenceLength()); + clone.getFrameSequenceLength(), sprite.getFrameSequenceLength()); assertEquals("getRefPixelX()", clone.getRefPixelX(), sprite - .getRefPixelX()); + .getRefPixelX()); assertEquals("getRefPixelY()", clone.getRefPixelY(), sprite - .getRefPixelY()); + .getRefPixelY()); assertTrue("isVisible()", clone.isVisible() == sprite.isVisible()); // check frame sequence - for (int i = 0; i < iCustomSeq6.length; i++) { + for(int i = 0; i < iCustomSeq6.length; i++) + { int frOriginal = sprite.getFrame(); int frClone = clone.getFrame(); assertEquals("frame sequence, frame:" + i, frOriginal, frClone); @@ -323,7 +351,8 @@ } private void runConstructTest(Image img, int frameWidth, int frameHeight, - int frameCount) { + int frameCount) + { Sprite sprite = new Sprite(img, frameWidth, frameHeight); assertEquals("getRawFrameCount ", frameCount, sprite.getRawFrameCount()); assertEquals("getWidth ", frameWidth, sprite.getWidth()); @@ -333,7 +362,8 @@ /** * 2.0 Sprite - Frame Sequence Test */ - public void testFrameSequences() { + public void testFrameSequences() + { int aFrameWidth = 4; int aFrameHeight = 4; int[] argb = new int[48]; @@ -341,17 +371,21 @@ // the image will contain three frames // first 4x4 frame is black, second frame is white, // third frame has vertical stripes white/black/white/black - for (int i = 0; i < 48; i++) { + for(int i = 0; i < 48; i++) + { int x = i % 12; - if (x < 4) { + if(x < 4) + { argb[i] = 0xFF000000; } - else if (x < 8) { + else if(x < 8) + { argb[i] = 0xFFFFFFFF; } - else { + else + { int c = x % 2; - if (c == 0) + if(c == 0) argb[i] = 0xFFFFFFFF; else argb[i] = 0xFF000000; @@ -359,7 +393,7 @@ } Image aImage = Image.createRGBImage(argb, aFrameWidth * 3, - aFrameHeight, true); + aFrameHeight, true); Sprite sprite = new Sprite(aImage, aFrameWidth, aFrameHeight); // check methods @@ -415,68 +449,84 @@ // checking("2.02 Checking custom frame sequence"); // checking(" 2.02.01 setFrameSequence - invalid parameters - array len is 0"); - try { + try + { sprite.setFrameSequence(new int[0]); fail("IllegalArgumentException expected"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { } // pass - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } int[] newFs = {0, 2, -1}; // checking(" 2.02.02 setFrameSequence - invalid parameters - array contains negative numbers"); - try { + try + { sprite.setFrameSequence(newFs); fail("ArrayIndexOutOfBoundsException expected"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { } // pass - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } int[] newFs1 = {0, 5, 1}; newFs = newFs1; // checking(" 2.02.03 setFrameSequence - invalid parameters - array contains too large frame index "); - try { + try + { sprite.setFrameSequence(newFs); fail("ArrayIndexOutOfBoundsException expected"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { } // pass - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } int[] tmpFs2 = {0, 2, 1, 0, 2, 1}; newFs = tmpFs2; // checking(" 2.02.04 setFrameSequence - valid parameters"); - try { + try + { sprite.setFrameSequence(newFs); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } int[] newFs2 = {0, 2, 1}; newFs = newFs2; // checking(" 2.02.04a setFrameSequence - valid sequence of different length"); - try { + try + { sprite.setFrameSequence(newFs); } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // is passed null, frame sequence must be reset to default // checking(" 2.02.05 setFrameSequence - null argument"); - try { - try { + try + { + try + { sprite.setFrameSequence(null); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } // checking(" 2.02.05 Frame 0"); @@ -499,17 +549,20 @@ verifyImage(sprite, 0); // 0 defines the frame to check } - catch (Exception exx) { + catch(Exception exx) + { exx.printStackTrace(); fail("Exception " + exx); } // checking(" 2.02.05 Setting back to custom"); // set it back to custom - try { + try + { sprite.setFrameSequence(newFs); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } @@ -545,7 +598,8 @@ verifyImage(sprite, 2); // 0 defines the frame to check } - private void verifyImage(Sprite aSprite, int aInd) { + private void verifyImage(Sprite aSprite, int aInd) + { // checking( "Verifying image :" + aInd ); Image image = Image.createImage(4, 4); Graphics g = image.getGraphics(); @@ -554,34 +608,44 @@ int[] rgb = new int[16]; image.getRGB(rgb, 0, 4, 0, 0, 4, 4); // compare the data - if (aInd < 2) { + if(aInd < 2) + { // solid black or white int color; - if (aInd == 0) { + if(aInd == 0) + { color = 0xFF000000; } - else { + else + { color = 0xFFFFFFFF; } - for (int j = 0; j < 16; j++) { - if (rgb[j] != color) { + for(int j = 0; j < 16; j++) + { + if(rgb[j] != color) + { // failed printRGB(rgb, 4, 4); } assertEquals("Rgb[" + j + "]", color, rgb[j]); } } - else if (aInd == 2) { - for (int j = 0; j < 16; j++) { + else if(aInd == 2) + { + for(int j = 0; j < 16; j++) + { int color; - if ((j % 2) == 0) { + if((j % 2) == 0) + { color = 0xFFFFFFFF; } - else { + else + { color = 0xFF000000; } - if (rgb[j] != color) { + if(rgb[j] != color) + { // failed printRGB(rgb, 4, 4); } @@ -593,25 +657,29 @@ /** * 2.1 Sprite - Frame Sequence Rotation Test */ - public void testFrameSequenceRotation() { + public void testFrameSequenceRotation() + { int aFrameWidth = 4; int aFrameHeight = 4; // frame1 black int[] argb1 = new int[16]; - for (int i = 0; i < 16; i++) { + for(int i = 0; i < 16; i++) + { argb1[i] = 0xFF000000; } // frame 2 white int[] argb2 = new int[16]; - for (int i = 0; i < 16; i++) { + for(int i = 0; i < 16; i++) + { argb2[i] = 0xFFFFFFFF; } // frame 3 black / white int[] argb3 = new int[16]; - for (int i = 0; i < 16; i++) { + for(int i = 0; i < 16; i++) + { argb3[i] = 0xFF000000; } argb3[5] = 0xFFFFFFFF; @@ -621,7 +689,8 @@ // frame 4 white / black int[] argb4 = new int[16]; - for (int i = 0; i < 16; i++) { + for(int i = 0; i < 16; i++) + { argb4[i] = 0xFFFFFFFF; } argb4[5] = 0xFF000000; @@ -634,7 +703,7 @@ // bottom left 4x4 is black with white 2x2 centre // bottom right 4x4 is white with black 2x2 centre Image image = createImage2(argb1, argb2, argb3, argb4, aFrameWidth, - aFrameHeight); + aFrameHeight); Sprite sprite = new Sprite(image, aFrameWidth, aFrameHeight); @@ -676,7 +745,8 @@ * displayed should always be the same, irrespective of transform. */ private void checkTransformedImage(Sprite aSprite, int[] aData0, - int[] aData1, int[] aData2, int[] aData3) { + int[] aData1, int[] aData2, int[] aData3) + { aSprite.setFrame(0); verifyImage2(aSprite, aData0); aSprite.setFrame(1); @@ -691,15 +761,16 @@ * Creates a 8x8 image */ private Image createImage2(int[] aData1, int[] aData2, int[] aData3, - int[] aData4, int aFrameWidth, int aFrameHeight) { + int[] aData4, int aFrameWidth, int aFrameHeight) + { Image frame1 = Image.createRGBImage(aData1, aFrameWidth, aFrameHeight, - true); + true); Image frame2 = Image.createRGBImage(aData2, aFrameWidth, aFrameHeight, - true); + true); Image frame3 = Image.createRGBImage(aData3, aFrameWidth, aFrameHeight, - true); + true); Image frame4 = Image.createRGBImage(aData4, aFrameWidth, aFrameHeight, - true); + true); Image frameImage = Image.createImage(aFrameWidth * 2, aFrameHeight * 2); Graphics g = frameImage.getGraphics(); @@ -707,7 +778,7 @@ g.drawImage(frame2, aFrameWidth, 0, Graphics.TOP | Graphics.LEFT); g.drawImage(frame3, 0, aFrameHeight, Graphics.TOP | Graphics.LEFT); g.drawImage(frame4, aFrameWidth, aFrameHeight, Graphics.TOP - | Graphics.LEFT); + | Graphics.LEFT); return frameImage; } @@ -715,7 +786,8 @@ * Checks images used in frame sequence rotation tests aData is the RGB data * used to create the Sprite frame */ - private void verifyImage2(Sprite aSprite, int[] aData) { + private void verifyImage2(Sprite aSprite, int[] aData) + { // draw Sprite to mutable Image Image image = Image.createImage(4, 4); Graphics g = image.getGraphics(); @@ -728,14 +800,17 @@ image.getRGB(rgb, 0, 4, 0, 0, 4, 4); int length = rgb.length; - if (length != aData.length) { + if(length != aData.length) + { // failed printRGB(rgb, 4, 4); } assertEquals("length", rgb.length, aData.length); - for (int i = 0; i < length; i++) { - if (rgb[i] != aData[i]) { + for(int i = 0; i < length; i++) + { + if(rgb[i] != aData[i]) + { // failed printRGB(rgb, 4, 4); } @@ -747,7 +822,8 @@ /** * 3.0 Sprite - Rotation Test */ - public void testRotations() { + public void testRotations() + { // checking("Test 3.01 Rotate Sprite with no reference pixel"); doRotation(0, 0); @@ -781,14 +857,17 @@ * - Rotation and mirroring (pixel by pixel checking)
            * The test is designed to catch one-out errors. */ - private void doRotation(int aRefX, int aRefY) { + private void doRotation(int aRefX, int aRefY) + { int[] transforms = {Sprite.TRANS_NONE, Sprite.TRANS_ROT90, - Sprite.TRANS_ROT180, Sprite.TRANS_ROT270, Sprite.TRANS_MIRROR, - Sprite.TRANS_MIRROR_ROT90, Sprite.TRANS_MIRROR_ROT180, - Sprite.TRANS_MIRROR_ROT270}; + Sprite.TRANS_ROT180, Sprite.TRANS_ROT270, Sprite.TRANS_MIRROR, + Sprite.TRANS_MIRROR_ROT90, Sprite.TRANS_MIRROR_ROT180, + Sprite.TRANS_MIRROR_ROT270 + }; String[] transformNames = {"TRANS_NONE", "TRANS_ROT90", "TRANS_ROT180", - "TRANS_ROT270", "TRANS_MIRROR", "TRANS_MIRROR_ROT90", - "TRANS_MIRROR_ROT180", "TRANS_MIRROR_ROT270"}; + "TRANS_ROT270", "TRANS_MIRROR", "TRANS_MIRROR_ROT90", + "TRANS_MIRROR_ROT180", "TRANS_MIRROR_ROT270" + }; Image image = null; Sprite sprite = null; @@ -798,77 +877,91 @@ // WWbb // Wbbb int[] imageData = {0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFF000000}; + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFF000000 + }; - int[][] transData = { - { - // TRANS_NONE - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFF000000}, - { - // TRANS_ROT90 - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000}, - { - // TRANS_ROT180 - 0xFF000000, 0xFF000000, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000}, - { - // TRANS_ROT270 - 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, - { - // TRANS_MIRROR - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, - 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFF000000, 0xFF000000, 0xFFFFFFFF}, - { - // TRANS_MIRROR_ROT90 - 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000, - 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000}, - { - // TRANS_MIRROR_ROT180 - 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFF000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000}, - { - // TRANS_MIRROR_ROT270 - 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, - 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000}}; + int[][] transData = + { + { + // TRANS_NONE + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFF000000 + }, + { + // TRANS_ROT90 + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000 + }, + { + // TRANS_ROT180 + 0xFF000000, 0xFF000000, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000 + }, + { + // TRANS_ROT270 + 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF + }, + { + // TRANS_MIRROR + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, + 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFF000000, 0xFF000000, 0xFFFFFFFF + }, + { + // TRANS_MIRROR_ROT90 + 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000, + 0xFF000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000 + }, + { + // TRANS_MIRROR_ROT180 + 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFF000000, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000 + }, + { + // TRANS_MIRROR_ROT270 + 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000, + 0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000 + } + }; - try { + try + { // make images and sprites // checking("createRGBImage"); image = Image.createRGBImage(imageData, 4, 4, true); } - catch (Exception ex) { + catch(Exception ex) + { fail("Exception " + ex); } - for (int i = 0; i < transforms.length; i++) { + for(int i = 0; i < transforms.length; i++) + { sprite = new Sprite(image, 4, 4); sprite.defineReferencePixel(aRefX, aRefY); sprite.setRefPixelPosition(20, 20); Point okTopLeft = transform(transforms[i], new Point(sprite.getX(), - sprite.getY()), new Point(sprite.getRefPixelY(), sprite - .getRefPixelX())); + sprite.getY()), new Point(sprite.getRefPixelY(), sprite + .getRefPixelX())); sprite.setTransform(transforms[i]); Image rgb = Image.createImage(40, 40); @@ -878,47 +971,51 @@ // is the top left point ok? // checking("is the top left point ok?"); - if (okTopLeft.x != spriteTopLeft.x - || okTopLeft.y != spriteTopLeft.y) { + if(okTopLeft.x != spriteTopLeft.x + || okTopLeft.y != spriteTopLeft.y) + { rotationTestFailure("Sprite's TL pixel has not been preserved. It is at : (" - + spriteTopLeft.x - + "," - + spriteTopLeft.y - + "), should be at (" - + okTopLeft.x - + "," - + okTopLeft.y - + ")." - + "\nReference at (" - + sprite.getRefPixelX() - + "," - + sprite.getRefPixelY() - + ").\n" - + "Transform " - + transformNames[i]); + + spriteTopLeft.x + + "," + + spriteTopLeft.y + + "), should be at (" + + okTopLeft.x + + "," + + okTopLeft.y + + ")." + + "\nReference at (" + + sprite.getRefPixelX() + + "," + + sprite.getRefPixelY() + + ").\n" + + "Transform " + + transformNames[i]); } // did the reference pixel change position? // checking("did the reference pixel change position?"); - if (sprite.getRefPixelX() != 20 || sprite.getRefPixelY() != 20) { + if(sprite.getRefPixelX() != 20 || sprite.getRefPixelY() != 20) + { rotationTestFailure("Sprite's reference pixel has not been preserved. It is at : (" - + sprite.getRefPixelX() - + "," - + sprite.getRefPixelY() - + "), should be at (20,20).\n" - + "Sprite location (" - + spriteTopLeft.x - + "," - + spriteTopLeft.y - + ").\n" - + "Transform " + transformNames[i]); + + sprite.getRefPixelX() + + "," + + sprite.getRefPixelY() + + "), should be at (20,20).\n" + + "Sprite location (" + + spriteTopLeft.x + + "," + + spriteTopLeft.y + + ").\n" + + "Transform " + transformNames[i]); } // get a 4x4 image and compare // checking("get a 4x4 image and compare"); int[] comp = new int[16]; rgb.getRGB(comp, 0, 4, spriteTopLeft.x, spriteTopLeft.y, 4, 4); - for (int j = 0; j < 16; j++) { - if (comp[j] != transData[i][j]) { + for(int j = 0; j < 16; j++) + { + if(comp[j] != transData[i][j]) + { // checking("Comparison failed while testing transform " // + transformNames[i] +" on pixel " + j ); // checking("Should be : " ); @@ -926,7 +1023,7 @@ // checking("Is : " ); printRGB(comp, 4, 4); rotationTestFailure("Comparison failed while testing transform " - + transformNames[i] + " on pixel " + j); + + transformNames[i] + " on pixel " + j); } } } @@ -935,12 +1032,15 @@ private boolean iReportRotationErrors = true; - private void rotationTestFailure(String aMessage) { + private void rotationTestFailure(String aMessage) + { // checking("rotationTestFailure " + aMessage); - if (iReportRotationErrors) { + if(iReportRotationErrors) + { fail(aMessage); } - else { + else + { System.out.println("\n\n" + aMessage); } } @@ -954,57 +1054,69 @@ * @param sprite transformed sprite * @return the location upper-left corner of the transformed sprite */ - private Point transform(int aTransform, Point aPos, Point aRefPix) { - switch (aTransform) { - case Sprite.TRANS_NONE: { - return new Point(aPos.x, aPos.y); - } - case Sprite.TRANS_ROT90: { - // sprite top-left - int xp = aPos.x; - int yp = aPos.y; - int xr = aRefPix.x; - int yr = aRefPix.y; - int dx = xp - xr; - int dy = yp - yr; - int x = xr - dy - 3; - int y = yr + dx; - return new Point(x, y); - } - case Sprite.TRANS_ROT180: { - Point tmp = transform(Sprite.TRANS_ROT90, aPos, aRefPix); - return transform(Sprite.TRANS_ROT90, tmp, aRefPix); - } - case Sprite.TRANS_ROT270: { - Point tmp = transform(Sprite.TRANS_ROT180, aPos, aRefPix); - return transform(Sprite.TRANS_ROT90, tmp, aRefPix); - } - case Sprite.TRANS_MIRROR: { - int nx = 2 * aRefPix.x - aPos.x - 3; - int ny = aPos.y; - return new Point(nx, ny); - } - case Sprite.TRANS_MIRROR_ROT90: { - Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); - return transform(Sprite.TRANS_ROT90, tmp, aRefPix); - } - case Sprite.TRANS_MIRROR_ROT180: { - Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); - return transform(Sprite.TRANS_ROT180, tmp, aRefPix); - } - case Sprite.TRANS_MIRROR_ROT270: { - Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); - return transform(Sprite.TRANS_ROT270, tmp, aRefPix); - } - default: - return null; + private Point transform(int aTransform, Point aPos, Point aRefPix) + { + switch(aTransform) + { + case Sprite.TRANS_NONE: + { + return new Point(aPos.x, aPos.y); + } + case Sprite.TRANS_ROT90: + { + // sprite top-left + int xp = aPos.x; + int yp = aPos.y; + int xr = aRefPix.x; + int yr = aRefPix.y; + int dx = xp - xr; + int dy = yp - yr; + int x = xr - dy - 3; + int y = yr + dx; + return new Point(x, y); + } + case Sprite.TRANS_ROT180: + { + Point tmp = transform(Sprite.TRANS_ROT90, aPos, aRefPix); + return transform(Sprite.TRANS_ROT90, tmp, aRefPix); + } + case Sprite.TRANS_ROT270: + { + Point tmp = transform(Sprite.TRANS_ROT180, aPos, aRefPix); + return transform(Sprite.TRANS_ROT90, tmp, aRefPix); + } + case Sprite.TRANS_MIRROR: + { + int nx = 2 * aRefPix.x - aPos.x - 3; + int ny = aPos.y; + return new Point(nx, ny); + } + case Sprite.TRANS_MIRROR_ROT90: + { + Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); + return transform(Sprite.TRANS_ROT90, tmp, aRefPix); + } + case Sprite.TRANS_MIRROR_ROT180: + { + Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); + return transform(Sprite.TRANS_ROT180, tmp, aRefPix); + } + case Sprite.TRANS_MIRROR_ROT270: + { + Point tmp = transform(Sprite.TRANS_MIRROR, aPos, aRefPix); + return transform(Sprite.TRANS_ROT270, tmp, aRefPix); + } + default: + return null; } } - class Point { + class Point + { public int x, y; - public Point(int x, int y) { + public Point(int x, int y) + { this.x = x; this.y = y; } @@ -1013,7 +1125,8 @@ /** * 4.0 Sprite - Change Image Test */ - public void testChangeImage() { + public void testChangeImage() + { int currentFrame = 3; // checking("Test 4.01 Change Sprite image: same frames, default sequence"); @@ -1023,7 +1136,7 @@ // will be updated to be the default frame sequence for the new frame // set Sprite sprite = createSprite(iImages[0], iFrameWidth12, iFrameHeight12, - null, currentFrame); + null, currentFrame); sprite.setImage(iImages[1], iFrameWidth12, iFrameHeight12); checkFrames(sprite, iDefaultSeq12, currentFrame); @@ -1032,7 +1145,7 @@ // Check If a custom frame sequence has been defined, it will remain // unchanged. sprite = createSprite(iImages[0], iFrameWidth12, iFrameHeight12, - iCustomSeq12, currentFrame); + iCustomSeq12, currentFrame); sprite.setImage(iImages[2], iFrameWidth12, iFrameHeight12); checkFrames(sprite, iCustomSeq12, currentFrame); @@ -1043,7 +1156,7 @@ // will be updated to be the default frame sequence for the new frame // set sprite = createSprite(iImages[0], iFrameWidth12, iFrameHeight12, null, - currentFrame); + currentFrame); sprite.setImage(iImages[3], iFrameWidth24, iFrameHeight24); checkFrames(sprite, iDefaultSeq24, currentFrame); @@ -1052,7 +1165,7 @@ // Check If a custom frame sequence has been defined, it will remain // unchanged. sprite = createSprite(iImages[1], iFrameWidth12, iFrameHeight12, - iCustomSeq12, currentFrame); + iCustomSeq12, currentFrame); sprite.setImage(iImages[2], iFrameWidth24, iFrameHeight24); checkFrames(sprite, iCustomSeq12, currentFrame); @@ -1060,7 +1173,7 @@ // Check The current frame will be reset to entry 0 // Check revert to the default frame sequence for the new frame set. sprite = createSprite(iImages[1], iFrameWidth12, iFrameHeight12, null, - currentFrame); + currentFrame); sprite.setImage(iImages[3], iFrameWidth6, iFrameHeight6); checkFrames(sprite, iDefaultSeq6, 0); @@ -1068,15 +1181,16 @@ // Check The current frame will be reset to entry 0 // Check default sequence updated sprite = createSprite(iImages[2], iFrameWidth12, iFrameHeight12, - iCustomSeq12, currentFrame); + iCustomSeq12, currentFrame); sprite.setImage(iImages[3], iFrameWidth6, iFrameHeight6); checkFrames(sprite, iDefaultSeq6, 0); } private Sprite createSprite(Image aImage, int aFrameWidth, - int aFrameHeight, int[] aCustomSeq, int aCurrentFrame) { + int aFrameHeight, int[] aCustomSeq, int aCurrentFrame) + { Sprite sprite = new Sprite(aImage, aFrameWidth, aFrameHeight); - if (aCustomSeq != null) + if(aCustomSeq != null) sprite.setFrameSequence(aCustomSeq); sprite.setFrame(aCurrentFrame); return sprite; @@ -1084,48 +1198,54 @@ // checks current frame and frame sequence length private void checkFrames(Sprite sprite, int[] expectedSeq, - int expectedCurrentFrame) { + int expectedCurrentFrame) + { assertEquals("Current frame", expectedCurrentFrame, sprite.getFrame()); assertEquals("getFrameSequenceLength()", expectedSeq.length, sprite - .getFrameSequenceLength()); + .getFrameSequenceLength()); } /** * Utility methods used by all tests */ - private void printRGB(int[] aData, int aWidth, int aHeight) { + private void printRGB(int[] aData, int aWidth, int aHeight) + { // checking("printRGB:"); StringBuffer sb = new StringBuffer(aWidth); - for (int i = 0; i < aHeight; i++) { + for(int i = 0; i < aHeight; i++) + { sb.setLength(0); - for (int j = 0; j < aWidth; j++) { + for(int j = 0; j < aWidth; j++) + { int ind = i * aWidth + j; String cha = " "; - switch (aData[ind]) { - case 0xFFFFFFFF: - cha = "W"; - break; // opaque white - case 0x00FFFFFF: - cha = "w"; - break; // trans white - case 0xFF000000: - cha = "B"; - break; // opaque black - case 0x00000000: - cha = "b"; - break; // trans black - case 0xFFFF0000: - cha = "R"; - break; // opaque red - case 0xFF00FF00: - cha = "G"; - break; // opaque green - case 0xFF0000FF: - cha = "Bl"; - break;// opaque blue - default: { - sb.append("[" + Integer.toHexString(aData[ind]) + "]"); - } + switch(aData[ind]) + { + case 0xFFFFFFFF: + cha = "W"; + break; // opaque white + case 0x00FFFFFF: + cha = "w"; + break; // trans white + case 0xFF000000: + cha = "B"; + break; // opaque black + case 0x00000000: + cha = "b"; + break; // trans black + case 0xFFFF0000: + cha = "R"; + break; // opaque red + case 0xFF00FF00: + cha = "G"; + break; // opaque green + case 0xFF0000FF: + cha = "Bl"; + break;// opaque blue + default: + { + sb.append("[" + Integer.toHexString(aData[ind]) + "]"); + } } sb.append(cha); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/TiledLayerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/TiledLayerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/game/TiledLayerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.game; @@ -26,109 +26,115 @@ /** * TiledLayer non interactive tests */ -public class TiledLayerTest extends SWTTestCase { +public class TiledLayerTest extends SWTTestCase +{ // data used to create Images // image has width 40, height 30 private byte[] iImgData40x30 = {71, 73, 70, 56, 57, 97, 40, 0, 30, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, - 11, -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, - -23, 121, 33, 51, 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, - -96, -50, 117, 62, 93, -121, -29, 9, 26, 63, -68, -59, 102, -71, - 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, -21, 104, -101, - 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, - -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, - -122, 124, 90, 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, - 76, 69, 66, 63, -111, 70, -111, -116, 67, -114, 125, 114, -110, - -103, 62, 57, 115, 60, 49, 108, 118, 119, 120, 74, 55, -117, 60, - 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, -76, 72, - -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, - 28, 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, - -55, -72, -55, -112, -115, -63, -60, 100, -47, -83, -120, -53, 80, - 73, 21, -107, -108, 10, 77, -103, -33, 17, 102, 10, -61, 78, 11, - 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, -10, -49, 1, -45, - -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, 35, - 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, - 115, -96, -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, - -109, -10, -96, 11, 49, 66, 64, 2, 0, 59, 0,}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 40, 0, 30, 0, 2, 3, -1, 120, -70, 107, -66, 37, 18, 18, + 11, -107, -41, -114, 33, -74, 96, -32, -31, 24, 16, 86, 101, -45, + -23, 121, 33, 51, 46, 83, 44, -49, 113, -79, 110, -121, -96, -73, + -96, -50, 117, 62, 93, -121, -29, 9, 26, 63, -68, -59, 102, -71, + 28, 58, 111, -49, 80, -51, -110, 10, 5, 2, -122, -21, 104, -101, + 100, 76, 107, 86, -84, 118, -5, -24, 42, 104, 85, 16, 121, 77, + -110, 78, 88, 61, 96, 39, -76, 116, 96, -53, 46, 9, -100, 33, 20, + -122, 124, 90, 90, 86, 73, 80, -123, 68, -121, 79, -121, 3, 93, 62, + 76, 69, 66, 63, -111, 70, -111, -116, 67, -114, 125, 114, -110, + -103, 62, 57, 115, 60, 49, 108, 118, 119, 120, 74, 55, -117, 60, + 21, -95, -93, 47, 32, 43, 11, -100, 106, -92, 113, -102, -76, 72, + -99, -89, 12, -126, 60, -122, -119, -98, -73, 116, -120, 80, -112, + 28, 118, 118, 21, 5, -81, -66, -91, -67, -113, 78, -59, 89, -57, + -55, -72, -55, -112, -115, -63, -60, 100, -47, -83, -120, -53, 80, + 73, 21, -107, -108, 10, 77, -103, -33, 17, 102, 10, -61, 78, 11, + 99, 91, -85, 100, -74, 127, -101, -66, -19, 119, -10, -49, 1, -45, + -77, -109, -20, -93, -9, 89, -8, 104, -95, 91, 19, -125, -48, 35, + 113, 93, -38, 25, 0, -73, -117, -120, -68, 1, -127, -60, 72, 108, + 115, -96, -114, 42, 49, 15, 35, 102, 89, 37, 45, 11, -108, 71, 7, + -109, -10, -96, 11, 49, 66, 64, 2, 0, 59, 0, + }; // image has width 120, height 10 private byte[] iImgData120x10 = {71, 73, 70, 56, 57, 97, 120, 0, 10, 0, - -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, - 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, - 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, -36, -2, - 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, - 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, - -118, -73, 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, - -16, -104, 68, -51, -98, -115, -99, 107, 74, -83, -18, -82, 60, 29, - 78, 91, -69, 109, 7, -46, 87, 119, 0, -115, -115, 70, -95, -13, -7, - 82, 102, 28, -117, -110, -73, 114, 72, 23, -74, -37, 97, -25, -3, - 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, 63, 37, 24, - -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, - 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, - -92, 6, -114, 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, - -124, -104, 99, 43, -82, 7, 97, -85, 15, 85, 98, -77, -79, 100, - -73, 13, -118, 108, -63, 21, 97, -90, 17, -90, -56, 68, 111, 17, - 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0}; + -14, 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, + 109, -1, 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, + 0, 44, 0, 0, 0, 0, 120, 0, 10, 0, 66, 3, -75, 120, -70, -36, -2, + 38, -54, -7, 78, -71, 56, -109, -51, -77, -18, -34, -59, -127, -95, + 72, 12, 104, 42, -84, 66, -86, 10, 85, 44, 47, 44, -21, -42, 43, + -118, -73, 105, 21, -4, -64, -119, -48, -16, 27, 2, 3, 70, -92, + -16, -104, 68, -51, -98, -115, -99, 107, 74, -83, -18, -82, 60, 29, + 78, 91, -69, 109, 7, -46, 87, 119, 0, -115, -115, 70, -95, -13, -7, + 82, 102, 28, -117, -110, -73, 114, 72, 23, -74, -37, 97, -25, -3, + 64, -51, 77, -57, 94, 125, 88, 54, 127, 44, 73, 73, 63, 37, 24, + -125, 48, 123, -114, 121, 96, 95, -112, 88, -126, 126, 94, -109, + 87, 40, -118, 27, -107, -115, 119, -116, 88, -113, 95, 114, 19, + -92, 6, -114, 63, 50, -112, -114, 117, -114, -86, -110, 95, 92, + -124, -104, 99, 43, -82, 7, 97, -85, 15, 85, 98, -77, -79, 100, + -73, 13, -118, 108, -63, 21, 97, -90, 17, -90, -56, 68, 111, 17, + 50, -68, 117, -47, -46, -52, 76, -52, 9, 0, 59, 0 + }; // image has width 20, height 60 private byte[] iImgData20x60 = {71, 73, 70, 56, 57, 97, 20, 0, 60, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 20, 0, 60, 0, 2, 3, -1, 120, -86, 102, 87, -123, -60, 89, - -122, 24, -117, 57, 40, 59, -76, 88, -42, 60, -109, 87, 93, -39, - 49, 114, -27, -121, -118, 91, 43, -99, -31, -78, -54, 110, -83, - -111, -34, 12, 10, -126, -44, -31, 2, -4, -3, -128, 66, 34, -47, 8, - 12, -90, -108, 76, 11, -14, 41, -115, 54, -109, -43, -91, -46, - -103, -127, 106, 45, -103, 14, 97, 17, 48, -108, 71, 66, 49, -39, - -36, 112, -92, 35, 99, 69, -7, -20, 78, -87, -27, 108, -76, 29, - -66, -90, 11, 15, 119, 7, 115, 109, 11, 46, 11, 87, 10, 2, 115, - -123, 39, -121, 83, 67, -117, 10, -122, -119, -113, -118, 102, - -116, 96, -108, 92, -106, 1, -104, -101, -107, -111, 36, -103, 67, - -96, -105, 127, 23, 3, -87, 69, -85, 68, 84, -87, 89, 94, -82, -86, - 94, -83, 93, -81, -80, 89, -78, -72, -85, -70, -84, -71, 67, 53, - 117, -108, -65, 47, 42, 79, -79, -64, 54, -57, -60, -63, -53, -68, - -55, 12, -50, -75, -59, -62, -92, -52, 11, -86, -77, 22, 13, 1, 5, - -119, 53, -39, 89, -36, -34, -48, 7, -31, -85, -29, -33, -40, 32, - -30, 102, -28, -59, -25, 68, -23, -27, -15, -37, -18, 93, 40, -38, - 25, 16, -53, -26, 85, -5, -28, 28, 97, -48, -57, -88, 31, 65, 73, - 1, -121, -7, 43, 2, -48, -32, -65, -126, 84, 24, -46, 57, 83, 38, - 34, -118, -119, -36, -86, 65, 17, -44, -122, 45, -94, -58, 127, 24, - -39, 88, -60, 16, -78, -94, 45, -119, 29, 51, 118, -103, 19, 105, - 64, 27, 110, 43, -51, -76, 124, 105, 42, 17, 75, 83, 46, 95, 118, - 58, 116, 115, 103, -50, -114, 49, 3, -52, -44, -103, 0, 0, 59, 0}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 20, 0, 60, 0, 2, 3, -1, 120, -86, 102, 87, -123, -60, 89, + -122, 24, -117, 57, 40, 59, -76, 88, -42, 60, -109, 87, 93, -39, + 49, 114, -27, -121, -118, 91, 43, -99, -31, -78, -54, 110, -83, + -111, -34, 12, 10, -126, -44, -31, 2, -4, -3, -128, 66, 34, -47, 8, + 12, -90, -108, 76, 11, -14, 41, -115, 54, -109, -43, -91, -46, + -103, -127, 106, 45, -103, 14, 97, 17, 48, -108, 71, 66, 49, -39, + -36, 112, -92, 35, 99, 69, -7, -20, 78, -87, -27, 108, -76, 29, + -66, -90, 11, 15, 119, 7, 115, 109, 11, 46, 11, 87, 10, 2, 115, + -123, 39, -121, 83, 67, -117, 10, -122, -119, -113, -118, 102, + -116, 96, -108, 92, -106, 1, -104, -101, -107, -111, 36, -103, 67, + -96, -105, 127, 23, 3, -87, 69, -85, 68, 84, -87, 89, 94, -82, -86, + 94, -83, 93, -81, -80, 89, -78, -72, -85, -70, -84, -71, 67, 53, + 117, -108, -65, 47, 42, 79, -79, -64, 54, -57, -60, -63, -53, -68, + -55, 12, -50, -75, -59, -62, -92, -52, 11, -86, -77, 22, 13, 1, 5, + -119, 53, -39, 89, -36, -34, -48, 7, -31, -85, -29, -33, -40, 32, + -30, 102, -28, -59, -25, 68, -23, -27, -15, -37, -18, 93, 40, -38, + 25, 16, -53, -26, 85, -5, -28, 28, 97, -48, -57, -88, 31, 65, 73, + 1, -121, -7, 43, 2, -48, -32, -65, -126, 84, 24, -46, 57, 83, 38, + 34, -118, -119, -36, -86, 65, 17, -44, -122, 45, -94, -58, 127, 24, + -39, 88, -60, 16, -78, -94, 45, -119, 29, 51, 118, -103, 19, 105, + 64, 27, 110, 43, -51, -76, 124, 105, 42, 17, 75, 83, 46, 95, 118, + 58, 116, 115, 103, -50, -114, 49, 3, -52, -44, -103, 0, 0, 59, 0 + }; // image has width 60, height 20 private byte[] iImgData60x20 = {71, 73, 70, 56, 57, 97, 60, 0, 20, 0, -14, - 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, - 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, - 0, 0, 0, 60, 0, 20, 0, 2, 3, -26, 120, -70, -52, -10, -113, -107, - 57, -119, -91, -27, 82, 75, 112, 30, -96, 32, -128, -125, -48, - -100, 14, 100, 72, 24, -41, 118, -101, -74, -111, 34, 125, -120, - 56, -86, 47, 120, 88, -9, 37, 96, -112, 6, -60, -115, -116, -90, - -99, -114, -60, 108, -42, 66, 68, 90, 20, -86, -28, -64, 50, -42, - -62, 46, -64, 125, 112, 3, -86, -16, 74, -71, -77, -102, 93, 59, - -79, 58, -84, 108, 17, 119, 72, 35, -68, -10, -11, 118, -73, -28, - -59, -76, -76, 31, -7, -92, 127, 80, -127, 32, 121, 60, 79, 77, 76, - 113, 126, 61, 69, 63, 79, 61, 55, -112, -123, 86, 107, 98, 117, - 108, 75, 54, 12, 64, 105, 16, -123, -111, 71, -113, -114, -117, 63, - 13, -100, 58, 117, -97, -128, 67, -126, -84, 124, -90, 79, 59, -85, - -121, 126, 65, 70, 68, 16, 96, 118, 30, -80, 126, 115, 72, 62, -75, - -82, -75, 34, -107, -68, -65, -74, -124, 122, -119, -93, -54, 100, - -57, -97, -122, 66, -60, 73, 10, -105, 106, 93, -107, 16, -43, 100, - -115, -95, -66, 11, -41, 94, -71, -70, 6, -27, -39, -26, -74, -33, - -50, -47, -107, 86, -86, -102, 58, 61, -105, 117, -12, 119, 12, 76, - -38, 42, -11, 74, -13, -39, -11, -24, 60, 109, -86, -95, 111, 77, - 2, 0, 59, 0}; + 0, 0, -128, -128, -128, 36, 0, -1, 0, 0, 85, 0, 0, -86, 0, 109, -1, + 0, -110, -1, 73, 0, -1, 0, 0, -1, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, + 0, 0, 0, 60, 0, 20, 0, 2, 3, -26, 120, -70, -52, -10, -113, -107, + 57, -119, -91, -27, 82, 75, 112, 30, -96, 32, -128, -125, -48, + -100, 14, 100, 72, 24, -41, 118, -101, -74, -111, 34, 125, -120, + 56, -86, 47, 120, 88, -9, 37, 96, -112, 6, -60, -115, -116, -90, + -99, -114, -60, 108, -42, 66, 68, 90, 20, -86, -28, -64, 50, -42, + -62, 46, -64, 125, 112, 3, -86, -16, 74, -71, -77, -102, 93, 59, + -79, 58, -84, 108, 17, 119, 72, 35, -68, -10, -11, 118, -73, -28, + -59, -76, -76, 31, -7, -92, 127, 80, -127, 32, 121, 60, 79, 77, 76, + 113, 126, 61, 69, 63, 79, 61, 55, -112, -123, 86, 107, 98, 117, + 108, 75, 54, 12, 64, 105, 16, -123, -111, 71, -113, -114, -117, 63, + 13, -100, 58, 117, -97, -128, 67, -126, -84, 124, -90, 79, 59, -85, + -121, 126, 65, 70, 68, 16, 96, 118, 30, -80, 126, 115, 72, 62, -75, + -82, -75, 34, -107, -68, -65, -74, -124, 122, -119, -93, -54, 100, + -57, -97, -122, 66, -60, 73, 10, -105, 106, 93, -107, 16, -43, 100, + -115, -95, -66, 11, -41, 94, -71, -70, 6, -27, -39, -26, -74, -33, + -50, -47, -107, 86, -86, -102, 58, 61, -105, 117, -12, 119, 12, 76, + -38, 42, -11, 74, -13, -39, -11, -24, 60, 109, -86, -95, 111, 77, + 2, 0, 59, 0 + }; // create images from byte array data - Image[] iImages = { - Image.createImage(iImgData60x20, 0, iImgData60x20.length), // grid - Image.createImage(iImgData40x30, 0, iImgData40x30.length), // grid - Image.createImage(iImgData120x10, 0, iImgData120x10.length), // vertical - Image.createImage(iImgData20x60, 0, iImgData20x60.length), // horizontal + Image[] iImages = + { + Image.createImage(iImgData60x20, 0, iImgData60x20.length), // grid + Image.createImage(iImgData40x30, 0, iImgData40x30.length), // grid + Image.createImage(iImgData120x10, 0, iImgData120x10.length), // vertical + Image.createImage(iImgData20x60, 0, iImgData20x60.length), // horizontal }; // data used to create TiledLayer with 6 tiles. @@ -157,7 +163,8 @@ /** * Constructor. */ - public TiledLayerTest() { + public TiledLayerTest() + { } /** @@ -166,7 +173,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public TiledLayerTest(String sTestName) { + public TiledLayerTest(String sTestName) + { super(sTestName); } @@ -176,23 +184,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = TiledLayerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TiledLayerTest((String)e.nextElement())); - } + // Add widget tests + methodNames = TiledLayerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TiledLayerTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testCell"); @@ -201,100 +212,121 @@ methodNames.addElement("testFillCells"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testCell")) testCell(); - else if (getName().equals("testAnimatedTiles")) testAnimatedTiles(); - else if (getName().equals("testChangeImage")) testChangeImage(); - else if (getName().equals("testFillCells")) testFillCells(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testCell")) testCell(); + else if(getName().equals("testAnimatedTiles")) testAnimatedTiles(); + else if(getName().equals("testChangeImage")) testChangeImage(); + else if(getName().equals("testFillCells")) testFillCells(); else super.runTest(); } - + /** * 1.0 TiledLayer - Construction Test */ - public void testConstructors() { + public void testConstructors() + { Image image = iImages[0]; int tileWidth = iTileWidth6; int tileHeight = iTileHeight6; TiledLayer tiledLayer = null; // checking("Test 1.01 Construct with wrong row"); - try { + try + { tiledLayer = new TiledLayer(iCols, 0, image, tileWidth, tileHeight); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.02 Construct with wrong col"); - try { + try + { tiledLayer = new TiledLayer(0, iRows, image, tileWidth, tileHeight); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.03 Construct with tile width=0"); - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, 0, tileHeight); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.04 Construct with tile height=0"); - try { + try + { int wrongWidth = image.getWidth() / 2 + 1; tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, 0); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.05 Construct with incorrect tile width for image"); - try { + try + { // image width is not an integer multiple of the tileWidth int wrongWidth = image.getWidth() / 2 + 1; tiledLayer = new TiledLayer(iCols, iRows, image, wrongWidth, - tileHeight); + tileHeight); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.06 Construct with incorrect tile height for image"); - try { + try + { // image height is not an integer multiple of the tileHeight int wrongHeight = image.getHeight() / 2 + 1; tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - wrongHeight); + wrongHeight); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 1.07 Construct with correct tile size"); - for (int i = 0; i < iImages.length; i++) { + for(int i = 0; i < iImages.length; i++) + { Image img = iImages[i]; // single tile runConstructTest(img, img.getWidth(), img.getHeight(), 1); @@ -308,10 +340,13 @@ // checks TiledLayer properties are correct after construction private void runConstructTest(Image image, - int tileWidth, int tileHeight, int tileCount) { + int tileWidth, int tileHeight, int tileCount) + { // vary number of rows and columns - for (int r = 1; r < iRows; r++) { - for (int c = 1; c < iCols; c++) { + for(int r = 1; r < iRows; r++) + { + for(int c = 1; c < iCols; c++) + { TiledLayer tl = new TiledLayer(c, r, image, tileWidth, tileHeight); assertEquals("getWidth ", tl.getWidth(), tileWidth * c); assertEquals("getHeight ", tl.getHeight(), tileHeight * r); @@ -328,7 +363,8 @@ /** * 2.0 TiledLayer - Cell Test */ - public void testCell() { + public void testCell() + { Image image = iImages[0]; int tileWidth = iTileWidth6; int tileHeight = iTileHeight6; @@ -336,57 +372,66 @@ TiledLayer tiledLayer; // checking("Test 2.01 CellTest: wrong tile index"); - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.setCell(0, 0, tileCount + 1); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 2.02 CellTest: col is outside the bounds of the TiledLayer grid"); - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.setCell(iCols, iRows - 1, tileCount); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 2.03 CellTest: row is outside the bounds of the TiledLayer grid"); - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.setCell(iCols - 1, iRows, tileCount); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 2.04 CellTest: default cells"); tiledLayer = createTiledLayer(iCols, iRows, image, tileWidth, - tileHeight, null); + tileHeight, null); checkCells(tiledLayer, iDefaultCells); // checking("Test 2.05 CellTest: setCells"); tiledLayer = createTiledLayer(iCols, iRows, image, tileWidth, - tileHeight, iSetCells); + tileHeight, iSetCells); checkCells(tiledLayer, iSetCells); // checking("Test 2.06 CellTest: fillCells"); tiledLayer = createTiledLayer(iCols, iRows, image, tileWidth, - tileHeight, null); + tileHeight, null); tiledLayer.fillCells(0, 0, 1, 2, 1); tiledLayer.fillCells(1, 0, 2, 1, 2); tiledLayer.fillCells(2, 1, 2, 1, 3); @@ -397,37 +442,42 @@ /** * 3.0 TiledLayer - Animated Tiles Test */ - public void testAnimatedTiles() { + public void testAnimatedTiles() + { TiledLayer tiledLayer = new TiledLayer(iCols, iRows, iImages[0], - iTileWidth6, iTileHeight6); + iTileWidth6, iTileHeight6); // checking("Test 3.01 Animated Tiles Test: invalid static tile index"); - try { + try + { tiledLayer.createAnimatedTile(iTileCount6 + 1); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 3.02 Animated Tiles Test: create and set animated tiles"); - for (int i = 0; i < iTileCount6 * 3; i++) { + for(int i = 0; i < iTileCount6 * 3; i++) + { int tileIndex = i % iTileCount6; int animTile = tiledLayer.createAnimatedTile(tileIndex); assertEquals("index of newly created animated tile", animTile, ~i); assertEquals("index returned by getAnimatedTile", tiledLayer - .getAnimatedTile(animTile), tileIndex); + .getAnimatedTile(animTile), tileIndex); int newTileIndex = i % (iTileCount6 / 2); tiledLayer.setAnimatedTile(animTile, newTileIndex); assertEquals("index after setAnimatedTile", tiledLayer - .getAnimatedTile(animTile), newTileIndex); + .getAnimatedTile(animTile), newTileIndex); } // checking("Test 3.03 Animated Tiles Test: set cells to animated tiles"); tiledLayer = new TiledLayer(iCols, iRows, iImages[0], iTileWidth6, - iTileHeight6); + iTileHeight6); int animTile1 = tiledLayer.createAnimatedTile(0); int animTile2 = tiledLayer.createAnimatedTile(1); tiledLayer.fillCells(0, 0, 4, 1, animTile1); @@ -446,11 +496,12 @@ /** * 4.0 TiledLayer - Change Image Test */ - public void testChangeImage() { + public void testChangeImage() + { // checking("Test 4.01 Change TiledLayer image: same tiles, clear cells, no anim tiles"); // Check: Animated tiles and cell contents preserved TiledLayer tiledLayer = createTiledLayer(iCols, iRows, iImages[0], - iTileWidth12, iTileHeight12, null); + iTileWidth12, iTileHeight12, null); tiledLayer.setStaticTileSet(iImages[1], iTileWidth12, iTileHeight12); checkCells(tiledLayer, iDefaultCells); checkAnimCellsPreserved(tiledLayer, iTileCount12, false); @@ -458,7 +509,7 @@ // checking("Test 4.02 Change TiledLayer image: same tiles, cells set, anim cells set"); // Check: Animated tiles and cell contents preserved tiledLayer = createTiledLayer(iCols, iRows, iImages[0], iTileWidth12, - iTileHeight12, iSetCells); + iTileHeight12, iSetCells); createAnimatedTiles(tiledLayer, iTileCount12); tiledLayer.setStaticTileSet(iImages[2], iTileWidth12, iTileHeight12); checkCells(tiledLayer, iSetCells); @@ -467,7 +518,7 @@ // checking("Test 4.03 Change TiledLayer image: more tiles, clear cells, no anim tiles"); // Check: Animated tiles and cell contents preserved tiledLayer = createTiledLayer(iCols, iRows, iImages[0], iTileWidth12, - iTileHeight12, null); + iTileHeight12, null); tiledLayer.setStaticTileSet(iImages[3], iTileWidth24, iTileHeight24); checkCells(tiledLayer, iDefaultCells); checkAnimCellsPreserved(tiledLayer, iTileCount12, false); @@ -475,7 +526,7 @@ // checking("Test 4.04 Change TiledLayer image: more tiles, cells set, anim tiles"); // Check: Animated tiles and cell contents preserved tiledLayer = createTiledLayer(iCols, iRows, iImages[1], iTileWidth12, - iTileHeight12, iSetCells); + iTileHeight12, iSetCells); createAnimatedTiles(tiledLayer, iTileCount12); tiledLayer.setStaticTileSet(iImages[2], iTileWidth24, iTileHeight24); checkCells(tiledLayer, iSetCells); @@ -485,7 +536,7 @@ // Check: Contents of the grid cleared (all contain index 0) and all // animated tiles deleted. tiledLayer = createTiledLayer(iCols, iRows, iImages[1], iTileWidth12, - iTileHeight12, null); + iTileHeight12, null); tiledLayer.setStaticTileSet(iImages[3], iTileWidth6, iTileHeight6); checkCells(tiledLayer, iDefaultCells); checkAnimCellsPreserved(tiledLayer, iTileCount6, false); @@ -494,7 +545,7 @@ // Check: Contents of the grid cleared (all contain index 0) and all // animated tiles deleted. tiledLayer = createTiledLayer(iCols, iRows, iImages[2], iTileWidth12, - iTileHeight12, iSetCells); + iTileHeight12, iSetCells); createAnimatedTiles(tiledLayer, iTileCount12); tiledLayer.setStaticTileSet(iImages[3], iTileWidth6, iTileHeight6); checkCells(tiledLayer, iDefaultCells); @@ -504,7 +555,8 @@ /** * 5.0 TiledLayer - Fill Cells Test */ - public void testFillCells() { + public void testFillCells() + { Image image = iImages[0]; int tileWidth = iTileWidth6; int tileHeight = iTileHeight6; @@ -512,113 +564,139 @@ // checking("Test 5.01 Number of absolute columns less than zero"); // Check: correct exception should be thrown - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.fillCells(iCols / 2, iRows / 2, -1, iRows / 4, 1); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 5.02 Number of absolute rows less than zero"); // Check: correct exception should be thrown - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.fillCells(iCols / 2, iRows / 2, iCols / 4, -1, 1); fail("IllegalArgumentException expected"); } - catch (java.lang.IllegalArgumentException ex) { + catch(java.lang.IllegalArgumentException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 5.03 Column extends bounds of grid"); // Check: correct exception should be thrown - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.fillCells(iCols + 1, iRows / 2, 1, 1, 1); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // checking("Test 5.04 Row extends bounds of grid"); // Check: correct exception should be thrown - try { + try + { tiledLayer = new TiledLayer(iCols, iRows, image, tileWidth, - tileHeight); + tileHeight); tiledLayer.fillCells(iCols / 2, iRows + 1, 1, 1, 1); fail("IndexOutOfBoundsException expected"); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } } // creates an animated tile for each tile and one for a clear cell - private void createAnimatedTiles(TiledLayer aTiledLayer, int aMaxTileIndex) { - for (int i = aMaxTileIndex; i >= 0; --i) + private void createAnimatedTiles(TiledLayer aTiledLayer, int aMaxTileIndex) + { + for(int i = aMaxTileIndex; i >= 0; --i) aTiledLayer.createAnimatedTile(i); } // checks if animated cells have been deleted private void checkAnimCellsPreserved(TiledLayer tl, int aMaxTileIndex, - boolean aPreserved) { - if (aPreserved) { + boolean aPreserved) + { + if(aPreserved) + { // check animated cells are still present // should be one for each tile and one for a clear cell - for (int i = 0; i <= aMaxTileIndex; ++i) { + for(int i = 0; i <= aMaxTileIndex; ++i) + { assertEquals("animated cells have not been deleted", - aMaxTileIndex - i, tl.getAnimatedTile(~i)); + aMaxTileIndex - i, tl.getAnimatedTile(~i)); } assertEquals("count has not been reset", tl - .createAnimatedTile(aMaxTileIndex), ~(aMaxTileIndex + 1)); + .createAnimatedTile(aMaxTileIndex), ~(aMaxTileIndex + 1)); } - else { + else + { // check cannot get or set animated tiles - try { + try + { tl.getAnimatedTile(-1); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } - try { + try + { tl.setAnimatedTile(-1, aMaxTileIndex); } - catch (java.lang.IndexOutOfBoundsException ex) { + catch(java.lang.IndexOutOfBoundsException ex) + { } - catch (Exception ex) { + catch(Exception ex) + { fail("Wrong exception " + ex); } // a new animated tile should have index -1 assertEquals("count has been reset", tl - .createAnimatedTile(aMaxTileIndex), -1); + .createAnimatedTile(aMaxTileIndex), -1); } } // create TiledLayer and setCells private TiledLayer createTiledLayer(int cols, int rows, Image img, - int tileWidth, int tileHeight, int[][] aCells) { + int tileWidth, int tileHeight, int[][] aCells) + { TiledLayer tl = new TiledLayer(cols, rows, img, tileWidth, tileHeight); - if (aCells != null) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) + if(aCells != null) + { + for(int i = 0; i < rows; i++) + { + for(int j = 0; j < cols; j++) tl.setCell(j, i, aCells[i][j]); } } @@ -626,23 +704,28 @@ } // checks cell contents - private void checkCells(TiledLayer tiledLayer, int[][] expectedCells) { - for (int i = 0; i < tiledLayer.getRows(); i++) { - for (int j = 0; j < tiledLayer.getColumns(); j++) + private void checkCells(TiledLayer tiledLayer, int[][] expectedCells) + { + for(int i = 0; i < tiledLayer.getRows(); i++) + { + for(int j = 0; j < tiledLayer.getColumns(); j++) assertEquals("getCell ", tiledLayer.getCell(j, i), - expectedCells[i][j]); + expectedCells[i][j]); } } // checks cell contents, use if all animated tiles private void checkAnimCells(TiledLayer tiledLayer, int[][] animCells, - int[][] staticCells) { - for (int r = 0; r < tiledLayer.getRows(); r++) { - for (int c = 0; c < tiledLayer.getColumns(); c++) { + int[][] staticCells) + { + for(int r = 0; r < tiledLayer.getRows(); r++) + { + for(int c = 0; c < tiledLayer.getColumns(); c++) + { int tileIndex = tiledLayer.getCell(c, r); assertEquals("getCell ", tileIndex, animCells[r][c]); assertEquals("getAnimatedTile ", tiledLayer - .getAnimatedTile(tileIndex), staticCells[r][c]); + .getAnimatedTile(tileIndex), staticCells[r][c]); } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/gauge/GaugeTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/gauge/GaugeTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/gauge/GaugeTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.gauge; @@ -28,7 +28,8 @@ *
          • Collection of tests to test Gauge's API functionality.
            *
            */ -public class GaugeTest extends SWTTestCase { +public class GaugeTest extends SWTTestCase +{ private static String label = "Label"; @@ -38,7 +39,8 @@ /** * Constructor. */ - public GaugeTest() { + public GaugeTest() + { } /** @@ -47,14 +49,16 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public GaugeTest(String sTestName) { + public GaugeTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { } /** @@ -63,41 +67,46 @@ * * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = GaugeTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new GaugeTest((String)e.nextElement())); - } + // Add widget tests + methodNames = GaugeTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new GaugeTest((String)e.nextElement())); + } - return suite; - } - - public static java.util.Vector methodNames() { + return suite; + } + + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } /** * Tests the gauge accessor methods. */ - public void testAccessors() { + public void testAccessors() + { Gauge gauge = new Gauge(null, false, POSITIVE_INT, 0); assertTrue("Should be noninteractive", !gauge.isInteractive()); assertEquals("Maxvalues don't match", POSITIVE_INT, - gauge.getMaxValue()); + gauge.getMaxValue()); assertEquals("Labels don't match", null, gauge.getLabel()); gauge.setLabel(label); @@ -110,80 +119,88 @@ assertEquals("Values mismatch", POSITIVE_INT, gauge.getValue()); gauge.setValue(0); - try { + try + { gauge.setMaxValue(NEGATIVE_INT); fail("1. IllegalArgumentException expected"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { } gauge.setMaxValue(Gauge.INDEFINITE); - try { + try + { gauge.setValue(NEGATIVE_INT); fail("2. IllegalArgumentException expected"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { } - try { + try + { gauge.setValue(Gauge.CONTINUOUS_IDLE); gauge.setValue(Gauge.INCREMENTAL_IDLE); gauge.setValue(Gauge.CONTINUOUS_RUNNING); gauge.setValue(Gauge.INCREMENTAL_UPDATING); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { fail("3. IllegalArgumentException thrown " + iae.getMessage()); } - try { + try + { gauge.setValue(POSITIVE_INT); fail("4. IllegalArgumentException expected"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { } // Test minimum bounds, non-interactive: gauge.setLabel(null); assertTrue("Minimum height was zero or negative, case 1.", - gauge.getMinimumHeight() > 0); + gauge.getMinimumHeight() > 0); //print("non-interactive minimum height: " // + gauge.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 1.", - gauge.getMinimumWidth() > 0); + gauge.getMinimumWidth() > 0); //print("non-interactive minimum width: " // + gauge.getMinimumWidth()); // Minimum bounds, interactive: Gauge gauge2 = new Gauge(null, true, POSITIVE_INT, 0); assertTrue("Minimum height was zero or negative, case 2.", - gauge2.getMinimumHeight() > 0); + gauge2.getMinimumHeight() > 0); //print("interactive minimum height: " // + gauge2.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 2.", - gauge2.getMinimumWidth() > 0); + gauge2.getMinimumWidth() > 0); //print("interactive minimum width: " // + gauge2.getMinimumWidth()); // Minimum bounds, non-interactive with label: Gauge gauge3 = new Gauge("label", false, POSITIVE_INT, 0); assertTrue("Minimum height was zero or negative, case 3.", - gauge3.getMinimumHeight() > 0); + gauge3.getMinimumHeight() > 0); //print("labeled non-interactive minimum height: " // + gauge3.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 3.", - gauge3.getMinimumWidth() > 0); + gauge3.getMinimumWidth() > 0); //print("labeled non-interactive minimum width: " // + gauge3.getMinimumWidth()); // Minimum bounds, interactive with label: Gauge gauge4 = new Gauge("label", true, POSITIVE_INT, 0); assertTrue("Minimum height was zero or negative, case 4.", - gauge4.getMinimumHeight() > 0); + gauge4.getMinimumHeight() > 0); //print("labeled interactive minimum height: " // + gauge4.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 4.", - gauge4.getMinimumWidth() > 0); + gauge4.getMinimumWidth() > 0); //print("labeled interactive minimum width: " // + gauge4.getMinimumWidth()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/DirectGraphicsTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/DirectGraphicsTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/DirectGraphicsTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.graphics; @@ -27,14 +27,16 @@ import com.nokia.mid.ui.DirectGraphics; import com.nokia.mid.ui.DirectUtils; -public class DirectGraphicsTest extends SWTTestCase { +public class DirectGraphicsTest extends SWTTestCase +{ private TestCanvas testCanvas; /** * Constructor. */ - public DirectGraphicsTest() { + public DirectGraphicsTest() + { } /** @@ -43,16 +45,19 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public DirectGraphicsTest(String sTestName) { + public DirectGraphicsTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { testCanvas = new TestCanvas(); Display.getDisplay(getMIDlet()).setCurrent(testCanvas); } - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { testCanvas = null; } @@ -62,23 +67,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = DirectGraphicsTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DirectGraphicsTest((String)e.nextElement())); - } + // Add widget tests + methodNames = DirectGraphicsTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DirectGraphicsTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testGraphics"); methodNames.addElement("testDrawImage"); @@ -96,26 +104,28 @@ methodNames.addElement("testSetGetARGBColor"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testGraphics")) testCanvas.runTest(TestCanvas.TEST_GRAPHICS); - else if (getName().equals("testDrawImage")) testCanvas.runTest(TestCanvas.TEST_DRAWIMAGE); - else if (getName().equals("testDrawGetPixels")) testCanvas.runDrawGetPixels(); - else if (getName().equals("testDrawGetPixelsByte")) testCanvas.runDrawGetPixelsByte(); - else if (getName().equals("testDrawGetPixelsShort")) testCanvas.runDrawGetPixelsShort(); - else if (getName().equals("testDrawGetPixelsShort555")) testCanvas.runDrawGetPixelsShort555(); - else if (getName().equals("testDrawGetPixelsShort444")) testCanvas.runDrawGetPixelsShort444(); - else if (getName().equals("testDrawGetPixelsShort4444")) testCanvas.runDrawGetPixelsShort4444(); - else if (getName().equals("testDrawPolygon")) testCanvas.runTest(TestCanvas.TEST_DRAWPOLYGON); - else if (getName().equals("testDrawTriangle")) testCanvas.runTest(TestCanvas.TEST_DRAWTRIANGLE); - else if (getName().equals("testFillPolygon")) testCanvas.runTest(TestCanvas.TEST_FILLPOLYGON); - else if (getName().equals("testFillTriangle")) testCanvas.runTest(TestCanvas.TEST_FILLTRIANGLE); - else if (getName().equals("testGetNativePixelFormat")) testCanvas.runTest(TestCanvas.TEST_GETNATIVEPIXELFORMAT); - else if (getName().equals("testSetGetARGBColor")) testCanvas.runTest(TestCanvas.TEST_SETGETARGBCOLOR); + + protected void runTest() throws Throwable + { + if(getName().equals("testGraphics")) testCanvas.runTest(TestCanvas.TEST_GRAPHICS); + else if(getName().equals("testDrawImage")) testCanvas.runTest(TestCanvas.TEST_DRAWIMAGE); + else if(getName().equals("testDrawGetPixels")) testCanvas.runDrawGetPixels(); + else if(getName().equals("testDrawGetPixelsByte")) testCanvas.runDrawGetPixelsByte(); + else if(getName().equals("testDrawGetPixelsShort")) testCanvas.runDrawGetPixelsShort(); + else if(getName().equals("testDrawGetPixelsShort555")) testCanvas.runDrawGetPixelsShort555(); + else if(getName().equals("testDrawGetPixelsShort444")) testCanvas.runDrawGetPixelsShort444(); + else if(getName().equals("testDrawGetPixelsShort4444")) testCanvas.runDrawGetPixelsShort4444(); + else if(getName().equals("testDrawPolygon")) testCanvas.runTest(TestCanvas.TEST_DRAWPOLYGON); + else if(getName().equals("testDrawTriangle")) testCanvas.runTest(TestCanvas.TEST_DRAWTRIANGLE); + else if(getName().equals("testFillPolygon")) testCanvas.runTest(TestCanvas.TEST_FILLPOLYGON); + else if(getName().equals("testFillTriangle")) testCanvas.runTest(TestCanvas.TEST_FILLTRIANGLE); + else if(getName().equals("testGetNativePixelFormat")) testCanvas.runTest(TestCanvas.TEST_GETNATIVEPIXELFORMAT); + else if(getName().equals("testSetGetARGBColor")) testCanvas.runTest(TestCanvas.TEST_SETGETARGBCOLOR); else super.runTest(); } - - class TestCanvas extends Canvas { + + class TestCanvas extends Canvas + { static final int TEST_NONE = 0; static final int TEST_GRAPHICS = 1; @@ -155,8 +165,10 @@ private byte[] bRgbDataMaskSet = new byte[testWidth * testHeight]; private byte[] bRgbDataMaskGet = new byte[testWidth * testHeight]; - public TestCanvas() { - for (int i = 0; i< rgbDataSet.length; i++) { + public TestCanvas() + { + for(int i = 0; i< rgbDataSet.length; i++) + { rgbDataSet[i] = 0xFFFF0000; bRgbDataSet[i] = (byte) 0xFF; bRgbDataMaskSet[i] = (byte) 0xFF; @@ -169,7 +181,8 @@ /** * Set failing message. */ - private void setFailMessage(String msg) { + private void setFailMessage(String msg) + { failMsg = msg; passed = (failMsg == null); } @@ -177,19 +190,22 @@ /** * Run the specified test. */ - public void runTest(int test) { + public void runTest(int test) + { setFailMessage(null); doRunTest(test); assertTrue(failMsg, passed); } - private void doRunTest(int test) { + private void doRunTest(int test) + { testMode = test; repaint(); serviceRepaints(); } - public void runDrawGetPixels() { + public void runDrawGetPixels() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELS); doRunTest(TEST_GETPIXELS); @@ -199,7 +215,8 @@ assertTrue(failMsg, passed); } - public void runDrawGetPixelsByte() { + public void runDrawGetPixelsByte() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELSBYTE); doRunTest(TEST_GETPIXELSBYTE); @@ -209,7 +226,8 @@ assertTrue(failMsg, passed); } - public void runDrawGetPixelsShort() { + public void runDrawGetPixelsShort() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELSSHORT); doRunTest(TEST_GETPIXELSSHORT); @@ -218,7 +236,8 @@ //doRunTest(TEST_GETPIXELS); assertTrue(failMsg, passed); } - public void runDrawGetPixelsShort555() { + public void runDrawGetPixelsShort555() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELSSHORT555); doRunTest(TEST_GETPIXELSSHORT555); @@ -227,7 +246,8 @@ //doRunTest(TEST_GETPIXELS); assertTrue(failMsg, passed); } - public void runDrawGetPixelsShort444() { + public void runDrawGetPixelsShort444() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELSSHORT444); doRunTest(TEST_GETPIXELSSHORT444); @@ -236,7 +256,8 @@ //doRunTest(TEST_GETPIXELS); assertTrue(failMsg, passed); } - public void runDrawGetPixelsShort4444() { + public void runDrawGetPixelsShort4444() + { setFailMessage(null); doRunTest(TEST_DRAWPIXELSSHORT4444); doRunTest(TEST_GETPIXELSSHORT4444); @@ -247,423 +268,498 @@ } - protected void paint(Graphics g) { - try { + protected void paint(Graphics g) + { + try + { DirectGraphics dg = DirectUtils.getDirectGraphics(g); - switch (testMode) { - case TEST_NONE: - break; - case TEST_GRAPHICS: - if (dg == null) { - fail("DirectGraphics object is null in paint()"); - } - break; - case TEST_DRAWIMAGE: - testDrawImage(dg); - break; - case TEST_DRAWPIXELS: - testDrawPixels(dg); - break; - case TEST_DRAWPIXELSBYTE: - testDrawPixelsByte(dg); - break; - case TEST_GETPIXELS: - testGetPixels(dg); - break; - case TEST_DRAWPIXELSSHORT: - testDrawPixelsShort(dg); - break; - case TEST_GETPIXELSBYTE: - testGetPixelsByte(dg); - break; - case TEST_DRAWPIXELSSHORT555: - testDrawPixelsShort555(dg); - break; - case TEST_GETPIXELSSHORT555: - testGetPixelsShort555(dg); - break; - case TEST_DRAWPIXELSSHORT444: - testDrawPixelsShort444(dg); - break; - case TEST_GETPIXELSSHORT444: - testGetPixelsShort444(dg); - break; - case TEST_DRAWPIXELSSHORT4444: - testDrawPixelsShort4444(dg); - break; - case TEST_GETPIXELSSHORT4444: - testGetPixelsShort4444(dg); - break; - case TEST_GETPIXELSSHORT: - testGetPixelsShort(dg); - break; - case TEST_DRAWPOLYGON: - testDrawPolygon(dg); - break; - case TEST_DRAWTRIANGLE: - testDrawTriangle(dg); - break; - case TEST_FILLPOLYGON: - testFillPolygon(dg); - break; - case TEST_FILLTRIANGLE: - testFillTriangle(dg); - break; - case TEST_GETNATIVEPIXELFORMAT: - testGetNativePixelFormat(dg); - break; - case TEST_SETGETARGBCOLOR: - testSetGetAlphaColor(dg); - break; - default: + switch(testMode) + { + case TEST_NONE: + break; + case TEST_GRAPHICS: + if(dg == null) + { + fail("DirectGraphics object is null in paint()"); + } + break; + case TEST_DRAWIMAGE: + testDrawImage(dg); + break; + case TEST_DRAWPIXELS: + testDrawPixels(dg); + break; + case TEST_DRAWPIXELSBYTE: + testDrawPixelsByte(dg); + break; + case TEST_GETPIXELS: + testGetPixels(dg); + break; + case TEST_DRAWPIXELSSHORT: + testDrawPixelsShort(dg); + break; + case TEST_GETPIXELSBYTE: + testGetPixelsByte(dg); + break; + case TEST_DRAWPIXELSSHORT555: + testDrawPixelsShort555(dg); + break; + case TEST_GETPIXELSSHORT555: + testGetPixelsShort555(dg); + break; + case TEST_DRAWPIXELSSHORT444: + testDrawPixelsShort444(dg); + break; + case TEST_GETPIXELSSHORT444: + testGetPixelsShort444(dg); + break; + case TEST_DRAWPIXELSSHORT4444: + testDrawPixelsShort4444(dg); + break; + case TEST_GETPIXELSSHORT4444: + testGetPixelsShort4444(dg); + break; + case TEST_GETPIXELSSHORT: + testGetPixelsShort(dg); + break; + case TEST_DRAWPOLYGON: + testDrawPolygon(dg); + break; + case TEST_DRAWTRIANGLE: + testDrawTriangle(dg); + break; + case TEST_FILLPOLYGON: + testFillPolygon(dg); + break; + case TEST_FILLTRIANGLE: + testFillTriangle(dg); + break; + case TEST_GETNATIVEPIXELFORMAT: + testGetNativePixelFormat(dg); + break; + case TEST_SETGETARGBCOLOR: + testSetGetAlphaColor(dg); + break; + default: } } /*catch (AssertionFailedException afe) { setFailMessage(afe.getMessage()); }*/ - catch (Exception e) { - setFailMessage(e.getMessage()); + catch(Exception e) + { + setFailMessage(e.getMessage()); } - finally { + finally + { testMode = TEST_NONE; } } - private void testDrawImage(DirectGraphics dg) throws IOException { + private void testDrawImage(DirectGraphics dg) throws IOException + { Image testImage = Image.createImage("image1.jpg"); - try { + try + { dg.drawImage(null, 0, 0, 0, 0); fail("NullPointerException should be thrown on null image"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } - try { + try + { dg.drawImage(testImage, 0, 0, 0, -1); fail("IllegalArgumentException should be thrown on invalid manipulation"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } - try { + try + { dg.drawImage(testImage, 0, 0, -1, 0); fail("IllegalArgumentException should be thrown on invalid anchor"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } dg.drawImage(testImage, 0, 0, 0, 0); dg.drawImage(testImage, 0, 0, 0, DirectGraphics.ROTATE_90); dg.drawImage(testImage, 0, 0, 0, - DirectGraphics.ROTATE_90 | DirectGraphics.FLIP_HORIZONTAL); + DirectGraphics.ROTATE_90 | DirectGraphics.FLIP_HORIZONTAL); } - private void testDrawPixels(DirectGraphics dg) { - try { - dg.drawPixels( (int[]) null, false, 0, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_INT_888_RGB); + private void testDrawPixels(DirectGraphics dg) + { + try + { + dg.drawPixels((int[]) null, false, 0, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_INT_888_RGB); fail("NullPointerException should be thrown on null array - drawPixels"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } - try { - dg.drawPixels( rgbDataSet, false, -1, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_INT_888_RGB); + try + { + dg.drawPixels(rgbDataSet, false, -1, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_INT_888_RGB); fail("ArrayIndexOutOfBoundsException should be thrown on invalid offset"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } - try { + try + { dg.drawPixels(rgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - -1, DirectGraphics.TYPE_INT_888_RGB); + 0, 0, testWidth, testHeight, + -1, DirectGraphics.TYPE_INT_888_RGB); fail("IllegalArgumentException should be thrown on invalid manipulation"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } - try { + try + { dg.drawPixels(rgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, -1); + 0, 0, testWidth, testHeight, + 0, -1); fail("IllegalArgumentException should be thrown on invalid format"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } // draw image to GC dg.drawPixels(rgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_INT_888_RGB); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_INT_888_RGB); } - private void testDrawPixelsByte(DirectGraphics dg) { - try { - dg.drawPixels( (byte[]) null, (byte[]) null, 0, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_BYTE_1_GRAY); + private void testDrawPixelsByte(DirectGraphics dg) + { + try + { + dg.drawPixels((byte[]) null, (byte[]) null, 0, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_BYTE_1_GRAY); fail("NullPointerException should be thrown on null array - drawPixels"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } - try { - dg.drawPixels( bRgbDataSet, bRgbDataMaskSet, -1, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_BYTE_1_GRAY); + try + { + dg.drawPixels(bRgbDataSet, bRgbDataMaskSet, -1, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_BYTE_1_GRAY); fail("ArrayIndexOutOfBoundsException should be thrown on invalid offset"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } - try { + try + { dg.drawPixels(bRgbDataSet, bRgbDataMaskSet, 0, testWidth, - 0, 0, testWidth, testHeight, - -1, DirectGraphics.TYPE_BYTE_1_GRAY); + 0, 0, testWidth, testHeight, + -1, DirectGraphics.TYPE_BYTE_1_GRAY); fail("IllegalArgumentException should be thrown on invalid manipulation"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } - try { + try + { dg.drawPixels(bRgbDataSet, bRgbDataMaskSet, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, -1); + 0, 0, testWidth, testHeight, + 0, -1); fail("IllegalArgumentException should be thrown on invalid format"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } // draw image to GC dg.drawPixels(bRgbDataSet, bRgbDataMaskSet, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_BYTE_1_GRAY); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_BYTE_1_GRAY); - // while(true); + // while(true); } - private void testDrawPixelsShort(DirectGraphics dg) { - try { - dg.drawPixels( (short[]) null, false, 0, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_USHORT_565_RGB); + private void testDrawPixelsShort(DirectGraphics dg) + { + try + { + dg.drawPixels((short[]) null, false, 0, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_USHORT_565_RGB); fail("NullPointerException should be thrown on null array - drawPixels"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } - try { - dg.drawPixels( sRgbDataSet, false, -1, 0, - 0, 0, 0, 0, - 0, DirectGraphics.TYPE_USHORT_565_RGB); + try + { + dg.drawPixels(sRgbDataSet, false, -1, 0, + 0, 0, 0, 0, + 0, DirectGraphics.TYPE_USHORT_565_RGB); fail("ArrayIndexOutOfBoundsException should be thrown on invalid offset"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } - try { + try + { dg.drawPixels(sRgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - -1, DirectGraphics.TYPE_USHORT_565_RGB); + 0, 0, testWidth, testHeight, + -1, DirectGraphics.TYPE_USHORT_565_RGB); fail("IllegalArgumentException should be thrown on invalid manipulation"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } - try { + try + { dg.drawPixels(sRgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, -1); + 0, 0, testWidth, testHeight, + 0, -1); fail("IllegalArgumentException should be thrown on invalid format"); } - catch (IllegalArgumentException obe) { + catch(IllegalArgumentException obe) + { // Ok } // draw image to GC dg.drawPixels(sRgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_USHORT_565_RGB); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_USHORT_565_RGB); } - private void testDrawPixelsShort555(DirectGraphics dg) { + private void testDrawPixelsShort555(DirectGraphics dg) + { dg.drawPixels(sRgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_USHORT_555_RGB); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_USHORT_555_RGB); } - private void testGetPixelsShort555(DirectGraphics dg) { + private void testGetPixelsShort555(DirectGraphics dg) + { dg.getPixels(sRgbDataGet, 0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_USHORT_555_RGB); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_USHORT_555_RGB); // compare gotten data with previously set data - for (int i = 0; i < sRgbDataSet.length; i++) { - if (sRgbDataGet[i] != sRgbDataSet[i]) { + for(int i = 0; i < sRgbDataSet.length; i++) + { + if(sRgbDataGet[i] != sRgbDataSet[i]) + { fail("RGB Data mismatch at " + i + " : set " - + sRgbDataSet[i] + " get " + sRgbDataGet[i]); + + sRgbDataSet[i] + " get " + sRgbDataGet[i]); } } } - private void testDrawPixelsShort444(DirectGraphics dg) { + private void testDrawPixelsShort444(DirectGraphics dg) + { dg.drawPixels(sRgbDataSet, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_USHORT_444_RGB); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_USHORT_444_RGB); } - private void testGetPixelsShort444(DirectGraphics dg) { + private void testGetPixelsShort444(DirectGraphics dg) + { dg.getPixels(sRgbDataGet, 0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_USHORT_444_RGB); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_USHORT_444_RGB); // compare gotten data with previously set data - for (int i = 0; i < sRgbDataSet.length; i++) { - if (sRgbDataGet[i] != sRgbDataSet[i]) { + for(int i = 0; i < sRgbDataSet.length; i++) + { + if(sRgbDataGet[i] != sRgbDataSet[i]) + { fail("RGB Data mismatch at " + i + " : set " - + sRgbDataSet[i] + " get " + sRgbDataGet[i]); + + sRgbDataSet[i] + " get " + sRgbDataGet[i]); } } } - private void testDrawPixelsShort4444(DirectGraphics dg) { + private void testDrawPixelsShort4444(DirectGraphics dg) + { dg.drawPixels(sRgbDataSet4444, false, 0, testWidth, - 0, 0, testWidth, testHeight, - 0, DirectGraphics.TYPE_USHORT_4444_ARGB); + 0, 0, testWidth, testHeight, + 0, DirectGraphics.TYPE_USHORT_4444_ARGB); } - private void testGetPixelsShort4444(DirectGraphics dg) { + private void testGetPixelsShort4444(DirectGraphics dg) + { dg.getPixels(sRgbDataGet, 0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_USHORT_4444_ARGB); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_USHORT_4444_ARGB); // compare gotten data with previously set data - for (int i = 0; i < sRgbDataSet4444.length; i++) { - if (sRgbDataGet[i] != sRgbDataSet4444[i]) { + for(int i = 0; i < sRgbDataSet4444.length; i++) + { + if(sRgbDataGet[i] != sRgbDataSet4444[i]) + { fail("RGB Data mismatch at " + i + " : set " - + sRgbDataSet4444[i] + " get " + sRgbDataGet[i]); + + sRgbDataSet4444[i] + " get " + sRgbDataGet[i]); } } } - private void testGetPixels(DirectGraphics dg) { - try { - dg.getPixels( (int[]) null, 0, 1, - 0, 0, 1, 1, - DirectGraphics.TYPE_INT_888_RGB); + private void testGetPixels(DirectGraphics dg) + { + try + { + dg.getPixels((int[]) null, 0, 1, + 0, 0, 1, 1, + DirectGraphics.TYPE_INT_888_RGB); fail("IllegalArgumentException should be thrown on null array - getPixels"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } // get data from GC dg.getPixels(rgbDataGet, 0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_INT_888_RGB); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_INT_888_RGB); // compare gotten data with previously set data - for (int i = 0; i < rgbDataSet.length; i++) { - if (rgbDataGet[i] != rgbDataSet[i]) { + for(int i = 0; i < rgbDataSet.length; i++) + { + if(rgbDataGet[i] != rgbDataSet[i]) + { fail("RGB Data mismatch at " + i + " : set " - + rgbDataSet[i] + " get " + rgbDataGet[i]); + + rgbDataSet[i] + " get " + rgbDataGet[i]); } } } - private void testGetPixelsByte(DirectGraphics dg) { - try { - dg.getPixels( (byte[]) null, (byte []) null,0, 1, - 0, 0, 1, 1, - DirectGraphics.TYPE_BYTE_1_GRAY); + private void testGetPixelsByte(DirectGraphics dg) + { + try + { + dg.getPixels((byte[]) null, (byte []) null,0, 1, + 0, 0, 1, 1, + DirectGraphics.TYPE_BYTE_1_GRAY); fail("IllegalArgumentException should be thrown on null array - getPixels"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } // get data from GC dg.getPixels(bRgbDataGet, bRgbDataMaskGet,0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_BYTE_1_GRAY); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_BYTE_1_GRAY); // compare gotten data with previously set data - for (int i = 0; i < (bRgbDataSet.length / 8); i++) { - if (bRgbDataGet[i] != bRgbDataSet[i]) { + for(int i = 0; i < (bRgbDataSet.length / 8); i++) + { + if(bRgbDataGet[i] != bRgbDataSet[i]) + { fail("RGB Data mismatch at " + i + " : set " - + bRgbDataSet[i] + " get " + bRgbDataGet[i]); + + bRgbDataSet[i] + " get " + bRgbDataGet[i]); } - if (i != 0 && ((i % 4) == 0)) { + if(i != 0 && ((i % 4) == 0)) + { i = i + 4; } } } - private void testGetPixelsShort(DirectGraphics dg) { - try { - dg.getPixels( (short[]) null, 0, 1, - 0, 0, 1, 1, - DirectGraphics.TYPE_USHORT_565_RGB); + private void testGetPixelsShort(DirectGraphics dg) + { + try + { + dg.getPixels((short[]) null, 0, 1, + 0, 0, 1, 1, + DirectGraphics.TYPE_USHORT_565_RGB); fail("IllegalArgumentException should be thrown on null array - getPixels"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // Ok } // get data from GC dg.getPixels(sRgbDataGet, 0, testWidth, - 0, 0, testWidth, testHeight, - DirectGraphics.TYPE_USHORT_565_RGB); + 0, 0, testWidth, testHeight, + DirectGraphics.TYPE_USHORT_565_RGB); // compare gotten data with previously set data - for (int i = 0; i < sRgbDataSet.length; i++) { - if (sRgbDataGet[i] != sRgbDataSet[i]) { + for(int i = 0; i < sRgbDataSet.length; i++) + { + if(sRgbDataGet[i] != sRgbDataSet[i]) + { fail("RGB Data mismatch at " + i + " : set " - + sRgbDataSet[i] + " get " + sRgbDataGet[i]); + + sRgbDataSet[i] + " get " + sRgbDataGet[i]); } } } - private void testDrawPolygon(DirectGraphics dg) { - try { + private void testDrawPolygon(DirectGraphics dg) + { + try + { dg.drawPolygon(null, 0, null, 0, 1, 0); fail("NullPointerException should be thrown on null arrays"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } int[] xP = new int[] {10, 20, 30, 40}; int[] yP = new int[] {40, 30, 20, 10}; - try { + try + { dg.drawPolygon(xP, 0, yP, 0, 5, 0); fail("ArrayIndexOutOfBoundsException should be thrown on " - + "invalid nPoints"); + + "invalid nPoints"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } - try { + try + { dg.drawPolygon(xP, 4, yP, 3, 4, 0); fail("ArrayIndexOutOfBoundsException should be thrown on " - + "invalid offsets"); + + "invalid offsets"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } @@ -672,37 +768,45 @@ dg.drawPolygon(xP, 2, yP, 2, 2, 0); } - private void testDrawTriangle(DirectGraphics dg) { + private void testDrawTriangle(DirectGraphics dg) + { dg.drawTriangle(10, 10, 20, 20, 30, 0, 0); } - private void testFillPolygon(DirectGraphics dg) { - try { + private void testFillPolygon(DirectGraphics dg) + { + try + { dg.fillPolygon(null, 0, null, 0, 1, 0); fail("NullPointerException should be thrown on null arrays"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Ok } int[] xP = new int[] {10, 20, 30, 40}; int[] yP = new int[] {40, 30, 20, 10}; - try { + try + { dg.fillPolygon(xP, 0, yP, 0, 5, 0); fail("ArrayIndexOutOfBoundsException should be thrown on " - + "invalid nPoints"); + + "invalid nPoints"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } - try { + try + { dg.fillPolygon(xP, 4, yP, 3, 4, 0); fail("ArrayIndexOutOfBoundsException should be thrown on " - + "invalid offsets"); + + "invalid offsets"); } - catch (ArrayIndexOutOfBoundsException obe) { + catch(ArrayIndexOutOfBoundsException obe) + { // Ok } @@ -711,17 +815,21 @@ dg.fillPolygon(xP, 2, yP, 2, 2, 0); } - private void testFillTriangle(DirectGraphics dg) { + private void testFillTriangle(DirectGraphics dg) + { dg.fillTriangle(10, 10, 20, 20, 30, 0, 0); } - private void testGetNativePixelFormat(DirectGraphics dg) { + private void testGetNativePixelFormat(DirectGraphics dg) + { dg.getNativePixelFormat(); } - private void testSetGetAlphaColor(DirectGraphics dg) { + private void testSetGetAlphaColor(DirectGraphics dg) + { dg.setARGBColor(0xAAFF1166); - if (dg.getAlphaComponent() != 0xAA) { + if(dg.getAlphaComponent() != 0xAA) + { fail("Alpha component mismatch"); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/GraphicsTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/GraphicsTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/graphics/GraphicsTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.graphics; @@ -23,14 +23,16 @@ import com.nokia.openlcdui.mt.SWTTestCase; -public class GraphicsTest extends SWTTestCase { +public class GraphicsTest extends SWTTestCase +{ private TestCanvas testCanvas; /** * Constructor. */ - public GraphicsTest() { + public GraphicsTest() + { } /** @@ -39,17 +41,20 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public GraphicsTest(String sTestName) { + public GraphicsTest(String sTestName) + { super(sTestName); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); testCanvas = new TestCanvas(); Display.getDisplay(getMIDlet()).setCurrent(testCanvas); } - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { super.tearDown(); testCanvas = null; } @@ -60,23 +65,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = GraphicsTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new GraphicsTest((String)e.nextElement())); - } + // Add widget tests + methodNames = GraphicsTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new GraphicsTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testGraphics"); methodNames.addElement("testTranslate"); @@ -98,26 +106,31 @@ methodNames.addElement("testDrawRegion"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testGraphics")) testCanvas.test(TestCanvas.TEST_GRAPHICS); - else if (getName().equals("testTranslate")) testCanvas.test(TestCanvas.TEST_TRANSLATE); - else if (getName().equals("testColor")) testCanvas.test(TestCanvas.TEST_COLOR); - else if (getName().equals("testClip")) testCanvas.test(TestCanvas.TEST_CLIP); - else if (getName().equals("testDrawLine")) testCanvas.test(TestCanvas.TEST_DRAWLINE); - else if (getName().equals("testFillRect")) testCanvas.test(TestCanvas.TEST_FILLRECT); - else if (getName().equals("testDrawRect")) testCanvas.test(TestCanvas.TEST_DRAWRECT); - else if (getName().equals("testDrawRoundRect")) testCanvas.test(TestCanvas.TEST_DRAWROUNDRECT); - else if (getName().equals("testFillRoundRect")) testCanvas.test(TestCanvas.TEST_FILLROUNDRECT); - else if (getName().equals("testFillArc")) testCanvas.test(TestCanvas.TEST_FILLARC); - else if (getName().equals("testDrawArc")) testCanvas.test(TestCanvas.TEST_DRAWARC); - else if (getName().equals("testDrawString")) testCanvas.test(TestCanvas.TEST_DRAWSTRING); - else if (getName().equals("testDrawImage")) testCanvas.test(TestCanvas.TEST_DRAWIMAGE); - else if (getName().equals("testStrokeStyle")) testCanvas.test(TestCanvas.TEST_STROKESTYLE); - else if (getName().equals("testDrawRGB")) {DISABLE_TEST();testCanvas.test(TestCanvas.TEST_DRAWRGB);} - else if (getName().equals("testFillTriangle")) testCanvas.test(TestCanvas.TEST_FILLTRIANGLE); - else if (getName().equals("testCopyArea")) testCanvas.test(TestCanvas.TEST_COPYAREA); - else if (getName().equals("testDrawRegion")) testCanvas.test(TestCanvas.TEST_DRAWREGION); + + protected void runTest() throws Throwable + { + if(getName().equals("testGraphics")) testCanvas.test(TestCanvas.TEST_GRAPHICS); + else if(getName().equals("testTranslate")) testCanvas.test(TestCanvas.TEST_TRANSLATE); + else if(getName().equals("testColor")) testCanvas.test(TestCanvas.TEST_COLOR); + else if(getName().equals("testClip")) testCanvas.test(TestCanvas.TEST_CLIP); + else if(getName().equals("testDrawLine")) testCanvas.test(TestCanvas.TEST_DRAWLINE); + else if(getName().equals("testFillRect")) testCanvas.test(TestCanvas.TEST_FILLRECT); + else if(getName().equals("testDrawRect")) testCanvas.test(TestCanvas.TEST_DRAWRECT); + else if(getName().equals("testDrawRoundRect")) testCanvas.test(TestCanvas.TEST_DRAWROUNDRECT); + else if(getName().equals("testFillRoundRect")) testCanvas.test(TestCanvas.TEST_FILLROUNDRECT); + else if(getName().equals("testFillArc")) testCanvas.test(TestCanvas.TEST_FILLARC); + else if(getName().equals("testDrawArc")) testCanvas.test(TestCanvas.TEST_DRAWARC); + else if(getName().equals("testDrawString")) testCanvas.test(TestCanvas.TEST_DRAWSTRING); + else if(getName().equals("testDrawImage")) testCanvas.test(TestCanvas.TEST_DRAWIMAGE); + else if(getName().equals("testStrokeStyle")) testCanvas.test(TestCanvas.TEST_STROKESTYLE); + else if(getName().equals("testDrawRGB")) + { + DISABLE_TEST(); + testCanvas.test(TestCanvas.TEST_DRAWRGB); + } + else if(getName().equals("testFillTriangle")) testCanvas.test(TestCanvas.TEST_FILLTRIANGLE); + else if(getName().equals("testCopyArea")) testCanvas.test(TestCanvas.TEST_COPYAREA); + else if(getName().equals("testDrawRegion")) testCanvas.test(TestCanvas.TEST_DRAWREGION); else super.runTest(); } @@ -138,7 +151,8 @@ // } // - class TestCanvas extends Canvas { + class TestCanvas extends Canvas + { static final int TEST_NONE = 0; static final int TEST_GRAPHICS = 1; @@ -166,15 +180,18 @@ private String failMsg; - public TestCanvas() { + public TestCanvas() + { }; - private void setFailMessage(String msg) { + private void setFailMessage(String msg) + { failMsg = msg; passed = (failMsg == null); } - public void test(int mode) { + public void test(int mode) + { setFailMessage(null); testMode = mode; testCanvas.repaint(); @@ -182,104 +199,112 @@ assertTrue(failMsg, passed); } - protected void paint(Graphics g) { - try { - switch (testMode) { - case TEST_NONE: - break; + protected void paint(Graphics g) + { + try + { + switch(testMode) + { + case TEST_NONE: + break; - case TEST_GRAPHICS: - if (g == null) { - fail("Graphics object in Canvas.paint() is null"); - } - break; + case TEST_GRAPHICS: + if(g == null) + { + fail("Graphics object in Canvas.paint() is null"); + } + break; - case TEST_COLOR: - testColor(g); - break; - - case TEST_DRAWLINE: - testDrawLine(g); - break; + case TEST_COLOR: + testColor(g); + break; - case TEST_FILLRECT: - testFillRect(g); - break; + case TEST_DRAWLINE: + testDrawLine(g); + break; - case TEST_CLIP: - testClip(g); - break; + case TEST_FILLRECT: + testFillRect(g); + break; - case TEST_COPYAREA: - testCopyArea(g); - break; + case TEST_CLIP: + testClip(g); + break; - case TEST_DRAWROUNDRECT: - testDrawRoundRect(g); - break; + case TEST_COPYAREA: + testCopyArea(g); + break; - case TEST_DRAWRECT: - testDrawRect(g); - break; + case TEST_DRAWROUNDRECT: + testDrawRoundRect(g); + break; - case TEST_STROKESTYLE: - testStrokeStyle(g); - break; + case TEST_DRAWRECT: + testDrawRect(g); + break; - case TEST_TRANSLATE: - testTranslate(g); - break; + case TEST_STROKESTYLE: + testStrokeStyle(g); + break; - case TEST_FILLROUNDRECT: - testFillRoundRect(g); - break; + case TEST_TRANSLATE: + testTranslate(g); + break; - case TEST_FILLARC: - testFillArc(g); - break; + case TEST_FILLROUNDRECT: + testFillRoundRect(g); + break; - case TEST_DRAWARC: - testDrawArc(g); - break; + case TEST_FILLARC: + testFillArc(g); + break; - case TEST_FILLTRIANGLE: - testFillTriangle(g); - break; + case TEST_DRAWARC: + testDrawArc(g); + break; - case TEST_DRAWSTRING: - testDrawString(g); - break; + case TEST_FILLTRIANGLE: + testFillTriangle(g); + break; + + case TEST_DRAWSTRING: + testDrawString(g); + break; - case TEST_DRAWIMAGE: - testDrawImage(g); - break; + case TEST_DRAWIMAGE: + testDrawImage(g); + break; - case TEST_DRAWRGB: - testDrawRGB(g); - break; - case TEST_DRAWREGION: - testDrawRegion(g); - break; - default: + case TEST_DRAWRGB: + testDrawRGB(g); + break; + case TEST_DRAWREGION: + testDrawRegion(g); + break; + default: } } /*catch (AssertionFailedException afe) { setFailMessage(afe.getMessage()); }*/ - catch (Exception e) { + catch(Exception e) + { setFailMessage("Unhandled exception" + e.getMessage()); } testMode = TEST_NONE; } - private void testDrawImage(Graphics g) { + private void testDrawImage(Graphics g) + { String imgFile = "image1.jpg"; Image testImage = null; - try { + try + { testImage = Image.createImage(imgFile); } - catch (Exception e) { + catch(Exception e) + { fail("Unable to load " + imgFile + " image for test"); } @@ -287,86 +312,101 @@ g.drawImage(testImage, Integer.MAX_VALUE, Integer.MIN_VALUE, 0); g.drawImage(testImage, 50, 50, Graphics.HCENTER | Graphics.VCENTER); - try { + try + { g.drawImage(null, 0, 0, 0); fail("NullPointerException not thrown at Graphics.drawImage"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // ok } // Test invalid anchors - try { + try + { g.drawImage(testImage, 50, 50, - Graphics.HCENTER | Graphics.LEFT); + Graphics.HCENTER | Graphics.LEFT); g.drawImage(testImage, 50, 50, Graphics.VCENTER | Graphics.LEFT - | Graphics.TOP); + | Graphics.TOP); g.drawImage(testImage, 50, 50, Graphics.RIGHT | Graphics.LEFT); fail("IllegalArgumentException not thrown at Graphics.drawImage"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // ok } } - private void testDrawString(Graphics g) { + private void testDrawString(Graphics g) + { // Tests for Graphics.drawString g.drawString("TestString", 10, 10, Graphics.TOP | Graphics.LEFT); - try { + try + { g.drawString(null, 0, 0, Graphics.TOP | Graphics.LEFT); fail("NullPointerException not thrown " - + "as expected in Graphics.drawString()"); + + "as expected in Graphics.drawString()"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } - try { + try + { g.drawString("TestString", 10, 0, Graphics.TOP - | Graphics.BOTTOM); + | Graphics.BOTTOM); fail("IllegalArgumentException not thrown " - + "as expected in Graphics.drawString()"); + + "as expected in Graphics.drawString()"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Tests for Graphics.drawSubString g.drawSubstring("TestString", 3, 5, 10, 10, Graphics.TOP - | Graphics.LEFT); + | Graphics.LEFT); - try { + try + { g.drawSubstring(null, 2, 4, 10, 10, Graphics.TOP - | Graphics.LEFT); + | Graphics.LEFT); fail("NullPointerException not thrown " - + "as expected in Graphics.drawSubString()"); + + "as expected in Graphics.drawSubString()"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } - try { + try + { g.drawSubstring("TestString", 0, 4, 10, 0, Graphics.LEFT - | Graphics.RIGHT); + | Graphics.RIGHT); fail("IllegalArgumentException not " - + "thrown as expected in Graphics.drawSubString()"); + + "thrown as expected in Graphics.drawSubString()"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } - try { + try + { g.drawSubstring("TestString", 5, 20, 0, 0, Graphics.LEFT - | Graphics.RIGHT); + | Graphics.RIGHT); fail("StringIndexOutOfBoundsException " - + "not thrown as expected in " - + "Graphics.drawSubString()"); + + "not thrown as expected in " + + "Graphics.drawSubString()"); } - catch (StringIndexOutOfBoundsException e) { + catch(StringIndexOutOfBoundsException e) + { // Ok } @@ -378,136 +418,159 @@ // g.drawChar('\t', 10, 10, Graphics.TOP | Graphics.LEFT); // g.drawChar('\u00FE', 10, 30, Graphics.TOP | Graphics.LEFT); - try { + try + { g.drawChar('X', 10, 0, Graphics.TOP | Graphics.BASELINE - | Graphics.LEFT | Graphics.HCENTER); + | Graphics.LEFT | Graphics.HCENTER); fail("IllegalArgumentException not " - + "thrown as expected in Graphics.drawChar()"); + + "thrown as expected in Graphics.drawChar()"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Tests for Graphics.drawChars char[] testChars = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', - 'l', 'd',}; + 'l', 'd', + }; g.drawChars(testChars, 0, 5, 10, 10, Graphics.TOP | Graphics.LEFT); - try { + try + { g.drawChars(testChars, 5, 3, 10, 0, Graphics.TOP - | Graphics.BASELINE | Graphics.LEFT | Graphics.HCENTER); + | Graphics.BASELINE | Graphics.LEFT | Graphics.HCENTER); fail("IllegalArgumentException not " - + "thrown as expected in Graphics.drawChars()"); + + "thrown as expected in Graphics.drawChars()"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } - try { + try + { g.drawChars(null, 1, 3, 10, 0, Graphics.TOP | Graphics.LEFT); fail("NullPointerException " - + "not thrown as expected in Graphics.drawChars()"); + + "not thrown as expected in Graphics.drawChars()"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } - try { + try + { g.drawChars(testChars, 5, 20, 10, 0, Graphics.TOP - | Graphics.LEFT); + | Graphics.LEFT); fail("ArrayIndexOutOfBoundsException not" - + " thrown as expected in Graphics.drawChars()"); + + " thrown as expected in Graphics.drawChars()"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } } - private void testFillTriangle(Graphics g) { + private void testFillTriangle(Graphics g) + { g.fillTriangle(0, 0, 0, 0, 0, 0); g.fillTriangle(0, 0, -100, 20, 50, -35); g.fillTriangle(Integer.MIN_VALUE, Integer.MIN_VALUE, - Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, - Integer.MAX_VALUE); + Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, + Integer.MAX_VALUE); } - private void testFillArc(Graphics g) { + private void testFillArc(Graphics g) + { g.fillArc(10, 10, 40, 20, 20, 300); g.fillArc(10, 10, -40, -20, 20, 300); g.fillArc(10, 10, 40, 20, 20, -300); g.fillArc(10, 10, 40, 20, -520, -300); } - private void testDrawArc(Graphics g) { + private void testDrawArc(Graphics g) + { g.drawArc(10, 10, 40, 20, 20, 300); g.drawArc(10, 10, -40, -20, 20, 300); g.drawArc(10, 10, 40, 20, 20, -300); g.drawArc(10, 10, 40, 20, -520, -300); } - private void testTranslate(Graphics g) { + private void testTranslate(Graphics g) + { int translateX = 10; int translateY = 12; g.translate(translateX, translateY); int returnX = g.getTranslateX(); - if (returnX != translateX) { + if(returnX != translateX) + { fail("Graphics.translate() and " - + "Graphics.getTranslateX() don't match - expected:" - + translateX + " , received:" + returnX); + + "Graphics.getTranslateX() don't match - expected:" + + translateX + " , received:" + returnX); } - if (g.getTranslateY() != translateY) { + if(g.getTranslateY() != translateY) + { fail("Graphics.translate() and " - + "Graphics.getTranslateY() don't match" + translateY - + " , received:" + g.getTranslateY()); + + "Graphics.getTranslateY() don't match" + translateY + + " , received:" + g.getTranslateY()); } } - private void testStrokeStyle(Graphics g) { + private void testStrokeStyle(Graphics g) + { int strokeStyle1 = Graphics.DOTTED; int strokeStyle2 = Graphics.SOLID; int strokeStyleInvalid = -1; g.setStrokeStyle(strokeStyle1); - if (g.getStrokeStyle() != strokeStyle1) { + if(g.getStrokeStyle() != strokeStyle1) + { fail("Graphics.setStrokeStyle() " - + "and Graphics.getStrokeStyle() don't match"); + + "and Graphics.getStrokeStyle() don't match"); } g.setStrokeStyle(strokeStyle2); - if (g.getStrokeStyle() != strokeStyle2) { + if(g.getStrokeStyle() != strokeStyle2) + { fail("Graphics.setStrokeStyle() " - + "and Graphics.getStrokeStyle() don't match"); + + "and Graphics.getStrokeStyle() don't match"); } - try { + try + { g.setStrokeStyle(strokeStyleInvalid); fail("Graphics.setStrokeStyle(): " - + "no exception thrown on invalid stroke style"); + + "no exception thrown on invalid stroke style"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } } - private void testDrawRect(Graphics g) { + private void testDrawRect(Graphics g) + { g.drawRect(0, 0, 120, 200); g.drawRect(-10, -20, -120, -200); g.drawRect(-10, -20, 120, 200); } - private void testDrawRoundRect(Graphics g) { + private void testDrawRoundRect(Graphics g) + { g.drawRoundRect(0, 0, 120, 200, 10, 5); g.drawRoundRect(-10, -20, -120, -200, -10, -5); g.drawRoundRect(-10, -20, 120, 200, 0, 0); } - private void testCopyArea(Graphics g) { + private void testCopyArea(Graphics g) + { final int fromX = 10; final int fromY = 15; final int width = 22; @@ -517,14 +580,16 @@ // Test IllegalStateException when the destination // of copyArea is the display device. - try { + try + { g.copyArea(fromX, fromY, width, height, destX, destY, - Graphics.TOP | Graphics.LEFT); + Graphics.TOP | Graphics.LEFT); fail("IllegalStateException not thrown as expected in " - + "testCopyArea"); + + "testCopyArea"); } - catch (IllegalStateException e) { + catch(IllegalStateException e) + { // Ok } @@ -536,22 +601,25 @@ // Test IllegalArgumentException when the region // exceeds the size of the image. - try { + try + { testGraphics.copyArea(fromX, fromY, imgW + 1, height, destX, - destY, Graphics.TOP | Graphics.LEFT); + destY, Graphics.TOP | Graphics.LEFT); fail("IllegalArgumentException not thrown as " - + "expected in testCopyArea"); + + "expected in testCopyArea"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } testGraphics.copyArea(fromX, fromY, width, height, destX, destY, - Graphics.TOP | Graphics.LEFT); + Graphics.TOP | Graphics.LEFT); } - private void testClip(Graphics g) { + private void testClip(Graphics g) + { final int clipX = 10; final int clipY = 20; final int clipW = 40; @@ -559,24 +627,28 @@ g.setClip(clipX, clipY, clipW, clipH); - if (g.getClipX() != clipX) { + if(g.getClipX() != clipX) + { fail("Graphics.setClip() " - + "and Graphics.getClipX() don't match"); + + "and Graphics.getClipX() don't match"); } - if (g.getClipY() != clipY) { + if(g.getClipY() != clipY) + { fail("Graphics.setClip() " - + "and Graphics.getClipY() don't match"); + + "and Graphics.getClipY() don't match"); } - if (g.getClipWidth() != clipW) { + if(g.getClipWidth() != clipW) + { fail("Graphics.setClip() " - + "and Graphics.getClipWidth() don't match"); + + "and Graphics.getClipWidth() don't match"); } - if (g.getClipHeight() != clipH) { + if(g.getClipHeight() != clipH) + { fail("Graphics.setClip() " - + "and Graphics.getClipHeight() don't match"); + + "and Graphics.getClipHeight() don't match"); } final int newClipX = 15; @@ -586,85 +658,103 @@ g.clipRect(newClipX, newClipY, newClipW, newClipH); - if (g.getClipX() != newClipX) { + if(g.getClipX() != newClipX) + { fail("Graphics.clipRect() " - + "and Graphics.getClipX() don't match"); + + "and Graphics.getClipX() don't match"); } - if (g.getClipY() != newClipY) { + if(g.getClipY() != newClipY) + { fail("Graphics.clipRect() " - + "and Graphics.getClipY() don't match"); + + "and Graphics.getClipY() don't match"); } - if (g.getClipWidth() != clipW - (newClipX - clipX)) { + if(g.getClipWidth() != clipW - (newClipX - clipX)) + { fail("Graphics.clipRect() " - + "and Graphics.getClipWidth() don't match"); + + "and Graphics.getClipWidth() don't match"); } - if (g.getClipHeight() != clipH - (newClipY - clipY)) { + if(g.getClipHeight() != clipH - (newClipY - clipY)) + { fail("Graphics.clipRect() " - + "and Graphics.getClipHeight() don't match"); + + "and Graphics.getClipHeight() don't match"); } } - private void testDrawLine(Graphics g) { + private void testDrawLine(Graphics g) + { g.drawLine(0, 0, 10, 10); g.setColor(255, 0, 0); g.drawLine(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, - Integer.MAX_VALUE); + Integer.MAX_VALUE); } - private void testFillRect(Graphics g) { + private void testFillRect(Graphics g) + { g.fillRect(0, 0, 10, 10); g.fillRect(0, 0, -10, -10); g.setColor(255, 0, 0); g.fillRect(Integer.MIN_VALUE, Integer.MIN_VALUE, - Integer.MAX_VALUE, Integer.MAX_VALUE); + Integer.MAX_VALUE, Integer.MAX_VALUE); } - private void testFillRoundRect(Graphics g) { + private void testFillRoundRect(Graphics g) + { g.fillRoundRect(0, 0, 10, 10, 3, 3); g.fillRoundRect(0, 0, -10, -10, -5, -3); g.setColor(255, 0, 0); g.fillRoundRect(Integer.MIN_VALUE, Integer.MIN_VALUE, - Integer.MAX_VALUE, Integer.MAX_VALUE, - Integer.MAX_VALUE, Integer.MAX_VALUE); + Integer.MAX_VALUE, Integer.MAX_VALUE, + Integer.MAX_VALUE, Integer.MAX_VALUE); } - private void testColor(Graphics g) { + private void testColor(Graphics g) + { boolean passed1 = false, passed2 = false, passed3 = false; // test InvalidArgumentException - try { + try + { g.setColor(256, 255, 255); } - catch (Exception e) { - if (e instanceof IllegalArgumentException) { + catch(Exception e) + { + if(e instanceof IllegalArgumentException) + { passed1 = true; } } - try { + try + { g.setColor(0, 256, 255); } - catch (Exception e) { - if (e instanceof IllegalArgumentException) { + catch(Exception e) + { + if(e instanceof IllegalArgumentException) + { passed2 = true; } } - try { + try + { g.setColor(0, 255, 256); } - catch (Exception e) { - if (e instanceof IllegalArgumentException) { + catch(Exception e) + { + if(e instanceof IllegalArgumentException) + { passed3 = true; } } - if (!(passed1 & passed2 & passed3)) { + if(!(passed1 & passed2 & passed3)) + { fail("IllegalArgumentException " + "not thrown for invalid " - + "input in Graphics.setColor()"); + + "input in Graphics.setColor()"); } int red = 45; @@ -673,19 +763,22 @@ g.setColor(red, green, blue); - if (g.getRedComponent() != red) { + if(g.getRedComponent() != red) + { fail("Graphics.setColor(int, int, int) and" - + " Graphics.getRedComponent() do not match"); + + " Graphics.getRedComponent() do not match"); } - if (g.getGreenComponent() != green) { + if(g.getGreenComponent() != green) + { fail("Graphics.setColor(int, int, int) and" - + " Graphics.getGreenComponent() do not match"); + + " Graphics.getGreenComponent() do not match"); } - if (g.getBlueComponent() != blue) { + if(g.getBlueComponent() != blue) + { fail("Graphics.setColor(int, int, int) and" - + "Graphics.getBlueComponent() do not match"); + + "Graphics.getBlueComponent() do not match"); } int color = red << 16 | green << 8 | blue; // 0x00RRGGBB @@ -693,74 +786,90 @@ g.setColor(0xAB << 24 | color); // 0x(dirt)RRGGBB int testColor = g.getColor(); - if (testColor != color) { + if(testColor != color) + { fail("Graphics.setColor(int) " - + "and Graphics.getColor() do not match"); + + "and Graphics.getColor() do not match"); } - if (g.getRedComponent() != red) { + if(g.getRedComponent() != red) + { fail("Graphics.setColor(int)" - + "and Graphics.getRedComponent() do not match"); + + "and Graphics.getRedComponent() do not match"); } - if (g.getGreenComponent() != green) { + if(g.getGreenComponent() != green) + { fail("Graphics.setColor(int) " - + "and Graphics.getGreenComponent()" + " do not match"); + + "and Graphics.getGreenComponent()" + " do not match"); } - if (g.getBlueComponent() != blue) { + if(g.getBlueComponent() != blue) + { fail("Graphics.setColor(int) " - + "and Graphics.getBlueComponent() do not match"); + + "and Graphics.getBlueComponent() do not match"); } int gray = 152; g.setGrayScale(gray); - if (g.getGrayScale() != gray) { + if(g.getGrayScale() != gray) + { fail("Graphics.setGrayScale(int) " - + "and Graphics.getGrayScale() do not match"); + + "and Graphics.getGrayScale() do not match"); } } - private void testDrawRGB(Graphics g) { - + private void testDrawRGB(Graphics g) + { + // Test NullPointerException - try { + try + { g.drawRGB(null, 0, 1, 0, 0, 1, 1, true); fail("NullPointerException " + "not thrown in testDrawRGB"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { } // Test ArrayIndexOutOfBoundsException int[] rgb = {0x00000000, 0x11111111, 0x22222222, 0x33333333, - 0x44444444, 0x55555555, 0x66666666, 0x77777777}; - try { + 0x44444444, 0x55555555, 0x66666666, 0x77777777 + }; + try + { g.drawRGB(rgb, 0, 4, 0, 0, 4, 4, true); fail("ArrayIndexOutOfBoundsException " - + "not thrown in testDrawRGB. 1"); + + "not thrown in testDrawRGB. 1"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } - try { + try + { g.drawRGB(rgb, 0, 16, 0, 0, 4, 2, true); fail("ArrayIndexOutOfBoundsException " - + "not thrown in testDrawRGB. 2"); + + "not thrown in testDrawRGB. 2"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } } - private void testDrawRegion(Graphics g) { + private void testDrawRegion(Graphics g) + { // Test NullPointerException - try { + try + { g.drawRegion(null, 0, 0, 1, 1, 0, 0, 0, 0); fail("NullPointerException " + "not thrown in testDrawRegion"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } @@ -769,60 +878,68 @@ Image srcImage = Image.createImage(30, 30); Graphics srcImageGraphics = srcImage.getGraphics(); - try { + try + { srcImageGraphics.drawRegion(srcImage, 0, 0, 1, 1, - Sprite.TRANS_NONE, 0, 0, 0); + Sprite.TRANS_NONE, 0, 0, 0); fail("IllegalArgumentException for the same source " - + "and destination not thrown in testDrawRegion"); + + "and destination not thrown in testDrawRegion"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Test IllegalArgumentException for illegal transform - try { + try + { g.drawRegion(srcImage, 0, 0, 1, 1, - // invalid transform - Sprite.TRANS_NONE + 100, 0, 0, 0); + // invalid transform + Sprite.TRANS_NONE + 100, 0, 0, 0); fail("IllegalArgumentException not thrown for invalid " - + "transform in testDrawRegion"); + + "transform in testDrawRegion"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Test IllegalArgumentException for illegal anchor - try { + try + { g.drawRegion(srcImage, 0, 0, 1, 1, - // invalid transform - Sprite.TRANS_NONE, 0, 0, Graphics.LEFT - | Graphics.RIGHT); + // invalid transform + Sprite.TRANS_NONE, 0, 0, Graphics.LEFT + | Graphics.RIGHT); fail("IllegalArgumentException not thrown for invalid " - + "anchor in testDrawRegion"); + + "anchor in testDrawRegion"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Test IllegalArgumentException for illegal region - try { + try + { g.drawRegion(srcImage, -1, 0, 1, 1, - // invalid transform - Sprite.TRANS_NONE, 0, 0, Graphics.LEFT); + // invalid transform + Sprite.TRANS_NONE, 0, 0, Graphics.LEFT); fail("IllegalArgumentException not thrown for invalid " - + "region in testDrawRegion"); + + "region in testDrawRegion"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } // Test valid inputs g.drawRegion(srcImage, 10, 10, 5, 5, Sprite.TRANS_MIRROR_ROT270, 1, - 1, Graphics.TOP | Graphics.LEFT); + 1, Graphics.TOP | Graphics.LEFT); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/image/ImageTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/image/ImageTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/image/ImageTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.image; @@ -29,12 +29,14 @@ /** * Unit tests for LCDUI Image class. */ -public class ImageTest extends SWTTestCase { +public class ImageTest extends SWTTestCase +{ /** * Constructor. */ - public ImageTest() { + public ImageTest() + { } /** @@ -43,7 +45,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ImageTest(String sTestName) { + public ImageTest(String sTestName) + { super(sTestName); } @@ -53,23 +56,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = ImageTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ImageTest((String)e.nextElement())); - } + // Add widget tests + methodNames = ImageTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ImageTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCreate"); methodNames.addElement("testCreateFromFile"); @@ -80,45 +86,51 @@ methodNames.addElement("testGetRGB"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testCreate")) testCreate(); - else if (getName().equals("testCreateFromFile")) testCreateFromFile(); - else if (getName().equals("testCreateFromImage")) testCreateFromImage(); - else if (getName().equals("testCreateFromARGB")) testCreateFromARGB(); - else if (getName().equals("testCreateFromDataBuffer")) testCreateFromDataBuffer(); - else if (getName().equals("testCreateFromImageTrans")) testCreateFromImageTrans(); - else if (getName().equals("testGetRGB")) testGetRGB(); + + protected void runTest() throws Throwable + { + if(getName().equals("testCreate")) testCreate(); + else if(getName().equals("testCreateFromFile")) testCreateFromFile(); + else if(getName().equals("testCreateFromImage")) testCreateFromImage(); + else if(getName().equals("testCreateFromARGB")) testCreateFromARGB(); + else if(getName().equals("testCreateFromDataBuffer")) testCreateFromDataBuffer(); + else if(getName().equals("testCreateFromImageTrans")) testCreateFromImageTrans(); + else if(getName().equals("testGetRGB")) testGetRGB(); else super.runTest(); } - - + + /** * Tests for image creation. * Tests Image.createImage(int width, int height). */ - public void testCreate() { + public void testCreate() + { Image testImage = null; final int testSize = 20; // Test IllegalArgumentException - try { + try + { testImage = Image.createImage(0, -1); fail("No IllegalArgumentException calling " - + "Image.createImage(0, -1); in testCreateImage1"); + + "Image.createImage(0, -1); in testCreateImage1"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } // Test valid inputs - try { + try + { testImage = Image.createImage(testSize, testSize); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling Image.createImage(" - + testSize + ", " + testSize - + ") in testCreateImage1:" + e); + + testSize + ", " + testSize + + ") in testCreateImage1:" + e); } assertTrue("Image.createImage(int, int) " @@ -140,12 +152,14 @@ + "expected - true", testImage.isMutable()); - try { + try + { testImage.getGraphics(); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception on Image.getGraphics() " - + "for immutable Image in testCreateImage2: " + e); + + "for immutable Image in testCreateImage2: " + e); } @@ -174,33 +188,40 @@ * Tests for image creation from a file. * Tests Image.createImage(String fileName) */ - public void testCreateFromFile() { + public void testCreateFromFile() + { Image testImage = null; // Test NullPointerException - try { + try + { testImage = Image.createImage((String) null); fail("NullPointerException not thrown in createImage(null)"); } - catch (NullPointerException ioE) { - // Ok + catch(NullPointerException ioE) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling " + "Image.createImage(null) in testCreateImage2: " + e); } // Test createImage for non-existing file String invalidName = "12345678.90"; - try { + try + { testImage = Image.createImage(invalidName); fail("IOException not thrown when calling Image.createImage(invalidName)"); } - catch (IOException ioE) { - // Ok + catch(IOException ioE) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling " + "Image.createImage(invalidName) in testCreateImage2: " + e); } @@ -212,7 +233,7 @@ fail("IOException not thrown when calling Image.createImage(invalidFile)"); } catch (IOException ioE) { - // Ok + // Ok } catch (Exception e) { fail("Unexpected exception calling " @@ -221,13 +242,16 @@ // Test createImage for the file that contains valid data String imgFile = "image1.jpg"; - try { + try + { testImage = Image.createImage(imgFile); } - catch (IOException ioE) { + catch(IOException ioE) + { fail("I/O exception in testCreateImage2"); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception in testCreateImage2: " + e); } @@ -240,16 +264,19 @@ + "expected - false", !testImage.isMutable()); - try { + try + { Graphics g = testImage.getGraphics(); fail("IllegalStateException not thrown for Image.getGraphics with immutable Image"); } - catch (IllegalStateException e) { - // Ok + catch(IllegalStateException e) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception on Image.getGraphics() " - + "for immutable Image in testCreateImage2: " + e); + + "for immutable Image in testCreateImage2: " + e); } } @@ -257,45 +284,54 @@ * Tests for image creation from another image. * Tests Image.createImage(Image img) */ - public void testCreateFromImage() { + public void testCreateFromImage() + { Image srcImage = null; Image testImage = null; // Test NullPointerException - try { + try + { testImage = Image.createImage((Image) null); fail("NullPointerException not thrown in createImage(null)"); } - catch (NullPointerException ioE) { - // Ok + catch(NullPointerException ioE) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling " + "Image.createImage(null) in testCreateImage3: " + e); } final int testSize = 20; - try { + try + { srcImage = Image.createImage(testSize, testSize); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling Image.createImage(" - + testSize + ", " + testSize - + ") in testCreateImage3: " + e); + + testSize + ", " + testSize + + ") in testCreateImage3: " + e); } - try { + try + { testImage = Image.createImage(srcImage); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling Image.createImage(Image)" - + " in testCreateImage3: " + e); + + " in testCreateImage3: " + e); } assertTrue("Image.createImage(Image) returned null in testCreateImage3", - testImage != null); + testImage != null); - if (testImage.isMutable()) { + if(testImage.isMutable()) + { fail("Image must be immutable in testCreateImage3"); } } @@ -307,9 +343,11 @@ int height, boolean processAlpha); */ - public void testCreateFromARGB() { + public void testCreateFromARGB() + { - final int[] argb = { + final int[] argb = + { 0xFFFFFFFF, 0x00000000, 0x01010101, @@ -321,54 +359,65 @@ Image testImage = null; // Test NullPoiterException - try { - testImage = Image.createRGBImage(null, w, h, true); - fail("NullPointerException not thrown on Image.createRGBImage(null, w, h, true)"); - } - catch (NullPointerException e) { - // Ok - } - catch (Exception e) { - fail("Unexpected exception calling " - + "Image.createRGBImage(null, w, h, true);" - + " in testCreateRGBImage: " + e); - } + try + { + testImage = Image.createRGBImage(null, w, h, true); + fail("NullPointerException not thrown on Image.createRGBImage(null, w, h, true)"); + } + catch(NullPointerException e) + { + // Ok + } + catch(Exception e) + { + fail("Unexpected exception calling " + + "Image.createRGBImage(null, w, h, true);" + + " in testCreateRGBImage: " + e); + } - // Test IllegalArgumentException - try { - testImage = Image.createRGBImage(argb, 0, -1, true); - fail("IllegalArgumentException not thrown on Image.createRGBImage(argb, 0, -1, true)"); - } - catch (IllegalArgumentException e) { - // Ok - } - catch (Exception e) { - fail("Unexpected exception " - + "calling Image.createRGBImage(argb, 0, -1, true); " - + "in testCreateRGBImage: " + e); - } + // Test IllegalArgumentException + try + { + testImage = Image.createRGBImage(argb, 0, -1, true); + fail("IllegalArgumentException not thrown on Image.createRGBImage(argb, 0, -1, true)"); + } + catch(IllegalArgumentException e) + { + // Ok + } + catch(Exception e) + { + fail("Unexpected exception " + + "calling Image.createRGBImage(argb, 0, -1, true); " + + "in testCreateRGBImage: " + e); + } - // Test ArrayIndexOutOfBoundsException - try { - testImage = Image.createRGBImage(argb, 2 * w, h, true); - fail("ArrayIndexOutOfBoundsException not thrown on Image.createRGBImage(argb, 2 * w, h, true)"); - } - catch (ArrayIndexOutOfBoundsException e) { - // Ok - } - catch (Exception e) { + // Test ArrayIndexOutOfBoundsException + try + { + testImage = Image.createRGBImage(argb, 2 * w, h, true); + fail("ArrayIndexOutOfBoundsException not thrown on Image.createRGBImage(argb, 2 * w, h, true)"); + } + catch(ArrayIndexOutOfBoundsException e) + { + // Ok + } + catch(Exception e) + { fail("Unexpected exception calling " + "Image.createRGBImage(argb, 2 * w, h, true); " + "in testCreateRGBImage: " + e); } // Test valid inputs - try { + try + { testImage = Image.createRGBImage(argb, w, h, true); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception calling Image.createImage(Image)" - + " in testCreateRGBImage: " + e); + + " in testCreateRGBImage: " + e); } assertTrue("Image.createRGBImage() returned null", testImage != null); @@ -379,47 +428,56 @@ * Tests for image creation from an encoded data buffer. * Tests Image.createImage(byte[] data, int offset, int dataLength). */ - public void testCreateFromDataBuffer() { + public void testCreateFromDataBuffer() + { - DISABLE_TEST(); + DISABLE_TEST(); Image testImage = null; String imgFile = "/image1.jpg"; int dataLen = 0; byte[] dataBuffer = null; // Test NullPointerException - try { + try + { testImage = Image.createImage(null, 10, 10); fail("NullPointerException not thrown on Image.createImage(null, 10, 10)"); } - catch (NullPointerException e) { - // Ok + catch(NullPointerException e) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unspecified exception in " + "Image.createImage(null, 10, 10) in testCreateImage5: " + e); } - try { + try + { java.io.InputStream fis = Image.class.getResourceAsStream(imgFile); dataLen = fis.available(); dataBuffer = new byte[dataLen]; fis.read(dataBuffer); fis.close(); } - catch (Exception e) { + catch(Exception e) + { fail("Exception reading a buffer in testCreateImage5: " + e); } // Test ArrayIndexOutOfBoundsException - try { + try + { testImage = Image.createImage(dataBuffer, 0, dataLen * 2); fail("ArrayIndexOutOfBoundsException not thrown on Image.createImage(dataBuffer, 0, dataLen*2)"); } - catch (ArrayIndexOutOfBoundsException e) { - // Ok + catch(ArrayIndexOutOfBoundsException e) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unspecified exception in " + "Image.createImage(dataBuffer, 0, dataLen*2)" + " in testCreateImage5: " + e); @@ -430,28 +488,34 @@ // create some invalid data byte[] invalidBuffer = new byte[dataLen]; System.arraycopy(dataBuffer, 0, invalidBuffer, 0, dataLen); - for (int i = 0; i < dataLen; i += 5) { - invalidBuffer[i] = (byte) (System.currentTimeMillis() % 255); + for(int i = 0; i < dataLen; i += 5) + { + invalidBuffer[i] = (byte)(System.currentTimeMillis() % 255); } - try { + try + { testImage = Image.createImage(invalidBuffer, 0, dataLen); fail("IllegalArgumentException not thrown on Image.createImage(invalidBuffer, 0, dataLen)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception in " + "Image.createImage(invalidBuffer, 0, dataLen) " + "in testCreateImage5: " + e); } // Test valid inputs - try { + try + { testImage = Image.createImage(dataBuffer, 0, dataLen); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception: " + e); } @@ -464,16 +528,19 @@ + "expected - false", !testImage.isMutable()); - try { + try + { Graphics g = testImage.getGraphics(); fail("IllegalStateException not thrown on Image.getGraphics for immutable Image"); } - catch (IllegalStateException e) { - // Ok + catch(IllegalStateException e) + { + // Ok } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception on Image.getGraphics() " - + "for immutable Image in testCreateImage5: " + e); + + "for immutable Image in testCreateImage5: " + e); } } @@ -482,84 +549,99 @@ * Tests Image.createImage(Image img, int x, int y, * int w, int h, int transform). */ - public void testCreateFromImageTrans() { + public void testCreateFromImageTrans() + { Image srcImage = null; Image testImage = null; final int INVALID_TRANSFORM = 0xfff; String imgFile = "image1.jpg"; - try { - try { + try + { + try + { srcImage = Image.createImage(imgFile); } - catch (IOException ioE) { + catch(IOException ioE) + { fail("I/O exception in testCreateImage6"); } // Test null source image - try { + try + { testImage = Image.createImage(null, 10, 10, 20, 30, Sprite.TRANS_NONE); fail("NullPointerException not thrown for null source image"); } - catch (NullPointerException e) { - // Ok + catch(NullPointerException e) + { + // Ok } // Test illegal width/height < 0 values - try { + try + { testImage = Image.createImage(srcImage, 10, 10, -1, 0, Sprite.TRANS_NONE); fail("IllegalArgumentException not thrown for width/height < 0"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } // Test invalid region bounds - try { + try + { testImage = Image.createImage(srcImage, -10, -10, 20, 30, Sprite.TRANS_NONE); fail("IllegalArgumentException not thrown for " + "negative bounds invalid region"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } - try { + try + { testImage = Image.createImage(srcImage, 10, 10, 2000, 30, Sprite.TRANS_NONE); fail("IllegalArgumentException not thrown " + "for too big invalid region"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } // Test invalid transform value - try { + try + { testImage = Image.createImage(srcImage, 10, 10, 20, 30, INVALID_TRANSFORM); fail("IllegalArgumentException not thrown " - + "for illegal transform "); + + "for illegal transform "); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } testImage = Image.createImage(srcImage, 10, 10, 20, 30, Sprite.TRANS_NONE); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception in testCreateImage6: " + e); e.printStackTrace(); } assertTrue("Image.createImage(Image img, int x, int y, int w, " - + "int h, int transform) returned null", testImage != null); + + "int h, int transform) returned null", testImage != null); } /** @@ -572,7 +654,8 @@ * int width, * int height) */ - public void testGetRGB() { + public void testGetRGB() + { String imgFile = "image1.jpg"; @@ -581,11 +664,14 @@ Image srcImage = null; - try { - try { + try + { + try + { srcImage = Image.createImage(imgFile); } - catch (IOException ioE) { + catch(IOException ioE) + { fail("Unable to load test image in testGetRGB"); } @@ -594,45 +680,54 @@ * srcImage.getHeight() / 10]; // Test NullPointerException - try { + try + { srcImage.getRGB(null, 10, 10, 10, 10, 10, 10); fail("NullPointerException not thrown in testGetRGB"); } - catch (NullPointerException e) { - // Ok + catch(NullPointerException e) + { + // Ok } // Test IllegalArgumentException on invalid bounds - try { + try + { srcImage.getRGB(longImgData, 0, 500, 0, 0, 1000, 1000); fail("IllegalArgumentException not thrown on invalid bounds (case1)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } // Test IllegalArgumentException if abs(scanlength) < width int regionWidth = 50; - try { + try + { srcImage.getRGB(longImgData, 0, regionWidth - 1, 0, 0, regionWidth, 10); fail("IllegalArgumentException not thrown on invalid bounds (case2)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } - try { + try + { srcImage.getRGB(longImgData, 0, -regionWidth + 1, 0, 0, regionWidth, 10); fail("IllegalArgumentException not thrown on invalid bounds (case3)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } // Test ArrayIndexOutOfBoundsException - try { + try + { int imgWidth = srcImage.getWidth(); int imgHeight = srcImage.getHeight(); srcImage.getRGB(shortImgData, 0, @@ -640,8 +735,9 @@ fail("ArrayIndexOutOfBoundsException not thrown"); } - catch (ArrayIndexOutOfBoundsException e) { - // Ok + catch(ArrayIndexOutOfBoundsException e) + { + // Ok } // Test valid inputs @@ -661,7 +757,8 @@ // assertTrue("Image.getRGB returned no RGB data with scanLength < 0", // longImgData[longImgData.length - 1] != 0); } - catch (Exception e) { + catch(Exception e) + { fail("Unexpected exception in testGetRGB: " + e); e.printStackTrace(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/imageitem/ImageItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/imageitem/ImageItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/imageitem/ImageItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.imageitem; @@ -32,7 +32,8 @@ *

            * Created: 2008-06-09 */ -public class ImageItemTest extends SWTTestCase { +public class ImageItemTest extends SWTTestCase +{ private static final int INVALID_APPEARANCE_MODE = 3; private static final int INVALID_LAYOUT = 4; @@ -40,21 +41,24 @@ /** * Constructor. */ - public ImageItemTest() { + public ImageItemTest() + { } /** * @param sTestName Test name. * @param rTestMethod Test method. */ - public ImageItemTest(String sTestName) { + public ImageItemTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { } /** @@ -63,109 +67,125 @@ * * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = ImageItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ImageItemTest((String)e.nextElement())); - } + // Add widget tests + methodNames = ImageItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ImageItemTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } - + /** * Tests the basic functionality of the accessor methods. */ - public void testAccessors() { + public void testAccessors() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; //Create new ImageItem with illegal layout directive: - try { + try + { ImageItem item = new ImageItem( - "", null, INVALID_LAYOUT, "", Item.PLAIN); + "", null, INVALID_LAYOUT, "", Item.PLAIN); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when creating ImageItem with" - + " illegal layout directive."; + + " illegal layout directive."; } //Create new ImageItem with invalid appearance mode: exceptionThrown = false; - try { + try + { ImageItem item = new ImageItem( - "", null, Item.LAYOUT_DEFAULT, "", INVALID_APPEARANCE_MODE); + "", null, Item.LAYOUT_DEFAULT, "", INVALID_APPEARANCE_MODE); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when creating ImageItem with" - + " invalid appearance mode."; + + " invalid appearance mode."; } //Create some new ImageItems with varied parameters: ImageItem item2 = new ImageItem( - null, null, Item.LAYOUT_DEFAULT, "altText", Item.PLAIN); + null, null, Item.LAYOUT_DEFAULT, "altText", Item.PLAIN); ImageItem item3 = new ImageItem( - "label", null, Item.LAYOUT_EXPAND, null, Item.BUTTON); + "label", null, Item.LAYOUT_EXPAND, null, Item.BUTTON); ImageItem item4 = new ImageItem( - "label", null, Item.LAYOUT_CENTER | Item.LAYOUT_NEWLINE_AFTER, - "altText", Item.HYPERLINK); + "label", null, Item.LAYOUT_CENTER | Item.LAYOUT_NEWLINE_AFTER, + "altText", Item.HYPERLINK); //Try to get alt text and change it and get it again: - if (item3.getAltText() != null) { + if(item3.getAltText() != null) + { testPassed = false; testMsg = " Alternate text not null when expected."; } item3.setAltText("altTestText"); - if (!item3.getAltText().equals("altTestText")) { + if(!item3.getAltText().equals("altTestText")) + { testPassed = false; testMsg = " Invalid alternate text returned."; } //Try to get appearance mode: - if (item3.getAppearanceMode() != Item.BUTTON) { + if(item3.getAppearanceMode() != Item.BUTTON) + { testPassed = false; testMsg = " Invalid appearance mode returned."; } //Try to get layout directive: - if (item4.getLayout() - != (Item.LAYOUT_CENTER | Item.LAYOUT_NEWLINE_AFTER)) { + if(item4.getLayout() + != (Item.LAYOUT_CENTER | Item.LAYOUT_NEWLINE_AFTER)) + { testPassed = false; testMsg = " Invalid layout returned."; } //Try to set layout and verify it is set correctly: item4.setLayout(Item.LAYOUT_RIGHT | Item.LAYOUT_SHRINK); - if (item4.getLayout() - != (Item.LAYOUT_RIGHT | Item.LAYOUT_SHRINK)) { + if(item4.getLayout() + != (Item.LAYOUT_RIGHT | Item.LAYOUT_SHRINK)) + { testPassed = false; testMsg = " Invalid layout returned after setting new layout."; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/item/ItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/item/ItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/item/ItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.item; @@ -30,7 +30,8 @@ *

            * Created: 2008-06-06 */ -public class ItemTest extends SWTTestCase implements ItemStateListener { +public class ItemTest extends SWTTestCase implements ItemStateListener +{ private static final int NOTIFY_STATE_CHANGED_DELAY = 100; @@ -50,22 +51,25 @@ /** * Constructor. */ - public ItemTest() { + public ItemTest() + { } /** * @param sTestName Test name. * @param rTestMethod Test method. */ - public ItemTest(String sTestName) { + public ItemTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - display = Display.getDisplay(getMIDlet()); + protected void setUp() throws Exception + { + display = Display.getDisplay(getMIDlet()); } /** @@ -73,23 +77,26 @@ * any new test methods, otherwise they won't be run. * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = ItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ItemTest((String)e.nextElement())); - } + // Add widget tests + methodNames = ItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ItemTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testLayoutAccessors"); methodNames.addElement("testCommandAccessors"); @@ -99,21 +106,23 @@ methodNames.addElement("testMinimumSizes"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testLayoutAccessors")) testLayoutAccessors(); - else if (getName().equals("testCommandAccessors")) testCommandAccessors(); - else if (getName().equals("testLabelAccessors")) testLabelAccessors(); - else if (getName().equals("testDimensions")) testDimensions(); - else if (getName().equals("testNotifyStateChanged")) testNotifyStateChanged(); - else if (getName().equals("testMinimumSizes")) testMinimumSizes(); + + protected void runTest() throws Throwable + { + if(getName().equals("testLayoutAccessors")) testLayoutAccessors(); + else if(getName().equals("testCommandAccessors")) testCommandAccessors(); + else if(getName().equals("testLabelAccessors")) testLabelAccessors(); + else if(getName().equals("testDimensions")) testDimensions(); + else if(getName().equals("testNotifyStateChanged")) testNotifyStateChanged(); + else if(getName().equals("testMinimumSizes")) testMinimumSizes(); else super.runTest(); } - + /** * Tests the basic functionality of the layout accessor methods. */ - public void testLayoutAccessors() { + public void testLayoutAccessors() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; @@ -123,26 +132,31 @@ //Set correct layout and verify that same layout is returned //from getter: item.setLayout(Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER); - if (item.getLayout() != (Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER)) { + if(item.getLayout() != (Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER)) + { testPassed = false; testMsg = " invalid layout returned."; } //Set incorrect layout and verify that exception is thrown: - try { + try + { item.setLayout(INVALID_ITEM_LAYOUT); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when setting invalid layout."; } //Verify the layout is not changed: - if (item.getLayout() != (Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER)) { + if(item.getLayout() != (Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER)) + { testPassed = false; testMsg = " invalid layout returned after exception."; } @@ -157,7 +171,8 @@ * invalid or valid calls won't break anything and exceptions * are thrown when expected. */ - public void testCommandAccessors() { + public void testCommandAccessors() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; @@ -168,13 +183,16 @@ Command c3 = new Command("label3", null, Command.ITEM, 0); //Try to add null command: - try { + try + { item.addCommand(null); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when adding null command."; } @@ -219,7 +237,8 @@ * of item because label is used in different eSWT components and * behaviour may vary when using null as a label. */ - public void testLabelAccessors() { + public void testLabelAccessors() + { boolean testPassed = true; String testMsg = ""; @@ -229,14 +248,16 @@ item.setLabel("test label 1"); //Try to get label and verify it's the one previously set: - if (!item.getLabel().equals("test label 1")) { + if(!item.getLabel().equals("test label 1")) + { testPassed = false; testMsg = " Invalid label returned."; } //Try to set null label and verify it is null when queried: item.setLabel(null); - if (item.getLabel() != null) { + if(item.getLabel() != null) + { testPassed = false; testMsg = " non-null label returned."; } @@ -247,7 +268,8 @@ /** * Tests the basic functionality of item dimension related methods. */ - public void testDimensions() { + public void testDimensions() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; @@ -256,27 +278,33 @@ //Call setPreferredSize with illegal values and verify that //exception is thrown: - try { + try + { item.setPreferredSize(INVALID_PREFERRED_WIDTH, 0); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when setting preferred size with" - + " invalid width"; + + " invalid width"; } - try { + try + { item.setPreferredSize(0, INVALID_PREFERRED_HEIGHT); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when setting preferred size with" - + " invalid height"; + + " invalid height"; } //Lock preferred width and height and verify that correct @@ -285,12 +313,14 @@ //set here but this test assumes that values returned are same) item.setPreferredSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); - if (item.getPreferredWidth() != PREFERRED_WIDTH) { + if(item.getPreferredWidth() != PREFERRED_WIDTH) + { testPassed = false; testMsg = " Invalid preferred width returned."; } - if (item.getPreferredHeight() != PREFERRED_HEIGHT) { + if(item.getPreferredHeight() != PREFERRED_HEIGHT) + { testPassed = false; testMsg = " Invalid preferred height returned."; } @@ -299,9 +329,10 @@ // width is not that big. (There should be limit for maximum // width but no limit for height) item.setPreferredSize(BIG_PREFERRED_WIDTH, - BIG_PREFERRED_HEIGHT); + BIG_PREFERRED_HEIGHT); - if (item.getPreferredWidth() == BIG_PREFERRED_WIDTH) { + if(item.getPreferredWidth() == BIG_PREFERRED_WIDTH) + { testPassed = false; testMsg = " Too big preferred width allowed."; } @@ -315,7 +346,8 @@ * because the method is asynchronous. * */ - public void testNotifyStateChanged() { + public void testNotifyStateChanged() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; @@ -324,16 +356,19 @@ //Make sure that the method under test throws exception //if called when item is not owned by a form. - try { + try + { item.notifyStateChanged(); } - catch (IllegalStateException ex) { + catch(IllegalStateException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when calling notifyStateChanged" - + " and item is not owned by a form."; + + " and item is not owned by a form."; } assertTrue(getName() + " failed, " + testMsg, testPassed); @@ -346,7 +381,7 @@ //block(NOTIFY_STATE_CHANGED_DELAY); assertNull("notifyStateChanged() called listener but listener not" - + "added to Form.", latestStateListenerItem); + + "added to Form.", latestStateListenerItem); //Add listener and then test method again: form.setItemStateListener(this); @@ -354,14 +389,15 @@ block(NOTIFY_STATE_CHANGED_DELAY); assertEquals("notifyStateChanged() failed.", - item, latestStateListenerItem); + item, latestStateListenerItem); } /** * Tests the functionality of the methods getMinimumHeight() * and getMinimumWidth(). */ - public void testMinimumSizes() { + public void testMinimumSizes() + { int w; int h; @@ -372,20 +408,22 @@ //If image is null, then the values should be same as returned from //Display's getBestImageWidth/Height (+ label if present): assertEquals( - "ImageItem with null image returned invalid minimum width.", - w, display.getBestImageWidth(Display.CHOICE_GROUP_ELEMENT)); + "ImageItem with null image returned invalid minimum width.", + w, display.getBestImageWidth(Display.CHOICE_GROUP_ELEMENT)); assertEquals( - "ImageItem with null image returned invalid minimum height.", - h, display.getBestImageHeight(Display.CHOICE_GROUP_ELEMENT)); + "ImageItem with null image returned invalid minimum height.", + h, display.getBestImageHeight(Display.CHOICE_GROUP_ELEMENT)); //print("Minimum size of null ImageItem without label and " // + "with altText was: w=" + w + ", h=" + h); //Test ImageItem with image: Image image = null; - try { + try + { image = Image.createImage("100x100.png"); } - catch (Exception e) { + catch(Exception e) + { fail("Exception - " + e.getMessage()); } ImageItem imageItem2 = new ImageItem("label", image, 0, "altText"); @@ -432,7 +470,8 @@ * Receives events when item's state has changed. * @param item Item which state has changed. */ - public void itemStateChanged(Item item) { + public void itemStateChanged(Item item) + { latestStateListenerItem = item; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/list/ListTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/list/ListTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/list/ListTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.list; @@ -32,7 +32,8 @@ * * @created 1.8.2008 */ -public class ListTest extends SWTTestCase { +public class ListTest extends SWTTestCase +{ private static final int NUMITEMS = 20; @@ -41,7 +42,8 @@ /** * Constructor. */ - public ListTest() { + public ListTest() + { } /** @@ -50,19 +52,23 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public ListTest(String sTestName) { + public ListTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - super.setUp(); - try { + protected void setUp() throws Exception + { + super.setUp(); + try + { itemImage = Image.createImage("32x32.jpg"); } - catch (IOException ioe) { + catch(IOException ioe) + { ioe.printStackTrace(); } } @@ -73,46 +79,53 @@ * * @return New TestSuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = ListTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ListTest((String)e.nextElement())); - } + // Add widget tests + methodNames = ListTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ListTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructors"); methodNames.addElement("testAccessors"); methodNames.addElement("testMultiList"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructors")) testConstructors(); - else if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testMultiList")) testMultiList(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructors")) testConstructors(); + else if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testMultiList")) testMultiList(); else super.runTest(); } /** * Test method. */ - public void testConstructors() { - try { + public void testConstructors() + { + try + { new List(null, 0); fail("IllegalArgumentException should be thrown"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -122,35 +135,42 @@ new List(null, Choice.IMPLICIT); - try { + try + { new List(null, Choice.IMPLICIT, null, null); fail("NullPointerException should be thrown"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } String[] goodStrArr = new String[] {"1", "2", "3", "4" }; String[] badStrArr = new String[] {"1", null, "2", "3" }; Image[] goodImgArr = new Image[] {itemImage, itemImage, itemImage, - itemImage, }; + itemImage, + }; Image[] badImgArr = new Image[] {itemImage, itemImage, itemImage, }; - try { + try + { new List(null, Choice.IMPLICIT, badStrArr, null); fail("NullPointerException should be thrown - " - + "for null item in text array"); + + "for null item in text array"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } - try { + try + { new List(null, Choice.IMPLICIT, goodStrArr, badImgArr); fail("IllegalArgumentException should be thrown - " - + "text and image array length mismatch"); + + "text and image array length mismatch"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -161,94 +181,109 @@ /** * Test method. */ - public void testAccessors() { + public void testAccessors() + { List list = new List(null, Choice.IMPLICIT); list.setFitPolicy(Choice.TEXT_WRAP_DEFAULT); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_DEFAULT, list - .getFitPolicy()); + .getFitPolicy()); list.setFitPolicy(Choice.TEXT_WRAP_ON); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_ON, list - .getFitPolicy()); + .getFitPolicy()); list.setFitPolicy(Choice.TEXT_WRAP_OFF); assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_OFF, list - .getFitPolicy()); + .getFitPolicy()); - try { + try + { list.setFitPolicy(Choice.TEXT_WRAP_OFF + 1); fail("IllegalArgumentException not thrown - " - + "for invalid fit policy"); + + "for invalid fit policy"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { assertEquals("Fitpolicy mismatch", Choice.TEXT_WRAP_OFF, list - .getFitPolicy()); + .getFitPolicy()); } // append - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.append("item" + i, itemImage); } assertEquals("List size - after append", NUMITEMS, list.size()); // invalid append - try { + try + { list.append(null, itemImage); fail("NullPointerException not thrown - " - + "for invalid string append"); + + "for invalid string append"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // Fall-through } // delete - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.delete(0); } assertEquals("List size - after delete", 0, list.size()); // insert - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.insert(0, "item" + i, itemImage); } assertEquals("List size - after insert", NUMITEMS, list.size()); // invalid insert - try { + try + { list.insert(NUMITEMS * 2, "item" + NUMITEMS * 2, itemImage); fail("IndexOutOfBoundsException not thrown - " - + "for invalid insert index"); + + "for invalid insert index"); } - catch (IndexOutOfBoundsException iobe) { + catch(IndexOutOfBoundsException iobe) + { // Fall-through } // set - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.set(i, "item" + i * 2, itemImage); } assertEquals("List size - after set", NUMITEMS, list.size()); // check item strings individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertEquals("Item " + i + " mismatch", "item" + i * 2, list - .getString(i)); + .getString(i)); } // create fonts to plain=0, bold=1, italic=2 Font[] fonts = new Font[3]; - for (int i = 0; i < 3; i++) { + for(int i = 0; i < 3; i++) + { fonts[i] = Font.getFont(Font.FACE_SYSTEM, i, Font.SIZE_MEDIUM); } // set list fonts - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.setFont(i, fonts[i % 3]); } // check item fonts individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertEquals("Font " + i + " mismatch", fonts[i % 3], list - .getFont(i)); + .getFont(i)); } int selIndex = list.getSelectedIndex(); @@ -262,31 +297,37 @@ /** * Test method. */ - public void testMultiList() { + public void testMultiList() + { List list = new List(null, Choice.MULTIPLE); // append - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.append("item" + i, itemImage); } assertEquals("List size - after append", NUMITEMS, list.size()); - try { + try + { list.setSelectedFlags(null); fail("NullPointerException not thrown - " - + "for null selected array"); + + "for null selected array"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { // OK } - try { + try + { boolean[] badSelArr = new boolean[NUMITEMS / 2]; list.setSelectedFlags(badSelArr); fail("IllegalArgumentException not thrown - " - + "for invalid selected array size"); + + "for invalid selected array size"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { // OK } @@ -294,26 +335,30 @@ boolean[] getSelArr = new boolean[NUMITEMS]; // select odd items - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { setSelArr[i] = (i % 2 == 0); } list.setSelectedFlags(setSelArr); list.getSelectedFlags(getSelArr); // check each item individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, - setSelArr[i] == getSelArr[i]); + setSelArr[i] == getSelArr[i]); } // flip each item - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { list.setSelectedIndex(i, !setSelArr[i]); } // check each item individually - for (int i = 0; i < NUMITEMS; i++) { + for(int i = 0; i < NUMITEMS; i++) + { assertTrue("Selection mismatch at item " + i, setSelArr[i] != list - .isSelected(i)); + .isSelected(i)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/spacer/SpacerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/spacer/SpacerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/spacer/SpacerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.spacer; @@ -31,7 +31,8 @@ * * @created 1.8.2008 */ -public class SpacerTest extends SWTTestCase { +public class SpacerTest extends SWTTestCase +{ private static final int WIDTH = 100; private static final int HEIGHT = 100; @@ -39,7 +40,8 @@ /** * Constructor. */ - public SpacerTest() { + public SpacerTest() + { } /** @@ -48,14 +50,16 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public SpacerTest(String sTestName) { + public SpacerTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { } /** @@ -64,77 +68,92 @@ * * @return New TestSuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = SpacerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SpacerTest((String)e.nextElement())); - } + // Add widget tests + methodNames = SpacerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SpacerTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); else super.runTest(); } /** * Test method. */ - public void testAccessors() { + public void testAccessors() + { Spacer spacer; - try { + try + { spacer = new Spacer(-1, -1); fail("no IllegalArgumentException is thrown when parameters are" - + " incorrect in constructor"); + + " incorrect in constructor"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { //OK } spacer = new Spacer(WIDTH, HEIGHT); Command ok = new Command("Ok", "", Command.ITEM, 0); - try { + try + { spacer.addCommand(ok); fail("no IllegalStateException is thrown when adding command"); } - catch (IllegalStateException e) { + catch(IllegalStateException e) + { //OK } - try { + try + { spacer.setDefaultCommand(ok); fail("no IllegalStateException is thrown when setting default " - + " command"); + + " command"); } - catch (IllegalStateException e) { + catch(IllegalStateException e) + { //OK } - try { + try + { spacer.setLabel("some label"); fail("no IllegalStateException is thrown when setting label"); } - catch (IllegalStateException e) { + catch(IllegalStateException e) + { //OK } - try { + try + { spacer.setMinimumSize(-1, -1); fail("no IllegalArgumentException is thrown when setting minimum " - + "size less then 0"); + + "size less then 0"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { //OK } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/stringitem/StringItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/stringitem/StringItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/stringitem/StringItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.stringitem; @@ -31,28 +31,32 @@ *

            * Created: 2008-06-09 */ -public class StringItemTest extends SWTTestCase { +public class StringItemTest extends SWTTestCase +{ private static final int INVALID_APPEARANCE_MODE = 3; /** * Constructor. */ - public StringItemTest() { + public StringItemTest() + { } /** * @param sTestName Test name. * @param rTestMethod Test method. */ - public StringItemTest(String sTestName) { + public StringItemTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { } /** @@ -60,57 +64,65 @@ * any new test methods, otherwise they won't be run. * @return New testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = StringItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new StringItemTest((String)e.nextElement())); - } + // Add widget tests + methodNames = StringItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new StringItemTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); methodNames.addElement("testMinimumSize"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testMinimumSize")) testMinimumSize(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testMinimumSize")) testMinimumSize(); else super.runTest(); } - - + + /** * Tests the basic functionality of the accessor methods. */ - public void testAccessors() { + public void testAccessors() + { boolean testPassed = true; String testMsg = ""; boolean exceptionThrown = false; //Create new StringItem with invalid appearance mode //and check that exception is thrown: - try { + try + { StringItem item = new StringItem("", "", INVALID_APPEARANCE_MODE); } - catch (IllegalArgumentException ex) { + catch(IllegalArgumentException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { testPassed = false; testMsg = " No exception when creating StringItem with" - + " invalid appearance mode."; + + " invalid appearance mode."; } //Create different kind of StringItems: @@ -120,40 +132,46 @@ StringItem item5 = new StringItem("testLabel", "testText"); //Verify getText() after constructor: - if (item2.getText() != null) { + if(item2.getText() != null) + { testPassed = false; testMsg = " getText() didn't return null when expected."; } - if (!item3.getText().equals("testText")) { + if(!item3.getText().equals("testText")) + { testPassed = false; testMsg = " getText() didn't return correct value."; } //Set text and verify getText(): item2.setText("testText2"); - if (!item2.getText().equals("testText2")) { + if(!item2.getText().equals("testText2")) + { testPassed = false; testMsg = " getText() didn't return correct value after setText()."; } //Set null text and verify getText(): item2.setText(null); - if (item2.getText() != null) { + if(item2.getText() != null) + { testPassed = false; testMsg = " getText() didn't return correct value after setText()" - + " with null parameter. Instead it returned \"" - + item2.getText() + "\"."; + + " with null parameter. Instead it returned \"" + + item2.getText() + "\"."; } //Make sure that getAppearanceMode returns correct value: - if (item2.getAppearanceMode() != Item.PLAIN) { + if(item2.getAppearanceMode() != Item.PLAIN) + { testPassed = false; testMsg = " getAppearanceMode() returned incorrect value."; } //Get font and make sure it is not null: - if (item2.getFont() == null) { + if(item2.getFont() == null) + { testPassed = false; testMsg = " font was null by default."; } @@ -161,7 +179,8 @@ //Set null font and then verify that font returned is not null //(in that case StringItem should use default font instead of null): item2.setFont(null); - if (item2.getFont() == null) { + if(item2.getFont() == null) + { testPassed = false; testMsg = " font was null when default expected."; } @@ -173,63 +192,64 @@ /** * Tests the minimum size of different type of StringItems. */ - public void testMinimumSize() { + public void testMinimumSize() + { StringItem stringItem1 = new StringItem( - "label", "text", StringItem.PLAIN); + "label", "text", StringItem.PLAIN); StringItem stringItem2 = new StringItem(null, "text", StringItem.PLAIN); StringItem stringItem3 = new StringItem( - null, "text", StringItem.BUTTON); + null, "text", StringItem.BUTTON); stringItem3.addCommand(new Command("c", Command.ITEM, 0)); StringItem stringItem4 = new StringItem( - null, "text", StringItem.HYPERLINK); + null, "text", StringItem.HYPERLINK); stringItem4.addCommand(new Command("c", Command.ITEM, 0)); StringItem stringItem5 = new StringItem( - null, "very long hyperlink text that should be wrapped to many" - + " lines.", StringItem.HYPERLINK); + null, "very long hyperlink text that should be wrapped to many" + + " lines.", StringItem.HYPERLINK); stringItem5.addCommand(new Command("c", Command.ITEM, 0)); assertTrue("Minimum height was zero or negative, case 1.", - stringItem1.getMinimumHeight() > 0); + stringItem1.getMinimumHeight() > 0); //print("Plain with label, minimum height: " // + stringItem1.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 1.", - stringItem1.getMinimumWidth() > 0); + stringItem1.getMinimumWidth() > 0); //print("Plain with label, minimum width: " // + stringItem1.getMinimumWidth()); assertTrue("Minimum height was zero or negative, case 2.", - stringItem2.getMinimumHeight() > 0); + stringItem2.getMinimumHeight() > 0); //print("Plain without label, minimum height: " // + stringItem2.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 2.", - stringItem2.getMinimumWidth() > 0); + stringItem2.getMinimumWidth() > 0); //print("Plain without label, minimum width: " // + stringItem2.getMinimumWidth()); assertTrue("Minimum height was zero or negative, case 3.", - stringItem3.getMinimumHeight() > 0); + stringItem3.getMinimumHeight() > 0); //print("Button, minimum height: " // + stringItem3.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 3.", - stringItem3.getMinimumWidth() > 0); + stringItem3.getMinimumWidth() > 0); //print("Button, minimum width: " // + stringItem3.getMinimumWidth()); assertTrue("Minimum height was zero or negative, case 4.", - stringItem4.getMinimumHeight() > 0); + stringItem4.getMinimumHeight() > 0); //print("Short hyperlink, minimum height: " // + stringItem4.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 4.", - stringItem4.getMinimumWidth() > 0); + stringItem4.getMinimumWidth() > 0); //print("Short hyperlink, minimum width: " // + stringItem4.getMinimumWidth()); assertTrue("Minimum height was zero or negative, case 5.", - stringItem5.getMinimumHeight() > 0); + stringItem5.getMinimumHeight() > 0); //print("Long hyperlink, minimum height: " // + stringItem5.getMinimumHeight()); assertTrue("Minimum width was zero or negative, case 5.", - stringItem5.getMinimumWidth() > 0); + stringItem5.getMinimumWidth() > 0); //print("Long hyperlink, minimum width: " // + stringItem5.getMinimumWidth()); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textbox/TextBoxTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textbox/TextBoxTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textbox/TextBoxTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.textbox; @@ -33,7 +33,8 @@ * Created: 2008-04-23 * */ -public class TextBoxTest extends SWTTestCase { +public class TextBoxTest extends SWTTestCase +{ private static final int LENGTH = 100; private static final int LENGTH_BIG = 32000; @@ -48,72 +49,73 @@ private static final int EXPECTED_SIZE = 12; private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum." - + "Lorem ipsum dolor sit amet, " - + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" - + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " - + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " - + "ea commodo consequat. Duis aute irure dolor in reprehenderit " - + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." - + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" - + " qui officia deserunt mollit anim id est laborum."; + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "Lorem ipsum dolor sit amet, " + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "Lorem ipsum dolor sit amet, " + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "Lorem ipsum dolor sit amet, " + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "Lorem ipsum dolor sit amet, " + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum." + + "Lorem ipsum dolor sit amet, " + + "consectetur adipisicing elit, sed do eiusmod tempor incididunt" + + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, " + + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + + "ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + + " Excepteur sint occaecat cupidatat non proident, sunt in culpa" + + " qui officia deserunt mollit anim id est laborum."; /** * Empty constructor. */ - public TextBoxTest() { + public TextBoxTest() + { } /** @@ -121,7 +123,8 @@ * @param sTestName name of the test. * @param rTestMethod TestMethod used. */ - public TextBoxTest(String sTestName) { + public TextBoxTest(String sTestName) + { super(sTestName); } @@ -130,23 +133,26 @@ * any new test methods, otherwise they won't be run. * @return suite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = TextBoxTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TextBoxTest((String)e.nextElement())); - } + // Add widget tests + methodNames = TextBoxTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TextBoxTest((String)e.nextElement())); + } - return suite; - } - - public static java.util.Vector methodNames() { + return suite; + } + + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testTextBox"); methodNames.addElement("testTextBoxException"); @@ -175,33 +181,34 @@ methodNames.addElement("testNullHeaderContent"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testTextBox")) testTextBox(); - else if (getName().equals("testTextBoxException")) testTextBoxExceptions(); - else if (getName().equals("testSetStringException")) testSetStringExceptions(); - else if (getName().equals("testSetString")) testSetString(); - else if (getName().equals("testGetString")) testGetString(); - else if (getName().equals("testSetStringNull")) testSetStringNull(); - else if (getName().equals("testSetLongTextTB")) testSetLongTextTB(); - else if (getName().equals("testGetCharsExceptions")) testGetCharsExceptions(); - else if (getName().equals("testGetChars")) testGetChars(); - else if (getName().equals("testGetCharsCopyCount")) testGetCharsCopyCount(); - else if (getName().equals("testSetCharsExceptions")) testSetCharsExceptions(); - else if (getName().equals("testSetChars")) testSetChars(); - else if (getName().equals("testInsertExceptions")) testInsertExceptions(); - else if (getName().equals("testInsert")) testInsert(); - else if (getName().equals("testInsertArrayExceptions")) testInsertArrayExceptions(); - else if (getName().equals("testInsertArray")) testInsertArray(); - else if (getName().equals("testDeleteExceptions")) testDeleteExceptions(); - else if (getName().equals("testDelete")) testDelete(); - else if (getName().equals("testGetMaxSize")) testGetMaxSize(); - else if (getName().equals("testSetMaxSizeExceptions")) testSetMaxSizeExceptions(); - else if (getName().equals("testSetMaxSize")) testSetMaxSize(); - else if (getName().equals("testSize")) testSize(); - else if (getName().equals("testSetConstraintsExceptions")) testSetConstraintsExceptions(); - else if (getName().equals("testGetConstraints")) testGetConstraints(); - else if (getName().equals("testNullHeaderContent")) testNullHeaderContent(); + + protected void runTest() throws Throwable + { + if(getName().equals("testTextBox")) testTextBox(); + else if(getName().equals("testTextBoxException")) testTextBoxExceptions(); + else if(getName().equals("testSetStringException")) testSetStringExceptions(); + else if(getName().equals("testSetString")) testSetString(); + else if(getName().equals("testGetString")) testGetString(); + else if(getName().equals("testSetStringNull")) testSetStringNull(); + else if(getName().equals("testSetLongTextTB")) testSetLongTextTB(); + else if(getName().equals("testGetCharsExceptions")) testGetCharsExceptions(); + else if(getName().equals("testGetChars")) testGetChars(); + else if(getName().equals("testGetCharsCopyCount")) testGetCharsCopyCount(); + else if(getName().equals("testSetCharsExceptions")) testSetCharsExceptions(); + else if(getName().equals("testSetChars")) testSetChars(); + else if(getName().equals("testInsertExceptions")) testInsertExceptions(); + else if(getName().equals("testInsert")) testInsert(); + else if(getName().equals("testInsertArrayExceptions")) testInsertArrayExceptions(); + else if(getName().equals("testInsertArray")) testInsertArray(); + else if(getName().equals("testDeleteExceptions")) testDeleteExceptions(); + else if(getName().equals("testDelete")) testDelete(); + else if(getName().equals("testGetMaxSize")) testGetMaxSize(); + else if(getName().equals("testSetMaxSizeExceptions")) testSetMaxSizeExceptions(); + else if(getName().equals("testSetMaxSize")) testSetMaxSize(); + else if(getName().equals("testSize")) testSize(); + else if(getName().equals("testSetConstraintsExceptions")) testSetConstraintsExceptions(); + else if(getName().equals("testGetConstraints")) testGetConstraints(); + else if(getName().equals("testNullHeaderContent")) testNullHeaderContent(); else super.runTest(); } @@ -210,7 +217,8 @@ * This method tests that TextBox with correct parameters doesn't * throw any exception. */ - public void testTextBox() { + public void testTextBox() + { new TextBox("correct Box", "correct text", LENGTH, TextField.ANY); //Numeric text box with - in constructor as text. @@ -229,17 +237,20 @@ * This method tests that TextBox constructor throws * IllegalArgumentException if parameters are not valid. */ - public void testTextBoxExceptions() { + public void testTextBoxExceptions() + { /* * first block for testing incorrect maxSize; * maxSize is set to 0 */ - try { - new TextBox("", "", LENGTH_INCORRECT, TextField.ANY); + try + { + new TextBox("", "", LENGTH_INCORRECT, TextField.ANY); fail("IllegalArgumentException not thrown on incorrect length"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } /* @@ -247,12 +258,14 @@ * exceeds maxSize. * maxSize is set to 1, but text is "too many" */ - try { + try + { new TextBox("", "too many", LENGTH_SMALL, TextField.ANY); fail("IllegalArgumentException not thrown on small length"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } /* @@ -260,49 +273,58 @@ * is invalid. * constraint is set to negative */ - try { - new TextBox("", "", LENGTH, MINUS_INV_CONSTRAINT); - fail("IllegalArgumentException not thrown on invalid constraints (case1)"); + try + { + new TextBox("", "", LENGTH, MINUS_INV_CONSTRAINT); + fail("IllegalArgumentException not thrown on invalid constraints (case1)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } - try { - new TextBox("", "", LENGTH, BIG_INV_CONSTRAINT); + try + { + new TextBox("", "", LENGTH, BIG_INV_CONSTRAINT); fail("IllegalArgumentException not thrown on invalid constraints (case2)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } - try { - new TextBox("", "", LENGTH, INV_TEXT_FLAG); + try + { + new TextBox("", "", LENGTH, INV_TEXT_FLAG); fail("IllegalArgumentException not thrown on invalid constraints (case2)"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } } /** - * Correct Exception throwing check. This method tests that - * TextBox.setString(txt) throws IllegalArgumentException when txt is not - * valid input - */ - public void testSetStringExceptions() { + * Correct Exception throwing check. This method tests that + * TextBox.setString(txt) throws IllegalArgumentException when txt is not + * valid input + */ + public void testSetStringExceptions() + { /** * first block for testing if the length of string * exceeds maxSize. */ TextBox maxSizeExceed = new TextBox("", "", LENGTH_SMALL, TextField.ANY); - try { + try + { maxSizeExceed.setString("Exceeding maxSize"); fail("IllegalArgumentException not thrown on long string"); } - catch (IllegalArgumentException e) { - // Ok + catch(IllegalArgumentException e) + { + // Ok } String title = "TextBox Test"; @@ -312,11 +334,13 @@ String newText = "FOO"; TextBox tbObj = new TextBox(title, text, mSize, constraints); - try { + try + { tbObj.setString(newText); fail("IllegalArgumentException not thrown on invalid string"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } maxSizeExceed = null; @@ -326,14 +350,15 @@ * This method tests that TextBox.getString() * return correct result. */ - public void testGetString() { + public void testGetString() + { TextBox getStringTextBox = new TextBox(getName(), "TestGetString", LENGTH, TextField.ANY); String preset = "TestGetString"; String getString; getString = getStringTextBox.getString(); assertTrue("TextBox.getString(). Expected " - + getString + " should be equal to " - + preset, getString.equals(preset)); + + getString + " should be equal to " + + preset, getString.equals(preset)); getStringTextBox = null; } @@ -341,15 +366,16 @@ * This method tests that TextBox.setString(txt) * works correctly. */ - public void testSetString() { + public void testSetString() + { TextBox testSetStringTextBox = new TextBox(getName(), "", LENGTH, TextField.ANY); String setString = "newly setted String"; String getString; testSetStringTextBox.setString(setString); getString = testSetStringTextBox.getString(); assertTrue("TextBox.setString(). Expected" - + getString + " should be equal to " - + setString, getString.equals(setString)); + + getString + " should be equal to " + + setString, getString.equals(setString)); testSetStringTextBox = null; } @@ -357,30 +383,32 @@ * This method test that TextBox.setString(null) * empties the content of TextBox. */ - public void testSetStringNull() { + public void testSetStringNull() + { TextBox setStringNullTB = new TextBox(getName(), "some text", LENGTH, TextField.ANY); String getString; String nullString = null; setStringNullTB.setString(nullString); getString = setStringNullTB.getString(); assertTrue("TextBox.setString(null). Expected: " - + "TextBox.getString() return empty String" - + "but returned " + getString, getString.equals("")); + + "TextBox.getString() return empty String" + + "but returned " + getString, getString.equals("")); setStringNullTB = null; } /** * Tests that TextBox.setString(LONG_TEXT) working OK. */ - public void testSetLongTextTB() { + public void testSetLongTextTB() + { String getString; TextBox setLongString; - setLongString = new TextBox (getName(), LONG_TEXT, LENGTH_BIG, TextField.ANY); + setLongString = new TextBox(getName(), LONG_TEXT, LENGTH_BIG, TextField.ANY); getString = setLongString.getString(); assertTrue("TextBox.setString(LONG_TEXT). Expected" - + " TextBox.getString() returns: LING_TEXT, " - + "but returned: " + getString, getString.equals(LONG_TEXT)); + + " TextBox.getString() returns: LING_TEXT, " + + "but returned: " + getString, getString.equals(LONG_TEXT)); setLongString = null; } @@ -390,24 +418,29 @@ * ArrayIndexOutOfBoundsException if array is too short(shorter * then textBoxContent, and NullPointerException if dataArray is null. */ - public void testGetCharsExceptions() { + public void testGetCharsExceptions() + { TextBox getChars = new TextBox(getName(), "get char", LENGTH, TextField.ANY); char[] dataArray = new char[LENGTH_SMALL]; - try { + try + { getChars.getChars(dataArray); fail("ArrayIndexOutOfBoundsException not thrown on invalid chars"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } dataArray = null; - try { + try + { getChars.getChars(dataArray); fail("NullPointerException not thrown on invalid chars"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } } @@ -417,19 +450,21 @@ * Tests that array elements beyond copied content * are left unchanged, and copied content is correct. */ - public void testGetChars() { + public void testGetChars() + { TextBox getChars = new TextBox(getName(), "tb content", - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); String mergedString = null; // charData contains "some other content" char[] charData = {'s', 'o', 'm', 'e', ' ', 'o', 't', 'h', 'e', 'r', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; getChars.getChars(charData); - mergedString = new String (charData); + mergedString = new String(charData); assertTrue("TextBox.getChars(dataChars). Expected " - + "tb content content, but got " + mergedString, - mergedString.equals("tb content content")); + + "tb content content, but got " + mergedString, + mergedString.equals("tb content content")); } /** @@ -437,14 +472,15 @@ * Tests that getChars method returns correct * number of copied characters. */ - public void testGetCharsCopyCount () { + public void testGetCharsCopyCount() + { TextBox getChars = new TextBox(getName(), "five5", LENGTH, TextField.ANY); int numberOfCopied; char[] charData = new char [LENGTH]; numberOfCopied = getChars.getChars(charData); assertTrue("TextBox.getChars(dataChars). Expected " - + "returns 5, but returned " + numberOfCopied, - numberOfCopied == LENGTH_SMALL); + + "returns 5, but returned " + numberOfCopied, + numberOfCopied == LENGTH_SMALL); } /** @@ -452,29 +488,35 @@ * Tests that TexBox.setChars(char[] dataArray, int offset, int lngth) * throws correct exceptions in case of incorrect parameters. */ - public void testSetCharsExceptions() { + public void testSetCharsExceptions() + { /* * Test ArrayIndexOutOfBounds Exception if * specified range of chars to set is incorrect */ TextBox setCharsEx = new TextBox(getName(), "text", LENGTH, TextField.ANY); char[] charData = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; - try { + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; + try + { setCharsEx.setChars(charData, START_INDEX, LENGTH); fail("ArrayIndexOutOfBoundsException not thrown on invalid range"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } setCharsEx = new TextBox(getName(), "data", LENGTH_SMALL, TextField.ANY); - try { + try + { setCharsEx.setChars(charData, START_INDEX, charData.length - - LENGTH_SMALL - 1); + - LENGTH_SMALL - 1); fail("IllegalArgumentException not thrown on invalid start index"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } } @@ -484,16 +526,18 @@ * Tests that TextBox.setChar inserts correct content into * TextBox. */ - public void testSetChars() { + public void testSetChars() + { TextBox setChars = new TextBox(getName(), "text", LENGTH, TextField.ANY); String getString = null; char[] charData = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; setChars.setChars(charData, START_INDEX , COPY_COUNT); getString = setChars.getString(); assertTrue("TextBox.setChars(). Expected " - + "getString() returns \"content\" but got" - + getString, getString.equals("content")); + + "getString() returns \"content\" but got" + + getString, getString.equals("content")); } /** @@ -501,23 +545,28 @@ * Tests that TextBox.insert(String str, int startIndex) * throws correct exceptions in case of incorrect parameters. */ - public void testInsertExceptions () { + public void testInsertExceptions() + { TextBox insertTextBox = new TextBox(getName(), "text", LENGTH_SMALL, TextField.ANY); String insertString = null; - try { + try + { insertTextBox.insert(insertString, START_INDEX); fail("NullPointerException not thrown on invalid string"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } insertString = "some content"; - try { + try + { insertTextBox.insert(insertString, START_INDEX); fail("IllegalArgumentException not thrown on exceding size"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } } @@ -527,7 +576,8 @@ * Test that TextBox.insert() working correctly * */ - public void testInsert() { + public void testInsert() + { String initialContent = "some content"; String insertContent = "insert"; String getStringBefore; @@ -538,7 +588,7 @@ String getStringInsideExpected = "some insertcontent"; TextBox insertTextBox = new TextBox(getName(), initialContent, - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); //Testing insertion inside of content of TextBox insertTextBox.insert(insertContent, START_INDEX); getStringInside = insertTextBox.getString(); @@ -551,17 +601,17 @@ insertTextBox.insert(insertContent, LENGTH); getStringAfter = insertTextBox.getString(); assertTrue("TextBox.insert(). Expected: " - + getStringBeforeExpected + " but got " - + getStringBefore + "__________________" - + "TextBox.insert(). Expected: " - + getStringAfterExpected + " but got " - + getStringAfter + "__________________" - + "TextBox.insert(). Expected: " - + getStringInsideExpected + " but got " - + getStringInside, - (getStringBefore.equals(getStringBeforeExpected)) - && (getStringAfter.equals(getStringAfterExpected)) - && (getStringInside.equals(getStringInsideExpected))); + + getStringBeforeExpected + " but got " + + getStringBefore + "__________________" + + "TextBox.insert(). Expected: " + + getStringAfterExpected + " but got " + + getStringAfter + "__________________" + + "TextBox.insert(). Expected: " + + getStringInsideExpected + " but got " + + getStringInside, + (getStringBefore.equals(getStringBeforeExpected)) + && (getStringAfter.equals(getStringAfterExpected)) + && (getStringInside.equals(getStringInsideExpected))); } @@ -571,7 +621,8 @@ * int length, int position) throws correct exceptions * in case of incorrect parameters. */ - public void testInsertArrayExceptions() { + public void testInsertArrayExceptions() + { /* * Test ArrayIndexOutOfBounds Exception if * specified range of chars to insert is incorrect @@ -579,33 +630,40 @@ TextBox insertTextBoxEx = new TextBox(getName(), "some content", LENGTH, TextField.ANY); char[] charData = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; - try { + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; + try + { insertTextBoxEx.insert(charData, MINUS_VALUE, COPY_COUNT, START_INDEX); fail("ArrayIndexOutOfBoundsException not thrown on invalid range"); } - catch (ArrayIndexOutOfBoundsException e) { + catch(ArrayIndexOutOfBoundsException e) + { // Ok } insertTextBoxEx = null; insertTextBoxEx = new TextBox(getName(), "data", LENGTH_SMALL, TextField.ANY); - try { + try + { insertTextBoxEx.insert(charData, START_INDEX, COPY_COUNT, START_INDEX); fail("IllegalArgumentException not thrown on exceding size (case1)"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } insertTextBoxEx = null; charData = null; insertTextBoxEx = new TextBox(getName(), "data", LENGTH, TextField.ANY); - try { + try + { insertTextBoxEx.insert(charData, START_INDEX, COPY_COUNT, START_INDEX); fail("NullPointerException not thrown on exceding size (case2)"); } - catch (NullPointerException e) { + catch(NullPointerException e) + { // Ok } } @@ -615,18 +673,20 @@ * Tests that TextBox.insert(char[] charData, int offset, * int length, int position) working correctly. */ - public void testInsertArray() { + public void testInsertArray() + { String getStringExpected = "some contentcontent"; String getStringActual = null; TextBox insertTextBox = new TextBox(getName(), "some content", - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); char[] charData = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; insertTextBox.insert(charData, START_INDEX , COPY_COUNT, START_INDEX); getStringActual = insertTextBox.getString(); assertTrue("TextBox.insert(char[],int,int,int). Expected: " - + getStringExpected + " but got " + getStringActual, - getStringActual.equals(getStringExpected)); + + getStringExpected + " but got " + getStringActual, + getStringActual.equals(getStringExpected)); } /** @@ -634,13 +694,16 @@ * Test that TextBox.delete(int offset, int length) * throws correct exceptions in case of incorrect parameters. */ - public void testDeleteExceptions() { + public void testDeleteExceptions() + { TextBox deleteEx = new TextBox(getName(), "exception", LENGTH, TextField.ANY); - try { + try + { deleteEx.delete(START_INDEX, LENGTH_SMALL); fail("StringIndexOutOfBoundsException not thrown on invalid parameters"); } - catch (StringIndexOutOfBoundsException e) { + catch(StringIndexOutOfBoundsException e) + { // Ok } } @@ -650,28 +713,30 @@ * Tests that TextBox.delete(int offset, int length) * is working correctly. */ - public void testDelete () { + public void testDelete() + { String getString = null; String getStringExpected = "some nt"; TextBox deleteTextBox = new TextBox(getName(), "some content", LENGTH, TextField.ANY); deleteTextBox.delete(START_INDEX, LENGTH_SMALL); getString = deleteTextBox.getString(); assertTrue("TextBox.delete(int offset, int length). Expected: " - + getStringExpected + " but got: " + getString, - getString.equals(getStringExpected)); + + getStringExpected + " but got: " + getString, + getString.equals(getStringExpected)); } /** * TextBox.getmaxSize() test. * Tests that TextBox.getMaxSize() is working correctly */ - public void testGetMaxSize() { + public void testGetMaxSize() + { int getMaxSize; TextBox getMaxSizeTB = new TextBox(getName(), "content", - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); getMaxSize = getMaxSizeTB.getMaxSize(); assertTrue("TextBox.getMaxSize(). Expected: " + LENGTH - + " but got: " + getMaxSize, getMaxSize == LENGTH); + + " but got: " + getMaxSize, getMaxSize == LENGTH); } /** @@ -679,23 +744,28 @@ * Tests that TextBox.setMaxSuze() throws correct exceptions * in case of incorrect input. */ - public void testSetMaxSizeExceptions() { + public void testSetMaxSizeExceptions() + { TextBox setMaxSizeEx = new TextBox(getName(), "some content", LENGTH, TextField.ANY); - try { + try + { setMaxSizeEx.setMaxSize(LENGTH_INCORRECT); fail("IllegalArgumentException not thrown on invalid length"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } setMaxSizeEx.setString("someone@test.com"); setMaxSizeEx.setConstraints(TextField.EMAILADDR); - try { + try + { setMaxSizeEx.setMaxSize(LENGTH_SMALL); fail("IllegalArgumentException not thrown on invalid content after truncation"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } } @@ -705,7 +775,8 @@ * Test that TextBox.setMaxSize sets the correct size * and content of the TextBox is truncated. */ - public void testSetMaxSize() { + public void testSetMaxSize() + { int maxSize = 0; String getText = null; String getTextExpected = "some "; @@ -714,10 +785,10 @@ // test that content is truncated getText = setMaxSize.getString(); assertTrue("TextBox.setMaxSize(int maxSize). Expected " - + "return: " + LENGTH_SMALL + " but got: " + maxSize - + " TextBox.getText() returns: " + getTextExpected - + " but got: " + getText, (maxSize == LENGTH_SMALL) - && getText.equals(getTextExpected)); + + "return: " + LENGTH_SMALL + " but got: " + maxSize + + " TextBox.getText() returns: " + getTextExpected + + " but got: " + getText, (maxSize == LENGTH_SMALL) + && getText.equals(getTextExpected)); } /** @@ -725,13 +796,14 @@ * Tests that TextBox.size() returns correct number of * characters inputed into TextBox */ - public void testSize() { + public void testSize() + { int currentSize = 0; TextBox size = new TextBox(getName(), "some content", - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); currentSize = size.size(); assertTrue("TextBox.size(). Expected returns " + EXPECTED_SIZE - + " but got " + currentSize, currentSize == EXPECTED_SIZE); + + " but got " + currentSize, currentSize == EXPECTED_SIZE); } /** @@ -739,14 +811,17 @@ * Tests that TextBox.setConstraints(int aConstraints) throws * correct exception in case of incorrect input. */ - public void testSetConstraintsExceptions() { + public void testSetConstraintsExceptions() + { TextBox setConstraints = new TextBox(getName(), "some content", - LENGTH, TextField.ANY); - try { + LENGTH, TextField.ANY); + try + { setConstraints.setConstraints(BIG_INV_CONSTRAINT); fail("IllegalArgumentException not thrown on invalid constraints"); } - catch (IllegalArgumentException e) { + catch(IllegalArgumentException e) + { // Ok } } @@ -755,30 +830,34 @@ * TextBox.getConstraints() test. * Tests that TextBox.getConstraints() works correctly. */ - public void testGetConstraints() { + public void testGetConstraints() + { int actualConstraints = -1; TextBox getConstraintsTB = new TextBox(getName(), "some content", - LENGTH, TextField.ANY); + LENGTH, TextField.ANY); getConstraintsTB.setConstraints(TextField.EMAILADDR); actualConstraints = getConstraintsTB.getConstraints(); assertTrue("TextBox.getConstraints(). Expected: returns " - + TextField.EMAILADDR + " but got " + actualConstraints, - actualConstraints == TextField.EMAILADDR); + + TextField.EMAILADDR + " but got " + actualConstraints, + actualConstraints == TextField.EMAILADDR); } /** * Test fix for bug 5448(Creating TextBox with null title and null text * causes IllegalArgumentException). */ - public void testNullHeaderContent() { + public void testNullHeaderContent() + { TextBox nullTextBox = null; boolean passed = true; - try { + try + { nullTextBox = new TextBox(null, null, LENGTH, TextField.ANY); } - catch (Exception e) { + catch(Exception e) + { passed = false; - // spede.addToResultsList("Exception occured: " + e.getMessage()); + // spede.addToResultsList("Exception occured: " + e.getMessage()); } assertTrue("TextBox bug fix. Expected no Exception ", passed); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textfield/TextFieldTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textfield/TextFieldTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/textfield/TextFieldTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.textfield; @@ -30,12 +30,14 @@ * * @created 2008-09-23 */ -public class TextFieldTest extends SWTTestCase { +public class TextFieldTest extends SWTTestCase +{ /** * Constructor. */ - public TextFieldTest() { + public TextFieldTest() + { } /** @@ -44,14 +46,16 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public TextFieldTest(String sTestName) { + public TextFieldTest(String sTestName) + { super(sTestName); } /** * Any pre-test setup can be done here. */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { } /** @@ -60,23 +64,26 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = TextFieldTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TextFieldTest((String)e.nextElement())); - } + // Add widget tests + methodNames = TextFieldTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TextFieldTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testConstructor"); methodNames.addElement("testAccessors"); @@ -84,40 +91,46 @@ methodNames.addElement("testSetNullString"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testConstructor")) testConstructor(); - else if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testNullBodyHeader")) testNullBodyHeader(); - else if (getName().equals("testSetNullString")) testSetNullString(); + + protected void runTest() throws Throwable + { + if(getName().equals("testConstructor")) testConstructor(); + else if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testNullBodyHeader")) testNullBodyHeader(); + else if(getName().equals("testSetNullString")) testSetNullString(); else super.runTest(); } - - + + /** - * Test the TextField accessor methods. - */ - public void testConstructor () { + * Test the TextField accessor methods. + */ + public void testConstructor() + { TextField tf; final int illegalConstraint = -10; final int smallSize = 5; // Constructor tests - try { - tf = new TextField ("label", "text", 0, TextField.ANY); + try + { + tf = new TextField("label", "text", 0, TextField.ANY); fail("No IllegalArgumentExceptin thrown in constructor," - + " if maxSize is incorrect"); + + " if maxSize is incorrect"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK. } - try { + try + { tf = new TextField("label", "text", 1, illegalConstraint); fail("No IllegalArgumentExceptin thrown in constructor," - + " if constraints are incorrect"); + + " if constraints are incorrect"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK. } /*try { @@ -129,18 +142,21 @@ //OK. }*/ - try { - tf = new TextField ("label", "long text", smallSize, TextField.ANY); + try + { + tf = new TextField("label", "long text", smallSize, TextField.ANY); fail("No IllegalArgumentExceptin thrown in constructor," - + " if text is too long for specified maxSize"); + + " if text is too long for specified maxSize"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK. } } - public void testAccessors () { + public void testAccessors() + { TextField tf; final int normalSize = 100; final int smallSize = 5; @@ -151,14 +167,16 @@ final int copyCount = 7; final int invalidConstraints = -1345; final int expectedSize = 12; - try { + try + { //setText() tf = new TextField("label", "1234", smallSize, TextField.DECIMAL); tf.setString("12345678"); fail("No IllegalArgumentExceptin thrown in setString()," - + " if maxSize was exceeded"); + + " if maxSize was exceeded"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } /* @@ -174,46 +192,55 @@ //getChars char []ch = null; - try { + try + { tf = new TextField("label" , "text", normalSize, TextField.ANY); ch = new char [2]; tf.getChars(ch); fail("No ArrayIndexOutOfBoundsException is thrown in getChars()" - + " if char[] is too short for the content"); + + " if char[] is too short for the content"); } - catch (ArrayIndexOutOfBoundsException aioobe) { + catch(ArrayIndexOutOfBoundsException aioobe) + { //OK } - try { + try + { ch = null; tf = new TextField("label" , "text", normalSize, TextField.ANY); tf.getChars(ch); fail("No NullPointerException is thrown in getChars()" - + " if char[] is null"); + + " if char[] is null"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { //OK } //setChars() char []charData = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; - try { + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; + try + { tf = new TextField("label" , "text", normalSize, TextField.ANY); tf.setChars(charData, offset, incorrectLength); - fail ("No ArrayIndexOutOfBoundsException is thrown in setChars()" - + " if offset and length do not specify valid range"); + fail("No ArrayIndexOutOfBoundsException is thrown in setChars()" + + " if offset and length do not specify valid range"); } - catch (ArrayIndexOutOfBoundsException aioobe) { + catch(ArrayIndexOutOfBoundsException aioobe) + { //OK } - try { + try + { tf = new TextField("label" , "text", normalSize, TextField.ANY); tf.setChars(charData, negativeOffset, normalLength); - fail ("No ArrayIndexOutOfBoundsException is thrown in setChars()" - + " if offset and length do not specify valid range"); + fail("No ArrayIndexOutOfBoundsException is thrown in setChars()" + + " if offset and length do not specify valid range"); } - catch (ArrayIndexOutOfBoundsException aioobe) { + catch(ArrayIndexOutOfBoundsException aioobe) + { //OK } /*try { @@ -226,13 +253,15 @@ catch (IllegalArgumentException iae) { //OK }*/ - try { + try + { tf = new TextField("label" , "text", smallSize, TextField.ANY); tf.setChars(charData, offset, copyCount); - fail ("No IllegalArgumentException is thrown in setChars()" - + " if text exceeds current TextField's maxSize"); + fail("No IllegalArgumentException is thrown in setChars()" + + " if text exceeds current TextField's maxSize"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } //insert(String, position) @@ -245,53 +274,63 @@ catch (IllegalArgumentException iae) { //OK }*/ - try { + try + { tf = new TextField("label" , "text", smallSize, TextField.ANY); tf.insert("more text", 1); - fail ("No IllegalArgumentException is thrown in insert()" - + " if text exceeds current TextField's maxSize"); + fail("No IllegalArgumentException is thrown in insert()" + + " if text exceeds current TextField's maxSize"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } - try { + try + { tf = new TextField("label" , "text", smallSize, TextField.ANY); tf.insert(null, 1); - fail ("No NullPointerException is thrown in insert()" - + " if text is null"); + fail("No NullPointerException is thrown in insert()" + + " if text is null"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { //OK } // insert([]) - try { + try + { tf = new TextField("label" , "text", normalSize, TextField.ANY); tf.insert(charData, negativeOffset, normalLength, offset); - fail ("No ArrayIndexOutOfBoundsException is thrown in insert([])" - + " if offset and length do not specify valid range"); + fail("No ArrayIndexOutOfBoundsException is thrown in insert([])" + + " if offset and length do not specify valid range"); } - catch (ArrayIndexOutOfBoundsException aioobe) { + catch(ArrayIndexOutOfBoundsException aioobe) + { //OK } - try { + try + { tf = new TextField("label", "text", smallSize, TextField.ANY); tf.insert(charData, offset, normalLength, offset); //2nd offset means position - fail ("No IllegalArgumentException is thrown in insert([])" - + " if text exceeds current TextField's maxSize"); + fail("No IllegalArgumentException is thrown in insert([])" + + " if text exceeds current TextField's maxSize"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } - try { + try + { tf = new TextField("label", "text", smallSize, TextField.ANY); tf.insert(null, offset, 1, offset); - fail ("No NullPointerException is thrown in insert()" - + " if charData is null"); + fail("No NullPointerException is thrown in insert()" + + " if charData is null"); } - catch (NullPointerException npe) { + catch(NullPointerException npe) + { //OK } /*try { @@ -305,74 +344,82 @@ //OK } */ //delete() - try { + try + { tf = new TextField("label", "some text", normalSize, TextField.ANY); tf.delete(offset, smallSize); //smallSize = number of chars fail("No StringIndexOutOfBoundsException is thrown in delete()" - + " if offset and length do not specify valid range"); + + " if offset and length do not specify valid range"); } - catch (StringIndexOutOfBoundsException sioobe) { + catch(StringIndexOutOfBoundsException sioobe) + { //OK } //setMaxSize() - try { + try + { tf = new TextField("label", "some text", normalSize, TextField.ANY); tf.setMaxSize(0); - fail ("No IllegalArgumentException is thrown in setMaxSize()" - + " if newMaxSize is invalid"); + fail("No IllegalArgumentException is thrown in setMaxSize()" + + " if newMaxSize is invalid"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } //setConstraints() - try { + try + { tf = new TextField("label", "some text", normalSize, TextField.ANY); tf.setConstraints(invalidConstraints); - fail ("No IllegalArgumentException is thrown in setConstraints()" - + " if newConstriants is invalid"); + fail("No IllegalArgumentException is thrown in setConstraints()" + + " if newConstriants is invalid"); } - catch (IllegalArgumentException iae) { + catch(IllegalArgumentException iae) + { //OK } tf = new TextField("", - "content", normalSize, TextField.ANY); + "content", normalSize, TextField.ANY); String setString = "TestGetString"; tf.setString(setString); assertTrue("TextField setString() getString() not working correct", - setString.equals(tf.getString())); + setString.equals(tf.getString())); tf = null; tf = new TextField("header", "tb content", - normalSize, TextField.ANY); + normalSize, TextField.ANY); String mergedString = null; // charData contains "some other content" char[] newCharData = {'s', 'o', 'm', 'e', ' ', 'o', 't', 'h', 'e', - 'r', ' ', 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'r', ' ', 'c', 'o', 'n', 't', 'e', 'n', 't', + }; tf.getChars(newCharData); - mergedString = new String (newCharData); + mergedString = new String(newCharData); assertTrue("TextField getChars([]) not working properly", - mergedString.equals("tb content content")); + mergedString.equals("tb content content")); tf = null; tf = new TextField("getChar", "five5", normalSize, TextField.ANY); int numberOfCopied; charData = new char [normalSize]; numberOfCopied = tf.getChars(charData); assertTrue("TextField.getChars(dataChars). Expected " - + "returns 5, but returned " + numberOfCopied, - numberOfCopied == smallSize); + + "returns 5, but returned " + numberOfCopied, + numberOfCopied == smallSize); tf = null; - tf = new TextField ("", "text", normalSize, TextField.ANY); + tf = new TextField("", "text", normalSize, TextField.ANY); String getString = null; charData = null; char []charData2 = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; tf.setChars(charData2, offset , copyCount); getString = tf.getString(); assertTrue("TextField.setChars(). Expected " - + "getString() returns \"content\" but got" - + getString, getString.equals("content")); + + "getString() returns \"content\" but got" + + getString, getString.equals("content")); tf = null; String initialContent = "some content"; @@ -385,7 +432,7 @@ String getStringInsideExpected = "some insertcontent"; tf = new TextField("", initialContent, - normalSize, TextField.ANY); + normalSize, TextField.ANY); //Testing insertion inside of content of TextField tf.insert(insertContent, offset); getStringInside = tf.getString(); @@ -398,29 +445,30 @@ tf.insert(insertContent, normalSize); getStringAfter = tf.getString(); assertTrue("TextField.insert(). Expected: " - + getStringBeforeExpected + " but got " - + getStringBefore + "__________________" - + "TextField.insert(). Expected: " - + getStringAfterExpected + " but got " - + getStringAfter + "__________________" - + "TextField.insert(). Expected: " - + getStringInsideExpected + " but got " - + getStringInside, - (getStringBefore.equals(getStringBeforeExpected)) - && (getStringAfter.equals(getStringAfterExpected)) - && (getStringInside.equals(getStringInsideExpected))); + + getStringBeforeExpected + " but got " + + getStringBefore + "__________________" + + "TextField.insert(). Expected: " + + getStringAfterExpected + " but got " + + getStringAfter + "__________________" + + "TextField.insert(). Expected: " + + getStringInsideExpected + " but got " + + getStringInside, + (getStringBefore.equals(getStringBeforeExpected)) + && (getStringAfter.equals(getStringAfterExpected)) + && (getStringInside.equals(getStringInsideExpected))); tf = null; String getStringExpected = "some contentcontent"; String getStringActual = null; tf = new TextField("", "some content", normalSize, TextField.ANY); char[] charData3 = {'s', 'o', 'm', 'e', ' ', - 'c', 'o', 'n', 't', 'e', 'n', 't', }; + 'c', 'o', 'n', 't', 'e', 'n', 't', + }; tf.insert(charData3, offset , copyCount, offset); getStringActual = tf.getString(); assertTrue("TextField.insert(char[],int,int,int). Expected: " - + getStringExpected + " but got " + getStringActual, - getStringActual.equals(getStringExpected)); + + getStringExpected + " but got " + getStringActual, + getStringActual.equals(getStringExpected)); tf = null; getString = null; @@ -429,15 +477,15 @@ tf.delete(offset, smallSize); getString = tf.getString(); assertTrue("TextField.delete(int offset, int length). Expected: " - + getStringExpected + " but got: " + getString, - getString.equals(getStringExpected)); + + getStringExpected + " but got: " + getString, + getString.equals(getStringExpected)); tf = null; int getMaxSize; tf = new TextField("Header", "content", normalSize, TextField.ANY); getMaxSize = tf.getMaxSize(); assertTrue("TextBox.getMaxSize(). Expected: " + normalSize - + " but got: " + getMaxSize, getMaxSize == normalSize); + + " but got: " + getMaxSize, getMaxSize == normalSize); tf = null; int maxSize = 0; @@ -448,17 +496,17 @@ //test that content is truncated getText = tf.getString(); assertTrue("TextField.setMaxSize(int maxSize). Expected " - + "return: " + smallSize + " but got: " + maxSize - + " TextField.getText() returns: " + getTextExpected - + " but got: " + getText, (maxSize == smallSize) - && getText.equals(getTextExpected)); + + "return: " + smallSize + " but got: " + maxSize + + " TextField.getText() returns: " + getTextExpected + + " but got: " + getText, (maxSize == smallSize) + && getText.equals(getTextExpected)); tf = null; int currentSize = 0; tf = new TextField("header", "some content", normalSize, TextField.ANY); currentSize = tf.size(); assertTrue("TextField.size(). Expected returns " + expectedSize - + " but got " + currentSize, currentSize == expectedSize); + + " but got " + currentSize, currentSize == expectedSize); tf = null; int actualConstraints = -1; @@ -466,14 +514,15 @@ tf.setConstraints(TextField.EMAILADDR); actualConstraints = tf.getConstraints(); assertTrue("TextField.getConstraints(). Expected: returns " - + TextField.EMAILADDR + " but got " + actualConstraints, - actualConstraints == TextField.EMAILADDR); + + TextField.EMAILADDR + " but got " + actualConstraints, + actualConstraints == TextField.EMAILADDR); } /** * Test that null body and header are processed properly. */ - public void testNullBodyHeader() { + public void testNullBodyHeader() + { final int maxsize = 1000; String header = null; String body = null; @@ -490,7 +539,8 @@ /** * Test that setString(null) working properly. */ - public void testSetNullString() { + public void testSetNullString() + { final int maxsize = 1000; String header = "header"; String body = "body"; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/ticker/TickerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/ticker/TickerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt/ticker/TickerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt.ticker; @@ -31,7 +31,8 @@ *
            * Created: 2009-02-10 */ -public class TickerTest extends SWTTestCase { +public class TickerTest extends SWTTestCase +{ private static final String STRING_WITH_NEWLINE_CHARACTER = "string with\nnewline character."; @@ -39,7 +40,8 @@ /** * Empty constructor. */ - public TickerTest() { + public TickerTest() + { } /** @@ -47,7 +49,8 @@ * @param sTestName name of the test. * @param rTestMethod TestMethod used. */ - public TickerTest(String sTestName) { + public TickerTest(String sTestName) + { super(sTestName); } @@ -57,62 +60,71 @@ * * @return new testsuite. */ - public static Test suite() { - TestSuite suite = new TestSuite(); + public static Test suite() + { + TestSuite suite = new TestSuite(); - java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Vector methodNames; + java.util.Enumeration e; - // Add widget tests - methodNames = TickerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TickerTest((String)e.nextElement())); - } + // Add widget tests + methodNames = TickerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TickerTest((String)e.nextElement())); + } - return suite; - } + return suite; + } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAccessors"); methodNames.addElement("testOneTickerInManyDisplayables"); methodNames.addElement("testManyTickersInOneDisplayable"); return methodNames; } - - protected void runTest() throws Throwable { - if (getName().equals("testAccessors")) testAccessors(); - else if (getName().equals("testOneTickerInManyDisplayables")) testOneTickerInManyDisplayables(); - else if (getName().equals("testManyTickersInOneDisplayable")) testManyTickersInOneDisplayable(); + + protected void runTest() throws Throwable + { + if(getName().equals("testAccessors")) testAccessors(); + else if(getName().equals("testOneTickerInManyDisplayables")) testOneTickerInManyDisplayables(); + else if(getName().equals("testManyTickersInOneDisplayable")) testManyTickersInOneDisplayable(); else super.runTest(); } /** * Tests basic functionality of Ticker's methods. */ - public void testAccessors() { + public void testAccessors() + { // Instantiate a new Ticker with null-string and make sure an // exception is thrown: - try { + try + { new Ticker(null); fail("No nullpointerException when instantiating" - + " a Ticker with null string."); + + " a Ticker with null string."); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { } // Instantiate a new Ticker with empty string: Ticker ticker = new Ticker(""); // Set null string and make sure an exception is thrown: - try { + try + { ticker.setString(null); fail("No nullpointerException when calling tic" - + "ker.setString() with null parameter."); + + "ker.setString() with null parameter."); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { } // Set string with newline characters and make sure the string @@ -124,7 +136,8 @@ /** * Tests to add one ticker to many displayables. */ - public void testOneTickerInManyDisplayables() { + public void testOneTickerInManyDisplayables() + { Form form1 = new Form("ticker test"); Form form2 = new Form("ticker test"); Form form3 = new Form("ticker test"); @@ -143,7 +156,8 @@ /** * Tests to add many tickers to one displayable. */ - public void testManyTickersInOneDisplayable() { + public void testManyTickersInOneDisplayable() + { Ticker ticker1 = new Ticker("ticker"); Ticker ticker2 = new Ticker("ticker"); Ticker ticker3 = new Ticker("ticker"); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/ItemUITestBase.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/ItemUITestBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/ItemUITestBase.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot; @@ -25,7 +25,8 @@ import com.nokia.mj.impl.uitestutils.Key; public abstract class ItemUITestBase extends UITestBase implements ItemCommandListener, - ItemStateListener { + ItemStateListener +{ private Command lastItemCommand; private Item lastItem; @@ -33,15 +34,18 @@ protected Form form; - public ItemUITestBase() { - this(""); + public ItemUITestBase() + { + this(""); } - - public ItemUITestBase(String name) { + + public ItemUITestBase(String name) + { super(name); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); form = new Form("Form: " + getName()); form.setItemStateListener(this); @@ -54,7 +58,8 @@ * * @param item an item */ - protected void testCommand(Item item) { + protected void testCommand(Item item) + { Command cmd = new Command("ItemCmd", Command.ITEM, 0); item.addCommand(cmd); @@ -74,19 +79,23 @@ * @param expCmd expected Command * @param expItem expected Item */ - protected void assertItemCmdListener(String msg, Command expCmd, Item expItem) { + protected void assertItemCmdListener(String msg, Command expCmd, Item expItem) + { block(100); boolean expNull = (expCmd == null && expItem == null); boolean lastNull = (lastItemCommand == null && lastItem == null); - if (lastNull && !expNull) { + if(lastNull && !expNull) + { fail(msg + " - Listener should have been called with " - + expCmd + " on " + expItem); + + expCmd + " on " + expItem); } - else if (!lastNull && expNull) { + else if(!lastNull && expNull) + { fail(msg + " - Listener should not be called with " - + lastItemCommand + " on " + lastItem); + + lastItemCommand + " on " + lastItem); } - else { + else + { assertEquals(msg + " - Listener item mismatch ", expItem, lastItem); assertEquals(msg + " - Listener cmd mismatch ", expCmd, lastItemCommand); } @@ -94,7 +103,8 @@ lastItemCommand = null; } - public void commandAction(Command cmd, Item item) { + public void commandAction(Command cmd, Item item) + { lastItem = item; lastItemCommand = cmd; } @@ -104,24 +114,29 @@ * * @param expItem expected Item */ - protected void assertItemStateChanged(String msg, Item expItem) { + protected void assertItemStateChanged(String msg, Item expItem) + { block(100); boolean expNull = (expItem == null); boolean lastNull = (lastStateListenerItem == null); - if (lastNull && !expNull) { + if(lastNull && !expNull) + { fail(msg + " - Listener should have been called on " + expItem); } - else if (!lastNull && expNull) { + else if(!lastNull && expNull) + { fail(msg + " - Listener should not be called on " - + lastStateListenerItem); + + lastStateListenerItem); } - else { + else + { assertEquals(msg + " - Listener item mismatch ", expItem, lastStateListenerItem); } lastStateListenerItem = null; } - public void itemStateChanged(Item item) { + public void itemStateChanged(Item item) + { lastStateListenerItem = item; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/UITestBase.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/UITestBase.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/UITestBase.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot; @@ -27,7 +27,8 @@ import com.nokia.mj.impl.uitestutils.UITestUtils; import com.nokia.openlcdui.mt.SWTTestCase; -public class UITestBase extends SWTTestCase implements CommandListener { +public class UITestBase extends SWTTestCase implements CommandListener +{ public final static int KEYEVENT_DELAY = 100; public final static int CHANGE_DISPLAYABLE_DELAY = 500; @@ -38,38 +39,44 @@ protected UITestUtils uiTestUtils; protected Display display; - public UITestBase() { - this(""); + public UITestBase() + { + this(""); } - - public UITestBase(String name) { + + public UITestBase(String name) + { super(name); uiTestUtils = new UITestUtils(); } - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); display = Display.getDisplay(getMIDlet()); lastDisplayable = null; lastDispCommand = null; } - protected void setCurrent(Displayable disp) { + protected void setCurrent(Displayable disp) + { display.setCurrent(disp); block(CHANGE_DISPLAYABLE_DELAY); } - public void runTest() throws Throwable { - super.runTest(); + public void runTest() throws Throwable + { + super.runTest(); } - + /** * Emulates key event by sending key pressed and key released events. Events * are also dispatched if there is a Display available. * * @param aKeyCode Keycode as defined in com.nokia.mj.impl.uitestutils.Key */ - public void key(int keycode) { + public void key(int keycode) + { key(keycode, KEYEVENT_DELAY); } @@ -80,7 +87,8 @@ * @param keyCode Keycode as defined in com.nokia.mj.impl.uitestutils.Key * @param delay custom delay */ - public void key(int keycode, int delay) { + public void key(int keycode, int delay) + { Key key = new Key(keycode); uiTestUtils.triggerKeyPressEvent(key); flush(); @@ -95,7 +103,8 @@ * @param modifiers Modifier as defined in * com.nokia.mj.impl.uitestutils.Modifier */ - public void keyMod(int keycode, int modifiers) { + public void keyMod(int keycode, int modifiers) + { Key key = new Key(keycode); key.modifiers = modifiers; uiTestUtils.triggerKeyPressEvent(key); @@ -110,7 +119,8 @@ * @param x X-coordinate relative to the screen. * @param y Y-coordinate relative to the screen. */ - public void pointerTap(Point p) { + public void pointerTap(Point p) + { uiTestUtils.triggerPointerDownEvent(p.x, p.y); uiTestUtils.triggerPointerUpEvent(p.x, p.y); flush(); @@ -123,7 +133,8 @@ * @param x X-coordinate relative to the screen. * @param y Y-coordinate relative to the screen. */ - public void pointerDown(Point p) { + public void pointerDown(Point p) + { uiTestUtils.triggerPointerDownEvent(p.x, p.y); flush(); } @@ -135,7 +146,8 @@ * @param x X-coordinate relative to the screen. * @param y Y-coordinate relative to the screen. */ - public void pointerUp(Point p) { + public void pointerUp(Point p) + { uiTestUtils.triggerPointerUpEvent(p.x, p.y); flush(); } @@ -147,39 +159,46 @@ * @param x X-coordinate relative to the screen. * @param y Y-coordinate relative to the screen. */ - public void pointerMove(Point p) { + public void pointerMove(Point p) + { uiTestUtils.triggerPointerDragEvent(p.x, p.y); flush(); } - public void switchResolution() { - fail("switchResolution not implemented"); + public void switchResolution() + { + fail("switchResolution not implemented"); } - - public int getNumberOfResolutions() { - fail("getNumberOfResolutions not implemented"); - return 0; + + public int getNumberOfResolutions() + { + fail("getNumberOfResolutions not implemented"); + return 0; } - + /** * Assert the command listener values. * * @param expCmd expected Command * @param expDisp expected Displayable */ - protected void assertCmdListener(String msg, Command expCmd, Displayable disp) { + protected void assertCmdListener(String msg, Command expCmd, Displayable disp) + { block(100); boolean expNull = (expCmd == null && disp == null); boolean lastNull = (lastDispCommand == null && lastDisplayable == null); - if (lastNull && !expNull) { + if(lastNull && !expNull) + { fail(msg + " - Listener should have been called with " - + expCmd + " on " + disp); + + expCmd + " on " + disp); } - else if (!lastNull && expNull) { + else if(!lastNull && expNull) + { fail(msg + " - Listener should not be called with " - + lastDispCommand + " on " + lastDisplayable); + + lastDispCommand + " on " + lastDisplayable); } - else { + else + { assertEquals(msg + " - Listener displayable mismatch ", disp, lastDisplayable); assertEquals(msg + " - Listener command mismatch ", expCmd, lastDispCommand); } @@ -187,7 +206,8 @@ lastDispCommand = null; } - public void commandAction(Command cmd, Displayable disp) { + public void commandAction(Command cmd, Displayable disp) + { lastDisplayable = disp; lastDispCommand = cmd; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/alert/AlertUITest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/alert/AlertUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/alert/AlertUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.alert; @@ -35,7 +35,8 @@ * * @created 2008-07-01 */ -public class AlertUITest extends UITestBase { +public class AlertUITest extends UITestBase +{ private static final int SETCURRENT_TIMEOUT = 6000; private static final int TEXBOX_LENGTH = 100; @@ -43,19 +44,19 @@ private static String shortString = "Lorem ipsum"; private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue." - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue." + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; private TextBox textBox; private Command exitCmd; @@ -63,8 +64,9 @@ /** * Constructor. */ - public AlertUITest() { - super(); + public AlertUITest() + { + super(); } /** @@ -73,27 +75,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public AlertUITest(String sTestName) { + public AlertUITest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = AlertUITest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new AlertUITest((String)e.nextElement())); - } - + // Add widget tests + methodNames = AlertUITest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new AlertUITest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testShowTimedAlert"); methodNames.addElement("testCustomListener"); @@ -103,31 +109,34 @@ methodNames.addElement("testImageAndTextCombinations"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testShowTimedAlert")) testShowTimedAlert(); - else if (getName().equals("testCustomListener")) testCustomListener(); - else if (getName().equals("testCustomListenerCustomCommand")) testCustomListenerCustomCommand(); - else if (getName().equals("testKeypressOnCustomCommands")) testKeypressOnCustomCommands(); - else if (getName().equals("testLongTextScrolling")) testLongTextScrolling(); - else if (getName().equals("testImageAndTextCombinations")) testImageAndTextCombinations(); + + public void runTest() throws Throwable + { + if(getName().equals("testShowTimedAlert")) testShowTimedAlert(); + else if(getName().equals("testCustomListener")) testCustomListener(); + else if(getName().equals("testCustomListenerCustomCommand")) testCustomListenerCustomCommand(); + else if(getName().equals("testKeypressOnCustomCommands")) testKeypressOnCustomCommands(); + else if(getName().equals("testLongTextScrolling")) testLongTextScrolling(); + else if(getName().equals("testImageAndTextCombinations")) testImageAndTextCombinations(); else super.runTest(); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception + { + super.setUp(); exitCmd = new Command("exit", "exit", Command.EXIT, 0); textBox = new TextBox("textBox", "", TEXBOX_LENGTH, TextField.ANY); textBox.addCommand(exitCmd); } - + /** * Tests showing a timed alert with default values. */ - public void testShowTimedAlert() { + public void testShowTimedAlert() + { setCurrent(textBox); Alert alert = new Alert("timedAlert"); @@ -153,18 +162,19 @@ setCurrent(alert); block(timeout + CHANGE_DISPLAYABLE_DELAY); assertEquals("Textbox should be current", - textBox, display.getCurrent()); + textBox, display.getCurrent()); } /** * Tests showing a timed alert with custom command listener. */ - public void testCustomListener() { - setCurrent(textBox); + public void testCustomListener() + { + setCurrent(textBox); Alert alert = new Alert("customListenerAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); setCurrent(alert); // wait for max 10sec to get command listener callback @@ -176,12 +186,13 @@ * Tests showing a timed alert with custom command listener and custom * command. */ - public void testCustomListenerCustomCommand() { - setCurrent(textBox); + public void testCustomListenerCustomCommand() + { + setCurrent(textBox); Alert alert = new Alert("customCmdAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); Command testCmd = new Command("test", "test", Command.ITEM, 0); alert.addCommand(testCmd); @@ -194,19 +205,20 @@ /** * Tests pressing keys on Alert's custom commands. */ - public void testKeypressOnCustomCommands() { - setCurrent(textBox); + public void testKeypressOnCustomCommands() + { + setCurrent(textBox); Alert alert = new Alert("keypressAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); Command testCmd1 = new Command("Cmd1", "Command 1", Command.SCREEN, 0); Command testCmd2 = new Command("Cmd2", "Command 2", Command.SCREEN, 1); alert.addCommand(testCmd1); alert.addCommand(testCmd2); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); key(Key.CBA1, 0); @@ -224,17 +236,19 @@ /** * Tests scrolling a long text. */ - public void testLongTextScrolling() { - setCurrent(textBox); + public void testLongTextScrolling() + { + setCurrent(textBox); Alert alert = new Alert("scrollingAlert"); alert.setString(longString); alert.setCommandListener(this); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) + { key((i < 5 ? Key.DownArrow : Key.UpArrow)); } @@ -245,21 +259,26 @@ /** * Tests different text and image setting combinations. */ - public void testImageAndTextCombinations() { - setCurrent(textBox); + public void testImageAndTextCombinations() + { + setCurrent(textBox); Image smallImg = null; Image largeImg = null; - try { + try + { smallImg = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } - try { + try + { largeImg = Image.createImage("200x200.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 200x200.png"); } @@ -267,36 +286,40 @@ alert.setTimeout(Alert.FOREVER); alert.setCommandListener(this); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); - for (int textIndex = 0; textIndex < 3; textIndex++) { - switch (textIndex) { + for(int textIndex = 0; textIndex < 3; textIndex++) + { + switch(textIndex) + { + case 0: + alert.setString(null); + break; + case 1: + alert.setString(shortString); + break; + case 2: + alert.setString(longString); + break; + default: + break; + } + for(int imgIndex = 0; imgIndex < 3; imgIndex++) + { + switch(imgIndex) + { case 0: - alert.setString(null); + alert.setImage(null); break; case 1: - alert.setString(shortString); + alert.setImage(smallImg); break; case 2: - alert.setString(longString); + alert.setImage(largeImg); break; default: break; - } - for (int imgIndex = 0; imgIndex < 3; imgIndex++) { - switch (imgIndex) { - case 0: - alert.setImage(null); - break; - case 1: - alert.setImage(smallImg); - break; - case 2: - alert.setImage(largeImg); - break; - default: - break; } block(CHANGE_DISPLAYABLE_DELAY); // 0.3 sec } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupCommandTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.choicegroup; @@ -31,12 +31,14 @@ *
            * Created: 2008-11-04 */ -public class ChoiceGroupCommandTest extends ItemUITestBase { +public class ChoiceGroupCommandTest extends ItemUITestBase +{ - /** + /** * Constructor. */ - public ChoiceGroupCommandTest() { + public ChoiceGroupCommandTest() + { } /** @@ -45,40 +47,46 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ChoiceGroupCommandTest(String sTestName) { + public ChoiceGroupCommandTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ChoiceGroupCommandTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ChoiceGroupCommandTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ChoiceGroupCommandTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ChoiceGroupCommandTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCommandsExclusive"); methodNames.addElement("testCommandsMultiple"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommandsExclusive")) testChoiceGroupExclusiveCmds(); - else if (getName().equals("testCommandsMultiple")) testChoiceGroupMultipleCmds(); + + public void runTest() throws Throwable + { + if(getName().equals("testCommandsExclusive")) testChoiceGroupExclusiveCmds(); + else if(getName().equals("testCommandsMultiple")) testChoiceGroupMultipleCmds(); else super.runTest(); } - public void testChoiceGroupExclusiveCmds() { + public void testChoiceGroupExclusiveCmds() + { ChoiceGroup choiceGroup = new ChoiceGroup("Exclusive", Choice.EXCLUSIVE); choiceGroup.append("item1", null); choiceGroup.append("item2", null); @@ -87,7 +95,8 @@ testCommand(choiceGroup); } - public void testChoiceGroupMultipleCmds() { + public void testChoiceGroupMultipleCmds() + { ChoiceGroup choiceGroup = new ChoiceGroup("Multiple", Choice.MULTIPLE); choiceGroup.append("item1", null); choiceGroup.append("item2", null); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupPopupTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupPopupTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/choicegroup/ChoiceGroupPopupTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.choicegroup; @@ -32,12 +32,14 @@ *
            * Created: 2008-11-04 */ -public class ChoiceGroupPopupTest extends ItemUITestBase { +public class ChoiceGroupPopupTest extends ItemUITestBase +{ /** * Constructor. */ - public ChoiceGroupPopupTest() { + public ChoiceGroupPopupTest() + { } /** @@ -46,41 +48,47 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ChoiceGroupPopupTest(String sTestName) { + public ChoiceGroupPopupTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ChoiceGroupPopupTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ChoiceGroupPopupTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ChoiceGroupPopupTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ChoiceGroupPopupTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testOpenPopup"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testOpenPopup")) testOpenPopup(); + + public void runTest() throws Throwable + { + if(getName().equals("testOpenPopup")) testOpenPopup(); else super.runTest(); } - + /** * Test command on Items. */ - public void testOpenPopup() { + public void testOpenPopup() + { Command cmd = new Command("Cmd", Command.ITEM, 0); ChoiceGroup choiceGroup = new ChoiceGroup("Popup", Choice.POPUP); choiceGroup.append("item1", null); @@ -106,7 +114,7 @@ assertTrue("No item selected", choiceGroup.getSelectedIndex() != -1); assertTrue("Could not change selection", - choiceGroup.getSelectedIndex() != sel); + choiceGroup.getSelectedIndex() != sel); assertItemStateChanged("case1", choiceGroup); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/DynamicUpdateTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/DynamicUpdateTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/DynamicUpdateTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.command; @@ -33,7 +33,8 @@ *
            * Created: 2008-05-02 */ -public class DynamicUpdateTest extends UITestBase implements CommandListener { +public class DynamicUpdateTest extends UITestBase implements CommandListener +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; @@ -50,7 +51,8 @@ /** * Constructor. */ - public DynamicUpdateTest() { + public DynamicUpdateTest() + { } /** @@ -59,27 +61,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public DynamicUpdateTest(String sTestName) { + public DynamicUpdateTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = DynamicUpdateTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DynamicUpdateTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = DynamicUpdateTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DynamicUpdateTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAddAndRemoveManyCommands"); methodNames.addElement("testCommandInEmptyForm"); @@ -87,28 +93,30 @@ methodNames.addElement("testManyCommandListeners"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testAddAndRemoveManyCommands")) testAddAndRemoveManyCommands(); - else if (getName().equals("testCommandInEmptyForm")) testCommandInEmptyForm(); - else if (getName().equals("testAddCommandToManyDisplayables")) testAddCommandToManyDisplayables(); - else if (getName().equals("testManyCommandListeners")) testManyCommandListeners(); + + public void runTest() throws Throwable + { + if(getName().equals("testAddAndRemoveManyCommands")) testAddAndRemoveManyCommands(); + else if(getName().equals("testCommandInEmptyForm")) testCommandInEmptyForm(); + else if(getName().equals("testAddCommandToManyDisplayables")) testAddCommandToManyDisplayables(); + else if(getName().equals("testManyCommandListeners")) testManyCommandListeners(); else super.runTest(); } - + /** * Adds and removes many kind of commands to displayable and makes sure that * events occurs correctly all the time. */ - public void testAddAndRemoveManyCommands() { + public void testAddAndRemoveManyCommands() + { boolean testPassed = true; String testMsg = ""; latestCommand = null; latestDisplayable = null; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); Command item2 = new Command("item2", "item2", Command.ITEM, 1); @@ -132,15 +140,18 @@ // Click it: key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -154,15 +165,18 @@ key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from OK-command."; } - else if (latestCommand != ok1) { + else if(latestCommand != ok1) + { testPassed = false; testMsg = "not OK-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -186,15 +200,18 @@ key(Key.DownArrow, 0); key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from EXIT2-command."; } - else if (latestCommand != exit2) { + else if(latestCommand != exit2) + { testPassed = false; testMsg = "not EXIT2-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -211,15 +228,18 @@ key(Key.DownArrow, 0); key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from SCREEN1-command."; } - else if (latestCommand != screen1) { + else if(latestCommand != screen1) + { testPassed = false; testMsg = "not SCREEN1-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -246,7 +266,8 @@ key(Key.CBA2, 0); key(Key.Select); - if (latestCommand != null) { + if(latestCommand != null) + { testPassed = false; testMsg = "Event occured without commands."; } @@ -257,7 +278,8 @@ /** * Test to add command to empty form and verify it works. */ - public void testCommandInEmptyForm() { + public void testCommandInEmptyForm() + { latestCommand = null; latestDisplayable = null; @@ -273,25 +295,26 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command.", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong displayable delivered to commandAction-method.", - form, latestDisplayable); + form, latestDisplayable); } /** * Tests that it's possible to add one command to many displayables and * removing command from one displayable doesn't affect another displayable. */ - public void testAddCommandToManyDisplayables() { + public void testAddCommandToManyDisplayables() + { boolean testPassed = true; String testMsg = ""; latestCommand = null; latestDisplayable = null; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); @@ -307,15 +330,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in first displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in first displayable."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -328,15 +354,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in second displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in second displayable."; } - else if (latestDisplayable != textBox2) { + else if(latestDisplayable != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -349,15 +378,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in second displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in second displayable."; } - else if (latestDisplayable != textBox2) { + else if(latestDisplayable != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -373,15 +405,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in first displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in first displayable."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -393,7 +428,8 @@ * Tests the functionality of Command and CommandListener when there are * more than one CommandListener listening one Command. */ - public void testManyCommandListeners() { + public void testManyCommandListeners() + { boolean testPassed = true; String testMsg = ""; latestCommand2 = null; @@ -406,21 +442,25 @@ // Create two Displayables and two CommandListeners and add // same Command to both Displayables: TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); - textBox.setCommandListener(new CommandListener() { - public void commandAction(Command c, Displayable d) { + textBox.setCommandListener(new CommandListener() + { + public void commandAction(Command c, Displayable d) + { latestCommand2 = c; latestDisplayable2 = d; eventCount2++; } }); - textBox2.setCommandListener(new CommandListener() { - public void commandAction(Command c, Displayable d) { + textBox2.setCommandListener(new CommandListener() + { + public void commandAction(Command c, Displayable d) + { latestCommand3 = c; latestDisplayable3 = d; eventCount3++; @@ -435,19 +475,23 @@ key(Key.CBA1); - if (latestCommand3 == null) { + if(latestCommand3 == null) + { testPassed = false; testMsg = "no event in second displayable."; } - else if (latestCommand3 != item1) { + else if(latestCommand3 != item1) + { testPassed = false; testMsg = "wrong command in second displayable."; } - else if (latestDisplayable3 != textBox2) { + else if(latestDisplayable3 != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount3 != 1) { + else if(eventCount3 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount3; } @@ -457,26 +501,31 @@ key(Key.CBA1); - if (latestCommand2 == null) { + if(latestCommand2 == null) + { testPassed = false; testMsg = "no event in first displayable."; } - else if (latestCommand2 != item1) { + else if(latestCommand2 != item1) + { testPassed = false; testMsg = "wrong command in first displayable."; } - else if (latestDisplayable2 != textBox) { + else if(latestDisplayable2 != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount2 != 1) { + else if(eventCount2 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount2; } - else if (eventCount3 != 1) { + else if(eventCount3 != 1) + { testPassed = false; testMsg = "Unexpected number of events in second displayable: " - + eventCount2; + + eventCount2; } // Clear counters, remove command from second displayable and @@ -492,28 +541,34 @@ key(Key.CBA1); - if (latestCommand2 == null) { + if(latestCommand2 == null) + { testPassed = false; testMsg = "no event in first displayable."; } - else if (latestCommand2 != item1) { + else if(latestCommand2 != item1) + { testPassed = false; testMsg = "wrong command in first displayable."; } - else if (latestDisplayable2 != textBox) { + else if(latestDisplayable2 != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount2 != 1) { + else if(eventCount2 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount2; } - else if (eventCount3 != 0) { + else if(eventCount3 != 0) + { testPassed = false; testMsg = "Unexpected number of events in second displayable: " - + eventCount3; + + eventCount3; } - else if (latestCommand3 != null) { + else if(latestCommand3 != null) + { testPassed = false; testMsg = "Unexpected event in second displayable."; } @@ -528,7 +583,8 @@ * @param c Command. * @param d Displayable. */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { latestCommand = c; latestDisplayable = d; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/ItemCommandUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/ItemCommandUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/command/ItemCommandUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.command; @@ -34,7 +34,8 @@ *
            * Created: 2008-08-04 */ -public class ItemCommandUIRobotTest extends ItemUITestBase { +public class ItemCommandUIRobotTest extends ItemUITestBase +{ private Command latestCommand; private Item latestItem; @@ -45,7 +46,8 @@ /** * Constructor. */ - public ItemCommandUIRobotTest() { + public ItemCommandUIRobotTest() + { } /** @@ -54,27 +56,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ItemCommandUIRobotTest(String sTestName) { + public ItemCommandUIRobotTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ItemCommandUIRobotTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ItemCommandUIRobotTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ItemCommandUIRobotTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ItemCommandUIRobotTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testListener"); methodNames.addElement("testMultipleItems"); @@ -88,18 +94,19 @@ methodNames.addElement("testAddCommandToFocusedItem"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testListener")) testListener(); - else if (getName().equals("testMultipleItems")) testMultipleItems(); - else if (getName().equals("testInitializationOrders")) testInitializationOrders(); - else if (getName().equals("testCommandInItemAndInDisplayable")) testCommandInItemAndInDisplayable(); - else if (getName().equals("testMultipleCommands")) testMultipleCommands(); - else if (getName().equals("testOneCommandInMultipleItems")) testOneCommandInMultipleItems(); - else if (getName().equals("testDefaultCommand")) testDefaultCommand(); - else if (getName().equals("testDynamicUpdate")) testDynamicUpdate(); - else if (getName().equals("testItemWithLabel")) testItemWithLabel(); - else if (getName().equals("testAddCommandToFocusedItem")) testAddCommandToFocusedItem(); + + public void runTest() throws Throwable + { + if(getName().equals("testListener")) testListener(); + else if(getName().equals("testMultipleItems")) testMultipleItems(); + else if(getName().equals("testInitializationOrders")) testInitializationOrders(); + else if(getName().equals("testCommandInItemAndInDisplayable")) testCommandInItemAndInDisplayable(); + else if(getName().equals("testMultipleCommands")) testMultipleCommands(); + else if(getName().equals("testOneCommandInMultipleItems")) testOneCommandInMultipleItems(); + else if(getName().equals("testDefaultCommand")) testDefaultCommand(); + else if(getName().equals("testDynamicUpdate")) testDynamicUpdate(); + else if(getName().equals("testItemWithLabel")) testItemWithLabel(); + else if(getName().equals("testAddCommandToFocusedItem")) testAddCommandToFocusedItem(); else super.runTest(); } @@ -107,7 +114,8 @@ /** * Tests the basic functionality of itemCommandListener. */ - public void testListener() { + public void testListener() + { Form form = new Form("form"); StringItem button1 = new StringItem("", "click!", Item.BUTTON); @@ -123,22 +131,22 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK.", - ok, latestCommand); + + " when pressing MSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK.", - button1, latestItem); + + " when pressing MSK.", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK.", - ok, latestCommand); + + " when pressing LSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK.", - button1, latestItem); + + " when pressing LSK.", + button1, latestItem); } @@ -146,7 +154,8 @@ * Tests that item commands works when there are multiple items * in a form and focus moves between items. */ - public void testMultipleItems() { + public void testMultipleItems() + { latestCommand = null; latestItem = null; @@ -176,11 +185,11 @@ //Click first button: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 1)", - ok1, latestCommand); + + " when pressing LSK. (case 1)", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 1)", - button1, latestItem); + + " when pressing LSK. (case 1)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -189,11 +198,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 2)", - ok2, latestCommand); + + " when pressing LSK. (case 2)", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 2)", - button2, latestItem); + + " when pressing LSK. (case 2)", + button2, latestItem); latestCommand = null; latestItem = null; @@ -201,11 +210,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 3)", - ok3, latestCommand); + + " when pressing LSK. (case 3)", + ok3, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 3)", - button3, latestItem); + + " when pressing LSK. (case 3)", + button3, latestItem); latestCommand = null; latestItem = null; } @@ -213,7 +222,8 @@ /** * Tests different orders to add command, set listener etc. */ - public void testInitializationOrders() { + public void testInitializationOrders() + { latestCommand = null; latestItem = null; @@ -232,11 +242,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 1)", - ok, latestCommand); + + " when pressing LSK. (case 1)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 1)", - button1, latestItem); + + " when pressing LSK. (case 1)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -255,11 +265,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 2)", - ok, latestCommand); + + " when pressing LSK. (case 2)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 2)", - button1, latestItem); + + " when pressing LSK. (case 2)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -277,11 +287,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 3)", - ok, latestCommand); + + " when pressing LSK. (case 3)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 3)", - button1, latestItem); + + " when pressing LSK. (case 3)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -299,11 +309,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 4)", - ok, latestCommand); + + " when pressing LSK. (case 4)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 4)", - button1, latestItem); + + " when pressing LSK. (case 4)", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -312,7 +322,8 @@ * Makes sure that command works when it is added to item and * to displayable at the same time. */ - public void testCommandInItemAndInDisplayable() { + public void testCommandInItemAndInDisplayable() + { latestCommand = null; latestItem = null; @@ -337,11 +348,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting first occurence.", - ok, latestCommand); + + " when selecting first occurence.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting first occurence.", - button1, latestItem); + + " when selecting first occurence.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -351,11 +362,11 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting second occurence.", - ok, latestDisplayableCommand); + + " when selecting second occurence.", + ok, latestDisplayableCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting second occurence.", - form, latestDisplayable); + + " when selecting second occurence.", + form, latestDisplayable); latestDisplayableCommand = null; latestDisplayable = null; } @@ -364,7 +375,8 @@ * Test to add multiple commands to one item and verify the commands * work as expected. */ - public void testMultipleCommands() { + public void testMultipleCommands() + { latestCommand = null; latestItem = null; @@ -388,11 +400,11 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's first command.", - ok1, latestCommand); + + " when selecting item's first command.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's first command.", - button1, latestItem); + + " when selecting item's first command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -400,11 +412,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's second command.", - ok2, latestCommand); + + " when selecting item's second command.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's second command.", - button1, latestItem); + + " when selecting item's second command.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -413,7 +425,8 @@ * Test to add one command to multiple items and verify the command * work as expected. */ - public void testOneCommandInMultipleItems() { + public void testOneCommandInMultipleItems() + { latestCommand = null; latestItem = null; @@ -435,11 +448,11 @@ //Click first button: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when clicking first button.", - ok1, latestCommand); + + " when clicking first button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when clicking first button.", - button1, latestItem); + + " when clicking first button.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -447,11 +460,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when clicking second button.", - ok1, latestCommand); + + " when clicking second button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when clicking second button.", - button2, latestItem); + + " when clicking second button.", + button2, latestItem); latestCommand = null; latestItem = null; } @@ -460,7 +473,8 @@ /** * Tests the functionality of default command. */ - public void testDefaultCommand() { + public void testDefaultCommand() + { latestCommand = null; latestItem = null; @@ -486,11 +500,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's first command.", - ok1, latestCommand); + + " when selecting item's first command.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's first command.", - button1, latestItem); + + " when selecting item's first command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -506,11 +520,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's second command.", - ok2, latestCommand); + + " when selecting item's second command.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's second command.", - button1, latestItem); + + " when selecting item's second command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -518,11 +532,11 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when selecting item's default command from MSK.", - ok2, latestCommand); + + " when selecting item's default command from MSK.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's default command from MSK.", - button1, latestItem); + + " when selecting item's default command from MSK.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -532,7 +546,8 @@ * For example makes sure that focus is where it should be. * */ - public void testDynamicUpdate() { + public void testDynamicUpdate() + { latestCommand = null; latestItem = null; @@ -558,11 +573,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing second button.", - ok2, latestCommand); + + " when pressing second button.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing second button.", - button2, latestItem); + + " when pressing second button.", + button2, latestItem); latestCommand = null; latestItem = null; @@ -573,11 +588,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing second button after update.", - ok2, latestCommand); + + " when pressing second button after update.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing second after update.", - button2, latestItem); + + " when pressing second after update.", + button2, latestItem); latestCommand = null; latestItem = null; @@ -585,11 +600,11 @@ key(Key.LeftArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing first button.", - ok1, latestCommand); + + " when pressing first button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing first button.", - button1, latestItem); + + " when pressing first button.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -597,7 +612,8 @@ /** * Tests commands when there's label in item. */ - public void testItemWithLabel() { + public void testItemWithLabel() + { latestCommand = null; latestItem = null; @@ -615,35 +631,37 @@ //Click middle soft key, this should activate item's command: key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK (StringItem).", - ok, latestCommand); + + " when pressing MSK (StringItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK (StringItem).", - button1, latestItem); + + " when pressing MSK (StringItem).", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK (StringItem).", - ok, latestCommand); + + " when pressing LSK (StringItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK (StringItem).", - button1, latestItem); + + " when pressing LSK (StringItem).", + button1, latestItem); latestCommand = null; latestItem = null; //Test ImageItem next: Image image = null; - try { + try + { image = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } ImageItem image1 = new ImageItem( - "label", image, Item.BUTTON, "altText", ImageItem.BUTTON); + "label", image, Item.BUTTON, "altText", ImageItem.BUTTON); image1.addCommand(ok); image1.setItemCommandListener(this); @@ -657,22 +675,22 @@ //Click middle soft key, this should activate item's command: key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK (ImageItem).", - ok, latestCommand); + + " when pressing MSK (ImageItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK (ImageItem).", - image1, latestItem); + + " when pressing MSK (ImageItem).", + image1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK (ImageItem).", - ok, latestCommand); + + " when pressing LSK (ImageItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK (ImageItem).", - image1, latestItem); + + " when pressing LSK (ImageItem).", + image1, latestItem); latestCommand = null; latestItem = null; } @@ -680,7 +698,8 @@ /** * Tests to add command to item that's focused. */ - public void testAddCommandToFocusedItem() { + public void testAddCommandToFocusedItem() + { latestCommand = null; latestItem = null; @@ -708,22 +727,22 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK.", - ok, latestCommand); + + " when pressing MSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK.", - button1, latestItem); + + " when pressing MSK.", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK.", - ok, latestCommand); + + " when pressing LSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK.", - button1, latestItem); + + " when pressing LSK.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -734,7 +753,8 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; } @@ -745,7 +765,8 @@ * @param c Command * @param d Displayable */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { latestDisplayableCommand = c; latestDisplayable = d; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/customitem/CustomItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/customitem/CustomItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/customitem/CustomItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.customitem; @@ -32,51 +32,57 @@ *
            * Created: 2008-12-01 */ -public class CustomItemTest extends ItemUITestBase { +public class CustomItemTest extends ItemUITestBase +{ private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; /** * Constructor. */ - public CustomItemTest() { + public CustomItemTest() + { } - + /** * Constructor. * * @param sTestName Test name. * @param rTestMethod Test method. */ - public CustomItemTest(String sTestName) { + public CustomItemTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = CustomItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new CustomItemTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = CustomItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new CustomItemTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testBasicMethodCalls"); methodNames.addElement("testInnerTraverse1"); @@ -84,20 +90,22 @@ methodNames.addElement("testInnerTraverse5"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testBasicMethodCalls")) testBasicMethodCalls(); - else if (getName().equals("testInnerTraverse1")) testInnerTraversal(1); - else if (getName().equals("testInnerTraverse3")) testInnerTraversal(3); - else if (getName().equals("testInnerTraverse5")) testInnerTraversal(5); + + public void runTest() throws Throwable + { + if(getName().equals("testBasicMethodCalls")) testBasicMethodCalls(); + else if(getName().equals("testInnerTraverse1")) testInnerTraversal(1); + else if(getName().equals("testInnerTraverse3")) testInnerTraversal(3); + else if(getName().equals("testInnerTraverse5")) testInnerTraversal(5); else super.runTest(); } - + /** * Tests that getMinimumSize returns non-zero values. */ - public void testBasicMethodCalls() { + public void testBasicMethodCalls() + { Form bg = new Form("background"); setCurrent(bg); @@ -114,11 +122,11 @@ setCurrent(form); assertEquals("1. Invalid CustomItem state", - MyCustomItem.TEST_SIZECHANGE - | MyCustomItem.TEST_SHOW - | MyCustomItem.TEST_PAINT - | MyCustomItem.TEST_TRAVERSEIN, - ci1.getState()); + MyCustomItem.TEST_SIZECHANGE + | MyCustomItem.TEST_SHOW + | MyCustomItem.TEST_PAINT + | MyCustomItem.TEST_TRAVERSEIN, + ci1.getState()); assertTrue("invalid width", ci1.width < 1000); @@ -128,22 +136,22 @@ key(Key.CBA1); key(Key.CBA2); assertEquals("2. Invalid CustomItem state", - MyCustomItem.TEST_KEYPRESS - | MyCustomItem.TEST_KEYRELEASE, - ci1.getState()); + MyCustomItem.TEST_KEYPRESS + | MyCustomItem.TEST_KEYRELEASE, + ci1.getState()); // Hide form setCurrent(bg); assertTrue("hideNotify() not called", - ci1.isCalled(MyCustomItem.TEST_HIDE)); + ci1.isCalled(MyCustomItem.TEST_HIDE)); // Set current item ci1.clearState(); display.setCurrentItem(ci1); block(CHANGE_DISPLAYABLE_DELAY); assertTrue("showNotify() not called", - ci1.isCalled(MyCustomItem.TEST_SHOW)); + ci1.isCalled(MyCustomItem.TEST_SHOW)); // partial repaint ci1.clearState(); @@ -151,11 +159,12 @@ block(KEYEVENT_DELAY); assertTrue("paint() not called", ci1.isCalled(MyCustomItem.TEST_PAINT)); assertTrue("wrong clipping area", - ci1.clipX == 10 && ci1.clipY == 5 && - ci1.clipW == 20 && ci1.clipH == 10); + ci1.clipX == 10 && ci1.clipY == 5 && + ci1.clipW == 20 && ci1.clipH == 10); } - void testInnerTraversal(int numInnerTraversals) { + void testInnerTraversal(int numInnerTraversals) + { Form fg = new Form("InnerTraverse " + numInnerTraversals); MyCustomItem ci1 = new MyCustomItem("CustomItem 1", numInnerTraversals); ci1.sizeChanged(1000, 75); @@ -172,39 +181,43 @@ // Traversing to CI 2 ci1.clearState(); ci2.clearState(); - for (int i = 0; i < numInnerTraversals; i++) { + for(int i = 0; i < numInnerTraversals; i++) + { assertTrue("Illegal traversing to CI 2", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); key(Key.DownArrow); } assertTrue("Should traverse to CI 2", - ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) - && ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); + ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) + && ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); // Traversing back to CI 1 ci1.clearState(); ci2.clearState(); - for (int i = 0; i < numInnerTraversals - 1; i++) { + for(int i = 0; i < numInnerTraversals - 1; i++) + { assertTrue("1. Illegal traversing to CI 1", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); key(Key.DownArrow); } - for (int i = 0; i < numInnerTraversals; i++) { + for(int i = 0; i < numInnerTraversals; i++) + { assertTrue("2. Illegal traversing to CI 1", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); key(Key.UpArrow); } assertTrue("Should traverse to CI 1", - ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); } - class MyCustomItem extends CustomItem { + class MyCustomItem extends CustomItem + { static final int TEST_SHOW = 1; static final int TEST_HIDE = 2; @@ -222,77 +235,95 @@ int clipX, clipY, clipW, clipH; int width, height; - protected MyCustomItem(String label, int numInnerFocus) { + protected MyCustomItem(String label, int numInnerFocus) + { super(label); numFocus = Math.max(1, numInnerFocus); focus = -1; } - void clearState() { + void clearState() + { state = 0; } - int getState() { + int getState() + { return state; } - boolean isCalled(int mask) { + boolean isCalled(int mask) + { return (state & mask) != 0; } - private void setState(int newState) { + private void setState(int newState) + { state |= newState; } - void doRepaint(int x, int y, int w, int h) { + void doRepaint(int x, int y, int w, int h) + { repaint(x, y, w, h); } - protected void keyPressed(int keyCode) { + protected void keyPressed(int keyCode) + { setState(TEST_KEYPRESS); } - protected void keyReleased(int keyCode) { + protected void keyReleased(int keyCode) + { setState(TEST_KEYRELEASE); } - protected void showNotify() { + protected void showNotify() + { setState(TEST_SHOW); } - protected void hideNotify() { + protected void hideNotify() + { setState(TEST_HIDE); } - protected void sizeChanged(int width, int height) { + protected void sizeChanged(int width, int height) + { this.width = width; this.height = height; setState(TEST_SIZECHANGE); } protected boolean traverse(int dir, int viewportWidth, - int viewportHeight, int[] visRect_inout) { + int viewportHeight, int[] visRect_inout) + { boolean ret = false; setState(TEST_TRAVERSEIN); - if (numFocus == 1) { + if(numFocus == 1) + { focus = 0; } - else if (numFocus > 1) { + else if(numFocus > 1) + { int div = numFocus + 1; focus++; - if (dir == Canvas.UP || dir == Canvas.LEFT) { + if(dir == Canvas.UP || dir == Canvas.LEFT) + { focus = (focus - 1 + div) % div; } - else if (dir == Canvas.DOWN || dir == Canvas.RIGHT) { + else if(dir == Canvas.DOWN || dir == Canvas.RIGHT) + { focus = (focus + 1 + div) % div; } - else { + else + { focus = 1; } focus--; - if (focus > -1) { + if(focus > -1) + { ret = true; } } @@ -300,13 +331,15 @@ return ret; } - protected void traverseOut() { + protected void traverseOut() + { setState(TEST_TRAVERSEOUT); focus = -1; repaint(); } - protected void paint(Graphics g, int w, int h) { + protected void paint(Graphics g, int w, int h) + { setState(TEST_PAINT); clipX = g.getClipX(); @@ -317,25 +350,30 @@ g.setColor(0xffffff); g.fillRect(0, 0, w, h); - if (focus > -1) { + if(focus > -1) + { g.setColor(0x000000); - g.fillRect(0, focus * (h / numFocus), w, h / numFocus); + g.fillRect(0, focus *(h / numFocus), w, h / numFocus); } } - protected int getMinContentHeight() { + protected int getMinContentHeight() + { return height; } - protected int getMinContentWidth() { + protected int getMinContentWidth() + { return width; } - protected int getPrefContentHeight(int h) { + protected int getPrefContentHeight(int h) + { return height; } - protected int getPrefContentWidth(int w) { + protected int getPrefContentWidth(int w) + { return width; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/datefield/DateFieldUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/datefield/DateFieldUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/datefield/DateFieldUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.datefield; @@ -35,7 +35,8 @@ *
            * Created: 2008-10-02 */ -public class DateFieldUIRobotTest extends ItemUITestBase { +public class DateFieldUIRobotTest extends ItemUITestBase +{ //2008-10-07 11:30:35 is 1223368235775 in millis. private static final long TEST_DATE_IN_MILLIS = 1223368235775L; @@ -53,7 +54,8 @@ /** * Constructor. */ - public DateFieldUIRobotTest() { + public DateFieldUIRobotTest() + { } /** @@ -62,27 +64,31 @@ * @param testName Test name. * @param testMethod Test method. */ - public DateFieldUIRobotTest(String testName) { + public DateFieldUIRobotTest(String testName) + { super(testName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = DateFieldUIRobotTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new DateFieldUIRobotTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = DateFieldUIRobotTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new DateFieldUIRobotTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCommands"); methodNames.addElement("testMinimumSize"); @@ -94,23 +100,25 @@ methodNames.addElement("testSetAndGetDateTime"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommands")) testCommands(); - else if (getName().equals("testMinimumSize")) testMinimumSize(); - else if (getName().equals("testInputModeChange")) testInputModeChange(); - else if (getName().equals("testItemStateChange")) testItemStateChange(); - else if (getName().equals("testGetDateWhenModifying")) testGetDateWhenModifying(); - else if (getName().equals("testSetAndGetDate")) testSetAndGetDate(); - else if (getName().equals("testSetAndGetTime")) testSetAndGetTime(); - else if (getName().equals("testSetAndGetDateTime")) testSetAndGetDateTime(); + + public void runTest() throws Throwable + { + if(getName().equals("testCommands")) testCommands(); + else if(getName().equals("testMinimumSize")) testMinimumSize(); + else if(getName().equals("testInputModeChange")) testInputModeChange(); + else if(getName().equals("testItemStateChange")) testItemStateChange(); + else if(getName().equals("testGetDateWhenModifying")) testGetDateWhenModifying(); + else if(getName().equals("testSetAndGetDate")) testSetAndGetDate(); + else if(getName().equals("testSetAndGetTime")) testSetAndGetTime(); + else if(getName().equals("testSetAndGetDateTime")) testSetAndGetDateTime(); else super.runTest(); } /** * Tests the basic functionality of command added to DateField. */ - public void testCommands() { + public void testCommands() + { DateField dateField = new DateField("label", DateField.DATE); testCommand(dateField); } @@ -118,7 +126,8 @@ /** * Tests that getMinimumSize returns non-zero values. */ - public void testMinimumSize() { + public void testMinimumSize() + { //With label: DateField dateField = new DateField("label", DateField.DATE); @@ -126,7 +135,8 @@ int h = dateField.getMinimumHeight(); print("Size returned (with label), w: " + w + ", h: " + h); - if ((w <= 0) || (h <= 0)) { + if((w <= 0) || (h <= 0)) + { fail("Minimum width or height was zero or less."); } @@ -137,7 +147,8 @@ h = dateField2.getMinimumHeight(); print("Size returned (without label), w: " + w + ", h: " + h); - if ((w <= 0) || (h <= 0)) { + if((w <= 0) || (h <= 0)) + { fail("Minimum width or height was zero or less."); } } @@ -145,7 +156,8 @@ /** * Tests to change input mode dynamically. */ - public void testInputModeChange() { + public void testInputModeChange() + { // Create DateField of input mode TIME: DateField dateField = new DateField("label", DateField.TIME); form.append(dateField); @@ -171,13 +183,14 @@ calendar.setTime(newDate); assertEquals("Wrong day returned after input mode changed.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); } /** * Tests the ItemStateChange-listener added to DateField. */ - public void testItemStateChange() { + public void testItemStateChange() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -193,7 +206,7 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); // Change item's state programmatically and make sure the // listener is _not_ called: @@ -204,7 +217,8 @@ /** * Test to get date when user is modifying datefield. */ - public void testGetDateWhenModifying() { + public void testGetDateWhenModifying() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -220,7 +234,8 @@ /** * Test to set and get date. */ - public void testSetAndGetDate() { + public void testSetAndGetDate() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -246,17 +261,18 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals("Wrong month returned.", - TEST_MONTH, calendar.get(Calendar.MONTH)); + TEST_MONTH, calendar.get(Calendar.MONTH)); assertEquals("Wrong year returned.", - TEST_YEAR, calendar.get(Calendar.YEAR)); + TEST_YEAR, calendar.get(Calendar.YEAR)); } /** * Test to set and get time. */ - public void testSetAndGetTime() { + public void testSetAndGetTime() + { DateField dateField = new DateField("label", DateField.TIME); form.append(dateField); setCurrent(form); @@ -281,15 +297,16 @@ calendar.setTime(newDate); assertEquals("Wrong hour returned.", - TEST_HOUR, calendar.get(Calendar.HOUR)); + TEST_HOUR, calendar.get(Calendar.HOUR)); assertEquals("Wrong minute returned.", - TEST_MINUTE, calendar.get(Calendar.MINUTE)); + TEST_MINUTE, calendar.get(Calendar.MINUTE)); } /** * Test to set and get date_time. */ - public void testSetAndGetDateTime() { + public void testSetAndGetDateTime() + { DateField dateField = new DateField("label", DateField.DATE_TIME); form.append(dateField); setCurrent(form); @@ -323,15 +340,15 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals("Wrong month returned.", - TEST_MONTH, calendar.get(Calendar.MONTH)); + TEST_MONTH, calendar.get(Calendar.MONTH)); assertEquals("Wrong year returned.", - TEST_YEAR, calendar.get(Calendar.YEAR)); + TEST_YEAR, calendar.get(Calendar.YEAR)); assertEquals("Wrong hour returned.", - TEST_HOUR, calendar.get(Calendar.HOUR)); + TEST_HOUR, calendar.get(Calendar.HOUR)); assertEquals("Wrong minute returned.", - TEST_MINUTE, calendar.get(Calendar.MINUTE)); + TEST_MINUTE, calendar.get(Calendar.MINUTE)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/FlashAndVibrateTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/FlashAndVibrateTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/FlashAndVibrateTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.display; @@ -34,7 +34,8 @@ *
            * Created: 2008-05-23 */ -public class FlashAndVibrateTest extends UITestBase { +public class FlashAndVibrateTest extends UITestBase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; private static final int SEND_BACKGROUND_DELAY = 300; @@ -46,7 +47,8 @@ /** * Constructor. */ - public FlashAndVibrateTest() { + public FlashAndVibrateTest() + { } /** @@ -55,36 +57,41 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FlashAndVibrateTest(String sTestName) { + public FlashAndVibrateTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = FlashAndVibrateTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FlashAndVibrateTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = FlashAndVibrateTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FlashAndVibrateTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testMethodsWhenBackground"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testMethodsWhenBackground")) testMethodsWhenBackground(); + + public void runTest() throws Throwable + { + if(getName().equals("testMethodsWhenBackground")) testMethodsWhenBackground(); else super.runTest(); - } + } /** * Test that vibrate() and flashBacklights() -methods returns false when @@ -92,13 +99,14 @@ * flashing and vibration are supported and will pass even if there's * no support to the functionality. */ - public void testMethodsWhenBackground() { + public void testMethodsWhenBackground() + { boolean testPassed = true; String testMsg = ""; Display display = Display.getDisplay(getMIDlet()); TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); setCurrent(textBox); @@ -107,15 +115,17 @@ key(Key.Applications, SEND_BACKGROUND_DELAY); - if (display.vibrate(VIBRA_TIME)) { + if(display.vibrate(VIBRA_TIME)) + { testPassed = false; testMsg = "vibrate() returned true when MIDlet was in background."; } - if (display.flashBacklight(FLASH_TIME)) { + if(display.flashBacklight(FLASH_TIME)) + { testPassed = false; testMsg = "flashBacklights() returned true when MIDlet" - + " was in background."; + + " was in background."; } //Move MIDlet back to foreground: diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/SetCurrentItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/SetCurrentItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/display/SetCurrentItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.display; @@ -33,7 +33,8 @@ * Created: 2008-08-26 */ public class SetCurrentItemTest extends UITestBase implements - ItemCommandListener { + ItemCommandListener +{ private static int count1; private static int count2; @@ -53,7 +54,8 @@ /** * Constructor. */ - public SetCurrentItemTest() { + public SetCurrentItemTest() + { } /** @@ -62,27 +64,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SetCurrentItemTest(String sTestName) { + public SetCurrentItemTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = SetCurrentItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SetCurrentItemTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = SetCurrentItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SetCurrentItemTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testExceptions"); methodNames.addElement("testSetCurrentItem"); @@ -90,23 +96,26 @@ methodNames.addElement("displayableSwithTest"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testExceptions")) testExceptions(); - else if (getName().equals("testSetCurrentItem")) testSetCurrentItem(); - else if (getName().equals("testCrash")) testCrash(); - else if (getName().equals("displayableSwithTest")) displayableSwithTest(); + + public void runTest() throws Throwable + { + if(getName().equals("testExceptions")) testExceptions(); + else if(getName().equals("testSetCurrentItem")) testSetCurrentItem(); + else if(getName().equals("testCrash")) testCrash(); + else if(getName().equals("displayableSwithTest")) displayableSwithTest(); else super.runTest(); } - + /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - for (int i = 0; i < sia.length; i++) { - sia[i] = new StringItem("", "click" + (i + 1), Item.BUTTON); - } + for(int i = 0; i < sia.length; i++) + { + sia[i] = new StringItem("", "click" + (i + 1), Item.BUTTON); + } } @@ -114,33 +123,40 @@ * Makes sure that setCurrentItem() throws exceptions as * expected. */ - public void testExceptions() { + public void testExceptions() + { boolean exceptionThrown = false; StringItem button1 = new StringItem("", "click!", Item.BUTTON); //Test null item: - try { + try + { display.setCurrentItem(null); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { fail("No exception when item was null."); } //Test to call method when item is not owned by a container: exceptionThrown = false; - try { + try + { display.setCurrentItem(button1); } - catch (IllegalStateException ex) { + catch(IllegalStateException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { fail("No exception when item was not owned by a container."); } } @@ -151,7 +167,8 @@ * visible, is it focusable or not, but the check of item's visibility * is out of scope of this test. */ - public void testSetCurrentItem() { + public void testSetCurrentItem() + { latestCommand = null; latestItem = null; @@ -161,9 +178,10 @@ StringItem button1 = new StringItem("", "click!", Item.BUTTON); StringItem button2 = new StringItem("", "click me2", Item.BUTTON); StringItem[] lotOfButtons = new StringItem[25]; - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { lotOfButtons[i] = new StringItem( - "", "button " + (i + 1), Item.BUTTON); + "", "button " + (i + 1), Item.BUTTON); } Command ok = new Command("Ok", "", Command.ITEM, 0); @@ -178,14 +196,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 1).", - ok, latestCommand); + + " (case 1).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 1).", - button1, latestItem); + + " (case 1).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 1).", - form, display.getCurrent()); + + " (case 1).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -197,14 +215,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 2).", - ok, latestCommand); + + " (case 2).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 2).", - button1, latestItem); + + " (case 2).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 2).", - form, display.getCurrent()); + + " (case 2).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -219,14 +237,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 3).", - ok, latestCommand); + + " (case 3).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 3).", - button1, latestItem); + + " (case 3).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 3).", - form2, display.getCurrent()); + + " (case 3).", + form2, display.getCurrent()); latestCommand = null; latestItem = null; @@ -234,7 +252,8 @@ //Test method when item is in another displayable //and there are lot of items before the item: form2.deleteAll(); - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { form.append(lotOfButtons[i]); } form.append(button1); @@ -245,14 +264,14 @@ block(500); key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 4).", - ok, latestCommand); + + " (case 4).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 4).", - button1, latestItem); + + " (case 4).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 4).", - form, display.getCurrent()); + + " (case 4).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -261,7 +280,8 @@ //and there are lot of items before the item: form.deleteAll(); form.append(button1); - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { form.append(lotOfButtons[i]); } form.append(button2); @@ -275,14 +295,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 5).", - ok, latestCommand); + + " (case 5).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 5).", - button1, latestItem); + + " (case 5).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 5).", - form, display.getCurrent()); + + " (case 5).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -301,7 +321,8 @@ * Test tries to make setCurrentItem()-method crash or hang * the midlet somehow. */ - public void testCrash() { + public void testCrash() + { Form form = new Form("form"); Form form2 = new Form("form2"); StringItem plain1 = new StringItem("", "not focusable.", Item.PLAIN); @@ -324,7 +345,8 @@ //Make many calls without delay: form.append(button1); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) + { display.setCurrentItem(button1); display.setCurrentItem(plain1); } @@ -336,7 +358,8 @@ * Displayable is switched to new one, but old still has * doLayout() ongoing. */ - public void displayableSwithTest() { + public void displayableSwithTest() + { Form form = new Form("form"); Form form2 = new Form("form2"); @@ -354,7 +377,8 @@ form.append(button1); form.append(button2); - for (int i = 0; i < sia.length; i++) { + for(int i = 0; i < sia.length; i++) + { form2.append(sia[i]); sia[i].addCommand(c3); } @@ -366,7 +390,7 @@ block(CHANGE_DISPLAYABLE_DELAY); key(Key.Select); assertEquals("Not Correct Comand was called, probable Displayable" - + " switched back to initial.", c3, latestCommand); + + " switched back to initial.", c3, latestCommand); } /** @@ -375,24 +399,28 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; - if (c == c1) { + if(c == c1) + { System.out.println("button1 clicked, command: " + c + " item: " - + item); + + item); button1.setText("clicks: " + (++count1)); display.setCurrentItem(button3); //display.setCurrentItem(sia[sia.length-1]); } - else if (c == c2) { + else if(c == c2) + { System.out.println("button2 clicked, command: " + c + " item: " - + item); + + item); button2.setText("clicks: " + (++count2)); } - else if (c == c3) { + else if(c == c3) + { System.out.println("button3 clicked, command: " + c + " item: " - + item); + + item); //button3.setText("clicks: "+ (++count3)); display.setCurrentItem(button1); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/AddCommandTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/AddCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/AddCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.displayable; @@ -34,35 +34,41 @@ *
            * Created: 2008-04-30 */ -public class AddCommandTest extends UITestBase { +public class AddCommandTest extends UITestBase +{ private static final int MAX_CHARS = 100; - public AddCommandTest() { - super(); - } + public AddCommandTest() + { + super(); + } - public AddCommandTest(String name) { - super(name); - } + public AddCommandTest(String name) + { + super(name); + } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = AddCommandTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new AddCommandTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = AddCommandTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new AddCommandTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAddCommandBeforeListener"); methodNames.addElement("testAddCommandAfterListener"); @@ -71,21 +77,23 @@ methodNames.addElement("testAddCommandTwice"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testAddCommandBeforeListener")) testAddCommandBeforeListener(); - else if (getName().equals("testAddCommandAfterListener")) testAddCommandAfterListener(); - else if (getName().equals("testRemoveListener")) testRemoveListener(); - else if (getName().equals("testAddToManyDisplayables")) testAddToManyDisplayables(); - else if (getName().equals("testAddCommandTwice")) testAddCommandTwice(); + + public void runTest() throws Throwable + { + if(getName().equals("testAddCommandBeforeListener")) testAddCommandBeforeListener(); + else if(getName().equals("testAddCommandAfterListener")) testAddCommandAfterListener(); + else if(getName().equals("testRemoveListener")) testRemoveListener(); + else if(getName().equals("testAddToManyDisplayables")) testAddToManyDisplayables(); + else if(getName().equals("testAddCommandTwice")) testAddCommandTwice(); else super.runTest(); - } - + } + /** * Test command adding before CommandListener is set. */ - public void testAddCommandBeforeListener() { + public void testAddCommandBeforeListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -103,7 +111,8 @@ /** * Test command adding after CommandListener is set. */ - public void testAddCommandAfterListener() { + public void testAddCommandAfterListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -122,7 +131,8 @@ * Test that removing CommandListener will work and no commands are * delivered to CommandListener anymore. */ - public void testRemoveListener() { + public void testRemoveListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -144,7 +154,8 @@ * In LCDUI it's possible to add same Command to many Displayables. This * test tests that events occurs correctly in such case. */ - public void testAddToManyDisplayables() { + public void testAddToManyDisplayables() + { // There are two Displayables and one Command in this test: TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); TextBox textBox2 = new TextBox("title2", "content2", MAX_CHARS, 0); @@ -198,7 +209,8 @@ * Tests that nothing happens if command is added to the displayable which * already contains the command. */ - public void testAddCommandTwice() { + public void testAddCommandTwice() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SendBackgroundTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SendBackgroundTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SendBackgroundTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.displayable; @@ -33,7 +33,8 @@ *
            * Created: 2008-05-07 */ -public class SendBackgroundTest extends UITestBase { +public class SendBackgroundTest extends UITestBase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; private static final int SEND_BACKGROUND_DELAY = 300; @@ -42,8 +43,9 @@ /** * Constructor. */ - public SendBackgroundTest() { - super(); + public SendBackgroundTest() + { + super(); } /** @@ -52,51 +54,57 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SendBackgroundTest(String sTestName) { + public SendBackgroundTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = SendBackgroundTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SendBackgroundTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = SendBackgroundTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SendBackgroundTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testIsShownWhenBackground"); methodNames.addElement("testIsShownWhenNotCurrent"); methodNames.addElement("testGetHeightAndWidth"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testIsShownWhenBackground")) testIsShownWhenBackground(); - else if (getName().equals("testIsShownWhenNotCurrent")) testIsShownWhenNotCurrent(); - else if (getName().equals("testGetHeightAndWidth")) testGetHeightAndWidth(); + + public void runTest() throws Throwable + { + if(getName().equals("testIsShownWhenBackground")) testIsShownWhenBackground(); + else if(getName().equals("testIsShownWhenNotCurrent")) testIsShownWhenNotCurrent(); + else if(getName().equals("testGetHeightAndWidth")) testGetHeightAndWidth(); else super.runTest(); - } + } /** * Test that isShown()-method returns false when displayable is in * background. */ - public void testIsShownWhenBackground() { + public void testIsShownWhenBackground() + { boolean testPassed = true; String testMsg = ""; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); setCurrent(textBox); @@ -104,7 +112,8 @@ // returns false: key(Key.Applications, SEND_BACKGROUND_DELAY); - if (textBox.isShown()) { + if(textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned true when MIDlet was in background."; } @@ -116,7 +125,8 @@ key(Key.Select, 0); key(Key.Select, SEND_FOREGROUND_DELAY); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when MIDlet was in foreground."; } @@ -128,18 +138,20 @@ * Tests that isShown() returns false if displayable is first set current * and then another displayable is set current. */ - public void testIsShownWhenNotCurrent() { + public void testIsShownWhenNotCurrent() + { boolean testPassed = true; String testMsg = ""; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); // First set displayable current and make sure it's shown: setCurrent(textBox); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when displayable current."; } @@ -148,7 +160,8 @@ // one isn't shown: setCurrent(textBox2); - if (textBox.isShown()) { + if(textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned true when displayable isn't current."; } @@ -156,10 +169,11 @@ // Now move first displayable back to current and make sure // it knows it's shown: setCurrent(textBox); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when displayable set " - + " back to current."; + + " back to current."; } assertTrue(getName() + " failed, " + testMsg, testPassed); @@ -169,16 +183,17 @@ * Tests the functionality of getWidth() and getHeight()-methods when * displayable not current and when MIDlet is sent to background. */ - public void testGetHeightAndWidth() { + public void testGetHeightAndWidth() + { boolean testPassed = true; String testMsg = ""; int width = 0; int height = 0; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); // Get initial values: width = textBox.getWidth(); @@ -187,23 +202,25 @@ // Set displayable to current and make sure the dimension isn't changed: setCurrent(textBox); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after displayable set current:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } // Send MIDlet to background and verify that dimension remains same: key(Key.Applications, SEND_BACKGROUND_DELAY); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after MIDlet sent to background:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } // Move MIDlet back to foreground: @@ -216,12 +233,13 @@ // of first displayable remains same: setCurrent(textBox2); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after other displayable set current:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } assertTrue(getName() + " failed, " + testMsg, testPassed); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SizeChangedTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SizeChangedTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/displayable/SizeChangedTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.displayable; @@ -30,7 +30,8 @@ *
            * Created: 2008-05-19 */ -public class SizeChangedTest extends UITestBase { +public class SizeChangedTest extends UITestBase +{ private static final int MAX_CHARS = 100; private static final int DELAY_AFTER_RESOLUTION_CHANGE = 300; @@ -43,8 +44,9 @@ /** * Constructor. */ - public SizeChangedTest() { - super(); + public SizeChangedTest() + { + super(); } /** @@ -53,43 +55,49 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SizeChangedTest(String sTestName) { + public SizeChangedTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = SizeChangedTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SizeChangedTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = SizeChangedTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SizeChangedTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testSizeChange"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testSizeChange")) testSizeChange(); + + public void runTest() throws Throwable + { + if(getName().equals("testSizeChange")) testSizeChange(); else super.runTest(); - } + } /** * Creates class that extends Displayable and implements * sizeChanged()-method. Then verifies the method is called as described in * API spesification. */ - public void testSizeChange() { + public void testSizeChange() + { boolean testPassed = true; String testMsg = ""; int width; @@ -102,10 +110,11 @@ // Displayable is set to visible: setCurrent(scl); - if (firstCallFailure) { + if(firstCallFailure) + { testPassed = false; testMsg = "sizeChanged not called before" - + " displayable set to visible."; + + " displayable set to visible."; } sizeChangedFlag = false; width = newWidth; @@ -115,20 +124,23 @@ // different resolution (this emulates dynamic change from // portrait to landscape screen): switchResolution(); - + // Verify that sizeChanged() is called and the // width and height values are not the same as before: - if (!sizeChangedFlag) { + if(!sizeChangedFlag) + { testPassed = false; testMsg = "sizeChanged not called when" - + " screen dimension changed."; + + " screen dimension changed."; } - else if (width == newWidth) { + else if(width == newWidth) + { testPassed = false; testMsg = "width not updated when" + " screen dimension changed."; } - else if (height == newHeight) { + else if(height == newHeight) + { testPassed = false; testMsg = "height not updated when" + " screen dimension changed."; } @@ -143,7 +155,8 @@ // Change the size of the invisible displayable by // changing the screen resolution back to original: - for (int i = 0; i < getNumberOfResolutions() - 1; i++) { + for(int i = 0; i < getNumberOfResolutions() - 1; i++) + { switchResolution(); } block(DELAY_AFTER_RESOLUTION_CHANGE); @@ -153,21 +166,24 @@ // Also make sure the width and height are updated. setCurrent(scl); - if (!sizeChangedFlag) { + if(!sizeChangedFlag) + { testPassed = false; testMsg = "sizeChanged not called when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } - else if (width == newWidth) { + else if(width == newWidth) + { testPassed = false; testMsg = "width not updated when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } - else if (height == newHeight) { + else if(height == newHeight) + { testPassed = false; testMsg = "height not updated when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } assertTrue(getName() + " failed, " + testMsg, testPassed); @@ -178,19 +194,23 @@ * extend Displayable directly. That's why Canvas is extended here. Another * possible class would be Form. */ - class SizeChangeListener extends Canvas { + class SizeChangeListener extends Canvas + { private boolean firstCall = true; /* (non-Javadoc) * @see javax.microedition.lcdui.Canvas#sizeChanged(int, int) */ - protected void sizeChanged(int w, int h) { - if (firstCall) { + protected void sizeChanged(int w, int h) + { + if(firstCall) + { // sizeChanged must be called at least once // before displayable is set to visible. // Make sure the displayable is not visible yet: - if (isShown()) { + if(isShown()) + { firstCallFailure = true; } firstCall = false; @@ -201,7 +221,8 @@ newHeight = h; } - protected void paint(Graphics g) { + protected void paint(Graphics g) + { } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/form/FormItemTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/form/FormItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/form/FormItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.form; @@ -33,13 +33,15 @@ *
            * Created: 2008-11-12 */ -public class FormItemTest extends ItemUITestBase { +public class FormItemTest extends ItemUITestBase +{ /** * Constructor. */ - public FormItemTest() { - super(); + public FormItemTest() + { + super(); } /** @@ -48,27 +50,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FormItemTest(String sTestName) { + public FormItemTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = FormItemTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FormItemTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = FormItemTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FormItemTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testAppendItemAfterSetCurrent"); methodNames.addElement("testRemoveCommandFromLabeledFocusedItem"); @@ -76,21 +82,23 @@ methodNames.addElement("testRemoveItemsWhenBackground"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testAppendItemAfterSetCurrent")) testAppendItemAfterSetCurrent(); - else if (getName().equals("testRemoveCommandFromLabeledFocusedItem")) testRemoveCommandFromLabeledFocusedItem(); - else if (getName().equals("testAddRemoveItems")) testAddRemoveItems(); - else if (getName().equals("testRemoveItemsWhenBackground")) testRemoveItemsWhenBackground(); + + public void runTest() throws Throwable + { + if(getName().equals("testAppendItemAfterSetCurrent")) testAppendItemAfterSetCurrent(); + else if(getName().equals("testRemoveCommandFromLabeledFocusedItem")) testRemoveCommandFromLabeledFocusedItem(); + else if(getName().equals("testAddRemoveItems")) testAddRemoveItems(); + else if(getName().equals("testRemoveItemsWhenBackground")) testRemoveItemsWhenBackground(); else super.runTest(); - } - + } + /** * Tests to remove command from focused item which has label and * verifies that focus is moved to next/previous focusable item. */ - public void testRemoveCommandFromLabeledFocusedItem() { + public void testRemoveCommandFromLabeledFocusedItem() + { StringItem button1 = new StringItem("label", "click!", Item.BUTTON); StringItem button2 = new StringItem("label", "click2!", Item.BUTTON); @@ -129,7 +137,8 @@ /** * Tests to add and remove items to/from form. */ - public void testAddRemoveItems() { + public void testAddRemoveItems() + { Command ok1 = new Command("Ok1", "", Command.ITEM, 0); Command ok2 = new Command("Ok2", "", Command.ITEM, 0); @@ -171,11 +180,12 @@ * Tests to append item to form after form is set current. Then * verifies the focus transfer works. */ - public void testAppendItemAfterSetCurrent() { + public void testAppendItemAfterSetCurrent() + { StringItem hyperlink = new StringItem("label", "url", - StringItem.HYPERLINK); + StringItem.HYPERLINK); StringItem button1 = new StringItem(null, "button1", - StringItem.BUTTON); + StringItem.BUTTON); Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); button1.addCommand(dummyCommand); @@ -207,9 +217,10 @@ /** * Test that command are working properly in case of */ - public void testRemoveItemsWhenBackground() { - Form forma = new Form ("Form A"); - Form formb = new Form ("Form B"); + public void testRemoveItemsWhenBackground() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); Command dummyCommand1 = new Command("dummy1", "", Command.ITEM, 0); Command dummyCommand2 = new Command("dummy2", "", Command.ITEM, 0); Command dummyCommand3 = new Command("dummy3", "", Command.ITEM, 0); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/gauge/GaugeCommandsTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/gauge/GaugeCommandsTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/gauge/GaugeCommandsTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.gauge; @@ -32,7 +32,8 @@ *
            * Created: 2008-09-15 */ -public class GaugeCommandsTest extends ItemUITestBase { +public class GaugeCommandsTest extends ItemUITestBase +{ private static final int GAUGE_MAX_VALUE = 10; private static final int GAUGE_MAX_VALUE_2 = 5; @@ -41,7 +42,8 @@ /** * Constructor. */ - public GaugeCommandsTest() { + public GaugeCommandsTest() + { } /** @@ -50,27 +52,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public GaugeCommandsTest(String sTestName) { + public GaugeCommandsTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = GaugeCommandsTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new GaugeCommandsTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = GaugeCommandsTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new GaugeCommandsTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testShowTimedAlert"); methodNames.addElement("testCustomListener"); @@ -80,46 +86,49 @@ methodNames.addElement("testImageAndTextCombinations"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommands")) testCommands(); + + public void runTest() throws Throwable + { + if(getName().equals("testCommands")) testCommands(); // TODO: currently failing because ProgressBar is not focusable. // It is not clear should it be focusable in future? - else if (getName().equals("testNoninteractiveCommands")) testNoninteractiveCommands(); - else if (getName().equals("testValueChange")) testValueChange(); - else if (getName().equals("testItemState")) testItemState(); + else if(getName().equals("testNoninteractiveCommands")) testNoninteractiveCommands(); + else if(getName().equals("testValueChange")) testValueChange(); + else if(getName().equals("testItemState")) testItemState(); else super.runTest(); - } - + } + /** - * Tests the basic functionality of command added to Gauge. - */ - public void testCommands() { - Gauge gauge = new Gauge("interactive, max=10, initial=0", true, - GAUGE_MAX_VALUE, 0); - - Command ok = new Command("Ok", "", Command.ITEM, 0); - gauge.addCommand(ok); - gauge.setItemCommandListener(this); + * Tests the basic functionality of command added to Gauge. + */ + public void testCommands() + { + Gauge gauge = new Gauge("interactive, max=10, initial=0", true, + GAUGE_MAX_VALUE, 0); - form.append(gauge); + Command ok = new Command("Ok", "", Command.ITEM, 0); + gauge.addCommand(ok); + gauge.setItemCommandListener(this); - Display.getDisplay(getMIDlet()).setCurrent(form); - block(CHANGE_DISPLAYABLE_DELAY); + form.append(gauge); - // Click command and verify it works: - key(Key.CBA1); - assertItemCmdListener("", ok, gauge); - } + Display.getDisplay(getMIDlet()).setCurrent(form); + block(CHANGE_DISPLAYABLE_DELAY); + + // Click command and verify it works: + key(Key.CBA1); + assertItemCmdListener("", ok, gauge); + } /** - * It should be possible to add commands to non-interactive gauges too and - * in that case gauges should be selectable. - */ - public void testNoninteractiveCommands() { + * It should be possible to add commands to non-interactive gauges too and + * in that case gauges should be selectable. + */ + public void testNoninteractiveCommands() + { Gauge gauge = new Gauge("non-interactive, max=10, initial=0", - false, GAUGE_MAX_VALUE, 0); + false, GAUGE_MAX_VALUE, 0); Command ok = new Command("Ok", "", Command.ITEM, 0); StringItem button1 = new StringItem("", "click!", Item.BUTTON); button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); @@ -134,7 +143,7 @@ // Click LSK and verify it activates command: key(Key.CBA1); - assertItemCmdListener("case1", ok, gauge); + assertItemCmdListener("case1", ok, gauge); // Add button, change focus to it and make sure it is possible // to move focus back to gauge: @@ -148,64 +157,66 @@ } /** - * Tests Gauge's value changing. - */ - public void testValueChange() { - Gauge gauge = new Gauge("interactive, max=10, initial=0", true, - GAUGE_MAX_VALUE, 0); - StringItem button1 = new StringItem("", "click!", Item.BUTTON); - button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); + * Tests Gauge's value changing. + */ + public void testValueChange() + { + Gauge gauge = new Gauge("interactive, max=10, initial=0", true, + GAUGE_MAX_VALUE, 0); + StringItem button1 = new StringItem("", "click!", Item.BUTTON); + button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); - form.append(gauge); + form.append(gauge); - // Add dummy button after gauge. This makes sure that the focus - // is not moving when pressing right-arrow when gauge is selected. - form.append(button1); + // Add dummy button after gauge. This makes sure that the focus + // is not moving when pressing right-arrow when gauge is selected. + form.append(button1); - setCurrent(form); + setCurrent(form); - // Change gauge value: - key(Key.RightArrow); - assertEquals("Wrong gauge value (case 1).", 1, gauge.getValue()); + // Change gauge value: + key(Key.RightArrow); + assertEquals("Wrong gauge value (case 1).", 1, gauge.getValue()); - // Change gauge value back to original: - key(Key.LeftArrow); - assertEquals("Wrong gauge value (case 2).", 0, gauge.getValue()); + // Change gauge value back to original: + key(Key.LeftArrow); + assertEquals("Wrong gauge value (case 2).", 0, gauge.getValue()); - // Change value dynamically: - gauge.setValue(GAUGE_MAX_VALUE); + // Change value dynamically: + gauge.setValue(GAUGE_MAX_VALUE); - // Change maximum value to be lower than current value: - gauge.setMaxValue(GAUGE_MAX_VALUE_2); + // Change maximum value to be lower than current value: + gauge.setMaxValue(GAUGE_MAX_VALUE_2); - // Make sure the current value is changed to maximum: - assertEquals("Current value not changed to maximum.", - GAUGE_MAX_VALUE_2, gauge.getValue()); + // Make sure the current value is changed to maximum: + assertEquals("Current value not changed to maximum.", + GAUGE_MAX_VALUE_2, gauge.getValue()); - // Set value to minimum and then move value by using keypresses. - // That makes sure the visual appearance of gauge is changed dynamically - // when value is changed programmatically: - gauge.setValue(0); - key(Key.RightArrow); - key(Key.RightArrow); + // Set value to minimum and then move value by using keypresses. + // That makes sure the visual appearance of gauge is changed dynamically + // when value is changed programmatically: + gauge.setValue(0); + key(Key.RightArrow); + key(Key.RightArrow); - assertEquals("Value not expected after setValue()-call.", - GAUGE_TEST_VALUE, gauge.getValue()); + assertEquals("Value not expected after setValue()-call.", + GAUGE_TEST_VALUE, gauge.getValue()); - // Remove gauge from form and try to set value again: - form.deleteAll(); - gauge.setValue(GAUGE_TEST_VALUE); - assertEquals("Value not expected after gauge removed from form.", - GAUGE_TEST_VALUE, gauge.getValue()); - } + // Remove gauge from form and try to set value again: + form.deleteAll(); + gauge.setValue(GAUGE_TEST_VALUE); + assertEquals("Value not expected after gauge removed from form.", + GAUGE_TEST_VALUE, gauge.getValue()); + } /** - * Tests that Form receives ItemStateChanged-events when gauge's value is - * changed. - */ - public void testItemState() { + * Tests that Form receives ItemStateChanged-events when gauge's value is + * changed. + */ + public void testItemState() + { Gauge gauge = new Gauge("interactive, max=10, initial=0", - true, GAUGE_MAX_VALUE, 0); + true, GAUGE_MAX_VALUE, 0); form.append(gauge); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/imageitem/ImageItemHyperLinkTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/imageitem/ImageItemHyperLinkTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/imageitem/ImageItemHyperLinkTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.imageitem; @@ -34,7 +34,8 @@ *
            * Created: 2008-10-20 */ -public class ImageItemHyperLinkTest extends ItemUITestBase { +public class ImageItemHyperLinkTest extends ItemUITestBase +{ private Image smallImage; private Image mediumImage; @@ -43,7 +44,8 @@ /** * Constructor. */ - public ImageItemHyperLinkTest() { + public ImageItemHyperLinkTest() + { } /** @@ -52,27 +54,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ImageItemHyperLinkTest(String sTestName) { + public ImageItemHyperLinkTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ImageItemHyperLinkTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ImageItemHyperLinkTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ImageItemHyperLinkTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ImageItemHyperLinkTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCommands"); methodNames.addElement("testAppearanceModeChangePlain"); @@ -84,16 +90,17 @@ methodNames.addElement("testLongImageHyperlink"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommands")) testCommands(); - else if (getName().equals("testAppearanceModeChangePlain")) testAppearanceModeChange(ImageItem.PLAIN); - else if (getName().equals("testAppearanceModeChangeButton")) testAppearanceModeChange(ImageItem.BUTTON); - else if (getName().equals("testAppearanceModeChangeHyperlink")) testAppearanceModeChange(ImageItem.HYPERLINK); - else if (getName().equals("testFocusInAppearanceModeChangePlain")) testFocusInAppearanceModeChange(ImageItem.PLAIN); - else if (getName().equals("testFocusInAppearanceModeChangeButton")) testFocusInAppearanceModeChange(ImageItem.BUTTON); - else if (getName().equals("testFocusInAppearanceModeChangeHyperlink")) testFocusInAppearanceModeChange(ImageItem.HYPERLINK); - else if (getName().equals("testLongImageHyperlink")) testLongImageHyperlink(); + + public void runTest() throws Throwable + { + if(getName().equals("testCommands")) testCommands(); + else if(getName().equals("testAppearanceModeChangePlain")) testAppearanceModeChange(ImageItem.PLAIN); + else if(getName().equals("testAppearanceModeChangeButton")) testAppearanceModeChange(ImageItem.BUTTON); + else if(getName().equals("testAppearanceModeChangeHyperlink")) testAppearanceModeChange(ImageItem.HYPERLINK); + else if(getName().equals("testFocusInAppearanceModeChangePlain")) testFocusInAppearanceModeChange(ImageItem.PLAIN); + else if(getName().equals("testFocusInAppearanceModeChangeButton")) testFocusInAppearanceModeChange(ImageItem.BUTTON); + else if(getName().equals("testFocusInAppearanceModeChangeHyperlink")) testFocusInAppearanceModeChange(ImageItem.HYPERLINK); + else if(getName().equals("testLongImageHyperlink")) testLongImageHyperlink(); else super.runTest(); } @@ -101,24 +108,31 @@ /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - super.setUp(); - try { + protected void setUp() throws Exception + { + super.setUp(); + try + { smallImage = Image.createImage("32x32.jpeg"); } - catch (IOException e) { + catch(IOException e) + { // } - try { + try + { mediumImage = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { // } - try { + try + { longImage = Image.createImage("100x300.png"); } - catch (IOException e) { + catch(IOException e) + { // } } @@ -127,9 +141,10 @@ /** * Tests the basic functionality of command added to Hyperlink. */ - public void testCommands() { + public void testCommands() + { ImageItem hyperlink = new ImageItem("label", smallImage, 0, "small", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); testCommand(hyperlink); @@ -138,14 +153,14 @@ form.deleteAll(); Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); ImageItem button1 = new ImageItem(null, smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem(null, smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); button1.addCommand(dummyCommand); button2.addCommand(dummyCommand); ImageItem hyperlink3 = new ImageItem(null, mediumImage, 0, "medium", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); hyperlink3.addCommand(ok); hyperlink3.setItemCommandListener(this); @@ -171,20 +186,22 @@ * * @param mode Appearancemode of ImageItem. */ - public void testAppearanceModeChange(int mode) { - switch (mode) { - case ImageItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case ImageItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case ImageItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; + public void testAppearanceModeChange(int mode) + { + switch(mode) + { + case ImageItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case ImageItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case ImageItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; } ImageItem imageItem = new ImageItem("label", smallImage, 0, "url", mode); @@ -208,39 +225,41 @@ imageItem.addCommand(ok); block(CHANGE_DISPLAYABLE_DELAY); - key(Key.CBA1); + key(Key.CBA1); assertItemCmdListener("Added command", ok, imageItem); } /** - * Tests that focus transfer works when commands are added/removed - * dynamically. - * - * @param mode - * Appearancemode of ImageItem. - */ - public void testFocusInAppearanceModeChange(int mode) { - switch (mode) { - case ImageItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case ImageItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case ImageItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; + * Tests that focus transfer works when commands are added/removed + * dynamically. + * + * @param mode + * Appearancemode of ImageItem. + */ + public void testFocusInAppearanceModeChange(int mode) + { + switch(mode) + { + case ImageItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case ImageItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case ImageItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; } ImageItem imageItem = new ImageItem(null, smallImage, 0, "url", mode); ImageItem button1 = new ImageItem(null, mediumImage, 0, "button1", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem(null, smallImage, 0, "button2", - ImageItem.BUTTON); + ImageItem.BUTTON); Command ok = new Command("Ok", "", Command.ITEM, 0); Command buttonCommand1 = new Command("bc1", "", Command.ITEM, 0); @@ -309,16 +328,17 @@ * test that ImageItem of HYPERLINK type working ok with when image is * bigger then screensize. */ - public void testLongImageHyperlink() { + public void testLongImageHyperlink() + { ImageItem imageItem = new ImageItem(null, smallImage, 0, "button", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem hyperlink1 = new ImageItem(null, longImage, 0, "hyperlink", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); hyperlink1.setLayout(Item.LAYOUT_RIGHT); ImageItem hyperlink2 = new ImageItem(null, smallImage, 0, "button2", - ImageItem.BUTTON); + ImageItem.BUTTON); hyperlink2.setLayout(Item.LAYOUT_CENTER); Form forma = new Form("Form A"); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/item/ItemUITest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/item/ItemUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/item/ItemUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.item; @@ -32,7 +32,8 @@ *
            * Created: 2008-12-05 */ -public class ItemUITest extends ItemUITestBase { +public class ItemUITest extends ItemUITestBase +{ private static final int BIG_PREFERRED_HEIGHT = 500; private static final int BIG_PREFERRED_WIDTH = 2500; @@ -51,7 +52,8 @@ /** * Constructor. */ - public ItemUITest() { + public ItemUITest() + { } /** @@ -60,27 +62,31 @@ * @param testName Test name. * @param testMethod Test method. */ - public ItemUITest(String testName) { + public ItemUITest(String testName) + { super(testName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ItemUITest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ItemUITest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ItemUITest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ItemUITest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testPreferredSizesDateFieldTime"); methodNames.addElement("testPreferredSizesDateFieldDate"); @@ -95,88 +101,101 @@ methodNames.addElement("testPreferredSizesPlainLongText"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testPreferredSizesDateFieldTime")) { - testPreferredSizes(new DateField(null, DateField.TIME), true); + + public void runTest() throws Throwable + { + if(getName().equals("testPreferredSizesDateFieldTime")) + { + testPreferredSizes(new DateField(null, DateField.TIME), true); } - else if (getName().equals("testPreferredSizesDateFieldDate")) { - testPreferredSizes(new DateField(null, DateField.DATE), true); + else if(getName().equals("testPreferredSizesDateFieldDate")) + { + testPreferredSizes(new DateField(null, DateField.DATE), true); } - else if (getName().equals("testPreferredSizesDateFieldDateTime")) { - testPreferredSizes(new DateField(null, DateField.DATE_TIME), true); + else if(getName().equals("testPreferredSizesDateFieldDateTime")) + { + testPreferredSizes(new DateField(null, DateField.DATE_TIME), true); } - else if (getName().equals("testPreferredSizesNonInteractiveGauge")) { - testPreferredSizes( - new Gauge(null, false, - GAUGE_MAX_VALUE, - GAUGE_INITIAL_VALUE), false); + else if(getName().equals("testPreferredSizesNonInteractiveGauge")) + { + testPreferredSizes( + new Gauge(null, false, + GAUGE_MAX_VALUE, + GAUGE_INITIAL_VALUE), false); } - else if (getName().equals("testPreferredSizesInteractiveGauge")) { - testPreferredSizes( - new Gauge(null, true, - GAUGE_MAX_VALUE, - GAUGE_INITIAL_VALUE), true); + else if(getName().equals("testPreferredSizesInteractiveGauge")) + { + testPreferredSizes( + new Gauge(null, true, + GAUGE_MAX_VALUE, + GAUGE_INITIAL_VALUE), true); } - else if (getName().equals("testPreferredSizesShortText")) { - testPreferredSizes( - new StringItem(null, "short text", - Item.BUTTON), true); + else if(getName().equals("testPreferredSizesShortText")) + { + testPreferredSizes( + new StringItem(null, "short text", + Item.BUTTON), true); } - else if (getName().equals("testPreferredSizesLongText")) { - testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.BUTTON), true); + else if(getName().equals("testPreferredSizesLongText")) + { + testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.BUTTON), true); } - else if (getName().equals("testPreferredSizesHyperLinkShortText")) { - testPreferredSizes( - new StringItem(null, "short text", - Item.HYPERLINK), true); + else if(getName().equals("testPreferredSizesHyperLinkShortText")) + { + testPreferredSizes( + new StringItem(null, "short text", + Item.HYPERLINK), true); } - else if (getName().equals("testPreferredSizesHyperLinkLongText")) { - testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.HYPERLINK), true); + else if(getName().equals("testPreferredSizesHyperLinkLongText")) + { + testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.HYPERLINK), true); } - else if (getName().equals("testPreferredSizesPlainShortText")) { - testPreferredSizes( - new StringItem(null, "short text", - Item.PLAIN), false); + else if(getName().equals("testPreferredSizesPlainShortText")) + { + testPreferredSizes( + new StringItem(null, "short text", + Item.PLAIN), false); } - else if (getName().equals("testPreferredSizesPlainLongText")) { - testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.PLAIN), false); + else if(getName().equals("testPreferredSizesPlainLongText")) + { + testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.PLAIN), false); } else super.runTest(); - } - + } + /** - * Tests preferred size of specified item. This method only makes sure that - * setting and getting preferred size won't crash the application and the - * values returned are somewhat meaningful, for example not negative. It - * also makes sure the focus stays in item when preferred size is changed. - * - * @param item - * Item to be tested. It doesn't matter does item has label or - * not. Method will test preferred size with and without label - * automatically. - * @param testCommands - * If true, method will make sure the focus is not changed when - * preferred size is changed and commands works all the time. - * This must be false if item cant have commands. - */ - public void testPreferredSizes(Item item, boolean testCommands) { + * Tests preferred size of specified item. This method only makes sure that + * setting and getting preferred size won't crash the application and the + * values returned are somewhat meaningful, for example not negative. It + * also makes sure the focus stays in item when preferred size is changed. + * + * @param item + * Item to be tested. It doesn't matter does item has label or + * not. Method will test preferred size with and without label + * automatically. + * @param testCommands + * If true, method will make sure the focus is not changed when + * preferred size is changed and commands works all the time. + * This must be false if item cant have commands. + */ + public void testPreferredSizes(Item item, boolean testCommands) + { int w; int h; @@ -185,7 +204,8 @@ Command ok1 = new Command("Ok1", "", Command.ITEM, 0); Command ok2 = new Command("Ok2", "", Command.ITEM, 0); - if (testCommands) { + if(testCommands) + { button1.addCommand(ok1); button2.addCommand(ok2); @@ -193,7 +213,8 @@ button2.setItemCommandListener(this); // Add commands to item only in first round: - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { item.addCommand(itemCommand); item.setItemCommandListener(this); } @@ -202,26 +223,27 @@ // Unlock preferred size: item.setPreferredSize(-1, -1); - switch (state) { - case STATE_NO_EXTRA_ITEMS: - form.append(item); - break; - case STATE_ITEM_BEFORE: - form.append(button1); - form.append(item); - break; - case STATE_ITEM_AFTER: - form.append(item); - form.append(button1); - break; - case STATE_ITEM_BEFORE_AND_AFTER: - form.append(button1); - form.append(item); - form.append(button2); - break; - default: - fail("invalid state, bug in test."); - break; + switch(state) + { + case STATE_NO_EXTRA_ITEMS: + form.append(item); + break; + case STATE_ITEM_BEFORE: + form.append(button1); + form.append(item); + break; + case STATE_ITEM_AFTER: + form.append(item); + form.append(button1); + break; + case STATE_ITEM_BEFORE_AND_AFTER: + form.append(button1); + form.append(item); + form.append(button2); + break; + default: + fail("invalid state, bug in test."); + break; } display.setCurrentItem(item); @@ -232,16 +254,17 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label was: w=" - + w + ", h=" + h); + + w + ", h=" + h); } this.assertTrue("Width not greater than zero" - + " (without label), state: " + state, w > 0); + + " (without label), state: " + state, w > 0); this.assertTrue("Height not greater than zero" - + " (without label), state: " + state, h > 0); + + " (without label), state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); //Test Item with label: item.setLabel("label"); @@ -249,16 +272,17 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label was: w=" - + w + ", h=" + h); + + w + ", h=" + h); } this.assertTrue("Width not greater than zero" - + " (with label), state: " + state, w > 0); + + " (with label), state: " + state, w > 0); this.assertTrue("Height not greater than zero" - + " (with label), state: " + state, h > 0); + + " (with label), state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); // Set preferred width larger than screen width and make // sure the width is not larger than screen width: @@ -267,39 +291,42 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label after setting" - + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" - + w + ", h=" + h); + + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero," - + " state: " + state, h > 0); + + " state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); item.setLabel(null); block(CHANGE_DISPLAYABLE_DELAY); w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label after setting" - + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" - + w + ", h=" + h); + + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero (no label)," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero (no label)," - + " state: " + state, h > 0); + + " state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width (no label)," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); //Test command, that verifies the focus is not changed: - if (testCommands) { + if(testCommands) + { key(Key.CBA1); assertItemCmdListener("", itemCommand, item); } @@ -314,44 +341,49 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label after setting" - + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" - + w + ", h=" + h); + + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero," - + " state: " + state, h > 0); + + " state: " + state, h > 0); item.setLabel(null); block(CHANGE_DISPLAYABLE_DELAY); w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label after setting" - + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" - + w + ", h=" + h); + + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero (no label)," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero (no label)," - + " state: " + state, h > 0); + + " state: " + state, h > 0); //Test command, that verifies the focus is not changed: - if (testCommands) { + if(testCommands) + { key(Key.CBA1); assertItemCmdListener("", itemCommand, item); } form.deleteAll(); - if (state < STATE_ITEM_BEFORE_AND_AFTER) { + if(state < STATE_ITEM_BEFORE_AND_AFTER) + { state++; testPreferredSizes(item, testCommands); } - else { + else + { state = 0; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/list/ListUITest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/list/ListUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/list/ListUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.list; @@ -32,7 +32,8 @@ *
            * @created 7.8.2008 */ -public class ListUITest extends UITestBase { +public class ListUITest extends UITestBase +{ private static final int SETCURRENT_TIMEOUT = 6000; private static final int WAIT_CYCLE_TIME = 50; @@ -45,7 +46,8 @@ /** * Constructor. */ - public ListUITest() { + public ListUITest() + { } /** @@ -54,34 +56,39 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public ListUITest(String sTestName) { + public ListUITest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = ListUITest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new ListUITest((String)e.nextElement())); - } - + // Add widget tests + methodNames = ListUITest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new ListUITest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testDefaultSelectCmd"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testDefaultSelectCmd")) testDefaultSelectCmd(); + + public void runTest() throws Throwable + { + if(getName().equals("testDefaultSelectCmd")) testDefaultSelectCmd(); else super.runTest(); } @@ -89,7 +96,8 @@ /** * Test method. */ - public void testDefaultSelectCmd() { + public void testDefaultSelectCmd() + { List list = new List("Implicit List", Choice.IMPLICIT); list.setCommandListener(this); assertSetCurrent(list); @@ -123,7 +131,8 @@ * @param aCommand Command. * @param aDisplayable Displayable. */ - public void commandAction(Command aCommand, Displayable aDisplayable) { + public void commandAction(Command aCommand, Displayable aDisplayable) + { lastCommand = aCommand; lastDisplayable = aDisplayable; doNotify(); @@ -134,11 +143,13 @@ * * @param disp a displayable */ - protected void assertSetCurrent(Displayable disp) { + protected void assertSetCurrent(Displayable disp) + { display.setCurrent(disp); Displayable curr = null; int waitSum = 0; - while (curr != disp && waitSum <= SETCURRENT_TIMEOUT) { + while(curr != disp && waitSum <= SETCURRENT_TIMEOUT) + { block(CHANGE_DISPLAYABLE_DELAY); waitSum += CHANGE_DISPLAYABLE_DELAY; curr = display.getCurrent(); @@ -152,12 +163,13 @@ * @param expCmd expected Command * @param expDisp expected Displayable */ - protected void assertCommandListener(Command expCmd, Displayable expDisp) { + protected void assertCommandListener(Command expCmd, Displayable expDisp) + { assertTrue("Command listener wasn't called with " + expCmd.getLabel(), - syncFlag); + syncFlag); assertEquals("Last displayable mismatch", expDisp, lastDisplayable); assertEquals("Last command should be " + expCmd.getLabel(), expCmd, - lastCommand); + lastCommand); } /** @@ -166,11 +178,13 @@ * @param timeout timeout * @return true if the doNotify was called during this, else otherwise */ - protected boolean doWait(int timeout) { + protected boolean doWait(int timeout) + { clearCallbackValues(); int waitSum = 0; // wait here until syncFlag gets true or timeout expires - while (!syncFlag && waitSum <= timeout) { + while(!syncFlag && waitSum <= timeout) + { block(WAIT_CYCLE_TIME); waitSum += WAIT_CYCLE_TIME; } @@ -180,14 +194,16 @@ /** * Notify the doWait method. */ - protected void doNotify() { + protected void doNotify() + { syncFlag = true; } /** * Clear command listener values. */ - protected void clearCallbackValues() { + protected void clearCallbackValues() + { syncFlag = false; lastCommand = null; lastDisplayable = null; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/spacer/SpacerTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/spacer/SpacerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/spacer/SpacerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.spacer; @@ -34,7 +34,8 @@ *
            * Created: 2008-10-20 */ -public class SpacerTest extends ItemUITestBase { +public class SpacerTest extends ItemUITestBase +{ private Command latestCommand; private Item latestItem; @@ -43,7 +44,8 @@ /** * Constructor. */ - public SpacerTest() { + public SpacerTest() + { } /** @@ -52,46 +54,54 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SpacerTest(String sTestName) { + public SpacerTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = SpacerTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new SpacerTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = SpacerTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new SpacerTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testSizeChange"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testSizeChange")) testSizeChange(); + + public void runTest() throws Throwable + { + if(getName().equals("testSizeChange")) testSizeChange(); else super.runTest(); } - + /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - try { + try + { smallImage = Image.createImage("32x32.jpeg"); } - catch (IOException e) { + catch(IOException e) + { // } } @@ -100,11 +110,12 @@ /** * Tests the basic functionality of command added to Hyperlink. */ - public void testSizeChange() { + public void testSizeChange() + { ImageItem button = new ImageItem("label", smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem("label", smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); Spacer spacer = new Spacer(0, 0); Command ok = new Command("Ok", "", Command.ITEM, 0); @@ -124,18 +135,18 @@ // Click command and verify it works: key(Key.CBA1); assertEquals("Command not activated or not correct command.(case 1)", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method.(case 1)", - button, latestItem); + button, latestItem); latestCommand = null; latestItem = null; // Check that after arrowDown focus didn't change. key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command.(case 2)", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method.(case 2)", - button, latestItem); + button, latestItem); latestCommand = null; latestItem = null; // change spacers's size to form width and again press arrow down. @@ -145,9 +156,9 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct " - + "command when using MSK.(case 3)", ok2, latestCommand); + + "command when using MSK.(case 3)", ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when using MSK.(case 3)", button2, latestItem); + + " when using MSK.(case 3)", button2, latestItem); } /** @@ -156,7 +167,8 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/HyperLinkTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/HyperLinkTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/HyperLinkTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.stringitem; @@ -32,12 +32,14 @@ *
            * Created: 2008-10-20 */ -public class HyperLinkTest extends ItemUITestBase { +public class HyperLinkTest extends ItemUITestBase +{ /** * Constructor. */ - public HyperLinkTest() { + public HyperLinkTest() + { } /** @@ -46,27 +48,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public HyperLinkTest(String sTestName) { + public HyperLinkTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = HyperLinkTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new HyperLinkTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = HyperLinkTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new HyperLinkTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCommands"); methodNames.addElement("testAppearanceModeChangePlain"); @@ -79,293 +85,312 @@ methodNames.addElement("testLongHyperlinkWithMSK"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommands")) testCommands(); - else if (getName().equals("testAppearanceModeChangePlain")) { - testAppearanceModeChange(StringItem.PLAIN); + + public void runTest() throws Throwable + { + if(getName().equals("testCommands")) testCommands(); + else if(getName().equals("testAppearanceModeChangePlain")) + { + testAppearanceModeChange(StringItem.PLAIN); } - else if (getName().equals("testAppearanceModeChangeButton")) { - testAppearanceModeChange(StringItem.BUTTON); + else if(getName().equals("testAppearanceModeChangeButton")) + { + testAppearanceModeChange(StringItem.BUTTON); } - else if (getName().equals("testAppearanceModeChangeHyperlink")) { - testAppearanceModeChange(StringItem.HYPERLINK); + else if(getName().equals("testAppearanceModeChangeHyperlink")) + { + testAppearanceModeChange(StringItem.HYPERLINK); } - else if (getName().equals("testFocusInAppearanceModeChangePlain")) { - testFocusInAppearanceModeChange(StringItem.PLAIN); + else if(getName().equals("testFocusInAppearanceModeChangePlain")) + { + testFocusInAppearanceModeChange(StringItem.PLAIN); } - else if (getName().equals("testFocusInAppearanceModeChangeButton")) { - testFocusInAppearanceModeChange(StringItem.BUTTON); + else if(getName().equals("testFocusInAppearanceModeChangeButton")) + { + testFocusInAppearanceModeChange(StringItem.BUTTON); } - else if (getName().equals("testFocusInAppearanceModeChangeHyperlink")) { - testFocusInAppearanceModeChange(StringItem.HYPERLINK); + else if(getName().equals("testFocusInAppearanceModeChangeHyperlink")) + { + testFocusInAppearanceModeChange(StringItem.HYPERLINK); } - else if (getName().equals("testLongHyperlinkWithLSK")) { - testLongHyperlink(Key.CBA1); + else if(getName().equals("testLongHyperlinkWithLSK")) + { + testLongHyperlink(Key.CBA1); } - else if (getName().equals("testLongHyperlinkWithMSK")) { - testLongHyperlink(Key.Select); + else if(getName().equals("testLongHyperlinkWithMSK")) + { + testLongHyperlink(Key.Select); } else super.runTest(); - } - + } + + + /** + * Tests the basic functionality of command added to Hyperlink. + */ + public void testCommands() + { + StringItem hyperlink = new StringItem("label", "url", + StringItem.HYPERLINK); + + testCommand(hyperlink); + + // Because focus transfer in case of hyperlink is different than + // in normal cases it is good to test that commands works when + // moving focus from previous item to hyperlink as well as when + // moving focus from next item: + form.deleteAll(); + StringItem button1 = new StringItem(null, "button1", StringItem.BUTTON); + StringItem button2 = new StringItem(null, "button2", StringItem.BUTTON); + Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); + button1.addCommand(dummyCommand); + button2.addCommand(dummyCommand); + button1.setItemCommandListener(this); + button2.setItemCommandListener(this); + + // Some typical url-characters are replaced with 'x'-chars to avoid + // some problems in eSWT/AVKON implementation. Those problems should + // go away when using QT-based eSWT. + + Command ok = new Command("Ok", "", Command.ITEM, 0); + + StringItem hyperlink3 = new StringItem(null, + "xxxx://this.link.should.be.wrapped.to.many" + + ".lines.info/index.php?wrapped=truexi=hope", + StringItem.HYPERLINK); + hyperlink3.addCommand(ok); + hyperlink3.setItemCommandListener(this); + + form.append(button1); + form.append(hyperlink3); + form.append(button2); + + block(CHANGE_DISPLAYABLE_DELAY); + + key(Key.RightArrow); + key(Key.CBA1); + assertItemCmdListener("hyperlink focus transfer test, case 1", ok, + hyperlink3); + + key(Key.RightArrow); + key(Key.LeftArrow); + key(Key.CBA1); + assertItemCmdListener("hyperlink focus transfer test, case 2", ok, + hyperlink3); + } + + /** + * Tests that commands are working as expected when commands + * are added or removed dynamically. + * + * @param mode Appearancemode of StringItem. + */ + public void testAppearanceModeChange(int mode) + { + switch(mode) + { + case StringItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case StringItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case StringItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; + } + + StringItem stringItem = new StringItem("label", "url", mode); + Command ok = new Command("Ok", "", Command.ITEM, 0); + + form.append(stringItem); + stringItem.addCommand(ok); + stringItem.setItemCommandListener(this); + + setCurrent(form); + + // Remove command and make sure the command is not working anymore: + stringItem.removeCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); + + key(Key.CBA1); + assertItemCmdListener("cmd activated after removing", null, null); + + // Add command again and verify it works: + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); + + key(Key.CBA1); + assertItemCmdListener("", ok, stringItem); + } /** - * Tests the basic functionality of command added to Hyperlink. - */ - public void testCommands() { - StringItem hyperlink = new StringItem("label", "url", - StringItem.HYPERLINK); - - testCommand(hyperlink); - - // Because focus transfer in case of hyperlink is different than - // in normal cases it is good to test that commands works when - // moving focus from previous item to hyperlink as well as when - // moving focus from next item: - form.deleteAll(); - StringItem button1 = new StringItem(null, "button1", StringItem.BUTTON); - StringItem button2 = new StringItem(null, "button2", StringItem.BUTTON); - Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); - button1.addCommand(dummyCommand); - button2.addCommand(dummyCommand); - button1.setItemCommandListener(this); - button2.setItemCommandListener(this); - - // Some typical url-characters are replaced with 'x'-chars to avoid - // some problems in eSWT/AVKON implementation. Those problems should - // go away when using QT-based eSWT. + * Tests that focus transfer works when commands are added/removed + * dynamically. + * + * @param mode Appearancemode of StringItem. + */ + public void testFocusInAppearanceModeChange(int mode) + { + switch(mode) + { + case StringItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case StringItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case StringItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; + } - Command ok = new Command("Ok", "", Command.ITEM, 0); + StringItem stringItem = new StringItem(null, "url", mode); - StringItem hyperlink3 = new StringItem(null, - "xxxx://this.link.should.be.wrapped.to.many" - + ".lines.info/index.php?wrapped=truexi=hope", - StringItem.HYPERLINK); - hyperlink3.addCommand(ok); - hyperlink3.setItemCommandListener(this); - - form.append(button1); - form.append(hyperlink3); - form.append(button2); + StringItem button1 = new StringItem(null, "button1", Item.BUTTON); + StringItem button2 = new StringItem(null, "button2", Item.BUTTON); - block(CHANGE_DISPLAYABLE_DELAY); - - key(Key.RightArrow); - key(Key.CBA1); - assertItemCmdListener("hyperlink focus transfer test, case 1", ok, - hyperlink3); + Command ok = new Command("giamcc1", "", Command.ITEM, 0); + Command buttonCommand1 = new Command("giamcc12", "", Command.ITEM, 0); + Command buttonCommand2 = new Command("giamcc13", "", Command.ITEM, 0); - key(Key.RightArrow); - key(Key.LeftArrow); - key(Key.CBA1); - assertItemCmdListener("hyperlink focus transfer test, case 2", ok, - hyperlink3); - } + form.append(button1); + form.append(stringItem); + form.append(button2); - /** - * Tests that commands are working as expected when commands - * are added or removed dynamically. - * - * @param mode Appearancemode of StringItem. - */ - public void testAppearanceModeChange(int mode) { - switch (mode) { - case StringItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case StringItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case StringItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; - } + // Set listener but do not add commands yet: + stringItem.setItemCommandListener(this); + button1.addCommand(buttonCommand1); + button2.addCommand(buttonCommand2); + button1.setItemCommandListener(this); + button2.setItemCommandListener(this); + + setCurrent(form); - StringItem stringItem = new StringItem("label", "url", mode); - Command ok = new Command("Ok", "", Command.ITEM, 0); + // At this point there are two buttons and plain stringItem + // in middle of them. Focus is in first button. + // Move to second button, add command to StringItem, move + // to StringItem and verify command works: + key(Key.RightArrow); - form.append(stringItem); - stringItem.addCommand(ok); - stringItem.setItemCommandListener(this); + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - setCurrent(form); + key(Key.LeftArrow); - // Remove command and make sure the command is not working anymore: - stringItem.removeCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + assertItemCmdListener("case1", ok, stringItem); - key(Key.CBA1); - assertItemCmdListener("cmd activated after removing", null, null); + // Now remove command from StringItem. Test assumes that in this + // case focus is moved to next item which is the second button. + // Verify that happens and also make sure it is possible to move + // to first button also: + stringItem.removeCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - // Add command again and verify it works: - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); - - key(Key.CBA1); - assertItemCmdListener("", ok, stringItem); - } + key(Key.CBA1); + assertItemCmdListener("case2", buttonCommand2, button2); - /** - * Tests that focus transfer works when commands are added/removed - * dynamically. - * - * @param mode Appearancemode of StringItem. - */ - public void testFocusInAppearanceModeChange(int mode) { - switch (mode) { - case StringItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case StringItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case StringItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; - } + key(Key.LeftArrow); + + key(Key.CBA1); + assertItemCmdListener("case3", buttonCommand1, button1); - StringItem stringItem = new StringItem(null, "url", mode); + // Now add command back to StringItem again and make sure it + // works: + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - StringItem button1 = new StringItem(null, "button1", Item.BUTTON); - StringItem button2 = new StringItem(null, "button2", Item.BUTTON); + key(Key.RightArrow); - Command ok = new Command("giamcc1", "", Command.ITEM, 0); - Command buttonCommand1 = new Command("giamcc12", "", Command.ITEM, 0); - Command buttonCommand2 = new Command("giamcc13", "", Command.ITEM, 0); - - form.append(button1); - form.append(stringItem); - form.append(button2); - - // Set listener but do not add commands yet: - stringItem.setItemCommandListener(this); - button1.addCommand(buttonCommand1); - button2.addCommand(buttonCommand2); - button1.setItemCommandListener(this); - button2.setItemCommandListener(this); + key(Key.CBA1); + assertItemCmdListener("case4", ok, stringItem); - setCurrent(form); + // And verify also the functionality of second button after + // these changes: + key(Key.RightArrow); - // At this point there are two buttons and plain stringItem - // in middle of them. Focus is in first button. - // Move to second button, add command to StringItem, move - // to StringItem and verify command works: - key(Key.RightArrow); - - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); - - key(Key.LeftArrow); - - assertItemCmdListener("case1", ok, stringItem); + key(Key.CBA1); + assertItemCmdListener("case5", buttonCommand2, button2); + } - // Now remove command from StringItem. Test assumes that in this - // case focus is moved to next item which is the second button. - // Verify that happens and also make sure it is possible to move - // to first button also: - stringItem.removeCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); - - key(Key.CBA1); - assertItemCmdListener("case2", buttonCommand2, button2); - - key(Key.LeftArrow); - - key(Key.CBA1); - assertItemCmdListener("case3", buttonCommand1, button1); + /** + * Tests that Hyperlink works as expected when its size exceeds + * screen height. + * + * @param key Keycode which is used to verify the hyperlink command + * works. + */ + public void testLongHyperlink(int key) + { + StringItem stringItem = new StringItem( + "label", + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. " + + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. " + + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. ", + StringItem.HYPERLINK); - // Now add command back to StringItem again and make sure it - // works: - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); - - key(Key.RightArrow); + Command ok = new Command("lhlc1", "", Command.ITEM, 0); - key(Key.CBA1); - assertItemCmdListener("case4", ok, stringItem); + StringItem button1 = new StringItem(null, "button1", Item.BUTTON); + Command buttonCommand1 = new Command("lhlc2", "", Command.ITEM, 0); - // And verify also the functionality of second button after - // these changes: - key(Key.RightArrow); - - key(Key.CBA1); - assertItemCmdListener("case5", buttonCommand2, button2); - } + form.append(stringItem); + stringItem.addCommand(ok); + stringItem.setItemCommandListener(this); - /** - * Tests that Hyperlink works as expected when its size exceeds - * screen height. - * - * @param key Keycode which is used to verify the hyperlink command - * works. - */ - public void testLongHyperlink(int key) { - StringItem stringItem = new StringItem( - "label", - "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. " - + "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. " - + "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. ", - StringItem.HYPERLINK); + form.append(button1); + button1.addCommand(buttonCommand1); + button1.setItemCommandListener(this); + + setCurrent(form); - Command ok = new Command("lhlc1", "", Command.ITEM, 0); - - StringItem button1 = new StringItem(null, "button1", Item.BUTTON); - Command buttonCommand1 = new Command("lhlc2", "", Command.ITEM, 0); - - form.append(stringItem); - stringItem.addCommand(ok); - stringItem.setItemCommandListener(this); - - form.append(button1); - button1.addCommand(buttonCommand1); - button1.setItemCommandListener(this); + //TODO: When running all tests and the key is LSK and in following loop + //the i is 0, latestCommand is buttonCommand1 and latestItem is null. + //If button is not added to the form then the latestCommand also + //will be null. + //Problem has something to do with timing, because + //adding debugprints to this test will sometimes make it pass. + //For example following delay will make the test pass: + block(CHANGE_DISPLAYABLE_DELAY); - setCurrent(form); - - //TODO: When running all tests and the key is LSK and in following loop - //the i is 0, latestCommand is buttonCommand1 and latestItem is null. - //If button is not added to the form then the latestCommand also - //will be null. - //Problem has something to do with timing, because - //adding debugprints to this test will sometimes make it pass. - //For example following delay will make the test pass: - block(CHANGE_DISPLAYABLE_DELAY); + // Scroll down and after each keydown-press make sure the hyperlink + // is still focused: + final int rounds = 10; + final int roundsInHyperlink = 3; + for(int i = 0; i < rounds; i++) + { + key(key); - // Scroll down and after each keydown-press make sure the hyperlink - // is still focused: - final int rounds = 10; - final int roundsInHyperlink = 3; - for (int i = 0; i < rounds; i++) { - key(key); + if(i < roundsInHyperlink) + { + // Code assumes that it takes at least three + // keypresses to reach button which is located below hyperlink: + assertItemCmdListener("clicking hyperlink. i=" + i, ok, + stringItem); + } + else if(i >= (rounds - 1)) + { + // After 10 keypresses button should be focused: + assertItemCmdListener("clicking button. i=" + i, + buttonCommand1, button1); + } - if (i < roundsInHyperlink) { - // Code assumes that it takes at least three - // keypresses to reach button which is located below hyperlink: - assertItemCmdListener("clicking hyperlink. i=" + i, ok, - stringItem); - } else if (i >= (rounds - 1)) { - // After 10 keypresses button should be focused: - assertItemCmdListener("clicking button. i=" + i, - buttonCommand1, button1); - } - - key(Key.RightArrow); - block(CHANGE_DISPLAYABLE_DELAY); - } - } + key(Key.RightArrow); + block(CHANGE_DISPLAYABLE_DELAY); + } + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/StringItemUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/StringItemUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/stringitem/StringItemUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.stringitem; @@ -33,7 +33,8 @@ * Created: 2008-08-27 */ public class StringItemUIRobotTest extends UITestBase implements - ItemCommandListener, CommandListener { + ItemCommandListener, CommandListener +{ private Form form; private StringItem button1; @@ -47,7 +48,8 @@ /** * Constructor. */ - public StringItemUIRobotTest() { + public StringItemUIRobotTest() + { } /** @@ -56,34 +58,39 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public StringItemUIRobotTest(String sTestName) { + public StringItemUIRobotTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = StringItemUIRobotTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new StringItemUIRobotTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = StringItemUIRobotTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new StringItemUIRobotTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testSetTextNullEmpty"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testSetTextNullEmpty")) testSetTextNullEmpty(); + + public void runTest() throws Throwable + { + if(getName().equals("testSetTextNullEmpty")) testSetTextNullEmpty(); else super.runTest(); } @@ -91,7 +98,8 @@ * Test that StringItem.setText(text) working properly. * Only text = null and text = "" investigated. */ - public void testSetTextNullEmpty() { + public void testSetTextNullEmpty() + { button1 = new StringItem("", "click!", Item.BUTTON); button2 = new StringItem("", "click 2!", Item.BUTTON); button3 = new StringItem("", "click 3!", Item.BUTTON); @@ -99,7 +107,7 @@ c1 = new Command("Ok1", "", Command.ITEM, 0); c2 = new Command("Ok2", "", Command.ITEM, 0); c3 = new Command("Ok3", "", Command.ITEM, 0); - form = new Form ("setTextTest"); + form = new Form("setTextTest"); form.setCommandListener(this); button1.addCommand(c1); button1.setItemCommandListener(this); @@ -123,7 +131,7 @@ key(Key.RightArrow); key(Key.Select); assertEquals("StringItem content was not changed!", "some text", si - .getText()); + .getText()); } @@ -132,14 +140,18 @@ * @param c Command. * @param item that triggered the command. */ - public void commandAction(Command c, Item item) { - if (c == c1) { + public void commandAction(Command c, Item item) + { + if(c == c1) + { si.setText(""); } - if (c == c2) { + if(c == c2) + { si.setText(null); } - if (c == c3) { + if(c == c3) + { si.setText("some text"); } } @@ -148,7 +160,8 @@ * @param c Command. * @param d displayable that triggered the command. */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TestUITextBox.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TestUITextBox.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TestUITextBox.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.textbox; @@ -32,26 +32,30 @@ *

            * Created: 2008-04-25 */ -public class TestUITextBox extends UITestBase { +public class TestUITextBox extends UITestBase +{ private static final int LENGTH = 100; private static final int EXPECTED_CARET_POSITION = 5; private TextBox textbox; - private int[] inputTextShort = new int[]{'7', '8', '8', '9', - '4', '5', '5', '5', '5', }; + private int[] inputTextShort = new int[] {'7', '8', '8', '9', + '4', '5', '5', '5', '5', + }; private int[] inputSentence = new int [] {'3', '3', '8', '8', '8', - '3', '3', '7', '7', '7', - '9', '9', '9', '1', '0', '9', - '6', '6', '6', '7', '7', - '7', '3', '0', '4', '4', - '4', '7', '7', '7', '7', - '0', '2', '2', '2', }; + '3', '3', '7', '7', '7', + '9', '9', '9', '1', '0', '9', + '6', '6', '6', '7', '7', + '7', '3', '0', '4', '4', + '4', '7', '7', '7', '7', + '0', '2', '2', '2', + }; /** * Constructor. */ - public TestUITextBox() { + public TestUITextBox() + { } /** @@ -60,27 +64,31 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TestUITextBox(String sTestName) { + public TestUITextBox(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = TestUITextBox.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TestUITextBox((String)e.nextElement())); - } - + // Add widget tests + methodNames = TestUITextBox.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TestUITextBox((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testNormalInputMode"); methodNames.addElement("testNonEditable"); @@ -88,12 +96,13 @@ methodNames.addElement("testGetCaretPosition"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testNormalInputMode")) testNormalInputMode(); - else if (getName().equals("testNonEditable")) testNonEditable(); - else if (getName().equals("testCapSent")) testCapSent(); - else if (getName().equals("testGetCaretPosition")) testGetCaretPosition(); + + public void runTest() throws Throwable + { + if(getName().equals("testNormalInputMode")) testNormalInputMode(); + else if(getName().equals("testNonEditable")) testNonEditable(); + else if(getName().equals("testCapSent")) testCapSent(); + else if(getName().equals("testGetCaretPosition")) testGetCaretPosition(); else super.runTest(); } @@ -102,18 +111,20 @@ * This method tests that TextBox getString, returns * correct text which was inputed with UIRobot. */ - public void testNormalInputMode() { + public void testNormalInputMode() + { textbox = new TextBox("ANY", "", LENGTH, TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "Puwg5. But returned " - + getString, getString.equals("Puwg5")); + + "Puwg5. But returned " + + getString, getString.equals("Puwg5")); textbox = null; } @@ -121,19 +132,21 @@ * Test that TextBox is not editable if * UNEDITABLE is specified in constructor. */ - public void testNonEditable() { + public void testNonEditable() + { textbox = new TextBox("No Edit", "editing is not allowed", LENGTH, - TextField.UNEDITABLE | TextField.ANY); + TextField.UNEDITABLE | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "editing is not allowed. But returned " + getString, - getString.equals("editing is not allowed")); + + "editing is not allowed. But returned " + getString, + getString.equals("editing is not allowed")); textbox = null; } @@ -142,19 +155,21 @@ * every word should start with capital letter. * TODO: waiting for fixes from eSWT. */ - public void testCapWord() { + public void testCapWord() + { textbox = new TextBox("Capital Words", "", LENGTH, - TextField.INITIAL_CAPS_WORD | TextField.ANY); + TextField.INITIAL_CAPS_WORD | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputSentence.length; i++) { + for(int i = 0; i < inputSentence.length; i++) + { key(inputSentence[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "Every. Word Is C. But returned " + getString, getString - .equals("Every. Word Is C")); + + "Every. Word Is C. But returned " + getString, getString + .equals("Every. Word Is C")); textbox = null; } @@ -163,19 +178,21 @@ * Test that TextBox behaves correctly if INITIAL_CAPS_SENTENCE specified. * every sentence should start with capital letter. */ - public void testCapSent() { + public void testCapSent() + { textbox = new TextBox("Capital Sentence", "", LENGTH, - TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); + TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputSentence.length; i++) { + for(int i = 0; i < inputSentence.length; i++) + { key(inputSentence[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() return: " - + "Every word is c. But returned " + getString, getString - .equals("Every. Word is c")); + + "Every word is c. But returned " + getString, getString + .equals("Every. Word is c")); textbox = null; } @@ -183,20 +200,22 @@ * TextBox.getCaretPosition() test. * Tests that getCaretPosition works correctly. */ - public void testGetCaretPosition() { + public void testGetCaretPosition() + { int getCaretPosition = 0; textbox = new TextBox("Get Caret", "", LENGTH, - TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); + TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getCaretPosition = textbox.getCaretPosition(); assertTrue("TextBox.getCaretPosition(). Expected: returns " - + EXPECTED_CARET_POSITION + " but got " + getCaretPosition, - getCaretPosition == EXPECTED_CARET_POSITION); + + EXPECTED_CARET_POSITION + " but got " + getCaretPosition, + getCaretPosition == EXPECTED_CARET_POSITION); textbox = null; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TextBoxInputModeUITest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TextBoxInputModeUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textbox/TextBoxInputModeUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.textbox; @@ -59,7 +59,8 @@ * * Note: The references images differ from 3.0 to 3.1 */ -public class TextBoxInputModeUITest extends UITestBase { +public class TextBoxInputModeUITest extends UITestBase +{ private static final int LENGTH = 2000; /* Possible build variants */ @@ -92,10 +93,10 @@ "" + (char) 38463 + (char) 24694 + (char) 21704 + (char) 25289; private static final String HONGKONG_adgj = "" + (char) 26159 + (char) 21542 + (char) 30340 + (char) 35441 - + (char) 28858 + (char) 20102 + (char) 20057 + (char) 28911; + + (char) 28858 + (char) 20102 + (char) 20057 + (char) 28911; private static final String TAIWAN_adgj = "" + (char) 12553 + (char) 30340 + (char) 12557 + (char) 30340 - + (char) 12560 + (char) 30340 + (char) 12563 + (char) 30340; + + (char) 12560 + (char) 30340 + (char) 12563 + (char) 30340; private static final String KANJI_adgj = "" + (char) 12363 + (char) 12373 + (char) 12383 + (char) 12394; private static final String KATAKANA_adgj = @@ -114,8 +115,9 @@ /** * Constructor. */ - public TextBoxInputModeUITest() { - super(); + public TextBoxInputModeUITest() + { + super(); } /** @@ -124,27 +126,31 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TextBoxInputModeUITest(String sTestName) { + public TextBoxInputModeUITest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = TextBoxInputModeUITest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TextBoxInputModeUITest((String)e.nextElement())); - } - + // Add widget tests + methodNames = TextBoxInputModeUITest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TextBoxInputModeUITest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testIS_TRADITIONAL_HANZI"); methodNames.addElement("testDefaultInputMode"); @@ -190,52 +196,53 @@ methodNames.addElement("testcommaInLowerAndUpperCase"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testDefaultInputMode")) testDefaultInputMode(); - else if (getName().equals("testIS_LATIN_DIGITS")) testIS_LATIN_DIGITS(); - else if (getName().equals("testMIDP_UPPERCASE_LATIN")) testMIDP_UPPERCASE_LATIN(); - else if (getName().equals("testMIDP_LOWERCASE_LATIN")) testMIDP_LOWERCASE_LATIN(); - else if (getName().equals("testUCB_BASIC_LATIN")) testUCB_BASIC_LATIN(); - else if (getName().equals("testUCB_GREEK")) testUCB_GREEK(); - else if (getName().equals("testUCB_CYRILLIC")) testUCB_CYRILLIC(); - else if (getName().equals("testUCB_HEBREW")) testUCB_HEBREW(); - else if (getName().equals("testUCB_ARABIC")) testUCB_ARABIC(); - else if (getName().equals("testUCB_DEVANAGARI")) testUCB_DEVANAGARI(); - else if (getName().equals("testUCB_ARMENIAN")) testUCB_ARMENIAN(); - else if (getName().equals("testUCB_THAI")) testUCB_THAI(); - else if (getName().equals("testUCB_HIRAGANA")) testUCB_HIRAGANA(); - else if (getName().equals("testUCB_KATAKANA")) testUCB_KATAKANA(); - else if (getName().equals("testIS_HALFWIDTH_KATAKANA")) testIS_HALFWIDTH_KATAKANA(); - else if (getName().equals("testIS_KANJI")) testIS_KANJI(); - else if (getName().equals("testIS_FULLWIDTH_DIGITS")) testIS_FULLWIDTH_DIGITS(); - else if (getName().equals("testIS_FULLWIDTH_LATIN")) testIS_FULLWIDTH_LATIN(); - else if (getName().equals("testIS_SIMPLIFIED_HANZI")) testIS_SIMPLIFIED_HANZI(); - else if (getName().equals("testIS_TRADITIONAL_HANZI")) testIS_TRADITIONAL_HANZI(); - else if (getName().equals("testnull")) testnull(); - else if (getName().equals("testUNKNOWN")) testUNKNOWN(); - else if (getName().equals("testempty")) testempty(); - else if (getName().equals("testinputModeChange")) testinputModeChange(); - else if (getName().equals("testinputModeAndMenuOpen")) testinputModeAndMenuOpen(); - else if (getName().equals("testinputModesInNumber")) testinputModesInNumber(); - else if (getName().equals("testinputModesInEmailaddr2")) testinputModesInEmailaddr2(); - else if (getName().equals("testinputModesInUrl")) testinputModesInUrl(); - else if (getName().equals("testinputModesInUrl2")) testinputModesInUrl2(); - else if (getName().equals("testinputModesInPassword")) testinputModesInPassword(); - else if (getName().equals("testinputModesInPassword2")) testinputModesInPassword2(); - else if (getName().equals("testinputModesInAny")) testinputModesInAny(); - else if (getName().equals("testinputModesInAny2")) testinputModesInAny2(); - else if (getName().equals("testinputModesInCapsSentence")) testinputModesInCapsSentence(); - else if (getName().equals("testinputModesInCapsWord")) testinputModesInCapsWord(); - else if (getName().equals("testinputModesInCapsSentenceEmailaddr")) testinputModesInCapsSentenceEmailaddr(); - else if (getName().equals("testinputModesInCapsSentenceUrl")) testinputModesInCapsSentenceUrl(); - else if (getName().equals("testinputLatinAfterOtherModes")) testinputLatinAfterOtherModes(); - else if (getName().equals("testinputLatinAfterOtherModes2")) testinputLatinAfterOtherModes2(); - else if (getName().equals("testinputModeNullSetting")) testinputModeNullSetting(); - else if (getName().equals("testcommaInLowerAndUpperCase")) testcommaInLowerAndUpperCase(); + + public void runTest() throws Throwable + { + if(getName().equals("testDefaultInputMode")) testDefaultInputMode(); + else if(getName().equals("testIS_LATIN_DIGITS")) testIS_LATIN_DIGITS(); + else if(getName().equals("testMIDP_UPPERCASE_LATIN")) testMIDP_UPPERCASE_LATIN(); + else if(getName().equals("testMIDP_LOWERCASE_LATIN")) testMIDP_LOWERCASE_LATIN(); + else if(getName().equals("testUCB_BASIC_LATIN")) testUCB_BASIC_LATIN(); + else if(getName().equals("testUCB_GREEK")) testUCB_GREEK(); + else if(getName().equals("testUCB_CYRILLIC")) testUCB_CYRILLIC(); + else if(getName().equals("testUCB_HEBREW")) testUCB_HEBREW(); + else if(getName().equals("testUCB_ARABIC")) testUCB_ARABIC(); + else if(getName().equals("testUCB_DEVANAGARI")) testUCB_DEVANAGARI(); + else if(getName().equals("testUCB_ARMENIAN")) testUCB_ARMENIAN(); + else if(getName().equals("testUCB_THAI")) testUCB_THAI(); + else if(getName().equals("testUCB_HIRAGANA")) testUCB_HIRAGANA(); + else if(getName().equals("testUCB_KATAKANA")) testUCB_KATAKANA(); + else if(getName().equals("testIS_HALFWIDTH_KATAKANA")) testIS_HALFWIDTH_KATAKANA(); + else if(getName().equals("testIS_KANJI")) testIS_KANJI(); + else if(getName().equals("testIS_FULLWIDTH_DIGITS")) testIS_FULLWIDTH_DIGITS(); + else if(getName().equals("testIS_FULLWIDTH_LATIN")) testIS_FULLWIDTH_LATIN(); + else if(getName().equals("testIS_SIMPLIFIED_HANZI")) testIS_SIMPLIFIED_HANZI(); + else if(getName().equals("testIS_TRADITIONAL_HANZI")) testIS_TRADITIONAL_HANZI(); + else if(getName().equals("testnull")) testnull(); + else if(getName().equals("testUNKNOWN")) testUNKNOWN(); + else if(getName().equals("testempty")) testempty(); + else if(getName().equals("testinputModeChange")) testinputModeChange(); + else if(getName().equals("testinputModeAndMenuOpen")) testinputModeAndMenuOpen(); + else if(getName().equals("testinputModesInNumber")) testinputModesInNumber(); + else if(getName().equals("testinputModesInEmailaddr2")) testinputModesInEmailaddr2(); + else if(getName().equals("testinputModesInUrl")) testinputModesInUrl(); + else if(getName().equals("testinputModesInUrl2")) testinputModesInUrl2(); + else if(getName().equals("testinputModesInPassword")) testinputModesInPassword(); + else if(getName().equals("testinputModesInPassword2")) testinputModesInPassword2(); + else if(getName().equals("testinputModesInAny")) testinputModesInAny(); + else if(getName().equals("testinputModesInAny2")) testinputModesInAny2(); + else if(getName().equals("testinputModesInCapsSentence")) testinputModesInCapsSentence(); + else if(getName().equals("testinputModesInCapsWord")) testinputModesInCapsWord(); + else if(getName().equals("testinputModesInCapsSentenceEmailaddr")) testinputModesInCapsSentenceEmailaddr(); + else if(getName().equals("testinputModesInCapsSentenceUrl")) testinputModesInCapsSentenceUrl(); + else if(getName().equals("testinputLatinAfterOtherModes")) testinputLatinAfterOtherModes(); + else if(getName().equals("testinputLatinAfterOtherModes2")) testinputLatinAfterOtherModes2(); + else if(getName().equals("testinputModeNullSetting")) testinputModeNullSetting(); + else if(getName().equals("testcommaInLowerAndUpperCase")) testcommaInLowerAndUpperCase(); else super.runTest(); } - + // ============================================================== @@ -243,34 +250,39 @@ * Tests default input mode, i.e. setInitialInputMode not called. The * default input mode depends on the build variant in use. */ - private void testDefaultInputMode() { + private void testDefaultInputMode() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "NONE", // no initial input mode setting - "", // initial content - inputKeys(new int[] {'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "NONE", // no initial input mode setting + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called before * displaying the text box. Number input mode will be used. */ - private void testIS_LATIN_DIGITS() { + private void testIS_LATIN_DIGITS() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN_DIGITS", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "2345"); // expected content + TextField.ANY, "IS_LATIN_DIGITS", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "2345"); // expected content } /** @@ -278,12 +290,13 @@ * The method is called before displaying the text box. * Latin text input mode will be used */ - private void testIS_LATIN() { + private void testIS_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "Adgj"); // expected content + TextField.ANY, "IS_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "Adgj"); // expected content } /** @@ -291,12 +304,13 @@ * The method is called before displaying the text box. * Uppercase latin text input mode will be used. */ - private void testMIDP_UPPERCASE_LATIN() { + private void testMIDP_UPPERCASE_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "MIDP_UPPERCASE_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "ADGJ"); // expected content + TextField.ANY, "MIDP_UPPERCASE_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "ADGJ"); // expected content } /** @@ -304,12 +318,13 @@ * The method is called before displaying the text box. * Lowercase latin text input mode will be used. */ - private void testMIDP_LOWERCASE_LATIN() { + private void testMIDP_LOWERCASE_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "MIDP_LOWERCASE_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "adgj"); // expected content + TextField.ANY, "MIDP_LOWERCASE_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "adgj"); // expected content } /**. @@ -317,12 +332,13 @@ * The method is called before displaying the text box. * Latin text input mode will be used (same as "IS_LATIN"). */ - private void testUCB_BASIC_LATIN() { + private void testUCB_BASIC_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "UCB_BASIC_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "Adgj"); // expected content + TextField.ANY, "UCB_BASIC_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "Adgj"); // expected content } /** @@ -330,12 +346,13 @@ * The method is called before displaying the text box. * Greek input mode will be used. */ - private void testUCB_GREEK() { + private void testUCB_GREEK() + { doInputModeTest(getName(), - TextField.ANY, "UCB_GREEK", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - GREEK_Adgj); // expected content + TextField.ANY, "UCB_GREEK", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + GREEK_Adgj); // expected content } /** @@ -343,12 +360,13 @@ * The method is called before displaying the text box. * Cyrillic input mode will be used. */ - private void testUCB_CYRILLIC() { + private void testUCB_CYRILLIC() + { doInputModeTest(getName(), - TextField.ANY, "UCB_CYRILLIC", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - CYRILLIC_Adgj); // expected content + TextField.ANY, "UCB_CYRILLIC", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + CYRILLIC_Adgj); // expected content } /** @@ -356,12 +374,13 @@ * The method is called before displaying the text box. * Hebrew input mode will be used. */ - private void testUCB_HEBREW() { + private void testUCB_HEBREW() + { doInputModeTest(getName(), - TextField.ANY, "UCB_HEBREW", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presess - HEBREW_adgj); // expected content + TextField.ANY, "UCB_HEBREW", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presess + HEBREW_adgj); // expected content } /** @@ -369,12 +388,13 @@ * The method is called before displaying the text box. * Arabic input mode will be used. */ - private void testUCB_ARABIC() { + private void testUCB_ARABIC() + { doInputModeTest(getName(), - TextField.ANY, "UCB_ARABIC", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - ARABIC_adgj); // expected content + TextField.ANY, "UCB_ARABIC", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + ARABIC_adgj); // expected content } /** @@ -382,14 +402,15 @@ * The method is called before displaying the text box. * Devanagari/Hindi input mode will be used. */ - private void testUCB_DEVANAGARI() { + private void testUCB_DEVANAGARI() + { String expectedContent = "\u0905\u090f\u0915\u091a"; doInputModeTest(getName(), - TextField.ANY, "UCB_DEVANAGARI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); // expected content + TextField.ANY, "UCB_DEVANAGARI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); // expected content } /** @@ -398,23 +419,27 @@ * This input mode is not supported in 3.0, so default input mode * will be used. */ - private void testUCB_ARMENIAN() { + private void testUCB_ARMENIAN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_ARMENIAN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_ARMENIAN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -423,23 +448,27 @@ * This input mode is supported only in Thai variant; other variants * will use the default input mode. */ - private void testUCB_THAI() { + private void testUCB_THAI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_THAI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_THAI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -448,23 +477,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testUCB_HIRAGANA() { + private void testUCB_HIRAGANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_HIRAGANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_HIRAGANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -473,23 +506,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testUCB_KATAKANA() { + private void testUCB_KATAKANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KATAKANA_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_KATAKANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_KATAKANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -498,23 +535,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_HALFWIDTH_KATAKANA() { + private void testIS_HALFWIDTH_KATAKANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = HALFWIDTH_KATAKANA_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_HALFWIDTH_KATAKANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_HALFWIDTH_KATAKANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -523,23 +564,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_KANJI() { + private void testIS_KANJI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_KANJI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_KANJI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -548,23 +593,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_FULLWIDTH_DIGITS() { + private void testIS_FULLWIDTH_DIGITS() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = FULLWIDTH_2345; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_FULLWIDTH_DIGITS", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_FULLWIDTH_DIGITS", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -573,23 +622,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_FULLWIDTH_LATIN() { + private void testIS_FULLWIDTH_LATIN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = FULLWIDTH_Adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_FULLWIDTH_LATIN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_FULLWIDTH_LATIN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -598,23 +651,27 @@ * This input mode is supported only in China variant; other variants * will use the default input mode. */ - private void testIS_SIMPLIFIED_HANZI() { + private void testIS_SIMPLIFIED_HANZI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_SIMPLIFIED_HANZI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_SIMPLIFIED_HANZI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -624,47 +681,55 @@ * when user's display/input language is either Traditional Hongkong or * Traditional Taiwan; otherwise the default input mode will be used. */ - private void testIS_TRADITIONAL_HANZI() { + private void testIS_TRADITIONAL_HANZI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_TRADITIONAL_HANZI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_TRADITIONAL_HANZI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } - /** - * Tests setInitialInputMode(null). - * The method is called before displaying the text box. This - * default input mode will be used. - */ - private void testnull() { + /** + * Tests setInitialInputMode(null). + * The method is called before displaying the text box. This + * default input mode will be used. + */ + private void testnull() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, null, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, null, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -672,23 +737,27 @@ * The method is called before displaying the text box. * The default input mode will be used. */ - private void testUNKNOWN() { + private void testUNKNOWN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UNKNOWN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UNKNOWN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -696,23 +765,27 @@ * The method is called before displaying the text box. * The default input mode will be used. */ - private void testempty() { + private void testempty() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } @@ -721,28 +794,32 @@ * already visible. Setting the initial input mode has no effect until * focus is changed temporarily elsewhere and then back to TextBox. */ - private void testinputModeChange() { + private void testinputModeChange() + { String expectedContent = "Adgj2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; // Clear-keys used in chinese input - // will remove latin numbers + // will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[]{"IS_LATIN_DIGITS"}, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + TextField.ANY, new String[] {"IS_LATIN_DIGITS"}, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -750,29 +827,33 @@ * has obscured the editor. Setting the initial input mode has no effect * until focus is changed temporarily elsewhere and then back to TextBox. */ - private void testinputModeAndMenuOpen() { + private void testinputModeAndMenuOpen() + { String expectedContent = "Adgj2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; // Clear-keys used in chinese input - // will remove latin numbers + // will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[]{"IS_LATIN_DIGITS"}, - "", // initial content - inputKeys(new int[]{'2', '3', Key.Edit, Key.CBA2, '4', '5'}), - true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + TextField.ANY, new String[] {"IS_LATIN_DIGITS"}, + "", // initial content + inputKeys(new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5'}), + true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -780,16 +861,19 @@ * Focus is changed after each setting to make the input mode effective. * Setting the initial input mode has no effect in NUMERIC text box. */ - private void testinputModesInNumber() { + private void testinputModesInNumber() + { doInputModeSequenceTest(getName(), - TextField.NUMERIC, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + TextField.NUMERIC, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -797,16 +881,19 @@ * Focus is changed after each setting to make the input mode effective. * Setting the initial input mode has no effect in DECIMAL text box. */ - private void testinputModesInDecimal() { + private void testinputModesInDecimal() + { doInputModeSequenceTest(getName(), - TextField.DECIMAL, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + TextField.DECIMAL, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -814,17 +901,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInEmailaddr() { + private void testinputModesInEmailaddr() + { doInputModeSequenceTest(getName(), - TextField.EMAILADDR, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); - // expected content + TextField.EMAILADDR, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + // expected content } /** @@ -833,27 +923,33 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInEmailaddr2() { + private void testinputModesInEmailaddr2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input will remove latin numbers + // Clear-keys used in chinese input will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.EMAILADDR, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.EMAILADDR, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -861,17 +957,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInUrl() { + private void testinputModesInUrl() + { doInputModeSequenceTest(getName(), - TextField.URL, new String[] - {"NONE", // default input mode in ANY text box - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); - // expected content + TextField.URL, new String[] + { + "NONE", // default input mode in ANY text box + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + // expected content } /** @@ -880,27 +979,33 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInUrl2() { + private void testinputModesInUrl2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin numbers + // Clear-keys used in chinese input removes latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj - + KANJI_adgj; + + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.URL, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.URL, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -908,17 +1013,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInPassword() { + private void testinputModesInPassword() + { doInputModeSequenceTest(getName(), - TextField.PASSWORD, new String[] - {"NONE", // default input mode in ANY text box - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", /*"IS_LATIN_DIGITS", */}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj/* + "2345"*/); - // expected content + TextField.PASSWORD, new String[] + { + "NONE", // default input mode in ANY text box + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", /*"IS_LATIN_DIGITS", */ + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj/* + "2345"*/); + // expected content } /** @@ -927,43 +1035,52 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInPassword2() { + private void testinputModesInPassword2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin numbers + // Clear-keys used in chinese input removes latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.PASSWORD, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // pressed keys (per input mode) - expectedContent); + TextField.PASSWORD, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // pressed keys (per input mode) + expectedContent); } /** * Tests different sequential input modes in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInAny() { + private void testinputModesInAny() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // pressed keys (per input mode) - GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); - // expected content + TextField.ANY, new String[] + { + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // pressed keys (per input mode) + GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); + // expected content } /** @@ -972,29 +1089,35 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInAny2() { + private void testinputModesInAny2() + { String expectedContent = "Adgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj; + + CHINA_adgj + CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj - + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; + + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + THAI_adgj - + THAI_adgj + THAI_adgj; + + THAI_adgj + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"NONE", // starts from default input mode - "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", - "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.ANY, new String[] + { + "NONE", // starts from default input mode + "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", + "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1002,27 +1125,33 @@ * ignored if the INITIAL_CAPS_SENTENCE modifier is defined in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentence() { + private void testinputModesInCapsSentence() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj + ARABIC_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + ARABIC_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.INITIAL_CAPS_SENTENCE, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.INITIAL_CAPS_SENTENCE, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1030,26 +1159,32 @@ * ignored if the INITIAL_CAPS_WORD modifier is defined in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsWord() { + private void testinputModesInCapsWord() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj + ARABIC_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + ARABIC_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.INITIAL_CAPS_WORD, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.INITIAL_CAPS_WORD, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1058,15 +1193,16 @@ * because the modifier is meaningless in EMAILADDR. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentenceEmailaddr() { + private void testinputModesInCapsSentenceEmailaddr() + { doInputModeSequenceTest(getName(), - TextField.EMAILADDR | TextField.INITIAL_CAPS_SENTENCE, - new String[] - {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + TextField.EMAILADDR | TextField.INITIAL_CAPS_SENTENCE, + new String[] + {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -1075,14 +1211,15 @@ * because the modifier is meaningless in URL. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentenceUrl() { + private void testinputModesInCapsSentenceUrl() + { doInputModeSequenceTest(getName(), - TextField.URL | TextField.INITIAL_CAPS_SENTENCE, new String[] - {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + TextField.URL | TextField.INITIAL_CAPS_SENTENCE, new String[] + {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -1135,17 +1272,20 @@ * Tests latin input modes after other input modes. * Focus is changed after each setting to make the input mode effective. */ - private void testinputLatinAfterOtherModes() { + private void testinputLatinAfterOtherModes() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"UCB_HEBREW", "IS_LATIN", - "UCB_GREEK", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", - "UCB_CYRILLIC", "IS_LATIN", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - HEBREW_adgj + "adgj" + GREEK_adgj + "ADGJ" - + ARABIC_adgj + "adgj" + CYRILLIC_adgj + "adgj"); + TextField.ANY, new String[] + { + "UCB_HEBREW", "IS_LATIN", + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", + "UCB_CYRILLIC", "IS_LATIN", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + HEBREW_adgj + "adgj" + GREEK_adgj + "ADGJ" + + ARABIC_adgj + "adgj" + CYRILLIC_adgj + "adgj"); } /** @@ -1154,67 +1294,79 @@ * Setting a Japanese or Chinese input mode will have effect only in * the corresponding variants. */ - private void testinputLatinAfterOtherModes2() { + private void testinputLatinAfterOtherModes2() + { String expectedContent = "Adgjadgjadgjadgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; - // Clear-keys used in chinese input removes latin chars + // Clear-keys used in chinese input removes latin chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "adgj" + KANJI_adgj + "adgj" - + FULLWIDTH_2345 + "adgjadgjadgj"; + + FULLWIDTH_2345 + "adgjadgjadgj"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "adgjadgjadgjadgjadgj" - + THAI_adgj + "adgj"; + + THAI_adgj + "adgj"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", - "IS_KANJI", "MIDP_LOWERCASE_LATIN", - "IS_FULLWIDTH_DIGITS", "MIDP_LOWERCASE_LATIN", - "UCB_THAI", "MIDP_LOWERCASE_LATIN", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.ANY, new String[] + { + "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", + "IS_KANJI", "MIDP_LOWERCASE_LATIN", + "IS_FULLWIDTH_DIGITS", "MIDP_LOWERCASE_LATIN", + "UCB_THAI", "MIDP_LOWERCASE_LATIN", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** * Tests null input mode after different input modes in ANY text box. */ - private void testinputModeNullSetting() { + private void testinputModeNullSetting() + { // NOTE: upper cases should be corrected! String expectedContent = "2345adgj" + ARABIC_adgj + "adgj" - + "adgjadgjadgjadgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + + "adgjadgjadgjadgjadgjadgjadgjadgj"; + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj + + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "2345" + KANJI_adgj + ARABIC_adgj + KANJI_adgj - + KANJI_adgj + KANJI_adgj + HALFWIDTH_KATAKANA_adgj - + KANJI_adgj + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj - + KANJI_adgj; + + KANJI_adgj + KANJI_adgj + HALFWIDTH_KATAKANA_adgj + + KANJI_adgj + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj + + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345A" + THAI_adgj + ARABIC_adgj + THAI_adgj - + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj - + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj; + + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj + + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"IS_LATIN_DIGITS", null, - "UCB_ARABIC", null, - "IS_SIMPLIFIED_HANZI", null, - "IS_HALFWIDTH_KATAKANA", null, - "IS_FULLWIDTH_DIGITS", null, - "UCB_THAI", null, }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - expectedContent); + TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", null, + "UCB_ARABIC", null, + "IS_SIMPLIFIED_HANZI", null, + "IS_HALFWIDTH_KATAKANA", null, + "IS_FULLWIDTH_DIGITS", null, + "UCB_THAI", null, + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + expectedContent); } /** @@ -1222,14 +1374,15 @@ * text box. Note: after a comma and space the input mode changes to * Text case (not sure whether this is correct behaviour) */ - private void testcommaInLowerAndUpperCase() { + private void testcommaInLowerAndUpperCase() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '1', '0', '4', '5' }, false, - // key presses (per input mode) - "ad. GjAD. Gj"); + TextField.ANY, new String[] + {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '1', '0', '4', '5' }, false, + // key presses (per input mode) + "ad. GjAD. Gj"); } @@ -1250,40 +1403,47 @@ * @param expectedContent Expected content of TextBox */ private void doInputModeTest(String testCaseName, - int constraints, String initialInputMode, String initialContent, - int[] pressedKeys, String expectedContent) { + int constraints, String initialInputMode, String initialContent, + int[] pressedKeys, String expectedContent) + { boolean passed = true; - try { + try + { // Create TextBox TextBox textBox = new TextBox( - testCaseName, // title - initialContent, LENGTH, constraints); + testCaseName, // title + initialContent, LENGTH, constraints); // Set initial input mode before displaying TextBox - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textBox.setInitialInputMode(initialInputMode); block(KEYEVENT_DELAY); } setCurrent(textBox); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textBox, - expectedContent, expectedContent == null ? true : false); + expectedContent, expectedContent == null ? true : false); } - catch (Exception exc) { - fail(testCaseName + " failed: "+exc.toString()); + catch(Exception exc) + { + fail(testCaseName + " failed: "+exc.toString()); passed = false; } assertTrue(testCaseName, passed); @@ -1309,34 +1469,40 @@ * @param expectedContent Expected content of TextBox */ private void doInputModeSequenceTest(String testCaseName, - int constraints, String[] nextInputModes, String initialContent, - int[] pressedKeys, boolean beforeAndAfter, - String expectedContent) { + int constraints, String[] nextInputModes, String initialContent, + int[] pressedKeys, boolean beforeAndAfter, + String expectedContent) + { boolean passed = true; - try { + try + { // Create TextBox - TextBox textBox = new TextBox(testCaseName, - initialContent, LENGTH, constraints); + TextBox textBox = new TextBox(testCaseName, + initialContent, LENGTH, constraints); // Create another TextBox in order to be able to change focus TextBox other = new TextBox("Focus change", - "Temporary text box", LENGTH, TextField.ANY); + "Temporary text box", LENGTH, TextField.ANY); // Display the original TextBox Display.getDisplay(getMIDlet()).setCurrent(textBox); block(CHANGE_DISPLAYABLE_DELAY); - for (int m = 0; m < nextInputModes.length; m++) { + for(int m = 0; m < nextInputModes.length; m++) + { // Set initial input mode while the original TextBox is visible textBox.setInitialInputMode(nextInputModes[m]); - if (beforeAndAfter) { + if(beforeAndAfter) + { // Do key presses (input mode setting not yet effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1348,8 +1514,10 @@ setCurrent(textBox); // Do key presses again (now input mode setting is effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1358,11 +1526,12 @@ // Check the result of all key presses (i.e. the used input modes) passed = checkResult(testCaseName, textBox, - expectedContent, expectedContent == null ? true : false); + expectedContent, expectedContent == null ? true : false); } - catch (Exception exc) { - fail(testCaseName + " failed: "+exc.toString()); + catch(Exception exc) + { + fail(testCaseName + " failed: "+exc.toString()); passed = false; } assertTrue(testCaseName, passed); @@ -1380,30 +1549,36 @@ * @return result Returns whether test case passed or failed */ private boolean checkResult(String testCaseName, - TextBox textBox, String expectedContent, boolean takeScreenshot) { + TextBox textBox, String expectedContent, boolean takeScreenshot) + { boolean passed = true; // Check the expected content - if (expectedContent != null) { - if (!expectedContent.equals(textBox.getString())) { + if(expectedContent != null) + { + if(!expectedContent.equals(textBox.getString())) + { passed = false; print(testCaseName + " test failed: content: " + textBox.getString() - + ", expected: " + expectedContent); + + ", expected: " + expectedContent); } } // Take the screenshot and compare it with the previous one - if (takeScreenshot) { - if (!takeScreenshot(testCaseName + ".gif")) { - passed = false; - print(testCaseName + " test " - + " failed: screenshot does not match"); - } + if(takeScreenshot) + { + if(!takeScreenshot(testCaseName + ".gif")) + { + passed = false; + print(testCaseName + " test " + + " failed: screenshot does not match"); + } } - if (passed) { - print(testCaseName + " test succeeded: " + textBox.getString()); + if(passed) + { + print(testCaseName + " test succeeded: " + textBox.getString()); } return passed; } @@ -1414,17 +1589,21 @@ * @param keys Key presses according to westen input * @return Key presses for the current variant */ - private int[] inputKeys(int[] keys) { + private int[] inputKeys(int[] keys) + { int[] input = null; int k = 0; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { input = new int[4 * keys.length]; - for (int i = 0; i < keys.length; i++) { + for(int i = 0; i < keys.length; i++) + { input[k] = keys[i]; k = k + 1; - if (keys[i] >= '0' && keys[i] <= '9') { + if(keys[i] >= '0' && keys[i] <= '9') + { input[k] = Key.Select; input[k + 1] = Key.Select; input[k + 2] = Key.Clear; @@ -1432,25 +1611,29 @@ } } } - else - if (variant == JAPAN_VARIANT) { - input = new int[2 * keys.length]; - for (int i = 0; i < keys.length; i++) { - input[k] = keys[i]; + else if(variant == JAPAN_VARIANT) + { + input = new int[2 * keys.length]; + for(int i = 0; i < keys.length; i++) + { + input[k] = keys[i]; + k = k + 1; + if(keys[i] >= '0' && keys[i] <= '9') + { + input[k] = Key.Select; k = k + 1; - if (keys[i] >= '0' && keys[i] <= '9') { - input[k] = Key.Select; - k = k + 1; - } } } - else { - input = keys; - k = input.length; - } + } + else + { + input = keys; + k = input.length; + } // Set the array size correct - if (k < input.length) { + if(k < input.length) + { int[] temp = new int[k]; System.arraycopy(input, 0, temp, 0, temp.length); input = temp; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/FormChangeFocusCheckTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/FormChangeFocusCheckTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/FormChangeFocusCheckTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.textfield; @@ -32,14 +32,16 @@ *
            * Created: 2008-09-15 */ -public class FormChangeFocusCheckTest extends UITestBase { +public class FormChangeFocusCheckTest extends UITestBase +{ private static int maxsize = 2000; /** * Constructor. */ - public FormChangeFocusCheckTest() { + public FormChangeFocusCheckTest() + { } /** @@ -48,27 +50,31 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FormChangeFocusCheckTest(String sTestName) { + public FormChangeFocusCheckTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = FormChangeFocusCheckTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new FormChangeFocusCheckTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = FormChangeFocusCheckTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new FormChangeFocusCheckTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testFormChangeAndFocus"); methodNames.addElement("setTextFieldToAnotherFormTest"); @@ -76,23 +82,25 @@ methodNames.addElement("testCaretPossitionAfterDisplayableChange"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testFormChangeAndFocus")) testFormChangeAndFocus(); - else if (getName().equals("setTextFieldToAnotherFormTest")) setTextFieldToAnotherFormTest(); - else if (getName().equals("removeTextFieldSetTextTest")) removeTextFieldSetTextTest(); - else if (getName().equals("testCaretPossitionAfterDisplayableChange")) testCaretPossitionAfterDisplayableChange(); + + public void runTest() throws Throwable + { + if(getName().equals("testFormChangeAndFocus")) testFormChangeAndFocus(); + else if(getName().equals("setTextFieldToAnotherFormTest")) setTextFieldToAnotherFormTest(); + else if(getName().equals("removeTextFieldSetTextTest")) removeTextFieldSetTextTest(); + else if(getName().equals("testCaretPossitionAfterDisplayableChange")) testCaretPossitionAfterDisplayableChange(); else super.runTest(); } /** - * Test that focus behaves correct after switching displayables when - * setCurrentItem is used. - */ - public void testFormChangeAndFocus() { - Form forma = new Form ("Form A"); - Form formb = new Form ("Form B"); - StringItem first = new StringItem (null, "first"); + * Test that focus behaves correct after switching displayables when + * setCurrentItem is used. + */ + public void testFormChangeAndFocus() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + StringItem first = new StringItem(null, "first"); String expectedContent = "Adg"; String expectedContent2 = "Adgjmp"; TextField tf1 = new TextField("name", null, maxsize, TextField.ANY); @@ -139,126 +147,129 @@ display.setCurrentItem(tf1); // seems that in case of setCurrentItem we need to wait more time to - // change displayable. - block(1000); + // change displayable. + block(1000); key('2'); // A - key('3'); // d - key('4'); // g - assertEquals("(case1) No text was inputed", expectedContent, tf1 - .getString()); - setCurrent(formb); + key('3'); // d + key('4'); // g + assertEquals("(case1) No text was inputed", expectedContent, tf1 + .getString()); + setCurrent(formb); - setCurrent(forma); + setCurrent(forma); - block(1000);// - // key('5', 0); // - key('5'); // k - key('6'); // m - key('7'); // p - assertEquals("(case2)No text was inputed after switching Displayble", - expectedContent2, tf1.getString()); - display.setCurrentItem(first); - block(CHANGE_DISPLAYABLE_DELAY); + block(1000);// + // key('5', 0); // + key('5'); // k + key('6'); // m + key('7'); // p + assertEquals("(case2)No text was inputed after switching Displayble", + expectedContent2, tf1.getString()); + display.setCurrentItem(first); + block(CHANGE_DISPLAYABLE_DELAY); key('2'); // a - key('3'); // d - key('4'); // g - assertEquals("(case3)text was inputed when setCurrentItem was set to " - + "StringItem", expectedContent2, tf1.getString()); - setCurrent(formb); - block(CHANGE_DISPLAYABLE_DELAY); + key('3'); // d + key('4'); // g + assertEquals("(case3)text was inputed when setCurrentItem was set to " + + "StringItem", expectedContent2, tf1.getString()); + setCurrent(formb); + block(CHANGE_DISPLAYABLE_DELAY); - setCurrent(forma); - block(CHANGE_DISPLAYABLE_DELAY); + setCurrent(forma); + block(CHANGE_DISPLAYABLE_DELAY); - key('2'); // a - key('3'); // d - key('4'); // g + key('2'); // a + key('3'); // d + key('4'); // g assertEquals("(case4)text was inputed when setCurrent was set to " - + "back to Form A and TextField was not visible", - expectedContent2, tf1.getString()); + + "back to Form A and TextField was not visible", + expectedContent2, tf1.getString()); } /** - * Check that caretPosition is remains the same when TextField is set to - * other form. - */ - public void setTextFieldToAnotherFormTest() { - String expectedContent = "Boaddy"; - Form forma = new Form("Form A"); - Form formb = new Form("Form B"); - TextField tf = new TextField("hader", "Body", maxsize, TextField.ANY); - forma.append(tf); + * Check that caretPosition is remains the same when TextField is set to + * other form. + */ + public void setTextFieldToAnotherFormTest() + { + String expectedContent = "Boaddy"; + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + TextField tf = new TextField("hader", "Body", maxsize, TextField.ANY); + forma.append(tf); - setCurrent(forma); - key(Key.LeftArrow); - key(Key.LeftArrow); // caret o|d - forma.delete(0); - formb.append(tf); - setCurrent(formb); - key('2'); // a - key('3'); // d - assertEquals("caret position was not the same after assigning TextField" - + " to another form", expectedContent, tf.getString()); - forma = null; - formb = null; - tf = null; - } + setCurrent(forma); + key(Key.LeftArrow); + key(Key.LeftArrow); // caret o|d + forma.delete(0); + formb.append(tf); + setCurrent(formb); + key('2'); // a + key('3'); // d + assertEquals("caret position was not the same after assigning TextField" + + " to another form", expectedContent, tf.getString()); + forma = null; + formb = null; + tf = null; + } /** - * Check that get caretPosition return correctPosition after TextField - * Removed from the Form and setString() is used. - */ - public void removeTextFieldSetTextTest() { - Form form = new Form("Form"); - TextField tf = new TextField("header", "some text", maxsize, - TextField.ANY); - form.append(tf); - setCurrent(form); - // enter some text to TextField - key('2'); // a - key('3'); // d - form.delete(0); - tf.setString("four"); - assertEquals("caret position was not set to correct, after setStrin()", - tf.size(), tf.getCaretPosition()); - form = null; - tf = null; - } + * Check that get caretPosition return correctPosition after TextField + * Removed from the Form and setString() is used. + */ + public void removeTextFieldSetTextTest() + { + Form form = new Form("Form"); + TextField tf = new TextField("header", "some text", maxsize, + TextField.ANY); + form.append(tf); + setCurrent(form); + // enter some text to TextField + key('2'); // a + key('3'); // d + form.delete(0); + tf.setString("four"); + assertEquals("caret position was not set to correct, after setStrin()", + tf.size(), tf.getCaretPosition()); + form = null; + tf = null; + } /** - * Check that caret positioned correctly after switching displayables. - */ - public void testCaretPossitionAfterDisplayableChange() { - Form forma = new Form("Form A"); - Form formb = new Form("Form B"); - TextField tf1 = new TextField("header", null, maxsize, TextField.ANY); - TextField tf2 = new TextField("header", null, maxsize, TextField.ANY); - tf1.setString("some text that should occupy few lines"); - tf2.setString("some text that should occupy few lines also"); - forma.append(tf1); - forma.append(tf2); - setCurrent(forma); - key(Key.LeftArrow); - key(Key.LeftArrow); - assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 - .getCaretPosition()); - setCurrent(formb); - setCurrent(forma); - assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 - .getCaretPosition()); - //go to next textField - key(Key.DownArrow); - key(Key.DownArrow); - key(Key.LeftArrow); - key(Key.LeftArrow); - assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 - .getCaretPosition()); - setCurrent(formb); - setCurrent(forma); - assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 - .getCaretPosition()); - } + * Check that caret positioned correctly after switching displayables. + */ + public void testCaretPossitionAfterDisplayableChange() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + TextField tf1 = new TextField("header", null, maxsize, TextField.ANY); + TextField tf2 = new TextField("header", null, maxsize, TextField.ANY); + tf1.setString("some text that should occupy few lines"); + tf2.setString("some text that should occupy few lines also"); + forma.append(tf1); + forma.append(tf2); + setCurrent(forma); + key(Key.LeftArrow); + key(Key.LeftArrow); + assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 + .getCaretPosition()); + setCurrent(formb); + setCurrent(forma); + assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 + .getCaretPosition()); + //go to next textField + key(Key.DownArrow); + key(Key.DownArrow); + key(Key.LeftArrow); + key(Key.LeftArrow); + assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 + .getCaretPosition()); + setCurrent(formb); + setCurrent(forma); + assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 + .getCaretPosition()); + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldCommandTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.textfield; @@ -33,14 +33,16 @@ *
            * Created: 2008-09-15 */ -public class TextFieldCommandTest extends ItemUITestBase { +public class TextFieldCommandTest extends ItemUITestBase +{ private static int maxsize = 2000; /** * Constructor. */ - public TextFieldCommandTest() { + public TextFieldCommandTest() + { } /** @@ -49,47 +51,53 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public TextFieldCommandTest(String sTestName) { + public TextFieldCommandTest(String sTestName) + { super(sTestName); } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = TextFieldCommandTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TextFieldCommandTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = TextFieldCommandTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TextFieldCommandTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testCommands"); methodNames.addElement("testTextFieldChange"); methodNames.addElement("testItemState"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testCommands")) testCommands(); - else if (getName().equals("testTextFieldChange")) testTextFieldChange(); - else if (getName().equals("testItemState")) testItemState(); + + public void runTest() throws Throwable + { + if(getName().equals("testCommands")) testCommands(); + else if(getName().equals("testTextFieldChange")) testTextFieldChange(); + else if(getName().equals("testItemState")) testItemState(); else super.runTest(); } - + /** * Tests the basic functionality of command added to TextField. */ - public void testCommands() { - TextField tf = new TextField ("name", "text", maxsize, TextField.ANY); + public void testCommands() + { + TextField tf = new TextField("name", "text", maxsize, TextField.ANY); Command ok = new Command("Ok", "", Command.ITEM, 0); tf.addCommand(ok); @@ -108,11 +116,12 @@ /** * Tests TextField's value changing. */ - public void testTextFieldChange() { + public void testTextFieldChange() + { TextField tf1 = new TextField("TextField", "text1", maxsize, - TextField.ANY); + TextField.ANY); TextField tf2 = new TextField("TextField", "text2", maxsize, - TextField.ANY); + TextField.ANY); boolean case1 = true; boolean case2 = true; boolean case3 = true; @@ -125,20 +134,22 @@ // Change TextField CaretPosition key(Key.RightArrow); - if (tf1.getCaretPosition() != 0) { + if(tf1.getCaretPosition() != 0) + { case1 = false; reason = "Wrong CaretPosition(case1). " + "expected " + 0 - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); reason += "<<<<<>>>>>>"; } - //assertEquals("Wrong CaretPosition(case1).", 0, tf1.getCaretPosition()); + //assertEquals("Wrong CaretPosition(case1).", 0, tf1.getCaretPosition()); // Change TextField CaretPosition back to original: key(Key.LeftArrow); - if (tf1.size() != tf1.getCaretPosition()) { + if(tf1.size() != tf1.getCaretPosition()) + { case2 = false; reason += "Wrong CaretPosition(case 2)." + "expected " + tf1.size() - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); reason += "<<<<<>>>>>>"; } /*assertEquals("Wrong CaretPosition(case 2).", tf1.size(), @@ -146,10 +157,11 @@ */ // Change focus to nextTextField key(Key.DownArrow); - if (tf2.getCaretPosition() != 0) { + if(tf2.getCaretPosition() != 0) + { case3 = false; reason += "Wrong CaretPosition(case 3)." + "expected " + 0 - + "but got" + tf2.getCaretPosition(); + + "but got" + tf2.getCaretPosition(); reason += "<<<<<>>>>>>"; } /*assertEquals("Wrong CaretPosition(case 3).", 0, @@ -157,10 +169,11 @@ // Now Caret have to be in the end key(Key.LeftArrow); - if (tf2.size() != tf2.getCaretPosition()) { + if(tf2.size() != tf2.getCaretPosition()) + { case4 = false; reason += "Wrong CaretPosition(case 4)." + "expected " + tf2.size() - + "but got" + tf2.getCaretPosition(); + + "but got" + tf2.getCaretPosition(); reason += "<<<<<>>>>>>"; } /* @@ -170,10 +183,11 @@ //go to first TextField key(Key.RightArrow); key(Key.UpArrow); - if (tf1.size() != tf1.getCaretPosition()) { + if(tf1.size() != tf1.getCaretPosition()) + { case5 = false; reason += "Wrong CaretPosition(case 5)." + "expected " + tf1.size() - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); } assertTrue(reason, case1 & case2 & case3 & case4 & case5); } @@ -182,9 +196,10 @@ * Tests that Form receives ItemStateChanged-events when TextField's * value is changed. */ - public void testItemState() { + public void testItemState() + { TextField tf = new TextField("header", "text", maxsize, - TextField.ANY); + TextField.ANY); form.append(tf); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldSetInitialInputModeTest.java --- a/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldSetInitialInputModeTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src/com/nokia/openlcdui/mt_uirobot/textfield/TextFieldSetInitialInputModeTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package com.nokia.openlcdui.mt_uirobot.textfield; @@ -58,7 +58,8 @@ * reason. Note: The references images differ from 3.0 to 3.1, and 3.2 */ -public class TextFieldSetInitialInputModeTest extends UITestBase { +public class TextFieldSetInitialInputModeTest extends UITestBase +{ /* Expected results for diffrent input modes */ private static final String ARABIC_adgj = "" + (char) 1576 + (char) 1575 @@ -82,40 +83,45 @@ private final int normalSize = 2000; /** - * Default constructor. - */ - public TextFieldSetInitialInputModeTest() { - } + * Default constructor. + */ + public TextFieldSetInitialInputModeTest() + { + } - /** - * Constructor. - * - * @param sTestName - * name of testcase. - * @param rTestMethod - * test method. - */ - public TextFieldSetInitialInputModeTest(String sTestName) { - super(sTestName); - } + /** + * Constructor. + * + * @param sTestName + * name of testcase. + * @param rTestMethod + * test method. + */ + public TextFieldSetInitialInputModeTest(String sTestName) + { + super(sTestName); + } - public static Test suite() { + public static Test suite() + { TestSuite suite = new TestSuite(); java.util.Vector methodNames; - java.util.Enumeration e; + java.util.Enumeration e; - // Add widget tests - methodNames = TextFieldSetInitialInputModeTest.methodNames(); - e = methodNames.elements(); - while (e.hasMoreElements()) { - suite.addTest(new TextFieldSetInitialInputModeTest((String)e.nextElement())); - } - + // Add widget tests + methodNames = TextFieldSetInitialInputModeTest.methodNames(); + e = methodNames.elements(); + while(e.hasMoreElements()) + { + suite.addTest(new TextFieldSetInitialInputModeTest((String)e.nextElement())); + } + return suite; } - public static java.util.Vector methodNames() { + public static java.util.Vector methodNames() + { java.util.Vector methodNames = new java.util.Vector(); methodNames.addElement("testDefaultInputMode"); methodNames.addElement("testIS_LATIN_DIGITS"); @@ -163,52 +169,53 @@ methodNames.addElement("testUppercaseBeforeMakingFormCurrent"); return methodNames; } - - public void runTest() throws Throwable { - if (getName().equals("testDefaultInputMode")) testDefaultInputMode(); - else if (getName().equals("testIS_LATIN_DIGITS")) testIS_LATIN_DIGITS(); - else if (getName().equals("testIS_LATIN_DIGITS2")) testIS_LATIN_DIGITS2(); - else if (getName().equals("testIS_LATIN")) testIS_LATIN(); - else if (getName().equals("testMIDP_UPPERCASE_LATIN")) testMIDP_UPPERCASE_LATIN(); - else if (getName().equals("testMIDP_LOWERCASE_LATIN")) testMIDP_LOWERCASE_LATIN(); - else if (getName().equals("testUCB_BASIC_LATIN")) testUCB_BASIC_LATIN(); - else if (getName().equals("testUCB_GREEK")) testUCB_GREEK(); - else if (getName().equals("testUCB_CYRILLIC")) testUCB_CYRILLIC(); - else if (getName().equals("testUCB_HEBREW")) testUCB_HEBREW(); - else if (getName().equals("testUCB_ARABIC")) testUCB_ARABIC(); - else if (getName().equals("testUCB_DEVANAGARI")) testUCB_DEVANAGARI(); - else if (getName().equals("testUCB_ARMENIAN")) testUCB_ARMENIAN(); - else if (getName().equals("testUCB_THAI")) testUCB_THAI(); - else if (getName().equals("testUCB_HIRAGANA")) testUCB_HIRAGANA(); - else if (getName().equals("testUCB_KATAKANA")) testUCB_KATAKANA(); - else if (getName().equals("testIS_HALFWIDTH_KATAKANA")) testIS_HALFWIDTH_KATAKANA(); - else if (getName().equals("testIS_KANJI")) testIS_KANJI(); - else if (getName().equals("testIS_FULLWIDTH_DIGITS")) testIS_FULLWIDTH_DIGITS(); - else if (getName().equals("testIS_FULLWIDTH_LATIN")) testIS_FULLWIDTH_LATIN(); - else if (getName().equals("testIS_SIMPLIFIED_HANZI")) testIS_SIMPLIFIED_HANZI(); - else if (getName().equals("testIS_TRADITIONAL_HANZI")) testIS_TRADITIONAL_HANZI(); - else if (getName().equals("testnull")) testnull(); - else if (getName().equals("testUNKNOWN")) testUNKNOWN(); - else if (getName().equals("testempty")) testempty(); - else if (getName().equals("testinputModeChange")) testinputModeChange(); - else if (getName().equals("testinputModeAndMenuOpen")) testinputModeAndMenuOpen(); - else if (getName().equals("testinputModesInEmailaddr")) testinputModesInEmailaddr(); - else if (getName().equals("testinputModesInEmailaddr2")) testinputModesInEmailaddr2(); - else if (getName().equals("testinputModesInUrl")) testinputModesInUrl(); - else if (getName().equals("testinputModesInUrl2")) testinputModesInUrl2(); - else if (getName().equals("testinputModesInPassword")) testinputModesInPassword(); - else if (getName().equals("testinputModesInPassword2")) testinputModesInPassword2(); - else if (getName().equals("testinputModesInAny")) testinputModesInAny(); - else if (getName().equals("testinputModesInAny")) testinputModesInAny2(); - else if (getName().equals("testinputModesInCapsSentence")) testinputModesInCapsSentence(); - else if (getName().equals("testinputModesInCapsWord")) testinputModesInCapsWord(); - else if (getName().equals("testinputModesInCapsSentenceEmailaddr")) testinputModesInCapsSentenceEmailaddr(); - else if (getName().equals("testinputModesInCapsSentenceUrl")) testinputModesInCapsSentenceUrl(); - else if (getName().equals("testinputLatinAfterOtherModes")) testinputLatinAfterOtherModes(); - else if (getName().equals("testinputLatinAfterOtherModes2")) testinputLatinAfterOtherModes2(); - else if (getName().equals("testinputModeNullSetting")) testinputModeNullSetting(); - else if (getName().equals("testcommaInLowerAndUpperCase")) testcommaInLowerAndUpperCase(); - else if (getName().equals("testUppercaseBeforeMakingFormCurrent")) testUppercaseBeforeMakingFormCurrent(); + + public void runTest() throws Throwable + { + if(getName().equals("testDefaultInputMode")) testDefaultInputMode(); + else if(getName().equals("testIS_LATIN_DIGITS")) testIS_LATIN_DIGITS(); + else if(getName().equals("testIS_LATIN_DIGITS2")) testIS_LATIN_DIGITS2(); + else if(getName().equals("testIS_LATIN")) testIS_LATIN(); + else if(getName().equals("testMIDP_UPPERCASE_LATIN")) testMIDP_UPPERCASE_LATIN(); + else if(getName().equals("testMIDP_LOWERCASE_LATIN")) testMIDP_LOWERCASE_LATIN(); + else if(getName().equals("testUCB_BASIC_LATIN")) testUCB_BASIC_LATIN(); + else if(getName().equals("testUCB_GREEK")) testUCB_GREEK(); + else if(getName().equals("testUCB_CYRILLIC")) testUCB_CYRILLIC(); + else if(getName().equals("testUCB_HEBREW")) testUCB_HEBREW(); + else if(getName().equals("testUCB_ARABIC")) testUCB_ARABIC(); + else if(getName().equals("testUCB_DEVANAGARI")) testUCB_DEVANAGARI(); + else if(getName().equals("testUCB_ARMENIAN")) testUCB_ARMENIAN(); + else if(getName().equals("testUCB_THAI")) testUCB_THAI(); + else if(getName().equals("testUCB_HIRAGANA")) testUCB_HIRAGANA(); + else if(getName().equals("testUCB_KATAKANA")) testUCB_KATAKANA(); + else if(getName().equals("testIS_HALFWIDTH_KATAKANA")) testIS_HALFWIDTH_KATAKANA(); + else if(getName().equals("testIS_KANJI")) testIS_KANJI(); + else if(getName().equals("testIS_FULLWIDTH_DIGITS")) testIS_FULLWIDTH_DIGITS(); + else if(getName().equals("testIS_FULLWIDTH_LATIN")) testIS_FULLWIDTH_LATIN(); + else if(getName().equals("testIS_SIMPLIFIED_HANZI")) testIS_SIMPLIFIED_HANZI(); + else if(getName().equals("testIS_TRADITIONAL_HANZI")) testIS_TRADITIONAL_HANZI(); + else if(getName().equals("testnull")) testnull(); + else if(getName().equals("testUNKNOWN")) testUNKNOWN(); + else if(getName().equals("testempty")) testempty(); + else if(getName().equals("testinputModeChange")) testinputModeChange(); + else if(getName().equals("testinputModeAndMenuOpen")) testinputModeAndMenuOpen(); + else if(getName().equals("testinputModesInEmailaddr")) testinputModesInEmailaddr(); + else if(getName().equals("testinputModesInEmailaddr2")) testinputModesInEmailaddr2(); + else if(getName().equals("testinputModesInUrl")) testinputModesInUrl(); + else if(getName().equals("testinputModesInUrl2")) testinputModesInUrl2(); + else if(getName().equals("testinputModesInPassword")) testinputModesInPassword(); + else if(getName().equals("testinputModesInPassword2")) testinputModesInPassword2(); + else if(getName().equals("testinputModesInAny")) testinputModesInAny(); + else if(getName().equals("testinputModesInAny")) testinputModesInAny2(); + else if(getName().equals("testinputModesInCapsSentence")) testinputModesInCapsSentence(); + else if(getName().equals("testinputModesInCapsWord")) testinputModesInCapsWord(); + else if(getName().equals("testinputModesInCapsSentenceEmailaddr")) testinputModesInCapsSentenceEmailaddr(); + else if(getName().equals("testinputModesInCapsSentenceUrl")) testinputModesInCapsSentenceUrl(); + else if(getName().equals("testinputLatinAfterOtherModes")) testinputLatinAfterOtherModes(); + else if(getName().equals("testinputLatinAfterOtherModes2")) testinputLatinAfterOtherModes2(); + else if(getName().equals("testinputModeNullSetting")) testinputModeNullSetting(); + else if(getName().equals("testcommaInLowerAndUpperCase")) testcommaInLowerAndUpperCase(); + else if(getName().equals("testUppercaseBeforeMakingFormCurrent")) testUppercaseBeforeMakingFormCurrent(); else super.runTest(); } @@ -219,48 +226,52 @@ * Tests default input mode, i.e. setInitialInputMode not called. The * default input mode depends on the build variant in use. */ - private void testDefaultInputMode() { + private void testDefaultInputMode() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "NONE", // no initial input - // mode setting - "", // initial content - new int[] { '2', '3', '4', '5', }, // key presses - expectedContent); + // mode setting + "", // initial content + new int[] { '2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called before * displaying the text field. Number input mode will be used. */ - private void testIS_LATIN_DIGITS() { + private void testIS_LATIN_DIGITS() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN_DIGITS", "", - // initial - // content - new int[] { '2', '3', '4', '5', }, // key presses - "2345"); // expected content + // initial + // content + new int[] { '2', '3', '4', '5', }, // key presses + "2345"); // expected content } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called after * appending the text field into the form Number input mode will be used. */ - private void testIS_LATIN_DIGITS2() { + private void testIS_LATIN_DIGITS2() + { doInputModeTest2(getName(), TextField.ANY, "IS_LATIN_DIGITS", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "2345"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "2345"); // expected content } /** * Tests setInitialInputMode("IS_LATIN"). The method is called before * displaying the text field. Latin text input mode will be used */ - private void testIS_LATIN() { + private void testIS_LATIN() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - "Adgj"); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + "Adgj"); // expected content } /** @@ -268,11 +279,12 @@ * before displaying the text field. Uppercase latin text input mode will be * used. */ - private void testMIDP_UPPERCASE_LATIN() { + private void testMIDP_UPPERCASE_LATIN() + { doInputModeTest(getName(), TextField.ANY, "MIDP_UPPERCASE_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "ADGJ"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "ADGJ"); // expected content } /** @@ -280,11 +292,12 @@ * before displaying the text field. Lowercase latin text input mode will be * used. */ - private void testMIDP_LOWERCASE_LATIN() { + private void testMIDP_LOWERCASE_LATIN() + { doInputModeTest(getName(), TextField.ANY, "MIDP_LOWERCASE_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "adgj"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "adgj"); // expected content } /** @@ -292,68 +305,74 @@ * before displaying the text field. Latin text input mode will be used * (same as "IS_LATIN"). */ - private void testUCB_BASIC_LATIN() { + private void testUCB_BASIC_LATIN() + { doInputModeTest(getName(), TextField.ANY, "UCB_BASIC_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "Adgj"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "Adgj"); // expected content } /** * Tests setInitialInputMode("UCB_GREEK"). The method is called before * displaying the text field. Greek input mode will be used. */ - private void testUCB_GREEK() { + private void testUCB_GREEK() + { doInputModeTest(getName(), TextField.ANY, "UCB_GREEK", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - GREEK_Adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + GREEK_Adgj); // expected content } /** * Tests setInitialInputMode("UCB_CYRILLIC"). The method is called before * displaying the text field. Cyrillic input mode will be used. */ - private void testUCB_CYRILLIC() { + private void testUCB_CYRILLIC() + { doInputModeTest(getName(), TextField.ANY, "UCB_CYRILLIC", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - CYRILLIC_Adgj); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + CYRILLIC_Adgj); // expected content } /** * Tests setInitialInputMode("UCB_HEBREW"). The method is called before * displaying the text field. Hebrew input mode will be used. */ - private void testUCB_HEBREW() { + private void testUCB_HEBREW() + { doInputModeTest(getName(), TextField.ANY, "UCB_HEBREW", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presess - HEBREW_adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presess + HEBREW_adgj); // expected content } /** * Tests setInitialInputMode("UCB_ARABIC"). The method is called before * displaying the text field. Arabic input mode will be used. */ - private void testUCB_ARABIC() { + private void testUCB_ARABIC() + { doInputModeTest(getName(), TextField.ANY, "UCB_ARABIC", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - ARABIC_adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + ARABIC_adgj); // expected content } /** * Tests setInitialInputMode("UCB_DEVANAGARI"). The method is called before * displaying the text field. Devanagari/Hindi input mode will be used. */ - private void testUCB_DEVANAGARI() { + private void testUCB_DEVANAGARI() + { String expectedContent = "\u0905\u090f\u0915\u091a"; doInputModeTest(getName(), TextField.ANY, "UCB_DEVANAGARI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); // expected content } /** @@ -361,13 +380,14 @@ * displaying the text field. This input mode is not supported in 3.0, so * default input mode will be used. */ - private void testUCB_ARMENIAN() { + private void testUCB_ARMENIAN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_ARMENIAN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -375,13 +395,14 @@ * displaying the text field. This input mode is supported only in Thai * variant; other variants will use the default input mode. */ - private void testUCB_THAI() { + private void testUCB_THAI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_THAI", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -389,13 +410,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testUCB_HIRAGANA() { + private void testUCB_HIRAGANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_HIRAGANA", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -403,13 +425,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testUCB_KATAKANA() { + private void testUCB_KATAKANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_KATAKANA", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -417,13 +440,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_HALFWIDTH_KATAKANA() { + private void testIS_HALFWIDTH_KATAKANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_HALFWIDTH_KATAKANA", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -431,13 +455,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testIS_KANJI() { + private void testIS_KANJI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_KANJI", "", // initial - // content - new int[] {'2', '3', '4', '5',}, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5',}, // key presses + expectedContent); } /** @@ -445,13 +470,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_FULLWIDTH_DIGITS() { + private void testIS_FULLWIDTH_DIGITS() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_FULLWIDTH_DIGITS", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -459,13 +485,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_FULLWIDTH_LATIN() { + private void testIS_FULLWIDTH_LATIN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_FULLWIDTH_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -473,13 +500,14 @@ * before displaying the text field. This input mode is supported only in * China variant; other variants will use the default input mode. */ - private void testIS_SIMPLIFIED_HANZI() { + private void testIS_SIMPLIFIED_HANZI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_SIMPLIFIED_HANZI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -489,13 +517,14 @@ * either Traditional Hongkong or Traditional Taiwan; otherwise the default * input mode will be used. */ - private void testIS_TRADITIONAL_HANZI() { + private void testIS_TRADITIONAL_HANZI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_TRADITIONAL_HANZI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } @@ -503,37 +532,40 @@ * Tests setInitialInputMode(null). The method is called before displaying * the text field. This default input mode will be used. */ - private void testnull() { + private void testnull() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, null, "", // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode("UNKNOWN"). The method is called before * displaying the text field. The default input mode will be used. */ - private void testUNKNOWN() { + private void testUNKNOWN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UNKNOWN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode(""). The method is called before displaying the * text field. The default input mode will be used. */ - private void testempty() { + private void testempty() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "", "", // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -541,17 +573,18 @@ * visible. Setting the initial input mode has no effect until focus is * changed temporarily elsewhere and then back to TextField. */ - private void testinputModeChange() { + private void testinputModeChange() + { String expectedContent = "Adgj2345"; doInputModeSequenceTest(getName(), TextField.ANY, - new String[] {"IS_LATIN_DIGITS" }, "", // initial content - new int[] {'2', '3', '4', '5', }, true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + new String[] {"IS_LATIN_DIGITS" }, "", // initial content + new int[] {'2', '3', '4', '5', }, true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -559,17 +592,18 @@ * obscured the editor. Setting the initial input mode has no effect until * focus is changed temporarily elsewhere and then back to TextField. */ - private void testinputModeAndMenuOpen() { + private void testinputModeAndMenuOpen() + { String expectedContent = "Adgj2345"; doInputModeSequenceTest(getName(), TextField.ANY, - new String[] {"IS_LATIN_DIGITS" }, "", // initial content - new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5' ,}, true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + new String[] {"IS_LATIN_DIGITS" }, "", // initial content + new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5' ,}, true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -577,15 +611,18 @@ * changed after each setting to make the input mode effective. Setting the * initial input mode has no effect in NUMERIC text field. */ - private void testinputModesInNumber() { - doInputModeSequenceTest(getName(), TextField.NUMERIC, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + private void testinputModesInNumber() + { + doInputModeSequenceTest(getName(), TextField.NUMERIC, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -593,15 +630,18 @@ * changed after each setting to make the input mode effective. Setting the * initial input mode has no effect in DECIMAL text field. */ - private void testinputModesInDecimal() { - doInputModeSequenceTest(getName(), TextField.DECIMAL, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + private void testinputModesInDecimal() + { + doInputModeSequenceTest(getName(), TextField.DECIMAL, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -609,15 +649,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInEmailaddr() { - doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInEmailaddr() + { + doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -627,15 +670,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInEmailaddr2() { + private void testinputModesInEmailaddr2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -643,15 +689,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInUrl() { - doInputModeSequenceTest(getName(), TextField.URL, new String[] { - "NONE", // default input mode in ANY text field - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInUrl() + { + doInputModeSequenceTest(getName(), TextField.URL, new String[] + { + "NONE", // default input mode in ANY text field + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -661,15 +710,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInUrl2() { + private void testinputModesInUrl2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.URL, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.URL, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -677,15 +729,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInPassword() { - doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] { - "NONE", // default input mode in ANY text field - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInPassword() + { + doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] + { + "NONE", // default input mode in ANY text field + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -695,28 +750,34 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInPassword2() { + private void testinputModesInPassword2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // pressed keys (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // pressed keys (per input mode) + expectedContent); } /** * Tests different sequential input modes in ANY text field. Focus is * changed after each setting to make the input mode effective. */ - private void testinputModesInAny() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS" , }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // pressed keys (per input mode) - GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); + private void testinputModesInAny() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS" , + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // pressed keys (per input mode) + GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); // expected content } @@ -726,15 +787,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInAny2() { + private void testinputModesInAny2() + { String expectedContent = "Adgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "NONE", // starts from default input mode - "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", - "UCB_THAI", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "NONE", // starts from default input mode + "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", + "UCB_THAI", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -743,15 +807,17 @@ * field. Focus is changed after each setting to make the input mode * effective. */ - private void testinputModesInCapsSentence() { + private void testinputModesInCapsSentence() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; doInputModeSequenceTest(getName(), TextField.INITIAL_CAPS_SENTENCE, - new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -759,15 +825,17 @@ * ignored if the INITIAL_CAPS_WORD modifier is defined in ANY text field. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsWord() { + private void testinputModesInCapsWord() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; doInputModeSequenceTest(getName(), TextField.INITIAL_CAPS_WORD, - new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -776,14 +844,16 @@ * the modifier is meaningless in EMAILADDR. Focus is changed after each * setting to make the input mode effective. */ - private void testinputModesInCapsSentenceEmailaddr() { + private void testinputModesInCapsSentenceEmailaddr() + { doInputModeSequenceTest(getName(), TextField.EMAILADDR - | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", - "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", + "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -792,27 +862,32 @@ * modifier is meaningless in URL. Focus is changed after each setting to * make the input mode effective. */ - private void testinputModesInCapsSentenceUrl() { + private void testinputModesInCapsSentenceUrl() + { doInputModeSequenceTest(getName(), TextField.URL - | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", - "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", + "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** * Tests different textual input modes after IS_LATIN_DIGITS. Focus is * changed after each setting to make the input mode effective. */ - private void testinputModesAfterNumberMode() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", "MIDP_UPPERCASE_LATIN", "IS_LATIN_DIGITS", - "MIDP_LOWERCASE_LATIN", "IS_LATIN_DIGITS", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, "2345ADGJ2345adgj2345" - + ARABIC_adgj); + private void testinputModesAfterNumberMode() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", "MIDP_UPPERCASE_LATIN", "IS_LATIN_DIGITS", + "MIDP_LOWERCASE_LATIN", "IS_LATIN_DIGITS", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, "2345ADGJ2345adgj2345" + + ARABIC_adgj); } /** @@ -821,29 +896,35 @@ * Japanese or Chinese input mode will have effect only in the corresponding * variants. */ - private void testinputModesAfterNumberMode2() { + private void testinputModesAfterNumberMode2() + { String expectedContent = "23452345234523452345234523452345"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", "IS_LATIN_DIGITS", - "IS_KANJI", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "IS_LATIN_DIGITS", "UCB_THAI", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", "IS_LATIN_DIGITS", + "IS_KANJI", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "IS_LATIN_DIGITS", "UCB_THAI", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** * Tests latin input modes after other input modes. Focus is changed after * each setting to make the input mode effective. */ - private void testinputLatinAfterOtherModes() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_HEBREW", "IS_LATIN", "UCB_GREEK", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", "UCB_CYRILLIC", - "IS_LATIN", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, HEBREW_adgj + "adgj" - + GREEK_adgj + "ADGJ" + ARABIC_adgj + "adgj" - + CYRILLIC_adgj + "adgj"); + private void testinputLatinAfterOtherModes() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_HEBREW", "IS_LATIN", "UCB_GREEK", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", "UCB_CYRILLIC", + "IS_LATIN", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, HEBREW_adgj + "adgj" + + GREEK_adgj + "ADGJ" + ARABIC_adgj + "adgj" + + CYRILLIC_adgj + "adgj"); } /** @@ -852,30 +933,36 @@ * Japanese or Chinese input mode will have effect only in the corresponding * variants. */ - private void testinputLatinAfterOtherModes2() { + private void testinputLatinAfterOtherModes2() + { String expectedContent = "Adgjadgjadgjadgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", "IS_KANJI", - "MIDP_LOWERCASE_LATIN", "IS_FULLWIDTH_DIGITS", - "MIDP_LOWERCASE_LATIN", "UCB_THAI", "MIDP_LOWERCASE_LATIN", }, - "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", "IS_KANJI", + "MIDP_LOWERCASE_LATIN", "IS_FULLWIDTH_DIGITS", + "MIDP_LOWERCASE_LATIN", "UCB_THAI", "MIDP_LOWERCASE_LATIN", + }, + "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** * Tests null input mode after different input modes in ANY text field. */ - private void testinputModeNullSetting() { + private void testinputModeNullSetting() + { String expectedContent = "2345adgj" + ARABIC_adgj + "adgj" - + "adgjadgjadgjadgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", null, "UCB_ARABIC", null, - "IS_SIMPLIFIED_HANZI", null, "IS_HALFWIDTH_KATAKANA", null, - "IS_FULLWIDTH_DIGITS", null, "UCB_THAI", null, }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, expectedContent); + + "adgjadgjadgjadgjadgjadgjadgjadgj"; + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", null, "UCB_ARABIC", null, + "IS_SIMPLIFIED_HANZI", null, "IS_HALFWIDTH_KATAKANA", null, + "IS_FULLWIDTH_DIGITS", null, "UCB_THAI", null, + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, expectedContent); } /** @@ -883,13 +970,16 @@ * text field. Note: after a comma and space the input mode changes to Text * case (not sure whether this is correct behaviour) */ - private void testcommaInLowerAndUpperCase() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", }, "", // initial - // content - new int[] {'2', '3', '1', '0', '4', '5', }, false, - // key presses (per input mode) - "ad. GjAD. Gj"); + private void testcommaInLowerAndUpperCase() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + }, "", // initial + // content + new int[] {'2', '3', '1', '0', '4', '5', }, false, + // key presses (per input mode) + "ad. GjAD. Gj"); } /** @@ -898,15 +988,18 @@ * initial input language got from display language arabic => initial input * langauge got from global input language */ - private void testinputModesWithArabicInputLanguage() { + private void testinputModesWithArabicInputLanguage() + { changeInputLanguage(4, 1); // => Arabic input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(5, 10); // => back to English input language } @@ -917,15 +1010,18 @@ * initial input language got from display language arabic => initial input * langauge got from hard-coded default (Arabic) */ - private void testinputModesWithCyrillicInputLanguage() { + private void testinputModesWithCyrillicInputLanguage() + { changeInputLanguage(4, 2); // => Cyrillic input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(4, 10); // => back to English input language } @@ -936,15 +1032,18 @@ * latin => initial input language got from global input language arabic => * initial input langauge got from hard-coded default (Arabic) */ - private void testinputModesWithDanskInputLanguage() { + private void testinputModesWithDanskInputLanguage() + { changeInputLanguage(4, 8); // => Dansk input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(4, 10); // => back to English input language } @@ -954,7 +1053,8 @@ * TextField to the form, and then making the form current. The input text * must be uppercase. */ - private void testUppercaseBeforeMakingFormCurrent() { + private void testUppercaseBeforeMakingFormCurrent() + { boolean passed = true; int[] pressedKeys = new int[] {'2', '3', '4', '5', }; String expectedContent = "ADGJ"; @@ -962,12 +1062,13 @@ TextField textField = null; Form form = null; - try { + try + { // Create a form and a text field, and append text field to form - form = new Form(getName()); + form = new Form(getName()); - textField = new TextField("Text field", "", normalSize, TextField.ANY); - form.append(textField); + textField = new TextField("Text field", "", normalSize, TextField.ANY); + form.append(textField); // set the initial input mode before the form is current textField.setInitialInputMode("MIDP_UPPERCASE_LATIN"); @@ -977,8 +1078,10 @@ setCurrent(form); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -988,14 +1091,15 @@ passed = textField.getString().equals(expectedContent); } - catch (Exception exc) { + catch(Exception exc) + { print(getName() + " test failed: " + exc.toString()); - print(exc); + print(exc); passed = false; } assertTrue(getName() + " test " + "content: " + textField.getString() - + ", expected: " + expectedContent, passed); + + ", expected: " + expectedContent, passed); } /** @@ -1020,24 +1124,28 @@ * Expected content of TextField */ private void doInputModeTest(String testCaseName, int constraints, - String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String initialInputMode, String initialContent, int[] pressedKeys, + String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields Form form = new Form(testCaseName); - TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); - TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); + TextField textField = new TextField("Text field", initialContent, + normalSize, constraints); + TextField otherField = new TextField("Other field", "", normalSize, + TextField.ANY); // Set initial input mode before displaying TextField - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textField.setInitialInputMode(initialInputMode); } form.append(textField); @@ -1047,8 +1155,10 @@ block(CHANGE_DISPLAYABLE_DELAY); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1056,68 +1166,75 @@ // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); } /** - * Private method for testing initial input mode. Creates TextField and sets - * the initial input mode before displaying it. Generates the given key - * presses. At the end compares the content of TextField to the expected - * content, unless the expected content is null; in that case takes a - * screenshot. - * - * @param testCaseName - * Name of the test case - * @param constraints - * Combination of TextField.ANY,... - * @param initialInputMode - * Intial input mode to be set, e.g "IS_LATIN"; "NONE" means that - * setInitialInputMode is not called at all - * @param initialContent - * Initial context of TextField - * @param pressedKeys - * Array of key presses to be generated - * @param expectedContent - * Expected content of TextField - */ + * Private method for testing initial input mode. Creates TextField and sets + * the initial input mode before displaying it. Generates the given key + * presses. At the end compares the content of TextField to the expected + * content, unless the expected content is null; in that case takes a + * screenshot. + * + * @param testCaseName + * Name of the test case + * @param constraints + * Combination of TextField.ANY,... + * @param initialInputMode + * Intial input mode to be set, e.g "IS_LATIN"; "NONE" means that + * setInitialInputMode is not called at all + * @param initialContent + * Initial context of TextField + * @param pressedKeys + * Array of key presses to be generated + * @param expectedContent + * Expected content of TextField + */ private void doInputModeTest2(String testCaseName, int constraints, - String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String initialInputMode, String initialContent, int[] pressedKeys, + String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields - Form form = new Form(testCaseName); - TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); - TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); - form.append(textField); - form.append(otherField); + Form form = new Form(testCaseName); + TextField textField = new TextField("Text field", initialContent, + normalSize, constraints); + TextField otherField = new TextField("Other field", "", normalSize, + TextField.ANY); + form.append(textField); + form.append(otherField); // Set initial input mode before displaying TextField - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textField.setInitialInputMode(initialInputMode); } setCurrent(form); block(CHANGE_DISPLAYABLE_DELAY); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1125,13 +1242,14 @@ // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); @@ -1164,35 +1282,41 @@ * Expected content of TextField */ private void doInputModeSequenceTest(String testCaseName, int constraints, - String[] nextInputModes, String initialContent, int[] pressedKeys, - boolean beforeAndAfter, String expectedContent) { + String[] nextInputModes, String initialContent, int[] pressedKeys, + boolean beforeAndAfter, String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields Form form = new Form(testCaseName); TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); + normalSize, constraints); form.append(textField); TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); + TextField.ANY); form.append(otherField); // Display the form setCurrent(form); block(CHANGE_DISPLAYABLE_DELAY); - for (int m = 0; m < nextInputModes.length; m++) { + for(int m = 0; m < nextInputModes.length; m++) + { // Set initial input mode while the original TextField is // visible textField.setInitialInputMode(nextInputModes[m]); - if (beforeAndAfter) { + if(beforeAndAfter) + { // Do key presses (input mode setting not yet effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1206,8 +1330,10 @@ key(Key.UpArrow); // Do key presses again (now input mode setting is effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1216,13 +1342,14 @@ // Check the result of all key presses (i.e. the used input modes) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); @@ -1243,55 +1370,62 @@ * @return result Returns whether test case passed or failed */ private boolean checkResult(String testCaseName, TextField textBox, - String expectedContent, boolean takeScreenshot) { + String expectedContent, boolean takeScreenshot) + { - boolean passed = true; + boolean passed = true; - // Check the expected content - if (expectedContent != null) { - if (!expectedContent.equals(textBox.getString())) { - passed = false; - print(testCaseName + " test " - + " failed: content: " + textBox.getString() - + ", expected: " + expectedContent); - } - } + // Check the expected content + if(expectedContent != null) + { + if(!expectedContent.equals(textBox.getString())) + { + passed = false; + print(testCaseName + " test " + + " failed: content: " + textBox.getString() + + ", expected: " + expectedContent); + } + } - // Take the screenshot and compare it with the previous one - if (takeScreenshot) { - if (!takeScreenshot(testCaseName + ".gif")) { - passed = false; - print(testCaseName + " test " - + " failed: screenshot does not match"); + // Take the screenshot and compare it with the previous one + if(takeScreenshot) + { + if(!takeScreenshot(testCaseName + ".gif")) + { + passed = false; + print(testCaseName + " test " + + " failed: screenshot does not match"); - print("If failure is caused by different " - + "special characters which are show in the cell at " - + "the top of the Edit Menu, please IGNORE the result" - + " and treat the test as PASSED!"); - } - } + print("If failure is caused by different " + + "special characters which are show in the cell at " + + "the top of the Edit Menu, please IGNORE the result" + + " and treat the test as PASSED!"); + } + } - if (passed) { - print(testCaseName + " test succeeded: " + textBox.getString()); - } - return passed; - } + if(passed) + { + print(testCaseName + " test succeeded: " + textBox.getString()); + } + return passed; + } /** - * Private method for changing the input language - * - * @param positionInEditOptions - * Position of "Input language" menu item - * @param positionInLanguageList - * Position of the desired language - */ + * Private method for changing the input language + * + * @param positionInEditOptions + * Position of "Input language" menu item + * @param positionInLanguageList + * Position of the desired language + */ private void changeInputLanguage(int positionInEditOptions, - int positionInLanguageList) { + int positionInLanguageList) + { // Create a temporary TextBox in order to be able to set // the global input language TextBox other = new TextBox("Input language setting", - "Temporary text box", normalSize, TextField.ANY); + "Temporary text box", normalSize, TextField.ANY); // Display the text box setCurrent(other); @@ -1299,7 +1433,8 @@ // Open EditOptions menu and select Input language menu item key(Key.Edit); - for (int i = 0; i < positionInEditOptions; i++) { + for(int i = 0; i < positionInEditOptions; i++) + { key(Key.DownArrow); } block(KEYEVENT_DELAY); @@ -1307,7 +1442,8 @@ key(Key.Select); // Select the desired input language in the language list - for (int i = 1; i < positionInLanguageList; i++) { + for(int i = 1; i < positionInLanguageList; i++) + { key(Key.DownArrow); } block(KEYEVENT_DELAY); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src_j2me/com/nokia/mj/impl/utils/OmjTestRunner.java --- a/javauis/lcdui_qt/tsrc/src_j2me/com/nokia/mj/impl/utils/OmjTestRunner.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src_j2me/com/nokia/mj/impl/utils/OmjTestRunner.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -39,7 +39,8 @@ import javax.microedition.io.Connector; -public class OmjTestRunner extends TestRunner { +public class OmjTestRunner extends TestRunner +{ protected static final String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); protected static String RESULTS_DIR = null; @@ -51,23 +52,29 @@ protected Vector iTests = new Vector(); protected String iTestClassName = null; - static{ - String platform = System.getProperty("os.name"); + static + { + String platform = System.getProperty("os.name"); - if (platform != null && platform.equalsIgnoreCase("linux")) { - String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); - RESULTS_DIR = "file://"; - RESULTS_DIR = RESULTS_DIR + (JAVA_BIN_ROOT == null? ".": JAVA_BIN_ROOT) + "/"; - }else{ - RESULTS_DIR = System.getProperty("fileconn.dir.photos"); - } + if(platform != null && platform.equalsIgnoreCase("linux")) + { + String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); + RESULTS_DIR = "file://"; + RESULTS_DIR = RESULTS_DIR + (JAVA_BIN_ROOT == null? ".": JAVA_BIN_ROOT) + "/"; + } + else + { + RESULTS_DIR = System.getProperty("fileconn.dir.photos"); + } } - protected OmjTestRunner() { + protected OmjTestRunner() + { super(); } - public OmjTestRunner(Test aSuite) { + public OmjTestRunner(Test aSuite) + { super(); iSuite = aSuite; setTestClassName(aSuite.toString()); @@ -75,80 +82,96 @@ System.out.println("Results: "+iResultFilename); } - public void setTestClassName(String aTestClassName){ - iResultFilename = RESULTS_DIR + "results/" + aTestClassName + ".xml"; - iTestClassName = aTestClassName; + public void setTestClassName(String aTestClassName) + { + iResultFilename = RESULTS_DIR + "results/" + aTestClassName + ".xml"; + iTestClassName = aTestClassName; } - public OmjTestRunner(PrintStream aWriter) { + public OmjTestRunner(PrintStream aWriter) + { super(aWriter); } - public void endTest(Test aTest) { + public void endTest(Test aTest) + { System.out.println("endtest"); iTests.addElement(aTest); } - public void writeResultFile(TestResult aResult) { + public void writeResultFile(TestResult aResult) + { iEndTime = System.currentTimeMillis(); String xmlResult = toString(iSuite, iTestClassName, iTests, aResult, iEndTime - iStartTime); FileConnection fileConn = null; OutputStream outStream = null; - try{ - //System.out.println("RESULTS_DIR: " + RESULTS_DIR); - fileConn = (FileConnection) Connector.open(RESULTS_DIR,Connector.READ_WRITE); - if(!fileConn.exists()){ - fileConn.mkdir(); - } - fileConn.close(); - - RESULTS_DIR = RESULTS_DIR + "results/"; - fileConn = (FileConnection) Connector.open(RESULTS_DIR,Connector.READ_WRITE); - if(!fileConn.exists()){ - fileConn.mkdir(); - } - fileConn.close(); - - //System.out.println("iResultFilename: " + iResultFilename); - fileConn = (FileConnection) Connector.open(iResultFilename,Connector.READ_WRITE); - if(!fileConn.exists()){ - fileConn.create(); - }else{ - fileConn.delete(); - fileConn.create(); - } - outStream = fileConn.openOutputStream(); - outStream.write(xmlResult.getBytes(RESULT_FILE_ENCODING)); - outStream.flush(); + try + { + //System.out.println("RESULTS_DIR: " + RESULTS_DIR); + fileConn = (FileConnection) Connector.open(RESULTS_DIR,Connector.READ_WRITE); + if(!fileConn.exists()) + { + fileConn.mkdir(); + } + fileConn.close(); + + RESULTS_DIR = RESULTS_DIR + "results/"; + fileConn = (FileConnection) Connector.open(RESULTS_DIR,Connector.READ_WRITE); + if(!fileConn.exists()) + { + fileConn.mkdir(); + } + fileConn.close(); + + //System.out.println("iResultFilename: " + iResultFilename); + fileConn = (FileConnection) Connector.open(iResultFilename,Connector.READ_WRITE); + if(!fileConn.exists()) + { + fileConn.create(); + } + else + { + fileConn.delete(); + fileConn.create(); + } + outStream = fileConn.openOutputStream(); + outStream.write(xmlResult.getBytes(RESULT_FILE_ENCODING)); + outStream.flush(); } - catch(IOException ex){ - throw new RuntimeException - ("Writing results to " + iResultFilename + " failed: " + ex); + catch(IOException ex) + { + throw new RuntimeException + ("Writing results to " + iResultFilename + " failed: " + ex); } - finally{ - try{ - if(null != fileConn) - fileConn.close(); - if(null != outStream) - outStream.close(); - } - catch (IOException ioe) {} + finally + { + try + { + if(null != fileConn) + fileConn.close(); + if(null != outStream) + outStream.close(); + } + catch(IOException ioe) {} } } // Removes errors and failures from aTests which contain all tests. protected static void removeErrorsAndFailures - (Vector aTests, TestResult aResult) { + (Vector aTests, TestResult aResult) + { Enumeration e = aResult.errors(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); TestCase testCase = (TestCase)testFailure.failedTest(); aTests.removeElement(testCase); } e = aResult.failures(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); TestCase testCase = (TestCase)testFailure.failedTest(); aTests.removeElement(testCase); @@ -156,36 +179,40 @@ } protected static String toString - (Test aSuite, String aTestClassName, Vector aTests, TestResult aResult, long aTime) { + (Test aSuite, String aTestClassName, Vector aTests, TestResult aResult, long aTime) + { removeErrorsAndFailures(aTests, aResult); StringBuffer buf = new StringBuffer - ("\n"); + ("\n"); buf.append("\n"); + .append("\" tests=\"").append(aResult.runCount()) + .append("\" time=\"").append(aTime/1000.0) + .append("\" timestamp=\"").append(new Date().toString()) + .append("\">\n"); Enumeration e = aTests.elements(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestCase testCase = (TestCase)e.nextElement(); buf.append(toString(testCase)); } e = aResult.errors(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); buf.append(toString(testFailure, "error")); } e = aResult.failures(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); buf.append(toString(testFailure, "failure")); } @@ -194,55 +221,70 @@ return buf.toString(); } - protected static String toString(Test aTest) { + protected static String toString(Test aTest) + { StringBuffer buf = new StringBuffer(""); TestCase testCase = null; - if (aTest instanceof TestCase) { + if(aTest instanceof TestCase) + { testCase = (TestCase)aTest; } - if (testCase != null) { + if(testCase != null) + { buf.append(" \n"); + .append("\" name=\"").append(testCase.getName()) + .append("\"/>\n"); } return buf.toString(); } - protected static String toString(TestFailure aFailure, String aFailureTag) { + protected static String toString(TestFailure aFailure, String aFailureTag) + { StringBuffer buf = new StringBuffer(""); TestCase testCase = (TestCase)aFailure.failedTest(); Throwable thrownException = aFailure.thrownException(); - if (testCase != null) { + if(testCase != null) + { buf.append(" \n"); - } else { + } + else + { buf.append("\">\n") - .append(toString(thrownException, aFailureTag)) - .append(" \n"); + .append(toString(thrownException, aFailureTag)) + .append(" \n"); } - } else if (thrownException == null) { + } + else if(thrownException == null) + { buf.append(toString(thrownException, aFailureTag)); } return buf.toString(); } - protected static String toString(Throwable aThrowable, String aFailureTag) { + protected static String toString(Throwable aThrowable, String aFailureTag) + { StringBuffer buf = new StringBuffer(""); - if (aThrowable != null) { + if(aThrowable != null) + { String throwableString = aThrowable.toString(); - try { + try + { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); aThrowable.printStackTrace(new PrintStream(outputStream)); throwableString = outputStream.toString(); - } catch (Throwable t) { + } + catch(Throwable t) + { // ignore } buf.append(" <").append(aFailureTag).append(" message=\"").append(aThrowable.getMessage()) - .append("\" type=\"").append(aThrowable.getClass().getName()) - .append("\">").append(throwableString) - .append("\n"); + .append("\" type=\"").append(aThrowable.getClass().getName()) + .append("\">").append(throwableString) + .append("\n"); } return buf.toString(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/src_j2se/com/nokia/mj/impl/utils/OmjTestRunner.java --- a/javauis/lcdui_qt/tsrc/src_j2se/com/nokia/mj/impl/utils/OmjTestRunner.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/src_j2se/com/nokia/mj/impl/utils/OmjTestRunner.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ @@ -34,7 +34,8 @@ import java.util.Vector; -public class OmjTestRunner extends TestRunner { +public class OmjTestRunner extends TestRunner +{ protected static final String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); protected static String RESULTS_DIR = null; @@ -46,71 +47,86 @@ protected Vector iTests = new Vector(); protected String iTestClassName = null; - static{ - String platform = System.getProperty("os.name"); + static + { + String platform = System.getProperty("os.name"); - if (platform != null && platform.equalsIgnoreCase("linux")) { - String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); - RESULTS_DIR = ""; - RESULTS_DIR = RESULTS_DIR + (JAVA_BIN_ROOT == null? ".": JAVA_BIN_ROOT) + "/"; - }else{ - RESULTS_DIR = System.getProperty("fileconn.dir.photos"); - } + if(platform != null && platform.equalsIgnoreCase("linux")) + { + String JAVA_BIN_ROOT = System.getProperty("JAVA_BIN_ROOT"); + RESULTS_DIR = ""; + RESULTS_DIR = RESULTS_DIR + (JAVA_BIN_ROOT == null? ".": JAVA_BIN_ROOT) + "/"; + } + else + { + RESULTS_DIR = System.getProperty("fileconn.dir.photos"); + } } - protected OmjTestRunner() { + protected OmjTestRunner() + { super(); } - public OmjTestRunner(Test aSuite) { + public OmjTestRunner(Test aSuite) + { super(); iSuite = aSuite; setTestClassName(aSuite.toString()); iStartTime = System.currentTimeMillis(); } - public void setTestClassName(String aTestClassName){ - iResultFilename = RESULTS_DIR + "results/TEST-com.nokia.openlcdui.mt.AllTests.xml"; - iTestClassName = aTestClassName; + public void setTestClassName(String aTestClassName) + { + iResultFilename = RESULTS_DIR + "results/TEST-com.nokia.openlcdui.mt.AllTests.xml"; + iTestClassName = aTestClassName; } - public OmjTestRunner(PrintStream aWriter) { + public OmjTestRunner(PrintStream aWriter) + { super(aWriter); } - public void endTest(Test aTest) { + public void endTest(Test aTest) + { iTests.addElement(aTest); } - public void writeResultFile(TestResult aResult) { - try { + public void writeResultFile(TestResult aResult) + { + try + { iEndTime = System.currentTimeMillis(); String xmlResult = toString(iSuite, iTestClassName, iTests, aResult, iEndTime - iStartTime); - + FileWriter fstream = new FileWriter(iResultFilename); BufferedWriter out = new BufferedWriter(fstream); out.write(xmlResult); out.close(); } - catch (Exception e){//Catch exception if any + catch(Exception e) //Catch exception if any + { throw new RuntimeException - ("Writing results to " + iResultFilename + " failed: " + e); + ("Writing results to " + iResultFilename + " failed: " + e); } } // Removes errors and failures from aTests which contain all tests. protected static void removeErrorsAndFailures - (Vector aTests, TestResult aResult) { + (Vector aTests, TestResult aResult) + { Enumeration e = aResult.errors(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); TestCase testCase = (TestCase)testFailure.failedTest(); aTests.removeElement(testCase); } e = aResult.failures(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); TestCase testCase = (TestCase)testFailure.failedTest(); aTests.removeElement(testCase); @@ -118,36 +134,40 @@ } protected static String toString - (Test aSuite, String aTestClassName, Vector aTests, TestResult aResult, long aTime) { + (Test aSuite, String aTestClassName, Vector aTests, TestResult aResult, long aTime) + { removeErrorsAndFailures(aTests, aResult); StringBuffer buf = new StringBuffer - ("\n"); + ("\n"); buf.append("\n"); + .append("\" tests=\"").append(aResult.runCount()) + .append("\" time=\"").append(aTime/1000.0) + .append("\" timestamp=\"").append(new Date().toString()) + .append("\">\n"); Enumeration e = aTests.elements(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestCase testCase = (TestCase)e.nextElement(); buf.append(toString(testCase)); } e = aResult.errors(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); buf.append(toString(testFailure, "error")); } e = aResult.failures(); - while (e.hasMoreElements()) { + while(e.hasMoreElements()) + { TestFailure testFailure = (TestFailure)e.nextElement(); buf.append(toString(testFailure, "failure")); } @@ -156,66 +176,83 @@ return buf.toString(); } - protected static String toString(Test aTest) { + protected static String toString(Test aTest) + { StringBuffer buf = new StringBuffer(""); TestCase testCase = null; - if (aTest instanceof TestCase) { + if(aTest instanceof TestCase) + { testCase = (TestCase)aTest; } - if (testCase != null) { + if(testCase != null) + { buf.append(" \n"); + .append("\" name=\"").append(testCase.getName()) + .append("\"/>\n"); } return buf.toString(); } - protected static String toString(TestFailure aFailure, String aFailureTag) { + protected static String toString(TestFailure aFailure, String aFailureTag) + { StringBuffer buf = new StringBuffer(""); TestCase testCase = (TestCase)aFailure.failedTest(); Throwable thrownException = aFailure.thrownException(); - if (testCase != null) { + if(testCase != null) + { buf.append(" \n"); - } else { + } + else + { buf.append("\">\n") - .append(toString(thrownException, aFailureTag)) - .append(" \n"); + .append(toString(thrownException, aFailureTag)) + .append(" \n"); } - } else if (thrownException == null) { + } + else if(thrownException == null) + { buf.append(toString(thrownException, aFailureTag)); } return buf.toString(); } - protected static String toString(Throwable aThrowable, String aFailureTag) { + protected static String toString(Throwable aThrowable, String aFailureTag) + { StringBuffer buf = new StringBuffer(""); - if (aThrowable != null) { + if(aThrowable != null) + { String throwableString = aThrowable.toString(); String throwableMessage = aThrowable.getMessage(); - try { + try + { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); aThrowable.printStackTrace(new PrintStream(outputStream)); throwableString = outputStream.toString(); - } catch (Throwable t) { + } + catch(Throwable t) + { // ignore } String message = ""; String throwable = ""; - - if (throwableMessage != null) { + + if(throwableMessage != null) + { message = throwableMessage.replaceAll("<", "<").replaceAll(">", ">"); } - if (throwableString != null) { + if(throwableString != null) + { throwable = throwableString.replaceAll("<", "<").replaceAll(">", ">"); } - + buf.append(" <").append(aFailureTag).append(" message=\"").append(message) - .append("\" type=\"").append(aThrowable.getClass().getName()) - .append("\">").append(throwable) - .append("\n"); + .append("\" type=\"").append(aThrowable.getClass().getName()) + .append("\">").append(throwable) + .append("\n"); } return buf.toString(); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/alert/AlertSTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/alert/AlertSTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/alert/AlertSTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.alert; @@ -32,19 +32,20 @@ * * @created 2008-07-23 */ -public class AlertSTest extends UITestBase { +public class AlertSTest extends UITestBase +{ private static String shortString = "Lorem ipsum"; private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; private TextBox textBox; private Command exitCmd; @@ -52,7 +53,8 @@ /** * Constructor. */ - public AlertSTest() { + public AlertSTest() + { } /** @@ -61,21 +63,24 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public AlertSTest(String sTestName, TestMethod rTestMethod) { + public AlertSTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); exitCmd = new Command("exit", "exit", Command.EXIT, 0); textBox = new TextBox("textBox", "", 100, 0); textBox.addCommand(exitCmd); } - protected void tearDown() throws Exception { + protected void tearDown() throws Exception + { textBox.removeCommand(exitCmd); textBox = null; exitCmd = null; @@ -87,11 +92,14 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); - aSuite.addTest(new AlertSTest("testMethod", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new AlertSTest("testMethod", new TestMethod() + { + public void run(TestCase tc) + { ((AlertSTest) tc).testMethod(); } })); @@ -102,7 +110,8 @@ /** * Test method. */ - public void testMethod() { + public void testMethod() + { setCurrent(textBox); Gauge smallInd = new Gauge(null, false, 100, 0); @@ -110,16 +119,20 @@ Image smallImg = null; Image largeImg = null; - try { + try + { smallImg = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } - try { + try + { largeImg = Image.createImage("200x200.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 200x200.png"); } @@ -141,51 +154,57 @@ boolean match = true; - for (int i = 0; i < textArr.length; i++) { - switch (i) { + for(int i = 0; i < textArr.length; i++) + { + switch(i) + { + case 0: + alert.setString(null); + break; + case 1: + alert.setString(shortString); + break; + case 2: + alert.setString(longString); + break; + default: + break; + } + for(int j = 0; j < imgArr.length; j++) + { + switch(j) + { case 0: - alert.setString(null); + alert.setImage(null); break; case 1: - alert.setString(shortString); + alert.setImage(smallImg); break; case 2: - alert.setString(longString); + alert.setImage(largeImg); break; default: break; - } - for (int j = 0; j < imgArr.length; j++) { - switch (j) { + } + for(int k = 0; k < indArr.length; k++) + { + switch(k) + { case 0: - alert.setImage(null); + alert.setIndicator(null); break; case 1: - alert.setImage(smallImg); + alert.setIndicator(smallInd); break; case 2: - alert.setImage(largeImg); + alert.setIndicator(largeInd); break; default: break; - } - for (int k = 0; k < indArr.length; k++) { - switch (k) { - case 0: - alert.setIndicator(null); - break; - case 1: - alert.setIndicator(smallInd); - break; - case 2: - alert.setIndicator(largeInd); - break; - default: - break; } block(CHANGE_DISPLAYABLE_DELAY); // 0.3 sec String filename = fnamePrefix - + textArr[i] + imgArr[j] + indArr[k] + fnamePostfix; + + textArr[i] + imgArr[j] + indArr[k] + fnamePostfix; match = takeScreenshot(filename) && match; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/form/FormSTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/form/FormSTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/form/FormSTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.form; @@ -33,7 +33,8 @@ * * @created 2008-07-23 */ -public class FormSTest extends UITestBase { +public class FormSTest extends UITestBase +{ private Command exitCmd; @@ -45,7 +46,8 @@ /** * Constructor. */ - public FormSTest() { + public FormSTest() + { } /** @@ -54,27 +56,33 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public FormSTest(String sTestName, TestMethod rTestMethod) { + public FormSTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); exitCmd = new Command("exit", "exit", Command.EXIT, 0); - try { + try + { smallImage = Image.createImage("32x32.jpeg"); } - catch (IOException e) { + catch(IOException e) + { e.printStackTrace(); } - try { + try + { mediumImage = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { e.printStackTrace(); } } @@ -85,162 +93,172 @@ * * @return New testsuite. */ - public Test suite() { - TestSuite aSuite = new TestSuite(); + public Test suite() + { + TestSuite aSuite = new TestSuite(); - aSuite.addTest(new FormSTest("plainStringItemTest", new TestMethod() { - public void run(TestCase tc) { - ((FormSTest) tc).plainStringItemTest(); - } - })); - aSuite.addTest(new FormSTest("plainImageItemTest", new TestMethod() { - public void run(TestCase tc) { - ((FormSTest) tc).plainImageItemTest(); - } - })); - aSuite.addTest(new FormSTest("stringImageButtonTest", new TestMethod() { - public void run(TestCase tc) { - ((FormSTest) tc).stringImageButtonTest(); - } - })); + aSuite.addTest(new FormSTest("plainStringItemTest", new TestMethod() + { + public void run(TestCase tc) + { + ((FormSTest) tc).plainStringItemTest(); + } + })); + aSuite.addTest(new FormSTest("plainImageItemTest", new TestMethod() + { + public void run(TestCase tc) + { + ((FormSTest) tc).plainImageItemTest(); + } + })); + aSuite.addTest(new FormSTest("stringImageButtonTest", new TestMethod() + { + public void run(TestCase tc) + { + ((FormSTest) tc).stringImageButtonTest(); + } + })); - return aSuite; - } + return aSuite; + } /** - * Makes screenshot which shows different aspects of PLAIN StringItem. - */ - void plainStringItemTest() { - form = new Form("Form test"); + * Makes screenshot which shows different aspects of PLAIN StringItem. + */ + void plainStringItemTest() + { + form = new Form("Form test"); - String img = "FormPlainStringItem.gif"; - String fewLines = "Loremipsumdolorsitamet" - + "consectetuer adipiscing elit."; - StringItem st1 = new StringItem("header", "Text 1"); - StringItem st2 = new StringItem(null, "Text 2"); - st2.setLayout(Item.LAYOUT_TOP); - StringItem st3 = new StringItem(null, "Text 3"); - st3.setLayout(Item.LAYOUT_VCENTER); - StringItem st4 = new StringItem(null, "Text 4"); - st4.setLayout(Item.LAYOUT_CENTER); - StringItem st5 = new StringItem("header 5", "Text 5"); - StringItem st6 = new StringItem(null, "Text 6"); - st6.setLayout(Item.LAYOUT_TOP); - StringItem st7 = new StringItem(null, "Text 7"); - st7.setLayout(Item.LAYOUT_VCENTER); - StringItem st8 = new StringItem(null, "Text 8"); - st8.setLayout(Item.LAYOUT_RIGHT); - StringItem st9 = new StringItem("header 9", "Text 9"); - StringItem st10 = new StringItem(null, "Text 10"); - st10.setLayout(Item.LAYOUT_TOP); - StringItem st11 = new StringItem(null, "Text 11"); - st11.setLayout(Item.LAYOUT_VCENTER); - StringItem st12 = new StringItem(null, fewLines); - st12.setLayout(Item.LAYOUT_LEFT); - form.append(st1); - form.append(st2); - form.append(st3); - form.append(st4); - form.append(st5); - form.append(st6); - form.append(st7); - form.append(st8); - form.append(st9); - form.append(st10); - form.append(st11); - form.append(st12); - setCurrent(form); - boolean passed = true; - passed = takeScreenshot(img); - assertTrue("plainStringItemTest", passed); - form = null; - } + String img = "FormPlainStringItem.gif"; + String fewLines = "Loremipsumdolorsitamet" + + "consectetuer adipiscing elit."; + StringItem st1 = new StringItem("header", "Text 1"); + StringItem st2 = new StringItem(null, "Text 2"); + st2.setLayout(Item.LAYOUT_TOP); + StringItem st3 = new StringItem(null, "Text 3"); + st3.setLayout(Item.LAYOUT_VCENTER); + StringItem st4 = new StringItem(null, "Text 4"); + st4.setLayout(Item.LAYOUT_CENTER); + StringItem st5 = new StringItem("header 5", "Text 5"); + StringItem st6 = new StringItem(null, "Text 6"); + st6.setLayout(Item.LAYOUT_TOP); + StringItem st7 = new StringItem(null, "Text 7"); + st7.setLayout(Item.LAYOUT_VCENTER); + StringItem st8 = new StringItem(null, "Text 8"); + st8.setLayout(Item.LAYOUT_RIGHT); + StringItem st9 = new StringItem("header 9", "Text 9"); + StringItem st10 = new StringItem(null, "Text 10"); + st10.setLayout(Item.LAYOUT_TOP); + StringItem st11 = new StringItem(null, "Text 11"); + st11.setLayout(Item.LAYOUT_VCENTER); + StringItem st12 = new StringItem(null, fewLines); + st12.setLayout(Item.LAYOUT_LEFT); + form.append(st1); + form.append(st2); + form.append(st3); + form.append(st4); + form.append(st5); + form.append(st6); + form.append(st7); + form.append(st8); + form.append(st9); + form.append(st10); + form.append(st11); + form.append(st12); + setCurrent(form); + boolean passed = true; + passed = takeScreenshot(img); + assertTrue("plainStringItemTest", passed); + form = null; + } /** - * Makes screenshot which shows different aspects of PLAIN ImageItem. - */ - void plainImageItemTest() { - String img = "FormImageItem.gif"; - form = new Form("Form test"); + * Makes screenshot which shows different aspects of PLAIN ImageItem. + */ + void plainImageItemTest() + { + String img = "FormImageItem.gif"; + form = new Form("Form test"); - ImageItem im1 = new ImageItem("header 1", smallImage, - ImageItem.LAYOUT_LEFT, "justImage"); - ImageItem im2 = new ImageItem(null, smallImage, - ImageItem.LAYOUT_VCENTER, "justImage"); - ImageItem im3 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, - "justImage"); - ImageItem im4 = new ImageItem("header 2", smallImage, - ImageItem.LAYOUT_CENTER, "justImage"); - ImageItem im5 = new ImageItem(null, smallImage, - ImageItem.LAYOUT_VCENTER, "justImage"); - ImageItem im6 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, - "justImage"); - ImageItem im7 = new ImageItem("header 2", smallImage, - ImageItem.LAYOUT_RIGHT, "justImage"); - ImageItem im8 = new ImageItem(null, mediumImage, - ImageItem.LAYOUT_VCENTER, "justImage"); - ImageItem im9 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, - "justImage"); - form.append(im1); - form.append(im2); - form.append(im3); - form.append(im4); - form.append(im5); - form.append(im6); - form.append(im7); - form.append(im8); - form.append(im9); - setCurrent(form); - block(CHANGE_DISPLAYABLE_DELAY); - boolean passed = true; - passed = takeScreenshot(img); - assertTrue("plainImageItemTest", passed); - form = null; - } + ImageItem im1 = new ImageItem("header 1", smallImage, + ImageItem.LAYOUT_LEFT, "justImage"); + ImageItem im2 = new ImageItem(null, smallImage, + ImageItem.LAYOUT_VCENTER, "justImage"); + ImageItem im3 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, + "justImage"); + ImageItem im4 = new ImageItem("header 2", smallImage, + ImageItem.LAYOUT_CENTER, "justImage"); + ImageItem im5 = new ImageItem(null, smallImage, + ImageItem.LAYOUT_VCENTER, "justImage"); + ImageItem im6 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, + "justImage"); + ImageItem im7 = new ImageItem("header 2", smallImage, + ImageItem.LAYOUT_RIGHT, "justImage"); + ImageItem im8 = new ImageItem(null, mediumImage, + ImageItem.LAYOUT_VCENTER, "justImage"); + ImageItem im9 = new ImageItem(null, smallImage, ImageItem.LAYOUT_TOP, + "justImage"); + form.append(im1); + form.append(im2); + form.append(im3); + form.append(im4); + form.append(im5); + form.append(im6); + form.append(im7); + form.append(im8); + form.append(im9); + setCurrent(form); + block(CHANGE_DISPLAYABLE_DELAY); + boolean passed = true; + passed = takeScreenshot(img); + assertTrue("plainImageItemTest", passed); + form = null; + } /** - * Screenshot based test cases which demonstrates combination of PLAIN and - * BUTTON StrinItems, and PLAIN ImageItems. - */ - void stringImageButtonTest() { - form = new Form("Form test"); - String img = "FormImageStringButtonItem.gif"; + * Screenshot based test cases which demonstrates combination of PLAIN and + * BUTTON StrinItems, and PLAIN ImageItems. + */ + void stringImageButtonTest() + { + form = new Form("Form test"); + String img = "FormImageStringButtonItem.gif"; - StringItem st1 = new StringItem("header 1", "Text 1"); - StringItem st2 = new StringItem(null, "Text 2"); - StringItem st3 = new StringItem(null, "Text 3"); - ImageItem im1 = new ImageItem("header 2", smallImage, - ImageItem.LAYOUT_CENTER, "justImage"); - im1.setLayout(ImageItem.LAYOUT_CENTER); - ImageItem im2 = new ImageItem("header 3", mediumImage, - ImageItem.LAYOUT_CENTER, "justImage"); - ImageItem im3 = new ImageItem("header 4", smallImage, - ImageItem.LAYOUT_CENTER, "justImage"); - StringItem st4 = new StringItem("header 5", "Click 1", Item.BUTTON); - StringItem st5 = new StringItem(null, "Click 2", Item.BUTTON); - StringItem st6 = new StringItem(null, "Click 3", Item.BUTTON); - st4.setLayout(Item.LAYOUT_RIGHT); - st4.addCommand(exitCmd); - st5.addCommand(exitCmd); - st6.addCommand(exitCmd); - form.append(st1); - form.append(st2); - form.append(st3); + StringItem st1 = new StringItem("header 1", "Text 1"); + StringItem st2 = new StringItem(null, "Text 2"); + StringItem st3 = new StringItem(null, "Text 3"); + ImageItem im1 = new ImageItem("header 2", smallImage, + ImageItem.LAYOUT_CENTER, "justImage"); + im1.setLayout(ImageItem.LAYOUT_CENTER); + ImageItem im2 = new ImageItem("header 3", mediumImage, + ImageItem.LAYOUT_CENTER, "justImage"); + ImageItem im3 = new ImageItem("header 4", smallImage, + ImageItem.LAYOUT_CENTER, "justImage"); + StringItem st4 = new StringItem("header 5", "Click 1", Item.BUTTON); + StringItem st5 = new StringItem(null, "Click 2", Item.BUTTON); + StringItem st6 = new StringItem(null, "Click 3", Item.BUTTON); + st4.setLayout(Item.LAYOUT_RIGHT); + st4.addCommand(exitCmd); + st5.addCommand(exitCmd); + st6.addCommand(exitCmd); + form.append(st1); + form.append(st2); + form.append(st3); - form.append(im1); - form.append(im2); - form.append(im3); + form.append(im1); + form.append(im2); + form.append(im3); - form.append(st4); - form.append(st5); - form.append(st6); - setCurrent(form); - // block(SpedeRunner.longTapDelay); + form.append(st4); + form.append(st5); + form.append(st6); + setCurrent(form); + // block(SpedeRunner.longTapDelay); - boolean passed = true; - passed = takeScreenshot(img); - assertTrue("stringImageButtonTest", passed); - form = null; - } + boolean passed = true; + passed = takeScreenshot(img); + assertTrue("stringImageButtonTest", passed); + form = null; + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeSTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeSTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeSTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.textbox; @@ -60,13 +60,15 @@ * */ -public class TextBoxInputModeSTest extends UITestBase { +public class TextBoxInputModeSTest extends UITestBase +{ private static final int LENGTH = 2000; /** * Empty constructor. */ - public TextBoxInputModeSTest() { + public TextBoxInputModeSTest() + { } @@ -75,65 +77,77 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TextBoxInputModeSTest(String sTestName, TestMethod rTestMethod) { - super(sTestName, rTestMethod); - } + public TextBoxInputModeSTest(String sTestName, TestMethod rTestMethod) + { + super(sTestName, rTestMethod); + } /*************************************************************************** - * To create the test suite. You need to add a new aSuite.addTest antry for - * any new test methods. - * - * @return test suite - */ - public Test suite() { + * To create the test suite. You need to add a new aSuite.addTest antry for + * any new test methods. + * + * @return test suite + */ + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TextBoxInputModeSTest("testEditOptWhenLatDigits", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeSTest) tc).testEditOptWhenLatDigits(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeSTest) tc).testEditOptWhenLatDigits(); + } + } + )); aSuite.addTest(new TextBoxInputModeSTest("testEditOptionsWhenLatin", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeSTest) tc).testEditOptionsWhenLatin(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeSTest) tc).testEditOptionsWhenLatin(); + } + } + )); aSuite.addTest(new TextBoxInputModeSTest("testEditOptionsWhenArabic", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeSTest) tc) - .testEditOptionsWhenArabic(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeSTest) tc) + .testEditOptionsWhenArabic(); + } + } + )); aSuite.addTest(new TextBoxInputModeSTest( - "testEditOptionsWhenNonPredictive", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeSTest) tc) - .testEditOptionsWhenNonPredictive(); - } - } - )); + "testEditOptionsWhenNonPredictive", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeSTest) tc) + .testEditOptionsWhenNonPredictive(); + } + } + )); aSuite.addTest(new TextBoxInputModeSTest( - "testEditOptionsWhenPassword", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeSTest) tc) - .testEditOptionsWhenPassword(); - } - } - )); + "testEditOptionsWhenPassword", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeSTest) tc) + .testEditOptionsWhenPassword(); + } + } + )); return aSuite; } @@ -142,14 +156,15 @@ * Tests EditOptions menu after setInitialInputMode("IS_LATIN_DIGITS") * in order to see that the user can change the input mode. */ - private void testEditOptWhenLatDigits() { + private void testEditOptWhenLatDigits() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN_DIGITS", - "", // initial content - // key presses - new int[]{'2', '3', '4', '5', Key.Edit, Key.CBA1}, - null); + TextField.ANY, "IS_LATIN_DIGITS", + "", // initial content + // key presses + new int[] {'2', '3', '4', '5', Key.Edit, Key.CBA1}, + null); } /** @@ -157,13 +172,14 @@ * in order to see that the user can change the input mode and * and the input language. */ - private void testEditOptionsWhenLatin () { + private void testEditOptionsWhenLatin() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN", - "", // initial content - // key presses - new int[]{'2', '3', '4', '5', Key.Edit, Key.CBA1}, - null); + TextField.ANY, "IS_LATIN", + "", // initial content + // key presses + new int[] {'2', '3', '4', '5', Key.Edit, Key.CBA1}, + null); } /** @@ -171,13 +187,14 @@ * in order to see that the user can change the input mode the * input language and also Arabic Number mode. */ - private void testEditOptionsWhenArabic() { + private void testEditOptionsWhenArabic() + { doInputModeTest(getName(), - TextField.ANY, "UCB_ARABIC", - "", // initial content - // key presses - new int[]{'2', '3', '4', '5', Key.Edit, Key.CBA1}, - null); // no expected content, screenshot taken + TextField.ANY, "UCB_ARABIC", + "", // initial content + // key presses + new int[] {'2', '3', '4', '5', Key.Edit, Key.CBA1}, + null); // no expected content, screenshot taken } /** @@ -185,13 +202,14 @@ * when NON_PREDICTIVE. Edit Options menu does not contain any * "Predictive text on" menu item. */ - private void testEditOptionsWhenNonPredictive() { + private void testEditOptionsWhenNonPredictive() + { doInputModeTest(getName(), - TextField.NON_PREDICTIVE, "UCB_GREEK", - "", // initial content - // key presses - new int[]{'2', '3', '4', '5', Key.Edit, Key.CBA1}, - null); // no expected content, screenshot taken + TextField.NON_PREDICTIVE, "UCB_GREEK", + "", // initial content + // key presses + new int[] {'2', '3', '4', '5', Key.Edit, Key.CBA1}, + null); // no expected content, screenshot taken } /** @@ -199,13 +217,14 @@ * when PASSWORD. Edit Options menu does not contain any * "Predictive text on" menu item. */ - private void testEditOptionsWhenPassword() { + private void testEditOptionsWhenPassword() + { doInputModeTest(getName(), - TextField.PASSWORD, "UCB_HEBREW", - "", // initial content - // key presses - new int[]{'2', '3', '4', '5', Key.Edit, Key.CBA1}, - null); // no expected content, screenshot taken + TextField.PASSWORD, "UCB_HEBREW", + "", // initial content + // key presses + new int[] {'2', '3', '4', '5', Key.Edit, Key.CBA1}, + null); // no expected content, screenshot taken } @@ -229,20 +248,24 @@ String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String expectedContent) + { boolean passed = true; SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); - try { + try + { // Create TextBox TextBox textBox = new TextBox( - testCaseName, // title - initialContent, LENGTH, constraints); + testCaseName, // title + initialContent, LENGTH, constraints); // Set initial input mode before displaying TextBox - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textBox.setInitialInputMode(initialInputMode); block(KEYEVENT_DELAY); } @@ -250,19 +273,23 @@ setCurrent(textBox); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); - if (pressedKeys[i] == Key.Edit) { + if(pressedKeys[i] == Key.Edit) + { passed = spede.takeScreenshot(testCaseName + ".gif"); } } } } - catch (Exception exc) { + catch(Exception exc) + { spede.addToResultsList(testCaseName + " test failed: " - + exc.toString()); + + exc.toString()); spede.addToResultsList(exc); passed = false; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxInputModeTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.textbox; @@ -61,27 +61,30 @@ * Note: The references images differ from 3.0 to 3.1 */ -public class TextBoxInputModeTest extends UITestBase { +public class TextBoxInputModeTest extends UITestBase +{ private static final int LENGTH = 2000; /** * Empty constructor. */ - public TextBoxInputModeTest() { - super(); + public TextBoxInputModeTest() + { + super(); } /** - * Class constructor. - * - * @param sTestName - * name of the test - * @param rTestMethod - * TestMethod used - */ - public TextBoxInputModeTest(String sTestName, TestMethod rTestMethod) { - super(sTestName, rTestMethod); - } + * Class constructor. + * + * @param sTestName + * name of the test + * @param rTestMethod + * TestMethod used + */ + public TextBoxInputModeTest(String sTestName, TestMethod rTestMethod) + { + super(sTestName, rTestMethod); + } /*************************************** * To create the test suite. You need to add a new aSuite.addTest antry @@ -89,53 +92,64 @@ * * @return test suite */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TextBoxInputModeTest("testEditOptWhenLatDigits", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeTest) tc).testEditOptWhenLatDigits(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeTest) tc).testEditOptWhenLatDigits(); + } + } + )); aSuite.addTest(new TextBoxInputModeTest("testEditOptionsWhenLatin", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeTest) tc).testEditOptionsWhenLatin(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeTest) tc).testEditOptionsWhenLatin(); + } + } + )); aSuite.addTest(new TextBoxInputModeTest("testEditOptionsWhenArabic", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeTest) tc) - .testEditOptionsWhenArabic(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeTest) tc) + .testEditOptionsWhenArabic(); + } + } + )); aSuite.addTest(new TextBoxInputModeTest( - "testEditOptionsWhenNonPredictive", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeTest) tc) - .testEditOptionsWhenNonPredictive(); - } - } - )); + "testEditOptionsWhenNonPredictive", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeTest) tc) + .testEditOptionsWhenNonPredictive(); + } + } + )); aSuite.addTest(new TextBoxInputModeTest( - "testEditOptionsWhenPassword", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeTest) tc) - .testEditOptionsWhenPassword(); - } - } - )); + "testEditOptionsWhenPassword", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeTest) tc) + .testEditOptionsWhenPassword(); + } + } + )); return aSuite; } @@ -144,18 +158,20 @@ * Tests EditOptions menu after setInitialInputMode("IS_LATIN_DIGITS") * in order to see that the user can change the input mode. */ - private void testEditOptWhenLatDigits() { - int[] keyPresses = new int[]{'2', '3', '4', '5', Key.Edit}; + private void testEditOptWhenLatDigits() + { + int[] keyPresses = new int[] {'2', '3', '4', '5', Key.Edit}; boolean passed = true; TextBox textBox = new TextBox("testEditOptWhenLatDigits", // title - "", LENGTH, TextField.ANY); + "", LENGTH, TextField.ANY); textBox.setInitialInputMode("IS_LATIN_DIGITS"); block(KEYEVENT_DELAY); setCurrent(textBox); // Do key presses - for (int i = 0; i < keyPresses.length; i++) { + for(int i = 0; i < keyPresses.length; i++) + { key(keyPresses[i]); } block(CHANGE_DISPLAYABLE_DELAY); @@ -168,12 +184,13 @@ * in order to see that the user can change the input mode and * and the input language. */ - private void testEditOptionsWhenLatin () { + private void testEditOptionsWhenLatin() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5', Key.Edit}, // key presses - null); + TextField.ANY, "IS_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5', Key.Edit}, // key presses + null); } /** @@ -181,12 +198,13 @@ * in order to see that the user can change the input mode the * input language and also Arabic Number mode. */ - private void testEditOptionsWhenArabic() { + private void testEditOptionsWhenArabic() + { doInputModeTest(getName(), - TextField.ANY, "UCB_ARABIC", - "", // initial content - new int[]{'2', '3', '4', '5', Key.Edit}, // key presses - null); // no expected content, screenshot taken + TextField.ANY, "UCB_ARABIC", + "", // initial content + new int[] {'2', '3', '4', '5', Key.Edit}, // key presses + null); // no expected content, screenshot taken } /** @@ -194,12 +212,13 @@ * when NON_PREDICTIVE. Edit Options menu does not contain any * "Predictive text on" menu item. */ - private void testEditOptionsWhenNonPredictive() { + private void testEditOptionsWhenNonPredictive() + { doInputModeTest(getName(), - TextField.NON_PREDICTIVE, "UCB_GREEK", - "", // initial content - new int[]{'2', '3', '4', '5', Key.Edit}, // key presses - null); // no expected content, screenshot taken + TextField.NON_PREDICTIVE, "UCB_GREEK", + "", // initial content + new int[] {'2', '3', '4', '5', Key.Edit}, // key presses + null); // no expected content, screenshot taken } /** @@ -207,12 +226,13 @@ * when PASSWORD. Edit Options menu does not contain any * "Predictive text on" menu item. */ - private void testEditOptionsWhenPassword() { + private void testEditOptionsWhenPassword() + { doInputModeTest(getName(), - TextField.PASSWORD, "UCB_HEBREW", - "", // initial content - new int[]{'2', '3', '4', '5', Key.Edit}, // key presses - null); // no expected content, screenshot taken + TextField.PASSWORD, "UCB_HEBREW", + "", // initial content + new int[] {'2', '3', '4', '5', Key.Edit}, // key presses + null); // no expected content, screenshot taken } @@ -232,55 +252,56 @@ * @param expectedContent Expected content of TextBox */ private void doInputModeTest(String testCaseName, - int constraints, String initialInputMode, String initialContent, - int[] pressedKeys, String expectedContent) { -/* - boolean passed = true; - SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); + int constraints, String initialInputMode, String initialContent, + int[] pressedKeys, String expectedContent) + { + /* + boolean passed = true; + SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); - try { - // Create TextBox - TextBox textBox = new TextBox( - testCaseName, // title - initialContent, LENGTH, constraints); + try { + // Create TextBox + TextBox textBox = new TextBox( + testCaseName, // title + initialContent, LENGTH, constraints); - // Set initial input mode before displaying TextBox - if ("NONE".equals(initialInputMode)) { - // initial input mode not set - } - else { - textBox.setInitialInputMode(initialInputMode); - block(SpedeRunner.keyEventDelay); - } - Display.getDisplay(SpedeRunner.getInstance()).setCurrent(textBox); - block(CHANGE_DISPLAYABLE_DELAY); + // Set initial input mode before displaying TextBox + if ("NONE".equals(initialInputMode)) { + // initial input mode not set + } + else { + textBox.setInitialInputMode(initialInputMode); + block(SpedeRunner.keyEventDelay); + } + Display.getDisplay(SpedeRunner.getInstance()).setCurrent(textBox); + block(CHANGE_DISPLAYABLE_DELAY); - // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { - spede.triggerKeyPressEvent(new Key(pressedKeys[i])); - block(SpedeRunner.keyEventDelay); - } - } + // Do key presses + if (pressedKeys != null) { + for (int i = 0; i < pressedKeys.length; i++) { + spede.triggerKeyPressEvent(new Key(pressedKeys[i])); + block(SpedeRunner.keyEventDelay); + } + } - /*block(CHANGE_DISPLAYABLE_DELAY); - spede.takeScreenshot(testCaseName + ".gif"); + /*block(CHANGE_DISPLAYABLE_DELAY); + spede.takeScreenshot(testCaseName + ".gif"); - } - catch (Exception exc) { - System.out.println("!!!!======!!!!!"); + } + catch (Exception exc) { + System.out.println("!!!!======!!!!!"); - /* - spede.addToResultsList(testCaseName + " test failed: " - + exc.toString()); - spede.addToResultsList(exc); - passed = false; - } + /* + spede.addToResultsList(testCaseName + " test failed: " + + exc.toString()); + spede.addToResultsList(exc); + passed = false; + } - System.out.println("before assertTrue"); + System.out.println("before assertTrue"); - assertTrue(testCaseName, passed); - System.out.println("after assertTrue");*/ + assertTrue(testCaseName, passed); + System.out.println("after assertTrue");*/ } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxSTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxSTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textbox/TextBoxSTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.textbox; @@ -31,23 +31,27 @@ *
            * Created: 2008-05-06 */ -public class TextBoxSTest extends UITestBase { +public class TextBoxSTest extends UITestBase +{ private static final int LENGTH = 100; private static final int NEW_LENGTH = 200; private static final int CARET_SHIFT = 2; private TextBox textbox; - private int[] inputTextShort = new int[]{'7', '8', '8', '9', - '4', '5', '5', '5', '5', }; + private int[] inputTextShort = new int[] {'7', '8', '8', '9', + '4', '5', '5', '5', '5', + }; private int[] inputSentence = new int [] {'3', '3', '8', '8', '8', - '3', '3', '7', '7', '7', }; + '3', '3', '7', '7', '7', + }; /** * Empty constructor. */ - public TextBoxSTest() { - super(); + public TextBoxSTest() + { + super(); } /** @@ -55,7 +59,8 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TextBoxSTest(String sTestName, TestMethod rTestMethod) { + public TextBoxSTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -65,35 +70,42 @@ * any new test methods. * @return aSuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TextBoxSTest("textboxPasswordTest()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxSTest) tc).textboxPasswordTest(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxSTest) tc).textboxPasswordTest(); + } + } + )); aSuite.addTest(new TextBoxSTest("textboxComplexScreenshotTest()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxSTest) tc).textboxComplexScreenshotTest(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxSTest) tc).textboxComplexScreenshotTest(); + } + } + )); return aSuite; } - /** - * Tests password input. - */ - public void textboxPasswordTest() { + /** + * Tests password input. + */ + public void textboxPasswordTest() + { textbox = new TextBox("PASSWORD", null, LENGTH, TextField.PASSWORD); setCurrent(textbox); String img = "textboxPasswordIndicator.gif"; - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } @@ -112,7 +124,8 @@ * Complex screenshot based test, designed to test as much * features as possible in one test. */ - public void textboxComplexScreenshotTest () { + public void textboxComplexScreenshotTest() + { String getString = null; String setString = null; String insertString = "|insert()|"; @@ -121,8 +134,8 @@ int getSize = 0; String addContent = null; - textbox = new TextBox ("Complex test", "inital content", LENGTH, - TextField.ANY); + textbox = new TextBox("Complex test", "inital content", LENGTH, + TextField.ANY); setCurrent(textbox); String img = "textboxComplexSTest.gif"; @@ -132,7 +145,8 @@ //double initial content with "and" between them textbox.setString(setString); //input "Ever" - for (int i = 0; i < inputSentence.length; i++) { + for(int i = 0; i < inputSentence.length; i++) + { key(inputSentence[i], 0); } //get caret position. diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textfield/SetInitInModeTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textfield/SetInitInModeTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_screenshots/textfield/SetInitInModeTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_screenshots.textfield; @@ -67,7 +67,8 @@ * Note: The references images differ from 3.0 to 3.1, and 3.2 */ -public class SetInitInModeTest extends UITestBase { +public class SetInitInModeTest extends UITestBase +{ // ============================================================== @@ -76,7 +77,8 @@ /** * Default constructor. */ - public SetInitInModeTest() { + public SetInitInModeTest() + { } /** @@ -86,7 +88,8 @@ * @param rTestMethod test method. */ public SetInitInModeTest(String sTestName, - TestMethod rTestMethod) { + TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -96,48 +99,59 @@ * * @return test suite */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new SetInitInModeTest( - "test_EditOptionsWhenLatinDigits", new TestMethod() { - public void run(TestCase tc) { - ((SetInitInModeTest) tc) - .testEditOptionsWhenLatinDigits(); - } - })); + "test_EditOptionsWhenLatinDigits", new TestMethod() + { + public void run(TestCase tc) + { + ((SetInitInModeTest) tc) + .testEditOptionsWhenLatinDigits(); + } + })); aSuite.addTest(new SetInitInModeTest( - "test_EditOptionsWhenLatin", new TestMethod() { - public void run(TestCase tc) { - ((SetInitInModeTest) tc) - .testEditOptionsWhenLatin(); - } - })); + "test_EditOptionsWhenLatin", new TestMethod() + { + public void run(TestCase tc) + { + ((SetInitInModeTest) tc) + .testEditOptionsWhenLatin(); + } + })); aSuite.addTest(new SetInitInModeTest( - "test_EditOptionsWhenArabic", new TestMethod() { - public void run(TestCase tc) { - ((SetInitInModeTest) tc) - .testEditOptionsWhenArabic(); - } - })); + "test_EditOptionsWhenArabic", new TestMethod() + { + public void run(TestCase tc) + { + ((SetInitInModeTest) tc) + .testEditOptionsWhenArabic(); + } + })); aSuite.addTest(new SetInitInModeTest( - "test_EditOptionsWhenNonPredictive", new TestMethod() { - public void run(TestCase tc) { - ((SetInitInModeTest) tc) - .testEditOptionsWhenNonPredictive(); - } - })); + "test_EditOptionsWhenNonPredictive", new TestMethod() + { + public void run(TestCase tc) + { + ((SetInitInModeTest) tc) + .testEditOptionsWhenNonPredictive(); + } + })); aSuite.addTest(new SetInitInModeTest( - "test_EditOptionsWhenPassword", new TestMethod() { - public void run(TestCase tc) { - ((SetInitInModeTest) tc) - .testEditOptionsWhenPassword(); - } - })); + "test_EditOptionsWhenPassword", new TestMethod() + { + public void run(TestCase tc) + { + ((SetInitInModeTest) tc) + .testEditOptionsWhenPassword(); + } + })); @@ -151,22 +165,24 @@ * Tests EditOptions menu after setInitialInputMode("IS_LATIN_DIGITS") in * order to see that the user can change the input mode. */ - private void testEditOptionsWhenLatinDigits() { + private void testEditOptionsWhenLatinDigits() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN_DIGITS", "", - // initial content - new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses - null); + // initial content + new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses + null); } /** * Tests EditOptions menu after setInitialInputMode("IS_LATIN") in order to * see that the user can change the input mode and and the input language. */ - private void testEditOptionsWhenLatin() { + private void testEditOptionsWhenLatin() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN", "", // initial - // content - new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses - null); + // content + new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses + null); } /** @@ -174,11 +190,12 @@ * to see that the user can change the input mode the input language and * also Arabic Number mode. */ - private void testEditOptionsWhenArabic() { + private void testEditOptionsWhenArabic() + { doInputModeTest(getName(), TextField.ANY, "UCB_ARABIC", "", // initial - // content - new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses - null); // no expected content, screenshot taken + // content + new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses + null); // no expected content, screenshot taken } /** @@ -186,11 +203,12 @@ * NON_PREDICTIVE. Edit Options menu does not contain any "Predictive text * on" menu item. */ - private void testEditOptionsWhenNonPredictive() { + private void testEditOptionsWhenNonPredictive() + { doInputModeTest(getName(), TextField.NON_PREDICTIVE, "UCB_GREEK", "", - // initial content - new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses - null); // no expected content, screenshot taken + // initial content + new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses + null); // no expected content, screenshot taken } /** @@ -198,11 +216,12 @@ * PASSWORD. Edit Options menu does not contain any "Predictive text on" * menu item. */ - private void testEditOptionsWhenPassword() { + private void testEditOptionsWhenPassword() + { doInputModeTest(getName(), TextField.PASSWORD, "UCB_HEBREW", "", - // initial content - new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses - null); // no expected content, screenshot taken + // initial content + new int[] {'2', '3', '4', '5', Key.Edit, }, // key presses + null); // no expected content, screenshot taken } @@ -223,24 +242,28 @@ * @param expectedContent Expected content of TextField */ private void doInputModeTest(String testCaseName, int constraints, - String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String initialInputMode, String initialContent, int[] pressedKeys, + String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields Form form = new Form(testCaseName); TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); + normalSize, constraints); TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); + TextField.ANY); // Set initial input mode before displaying TextField - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textField.setInitialInputMode(initialInputMode); } form.append(textField); @@ -252,8 +275,10 @@ // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -261,12 +286,13 @@ // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); + print(exc); passed = false; } @@ -285,39 +311,45 @@ * @return result Returns whether test case passed or failed */ private boolean checkResult(String testCaseName, TextField textBox, - String expectedContent, boolean takeScreenshot) { + String expectedContent, boolean takeScreenshot) + { boolean passed = true; SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); // Check the expected content - if (expectedContent != null) { - if (!expectedContent.equals(textBox.getString())) { + if(expectedContent != null) + { + if(!expectedContent.equals(textBox.getString())) + { passed = false; spede.addToResultsList(testCaseName + " test " - + " failed: content: " + textBox.getString() - + ", expected: " + expectedContent); + + " failed: content: " + textBox.getString() + + ", expected: " + expectedContent); } } // Take the screenshot and compare it with the previous one - if (takeScreenshot) { - if (!spede.takeScreenshot(testCaseName + ".gif")) { + if(takeScreenshot) + { + if(!spede.takeScreenshot(testCaseName + ".gif")) + { passed = false; spede.addToResultsList(testCaseName + " test " - + " failed: screenshot does not match"); + + " failed: screenshot does not match"); spede.addToResultsList("If failure is caused by different " - + "special characters which are show in the cell at " - + "the top of the Edit Menu, please IGNORE the result" - + " and treat the test as PASSED!"); + + "special characters which are show in the cell at " + + "the top of the Edit Menu, please IGNORE the result" + + " and treat the test as PASSED!"); } } - if (passed) { + if(passed) + { spede.addToResultsList(testCaseName + " test succeeded: " - + textBox.getString()); + + textBox.getString()); } return passed; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/alert/AlertUITest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/alert/AlertUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/alert/AlertUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.alert; @@ -36,7 +36,8 @@ * * @created 2008-07-01 */ -public class AlertUITest extends UITestBase { +public class AlertUITest extends UITestBase +{ private static final int SETCURRENT_TIMEOUT = 6000; private static final int TEXBOX_LENGTH = 100; @@ -44,19 +45,19 @@ private static String shortString = "Lorem ipsum"; private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue." - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue." + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; private TextBox textBox; private Command exitCmd; @@ -64,8 +65,9 @@ /** * Constructor. */ - public AlertUITest() { - super(); + public AlertUITest() + { + super(); } /** @@ -74,15 +76,17 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public AlertUITest(String sTestName, TestMethod rTestMethod) { + public AlertUITest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception + { + super.setUp(); exitCmd = new Command("exit", "exit", Command.EXIT, 0); textBox = new TextBox("textBox", "", TEXBOX_LENGTH, TextField.ANY); textBox.addCommand(exitCmd); @@ -94,48 +98,61 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); - aSuite.addTest(new AlertUITest("testShowTimedAlert", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new AlertUITest("testShowTimedAlert", new TestMethod() + { + public void run(TestCase tc) + { ((AlertUITest) tc).testShowTimedAlert(); } })); - aSuite.addTest(new AlertUITest("testCustomListener", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new AlertUITest("testCustomListener", new TestMethod() + { + public void run(TestCase tc) + { ((AlertUITest) tc).testCustomListener(); } })); aSuite.addTest(new AlertUITest("testCustomListenerCustomCommand", - new TestMethod() { - public void run(TestCase tc) { - ((AlertUITest) tc).testCustomListenerCustomCommand(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AlertUITest) tc).testCustomListenerCustomCommand(); + } + })); aSuite.addTest(new AlertUITest("testKeypressOnCustomCommands", - new TestMethod() { - public void run(TestCase tc) { - ((AlertUITest) tc).testKeypressOnCustomCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AlertUITest) tc).testKeypressOnCustomCommands(); + } + })); aSuite.addTest(new AlertUITest("testLongTextScrolling", - new TestMethod() { - public void run(TestCase tc) { - ((AlertUITest) tc).testLongTextScrolling(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AlertUITest) tc).testLongTextScrolling(); + } + })); aSuite.addTest(new AlertUITest("testImageAndTextCombinations", - new TestMethod() { - public void run(TestCase tc) { - ((AlertUITest) tc).testImageAndTextCombinations(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AlertUITest) tc).testImageAndTextCombinations(); + } + })); return aSuite; } @@ -143,7 +160,8 @@ /** * Tests showing a timed alert with default values. */ - public void testShowTimedAlert() { + public void testShowTimedAlert() + { setCurrent(textBox); Alert alert = new Alert("timedAlert"); @@ -169,18 +187,19 @@ setCurrent(alert); block(timeout + CHANGE_DISPLAYABLE_DELAY); assertEquals("Textbox should be current", - textBox, display.getCurrent()); + textBox, display.getCurrent()); } /** * Tests showing a timed alert with custom command listener. */ - public void testCustomListener() { - setCurrent(textBox); + public void testCustomListener() + { + setCurrent(textBox); Alert alert = new Alert("customListenerAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); setCurrent(alert); // wait for max 10sec to get command listener callback @@ -192,12 +211,13 @@ * Tests showing a timed alert with custom command listener and custom * command. */ - public void testCustomListenerCustomCommand() { - setCurrent(textBox); + public void testCustomListenerCustomCommand() + { + setCurrent(textBox); Alert alert = new Alert("customCmdAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); Command testCmd = new Command("test", "test", Command.ITEM, 0); alert.addCommand(testCmd); @@ -210,19 +230,20 @@ /** * Tests pressing keys on Alert's custom commands. */ - public void testKeypressOnCustomCommands() { - setCurrent(textBox); + public void testKeypressOnCustomCommands() + { + setCurrent(textBox); Alert alert = new Alert("keypressAlert"); assertTrue("Alert should be timed", - alert.getTimeout() != Alert.FOREVER); + alert.getTimeout() != Alert.FOREVER); alert.setCommandListener(this); Command testCmd1 = new Command("Cmd1", "Command 1", Command.SCREEN, 0); Command testCmd2 = new Command("Cmd2", "Command 2", Command.SCREEN, 1); alert.addCommand(testCmd1); alert.addCommand(testCmd2); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); key(Key.CBA1, 0); @@ -240,17 +261,19 @@ /** * Tests scrolling a long text. */ - public void testLongTextScrolling() { - setCurrent(textBox); + public void testLongTextScrolling() + { + setCurrent(textBox); Alert alert = new Alert("scrollingAlert"); alert.setString(longString); alert.setCommandListener(this); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) + { key((i < 5 ? Key.DownArrow : Key.UpArrow)); } @@ -261,21 +284,26 @@ /** * Tests different text and image setting combinations. */ - public void testImageAndTextCombinations() { - setCurrent(textBox); + public void testImageAndTextCombinations() + { + setCurrent(textBox); Image smallImg = null; Image largeImg = null; - try { + try + { smallImg = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } - try { + try + { largeImg = Image.createImage("200x200.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 200x200.png"); } @@ -283,36 +311,40 @@ alert.setTimeout(Alert.FOREVER); alert.setCommandListener(this); assertTrue("Alert should be modal", - alert.getTimeout() == Alert.FOREVER); + alert.getTimeout() == Alert.FOREVER); setCurrent(alert); - for (int textIndex = 0; textIndex < 3; textIndex++) { - switch (textIndex) { + for(int textIndex = 0; textIndex < 3; textIndex++) + { + switch(textIndex) + { + case 0: + alert.setString(null); + break; + case 1: + alert.setString(shortString); + break; + case 2: + alert.setString(longString); + break; + default: + break; + } + for(int imgIndex = 0; imgIndex < 3; imgIndex++) + { + switch(imgIndex) + { case 0: - alert.setString(null); + alert.setImage(null); break; case 1: - alert.setString(shortString); + alert.setImage(smallImg); break; case 2: - alert.setString(longString); + alert.setImage(largeImg); break; default: break; - } - for (int imgIndex = 0; imgIndex < 3; imgIndex++) { - switch (imgIndex) { - case 0: - alert.setImage(null); - break; - case 1: - alert.setImage(smallImg); - break; - case 2: - alert.setImage(largeImg); - break; - default: - break; } block(CHANGE_DISPLAYABLE_DELAY); // 0.3 sec } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupCommandTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.choicegroup; @@ -31,12 +31,14 @@ *
            * Created: 2008-11-04 */ -public class ChoiceGroupCommandTest extends ItemUITestBase { +public class ChoiceGroupCommandTest extends ItemUITestBase +{ - /** + /** * Constructor. */ - public ChoiceGroupCommandTest() { + public ChoiceGroupCommandTest() + { } /** @@ -45,7 +47,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ChoiceGroupCommandTest(String sTestName, TestMethod rTestMethod) { + public ChoiceGroupCommandTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -56,31 +59,37 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new ChoiceGroupCommandTest("testCommands - EXCLUSIVE", - new TestMethod() { - public void run(TestCase tc) { - ChoiceGroup item = new ChoiceGroup("Exclusive", - Choice.EXCLUSIVE); - ((ChoiceGroupCommandTest) tc).testCommand(item); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ChoiceGroup item = new ChoiceGroup("Exclusive", + Choice.EXCLUSIVE); + ((ChoiceGroupCommandTest) tc).testCommand(item); + } + })); aSuite.addTest(new ChoiceGroupCommandTest("testCommands - MULTIPLE", - new TestMethod() { - public void run(TestCase tc) { - ChoiceGroup item = new ChoiceGroup("Multiple", - Choice.MULTIPLE); - ((ChoiceGroupCommandTest) tc).testCommand(item); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ChoiceGroup item = new ChoiceGroup("Multiple", + Choice.MULTIPLE); + ((ChoiceGroupCommandTest) tc).testCommand(item); + } + })); return aSuite; } - public void testChoiceGroupExclusiveCmds() { + public void testChoiceGroupExclusiveCmds() + { ChoiceGroup choiceGroup = new ChoiceGroup("Exclusive", Choice.EXCLUSIVE); choiceGroup.append("item1", null); choiceGroup.append("item2", null); @@ -89,7 +98,8 @@ testCommand(choiceGroup); } - public void testChoiceGroupMultipleCmds() { + public void testChoiceGroupMultipleCmds() + { ChoiceGroup choiceGroup = new ChoiceGroup("Multiple", Choice.MULTIPLE); choiceGroup.append("item1", null); choiceGroup.append("item2", null); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupPopupTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupPopupTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/choicegroup/ChoiceGroupPopupTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.choicegroup; @@ -32,12 +32,14 @@ *
            * Created: 2008-11-04 */ -public class ChoiceGroupPopupTest extends ItemUITestBase { +public class ChoiceGroupPopupTest extends ItemUITestBase +{ /** * Constructor. */ - public ChoiceGroupPopupTest() { + public ChoiceGroupPopupTest() + { } /** @@ -46,7 +48,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ChoiceGroupPopupTest(String sTestName, TestMethod rTestMethod) { + public ChoiceGroupPopupTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -57,14 +60,17 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new ChoiceGroupPopupTest("testOpenPopup", - new TestMethod() { - public void run(TestCase tc) { - ((ChoiceGroupPopupTest) tc).testOpenPopup(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ChoiceGroupPopupTest) tc).testOpenPopup(); + } + })); return aSuite; } @@ -72,7 +78,8 @@ /** * Test command on Items. */ - public void testOpenPopup() { + public void testOpenPopup() + { Command cmd = new Command("Cmd", Command.ITEM, 0); ChoiceGroup choiceGroup = new ChoiceGroup("Popup", Choice.POPUP); choiceGroup.append("item1", null); @@ -98,7 +105,7 @@ assertTrue("No item selected", choiceGroup.getSelectedIndex() != -1); assertTrue("Could not change selection", - choiceGroup.getSelectedIndex() != sel); + choiceGroup.getSelectedIndex() != sel); assertItemStateChanged("case1", choiceGroup); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/DynamicUpdateTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/DynamicUpdateTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/DynamicUpdateTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.command; @@ -34,7 +34,8 @@ *
            * Created: 2008-05-02 */ -public class DynamicUpdateTest extends UITestBase implements CommandListener { +public class DynamicUpdateTest extends UITestBase implements CommandListener +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; @@ -51,7 +52,8 @@ /** * Constructor. */ - public DynamicUpdateTest() { + public DynamicUpdateTest() + { } /** @@ -60,7 +62,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public DynamicUpdateTest(String sTestName, TestMethod rTestMethod) { + public DynamicUpdateTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -70,37 +73,46 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new DynamicUpdateTest("testAddAndRemoveManyCommands", - new TestMethod() { - public void run(TestCase tc) { - ((DynamicUpdateTest) tc).testAddAndRemoveManyCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((DynamicUpdateTest) tc).testAddAndRemoveManyCommands(); + } + })); aSuite.addTest(new DynamicUpdateTest("testCommandInEmptyForm", - new TestMethod() { - public void run(TestCase tc) { - ((DynamicUpdateTest) tc).testCommandInEmptyForm(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((DynamicUpdateTest) tc).testCommandInEmptyForm(); + } + })); aSuite.addTest(new DynamicUpdateTest( - "testAddCommandToManyDisplayables", new TestMethod() { - public void run(TestCase tc) { - ((DynamicUpdateTest) tc) - .testAddCommandToManyDisplayables(); - } - })); + "testAddCommandToManyDisplayables", new TestMethod() + { + public void run(TestCase tc) + { + ((DynamicUpdateTest) tc) + .testAddCommandToManyDisplayables(); + } + })); aSuite.addTest(new DynamicUpdateTest("testManyCommandListeners", - new TestMethod() { - public void run(TestCase tc) { - ((DynamicUpdateTest) tc).testManyCommandListeners(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((DynamicUpdateTest) tc).testManyCommandListeners(); + } + })); return aSuite; } @@ -109,14 +121,15 @@ * Adds and removes many kind of commands to displayable and makes sure that * events occurs correctly all the time. */ - public void testAddAndRemoveManyCommands() { + public void testAddAndRemoveManyCommands() + { boolean testPassed = true; String testMsg = ""; latestCommand = null; latestDisplayable = null; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); Command item2 = new Command("item2", "item2", Command.ITEM, 1); @@ -140,15 +153,18 @@ // Click it: key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -162,15 +178,18 @@ key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from OK-command."; } - else if (latestCommand != ok1) { + else if(latestCommand != ok1) + { testPassed = false; testMsg = "not OK-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -194,15 +213,18 @@ key(Key.DownArrow, 0); key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from EXIT2-command."; } - else if (latestCommand != exit2) { + else if(latestCommand != exit2) + { testPassed = false; testMsg = "not EXIT2-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -219,15 +241,18 @@ key(Key.DownArrow, 0); key(Key.Select); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from SCREEN1-command."; } - else if (latestCommand != screen1) { + else if(latestCommand != screen1) + { testPassed = false; testMsg = "not SCREEN1-command in event."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -254,7 +279,8 @@ key(Key.CBA2, 0); key(Key.Select); - if (latestCommand != null) { + if(latestCommand != null) + { testPassed = false; testMsg = "Event occured without commands."; } @@ -265,7 +291,8 @@ /** * Test to add command to empty form and verify it works. */ - public void testCommandInEmptyForm() { + public void testCommandInEmptyForm() + { latestCommand = null; latestDisplayable = null; @@ -281,25 +308,26 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command.", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong displayable delivered to commandAction-method.", - form, latestDisplayable); + form, latestDisplayable); } /** * Tests that it's possible to add one command to many displayables and * removing command from one displayable doesn't affect another displayable. */ - public void testAddCommandToManyDisplayables() { + public void testAddCommandToManyDisplayables() + { boolean testPassed = true; String testMsg = ""; latestCommand = null; latestDisplayable = null; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); @@ -315,15 +343,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in first displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in first displayable."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -336,15 +367,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in second displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in second displayable."; } - else if (latestDisplayable != textBox2) { + else if(latestDisplayable != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -357,15 +391,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in second displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in second displayable."; } - else if (latestDisplayable != textBox2) { + else if(latestDisplayable != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -381,15 +418,18 @@ key(Key.CBA1); - if (latestCommand == null) { + if(latestCommand == null) + { testPassed = false; testMsg = "no event from ITEM-command in first displayable."; } - else if (latestCommand != item1) { + else if(latestCommand != item1) + { testPassed = false; testMsg = "not ITEM-command in event in first displayable."; } - else if (latestDisplayable != textBox) { + else if(latestDisplayable != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } @@ -401,7 +441,8 @@ * Tests the functionality of Command and CommandListener when there are * more than one CommandListener listening one Command. */ - public void testManyCommandListeners() { + public void testManyCommandListeners() + { boolean testPassed = true; String testMsg = ""; latestCommand2 = null; @@ -414,21 +455,25 @@ // Create two Displayables and two CommandListeners and add // same Command to both Displayables: TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); Command item1 = new Command("item", "item", Command.ITEM, 0); - textBox.setCommandListener(new CommandListener() { - public void commandAction(Command c, Displayable d) { + textBox.setCommandListener(new CommandListener() + { + public void commandAction(Command c, Displayable d) + { latestCommand2 = c; latestDisplayable2 = d; eventCount2++; } }); - textBox2.setCommandListener(new CommandListener() { - public void commandAction(Command c, Displayable d) { + textBox2.setCommandListener(new CommandListener() + { + public void commandAction(Command c, Displayable d) + { latestCommand3 = c; latestDisplayable3 = d; eventCount3++; @@ -443,19 +488,23 @@ key(Key.CBA1); - if (latestCommand3 == null) { + if(latestCommand3 == null) + { testPassed = false; testMsg = "no event in second displayable."; } - else if (latestCommand3 != item1) { + else if(latestCommand3 != item1) + { testPassed = false; testMsg = "wrong command in second displayable."; } - else if (latestDisplayable3 != textBox2) { + else if(latestDisplayable3 != textBox2) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount3 != 1) { + else if(eventCount3 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount3; } @@ -465,26 +514,31 @@ key(Key.CBA1); - if (latestCommand2 == null) { + if(latestCommand2 == null) + { testPassed = false; testMsg = "no event in first displayable."; } - else if (latestCommand2 != item1) { + else if(latestCommand2 != item1) + { testPassed = false; testMsg = "wrong command in first displayable."; } - else if (latestDisplayable2 != textBox) { + else if(latestDisplayable2 != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount2 != 1) { + else if(eventCount2 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount2; } - else if (eventCount3 != 1) { + else if(eventCount3 != 1) + { testPassed = false; testMsg = "Unexpected number of events in second displayable: " - + eventCount2; + + eventCount2; } // Clear counters, remove command from second displayable and @@ -500,28 +554,34 @@ key(Key.CBA1); - if (latestCommand2 == null) { + if(latestCommand2 == null) + { testPassed = false; testMsg = "no event in first displayable."; } - else if (latestCommand2 != item1) { + else if(latestCommand2 != item1) + { testPassed = false; testMsg = "wrong command in first displayable."; } - else if (latestDisplayable2 != textBox) { + else if(latestDisplayable2 != textBox) + { testPassed = false; testMsg = "unexpected displayable in event."; } - else if (eventCount2 != 1) { + else if(eventCount2 != 1) + { testPassed = false; testMsg = "Unexpected number of events: " + eventCount2; } - else if (eventCount3 != 0) { + else if(eventCount3 != 0) + { testPassed = false; testMsg = "Unexpected number of events in second displayable: " - + eventCount3; + + eventCount3; } - else if (latestCommand3 != null) { + else if(latestCommand3 != null) + { testPassed = false; testMsg = "Unexpected event in second displayable."; } @@ -536,7 +596,8 @@ * @param c Command. * @param d Displayable. */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { latestCommand = c; latestDisplayable = d; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/ItemCommandUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/ItemCommandUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/command/ItemCommandUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.command; @@ -35,7 +35,8 @@ *
            * Created: 2008-08-04 */ -public class ItemCommandUIRobotTest extends ItemUITestBase { +public class ItemCommandUIRobotTest extends ItemUITestBase +{ private Command latestCommand; private Item latestItem; @@ -46,7 +47,8 @@ /** * Constructor. */ - public ItemCommandUIRobotTest() { + public ItemCommandUIRobotTest() + { } /** @@ -55,7 +57,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ItemCommandUIRobotTest(String sTestName, TestMethod rTestMethod) { + public ItemCommandUIRobotTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -65,84 +68,105 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new ItemCommandUIRobotTest("testListener", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testListener(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testListener(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testMultipleItems", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testMultipleItems(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testMultipleItems(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testInitializationOrders", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc). - testInitializationOrders(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc). + testInitializationOrders(); + } + })); aSuite.addTest( new ItemCommandUIRobotTest("testCommandInItemAndInDisplayable", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc). - testCommandInItemAndInDisplayable(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc). + testCommandInItemAndInDisplayable(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testMultipleCommands", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testMultipleCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testMultipleCommands(); + } + })); aSuite.addTest( new ItemCommandUIRobotTest("testOneCommandInMultipleItems", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc). - testOneCommandInMultipleItems(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc). + testOneCommandInMultipleItems(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testDefaultCommand", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testDefaultCommand(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testDefaultCommand(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testDynamicUpdate", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testDynamicUpdate(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testDynamicUpdate(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testItemWithLabel", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc).testItemWithLabel(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc).testItemWithLabel(); + } + })); aSuite.addTest(new ItemCommandUIRobotTest("testAddCommandToFocusedItem", - new TestMethod() { - public void run(TestCase tc) { - ((ItemCommandUIRobotTest) tc). - testAddCommandToFocusedItem(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemCommandUIRobotTest) tc). + testAddCommandToFocusedItem(); + } + })); return aSuite; } @@ -150,7 +174,8 @@ /** * Tests the basic functionality of itemCommandListener. */ - public void testListener() { + public void testListener() + { Form form = new Form("form"); StringItem button1 = new StringItem("", "click!", Item.BUTTON); @@ -166,22 +191,22 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK.", - ok, latestCommand); + + " when pressing MSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK.", - button1, latestItem); + + " when pressing MSK.", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK.", - ok, latestCommand); + + " when pressing LSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK.", - button1, latestItem); + + " when pressing LSK.", + button1, latestItem); } @@ -189,7 +214,8 @@ * Tests that item commands works when there are multiple items * in a form and focus moves between items. */ - public void testMultipleItems() { + public void testMultipleItems() + { latestCommand = null; latestItem = null; @@ -219,11 +245,11 @@ //Click first button: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 1)", - ok1, latestCommand); + + " when pressing LSK. (case 1)", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 1)", - button1, latestItem); + + " when pressing LSK. (case 1)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -232,11 +258,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 2)", - ok2, latestCommand); + + " when pressing LSK. (case 2)", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 2)", - button2, latestItem); + + " when pressing LSK. (case 2)", + button2, latestItem); latestCommand = null; latestItem = null; @@ -244,11 +270,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 3)", - ok3, latestCommand); + + " when pressing LSK. (case 3)", + ok3, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 3)", - button3, latestItem); + + " when pressing LSK. (case 3)", + button3, latestItem); latestCommand = null; latestItem = null; } @@ -256,7 +282,8 @@ /** * Tests different orders to add command, set listener etc. */ - public void testInitializationOrders() { + public void testInitializationOrders() + { latestCommand = null; latestItem = null; @@ -275,11 +302,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 1)", - ok, latestCommand); + + " when pressing LSK. (case 1)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 1)", - button1, latestItem); + + " when pressing LSK. (case 1)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -298,11 +325,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 2)", - ok, latestCommand); + + " when pressing LSK. (case 2)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 2)", - button1, latestItem); + + " when pressing LSK. (case 2)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -320,11 +347,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 3)", - ok, latestCommand); + + " when pressing LSK. (case 3)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 3)", - button1, latestItem); + + " when pressing LSK. (case 3)", + button1, latestItem); latestCommand = null; latestItem = null; @@ -342,11 +369,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK. (case 4)", - ok, latestCommand); + + " when pressing LSK. (case 4)", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK. (case 4)", - button1, latestItem); + + " when pressing LSK. (case 4)", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -355,7 +382,8 @@ * Makes sure that command works when it is added to item and * to displayable at the same time. */ - public void testCommandInItemAndInDisplayable() { + public void testCommandInItemAndInDisplayable() + { latestCommand = null; latestItem = null; @@ -380,11 +408,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting first occurence.", - ok, latestCommand); + + " when selecting first occurence.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting first occurence.", - button1, latestItem); + + " when selecting first occurence.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -394,11 +422,11 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting second occurence.", - ok, latestDisplayableCommand); + + " when selecting second occurence.", + ok, latestDisplayableCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting second occurence.", - form, latestDisplayable); + + " when selecting second occurence.", + form, latestDisplayable); latestDisplayableCommand = null; latestDisplayable = null; } @@ -407,7 +435,8 @@ * Test to add multiple commands to one item and verify the commands * work as expected. */ - public void testMultipleCommands() { + public void testMultipleCommands() + { latestCommand = null; latestItem = null; @@ -431,11 +460,11 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's first command.", - ok1, latestCommand); + + " when selecting item's first command.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's first command.", - button1, latestItem); + + " when selecting item's first command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -443,11 +472,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's second command.", - ok2, latestCommand); + + " when selecting item's second command.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's second command.", - button1, latestItem); + + " when selecting item's second command.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -456,7 +485,8 @@ * Test to add one command to multiple items and verify the command * work as expected. */ - public void testOneCommandInMultipleItems() { + public void testOneCommandInMultipleItems() + { latestCommand = null; latestItem = null; @@ -478,11 +508,11 @@ //Click first button: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when clicking first button.", - ok1, latestCommand); + + " when clicking first button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when clicking first button.", - button1, latestItem); + + " when clicking first button.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -490,11 +520,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when clicking second button.", - ok1, latestCommand); + + " when clicking second button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when clicking second button.", - button2, latestItem); + + " when clicking second button.", + button2, latestItem); latestCommand = null; latestItem = null; } @@ -503,7 +533,8 @@ /** * Tests the functionality of default command. */ - public void testDefaultCommand() { + public void testDefaultCommand() + { latestCommand = null; latestItem = null; @@ -529,11 +560,11 @@ key(Key.CBA1); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's first command.", - ok1, latestCommand); + + " when selecting item's first command.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's first command.", - button1, latestItem); + + " when selecting item's first command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -549,11 +580,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when selecting item's second command.", - ok2, latestCommand); + + " when selecting item's second command.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's second command.", - button1, latestItem); + + " when selecting item's second command.", + button1, latestItem); latestCommand = null; latestItem = null; @@ -561,11 +592,11 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when selecting item's default command from MSK.", - ok2, latestCommand); + + " when selecting item's default command from MSK.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when selecting item's default command from MSK.", - button1, latestItem); + + " when selecting item's default command from MSK.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -575,7 +606,8 @@ * For example makes sure that focus is where it should be. * */ - public void testDynamicUpdate() { + public void testDynamicUpdate() + { latestCommand = null; latestItem = null; @@ -601,11 +633,11 @@ key(Key.RightArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing second button.", - ok2, latestCommand); + + " when pressing second button.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing second button.", - button2, latestItem); + + " when pressing second button.", + button2, latestItem); latestCommand = null; latestItem = null; @@ -616,11 +648,11 @@ key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing second button after update.", - ok2, latestCommand); + + " when pressing second button after update.", + ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing second after update.", - button2, latestItem); + + " when pressing second after update.", + button2, latestItem); latestCommand = null; latestItem = null; @@ -628,11 +660,11 @@ key(Key.LeftArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing first button.", - ok1, latestCommand); + + " when pressing first button.", + ok1, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing first button.", - button1, latestItem); + + " when pressing first button.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -640,7 +672,8 @@ /** * Tests commands when there's label in item. */ - public void testItemWithLabel() { + public void testItemWithLabel() + { latestCommand = null; latestItem = null; @@ -658,35 +691,37 @@ //Click middle soft key, this should activate item's command: key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK (StringItem).", - ok, latestCommand); + + " when pressing MSK (StringItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK (StringItem).", - button1, latestItem); + + " when pressing MSK (StringItem).", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK (StringItem).", - ok, latestCommand); + + " when pressing LSK (StringItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK (StringItem).", - button1, latestItem); + + " when pressing LSK (StringItem).", + button1, latestItem); latestCommand = null; latestItem = null; //Test ImageItem next: Image image = null; - try { + try + { image = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { fail("Cannot load image 100x100.png"); } ImageItem image1 = new ImageItem( - "label", image, Item.BUTTON, "altText", ImageItem.BUTTON); + "label", image, Item.BUTTON, "altText", ImageItem.BUTTON); image1.addCommand(ok); image1.setItemCommandListener(this); @@ -700,22 +735,22 @@ //Click middle soft key, this should activate item's command: key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK (ImageItem).", - ok, latestCommand); + + " when pressing MSK (ImageItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK (ImageItem).", - image1, latestItem); + + " when pressing MSK (ImageItem).", + image1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK (ImageItem).", - ok, latestCommand); + + " when pressing LSK (ImageItem).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK (ImageItem).", - image1, latestItem); + + " when pressing LSK (ImageItem).", + image1, latestItem); latestCommand = null; latestItem = null; } @@ -723,7 +758,8 @@ /** * Tests to add command to item that's focused. */ - public void testAddCommandToFocusedItem() { + public void testAddCommandToFocusedItem() + { latestCommand = null; latestItem = null; @@ -751,22 +787,22 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " when pressing MSK.", - ok, latestCommand); + + " when pressing MSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing MSK.", - button1, latestItem); + + " when pressing MSK.", + button1, latestItem); latestCommand = null; latestItem = null; //Click left soft key, this should activate item's command too: key(Key.CBA1); assertEquals("Command not activated or not correct command" - + " when pressing LSK.", - ok, latestCommand); + + " when pressing LSK.", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when pressing LSK.", - button1, latestItem); + + " when pressing LSK.", + button1, latestItem); latestCommand = null; latestItem = null; } @@ -777,7 +813,8 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; } @@ -788,7 +825,8 @@ * @param c Command * @param d Displayable */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { latestDisplayableCommand = c; latestDisplayable = d; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/customitem/CustomItemTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/customitem/CustomItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/customitem/CustomItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.customitem; @@ -32,22 +32,24 @@ *
            * Created: 2008-12-01 */ -public class CustomItemTest extends ItemUITestBase { +public class CustomItemTest extends ItemUITestBase +{ private static String longString = "Lorem ipsum dolor sit amet, " - + "consectetuer adipiscing elit. Cras turpis ligula, " - + "condimentum nec, rhoncus quis, molestie in, arcu. " - + "Curabitur id lacus. Quisque dictum nulla id odio. " - + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." - + " Integer ut eros. Proin laoreet justo et augue. " - + "Praesent dui. Proin vel leo a eros auctor convallis. " - + "Aenean urna nunc, sagittis vel, pellentesque a, " - + "luctus a, metus. Phasellus posuere lacus nec augue."; + + "consectetuer adipiscing elit. Cras turpis ligula, " + + "condimentum nec, rhoncus quis, molestie in, arcu. " + + "Curabitur id lacus. Quisque dictum nulla id odio. " + + "Nullam nec urna. Cras ac lacus nec lacus iaculis aliquet." + + " Integer ut eros. Proin laoreet justo et augue. " + + "Praesent dui. Proin vel leo a eros auctor convallis. " + + "Aenean urna nunc, sagittis vel, pellentesque a, " + + "luctus a, metus. Phasellus posuere lacus nec augue."; /** * Constructor. */ - public CustomItemTest() { + public CustomItemTest() + { } /** @@ -56,7 +58,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public CustomItemTest(String sTestName, TestMethod rTestMethod) { + public CustomItemTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -66,36 +69,45 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new CustomItemTest("testBasicMethodCalls", - new TestMethod() { - public void run(TestCase tc) { - ((CustomItemTest) tc).testBasicMethodCalls(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((CustomItemTest) tc).testBasicMethodCalls(); + } + })); aSuite.addTest(new CustomItemTest("testInnerTraverse1", - new TestMethod() { - public void run(TestCase tc) { - ((CustomItemTest) tc).testInnerTraversal(1); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((CustomItemTest) tc).testInnerTraversal(1); + } + })); aSuite.addTest(new CustomItemTest("testInnerTraverse3", - new TestMethod() { - public void run(TestCase tc) { - ((CustomItemTest) tc).testInnerTraversal(3); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((CustomItemTest) tc).testInnerTraversal(3); + } + })); aSuite.addTest(new CustomItemTest("testInnerTraverse5", - new TestMethod() { - public void run(TestCase tc) { - ((CustomItemTest) tc).testInnerTraversal(5); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((CustomItemTest) tc).testInnerTraversal(5); + } + })); return aSuite; } @@ -103,7 +115,8 @@ /** * Tests that getMinimumSize returns non-zero values. */ - public void testBasicMethodCalls() { + public void testBasicMethodCalls() + { Form bg = new Form("background"); setCurrent(bg); @@ -120,11 +133,11 @@ setCurrent(form); assertEquals("1. Invalid CustomItem state", - MyCustomItem.TEST_SIZECHANGE - | MyCustomItem.TEST_SHOW - | MyCustomItem.TEST_PAINT - | MyCustomItem.TEST_TRAVERSEIN, - ci1.getState()); + MyCustomItem.TEST_SIZECHANGE + | MyCustomItem.TEST_SHOW + | MyCustomItem.TEST_PAINT + | MyCustomItem.TEST_TRAVERSEIN, + ci1.getState()); assertTrue("invalid width", ci1.width < 1000); @@ -134,22 +147,22 @@ key(Key.CBA1); key(Key.CBA2); assertEquals("2. Invalid CustomItem state", - MyCustomItem.TEST_KEYPRESS - | MyCustomItem.TEST_KEYRELEASE, - ci1.getState()); + MyCustomItem.TEST_KEYPRESS + | MyCustomItem.TEST_KEYRELEASE, + ci1.getState()); // Hide form setCurrent(bg); assertTrue("hideNotify() not called", - ci1.isCalled(MyCustomItem.TEST_HIDE)); + ci1.isCalled(MyCustomItem.TEST_HIDE)); // Set current item ci1.clearState(); display.setCurrentItem(ci1); block(CHANGE_DISPLAYABLE_DELAY); assertTrue("showNotify() not called", - ci1.isCalled(MyCustomItem.TEST_SHOW)); + ci1.isCalled(MyCustomItem.TEST_SHOW)); // partial repaint ci1.clearState(); @@ -157,11 +170,12 @@ block(KEYEVENT_DELAY); assertTrue("paint() not called", ci1.isCalled(MyCustomItem.TEST_PAINT)); assertTrue("wrong clipping area", - ci1.clipX == 10 && ci1.clipY == 5 && - ci1.clipW == 20 && ci1.clipH == 10); + ci1.clipX == 10 && ci1.clipY == 5 && + ci1.clipW == 20 && ci1.clipH == 10); } - void testInnerTraversal(int numInnerTraversals) { + void testInnerTraversal(int numInnerTraversals) + { Form fg = new Form("InnerTraverse " + numInnerTraversals); MyCustomItem ci1 = new MyCustomItem("CustomItem 1", numInnerTraversals); ci1.sizeChanged(1000, 75); @@ -178,39 +192,43 @@ // Traversing to CI 2 ci1.clearState(); ci2.clearState(); - for (int i = 0; i < numInnerTraversals; i++) { + for(int i = 0; i < numInnerTraversals; i++) + { assertTrue("Illegal traversing to CI 2", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); key(Key.DownArrow); } assertTrue("Should traverse to CI 2", - ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) - && ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); + ci1.isCalled(MyCustomItem.TEST_TRAVERSEOUT) + && ci2.isCalled(MyCustomItem.TEST_TRAVERSEIN)); // Traversing back to CI 1 ci1.clearState(); ci2.clearState(); - for (int i = 0; i < numInnerTraversals - 1; i++) { + for(int i = 0; i < numInnerTraversals - 1; i++) + { assertTrue("1. Illegal traversing to CI 1", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); key(Key.DownArrow); } - for (int i = 0; i < numInnerTraversals; i++) { + for(int i = 0; i < numInnerTraversals; i++) + { assertTrue("2. Illegal traversing to CI 1", - !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + !ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && !ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); key(Key.UpArrow); } assertTrue("Should traverse to CI 1", - ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) - && ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); + ci1.isCalled(MyCustomItem.TEST_TRAVERSEIN) + && ci2.isCalled(MyCustomItem.TEST_TRAVERSEOUT)); } - class MyCustomItem extends CustomItem { + class MyCustomItem extends CustomItem + { static final int TEST_SHOW = 1; static final int TEST_HIDE = 2; @@ -228,77 +246,95 @@ int clipX, clipY, clipW, clipH; int width, height; - protected MyCustomItem(String label, int numInnerFocus) { + protected MyCustomItem(String label, int numInnerFocus) + { super(label); numFocus = Math.max(1, numInnerFocus); focus = -1; } - void clearState() { + void clearState() + { state = 0; } - int getState() { + int getState() + { return state; } - boolean isCalled(int mask) { + boolean isCalled(int mask) + { return (state & mask) != 0; } - private void setState(int newState) { + private void setState(int newState) + { state |= newState; } - void doRepaint(int x, int y, int w, int h) { + void doRepaint(int x, int y, int w, int h) + { repaint(x, y, w, h); } - protected void keyPressed(int keyCode) { + protected void keyPressed(int keyCode) + { setState(TEST_KEYPRESS); } - protected void keyReleased(int keyCode) { + protected void keyReleased(int keyCode) + { setState(TEST_KEYRELEASE); } - protected void showNotify() { + protected void showNotify() + { setState(TEST_SHOW); } - protected void hideNotify() { + protected void hideNotify() + { setState(TEST_HIDE); } - protected void sizeChanged(int width, int height) { + protected void sizeChanged(int width, int height) + { this.width = width; this.height = height; setState(TEST_SIZECHANGE); } protected boolean traverse(int dir, int viewportWidth, - int viewportHeight, int[] visRect_inout) { + int viewportHeight, int[] visRect_inout) + { boolean ret = false; setState(TEST_TRAVERSEIN); - if (numFocus == 1) { + if(numFocus == 1) + { focus = 0; } - else if (numFocus > 1) { + else if(numFocus > 1) + { int div = numFocus + 1; focus++; - if (dir == Canvas.UP || dir == Canvas.LEFT) { + if(dir == Canvas.UP || dir == Canvas.LEFT) + { focus = (focus - 1 + div) % div; } - else if (dir == Canvas.DOWN || dir == Canvas.RIGHT) { + else if(dir == Canvas.DOWN || dir == Canvas.RIGHT) + { focus = (focus + 1 + div) % div; } - else { + else + { focus = 1; } focus--; - if (focus > -1) { + if(focus > -1) + { ret = true; } } @@ -306,13 +342,15 @@ return ret; } - protected void traverseOut() { + protected void traverseOut() + { setState(TEST_TRAVERSEOUT); focus = -1; repaint(); } - protected void paint(Graphics g, int w, int h) { + protected void paint(Graphics g, int w, int h) + { setState(TEST_PAINT); clipX = g.getClipX(); @@ -323,25 +361,30 @@ g.setColor(0xffffff); g.fillRect(0, 0, w, h); - if (focus > -1) { + if(focus > -1) + { g.setColor(0x000000); - g.fillRect(0, focus * (h / numFocus), w, h / numFocus); + g.fillRect(0, focus *(h / numFocus), w, h / numFocus); } } - protected int getMinContentHeight() { + protected int getMinContentHeight() + { return height; } - protected int getMinContentWidth() { + protected int getMinContentWidth() + { return width; } - protected int getPrefContentHeight(int h) { + protected int getPrefContentHeight(int h) + { return height; } - protected int getPrefContentWidth(int w) { + protected int getPrefContentWidth(int w) + { return width; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/datefield/DateFieldUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/datefield/DateFieldUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/datefield/DateFieldUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.datefield; @@ -35,7 +35,8 @@ *
            * Created: 2008-10-02 */ -public class DateFieldUIRobotTest extends ItemUITestBase { +public class DateFieldUIRobotTest extends ItemUITestBase +{ //2008-10-07 11:30:35 is 1223368235775 in millis. private static final long TEST_DATE_IN_MILLIS = 1223368235775L; @@ -53,7 +54,8 @@ /** * Constructor. */ - public DateFieldUIRobotTest() { + public DateFieldUIRobotTest() + { } /** @@ -62,7 +64,8 @@ * @param testName Test name. * @param testMethod Test method. */ - public DateFieldUIRobotTest(String testName, TestMethod testMethod) { + public DateFieldUIRobotTest(String testName, TestMethod testMethod) + { super(testName, testMethod); } @@ -71,22 +74,27 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new DateFieldUIRobotTest("testCommands", - new TestMethod() { - public void run(TestCase tc) { - ((DateFieldUIRobotTest) tc).testCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((DateFieldUIRobotTest) tc).testCommands(); + } + })); aSuite.addTest(new DateFieldUIRobotTest("testMinimumSize", - new TestMethod() { - public void run(TestCase tc) { - ((DateFieldUIRobotTest) tc).testMinimumSize(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((DateFieldUIRobotTest) tc).testMinimumSize(); + } + })); // TODO: Following tests wont pass until bug in eSWT is fixed. @@ -140,7 +148,8 @@ /** * Tests the basic functionality of command added to DateField. */ - public void testCommands() { + public void testCommands() + { DateField dateField = new DateField("label", DateField.DATE); testCommand(dateField); } @@ -148,7 +157,8 @@ /** * Tests that getMinimumSize returns non-zero values. */ - public void testMinimumSize() { + public void testMinimumSize() + { //With label: DateField dateField = new DateField("label", DateField.DATE); @@ -156,7 +166,8 @@ int h = dateField.getMinimumHeight(); print("Size returned (with label), w: " + w + ", h: " + h); - if ((w <= 0) || (h <= 0)) { + if((w <= 0) || (h <= 0)) + { fail("Minimum width or height was zero or less."); } @@ -167,7 +178,8 @@ h = dateField2.getMinimumHeight(); print("Size returned (without label), w: " + w + ", h: " + h); - if ((w <= 0) || (h <= 0)) { + if((w <= 0) || (h <= 0)) + { fail("Minimum width or height was zero or less."); } } @@ -175,7 +187,8 @@ /** * Tests to change input mode dynamically. */ - public void testInputModeChange() { + public void testInputModeChange() + { // Create DateField of input mode TIME: DateField dateField = new DateField("label", DateField.TIME); form.append(dateField); @@ -201,13 +214,14 @@ calendar.setTime(newDate); assertEquals("Wrong day returned after input mode changed.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); } /** * Tests the ItemStateChange-listener added to DateField. */ - public void testItemStateChange() { + public void testItemStateChange() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -223,7 +237,7 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); // Change item's state programmatically and make sure the // listener is _not_ called: @@ -234,7 +248,8 @@ /** * Test to get date when user is modifying datefield. */ - public void testGetDateWhenModifying() { + public void testGetDateWhenModifying() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -250,7 +265,8 @@ /** * Test to set and get date. */ - public void testSetAndGetDate() { + public void testSetAndGetDate() + { DateField dateField = new DateField("label", DateField.DATE); form.append(dateField); setCurrent(form); @@ -276,17 +292,18 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals("Wrong month returned.", - TEST_MONTH, calendar.get(Calendar.MONTH)); + TEST_MONTH, calendar.get(Calendar.MONTH)); assertEquals("Wrong year returned.", - TEST_YEAR, calendar.get(Calendar.YEAR)); + TEST_YEAR, calendar.get(Calendar.YEAR)); } /** * Test to set and get time. */ - public void testSetAndGetTime() { + public void testSetAndGetTime() + { DateField dateField = new DateField("label", DateField.TIME); form.append(dateField); setCurrent(form); @@ -311,15 +328,16 @@ calendar.setTime(newDate); assertEquals("Wrong hour returned.", - TEST_HOUR, calendar.get(Calendar.HOUR)); + TEST_HOUR, calendar.get(Calendar.HOUR)); assertEquals("Wrong minute returned.", - TEST_MINUTE, calendar.get(Calendar.MINUTE)); + TEST_MINUTE, calendar.get(Calendar.MINUTE)); } /** * Test to set and get date_time. */ - public void testSetAndGetDateTime() { + public void testSetAndGetDateTime() + { DateField dateField = new DateField("label", DateField.DATE_TIME); form.append(dateField); setCurrent(form); @@ -353,15 +371,15 @@ calendar.setTime(newDate); assertEquals("Wrong day returned.", - TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); + TEST_DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals("Wrong month returned.", - TEST_MONTH, calendar.get(Calendar.MONTH)); + TEST_MONTH, calendar.get(Calendar.MONTH)); assertEquals("Wrong year returned.", - TEST_YEAR, calendar.get(Calendar.YEAR)); + TEST_YEAR, calendar.get(Calendar.YEAR)); assertEquals("Wrong hour returned.", - TEST_HOUR, calendar.get(Calendar.HOUR)); + TEST_HOUR, calendar.get(Calendar.HOUR)); assertEquals("Wrong minute returned.", - TEST_MINUTE, calendar.get(Calendar.MINUTE)); + TEST_MINUTE, calendar.get(Calendar.MINUTE)); } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/FlashAndVibrateTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/FlashAndVibrateTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/FlashAndVibrateTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.display; @@ -34,7 +34,8 @@ *
            * Created: 2008-05-23 */ -public class FlashAndVibrateTest extends UITestBase { +public class FlashAndVibrateTest extends UITestBase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; private static final int SEND_BACKGROUND_DELAY = 300; @@ -46,7 +47,8 @@ /** * Constructor. */ - public FlashAndVibrateTest() { + public FlashAndVibrateTest() + { } /** @@ -55,7 +57,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FlashAndVibrateTest(String sTestName, TestMethod rTestMethod) { + public FlashAndVibrateTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -65,7 +68,8 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); /* @@ -86,13 +90,14 @@ * flashing and vibration are supported and will pass even if there's * no support to the functionality. */ - public void testMethodsWhenBackground() { + public void testMethodsWhenBackground() + { boolean testPassed = true; String testMsg = ""; Display display = Display.getDisplay(getMIDlet()); TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); setCurrent(textBox); @@ -101,15 +106,17 @@ key(Key.Applications, SEND_BACKGROUND_DELAY); - if (display.vibrate(VIBRA_TIME)) { + if(display.vibrate(VIBRA_TIME)) + { testPassed = false; testMsg = "vibrate() returned true when MIDlet was in background."; } - if (display.flashBacklight(FLASH_TIME)) { + if(display.flashBacklight(FLASH_TIME)) + { testPassed = false; testMsg = "flashBacklights() returned true when MIDlet" - + " was in background."; + + " was in background."; } //Move MIDlet back to foreground: diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/SetCurrentItemTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/SetCurrentItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/display/SetCurrentItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.display; @@ -33,7 +33,8 @@ * Created: 2008-08-26 */ public class SetCurrentItemTest extends UITestBase implements - ItemCommandListener { + ItemCommandListener +{ private static int count1; private static int count2; @@ -53,7 +54,8 @@ /** * Constructor. */ - public SetCurrentItemTest() { + public SetCurrentItemTest() + { } /** @@ -62,18 +64,21 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SetCurrentItemTest(String sTestName, TestMethod rTestMethod) { + public SetCurrentItemTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - for (int i = 0; i < sia.length; i++) { - sia[i] = new StringItem("", "click" + (i + 1), Item.BUTTON); - } + for(int i = 0; i < sia.length; i++) + { + sia[i] = new StringItem("", "click" + (i + 1), Item.BUTTON); + } } /** @@ -82,36 +87,45 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new SetCurrentItemTest("testExceptions", - new TestMethod() { - public void run(TestCase tc) { - ((SetCurrentItemTest) tc).testExceptions(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SetCurrentItemTest) tc).testExceptions(); + } + })); aSuite.addTest(new SetCurrentItemTest("testSetCurrentItem", - new TestMethod() { - public void run(TestCase tc) { - ((SetCurrentItemTest) tc).testSetCurrentItem(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SetCurrentItemTest) tc).testSetCurrentItem(); + } + })); aSuite.addTest(new SetCurrentItemTest("testCrash", - new TestMethod() { - public void run(TestCase tc) { - ((SetCurrentItemTest) tc).testCrash(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SetCurrentItemTest) tc).testCrash(); + } + })); aSuite.addTest(new SetCurrentItemTest("displayableSwithTest", - new TestMethod() { - public void run(TestCase tc) { - ((SetCurrentItemTest) tc).displayableSwithTest(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SetCurrentItemTest) tc).displayableSwithTest(); + } + })); return aSuite; } @@ -120,33 +134,40 @@ * Makes sure that setCurrentItem() throws exceptions as * expected. */ - public void testExceptions() { + public void testExceptions() + { boolean exceptionThrown = false; StringItem button1 = new StringItem("", "click!", Item.BUTTON); //Test null item: - try { + try + { display.setCurrentItem(null); } - catch (NullPointerException ex) { + catch(NullPointerException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { fail("No exception when item was null."); } //Test to call method when item is not owned by a container: exceptionThrown = false; - try { + try + { display.setCurrentItem(button1); } - catch (IllegalStateException ex) { + catch(IllegalStateException ex) + { exceptionThrown = true; } - if (!exceptionThrown) { + if(!exceptionThrown) + { fail("No exception when item was not owned by a container."); } } @@ -157,7 +178,8 @@ * visible, is it focusable or not, but the check of item's visibility * is out of scope of this test. */ - public void testSetCurrentItem() { + public void testSetCurrentItem() + { latestCommand = null; latestItem = null; @@ -167,9 +189,10 @@ StringItem button1 = new StringItem("", "click!", Item.BUTTON); StringItem button2 = new StringItem("", "click me2", Item.BUTTON); StringItem[] lotOfButtons = new StringItem[25]; - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { lotOfButtons[i] = new StringItem( - "", "button " + (i + 1), Item.BUTTON); + "", "button " + (i + 1), Item.BUTTON); } Command ok = new Command("Ok", "", Command.ITEM, 0); @@ -184,14 +207,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 1).", - ok, latestCommand); + + " (case 1).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 1).", - button1, latestItem); + + " (case 1).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 1).", - form, display.getCurrent()); + + " (case 1).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -203,14 +226,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 2).", - ok, latestCommand); + + " (case 2).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 2).", - button1, latestItem); + + " (case 2).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 2).", - form, display.getCurrent()); + + " (case 2).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -225,14 +248,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 3).", - ok, latestCommand); + + " (case 3).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 3).", - button1, latestItem); + + " (case 3).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 3).", - form2, display.getCurrent()); + + " (case 3).", + form2, display.getCurrent()); latestCommand = null; latestItem = null; @@ -240,7 +263,8 @@ //Test method when item is in another displayable //and there are lot of items before the item: form2.deleteAll(); - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { form.append(lotOfButtons[i]); } form.append(button1); @@ -251,14 +275,14 @@ block(500); key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 4).", - ok, latestCommand); + + " (case 4).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 4).", - button1, latestItem); + + " (case 4).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 4).", - form, display.getCurrent()); + + " (case 4).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -267,7 +291,8 @@ //and there are lot of items before the item: form.deleteAll(); form.append(button1); - for (int i = 0; i < lotOfButtons.length; i++) { + for(int i = 0; i < lotOfButtons.length; i++) + { form.append(lotOfButtons[i]); } form.append(button2); @@ -281,14 +306,14 @@ key(Key.Select); assertEquals("Command not activated or not correct command" - + " (case 5).", - ok, latestCommand); + + " (case 5).", + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " (case 5).", - button1, latestItem); + + " (case 5).", + button1, latestItem); assertEquals("Unexpected displayable" - + " (case 5).", - form, display.getCurrent()); + + " (case 5).", + form, display.getCurrent()); latestCommand = null; latestItem = null; @@ -307,7 +332,8 @@ * Test tries to make setCurrentItem()-method crash or hang * the midlet somehow. */ - public void testCrash() { + public void testCrash() + { Form form = new Form("form"); Form form2 = new Form("form2"); StringItem plain1 = new StringItem("", "not focusable.", Item.PLAIN); @@ -330,7 +356,8 @@ //Make many calls without delay: form.append(button1); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) + { display.setCurrentItem(button1); display.setCurrentItem(plain1); } @@ -342,7 +369,8 @@ * Displayable is switched to new one, but old still has * doLayout() ongoing. */ - public void displayableSwithTest() { + public void displayableSwithTest() + { Form form = new Form("form"); Form form2 = new Form("form2"); @@ -360,7 +388,8 @@ form.append(button1); form.append(button2); - for (int i = 0; i < sia.length; i++) { + for(int i = 0; i < sia.length; i++) + { form2.append(sia[i]); sia[i].addCommand(c3); } @@ -372,7 +401,7 @@ block(CHANGE_DISPLAYABLE_DELAY); key(Key.Select); assertEquals("Not Correct Comand was called, probable Displayable" - + " switched back to initial.", c3, latestCommand); + + " switched back to initial.", c3, latestCommand); } /** @@ -381,24 +410,28 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; - if (c == c1) { + if(c == c1) + { System.out.println("button1 clicked, command: " + c + " item: " - + item); + + item); button1.setText("clicks: " + (++count1)); display.setCurrentItem(button3); //display.setCurrentItem(sia[sia.length-1]); } - else if (c == c2) { + else if(c == c2) + { System.out.println("button2 clicked, command: " + c + " item: " - + item); + + item); button2.setText("clicks: " + (++count2)); } - else if (c == c3) { + else if(c == c3) + { System.out.println("button3 clicked, command: " + c + " item: " - + item); + + item); //button3.setText("clicks: "+ (++count3)); display.setCurrentItem(button1); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/AddCommandTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/AddCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/AddCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.displayable; @@ -34,62 +34,76 @@ *
            * Created: 2008-04-30 */ -public class AddCommandTest extends UITestBase { +public class AddCommandTest extends UITestBase +{ private static final int MAX_CHARS = 100; - public AddCommandTest() { - super(); - } + public AddCommandTest() + { + super(); + } - public AddCommandTest(String name, TestMethod method) { - super(name, method); - } + public AddCommandTest(String name, TestMethod method) + { + super(name, method); + } - /** + /** /** * Creates the test suite. You need to add a new aSuite.addTest antry for * any new test methods, otherwise they won't be run. * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new AddCommandTest("testAddCommandBeforeListener", - new TestMethod() { - public void run(TestCase tc) { - ((AddCommandTest) tc).testAddCommandBeforeListener(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AddCommandTest) tc).testAddCommandBeforeListener(); + } + })); aSuite.addTest(new AddCommandTest("testAddCommandAfterListener", - new TestMethod() { - public void run(TestCase tc) { - ((AddCommandTest) tc).testAddCommandAfterListener(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AddCommandTest) tc).testAddCommandAfterListener(); + } + })); aSuite.addTest(new AddCommandTest("testRemoveListener", - new TestMethod() { - public void run(TestCase tc) { - ((AddCommandTest) tc).testRemoveListener(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AddCommandTest) tc).testRemoveListener(); + } + })); aSuite.addTest(new AddCommandTest("testAddToManyDisplayables", - new TestMethod() { - public void run(TestCase tc) { - ((AddCommandTest) tc).testAddToManyDisplayables(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AddCommandTest) tc).testAddToManyDisplayables(); + } + })); aSuite.addTest(new AddCommandTest("testAddCommandTwice", - new TestMethod() { - public void run(TestCase tc) { - ((AddCommandTest) tc).testAddCommandTwice(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((AddCommandTest) tc).testAddCommandTwice(); + } + })); return aSuite; } @@ -97,7 +111,8 @@ /** * Test command adding before CommandListener is set. */ - public void testAddCommandBeforeListener() { + public void testAddCommandBeforeListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -115,7 +130,8 @@ /** * Test command adding after CommandListener is set. */ - public void testAddCommandAfterListener() { + public void testAddCommandAfterListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -134,7 +150,8 @@ * Test that removing CommandListener will work and no commands are * delivered to CommandListener anymore. */ - public void testRemoveListener() { + public void testRemoveListener() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); @@ -156,7 +173,8 @@ * In LCDUI it's possible to add same Command to many Displayables. This * test tests that events occurs correctly in such case. */ - public void testAddToManyDisplayables() { + public void testAddToManyDisplayables() + { // There are two Displayables and one Command in this test: TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); TextBox textBox2 = new TextBox("title2", "content2", MAX_CHARS, 0); @@ -210,7 +228,8 @@ * Tests that nothing happens if command is added to the displayable which * already contains the command. */ - public void testAddCommandTwice() { + public void testAddCommandTwice() + { TextBox textBox = new TextBox("title", "content", MAX_CHARS, 0); Command c1 = new Command("item1", "item1", Command.ITEM, 0); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SendBackgroundTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SendBackgroundTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SendBackgroundTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.displayable; @@ -33,7 +33,8 @@ *
            * Created: 2008-05-07 */ -public class SendBackgroundTest extends UITestBase { +public class SendBackgroundTest extends UITestBase +{ private static final int MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX = 100; private static final int SEND_BACKGROUND_DELAY = 300; @@ -42,8 +43,9 @@ /** * Constructor. */ - public SendBackgroundTest() { - super(); + public SendBackgroundTest() + { + super(); } /** @@ -52,7 +54,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SendBackgroundTest(String sTestName, TestMethod rTestMethod) { + public SendBackgroundTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -62,29 +65,36 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new SendBackgroundTest("testIsShownWhenBackground", - new TestMethod() { - public void run(TestCase tc) { - ((SendBackgroundTest) tc).testIsShownWhenBackground(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SendBackgroundTest) tc).testIsShownWhenBackground(); + } + })); aSuite.addTest(new SendBackgroundTest("testIsShownWhenNotCurrent", - new TestMethod() { - public void run(TestCase tc) { - ((SendBackgroundTest) tc).testIsShownWhenNotCurrent(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SendBackgroundTest) tc).testIsShownWhenNotCurrent(); + } + })); aSuite.addTest(new SendBackgroundTest("testGetHeightAndWidth", - new TestMethod() { - public void run(TestCase tc) { - ((SendBackgroundTest) tc).testGetHeightAndWidth(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SendBackgroundTest) tc).testGetHeightAndWidth(); + } + })); return aSuite; } @@ -93,12 +103,13 @@ * Test that isShown()-method returns false when displayable is in * background. */ - public void testIsShownWhenBackground() { + public void testIsShownWhenBackground() + { boolean testPassed = true; String testMsg = ""; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); setCurrent(textBox); @@ -106,7 +117,8 @@ // returns false: key(Key.Applications, SEND_BACKGROUND_DELAY); - if (textBox.isShown()) { + if(textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned true when MIDlet was in background."; } @@ -118,7 +130,8 @@ key(Key.Select, 0); key(Key.Select, SEND_FOREGROUND_DELAY); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when MIDlet was in foreground."; } @@ -130,18 +143,20 @@ * Tests that isShown() returns false if displayable is first set current * and then another displayable is set current. */ - public void testIsShownWhenNotCurrent() { + public void testIsShownWhenNotCurrent() + { boolean testPassed = true; String testMsg = ""; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); // First set displayable current and make sure it's shown: setCurrent(textBox); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when displayable current."; } @@ -150,7 +165,8 @@ // one isn't shown: setCurrent(textBox2); - if (textBox.isShown()) { + if(textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned true when displayable isn't current."; } @@ -158,10 +174,11 @@ // Now move first displayable back to current and make sure // it knows it's shown: setCurrent(textBox); - if (!textBox.isShown()) { + if(!textBox.isShown()) + { testPassed = false; testMsg = "isShown() returned false when displayable set " - + " back to current."; + + " back to current."; } assertTrue(getName() + " failed, " + testMsg, testPassed); @@ -171,16 +188,17 @@ * Tests the functionality of getWidth() and getHeight()-methods when * displayable not current and when MIDlet is sent to background. */ - public void testGetHeightAndWidth() { + public void testGetHeightAndWidth() + { boolean testPassed = true; String testMsg = ""; int width = 0; int height = 0; TextBox textBox = new TextBox("title", "content", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); TextBox textBox2 = new TextBox("title2", "content2", - MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); + MAX_NUM_OF_CHARS_IN_TEST_TEXTBOX, 0); // Get initial values: width = textBox.getWidth(); @@ -189,23 +207,25 @@ // Set displayable to current and make sure the dimension isn't changed: setCurrent(textBox); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after displayable set current:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } // Send MIDlet to background and verify that dimension remains same: key(Key.Applications, SEND_BACKGROUND_DELAY); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after MIDlet sent to background:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } // Move MIDlet back to foreground: @@ -218,12 +238,13 @@ // of first displayable remains same: setCurrent(textBox2); - if ((textBox.getWidth() != width) || (textBox.getHeight() != height)) { + if((textBox.getWidth() != width) || (textBox.getHeight() != height)) + { testPassed = false; testMsg = "dimension changed after other displayable set current:" - + " original w: " + width + " original h:" + height - + " new w: " + textBox.getWidth() + " new h: " - + textBox.getHeight(); + + " original w: " + width + " original h:" + height + + " new w: " + textBox.getWidth() + " new h: " + + textBox.getHeight(); } assertTrue(getName() + " failed, " + testMsg, testPassed); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SizeChangedTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SizeChangedTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/displayable/SizeChangedTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.displayable; @@ -30,7 +30,8 @@ *
            * Created: 2008-05-19 */ -public class SizeChangedTest extends UITestBase { +public class SizeChangedTest extends UITestBase +{ private static final int MAX_CHARS = 100; private static final int DELAY_AFTER_RESOLUTION_CHANGE = 300; @@ -43,8 +44,9 @@ /** * Constructor. */ - public SizeChangedTest() { - super(); + public SizeChangedTest() + { + super(); } /** @@ -53,7 +55,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SizeChangedTest(String sTestName, TestMethod rTestMethod) { + public SizeChangedTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -63,11 +66,14 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); - aSuite.addTest(new SizeChangedTest("testSizeChange", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new SizeChangedTest("testSizeChange", new TestMethod() + { + public void run(TestCase tc) + { ((SizeChangedTest) tc).testSizeChange(); } })); @@ -80,7 +86,8 @@ * sizeChanged()-method. Then verifies the method is called as described in * API spesification. */ - public void testSizeChange() { + public void testSizeChange() + { boolean testPassed = true; String testMsg = ""; int width; @@ -93,10 +100,11 @@ // Displayable is set to visible: setCurrent(scl); - if (firstCallFailure) { + if(firstCallFailure) + { testPassed = false; testMsg = "sizeChanged not called before" - + " displayable set to visible."; + + " displayable set to visible."; } sizeChangedFlag = false; width = newWidth; @@ -109,17 +117,20 @@ // Verify that sizeChanged() is called and the // width and height values are not the same as before: - if (!sizeChangedFlag) { + if(!sizeChangedFlag) + { testPassed = false; testMsg = "sizeChanged not called when" - + " screen dimension changed."; + + " screen dimension changed."; } - else if (width == newWidth) { + else if(width == newWidth) + { testPassed = false; testMsg = "width not updated when" + " screen dimension changed."; } - else if (height == newHeight) { + else if(height == newHeight) + { testPassed = false; testMsg = "height not updated when" + " screen dimension changed."; } @@ -134,7 +145,8 @@ // Change the size of the invisible displayable by // changing the screen resolution back to original: - for (int i = 0; i < spede().getNumberofResolutions() - 1; i++) { + for(int i = 0; i < spede().getNumberofResolutions() - 1; i++) + { spede().switchResolution(); } block(DELAY_AFTER_RESOLUTION_CHANGE); @@ -144,21 +156,24 @@ // Also make sure the width and height are updated. setCurrent(scl); - if (!sizeChangedFlag) { + if(!sizeChangedFlag) + { testPassed = false; testMsg = "sizeChanged not called when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } - else if (width == newWidth) { + else if(width == newWidth) + { testPassed = false; testMsg = "width not updated when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } - else if (height == newHeight) { + else if(height == newHeight) + { testPassed = false; testMsg = "height not updated when screen" - + " dimension changed and displayable in background."; + + " dimension changed and displayable in background."; } assertTrue(getName() + " failed, " + testMsg, testPassed); @@ -169,19 +184,23 @@ * extend Displayable directly. That's why Canvas is extended here. Another * possible class would be Form. */ - class SizeChangeListener extends Canvas { + class SizeChangeListener extends Canvas + { private boolean firstCall = true; /* (non-Javadoc) * @see javax.microedition.lcdui.Canvas#sizeChanged(int, int) */ - protected void sizeChanged(int w, int h) { - if (firstCall) { + protected void sizeChanged(int w, int h) + { + if(firstCall) + { // sizeChanged must be called at least once // before displayable is set to visible. // Make sure the displayable is not visible yet: - if (isShown()) { + if(isShown()) + { firstCallFailure = true; } firstCall = false; @@ -192,7 +211,8 @@ newHeight = h; } - protected void paint(Graphics g) { + protected void paint(Graphics g) + { } } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/form/FormItemTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/form/FormItemTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/form/FormItemTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.form; @@ -33,13 +33,15 @@ *
            * Created: 2008-11-12 */ -public class FormItemTest extends ItemUITestBase { +public class FormItemTest extends ItemUITestBase +{ /** * Constructor. */ - public FormItemTest() { - super(); + public FormItemTest() + { + super(); } /** @@ -48,7 +50,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FormItemTest(String sTestName, TestMethod rTestMethod) { + public FormItemTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -58,32 +61,39 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new FormItemTest("testAppendItemAfterSetCurrent", - new TestMethod() { - public void run(TestCase tc) { - ((FormItemTest) tc).testAppendItemAfterSetCurrent(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((FormItemTest) tc).testAppendItemAfterSetCurrent(); + } + })); aSuite.addTest(new FormItemTest( - "testRemoveCommandFromLabeledFocusedItem", - new TestMethod() { - public void run(TestCase tc) { - ((FormItemTest) tc). - testRemoveCommandFromLabeledFocusedItem(); - } - })); + "testRemoveCommandFromLabeledFocusedItem", + new TestMethod() + { + public void run(TestCase tc) + { + ((FormItemTest) tc). + testRemoveCommandFromLabeledFocusedItem(); + } + })); aSuite.addTest(new FormItemTest( - "testAddRemoveItems", - new TestMethod() { - public void run(TestCase tc) { - ((FormItemTest) tc).testAddRemoveItems(); - } - })); + "testAddRemoveItems", + new TestMethod() + { + public void run(TestCase tc) + { + ((FormItemTest) tc).testAddRemoveItems(); + } + })); /* aSuite.addTest(new FormItemTest("testRemoveItemsWhenBackground", @@ -92,7 +102,7 @@ ((FormItemTest) tc).testRemoveItemsWhenBackground(); } })); - */ + */ return aSuite; } @@ -101,7 +111,8 @@ * Tests to remove command from focused item which has label and * verifies that focus is moved to next/previous focusable item. */ - public void testRemoveCommandFromLabeledFocusedItem() { + public void testRemoveCommandFromLabeledFocusedItem() + { StringItem button1 = new StringItem("label", "click!", Item.BUTTON); StringItem button2 = new StringItem("label", "click2!", Item.BUTTON); @@ -140,7 +151,8 @@ /** * Tests to add and remove items to/from form. */ - public void testAddRemoveItems() { + public void testAddRemoveItems() + { Command ok1 = new Command("Ok1", "", Command.ITEM, 0); Command ok2 = new Command("Ok2", "", Command.ITEM, 0); @@ -182,11 +194,12 @@ * Tests to append item to form after form is set current. Then * verifies the focus transfer works. */ - public void testAppendItemAfterSetCurrent() { + public void testAppendItemAfterSetCurrent() + { StringItem hyperlink = new StringItem("label", "url", - StringItem.HYPERLINK); + StringItem.HYPERLINK); StringItem button1 = new StringItem(null, "button1", - StringItem.BUTTON); + StringItem.BUTTON); Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); button1.addCommand(dummyCommand); @@ -218,9 +231,10 @@ /** * Test that command are working properly in case of */ - public void testRemoveItemsWhenBackground() { - Form forma = new Form ("Form A"); - Form formb = new Form ("Form B"); + public void testRemoveItemsWhenBackground() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); Command dummyCommand1 = new Command("dummy1", "", Command.ITEM, 0); Command dummyCommand2 = new Command("dummy2", "", Command.ITEM, 0); Command dummyCommand3 = new Command("dummy3", "", Command.ITEM, 0); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/gauge/GaugeCommandsTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/gauge/GaugeCommandsTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/gauge/GaugeCommandsTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.gauge; @@ -33,7 +33,8 @@ *
            * Created: 2008-09-15 */ -public class GaugeCommandsTest extends ItemUITestBase { +public class GaugeCommandsTest extends ItemUITestBase +{ private static final int GAUGE_MAX_VALUE = 10; private static final int GAUGE_MAX_VALUE_2 = 5; @@ -42,7 +43,8 @@ /** * Constructor. */ - public GaugeCommandsTest() { + public GaugeCommandsTest() + { } /** @@ -51,7 +53,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public GaugeCommandsTest(String sTestName, TestMethod rTestMethod) { + public GaugeCommandsTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -61,15 +64,18 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new GaugeCommandsTest("testCommands", - new TestMethod() { - public void run(TestCase tc) { - ((GaugeCommandsTest) tc).testCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((GaugeCommandsTest) tc).testCommands(); + } + })); // TODO: currently failing because ProgressBar is not focusable. // It is not clear should it be focusable in future? @@ -83,50 +89,56 @@ */ aSuite.addTest(new GaugeCommandsTest("testValueChange", - new TestMethod() { - public void run(TestCase tc) { - ((GaugeCommandsTest) tc).testValueChange(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((GaugeCommandsTest) tc).testValueChange(); + } + })); aSuite.addTest(new GaugeCommandsTest("testItemState", - new TestMethod() { - public void run(TestCase tc) { - ((GaugeCommandsTest) tc).testItemState(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((GaugeCommandsTest) tc).testItemState(); + } + })); return aSuite; } /** - * Tests the basic functionality of command added to Gauge. - */ - public void testCommands() { - Gauge gauge = new Gauge("interactive, max=10, initial=0", true, - GAUGE_MAX_VALUE, 0); - - Command ok = new Command("Ok", "", Command.ITEM, 0); - gauge.addCommand(ok); - gauge.setItemCommandListener(this); + * Tests the basic functionality of command added to Gauge. + */ + public void testCommands() + { + Gauge gauge = new Gauge("interactive, max=10, initial=0", true, + GAUGE_MAX_VALUE, 0); - form.append(gauge); + Command ok = new Command("Ok", "", Command.ITEM, 0); + gauge.addCommand(ok); + gauge.setItemCommandListener(this); - Display.getDisplay(getMIDlet()).setCurrent(form); - block(CHANGE_DISPLAYABLE_DELAY); + form.append(gauge); - // Click command and verify it works: - key(Key.CBA1); - assertItemCmdListener("", ok, gauge); - } + Display.getDisplay(getMIDlet()).setCurrent(form); + block(CHANGE_DISPLAYABLE_DELAY); + + // Click command and verify it works: + key(Key.CBA1); + assertItemCmdListener("", ok, gauge); + } /** - * It should be possible to add commands to non-interactive gauges too and - * in that case gauges should be selectable. - */ - public void testNoninteractiveCommands() { + * It should be possible to add commands to non-interactive gauges too and + * in that case gauges should be selectable. + */ + public void testNoninteractiveCommands() + { Gauge gauge = new Gauge("non-interactive, max=10, initial=0", - false, GAUGE_MAX_VALUE, 0); + false, GAUGE_MAX_VALUE, 0); Command ok = new Command("Ok", "", Command.ITEM, 0); StringItem button1 = new StringItem("", "click!", Item.BUTTON); button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); @@ -141,7 +153,7 @@ // Click LSK and verify it activates command: key(Key.CBA1); - assertItemCmdListener("case1", ok, gauge); + assertItemCmdListener("case1", ok, gauge); // Add button, change focus to it and make sure it is possible // to move focus back to gauge: @@ -155,64 +167,66 @@ } /** - * Tests Gauge's value changing. - */ - public void testValueChange() { - Gauge gauge = new Gauge("interactive, max=10, initial=0", true, - GAUGE_MAX_VALUE, 0); - StringItem button1 = new StringItem("", "click!", Item.BUTTON); - button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); + * Tests Gauge's value changing. + */ + public void testValueChange() + { + Gauge gauge = new Gauge("interactive, max=10, initial=0", true, + GAUGE_MAX_VALUE, 0); + StringItem button1 = new StringItem("", "click!", Item.BUTTON); + button1.addCommand(new Command("Ok1", "", Command.ITEM, 0)); - form.append(gauge); + form.append(gauge); - // Add dummy button after gauge. This makes sure that the focus - // is not moving when pressing right-arrow when gauge is selected. - form.append(button1); + // Add dummy button after gauge. This makes sure that the focus + // is not moving when pressing right-arrow when gauge is selected. + form.append(button1); - setCurrent(form); + setCurrent(form); - // Change gauge value: - key(Key.RightArrow); - assertEquals("Wrong gauge value (case 1).", 1, gauge.getValue()); + // Change gauge value: + key(Key.RightArrow); + assertEquals("Wrong gauge value (case 1).", 1, gauge.getValue()); - // Change gauge value back to original: - key(Key.LeftArrow); - assertEquals("Wrong gauge value (case 2).", 0, gauge.getValue()); + // Change gauge value back to original: + key(Key.LeftArrow); + assertEquals("Wrong gauge value (case 2).", 0, gauge.getValue()); - // Change value dynamically: - gauge.setValue(GAUGE_MAX_VALUE); + // Change value dynamically: + gauge.setValue(GAUGE_MAX_VALUE); - // Change maximum value to be lower than current value: - gauge.setMaxValue(GAUGE_MAX_VALUE_2); + // Change maximum value to be lower than current value: + gauge.setMaxValue(GAUGE_MAX_VALUE_2); - // Make sure the current value is changed to maximum: - assertEquals("Current value not changed to maximum.", - GAUGE_MAX_VALUE_2, gauge.getValue()); + // Make sure the current value is changed to maximum: + assertEquals("Current value not changed to maximum.", + GAUGE_MAX_VALUE_2, gauge.getValue()); - // Set value to minimum and then move value by using keypresses. - // That makes sure the visual appearance of gauge is changed dynamically - // when value is changed programmatically: - gauge.setValue(0); - key(Key.RightArrow); - key(Key.RightArrow); + // Set value to minimum and then move value by using keypresses. + // That makes sure the visual appearance of gauge is changed dynamically + // when value is changed programmatically: + gauge.setValue(0); + key(Key.RightArrow); + key(Key.RightArrow); - assertEquals("Value not expected after setValue()-call.", - GAUGE_TEST_VALUE, gauge.getValue()); + assertEquals("Value not expected after setValue()-call.", + GAUGE_TEST_VALUE, gauge.getValue()); - // Remove gauge from form and try to set value again: - form.deleteAll(); - gauge.setValue(GAUGE_TEST_VALUE); - assertEquals("Value not expected after gauge removed from form.", - GAUGE_TEST_VALUE, gauge.getValue()); - } + // Remove gauge from form and try to set value again: + form.deleteAll(); + gauge.setValue(GAUGE_TEST_VALUE); + assertEquals("Value not expected after gauge removed from form.", + GAUGE_TEST_VALUE, gauge.getValue()); + } /** - * Tests that Form receives ItemStateChanged-events when gauge's value is - * changed. - */ - public void testItemState() { + * Tests that Form receives ItemStateChanged-events when gauge's value is + * changed. + */ + public void testItemState() + { Gauge gauge = new Gauge("interactive, max=10, initial=0", - true, GAUGE_MAX_VALUE, 0); + true, GAUGE_MAX_VALUE, 0); form.append(gauge); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/imageitem/ImageItemHyperLinkTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/imageitem/ImageItemHyperLinkTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/imageitem/ImageItemHyperLinkTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.imageitem; @@ -34,7 +34,8 @@ *
            * Created: 2008-10-20 */ -public class ImageItemHyperLinkTest extends ItemUITestBase { +public class ImageItemHyperLinkTest extends ItemUITestBase +{ private Image smallImage; private Image mediumImage; @@ -43,7 +44,8 @@ /** * Constructor. */ - public ImageItemHyperLinkTest() { + public ImageItemHyperLinkTest() + { } /** @@ -52,31 +54,39 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public ImageItemHyperLinkTest(String sTestName, TestMethod rTestMethod) { + public ImageItemHyperLinkTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { - super.setUp(); - try { + protected void setUp() throws Exception + { + super.setUp(); + try + { smallImage = Image.createImage("32x32.jpeg"); } - catch (IOException e) { + catch(IOException e) + { // } - try { + try + { mediumImage = Image.createImage("100x100.png"); } - catch (IOException e) { + catch(IOException e) + { // } - try { + try + { longImage = Image.createImage("100x300.png"); } - catch (IOException e) { + catch(IOException e) + { // } } @@ -87,80 +97,97 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new ImageItemHyperLinkTest("testCommands", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc).testCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc).testCommands(); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testAppearanceModeChangePlain", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testAppearanceModeChange(ImageItem.PLAIN); - } - })); + "testAppearanceModeChangePlain", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testAppearanceModeChange(ImageItem.PLAIN); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testAppearanceModeChangeButton", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testAppearanceModeChange(ImageItem.BUTTON); - } - })); + "testAppearanceModeChangeButton", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testAppearanceModeChange(ImageItem.BUTTON); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testAppearanceModeChangeHyperlink", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testAppearanceModeChange(ImageItem.HYPERLINK); - } - })); + "testAppearanceModeChangeHyperlink", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testAppearanceModeChange(ImageItem.HYPERLINK); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testFocusInAppearanceModeChangePlain", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testFocusInAppearanceModeChange(ImageItem.PLAIN); - } - })); + "testFocusInAppearanceModeChangePlain", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testFocusInAppearanceModeChange(ImageItem.PLAIN); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testFocusInAppearanceModeChangeButton", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testFocusInAppearanceModeChange(ImageItem.BUTTON); - } - })); + "testFocusInAppearanceModeChangeButton", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testFocusInAppearanceModeChange(ImageItem.BUTTON); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testFocusInAppearanceModeChangeHyperlink", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testFocusInAppearanceModeChange(ImageItem.HYPERLINK); - } - })); + "testFocusInAppearanceModeChangeHyperlink", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testFocusInAppearanceModeChange(ImageItem.HYPERLINK); + } + })); aSuite.addTest(new ImageItemHyperLinkTest( - "testLongImageHyperlink", - new TestMethod() { - public void run(TestCase tc) { - ((ImageItemHyperLinkTest) tc). - testLongImageHyperlink(); - } - })); + "testLongImageHyperlink", + new TestMethod() + { + public void run(TestCase tc) + { + ((ImageItemHyperLinkTest) tc). + testLongImageHyperlink(); + } + })); return aSuite; } @@ -168,9 +195,10 @@ /** * Tests the basic functionality of command added to Hyperlink. */ - public void testCommands() { + public void testCommands() + { ImageItem hyperlink = new ImageItem("label", smallImage, 0, "small", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); testCommand(hyperlink); @@ -179,14 +207,14 @@ form.deleteAll(); Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); ImageItem button1 = new ImageItem(null, smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem(null, smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); button1.addCommand(dummyCommand); button2.addCommand(dummyCommand); ImageItem hyperlink3 = new ImageItem(null, mediumImage, 0, "medium", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); hyperlink3.addCommand(ok); hyperlink3.setItemCommandListener(this); @@ -212,20 +240,22 @@ * * @param mode Appearancemode of ImageItem. */ - public void testAppearanceModeChange(int mode) { - switch (mode) { - case ImageItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case ImageItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case ImageItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; + public void testAppearanceModeChange(int mode) + { + switch(mode) + { + case ImageItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case ImageItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case ImageItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; } ImageItem imageItem = new ImageItem("label", smallImage, 0, "url", mode); @@ -249,39 +279,41 @@ imageItem.addCommand(ok); block(CHANGE_DISPLAYABLE_DELAY); - key(Key.CBA1); + key(Key.CBA1); assertItemCmdListener("Added command", ok, imageItem); } /** - * Tests that focus transfer works when commands are added/removed - * dynamically. - * - * @param mode - * Appearancemode of ImageItem. - */ - public void testFocusInAppearanceModeChange(int mode) { - switch (mode) { - case ImageItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case ImageItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case ImageItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; + * Tests that focus transfer works when commands are added/removed + * dynamically. + * + * @param mode + * Appearancemode of ImageItem. + */ + public void testFocusInAppearanceModeChange(int mode) + { + switch(mode) + { + case ImageItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case ImageItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case ImageItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; } ImageItem imageItem = new ImageItem(null, smallImage, 0, "url", mode); ImageItem button1 = new ImageItem(null, mediumImage, 0, "button1", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem(null, smallImage, 0, "button2", - ImageItem.BUTTON); + ImageItem.BUTTON); Command ok = new Command("Ok", "", Command.ITEM, 0); Command buttonCommand1 = new Command("bc1", "", Command.ITEM, 0); @@ -350,16 +382,17 @@ * test that ImageItem of HYPERLINK type working ok with when image is * bigger then screensize. */ - public void testLongImageHyperlink() { + public void testLongImageHyperlink() + { ImageItem imageItem = new ImageItem(null, smallImage, 0, "button", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem hyperlink1 = new ImageItem(null, longImage, 0, "hyperlink", - ImageItem.HYPERLINK); + ImageItem.HYPERLINK); hyperlink1.setLayout(Item.LAYOUT_RIGHT); ImageItem hyperlink2 = new ImageItem(null, smallImage, 0, "button2", - ImageItem.BUTTON); + ImageItem.BUTTON); hyperlink2.setLayout(Item.LAYOUT_CENTER); Form forma = new Form("Form A"); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/item/ItemUITest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/item/ItemUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/item/ItemUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.item; @@ -33,7 +33,8 @@ *
            * Created: 2008-12-05 */ -public class ItemUITest extends ItemUITestBase { +public class ItemUITest extends ItemUITestBase +{ private static final int BIG_PREFERRED_HEIGHT = 500; private static final int BIG_PREFERRED_WIDTH = 2500; @@ -52,7 +53,8 @@ /** * Constructor. */ - public ItemUITest() { + public ItemUITest() + { } /** @@ -61,7 +63,8 @@ * @param testName Test name. * @param testMethod Test method. */ - public ItemUITest(String testName, TestMethod testMethod) { + public ItemUITest(String testName, TestMethod testMethod) + { super(testName, testMethod); } @@ -71,143 +74,167 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite suite = new TestSuite(); suite.addTest(new ItemUITest("testPreferredSizes, Datefield (time)", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new DateField(null, DateField.TIME), true); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new DateField(null, DateField.TIME), true); + } + })); suite.addTest(new ItemUITest("testPreferredSizes, Datefield (date)", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new DateField(null, DateField.DATE), true); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new DateField(null, DateField.DATE), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, Datefield (datetime)", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new DateField(null, DateField.DATE_TIME), true); - } - })); + "testPreferredSizes, Datefield (datetime)", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new DateField(null, DateField.DATE_TIME), true); + } + })); suite.addTest(new ItemUITest("testPreferredSizes," - + " Non-interactive gauge", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new Gauge(null, false, - GAUGE_MAX_VALUE, - GAUGE_INITIAL_VALUE), false); - } - })); + + " Non-interactive gauge", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new Gauge(null, false, + GAUGE_MAX_VALUE, + GAUGE_INITIAL_VALUE), false); + } + })); suite.addTest(new ItemUITest("testPreferredSizes, Interactive gauge", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new Gauge(null, true, - GAUGE_MAX_VALUE, - GAUGE_INITIAL_VALUE), true); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new Gauge(null, true, + GAUGE_MAX_VALUE, + GAUGE_INITIAL_VALUE), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, button stringItem, short text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, "short text", - Item.BUTTON), true); - } - })); + "testPreferredSizes, button stringItem, short text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, "short text", + Item.BUTTON), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, button stringItem, long text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.BUTTON), true); - } - })); + "testPreferredSizes, button stringItem, long text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.BUTTON), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, hyperlink stringItem, short text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, "short text", - Item.HYPERLINK), true); - } - })); + "testPreferredSizes, hyperlink stringItem, short text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, "short text", + Item.HYPERLINK), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, hyperlink stringItem, long text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.HYPERLINK), true); - } - })); + "testPreferredSizes, hyperlink stringItem, long text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.HYPERLINK), true); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, plain stringItem, short text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, "short text", - Item.PLAIN), false); - } - })); + "testPreferredSizes, plain stringItem, short text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, "short text", + Item.PLAIN), false); + } + })); suite.addTest(new ItemUITest( - "testPreferredSizes, plain stringItem, long text", - new TestMethod() { - public void run(TestCase tc) { - ((ItemUITest) tc).testPreferredSizes( - new StringItem(null, - "This is long text," - + " so long that it " - + "won't fit to one line", - Item.PLAIN), false); - } - })); + "testPreferredSizes, plain stringItem, long text", + new TestMethod() + { + public void run(TestCase tc) + { + ((ItemUITest) tc).testPreferredSizes( + new StringItem(null, + "This is long text," + + " so long that it " + + "won't fit to one line", + Item.PLAIN), false); + } + })); return suite; } /** - * Tests preferred size of specified item. This method only makes sure that - * setting and getting preferred size won't crash the application and the - * values returned are somewhat meaningful, for example not negative. It - * also makes sure the focus stays in item when preferred size is changed. - * - * @param item - * Item to be tested. It doesn't matter does item has label or - * not. Method will test preferred size with and without label - * automatically. - * @param testCommands - * If true, method will make sure the focus is not changed when - * preferred size is changed and commands works all the time. - * This must be false if item cant have commands. - */ - public void testPreferredSizes(Item item, boolean testCommands) { + * Tests preferred size of specified item. This method only makes sure that + * setting and getting preferred size won't crash the application and the + * values returned are somewhat meaningful, for example not negative. It + * also makes sure the focus stays in item when preferred size is changed. + * + * @param item + * Item to be tested. It doesn't matter does item has label or + * not. Method will test preferred size with and without label + * automatically. + * @param testCommands + * If true, method will make sure the focus is not changed when + * preferred size is changed and commands works all the time. + * This must be false if item cant have commands. + */ + public void testPreferredSizes(Item item, boolean testCommands) + { int w; int h; @@ -216,7 +243,8 @@ Command ok1 = new Command("Ok1", "", Command.ITEM, 0); Command ok2 = new Command("Ok2", "", Command.ITEM, 0); - if (testCommands) { + if(testCommands) + { button1.addCommand(ok1); button2.addCommand(ok2); @@ -224,7 +252,8 @@ button2.setItemCommandListener(this); // Add commands to item only in first round: - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { item.addCommand(itemCommand); item.setItemCommandListener(this); } @@ -233,26 +262,27 @@ // Unlock preferred size: item.setPreferredSize(-1, -1); - switch (state) { - case STATE_NO_EXTRA_ITEMS: - form.append(item); - break; - case STATE_ITEM_BEFORE: - form.append(button1); - form.append(item); - break; - case STATE_ITEM_AFTER: - form.append(item); - form.append(button1); - break; - case STATE_ITEM_BEFORE_AND_AFTER: - form.append(button1); - form.append(item); - form.append(button2); - break; - default: - fail("invalid state, bug in test."); - break; + switch(state) + { + case STATE_NO_EXTRA_ITEMS: + form.append(item); + break; + case STATE_ITEM_BEFORE: + form.append(button1); + form.append(item); + break; + case STATE_ITEM_AFTER: + form.append(item); + form.append(button1); + break; + case STATE_ITEM_BEFORE_AND_AFTER: + form.append(button1); + form.append(item); + form.append(button2); + break; + default: + fail("invalid state, bug in test."); + break; } display.setCurrentItem(item); @@ -263,16 +293,17 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label was: w=" - + w + ", h=" + h); + + w + ", h=" + h); } this.assertTrue("Width not greater than zero" - + " (without label), state: " + state, w > 0); + + " (without label), state: " + state, w > 0); this.assertTrue("Height not greater than zero" - + " (without label), state: " + state, h > 0); + + " (without label), state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); //Test Item with label: item.setLabel("label"); @@ -280,16 +311,17 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label was: w=" - + w + ", h=" + h); + + w + ", h=" + h); } this.assertTrue("Width not greater than zero" - + " (with label), state: " + state, w > 0); + + " (with label), state: " + state, w > 0); this.assertTrue("Height not greater than zero" - + " (with label), state: " + state, h > 0); + + " (with label), state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); // Set preferred width larger than screen width and make // sure the width is not larger than screen width: @@ -298,39 +330,42 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label after setting" - + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" - + w + ", h=" + h); + + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero," - + " state: " + state, h > 0); + + " state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); item.setLabel(null); block(CHANGE_DISPLAYABLE_DELAY); w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label after setting" - + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" - + w + ", h=" + h); + + " preferred width to " + BIG_PREFERRED_WIDTH + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero (no label)," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero (no label)," - + " state: " + state, h > 0); + + " state: " + state, h > 0); this.assertTrue("Item's width is larger than screen's width (no label)," - + " state: " + state, w <= form.getWidth()); + + " state: " + state, w <= form.getWidth()); //Test command, that verifies the focus is not changed: - if (testCommands) { + if(testCommands) + { key(Key.CBA1); assertItemCmdListener("", itemCommand, item); } @@ -345,44 +380,49 @@ w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item with label after setting" - + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" - + w + ", h=" + h); + + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero," - + " state: " + state, h > 0); + + " state: " + state, h > 0); item.setLabel(null); block(CHANGE_DISPLAYABLE_DELAY); w = item.getPreferredWidth(); h = item.getPreferredHeight(); - if (state == STATE_NO_EXTRA_ITEMS) { + if(state == STATE_NO_EXTRA_ITEMS) + { print("Preferred size of Item without label after setting" - + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" - + w + ", h=" + h); + + " preferred height to " + BIG_PREFERRED_HEIGHT + " was: w=" + + w + ", h=" + h); } this.assertTrue("Item's width equal or smaller than zero (no label)," - + " state: " + state, w > 0); + + " state: " + state, w > 0); this.assertTrue("Item's height equal or smaller than zero (no label)," - + " state: " + state, h > 0); + + " state: " + state, h > 0); //Test command, that verifies the focus is not changed: - if (testCommands) { + if(testCommands) + { key(Key.CBA1); assertItemCmdListener("", itemCommand, item); } form.deleteAll(); - if (state < STATE_ITEM_BEFORE_AND_AFTER) { + if(state < STATE_ITEM_BEFORE_AND_AFTER) + { state++; testPreferredSizes(item, testCommands); } - else { + else + { state = 0; } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/list/ListUITest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/list/ListUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/list/ListUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.list; @@ -33,7 +33,8 @@ *
            * @created 7.8.2008 */ -public class ListUITest extends UITestBase { +public class ListUITest extends UITestBase +{ private static final int SETCURRENT_TIMEOUT = 6000; private static final int WAIT_CYCLE_TIME = 50; @@ -46,7 +47,8 @@ /** * Constructor. */ - public ListUITest() { + public ListUITest() + { } /** @@ -55,7 +57,8 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public ListUITest(String sTestName, TestMethod rTestMethod) { + public ListUITest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -65,11 +68,14 @@ * * @return New TestSuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); - aSuite.addTest(new ListUITest("testDefaultSelectCmd", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new ListUITest("testDefaultSelectCmd", new TestMethod() + { + public void run(TestCase tc) + { ((ListUITest) tc).testDefaultSelectCmd(); } })); @@ -80,7 +86,8 @@ /** * Test method. */ - public void testDefaultSelectCmd() { + public void testDefaultSelectCmd() + { List list = new List("Implicit List", Choice.IMPLICIT); list.setCommandListener(this); assertSetCurrent(list); @@ -114,7 +121,8 @@ * @param aCommand Command. * @param aDisplayable Displayable. */ - public void commandAction(Command aCommand, Displayable aDisplayable) { + public void commandAction(Command aCommand, Displayable aDisplayable) + { lastCommand = aCommand; lastDisplayable = aDisplayable; doNotify(); @@ -125,11 +133,13 @@ * * @param disp a displayable */ - protected void assertSetCurrent(Displayable disp) { + protected void assertSetCurrent(Displayable disp) + { display.setCurrent(disp); Displayable curr = null; int waitSum = 0; - while (curr != disp && waitSum <= SETCURRENT_TIMEOUT) { + while(curr != disp && waitSum <= SETCURRENT_TIMEOUT) + { block(CHANGE_DISPLAYABLE_DELAY); waitSum += CHANGE_DISPLAYABLE_DELAY; curr = display.getCurrent(); @@ -143,12 +153,13 @@ * @param expCmd expected Command * @param expDisp expected Displayable */ - protected void assertCommandListener(Command expCmd, Displayable expDisp) { + protected void assertCommandListener(Command expCmd, Displayable expDisp) + { assertTrue("Command listener wasn't called with " + expCmd.getLabel(), - syncFlag); + syncFlag); assertEquals("Last displayable mismatch", expDisp, lastDisplayable); assertEquals("Last command should be " + expCmd.getLabel(), expCmd, - lastCommand); + lastCommand); } /** @@ -157,11 +168,13 @@ * @param timeout timeout * @return true if the doNotify was called during this, else otherwise */ - protected boolean doWait(int timeout) { + protected boolean doWait(int timeout) + { clearCallbackValues(); int waitSum = 0; // wait here until syncFlag gets true or timeout expires - while (!syncFlag && waitSum <= timeout) { + while(!syncFlag && waitSum <= timeout) + { block(WAIT_CYCLE_TIME); waitSum += WAIT_CYCLE_TIME; } @@ -171,14 +184,16 @@ /** * Notify the doWait method. */ - protected void doNotify() { + protected void doNotify() + { syncFlag = true; } /** * Clear command listener values. */ - protected void clearCallbackValues() { + protected void clearCallbackValues() + { syncFlag = false; lastCommand = null; lastDisplayable = null; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/spacer/SpacerTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/spacer/SpacerTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/spacer/SpacerTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.spacer; @@ -35,7 +35,8 @@ *
            * Created: 2008-10-20 */ -public class SpacerTest extends ItemUITestBase { +public class SpacerTest extends ItemUITestBase +{ private Command latestCommand; private Item latestItem; @@ -44,7 +45,8 @@ /** * Constructor. */ - public SpacerTest() { + public SpacerTest() + { } /** @@ -53,19 +55,23 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public SpacerTest(String sTestName, TestMethod rTestMethod) { + public SpacerTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } /** * Any pre-test setup can be done here */ - protected void setUp() throws Exception { + protected void setUp() throws Exception + { super.setUp(); - try { + try + { smallImage = Image.createImage("32x32.jpeg"); } - catch (IOException e) { + catch(IOException e) + { // } } @@ -76,15 +82,18 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new SpacerTest("testSizeChange", - new TestMethod() { - public void run(TestCase tc) { - ((SpacerTest) tc).testSizeChange(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((SpacerTest) tc).testSizeChange(); + } + })); @@ -94,11 +103,12 @@ /** * Tests the basic functionality of command added to Hyperlink. */ - public void testSizeChange() { + public void testSizeChange() + { ImageItem button = new ImageItem("label", smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); ImageItem button2 = new ImageItem("label", smallImage, 0, "small", - ImageItem.BUTTON); + ImageItem.BUTTON); Spacer spacer = new Spacer(0, 0); Command ok = new Command("Ok", "", Command.ITEM, 0); @@ -118,18 +128,18 @@ // Click command and verify it works: key(Key.CBA1); assertEquals("Command not activated or not correct command.(case 1)", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method.(case 1)", - button, latestItem); + button, latestItem); latestCommand = null; latestItem = null; // Check that after arrowDown focus didn't change. key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct command.(case 2)", - ok, latestCommand); + ok, latestCommand); assertEquals("Wrong item delivered to commandAction-method.(case 2)", - button, latestItem); + button, latestItem); latestCommand = null; latestItem = null; // change spacers's size to form width and again press arrow down. @@ -139,9 +149,9 @@ key(Key.DownArrow); key(Key.CBA1); assertEquals("Command not activated or not correct " - + "command when using MSK.(case 3)", ok2, latestCommand); + + "command when using MSK.(case 3)", ok2, latestCommand); assertEquals("Wrong item delivered to commandAction-method" - + " when using MSK.(case 3)", button2, latestItem); + + " when using MSK.(case 3)", button2, latestItem); } /** @@ -150,7 +160,8 @@ * @param c Command * @param item item */ - public void commandAction(Command c, Item item) { + public void commandAction(Command c, Item item) + { latestCommand = c; latestItem = item; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/HyperLinkTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/HyperLinkTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/HyperLinkTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.stringitem; @@ -32,12 +32,14 @@ *
            * Created: 2008-10-20 */ -public class HyperLinkTest extends ItemUITestBase { +public class HyperLinkTest extends ItemUITestBase +{ /** * Constructor. */ - public HyperLinkTest() { + public HyperLinkTest() + { } /** @@ -46,7 +48,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public HyperLinkTest(String sTestName, TestMethod rTestMethod) { + public HyperLinkTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -56,338 +59,367 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new HyperLinkTest("testCommands", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc).testCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc).testCommands(); + } + })); aSuite.addTest(new HyperLinkTest("testAppearanceModeChangePlain", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testAppearanceModeChange(StringItem.PLAIN); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testAppearanceModeChange(StringItem.PLAIN); + } + })); aSuite.addTest(new HyperLinkTest("testAppearanceModeChangeButton", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testAppearanceModeChange(StringItem.BUTTON); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testAppearanceModeChange(StringItem.BUTTON); + } + })); aSuite.addTest(new HyperLinkTest("testAppearanceModeChangeHyperlink", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testAppearanceModeChange(StringItem.HYPERLINK); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testAppearanceModeChange(StringItem.HYPERLINK); + } + })); aSuite.addTest(new HyperLinkTest("testFocusInAppearanceModeChangePlain", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testFocusInAppearanceModeChange(StringItem.PLAIN); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testFocusInAppearanceModeChange(StringItem.PLAIN); + } + })); aSuite.addTest(new HyperLinkTest( - "testFocusInAppearanceModeChangeButton", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testFocusInAppearanceModeChange(StringItem.BUTTON); - } - })); + "testFocusInAppearanceModeChangeButton", + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testFocusInAppearanceModeChange(StringItem.BUTTON); + } + })); aSuite.addTest(new HyperLinkTest( - "testFocusInAppearanceModeChangeHyperlink", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc). - testFocusInAppearanceModeChange(StringItem.HYPERLINK); - } - })); + "testFocusInAppearanceModeChangeHyperlink", + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc). + testFocusInAppearanceModeChange(StringItem.HYPERLINK); + } + })); aSuite.addTest(new HyperLinkTest("testLongHyperlinkWithLSK", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc).testLongHyperlink(Key.CBA1); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc).testLongHyperlink(Key.CBA1); + } + })); aSuite.addTest(new HyperLinkTest("testLongHyperlinkWithMSK", - new TestMethod() { - public void run(TestCase tc) { - ((HyperLinkTest) tc).testLongHyperlink(Key.Select); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((HyperLinkTest) tc).testLongHyperlink(Key.Select); + } + })); return aSuite; } /** - * Tests the basic functionality of command added to Hyperlink. - */ - public void testCommands() { - StringItem hyperlink = new StringItem("label", "url", - StringItem.HYPERLINK); + * Tests the basic functionality of command added to Hyperlink. + */ + public void testCommands() + { + StringItem hyperlink = new StringItem("label", "url", + StringItem.HYPERLINK); - testCommand(hyperlink); + testCommand(hyperlink); - // Because focus transfer in case of hyperlink is different than - // in normal cases it is good to test that commands works when - // moving focus from previous item to hyperlink as well as when - // moving focus from next item: - form.deleteAll(); - StringItem button1 = new StringItem(null, "button1", StringItem.BUTTON); - StringItem button2 = new StringItem(null, "button2", StringItem.BUTTON); - Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); - button1.addCommand(dummyCommand); - button2.addCommand(dummyCommand); - button1.setItemCommandListener(this); - button2.setItemCommandListener(this); + // Because focus transfer in case of hyperlink is different than + // in normal cases it is good to test that commands works when + // moving focus from previous item to hyperlink as well as when + // moving focus from next item: + form.deleteAll(); + StringItem button1 = new StringItem(null, "button1", StringItem.BUTTON); + StringItem button2 = new StringItem(null, "button2", StringItem.BUTTON); + Command dummyCommand = new Command("dummy", "", Command.ITEM, 0); + button1.addCommand(dummyCommand); + button2.addCommand(dummyCommand); + button1.setItemCommandListener(this); + button2.setItemCommandListener(this); - // Some typical url-characters are replaced with 'x'-chars to avoid - // some problems in eSWT/AVKON implementation. Those problems should - // go away when using QT-based eSWT. + // Some typical url-characters are replaced with 'x'-chars to avoid + // some problems in eSWT/AVKON implementation. Those problems should + // go away when using QT-based eSWT. - Command ok = new Command("Ok", "", Command.ITEM, 0); + Command ok = new Command("Ok", "", Command.ITEM, 0); - StringItem hyperlink3 = new StringItem(null, - "xxxx://this.link.should.be.wrapped.to.many" - + ".lines.info/index.php?wrapped=truexi=hope", - StringItem.HYPERLINK); - hyperlink3.addCommand(ok); - hyperlink3.setItemCommandListener(this); + StringItem hyperlink3 = new StringItem(null, + "xxxx://this.link.should.be.wrapped.to.many" + + ".lines.info/index.php?wrapped=truexi=hope", + StringItem.HYPERLINK); + hyperlink3.addCommand(ok); + hyperlink3.setItemCommandListener(this); - form.append(button1); - form.append(hyperlink3); - form.append(button2); + form.append(button1); + form.append(hyperlink3); + form.append(button2); - block(CHANGE_DISPLAYABLE_DELAY); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.RightArrow); - key(Key.CBA1); - assertItemCmdListener("hyperlink focus transfer test, case 1", ok, - hyperlink3); + key(Key.RightArrow); + key(Key.CBA1); + assertItemCmdListener("hyperlink focus transfer test, case 1", ok, + hyperlink3); - key(Key.RightArrow); - key(Key.LeftArrow); - key(Key.CBA1); - assertItemCmdListener("hyperlink focus transfer test, case 2", ok, - hyperlink3); - } + key(Key.RightArrow); + key(Key.LeftArrow); + key(Key.CBA1); + assertItemCmdListener("hyperlink focus transfer test, case 2", ok, + hyperlink3); + } - /** - * Tests that commands are working as expected when commands - * are added or removed dynamically. - * - * @param mode Appearancemode of StringItem. - */ - public void testAppearanceModeChange(int mode) { - switch (mode) { - case StringItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case StringItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case StringItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; - } + /** + * Tests that commands are working as expected when commands + * are added or removed dynamically. + * + * @param mode Appearancemode of StringItem. + */ + public void testAppearanceModeChange(int mode) + { + switch(mode) + { + case StringItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case StringItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case StringItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; + } - StringItem stringItem = new StringItem("label", "url", mode); - Command ok = new Command("Ok", "", Command.ITEM, 0); + StringItem stringItem = new StringItem("label", "url", mode); + Command ok = new Command("Ok", "", Command.ITEM, 0); - form.append(stringItem); - stringItem.addCommand(ok); - stringItem.setItemCommandListener(this); + form.append(stringItem); + stringItem.addCommand(ok); + stringItem.setItemCommandListener(this); - setCurrent(form); + setCurrent(form); - // Remove command and make sure the command is not working anymore: - stringItem.removeCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + // Remove command and make sure the command is not working anymore: + stringItem.removeCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.CBA1); - assertItemCmdListener("cmd activated after removing", null, null); + key(Key.CBA1); + assertItemCmdListener("cmd activated after removing", null, null); - // Add command again and verify it works: - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + // Add command again and verify it works: + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.CBA1); - assertItemCmdListener("", ok, stringItem); - } + key(Key.CBA1); + assertItemCmdListener("", ok, stringItem); + } - /** - * Tests that focus transfer works when commands are added/removed - * dynamically. - * - * @param mode Appearancemode of StringItem. - */ - public void testFocusInAppearanceModeChange(int mode) { - switch (mode) { - case StringItem.PLAIN: - print("Running test with appearance mode PLAIN."); - break; - case StringItem.BUTTON: - print("Running test with appearance mode BUTTON."); - break; - case StringItem.HYPERLINK: - print("Running test with appearance mode HYPERLINK."); - break; - default: - fail("Invalid test (incorrect appearance mode)."); - break; - } + /** + * Tests that focus transfer works when commands are added/removed + * dynamically. + * + * @param mode Appearancemode of StringItem. + */ + public void testFocusInAppearanceModeChange(int mode) + { + switch(mode) + { + case StringItem.PLAIN: + print("Running test with appearance mode PLAIN."); + break; + case StringItem.BUTTON: + print("Running test with appearance mode BUTTON."); + break; + case StringItem.HYPERLINK: + print("Running test with appearance mode HYPERLINK."); + break; + default: + fail("Invalid test (incorrect appearance mode)."); + break; + } - StringItem stringItem = new StringItem(null, "url", mode); + StringItem stringItem = new StringItem(null, "url", mode); - StringItem button1 = new StringItem(null, "button1", Item.BUTTON); - StringItem button2 = new StringItem(null, "button2", Item.BUTTON); + StringItem button1 = new StringItem(null, "button1", Item.BUTTON); + StringItem button2 = new StringItem(null, "button2", Item.BUTTON); - Command ok = new Command("giamcc1", "", Command.ITEM, 0); - Command buttonCommand1 = new Command("giamcc12", "", Command.ITEM, 0); - Command buttonCommand2 = new Command("giamcc13", "", Command.ITEM, 0); + Command ok = new Command("giamcc1", "", Command.ITEM, 0); + Command buttonCommand1 = new Command("giamcc12", "", Command.ITEM, 0); + Command buttonCommand2 = new Command("giamcc13", "", Command.ITEM, 0); - form.append(button1); - form.append(stringItem); - form.append(button2); + form.append(button1); + form.append(stringItem); + form.append(button2); - // Set listener but do not add commands yet: - stringItem.setItemCommandListener(this); - button1.addCommand(buttonCommand1); - button2.addCommand(buttonCommand2); - button1.setItemCommandListener(this); - button2.setItemCommandListener(this); + // Set listener but do not add commands yet: + stringItem.setItemCommandListener(this); + button1.addCommand(buttonCommand1); + button2.addCommand(buttonCommand2); + button1.setItemCommandListener(this); + button2.setItemCommandListener(this); - setCurrent(form); + setCurrent(form); - // At this point there are two buttons and plain stringItem - // in middle of them. Focus is in first button. - // Move to second button, add command to StringItem, move - // to StringItem and verify command works: - key(Key.RightArrow); + // At this point there are two buttons and plain stringItem + // in middle of them. Focus is in first button. + // Move to second button, add command to StringItem, move + // to StringItem and verify command works: + key(Key.RightArrow); - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.LeftArrow); + key(Key.LeftArrow); - assertItemCmdListener("case1", ok, stringItem); + assertItemCmdListener("case1", ok, stringItem); - // Now remove command from StringItem. Test assumes that in this - // case focus is moved to next item which is the second button. - // Verify that happens and also make sure it is possible to move - // to first button also: - stringItem.removeCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + // Now remove command from StringItem. Test assumes that in this + // case focus is moved to next item which is the second button. + // Verify that happens and also make sure it is possible to move + // to first button also: + stringItem.removeCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.CBA1); - assertItemCmdListener("case2", buttonCommand2, button2); + key(Key.CBA1); + assertItemCmdListener("case2", buttonCommand2, button2); - key(Key.LeftArrow); + key(Key.LeftArrow); - key(Key.CBA1); - assertItemCmdListener("case3", buttonCommand1, button1); + key(Key.CBA1); + assertItemCmdListener("case3", buttonCommand1, button1); - // Now add command back to StringItem again and make sure it - // works: - stringItem.addCommand(ok); - block(CHANGE_DISPLAYABLE_DELAY); + // Now add command back to StringItem again and make sure it + // works: + stringItem.addCommand(ok); + block(CHANGE_DISPLAYABLE_DELAY); - key(Key.RightArrow); + key(Key.RightArrow); - key(Key.CBA1); - assertItemCmdListener("case4", ok, stringItem); + key(Key.CBA1); + assertItemCmdListener("case4", ok, stringItem); - // And verify also the functionality of second button after - // these changes: - key(Key.RightArrow); + // And verify also the functionality of second button after + // these changes: + key(Key.RightArrow); - key(Key.CBA1); - assertItemCmdListener("case5", buttonCommand2, button2); - } + key(Key.CBA1); + assertItemCmdListener("case5", buttonCommand2, button2); + } - /** - * Tests that Hyperlink works as expected when its size exceeds - * screen height. - * - * @param key Keycode which is used to verify the hyperlink command - * works. - */ - public void testLongHyperlink(int key) { - StringItem stringItem = new StringItem( - "label", - "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. " - + "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. " - + "The quick brown fox jumps over the lazy dog and realizes" - + " that this hyperlink text is repeated several times to make" - + " sure the size of the hyperlink exceeds screen height. ", - StringItem.HYPERLINK); + /** + * Tests that Hyperlink works as expected when its size exceeds + * screen height. + * + * @param key Keycode which is used to verify the hyperlink command + * works. + */ + public void testLongHyperlink(int key) + { + StringItem stringItem = new StringItem( + "label", + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. " + + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. " + + "The quick brown fox jumps over the lazy dog and realizes" + + " that this hyperlink text is repeated several times to make" + + " sure the size of the hyperlink exceeds screen height. ", + StringItem.HYPERLINK); - Command ok = new Command("lhlc1", "", Command.ITEM, 0); + Command ok = new Command("lhlc1", "", Command.ITEM, 0); - StringItem button1 = new StringItem(null, "button1", Item.BUTTON); - Command buttonCommand1 = new Command("lhlc2", "", Command.ITEM, 0); + StringItem button1 = new StringItem(null, "button1", Item.BUTTON); + Command buttonCommand1 = new Command("lhlc2", "", Command.ITEM, 0); - form.append(stringItem); - stringItem.addCommand(ok); - stringItem.setItemCommandListener(this); + form.append(stringItem); + stringItem.addCommand(ok); + stringItem.setItemCommandListener(this); - form.append(button1); - button1.addCommand(buttonCommand1); - button1.setItemCommandListener(this); + form.append(button1); + button1.addCommand(buttonCommand1); + button1.setItemCommandListener(this); - setCurrent(form); + setCurrent(form); - //TODO: When running all tests and the key is LSK and in following loop - //the i is 0, latestCommand is buttonCommand1 and latestItem is null. - //If button is not added to the form then the latestCommand also - //will be null. - //Problem has something to do with timing, because - //adding debugprints to this test will sometimes make it pass. - //For example following delay will make the test pass: - block(CHANGE_DISPLAYABLE_DELAY); + //TODO: When running all tests and the key is LSK and in following loop + //the i is 0, latestCommand is buttonCommand1 and latestItem is null. + //If button is not added to the form then the latestCommand also + //will be null. + //Problem has something to do with timing, because + //adding debugprints to this test will sometimes make it pass. + //For example following delay will make the test pass: + block(CHANGE_DISPLAYABLE_DELAY); + + // Scroll down and after each keydown-press make sure the hyperlink + // is still focused: + final int rounds = 10; + final int roundsInHyperlink = 3; + for(int i = 0; i < rounds; i++) + { + key(key); - // Scroll down and after each keydown-press make sure the hyperlink - // is still focused: - final int rounds = 10; - final int roundsInHyperlink = 3; - for (int i = 0; i < rounds; i++) { - key(key); + if(i < roundsInHyperlink) + { + // Code assumes that it takes at least three + // keypresses to reach button which is located below hyperlink: + assertItemCmdListener("clicking hyperlink. i=" + i, ok, + stringItem); + } + else if(i >= (rounds - 1)) + { + // After 10 keypresses button should be focused: + assertItemCmdListener("clicking button. i=" + i, + buttonCommand1, button1); + } - if (i < roundsInHyperlink) { - // Code assumes that it takes at least three - // keypresses to reach button which is located below hyperlink: - assertItemCmdListener("clicking hyperlink. i=" + i, ok, - stringItem); - } else if (i >= (rounds - 1)) { - // After 10 keypresses button should be focused: - assertItemCmdListener("clicking button. i=" + i, - buttonCommand1, button1); - } - - key(Key.RightArrow); - block(CHANGE_DISPLAYABLE_DELAY); - } - } + key(Key.RightArrow); + block(CHANGE_DISPLAYABLE_DELAY); + } + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/StringItemUIRobotTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/StringItemUIRobotTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/stringitem/StringItemUIRobotTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.stringitem; @@ -33,7 +33,8 @@ * Created: 2008-08-27 */ public class StringItemUIRobotTest extends UITestBase implements - ItemCommandListener, CommandListener { + ItemCommandListener, CommandListener +{ private Form form; private StringItem button1; @@ -47,7 +48,8 @@ /** * Constructor. */ - public StringItemUIRobotTest() { + public StringItemUIRobotTest() + { } /** @@ -56,7 +58,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public StringItemUIRobotTest(String sTestName, TestMethod rTestMethod) { + public StringItemUIRobotTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -66,15 +69,18 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new StringItemUIRobotTest("testSetTextNullEmpty", - new TestMethod() { - public void run(TestCase tc) { - ((StringItemUIRobotTest) tc).testSetTextNullEmpty(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((StringItemUIRobotTest) tc).testSetTextNullEmpty(); + } + })); return aSuite; } @@ -83,7 +89,8 @@ * Test that StringItem.setText(text) working properly. * Only text = null and text = "" investigated. */ - public void testSetTextNullEmpty() { + public void testSetTextNullEmpty() + { button1 = new StringItem("", "click!", Item.BUTTON); button2 = new StringItem("", "click 2!", Item.BUTTON); button3 = new StringItem("", "click 3!", Item.BUTTON); @@ -91,7 +98,7 @@ c1 = new Command("Ok1", "", Command.ITEM, 0); c2 = new Command("Ok2", "", Command.ITEM, 0); c3 = new Command("Ok3", "", Command.ITEM, 0); - form = new Form ("setTextTest"); + form = new Form("setTextTest"); form.setCommandListener(this); button1.addCommand(c1); button1.setItemCommandListener(this); @@ -115,7 +122,7 @@ key(Key.RightArrow); key(Key.Select); assertEquals("StringItem content was not changed!", "some text", si - .getText()); + .getText()); } @@ -124,14 +131,18 @@ * @param c Command. * @param item that triggered the command. */ - public void commandAction(Command c, Item item) { - if (c == c1) { + public void commandAction(Command c, Item item) + { + if(c == c1) + { si.setText(""); } - if (c == c2) { + if(c == c2) + { si.setText(null); } - if (c == c3) { + if(c == c3) + { si.setText("some text"); } } @@ -140,7 +151,8 @@ * @param c Command. * @param d displayable that triggered the command. */ - public void commandAction(Command c, Displayable d) { + public void commandAction(Command c, Displayable d) + { } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TestUITextBox.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TestUITextBox.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TestUITextBox.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.textbox; @@ -32,26 +32,30 @@ *

            * Created: 2008-04-25 */ -public class TestUITextBox extends UITestBase { +public class TestUITextBox extends UITestBase +{ private static final int LENGTH = 100; private static final int EXPECTED_CARET_POSITION = 5; private TextBox textbox; - private int[] inputTextShort = new int[]{'7', '8', '8', '9', - '4', '5', '5', '5', '5', }; + private int[] inputTextShort = new int[] {'7', '8', '8', '9', + '4', '5', '5', '5', '5', + }; private int[] inputSentence = new int [] {'3', '3', '8', '8', '8', - '3', '3', '7', '7', '7', - '9', '9', '9', '1', '0', '9', - '6', '6', '6', '7', '7', - '7', '3', '0', '4', '4', - '4', '7', '7', '7', '7', - '0', '2', '2', '2', }; + '3', '3', '7', '7', '7', + '9', '9', '9', '1', '0', '9', + '6', '6', '6', '7', '7', + '7', '3', '0', '4', '4', + '4', '7', '7', '7', '7', + '0', '2', '2', '2', + }; /** * Constructor. */ - public TestUITextBox() { + public TestUITextBox() + { } /** @@ -60,7 +64,8 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TestUITextBox(String sTestName, TestMethod rTestMethod) { + public TestUITextBox(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -69,31 +74,40 @@ * any new test methods, otherwise they won't be run. * @return suite */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TestUITextBox("testNormalInputMode()", - new TestMethod() { - public void run(TestCase tc) { - ((TestUITextBox) tc).testNormalInputMode(); - } - })); - aSuite.addTest(new TestUITextBox("testNonEditable()", new TestMethod() { - public void run(TestCase tc) { + new TestMethod() + { + public void run(TestCase tc) + { + ((TestUITextBox) tc).testNormalInputMode(); + } + })); + aSuite.addTest(new TestUITextBox("testNonEditable()", new TestMethod() + { + public void run(TestCase tc) + { ((TestUITextBox) tc).testNonEditable(); } })); - aSuite.addTest(new TestUITextBox("testCapSent()", new TestMethod() { - public void run(TestCase tc) { + aSuite.addTest(new TestUITextBox("testCapSent()", new TestMethod() + { + public void run(TestCase tc) + { ((TestUITextBox) tc).testCapSent(); } })); aSuite.addTest(new TestUITextBox("testGetCaretPosition()", - new TestMethod() { - public void run(TestCase tc) { - ((TestUITextBox) tc).testGetCaretPosition(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TestUITextBox) tc).testGetCaretPosition(); + } + })); return aSuite; } @@ -101,18 +115,20 @@ * This method tests that TextBox getString, returns * correct text which was inputed with UIRobot. */ - public void testNormalInputMode() { + public void testNormalInputMode() + { textbox = new TextBox("ANY", "", LENGTH, TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "Puwg5. But returned " - + getString, getString.equals("Puwg5")); + + "Puwg5. But returned " + + getString, getString.equals("Puwg5")); textbox = null; } @@ -120,19 +136,21 @@ * Test that TextBox is not editable if * UNEDITABLE is specified in constructor. */ - public void testNonEditable() { + public void testNonEditable() + { textbox = new TextBox("No Edit", "editing is not allowed", LENGTH, - TextField.UNEDITABLE | TextField.ANY); + TextField.UNEDITABLE | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "editing is not allowed. But returned " + getString, - getString.equals("editing is not allowed")); + + "editing is not allowed. But returned " + getString, + getString.equals("editing is not allowed")); textbox = null; } @@ -141,19 +159,21 @@ * every word should start with capital letter. * TODO: waiting for fixes from eSWT. */ - public void testCapWord() { + public void testCapWord() + { textbox = new TextBox("Capital Words", "", LENGTH, - TextField.INITIAL_CAPS_WORD | TextField.ANY); + TextField.INITIAL_CAPS_WORD | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputSentence.length; i++) { + for(int i = 0; i < inputSentence.length; i++) + { key(inputSentence[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() returns: " - + "Every. Word Is C. But returned " + getString, getString - .equals("Every. Word Is C")); + + "Every. Word Is C. But returned " + getString, getString + .equals("Every. Word Is C")); textbox = null; } @@ -162,19 +182,21 @@ * Test that TextBox behaves correctly if INITIAL_CAPS_SENTENCE specified. * every sentence should start with capital letter. */ - public void testCapSent() { + public void testCapSent() + { textbox = new TextBox("Capital Sentence", "", LENGTH, - TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); + TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); String getString; setCurrent(textbox); - for (int i = 0; i < inputSentence.length; i++) { + for(int i = 0; i < inputSentence.length; i++) + { key(inputSentence[i], 0); } getString = textbox.getString(); assertTrue("Expected: TextBox.getText() return: " - + "Every word is c. But returned " + getString, getString - .equals("Every. Word is c")); + + "Every word is c. But returned " + getString, getString + .equals("Every. Word is c")); textbox = null; } @@ -182,20 +204,22 @@ * TextBox.getCaretPosition() test. * Tests that getCaretPosition works correctly. */ - public void testGetCaretPosition() { + public void testGetCaretPosition() + { int getCaretPosition = 0; textbox = new TextBox("Get Caret", "", LENGTH, - TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); + TextField.INITIAL_CAPS_SENTENCE | TextField.ANY); setCurrent(textbox); - for (int i = 0; i < inputTextShort.length; i++) { + for(int i = 0; i < inputTextShort.length; i++) + { key(inputTextShort[i], 0); } getCaretPosition = textbox.getCaretPosition(); assertTrue("TextBox.getCaretPosition(). Expected: returns " - + EXPECTED_CARET_POSITION + " but got " + getCaretPosition, - getCaretPosition == EXPECTED_CARET_POSITION); + + EXPECTED_CARET_POSITION + " but got " + getCaretPosition, + getCaretPosition == EXPECTED_CARET_POSITION); textbox = null; } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TextBoxInputModeUITest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TextBoxInputModeUITest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textbox/TextBoxInputModeUITest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.textbox; @@ -60,7 +60,8 @@ * * Note: The references images differ from 3.0 to 3.1 */ -public class TextBoxInputModeUITest extends UITestBase { +public class TextBoxInputModeUITest extends UITestBase +{ private static final int LENGTH = 2000; /* Possible build variants */ @@ -93,10 +94,10 @@ "" + (char) 38463 + (char) 24694 + (char) 21704 + (char) 25289; private static final String HONGKONG_adgj = "" + (char) 26159 + (char) 21542 + (char) 30340 + (char) 35441 - + (char) 28858 + (char) 20102 + (char) 20057 + (char) 28911; + + (char) 28858 + (char) 20102 + (char) 20057 + (char) 28911; private static final String TAIWAN_adgj = "" + (char) 12553 + (char) 30340 + (char) 12557 + (char) 30340 - + (char) 12560 + (char) 30340 + (char) 12563 + (char) 30340; + + (char) 12560 + (char) 30340 + (char) 12563 + (char) 30340; private static final String KANJI_adgj = "" + (char) 12363 + (char) 12373 + (char) 12383 + (char) 12394; private static final String KATAKANA_adgj = @@ -115,8 +116,9 @@ /** * Constructor. */ - public TextBoxInputModeUITest() { - super(); + public TextBoxInputModeUITest() + { + super(); } /** @@ -125,7 +127,8 @@ * @param sTestName name of the test * @param rTestMethod TestMethod used */ - public TextBoxInputModeUITest(String sTestName, TestMethod rTestMethod) { + public TextBoxInputModeUITest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -135,7 +138,8 @@ * * @return test suite */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); // Ignored cases @@ -180,214 +184,266 @@ */ aSuite.addTest(new TextBoxInputModeUITest("testDefaultInputMode", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testDefaultInputMode(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testDefaultInputMode(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_LATIN_DIGITS", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_LATIN_DIGITS(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_LATIN_DIGITS(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_LATIN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_LATIN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testMIDP_UPPERCASE_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testMIDP_UPPERCASE_LATIN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testMIDP_UPPERCASE_LATIN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testMIDP_LOWERCASE_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testMIDP_LOWERCASE_LATIN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testMIDP_LOWERCASE_LATIN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_BASIC_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_BASIC_LATIN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_BASIC_LATIN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_GREEK", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_GREEK(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_GREEK(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_CYRILLIC", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_CYRILLIC(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_CYRILLIC(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_HEBREW", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_HEBREW(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_HEBREW(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_ARABIC()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_ARABIC(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_ARABIC(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_DEVANAGARI", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_DEVANAGARI(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_DEVANAGARI(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_ARMENIAN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_ARMENIAN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_ARMENIAN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_THAI", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_THAI(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_THAI(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_HIRAGANA()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_HIRAGANA(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_HIRAGANA(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUCB_KATAKANA", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUCB_KATAKANA(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUCB_KATAKANA(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_HALFWIDTH_KATAKANA", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testIS_HALFWIDTH_KATAKANA(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testIS_HALFWIDTH_KATAKANA(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_KANJI()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_KANJI(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_KANJI(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_FULLWIDTH_DIGITS", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_FULLWIDTH_DIGITS(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_FULLWIDTH_DIGITS(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_FULLWIDTH_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_FULLWIDTH_LATIN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_FULLWIDTH_LATIN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_SIMPLIFIED_HANZI()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_SIMPLIFIED_HANZI(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_SIMPLIFIED_HANZI(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testIS_TRADITIONAL_HANZI", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testIS_TRADITIONAL_HANZI(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testIS_TRADITIONAL_HANZI(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testnull", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testnull(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testnull(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testUNKNOWN", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testUNKNOWN(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testUNKNOWN(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testempty", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testempty(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testempty(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModeChange", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModeChange(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModeChange(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModeAndMenuOpen", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModeAndMenuOpen(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModeAndMenuOpen(); + } + } + )); /*aSuite.addTest(new TextBoxInputModeSTest("testinputModesInNumber", new TestMethod() { @@ -406,108 +462,132 @@ ));*/ aSuite.addTest(new TextBoxInputModeUITest("testinputModesInEmailaddr", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInEmailaddr(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInEmailaddr(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInEmailaddr2", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInEmailaddr2(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInEmailaddr2(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInUrl", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInUrl(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInUrl(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInUrl2", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInUrl2(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInUrl2(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInPassword", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInPassword(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInPassword(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInPassword2", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInPassword2(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInPassword2(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInAny()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInAny(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInAny(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInAny2", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInAny2(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInAny2(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInCapsSentence", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInCapsSentence(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInCapsSentence(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModesInCapsWord()", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModesInCapsWord(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModesInCapsWord(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest( - "testinputModesInCapsSentenceEmailaddr", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInCapsSentenceEmailaddr(); - } - } - )); + "testinputModesInCapsSentenceEmailaddr", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInCapsSentenceEmailaddr(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest( - "testinputModesInCapsSentenceUrl", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputModesInCapsSentenceUrl(); - } - } - )); + "testinputModesInCapsSentenceUrl", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputModesInCapsSentenceUrl(); + } + } + )); /*aSuite.addTest(new TextBoxInputModeSTest( "testinputModesAfterNumberMode()", @@ -530,42 +610,50 @@ )); */ aSuite.addTest(new TextBoxInputModeUITest( - "testinputLatinAfterOtherModes", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputLatinAfterOtherModes(); - } - } - )); + "testinputLatinAfterOtherModes", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputLatinAfterOtherModes(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest( - "testinputLatinAfterOtherModes2", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testinputLatinAfterOtherModes2(); - } - } - )); + "testinputLatinAfterOtherModes2", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testinputLatinAfterOtherModes2(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest("testinputModeNullSetting", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc).testinputModeNullSetting(); - } - } - )); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc).testinputModeNullSetting(); + } + } + )); aSuite.addTest(new TextBoxInputModeUITest( - "testcommaInLowerAndUpperCase", - new TestMethod() { - public void run(TestCase tc) { - ((TextBoxInputModeUITest) tc) - .testcommaInLowerAndUpperCase(); - } - } - )); //*/ + "testcommaInLowerAndUpperCase", + new TestMethod() + { + public void run(TestCase tc) + { + ((TextBoxInputModeUITest) tc) + .testcommaInLowerAndUpperCase(); + } + } + )); //*/ return aSuite; } @@ -576,34 +664,39 @@ * Tests default input mode, i.e. setInitialInputMode not called. The * default input mode depends on the build variant in use. */ - private void testDefaultInputMode() { + private void testDefaultInputMode() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "NONE", // no initial input mode setting - "", // initial content - inputKeys(new int[] {'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "NONE", // no initial input mode setting + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called before * displaying the text box. Number input mode will be used. */ - private void testIS_LATIN_DIGITS() { + private void testIS_LATIN_DIGITS() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN_DIGITS", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "2345"); // expected content + TextField.ANY, "IS_LATIN_DIGITS", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "2345"); // expected content } /** @@ -611,12 +704,13 @@ * The method is called before displaying the text box. * Latin text input mode will be used */ - private void testIS_LATIN() { + private void testIS_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "IS_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "Adgj"); // expected content + TextField.ANY, "IS_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "Adgj"); // expected content } /** @@ -624,12 +718,13 @@ * The method is called before displaying the text box. * Uppercase latin text input mode will be used. */ - private void testMIDP_UPPERCASE_LATIN() { + private void testMIDP_UPPERCASE_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "MIDP_UPPERCASE_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "ADGJ"); // expected content + TextField.ANY, "MIDP_UPPERCASE_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "ADGJ"); // expected content } /** @@ -637,12 +732,13 @@ * The method is called before displaying the text box. * Lowercase latin text input mode will be used. */ - private void testMIDP_LOWERCASE_LATIN() { + private void testMIDP_LOWERCASE_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "MIDP_LOWERCASE_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "adgj"); // expected content + TextField.ANY, "MIDP_LOWERCASE_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "adgj"); // expected content } /**. @@ -650,12 +746,13 @@ * The method is called before displaying the text box. * Latin text input mode will be used (same as "IS_LATIN"). */ - private void testUCB_BASIC_LATIN() { + private void testUCB_BASIC_LATIN() + { doInputModeTest(getName(), - TextField.ANY, "UCB_BASIC_LATIN", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - "Adgj"); // expected content + TextField.ANY, "UCB_BASIC_LATIN", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + "Adgj"); // expected content } /** @@ -663,12 +760,13 @@ * The method is called before displaying the text box. * Greek input mode will be used. */ - private void testUCB_GREEK() { + private void testUCB_GREEK() + { doInputModeTest(getName(), - TextField.ANY, "UCB_GREEK", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - GREEK_Adgj); // expected content + TextField.ANY, "UCB_GREEK", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + GREEK_Adgj); // expected content } /** @@ -676,12 +774,13 @@ * The method is called before displaying the text box. * Cyrillic input mode will be used. */ - private void testUCB_CYRILLIC() { + private void testUCB_CYRILLIC() + { doInputModeTest(getName(), - TextField.ANY, "UCB_CYRILLIC", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - CYRILLIC_Adgj); // expected content + TextField.ANY, "UCB_CYRILLIC", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + CYRILLIC_Adgj); // expected content } /** @@ -689,12 +788,13 @@ * The method is called before displaying the text box. * Hebrew input mode will be used. */ - private void testUCB_HEBREW() { + private void testUCB_HEBREW() + { doInputModeTest(getName(), - TextField.ANY, "UCB_HEBREW", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presess - HEBREW_adgj); // expected content + TextField.ANY, "UCB_HEBREW", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presess + HEBREW_adgj); // expected content } /** @@ -702,12 +802,13 @@ * The method is called before displaying the text box. * Arabic input mode will be used. */ - private void testUCB_ARABIC() { + private void testUCB_ARABIC() + { doInputModeTest(getName(), - TextField.ANY, "UCB_ARABIC", - "", // initial content - new int[]{'2', '3', '4', '5'}, // key presses - ARABIC_adgj); // expected content + TextField.ANY, "UCB_ARABIC", + "", // initial content + new int[] {'2', '3', '4', '5'}, // key presses + ARABIC_adgj); // expected content } /** @@ -715,14 +816,15 @@ * The method is called before displaying the text box. * Devanagari/Hindi input mode will be used. */ - private void testUCB_DEVANAGARI() { + private void testUCB_DEVANAGARI() + { String expectedContent = "\u0905\u090f\u0915\u091a"; doInputModeTest(getName(), - TextField.ANY, "UCB_DEVANAGARI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); // expected content + TextField.ANY, "UCB_DEVANAGARI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); // expected content } /** @@ -731,23 +833,27 @@ * This input mode is not supported in 3.0, so default input mode * will be used. */ - private void testUCB_ARMENIAN() { + private void testUCB_ARMENIAN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_ARMENIAN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_ARMENIAN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -756,23 +862,27 @@ * This input mode is supported only in Thai variant; other variants * will use the default input mode. */ - private void testUCB_THAI() { + private void testUCB_THAI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_THAI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_THAI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -781,23 +891,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testUCB_HIRAGANA() { + private void testUCB_HIRAGANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_HIRAGANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_HIRAGANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -806,23 +920,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testUCB_KATAKANA() { + private void testUCB_KATAKANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KATAKANA_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UCB_KATAKANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UCB_KATAKANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -831,23 +949,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_HALFWIDTH_KATAKANA() { + private void testIS_HALFWIDTH_KATAKANA() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = HALFWIDTH_KATAKANA_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_HALFWIDTH_KATAKANA", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_HALFWIDTH_KATAKANA", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -856,23 +978,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_KANJI() { + private void testIS_KANJI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_KANJI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_KANJI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -881,23 +1007,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_FULLWIDTH_DIGITS() { + private void testIS_FULLWIDTH_DIGITS() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = FULLWIDTH_2345; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_FULLWIDTH_DIGITS", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_FULLWIDTH_DIGITS", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -906,23 +1036,27 @@ * This input mode is supported only in Japan variant; other variants * will use the default input mode. */ - private void testIS_FULLWIDTH_LATIN() { + private void testIS_FULLWIDTH_LATIN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = FULLWIDTH_Adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_FULLWIDTH_LATIN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_FULLWIDTH_LATIN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -931,23 +1065,27 @@ * This input mode is supported only in China variant; other variants * will use the default input mode. */ - private void testIS_SIMPLIFIED_HANZI() { + private void testIS_SIMPLIFIED_HANZI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_SIMPLIFIED_HANZI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_SIMPLIFIED_HANZI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -957,47 +1095,55 @@ * when user's display/input language is either Traditional Hongkong or * Traditional Taiwan; otherwise the default input mode will be used. */ - private void testIS_TRADITIONAL_HANZI() { + private void testIS_TRADITIONAL_HANZI() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "IS_TRADITIONAL_HANZI", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "IS_TRADITIONAL_HANZI", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } - /** - * Tests setInitialInputMode(null). - * The method is called before displaying the text box. This - * default input mode will be used. - */ - private void testnull() { + /** + * Tests setInitialInputMode(null). + * The method is called before displaying the text box. This + * default input mode will be used. + */ + private void testnull() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, null, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, null, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -1005,23 +1151,27 @@ * The method is called before displaying the text box. * The default input mode will be used. */ - private void testUNKNOWN() { + private void testUNKNOWN() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "UNKNOWN", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "UNKNOWN", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } /** @@ -1029,23 +1179,27 @@ * The method is called before displaying the text box. * The default input mode will be used. */ - private void testempty() { + private void testempty() + { String expectedContent = "Adgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj; } doInputModeTest(getName(), - TextField.ANY, "", - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), // key presses - expectedContent); + TextField.ANY, "", + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), // key presses + expectedContent); } @@ -1054,28 +1208,32 @@ * already visible. Setting the initial input mode has no effect until * focus is changed temporarily elsewhere and then back to TextBox. */ - private void testinputModeChange() { + private void testinputModeChange() + { String expectedContent = "Adgj2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; // Clear-keys used in chinese input - // will remove latin numbers + // will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[]{"IS_LATIN_DIGITS"}, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + TextField.ANY, new String[] {"IS_LATIN_DIGITS"}, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -1083,29 +1241,33 @@ * has obscured the editor. Setting the initial input mode has no effect * until focus is changed temporarily elsewhere and then back to TextBox. */ - private void testinputModeAndMenuOpen() { + private void testinputModeAndMenuOpen() + { String expectedContent = "Adgj2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; // Clear-keys used in chinese input - // will remove latin numbers + // will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[]{"IS_LATIN_DIGITS"}, - "", // initial content - inputKeys(new int[]{'2', '3', Key.Edit, Key.CBA2, '4', '5'}), - true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + TextField.ANY, new String[] {"IS_LATIN_DIGITS"}, + "", // initial content + inputKeys(new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5'}), + true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -1113,16 +1275,19 @@ * Focus is changed after each setting to make the input mode effective. * Setting the initial input mode has no effect in NUMERIC text box. */ - private void testinputModesInNumber() { + private void testinputModesInNumber() + { doInputModeSequenceTest(getName(), - TextField.NUMERIC, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + TextField.NUMERIC, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -1130,16 +1295,19 @@ * Focus is changed after each setting to make the input mode effective. * Setting the initial input mode has no effect in DECIMAL text box. */ - private void testinputModesInDecimal() { + private void testinputModesInDecimal() + { doInputModeSequenceTest(getName(), - TextField.DECIMAL, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + TextField.DECIMAL, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -1147,17 +1315,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInEmailaddr() { + private void testinputModesInEmailaddr() + { doInputModeSequenceTest(getName(), - TextField.EMAILADDR, new String[] - {"NONE", // starts from default input mode - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); - // expected content + TextField.EMAILADDR, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + // expected content } /** @@ -1166,27 +1337,33 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInEmailaddr2() { + private void testinputModesInEmailaddr2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input will remove latin numbers + // Clear-keys used in chinese input will remove latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.EMAILADDR, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.EMAILADDR, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1194,17 +1371,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInUrl() { + private void testinputModesInUrl() + { doInputModeSequenceTest(getName(), - TextField.URL, new String[] - {"NONE", // default input mode in ANY text box - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); - // expected content + TextField.URL, new String[] + { + "NONE", // default input mode in ANY text box + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + // expected content } /** @@ -1213,27 +1393,33 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInUrl2() { + private void testinputModesInUrl2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin numbers + // Clear-keys used in chinese input removes latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj - + KANJI_adgj; + + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.URL, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.URL, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1241,17 +1427,20 @@ * Focus is changed after each setting to make the input mode effective. * In all variants the default input mode is latin with lower case. */ - private void testinputModesInPassword() { + private void testinputModesInPassword() + { doInputModeSequenceTest(getName(), - TextField.PASSWORD, new String[] - {"NONE", // default input mode in ANY text box - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", /*"IS_LATIN_DIGITS", */}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj/* + "2345"*/); - // expected content + TextField.PASSWORD, new String[] + { + "NONE", // default input mode in ANY text box + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", /*"IS_LATIN_DIGITS", */ + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj/* + "2345"*/); + // expected content } /** @@ -1260,43 +1449,52 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInPassword2() { + private void testinputModesInPassword2() + { String expectedContent = "23452345234523452345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin numbers + // Clear-keys used in chinese input removes latin numbers } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "23452345" + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345234523452345" + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.PASSWORD, new String[] - {"IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // pressed keys (per input mode) - expectedContent); + TextField.PASSWORD, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // pressed keys (per input mode) + expectedContent); } /** * Tests different sequential input modes in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInAny() { + private void testinputModesInAny() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // pressed keys (per input mode) - GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); - // expected content + TextField.ANY, new String[] + { + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // pressed keys (per input mode) + GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); + // expected content } /** @@ -1305,29 +1503,35 @@ * Setting a Japanese or Chinese input mode will have effect in * the corresponding variants. */ - private void testinputModesInAny2() { + private void testinputModesInAny2() + { String expectedContent = "Adgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj; + + CHINA_adgj + CHINA_adgj; } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj - + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; + + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + THAI_adgj - + THAI_adgj + THAI_adgj; + + THAI_adgj + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"NONE", // starts from default input mode - "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", - "UCB_THAI", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.ANY, new String[] + { + "NONE", // starts from default input mode + "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", + "UCB_THAI", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1335,27 +1539,33 @@ * ignored if the INITIAL_CAPS_SENTENCE modifier is defined in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentence() { + private void testinputModesInCapsSentence() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj + ARABIC_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + ARABIC_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.INITIAL_CAPS_SENTENCE, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.INITIAL_CAPS_SENTENCE, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1363,26 +1573,32 @@ * ignored if the INITIAL_CAPS_WORD modifier is defined in ANY text box. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsWord() { + private void testinputModesInCapsWord() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + KANJI_adgj + ARABIC_adgj + "2345"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + THAI_adgj + ARABIC_adgj + "2345"; } doInputModeSequenceTest(getName(), - TextField.INITIAL_CAPS_WORD, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.INITIAL_CAPS_WORD, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** @@ -1391,15 +1607,16 @@ * because the modifier is meaningless in EMAILADDR. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentenceEmailaddr() { + private void testinputModesInCapsSentenceEmailaddr() + { doInputModeSequenceTest(getName(), - TextField.EMAILADDR | TextField.INITIAL_CAPS_SENTENCE, - new String[] - {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + TextField.EMAILADDR | TextField.INITIAL_CAPS_SENTENCE, + new String[] + {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -1408,14 +1625,15 @@ * because the modifier is meaningless in URL. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsSentenceUrl() { + private void testinputModesInCapsSentenceUrl() + { doInputModeSequenceTest(getName(), - TextField.URL | TextField.INITIAL_CAPS_SENTENCE, new String[] - {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + TextField.URL | TextField.INITIAL_CAPS_SENTENCE, new String[] + {"IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -1468,17 +1686,20 @@ * Tests latin input modes after other input modes. * Focus is changed after each setting to make the input mode effective. */ - private void testinputLatinAfterOtherModes() { + private void testinputLatinAfterOtherModes() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"UCB_HEBREW", "IS_LATIN", - "UCB_GREEK", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", - "UCB_CYRILLIC", "IS_LATIN", }, - "", // initial content - new int[]{'2', '3', '4', '5'}, false, - HEBREW_adgj + "adgj" + GREEK_adgj + "ADGJ" - + ARABIC_adgj + "adgj" + CYRILLIC_adgj + "adgj"); + TextField.ANY, new String[] + { + "UCB_HEBREW", "IS_LATIN", + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", + "UCB_CYRILLIC", "IS_LATIN", + }, + "", // initial content + new int[] {'2', '3', '4', '5'}, false, + HEBREW_adgj + "adgj" + GREEK_adgj + "ADGJ" + + ARABIC_adgj + "adgj" + CYRILLIC_adgj + "adgj"); } /** @@ -1487,67 +1708,79 @@ * Setting a Japanese or Chinese input mode will have effect only in * the corresponding variants. */ - private void testinputLatinAfterOtherModes2() { + private void testinputLatinAfterOtherModes2() + { String expectedContent = "Adgjadgjadgjadgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj; - // Clear-keys used in chinese input removes latin chars + // Clear-keys used in chinese input removes latin chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = KANJI_adgj + "adgj" + KANJI_adgj + "adgj" - + FULLWIDTH_2345 + "adgjadgjadgj"; + + FULLWIDTH_2345 + "adgjadgjadgj"; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = THAI_adgj + "adgjadgjadgjadgjadgj" - + THAI_adgj + "adgj"; + + THAI_adgj + "adgj"; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", - "IS_KANJI", "MIDP_LOWERCASE_LATIN", - "IS_FULLWIDTH_DIGITS", "MIDP_LOWERCASE_LATIN", - "UCB_THAI", "MIDP_LOWERCASE_LATIN", }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - // key presses (per input mode) - expectedContent); + TextField.ANY, new String[] + { + "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", + "IS_KANJI", "MIDP_LOWERCASE_LATIN", + "IS_FULLWIDTH_DIGITS", "MIDP_LOWERCASE_LATIN", + "UCB_THAI", "MIDP_LOWERCASE_LATIN", + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + // key presses (per input mode) + expectedContent); } /** * Tests null input mode after different input modes in ANY text box. */ - private void testinputModeNullSetting() { + private void testinputModeNullSetting() + { // NOTE: upper cases should be corrected! String expectedContent = "2345adgj" + ARABIC_adgj + "adgj" - + "adgjadgjadgjadgjadgjadgjadgjadgj"; - if (variant == CHINA_VARIANT) { + + "adgjadgjadgjadgjadgjadgjadgjadgj"; + if(variant == CHINA_VARIANT) + { expectedContent = CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj - + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; - // Clear-keys used in chinese input removes latin etc. chars + + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj + + CHINA_adgj + CHINA_adgj + CHINA_adgj + CHINA_adgj; + // Clear-keys used in chinese input removes latin etc. chars } - else if (variant == JAPAN_VARIANT) { + else if(variant == JAPAN_VARIANT) + { expectedContent = "2345" + KANJI_adgj + ARABIC_adgj + KANJI_adgj - + KANJI_adgj + KANJI_adgj + HALFWIDTH_KATAKANA_adgj - + KANJI_adgj + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj - + KANJI_adgj; + + KANJI_adgj + KANJI_adgj + HALFWIDTH_KATAKANA_adgj + + KANJI_adgj + FULLWIDTH_2345 + KANJI_adgj + KANJI_adgj + + KANJI_adgj; } - else if (variant == THAI_VARIANT) { + else if(variant == THAI_VARIANT) + { expectedContent = "2345A" + THAI_adgj + ARABIC_adgj + THAI_adgj - + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj - + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj; + + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj + + THAI_adgj + THAI_adgj + THAI_adgj + THAI_adgj; } doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"IS_LATIN_DIGITS", null, - "UCB_ARABIC", null, - "IS_SIMPLIFIED_HANZI", null, - "IS_HALFWIDTH_KATAKANA", null, - "IS_FULLWIDTH_DIGITS", null, - "UCB_THAI", null, }, - "", // initial content - inputKeys(new int[]{'2', '3', '4', '5'}), false, - expectedContent); + TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", null, + "UCB_ARABIC", null, + "IS_SIMPLIFIED_HANZI", null, + "IS_HALFWIDTH_KATAKANA", null, + "IS_FULLWIDTH_DIGITS", null, + "UCB_THAI", null, + }, + "", // initial content + inputKeys(new int[] {'2', '3', '4', '5'}), false, + expectedContent); } /** @@ -1555,14 +1788,15 @@ * text box. Note: after a comma and space the input mode changes to * Text case (not sure whether this is correct behaviour) */ - private void testcommaInLowerAndUpperCase() { + private void testcommaInLowerAndUpperCase() + { doInputModeSequenceTest(getName(), - TextField.ANY, new String[] - {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN"}, - "", // initial content - new int[]{'2', '3', '1', '0', '4', '5' }, false, - // key presses (per input mode) - "ad. GjAD. Gj"); + TextField.ANY, new String[] + {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN"}, + "", // initial content + new int[] {'2', '3', '1', '0', '4', '5' }, false, + // key presses (per input mode) + "ad. GjAD. Gj"); } @@ -1583,42 +1817,49 @@ * @param expectedContent Expected content of TextBox */ private void doInputModeTest(String testCaseName, - int constraints, String initialInputMode, String initialContent, - int[] pressedKeys, String expectedContent) { + int constraints, String initialInputMode, String initialContent, + int[] pressedKeys, String expectedContent) + { boolean passed = true; SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); - try { + try + { // Create TextBox TextBox textBox = new TextBox( - testCaseName, // title - initialContent, LENGTH, constraints); + testCaseName, // title + initialContent, LENGTH, constraints); // Set initial input mode before displaying TextBox - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textBox.setInitialInputMode(initialInputMode); block(KEYEVENT_DELAY); } setCurrent(textBox); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textBox, - expectedContent, expectedContent == null ? true : false); + expectedContent, expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { spede.addToResultsList(testCaseName + " test failed: " - + exc.toString()); + + exc.toString()); spede.addToResultsList(exc); passed = false; } @@ -1645,35 +1886,41 @@ * @param expectedContent Expected content of TextBox */ private void doInputModeSequenceTest(String testCaseName, - int constraints, String[] nextInputModes, String initialContent, - int[] pressedKeys, boolean beforeAndAfter, - String expectedContent) { + int constraints, String[] nextInputModes, String initialContent, + int[] pressedKeys, boolean beforeAndAfter, + String expectedContent) + { boolean passed = true; SpedeRunner spede = (SpedeRunner) SpedeRunner.getInstance(); - try { + try + { // Create TextBox - TextBox textBox = new TextBox(testCaseName, - initialContent, LENGTH, constraints); + TextBox textBox = new TextBox(testCaseName, + initialContent, LENGTH, constraints); // Create another TextBox in order to be able to change focus TextBox other = new TextBox("Focus change", - "Temporary text box", LENGTH, TextField.ANY); + "Temporary text box", LENGTH, TextField.ANY); // Display the original TextBox Display.getDisplay(getMIDlet()).setCurrent(textBox); block(CHANGE_DISPLAYABLE_DELAY); - for (int m = 0; m < nextInputModes.length; m++) { + for(int m = 0; m < nextInputModes.length; m++) + { // Set initial input mode while the original TextBox is visible textBox.setInitialInputMode(nextInputModes[m]); - if (beforeAndAfter) { + if(beforeAndAfter) + { // Do key presses (input mode setting not yet effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1685,8 +1932,10 @@ setCurrent(textBox); // Do key presses again (now input mode setting is effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1695,12 +1944,13 @@ // Check the result of all key presses (i.e. the used input modes) passed = checkResult(testCaseName, textBox, - expectedContent, expectedContent == null ? true : false); + expectedContent, expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { spede.addToResultsList(testCaseName + " test failed: " - + exc.toString()); + + exc.toString()); spede.addToResultsList(exc); passed = false; } @@ -1719,30 +1969,36 @@ * @return result Returns whether test case passed or failed */ private boolean checkResult(String testCaseName, - TextBox textBox, String expectedContent, boolean takeScreenshot) { + TextBox textBox, String expectedContent, boolean takeScreenshot) + { boolean passed = true; // Check the expected content - if (expectedContent != null) { - if (!expectedContent.equals(textBox.getString())) { + if(expectedContent != null) + { + if(!expectedContent.equals(textBox.getString())) + { passed = false; print(testCaseName + " test failed: content: " + textBox.getString() - + ", expected: " + expectedContent); + + ", expected: " + expectedContent); } } // Take the screenshot and compare it with the previous one - if (takeScreenshot) { - if (!takeScreenshot(testCaseName + ".gif")) { - passed = false; - print(testCaseName + " test " - + " failed: screenshot does not match"); - } + if(takeScreenshot) + { + if(!takeScreenshot(testCaseName + ".gif")) + { + passed = false; + print(testCaseName + " test " + + " failed: screenshot does not match"); + } } - if (passed) { - print(testCaseName + " test succeeded: " + textBox.getString()); + if(passed) + { + print(testCaseName + " test succeeded: " + textBox.getString()); } return passed; } @@ -1753,17 +2009,21 @@ * @param keys Key presses according to westen input * @return Key presses for the current variant */ - private int[] inputKeys(int[] keys) { + private int[] inputKeys(int[] keys) + { int[] input = null; int k = 0; - if (variant == CHINA_VARIANT) { + if(variant == CHINA_VARIANT) + { input = new int[4 * keys.length]; - for (int i = 0; i < keys.length; i++) { + for(int i = 0; i < keys.length; i++) + { input[k] = keys[i]; k = k + 1; - if (keys[i] >= '0' && keys[i] <= '9') { + if(keys[i] >= '0' && keys[i] <= '9') + { input[k] = Key.Select; input[k + 1] = Key.Select; input[k + 2] = Key.Clear; @@ -1771,25 +2031,29 @@ } } } - else - if (variant == JAPAN_VARIANT) { - input = new int[2 * keys.length]; - for (int i = 0; i < keys.length; i++) { - input[k] = keys[i]; + else if(variant == JAPAN_VARIANT) + { + input = new int[2 * keys.length]; + for(int i = 0; i < keys.length; i++) + { + input[k] = keys[i]; + k = k + 1; + if(keys[i] >= '0' && keys[i] <= '9') + { + input[k] = Key.Select; k = k + 1; - if (keys[i] >= '0' && keys[i] <= '9') { - input[k] = Key.Select; - k = k + 1; - } } } - else { - input = keys; - k = input.length; - } + } + else + { + input = keys; + k = input.length; + } // Set the array size correct - if (k < input.length) { + if(k < input.length) + { int[] temp = new int[k]; System.arraycopy(input, 0, temp, 0, temp.length); input = temp; diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/FormChangeFocusCheckTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/FormChangeFocusCheckTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/FormChangeFocusCheckTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.textfield; @@ -33,14 +33,16 @@ *
            * Created: 2008-09-15 */ -public class FormChangeFocusCheckTest extends UITestBase { +public class FormChangeFocusCheckTest extends UITestBase +{ private static int maxsize = 2000; /** * Constructor. */ - public FormChangeFocusCheckTest() { + public FormChangeFocusCheckTest() + { } /** @@ -49,7 +51,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public FormChangeFocusCheckTest(String sTestName, TestMethod rTestMethod) { + public FormChangeFocusCheckTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -59,47 +62,57 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new FormChangeFocusCheckTest("testFormChangeAndFocus", - new TestMethod() { - public void run(TestCase tc) { - ((FormChangeFocusCheckTest) tc) - .testFormChangeAndFocus(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((FormChangeFocusCheckTest) tc) + .testFormChangeAndFocus(); + } + })); + aSuite.addTest(new FormChangeFocusCheckTest( + "setTextFieldToAnotherFormTest", new TestMethod() + { + public void run(TestCase tc) + { + ((FormChangeFocusCheckTest) tc) + .setTextFieldToAnotherFormTest(); + } + })); aSuite.addTest(new FormChangeFocusCheckTest( - "setTextFieldToAnotherFormTest", new TestMethod() { - public void run(TestCase tc) { - ((FormChangeFocusCheckTest) tc) - .setTextFieldToAnotherFormTest(); - } - })); - aSuite.addTest(new FormChangeFocusCheckTest( - "removeTextFieldSetTextTest", new TestMethod() { - public void run(TestCase tc) { - ((FormChangeFocusCheckTest) tc) - .removeTextFieldSetTextTest(); - } - })); + "removeTextFieldSetTextTest", new TestMethod() + { + public void run(TestCase tc) + { + ((FormChangeFocusCheckTest) tc) + .removeTextFieldSetTextTest(); + } + })); aSuite.addTest(new FormChangeFocusCheckTest( - "testCaretPossitionAfterDisplayableChange", new TestMethod() { - public void run(TestCase tc) { - ((FormChangeFocusCheckTest) tc) - .testCaretPossitionAfterDisplayableChange(); - } - })); + "testCaretPossitionAfterDisplayableChange", new TestMethod() + { + public void run(TestCase tc) + { + ((FormChangeFocusCheckTest) tc) + .testCaretPossitionAfterDisplayableChange(); + } + })); return aSuite; } /** - * Test that focus behaves correct after switching displayables when - * setCurrentItem is used. - */ - public void testFormChangeAndFocus() { - Form forma = new Form ("Form A"); - Form formb = new Form ("Form B"); - StringItem first = new StringItem (null, "first"); + * Test that focus behaves correct after switching displayables when + * setCurrentItem is used. + */ + public void testFormChangeAndFocus() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + StringItem first = new StringItem(null, "first"); String expectedContent = "Adg"; String expectedContent2 = "Adgjmp"; TextField tf1 = new TextField("name", null, maxsize, TextField.ANY); @@ -146,126 +159,129 @@ display.setCurrentItem(tf1); // seems that in case of setCurrentItem we need to wait more time to - // change displayable. - block(1000); + // change displayable. + block(1000); key('2'); // A - key('3'); // d - key('4'); // g - assertEquals("(case1) No text was inputed", expectedContent, tf1 - .getString()); - setCurrent(formb); + key('3'); // d + key('4'); // g + assertEquals("(case1) No text was inputed", expectedContent, tf1 + .getString()); + setCurrent(formb); - setCurrent(forma); + setCurrent(forma); - block(1000);// - // key('5', 0); // - key('5'); // k - key('6'); // m - key('7'); // p - assertEquals("(case2)No text was inputed after switching Displayble", - expectedContent2, tf1.getString()); - display.setCurrentItem(first); - block(CHANGE_DISPLAYABLE_DELAY); + block(1000);// + // key('5', 0); // + key('5'); // k + key('6'); // m + key('7'); // p + assertEquals("(case2)No text was inputed after switching Displayble", + expectedContent2, tf1.getString()); + display.setCurrentItem(first); + block(CHANGE_DISPLAYABLE_DELAY); key('2'); // a - key('3'); // d - key('4'); // g - assertEquals("(case3)text was inputed when setCurrentItem was set to " - + "StringItem", expectedContent2, tf1.getString()); - setCurrent(formb); - block(CHANGE_DISPLAYABLE_DELAY); + key('3'); // d + key('4'); // g + assertEquals("(case3)text was inputed when setCurrentItem was set to " + + "StringItem", expectedContent2, tf1.getString()); + setCurrent(formb); + block(CHANGE_DISPLAYABLE_DELAY); - setCurrent(forma); - block(CHANGE_DISPLAYABLE_DELAY); + setCurrent(forma); + block(CHANGE_DISPLAYABLE_DELAY); - key('2'); // a - key('3'); // d - key('4'); // g + key('2'); // a + key('3'); // d + key('4'); // g assertEquals("(case4)text was inputed when setCurrent was set to " - + "back to Form A and TextField was not visible", - expectedContent2, tf1.getString()); + + "back to Form A and TextField was not visible", + expectedContent2, tf1.getString()); } /** - * Check that caretPosition is remains the same when TextField is set to - * other form. - */ - public void setTextFieldToAnotherFormTest() { - String expectedContent = "Boaddy"; - Form forma = new Form("Form A"); - Form formb = new Form("Form B"); - TextField tf = new TextField("hader", "Body", maxsize, TextField.ANY); - forma.append(tf); + * Check that caretPosition is remains the same when TextField is set to + * other form. + */ + public void setTextFieldToAnotherFormTest() + { + String expectedContent = "Boaddy"; + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + TextField tf = new TextField("hader", "Body", maxsize, TextField.ANY); + forma.append(tf); - setCurrent(forma); - key(Key.LeftArrow); - key(Key.LeftArrow); // caret o|d - forma.delete(0); - formb.append(tf); - setCurrent(formb); - key('2'); // a - key('3'); // d - assertEquals("caret position was not the same after assigning TextField" - + " to another form", expectedContent, tf.getString()); - forma = null; - formb = null; - tf = null; - } + setCurrent(forma); + key(Key.LeftArrow); + key(Key.LeftArrow); // caret o|d + forma.delete(0); + formb.append(tf); + setCurrent(formb); + key('2'); // a + key('3'); // d + assertEquals("caret position was not the same after assigning TextField" + + " to another form", expectedContent, tf.getString()); + forma = null; + formb = null; + tf = null; + } /** - * Check that get caretPosition return correctPosition after TextField - * Removed from the Form and setString() is used. - */ - public void removeTextFieldSetTextTest() { - Form form = new Form("Form"); - TextField tf = new TextField("header", "some text", maxsize, - TextField.ANY); - form.append(tf); - setCurrent(form); - // enter some text to TextField - key('2'); // a - key('3'); // d - form.delete(0); - tf.setString("four"); - assertEquals("caret position was not set to correct, after setStrin()", - tf.size(), tf.getCaretPosition()); - form = null; - tf = null; - } + * Check that get caretPosition return correctPosition after TextField + * Removed from the Form and setString() is used. + */ + public void removeTextFieldSetTextTest() + { + Form form = new Form("Form"); + TextField tf = new TextField("header", "some text", maxsize, + TextField.ANY); + form.append(tf); + setCurrent(form); + // enter some text to TextField + key('2'); // a + key('3'); // d + form.delete(0); + tf.setString("four"); + assertEquals("caret position was not set to correct, after setStrin()", + tf.size(), tf.getCaretPosition()); + form = null; + tf = null; + } /** - * Check that caret positioned correctly after switching displayables. - */ - public void testCaretPossitionAfterDisplayableChange() { - Form forma = new Form("Form A"); - Form formb = new Form("Form B"); - TextField tf1 = new TextField("header", null, maxsize, TextField.ANY); - TextField tf2 = new TextField("header", null, maxsize, TextField.ANY); - tf1.setString("some text that should occupy few lines"); - tf2.setString("some text that should occupy few lines also"); - forma.append(tf1); - forma.append(tf2); - setCurrent(forma); - key(Key.LeftArrow); - key(Key.LeftArrow); - assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 - .getCaretPosition()); - setCurrent(formb); - setCurrent(forma); - assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 - .getCaretPosition()); - //go to next textField - key(Key.DownArrow); - key(Key.DownArrow); - key(Key.LeftArrow); - key(Key.LeftArrow); - assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 - .getCaretPosition()); - setCurrent(formb); - setCurrent(forma); - assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 - .getCaretPosition()); - } + * Check that caret positioned correctly after switching displayables. + */ + public void testCaretPossitionAfterDisplayableChange() + { + Form forma = new Form("Form A"); + Form formb = new Form("Form B"); + TextField tf1 = new TextField("header", null, maxsize, TextField.ANY); + TextField tf2 = new TextField("header", null, maxsize, TextField.ANY); + tf1.setString("some text that should occupy few lines"); + tf2.setString("some text that should occupy few lines also"); + forma.append(tf1); + forma.append(tf2); + setCurrent(forma); + key(Key.LeftArrow); + key(Key.LeftArrow); + assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 + .getCaretPosition()); + setCurrent(formb); + setCurrent(forma); + assertEquals("caret is not on the correct place", tf1.size() - 2, tf1 + .getCaretPosition()); + //go to next textField + key(Key.DownArrow); + key(Key.DownArrow); + key(Key.LeftArrow); + key(Key.LeftArrow); + assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 + .getCaretPosition()); + setCurrent(formb); + setCurrent(forma); + assertEquals("caret is not on the correct place", tf2.size() - 1, tf2 + .getCaretPosition()); + } } diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldCommandTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldCommandTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldCommandTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.textfield; @@ -33,14 +33,16 @@ *
            * Created: 2008-09-15 */ -public class TextFieldCommandTest extends ItemUITestBase { +public class TextFieldCommandTest extends ItemUITestBase +{ private static int maxsize = 2000; /** * Constructor. */ - public TextFieldCommandTest() { + public TextFieldCommandTest() + { } /** @@ -49,7 +51,8 @@ * @param sTestName Test name. * @param rTestMethod Test method. */ - public TextFieldCommandTest(String sTestName, TestMethod rTestMethod) { + public TextFieldCommandTest(String sTestName, TestMethod rTestMethod) + { super(sTestName, rTestMethod); } @@ -59,35 +62,43 @@ * * @return New testsuite. */ - public Test suite() { + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TextFieldCommandTest("testCommands", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldCommandTest) tc).testCommands(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldCommandTest) tc).testCommands(); + } + })); aSuite.addTest(new TextFieldCommandTest("testTextFieldChange", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldCommandTest) tc).testTextFieldChange(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldCommandTest) tc).testTextFieldChange(); + } + })); aSuite.addTest(new TextFieldCommandTest("testItemState", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldCommandTest) tc).testItemState(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldCommandTest) tc).testItemState(); + } + })); return aSuite; } /** * Tests the basic functionality of command added to TextField. */ - public void testCommands() { - TextField tf = new TextField ("name", "text", maxsize, TextField.ANY); + public void testCommands() + { + TextField tf = new TextField("name", "text", maxsize, TextField.ANY); Command ok = new Command("Ok", "", Command.ITEM, 0); tf.addCommand(ok); @@ -106,11 +117,12 @@ /** * Tests TextField's value changing. */ - public void testTextFieldChange() { + public void testTextFieldChange() + { TextField tf1 = new TextField("TextField", "text1", maxsize, - TextField.ANY); + TextField.ANY); TextField tf2 = new TextField("TextField", "text2", maxsize, - TextField.ANY); + TextField.ANY); boolean case1 = true; boolean case2 = true; boolean case3 = true; @@ -123,20 +135,22 @@ // Change TextField CaretPosition key(Key.RightArrow); - if (tf1.getCaretPosition() != 0) { + if(tf1.getCaretPosition() != 0) + { case1 = false; reason = "Wrong CaretPosition(case1). " + "expected " + 0 - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); reason += "<<<<<>>>>>>"; } - //assertEquals("Wrong CaretPosition(case1).", 0, tf1.getCaretPosition()); + //assertEquals("Wrong CaretPosition(case1).", 0, tf1.getCaretPosition()); // Change TextField CaretPosition back to original: key(Key.LeftArrow); - if (tf1.size() != tf1.getCaretPosition()) { + if(tf1.size() != tf1.getCaretPosition()) + { case2 = false; reason += "Wrong CaretPosition(case 2)." + "expected " + tf1.size() - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); reason += "<<<<<>>>>>>"; } /*assertEquals("Wrong CaretPosition(case 2).", tf1.size(), @@ -144,10 +158,11 @@ */ // Change focus to nextTextField key(Key.DownArrow); - if (tf2.getCaretPosition() != 0) { + if(tf2.getCaretPosition() != 0) + { case3 = false; reason += "Wrong CaretPosition(case 3)." + "expected " + 0 - + "but got" + tf2.getCaretPosition(); + + "but got" + tf2.getCaretPosition(); reason += "<<<<<>>>>>>"; } /*assertEquals("Wrong CaretPosition(case 3).", 0, @@ -155,10 +170,11 @@ // Now Caret have to be in the end key(Key.LeftArrow); - if (tf2.size() != tf2.getCaretPosition()) { + if(tf2.size() != tf2.getCaretPosition()) + { case4 = false; reason += "Wrong CaretPosition(case 4)." + "expected " + tf2.size() - + "but got" + tf2.getCaretPosition(); + + "but got" + tf2.getCaretPosition(); reason += "<<<<<>>>>>>"; } /* @@ -168,10 +184,11 @@ //go to first TextField key(Key.RightArrow); key(Key.UpArrow); - if (tf1.size() != tf1.getCaretPosition()) { + if(tf1.size() != tf1.getCaretPosition()) + { case5 = false; reason += "Wrong CaretPosition(case 5)." + "expected " + tf1.size() - + "but got" + tf1.getCaretPosition(); + + "but got" + tf1.getCaretPosition(); } assertTrue(reason, case1 & case2 & case3 & case4 & case5); } @@ -180,9 +197,10 @@ * Tests that Form receives ItemStateChanged-events when TextField's * value is changed. */ - public void testItemState() { + public void testItemState() + { TextField tf = new TextField("header", "text", maxsize, - TextField.ANY); + TextField.ANY); form.append(tf); diff -r 2a9601315dfc -r 98ccebc37403 javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldSetInitialInputModeTest.java --- a/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldSetInitialInputModeTest.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/lcdui_qt/tsrc/uitestsrc/t_uirobot/textfield/TextFieldSetInitialInputModeTest.java Fri May 14 15:47:24 2010 +0300 @@ -11,7 +11,7 @@ * * Contributors: * -* Description: +* Description: * */ package t_uirobot.textfield; @@ -58,7 +58,8 @@ * reason. Note: The references images differ from 3.0 to 3.1, and 3.2 */ -public class TextFieldSetInitialInputModeTest extends UITestBase { +public class TextFieldSetInitialInputModeTest extends UITestBase +{ /* Expected results for diffrent input modes */ private static final String ARABIC_adgj = "" + (char) 1576 + (char) 1575 @@ -82,241 +83,298 @@ private final int normalSize = 2000; /** - * Default constructor. - */ - public TextFieldSetInitialInputModeTest() { - } + * Default constructor. + */ + public TextFieldSetInitialInputModeTest() + { + } - /** - * Constructor. - * - * @param sTestName - * name of testcase. - * @param rTestMethod - * test method. - */ - public TextFieldSetInitialInputModeTest(String sTestName, - TestMethod rTestMethod) { - super(sTestName, rTestMethod); - } + /** + * Constructor. + * + * @param sTestName + * name of testcase. + * @param rTestMethod + * test method. + */ + public TextFieldSetInitialInputModeTest(String sTestName, + TestMethod rTestMethod) + { + super(sTestName, rTestMethod); + } /*************************************************************************** - * To create the test suite. You need to add a new aSuite.addTest antry for - * any new test methods. - * - * @return test suite - */ - public Test suite() { + * To create the test suite. You need to add a new aSuite.addTest antry for + * any new test methods. + * + * @return test suite + */ + public Test suite() + { TestSuite aSuite = new TestSuite(); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testDefaultInputMode", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testDefaultInputMode(); - } - })); + "testDefaultInputMode", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testDefaultInputMode(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_LATIN_DIGITS", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_LATIN_DIGITS(); - } - })); + "testIS_LATIN_DIGITS", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_LATIN_DIGITS(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_LATIN_DIGITS2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_LATIN_DIGITS2(); - } - })); + "testIS_LATIN_DIGITS2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_LATIN_DIGITS2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testIS_LATIN", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testIS_LATIN(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testIS_LATIN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testMIDP_UPPERCASE_LATIN", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testMIDP_UPPERCASE_LATIN(); - } - })); + "testMIDP_UPPERCASE_LATIN", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testMIDP_UPPERCASE_LATIN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testMIDP_LOWERCASE_LATIN", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testMIDP_LOWERCASE_LATIN(); - } - })); + "testMIDP_LOWERCASE_LATIN", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testMIDP_LOWERCASE_LATIN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testUCB_BASIC_LATIN", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_BASIC_LATIN(); - } - })); + "testUCB_BASIC_LATIN", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_BASIC_LATIN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_GREEK", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testUCB_GREEK(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testUCB_GREEK(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_CYRILLIC", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_CYRILLIC(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_CYRILLIC(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_HEBREW", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_HEBREW(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_HEBREW(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_ARABIC()", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_ARABIC(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_ARABIC(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testUCB_DEVANAGARI", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_DEVANAGARI(); - } - })); + "testUCB_DEVANAGARI", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_DEVANAGARI(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_ARMENIAN", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_ARMENIAN(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_ARMENIAN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_THAI", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testUCB_THAI(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testUCB_THAI(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testUCB_HIRAGANA()", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_HIRAGANA(); - } - })); + "testUCB_HIRAGANA()", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_HIRAGANA(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUCB_KATAKANA", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUCB_KATAKANA(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUCB_KATAKANA(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_HALFWIDTH_KATAKANA", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_HALFWIDTH_KATAKANA(); - } - })); + "testIS_HALFWIDTH_KATAKANA", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_HALFWIDTH_KATAKANA(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testIS_KANJI()", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testIS_KANJI(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testIS_KANJI(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_FULLWIDTH_DIGITS", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_FULLWIDTH_DIGITS(); - } - })); + "testIS_FULLWIDTH_DIGITS", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_FULLWIDTH_DIGITS(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_FULLWIDTH_LATIN", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_FULLWIDTH_LATIN(); - } - })); + "testIS_FULLWIDTH_LATIN", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_FULLWIDTH_LATIN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_SIMPLIFIED_HANZI()", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_SIMPLIFIED_HANZI(); - } - })); + "testIS_SIMPLIFIED_HANZI()", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_SIMPLIFIED_HANZI(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testIS_TRADITIONAL_HANZI", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testIS_TRADITIONAL_HANZI(); - } - })); + "testIS_TRADITIONAL_HANZI", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testIS_TRADITIONAL_HANZI(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testnull", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testnull(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testnull(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testUNKNOWN", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testUNKNOWN(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testUNKNOWN(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest("testempty", - new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc).testempty(); - } - })); + new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc).testempty(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModeChange", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModeChange(); - } - })); + "testinputModeChange", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModeChange(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModeAndMenuOpen", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModeAndMenuOpen(); - } - })); // */ + "testinputModeAndMenuOpen", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModeAndMenuOpen(); + } + })); // */ /* * aSuite.addTest(new TextFieldSetInitialInputModeTest( @@ -331,100 +389,124 @@ */ aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInEmailaddr", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInEmailaddr(); - } - })); + "testinputModesInEmailaddr", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInEmailaddr(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInEmailaddr2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInEmailaddr2(); - } - })); + "testinputModesInEmailaddr2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInEmailaddr2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInUrl", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInUrl(); - } - })); + "testinputModesInUrl", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInUrl(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInUrl2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInUrl2(); - } - })); + "testinputModesInUrl2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInUrl2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInPassword", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInPassword(); - } - })); + "testinputModesInPassword", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInPassword(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInPassword2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInPassword2(); - } - })); + "testinputModesInPassword2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInPassword2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInAny()", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInAny(); - } - })); + "testinputModesInAny()", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInAny(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInAny2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInAny2(); - } - })); + "testinputModesInAny2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInAny2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInCapsSentence", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInCapsSentence(); - } - })); + "testinputModesInCapsSentence", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInCapsSentence(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInCapsWord()", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInCapsWord(); - } - })); + "testinputModesInCapsWord()", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInCapsWord(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInCapsSentenceEmailaddr", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInCapsSentenceEmailaddr(); - } - })); + "testinputModesInCapsSentenceEmailaddr", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInCapsSentenceEmailaddr(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModesInCapsSentenceUrl", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModesInCapsSentenceUrl(); - } - })); + "testinputModesInCapsSentenceUrl", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModesInCapsSentenceUrl(); + } + })); /* * aSuite.addTest(new TextFieldSetInitialInputModeTest( @@ -439,36 +521,44 @@ */ aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputLatinAfterOtherModes", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputLatinAfterOtherModes(); - } - })); + "testinputLatinAfterOtherModes", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputLatinAfterOtherModes(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputLatinAfterOtherModes2", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputLatinAfterOtherModes2(); - } - })); + "testinputLatinAfterOtherModes2", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputLatinAfterOtherModes2(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testinputModeNullSetting", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testinputModeNullSetting(); - } - })); + "testinputModeNullSetting", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testinputModeNullSetting(); + } + })); aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testcommaInLowerAndUpperCase", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testcommaInLowerAndUpperCase(); - } - })); + "testcommaInLowerAndUpperCase", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testcommaInLowerAndUpperCase(); + } + })); /* * see comment from the test case aSuite.addTest(new @@ -478,12 +568,14 @@ */ aSuite.addTest(new TextFieldSetInitialInputModeTest( - "testUppercaseBeforeMakingFormCurrent", new TestMethod() { - public void run(TestCase tc) { - ((TextFieldSetInitialInputModeTest) tc) - .testUppercaseBeforeMakingFormCurrent(); - } - })); + "testUppercaseBeforeMakingFormCurrent", new TestMethod() + { + public void run(TestCase tc) + { + ((TextFieldSetInitialInputModeTest) tc) + .testUppercaseBeforeMakingFormCurrent(); + } + })); return aSuite; } @@ -494,48 +586,52 @@ * Tests default input mode, i.e. setInitialInputMode not called. The * default input mode depends on the build variant in use. */ - private void testDefaultInputMode() { + private void testDefaultInputMode() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "NONE", // no initial input - // mode setting - "", // initial content - new int[] { '2', '3', '4', '5', }, // key presses - expectedContent); + // mode setting + "", // initial content + new int[] { '2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called before * displaying the text field. Number input mode will be used. */ - private void testIS_LATIN_DIGITS() { + private void testIS_LATIN_DIGITS() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN_DIGITS", "", - // initial - // content - new int[] { '2', '3', '4', '5', }, // key presses - "2345"); // expected content + // initial + // content + new int[] { '2', '3', '4', '5', }, // key presses + "2345"); // expected content } /** * Tests setInitialInputMode("IS_LATIN_DIGITS"). The method is called after * appending the text field into the form Number input mode will be used. */ - private void testIS_LATIN_DIGITS2() { + private void testIS_LATIN_DIGITS2() + { doInputModeTest2(getName(), TextField.ANY, "IS_LATIN_DIGITS", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "2345"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "2345"); // expected content } /** * Tests setInitialInputMode("IS_LATIN"). The method is called before * displaying the text field. Latin text input mode will be used */ - private void testIS_LATIN() { + private void testIS_LATIN() + { doInputModeTest(getName(), TextField.ANY, "IS_LATIN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - "Adgj"); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + "Adgj"); // expected content } /** @@ -543,11 +639,12 @@ * before displaying the text field. Uppercase latin text input mode will be * used. */ - private void testMIDP_UPPERCASE_LATIN() { + private void testMIDP_UPPERCASE_LATIN() + { doInputModeTest(getName(), TextField.ANY, "MIDP_UPPERCASE_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "ADGJ"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "ADGJ"); // expected content } /** @@ -555,11 +652,12 @@ * before displaying the text field. Lowercase latin text input mode will be * used. */ - private void testMIDP_LOWERCASE_LATIN() { + private void testMIDP_LOWERCASE_LATIN() + { doInputModeTest(getName(), TextField.ANY, "MIDP_LOWERCASE_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "adgj"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "adgj"); // expected content } /** @@ -567,68 +665,74 @@ * before displaying the text field. Latin text input mode will be used * (same as "IS_LATIN"). */ - private void testUCB_BASIC_LATIN() { + private void testUCB_BASIC_LATIN() + { doInputModeTest(getName(), TextField.ANY, "UCB_BASIC_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - "Adgj"); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + "Adgj"); // expected content } /** * Tests setInitialInputMode("UCB_GREEK"). The method is called before * displaying the text field. Greek input mode will be used. */ - private void testUCB_GREEK() { + private void testUCB_GREEK() + { doInputModeTest(getName(), TextField.ANY, "UCB_GREEK", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - GREEK_Adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + GREEK_Adgj); // expected content } /** * Tests setInitialInputMode("UCB_CYRILLIC"). The method is called before * displaying the text field. Cyrillic input mode will be used. */ - private void testUCB_CYRILLIC() { + private void testUCB_CYRILLIC() + { doInputModeTest(getName(), TextField.ANY, "UCB_CYRILLIC", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - CYRILLIC_Adgj); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + CYRILLIC_Adgj); // expected content } /** * Tests setInitialInputMode("UCB_HEBREW"). The method is called before * displaying the text field. Hebrew input mode will be used. */ - private void testUCB_HEBREW() { + private void testUCB_HEBREW() + { doInputModeTest(getName(), TextField.ANY, "UCB_HEBREW", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presess - HEBREW_adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presess + HEBREW_adgj); // expected content } /** * Tests setInitialInputMode("UCB_ARABIC"). The method is called before * displaying the text field. Arabic input mode will be used. */ - private void testUCB_ARABIC() { + private void testUCB_ARABIC() + { doInputModeTest(getName(), TextField.ANY, "UCB_ARABIC", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - ARABIC_adgj); // expected content + // content + new int[] {'2', '3', '4', '5', }, // key presses + ARABIC_adgj); // expected content } /** * Tests setInitialInputMode("UCB_DEVANAGARI"). The method is called before * displaying the text field. Devanagari/Hindi input mode will be used. */ - private void testUCB_DEVANAGARI() { + private void testUCB_DEVANAGARI() + { String expectedContent = "\u0905\u090f\u0915\u091a"; doInputModeTest(getName(), TextField.ANY, "UCB_DEVANAGARI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); // expected content + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); // expected content } /** @@ -636,13 +740,14 @@ * displaying the text field. This input mode is not supported in 3.0, so * default input mode will be used. */ - private void testUCB_ARMENIAN() { + private void testUCB_ARMENIAN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_ARMENIAN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -650,13 +755,14 @@ * displaying the text field. This input mode is supported only in Thai * variant; other variants will use the default input mode. */ - private void testUCB_THAI() { + private void testUCB_THAI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_THAI", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -664,13 +770,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testUCB_HIRAGANA() { + private void testUCB_HIRAGANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_HIRAGANA", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -678,13 +785,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testUCB_KATAKANA() { + private void testUCB_KATAKANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UCB_KATAKANA", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -692,13 +800,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_HALFWIDTH_KATAKANA() { + private void testIS_HALFWIDTH_KATAKANA() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_HALFWIDTH_KATAKANA", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -706,13 +815,14 @@ * displaying the text field. This input mode is supported only in Japan * variant; other variants will use the default input mode. */ - private void testIS_KANJI() { + private void testIS_KANJI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_KANJI", "", // initial - // content - new int[] {'2', '3', '4', '5',}, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5',}, // key presses + expectedContent); } /** @@ -720,13 +830,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_FULLWIDTH_DIGITS() { + private void testIS_FULLWIDTH_DIGITS() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_FULLWIDTH_DIGITS", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -734,13 +845,14 @@ * before displaying the text field. This input mode is supported only in * Japan variant; other variants will use the default input mode. */ - private void testIS_FULLWIDTH_LATIN() { + private void testIS_FULLWIDTH_LATIN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_FULLWIDTH_LATIN", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -748,13 +860,14 @@ * before displaying the text field. This input mode is supported only in * China variant; other variants will use the default input mode. */ - private void testIS_SIMPLIFIED_HANZI() { + private void testIS_SIMPLIFIED_HANZI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_SIMPLIFIED_HANZI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -764,13 +877,14 @@ * either Traditional Hongkong or Traditional Taiwan; otherwise the default * input mode will be used. */ - private void testIS_TRADITIONAL_HANZI() { + private void testIS_TRADITIONAL_HANZI() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "IS_TRADITIONAL_HANZI", "", - // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // initial content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } @@ -778,37 +892,40 @@ * Tests setInitialInputMode(null). The method is called before displaying * the text field. This default input mode will be used. */ - private void testnull() { + private void testnull() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, null, "", // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode("UNKNOWN"). The method is called before * displaying the text field. The default input mode will be used. */ - private void testUNKNOWN() { + private void testUNKNOWN() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "UNKNOWN", "", // initial - // content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + // content + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** * Tests setInitialInputMode(""). The method is called before displaying the * text field. The default input mode will be used. */ - private void testempty() { + private void testempty() + { String expectedContent = "Adgj"; doInputModeTest(getName(), TextField.ANY, "", "", // initial content - new int[] {'2', '3', '4', '5', }, // key presses - expectedContent); + new int[] {'2', '3', '4', '5', }, // key presses + expectedContent); } /** @@ -816,17 +933,18 @@ * visible. Setting the initial input mode has no effect until focus is * changed temporarily elsewhere and then back to TextField. */ - private void testinputModeChange() { + private void testinputModeChange() + { String expectedContent = "Adgj2345"; doInputModeSequenceTest(getName(), TextField.ANY, - new String[] {"IS_LATIN_DIGITS" }, "", // initial content - new int[] {'2', '3', '4', '5', }, true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + new String[] {"IS_LATIN_DIGITS" }, "", // initial content + new int[] {'2', '3', '4', '5', }, true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -834,17 +952,18 @@ * obscured the editor. Setting the initial input mode has no effect until * focus is changed temporarily elsewhere and then back to TextField. */ - private void testinputModeAndMenuOpen() { + private void testinputModeAndMenuOpen() + { String expectedContent = "Adgj2345"; doInputModeSequenceTest(getName(), TextField.ANY, - new String[] {"IS_LATIN_DIGITS" }, "", // initial content - new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5' ,}, true, - // keys are pressed both before and after the temporary - // focus change => input mode before the focus change - // will be the same as the original input mode although - // setInitialInputMode has already been called - expectedContent); + new String[] {"IS_LATIN_DIGITS" }, "", // initial content + new int[] {'2', '3', Key.Edit, Key.CBA2, '4', '5' ,}, true, + // keys are pressed both before and after the temporary + // focus change => input mode before the focus change + // will be the same as the original input mode although + // setInitialInputMode has already been called + expectedContent); } /** @@ -852,15 +971,18 @@ * changed after each setting to make the input mode effective. Setting the * initial input mode has no effect in NUMERIC text field. */ - private void testinputModesInNumber() { - doInputModeSequenceTest(getName(), TextField.NUMERIC, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + private void testinputModesInNumber() + { + doInputModeSequenceTest(getName(), TextField.NUMERIC, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -868,15 +990,18 @@ * changed after each setting to make the input mode effective. Setting the * initial input mode has no effect in DECIMAL text field. */ - private void testinputModesInDecimal() { - doInputModeSequenceTest(getName(), TextField.DECIMAL, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "2345234523452345234523452345"); // expected content + private void testinputModesInDecimal() + { + doInputModeSequenceTest(getName(), TextField.DECIMAL, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "UCB_ARABIC", "UCB_GREEK", "IS_KANJI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "2345234523452345234523452345"); // expected content } /** @@ -884,15 +1009,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInEmailaddr() { - doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] { - "NONE", // starts from default input mode - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInEmailaddr() + { + doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] + { + "NONE", // starts from default input mode + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -902,15 +1030,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInEmailaddr2() { + private void testinputModesInEmailaddr2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.EMAILADDR, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -918,15 +1049,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInUrl() { - doInputModeSequenceTest(getName(), TextField.URL, new String[] { - "NONE", // default input mode in ANY text field - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInUrl() + { + doInputModeSequenceTest(getName(), TextField.URL, new String[] + { + "NONE", // default input mode in ANY text field + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -936,15 +1070,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInUrl2() { + private void testinputModesInUrl2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.URL, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.URL, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -952,15 +1089,18 @@ * changed after each setting to make the input mode effective. In all * variants the default input mode is latin with lower case. */ - private void testinputModesInPassword() { - doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] { - "NONE", // default input mode in ANY text field - "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); + private void testinputModesInPassword() + { + doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] + { + "NONE", // default input mode in ANY text field + "IS_LATIN", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "UCB_GREEK", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjadgjADGJadgj" + ARABIC_adgj + GREEK_adgj + "2345"); // expected content } @@ -970,28 +1110,34 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInPassword2() { + private void testinputModesInPassword2() + { String expectedContent = "23452345234523452345"; - doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", - "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // pressed keys (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.PASSWORD, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", + "IS_FULLWIDTH_DIGITS", "IS_KANJI", "UCB_THAI", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // pressed keys (per input mode) + expectedContent); } /** * Tests different sequential input modes in ANY text field. Focus is * changed after each setting to make the input mode effective. */ - private void testinputModesInAny() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS" , }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // pressed keys (per input mode) - GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); + private void testinputModesInAny() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_GREEK", "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS" , + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // pressed keys (per input mode) + GREEK_Adgj + "ADGJadgj" + ARABIC_adgj + "2345"); // expected content } @@ -1001,15 +1147,18 @@ * Japanese or Chinese input mode will have effect in the corresponding * variants. */ - private void testinputModesInAny2() { + private void testinputModesInAny2() + { String expectedContent = "Adgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "NONE", // starts from default input mode - "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", - "UCB_THAI", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "NONE", // starts from default input mode + "IS_SIMPLIFIED_HANZI", "IS_FULLWIDTH_DIGITS", "IS_KANJI", + "UCB_THAI", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -1018,15 +1167,17 @@ * field. Focus is changed after each setting to make the input mode * effective. */ - private void testinputModesInCapsSentence() { + private void testinputModesInCapsSentence() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; doInputModeSequenceTest(getName(), TextField.INITIAL_CAPS_SENTENCE, - new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -1034,15 +1185,17 @@ * ignored if the INITIAL_CAPS_WORD modifier is defined in ANY text field. * Focus is changed after each setting to make the input mode effective. */ - private void testinputModesInCapsWord() { + private void testinputModesInCapsWord() + { String expectedContent = "Adgjadgj" + ARABIC_adgj + "2345"; doInputModeSequenceTest(getName(), TextField.INITIAL_CAPS_WORD, - new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "IS_LATIN_DIGITS", }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + new String[] {"MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "IS_LATIN_DIGITS", + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** @@ -1051,14 +1204,16 @@ * the modifier is meaningless in EMAILADDR. Focus is changed after each * setting to make the input mode effective. */ - private void testinputModesInCapsSentenceEmailaddr() { + private void testinputModesInCapsSentenceEmailaddr() + { doInputModeSequenceTest(getName(), TextField.EMAILADDR - | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", - "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", + "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** @@ -1067,27 +1222,32 @@ * modifier is meaningless in URL. Focus is changed after each setting to * make the input mode effective. */ - private void testinputModesInCapsSentenceUrl() { + private void testinputModesInCapsSentenceUrl() + { doInputModeSequenceTest(getName(), TextField.URL - | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", - "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - "adgjADGJadgj"); // expected content + | TextField.INITIAL_CAPS_SENTENCE, new String[] {"IS_LATIN", + "MIDP_UPPERCASE_LATIN", "MIDP_LOWERCASE_LATIN", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + "adgjADGJadgj"); // expected content } /** * Tests different textual input modes after IS_LATIN_DIGITS. Focus is * changed after each setting to make the input mode effective. */ - private void testinputModesAfterNumberMode() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", "MIDP_UPPERCASE_LATIN", "IS_LATIN_DIGITS", - "MIDP_LOWERCASE_LATIN", "IS_LATIN_DIGITS", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, "2345ADGJ2345adgj2345" - + ARABIC_adgj); + private void testinputModesAfterNumberMode() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", "MIDP_UPPERCASE_LATIN", "IS_LATIN_DIGITS", + "MIDP_LOWERCASE_LATIN", "IS_LATIN_DIGITS", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, "2345ADGJ2345adgj2345" + + ARABIC_adgj); } /** @@ -1096,29 +1256,35 @@ * Japanese or Chinese input mode will have effect only in the corresponding * variants. */ - private void testinputModesAfterNumberMode2() { + private void testinputModesAfterNumberMode2() + { String expectedContent = "23452345234523452345234523452345"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", "IS_LATIN_DIGITS", - "IS_KANJI", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", - "IS_LATIN_DIGITS", "UCB_THAI", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", "IS_SIMPLIFIED_HANZI", "IS_LATIN_DIGITS", + "IS_KANJI", "IS_LATIN_DIGITS", "IS_FULLWIDTH_DIGITS", + "IS_LATIN_DIGITS", "UCB_THAI", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** * Tests latin input modes after other input modes. Focus is changed after * each setting to make the input mode effective. */ - private void testinputLatinAfterOtherModes() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_HEBREW", "IS_LATIN", "UCB_GREEK", "MIDP_UPPERCASE_LATIN", - "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", "UCB_CYRILLIC", - "IS_LATIN", }, "", // initial content - new int[] {'2', '3', '4', '5', }, false, HEBREW_adgj + "adgj" - + GREEK_adgj + "ADGJ" + ARABIC_adgj + "adgj" - + CYRILLIC_adgj + "adgj"); + private void testinputLatinAfterOtherModes() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_HEBREW", "IS_LATIN", "UCB_GREEK", "MIDP_UPPERCASE_LATIN", + "UCB_ARABIC", "MIDP_LOWERCASE_LATIN", "UCB_CYRILLIC", + "IS_LATIN", + }, "", // initial content + new int[] {'2', '3', '4', '5', }, false, HEBREW_adgj + "adgj" + + GREEK_adgj + "ADGJ" + ARABIC_adgj + "adgj" + + CYRILLIC_adgj + "adgj"); } /** @@ -1127,30 +1293,36 @@ * Japanese or Chinese input mode will have effect only in the corresponding * variants. */ - private void testinputLatinAfterOtherModes2() { + private void testinputLatinAfterOtherModes2() + { String expectedContent = "Adgjadgjadgjadgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", "IS_KANJI", - "MIDP_LOWERCASE_LATIN", "IS_FULLWIDTH_DIGITS", - "MIDP_LOWERCASE_LATIN", "UCB_THAI", "MIDP_LOWERCASE_LATIN", }, - "", // initial content - new int[] {'2', '3', '4', '5', }, false, - // key presses (per input mode) - expectedContent); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_SIMPLIFIED_HANZI", "MIDP_LOWERCASE_LATIN", "IS_KANJI", + "MIDP_LOWERCASE_LATIN", "IS_FULLWIDTH_DIGITS", + "MIDP_LOWERCASE_LATIN", "UCB_THAI", "MIDP_LOWERCASE_LATIN", + }, + "", // initial content + new int[] {'2', '3', '4', '5', }, false, + // key presses (per input mode) + expectedContent); } /** * Tests null input mode after different input modes in ANY text field. */ - private void testinputModeNullSetting() { + private void testinputModeNullSetting() + { String expectedContent = "2345adgj" + ARABIC_adgj + "adgj" - + "adgjadgjadgjadgjadgjadgjadgjadgj"; - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "IS_LATIN_DIGITS", null, "UCB_ARABIC", null, - "IS_SIMPLIFIED_HANZI", null, "IS_HALFWIDTH_KATAKANA", null, - "IS_FULLWIDTH_DIGITS", null, "UCB_THAI", null, }, "", // initial - // content - new int[] {'2', '3', '4', '5', }, false, expectedContent); + + "adgjadgjadgjadgjadgjadgjadgjadgj"; + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "IS_LATIN_DIGITS", null, "UCB_ARABIC", null, + "IS_SIMPLIFIED_HANZI", null, "IS_HALFWIDTH_KATAKANA", null, + "IS_FULLWIDTH_DIGITS", null, "UCB_THAI", null, + }, "", // initial + // content + new int[] {'2', '3', '4', '5', }, false, expectedContent); } /** @@ -1158,13 +1330,16 @@ * text field. Note: after a comma and space the input mode changes to Text * case (not sure whether this is correct behaviour) */ - private void testcommaInLowerAndUpperCase() { - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", }, "", // initial - // content - new int[] {'2', '3', '1', '0', '4', '5', }, false, - // key presses (per input mode) - "ad. GjAD. Gj"); + private void testcommaInLowerAndUpperCase() + { + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "MIDP_LOWERCASE_LATIN", "MIDP_UPPERCASE_LATIN", + }, "", // initial + // content + new int[] {'2', '3', '1', '0', '4', '5', }, false, + // key presses (per input mode) + "ad. GjAD. Gj"); } /** @@ -1173,15 +1348,18 @@ * initial input language got from display language arabic => initial input * langauge got from global input language */ - private void testinputModesWithArabicInputLanguage() { + private void testinputModesWithArabicInputLanguage() + { changeInputLanguage(4, 1); // => Arabic input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(5, 10); // => back to English input language } @@ -1192,15 +1370,18 @@ * initial input language got from display language arabic => initial input * langauge got from hard-coded default (Arabic) */ - private void testinputModesWithCyrillicInputLanguage() { + private void testinputModesWithCyrillicInputLanguage() + { changeInputLanguage(4, 2); // => Cyrillic input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(4, 10); // => back to English input language } @@ -1211,15 +1392,18 @@ * latin => initial input language got from global input language arabic => * initial input langauge got from hard-coded default (Arabic) */ - private void testinputModesWithDanskInputLanguage() { + private void testinputModesWithDanskInputLanguage() + { changeInputLanguage(4, 8); // => Dansk input language - doInputModeSequenceTest(getName(), TextField.ANY, new String[] { - "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", }, "", - // initial content - new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" - + ARABIC_adgj); + doInputModeSequenceTest(getName(), TextField.ANY, new String[] + { + "UCB_CYRILLIC", "MIDP_LOWERCASE_LATIN", "UCB_ARABIC", + }, "", + // initial content + new int[] {'2', '3', '4', '5', }, false, CYRILLIC_Adgj + "adgj" + + ARABIC_adgj); changeInputLanguage(4, 10); // => back to English input language } @@ -1229,7 +1413,8 @@ * TextField to the form, and then making the form current. The input text * must be uppercase. */ - private void testUppercaseBeforeMakingFormCurrent() { + private void testUppercaseBeforeMakingFormCurrent() + { boolean passed = true; int[] pressedKeys = new int[] {'2', '3', '4', '5', }; String expectedContent = "ADGJ"; @@ -1237,12 +1422,13 @@ TextField textField = null; Form form = null; - try { + try + { // Create a form and a text field, and append text field to form - form = new Form(getName()); + form = new Form(getName()); - textField = new TextField("Text field", "", normalSize, TextField.ANY); - form.append(textField); + textField = new TextField("Text field", "", normalSize, TextField.ANY); + form.append(textField); // set the initial input mode before the form is current textField.setInitialInputMode("MIDP_UPPERCASE_LATIN"); @@ -1252,8 +1438,10 @@ setCurrent(form); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1263,14 +1451,15 @@ passed = textField.getString().equals(expectedContent); } - catch (Exception exc) { + catch(Exception exc) + { print(getName() + " test failed: " + exc.toString()); - print(exc); + print(exc); passed = false; } assertTrue(getName() + " test " + "content: " + textField.getString() - + ", expected: " + expectedContent, passed); + + ", expected: " + expectedContent, passed); } /** @@ -1295,24 +1484,28 @@ * Expected content of TextField */ private void doInputModeTest(String testCaseName, int constraints, - String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String initialInputMode, String initialContent, int[] pressedKeys, + String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields Form form = new Form(testCaseName); - TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); - TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); + TextField textField = new TextField("Text field", initialContent, + normalSize, constraints); + TextField otherField = new TextField("Other field", "", normalSize, + TextField.ANY); // Set initial input mode before displaying TextField - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textField.setInitialInputMode(initialInputMode); } form.append(textField); @@ -1322,8 +1515,10 @@ block(CHANGE_DISPLAYABLE_DELAY); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1331,68 +1526,75 @@ // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); } /** - * Private method for testing initial input mode. Creates TextField and sets - * the initial input mode before displaying it. Generates the given key - * presses. At the end compares the content of TextField to the expected - * content, unless the expected content is null; in that case takes a - * screenshot. - * - * @param testCaseName - * Name of the test case - * @param constraints - * Combination of TextField.ANY,... - * @param initialInputMode - * Intial input mode to be set, e.g "IS_LATIN"; "NONE" means that - * setInitialInputMode is not called at all - * @param initialContent - * Initial context of TextField - * @param pressedKeys - * Array of key presses to be generated - * @param expectedContent - * Expected content of TextField - */ + * Private method for testing initial input mode. Creates TextField and sets + * the initial input mode before displaying it. Generates the given key + * presses. At the end compares the content of TextField to the expected + * content, unless the expected content is null; in that case takes a + * screenshot. + * + * @param testCaseName + * Name of the test case + * @param constraints + * Combination of TextField.ANY,... + * @param initialInputMode + * Intial input mode to be set, e.g "IS_LATIN"; "NONE" means that + * setInitialInputMode is not called at all + * @param initialContent + * Initial context of TextField + * @param pressedKeys + * Array of key presses to be generated + * @param expectedContent + * Expected content of TextField + */ private void doInputModeTest2(String testCaseName, int constraints, - String initialInputMode, String initialContent, int[] pressedKeys, - String expectedContent) { + String initialInputMode, String initialContent, int[] pressedKeys, + String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields - Form form = new Form(testCaseName); - TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); - TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); - form.append(textField); - form.append(otherField); + Form form = new Form(testCaseName); + TextField textField = new TextField("Text field", initialContent, + normalSize, constraints); + TextField otherField = new TextField("Other field", "", normalSize, + TextField.ANY); + form.append(textField); + form.append(otherField); // Set initial input mode before displaying TextField - if ("NONE".equals(initialInputMode)) { + if("NONE".equals(initialInputMode)) + { // initial input mode not set } - else { + else + { textField.setInitialInputMode(initialInputMode); } setCurrent(form); block(CHANGE_DISPLAYABLE_DELAY); // Do key presses - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1400,13 +1602,14 @@ // Check the result of key presses (i.e. the used input mode) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); @@ -1439,35 +1642,41 @@ * Expected content of TextField */ private void doInputModeSequenceTest(String testCaseName, int constraints, - String[] nextInputModes, String initialContent, int[] pressedKeys, - boolean beforeAndAfter, String expectedContent) { + String[] nextInputModes, String initialContent, int[] pressedKeys, + boolean beforeAndAfter, String expectedContent) + { boolean passed = true; - try { + try + { // Create a form with two text fields Form form = new Form(testCaseName); TextField textField = new TextField("Text field", initialContent, - normalSize, constraints); + normalSize, constraints); form.append(textField); TextField otherField = new TextField("Other field", "", normalSize, - TextField.ANY); + TextField.ANY); form.append(otherField); // Display the form setCurrent(form); block(CHANGE_DISPLAYABLE_DELAY); - for (int m = 0; m < nextInputModes.length; m++) { + for(int m = 0; m < nextInputModes.length; m++) + { // Set initial input mode while the original TextField is // visible textField.setInitialInputMode(nextInputModes[m]); - if (beforeAndAfter) { + if(beforeAndAfter) + { // Do key presses (input mode setting not yet effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1481,8 +1690,10 @@ key(Key.UpArrow); // Do key presses again (now input mode setting is effective) - if (pressedKeys != null) { - for (int i = 0; i < pressedKeys.length; i++) { + if(pressedKeys != null) + { + for(int i = 0; i < pressedKeys.length; i++) + { key(pressedKeys[i]); } } @@ -1491,13 +1702,14 @@ // Check the result of all key presses (i.e. the used input modes) passed = checkResult(testCaseName, textField, expectedContent, - expectedContent == null ? true : false); + expectedContent == null ? true : false); } - catch (Exception exc) { + catch(Exception exc) + { print(testCaseName + " test failed: " + exc.toString()); - print(exc); - passed = false; + print(exc); + passed = false; } assertTrue(testCaseName, passed); @@ -1518,55 +1730,62 @@ * @return result Returns whether test case passed or failed */ private boolean checkResult(String testCaseName, TextField textBox, - String expectedContent, boolean takeScreenshot) { + String expectedContent, boolean takeScreenshot) + { - boolean passed = true; + boolean passed = true; - // Check the expected content - if (expectedContent != null) { - if (!expectedContent.equals(textBox.getString())) { - passed = false; - print(testCaseName + " test " - + " failed: content: " + textBox.getString() - + ", expected: " + expectedContent); - } - } + // Check the expected content + if(expectedContent != null) + { + if(!expectedContent.equals(textBox.getString())) + { + passed = false; + print(testCaseName + " test " + + " failed: content: " + textBox.getString() + + ", expected: " + expectedContent); + } + } - // Take the screenshot and compare it with the previous one - if (takeScreenshot) { - if (!takeScreenshot(testCaseName + ".gif")) { - passed = false; - print(testCaseName + " test " - + " failed: screenshot does not match"); + // Take the screenshot and compare it with the previous one + if(takeScreenshot) + { + if(!takeScreenshot(testCaseName + ".gif")) + { + passed = false; + print(testCaseName + " test " + + " failed: screenshot does not match"); - print("If failure is caused by different " - + "special characters which are show in the cell at " - + "the top of the Edit Menu, please IGNORE the result" - + " and treat the test as PASSED!"); - } - } + print("If failure is caused by different " + + "special characters which are show in the cell at " + + "the top of the Edit Menu, please IGNORE the result" + + " and treat the test as PASSED!"); + } + } - if (passed) { - print(testCaseName + " test succeeded: " + textBox.getString()); - } - return passed; - } + if(passed) + { + print(testCaseName + " test succeeded: " + textBox.getString()); + } + return passed; + } /** - * Private method for changing the input language - * - * @param positionInEditOptions - * Position of "Input language" menu item - * @param positionInLanguageList - * Position of the desired language - */ + * Private method for changing the input language + * + * @param positionInEditOptions + * Position of "Input language" menu item + * @param positionInLanguageList + * Position of the desired language + */ private void changeInputLanguage(int positionInEditOptions, - int positionInLanguageList) { + int positionInLanguageList) + { // Create a temporary TextBox in order to be able to set // the global input language TextBox other = new TextBox("Input language setting", - "Temporary text box", normalSize, TextField.ANY); + "Temporary text box", normalSize, TextField.ANY); // Display the text box setCurrent(other); @@ -1574,7 +1793,8 @@ // Open EditOptions menu and select Input language menu item key(Key.Edit); - for (int i = 0; i < positionInEditOptions; i++) { + for(int i = 0; i < positionInEditOptions; i++) + { key(Key.DownArrow); } block(KEYEVENT_DELAY); @@ -1582,7 +1802,8 @@ key(Key.Select); // Select the desired input language in the language list - for (int i = 1; i < positionInLanguageList; i++) { + for(int i = 1; i < positionInLanguageList; i++) + { key(Key.DownArrow); } block(KEYEVENT_DELAY); diff -r 2a9601315dfc -r 98ccebc37403 javauis/m2g_akn/inc/CM2GRenderContext.h --- a/javauis/m2g_akn/inc/CM2GRenderContext.h Mon May 03 12:27:20 2010 +0300 +++ b/javauis/m2g_akn/inc/CM2GRenderContext.h Fri May 14 15:47:24 2010 +0300 @@ -172,7 +172,7 @@ const TRect& aViewbox, const TPoint& aAnchor); - void CM2GRenderContext::RenderESWTL( + void RenderESWTL( TM2GSvgDocumentHandle& aSvgDocHandle, TReal32 aCurrentTime, const TRect& aViewbox, diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_akn/baseline/src/cmmacamerawindow.cpp --- a/javauis/mmapi_akn/baseline/src/cmmacamerawindow.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/mmapi_akn/baseline/src/cmmacamerawindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -206,7 +206,6 @@ // Stop and start ViewFinder to update position ResetViewFinder(); } - } @@ -311,8 +310,6 @@ *this, CMMACameraWindow::EResetViewFinder); } } - - } @@ -616,10 +613,6 @@ { iUICamera->StopViewFinder(); } - if (iDirectAccess->IsActive()) - { - iDirectAccess->Cancel(); - } iViewFinderVisible = EFalse; } @@ -717,11 +710,12 @@ } else { - DEBUG_INT( - "MMA::CMMACameraWindow::StartViewFinder() - \ -StartViewFinderDirectL error=%d", vfError); + DEBUG_INT("MMA::CMMACameraWindow::StartViewFinder() - \ + StartViewFinderDirectL error=%d", vfError); - TRAP_IGNORE(DrawViewFinderErrorL(vfError, drawRect)); + TRAPD(error, DrawViewFinderErrorL(vfError, drawRect)); + DEBUG_INT("MMA::CMMACameraWindow::StartViewFinder, \ + DrawViewFinderErrorL error = %d", error); } DEBUG(" > StartViewFinder"); @@ -738,8 +732,18 @@ const TInt /*aError*/, const TRect& aDrawRect) { + if (!iDirectAccess) + { + if (!iWs || !iScreenDevice || !iWindow) return; - ASSERT(iDirectAccess); + DEBUG("MMA::CMMACameraWindow::DrawViewFinderErrorL - \ + Instantiating CDirectScreenAccess"); + iDirectAccess = CDirectScreenAccess::NewL(*iWs, + *iScreenDevice, + *iWindow, + *this); + } + TInt dcError = KErrNone; if (!iDirectAccess->IsActive()) { @@ -831,9 +835,12 @@ delete iUICamera; iUICamera = NULL; iCameraPowerOn = EFalse; - iDirectAccess->Cancel(); - delete iDirectAccess; - iDirectAccess = NULL; + if (iDirectAccess) + { + iDirectAccess->Cancel(); + delete iDirectAccess; + iDirectAccess = NULL; + } delete iErrorIconBitmap; iErrorIconBitmap = NULL; delete iErrorIconMaskBitmap; @@ -882,15 +889,6 @@ CWsScreenDevice &aScreenDevice, RWindowBase &aWindow) { - TRAPD(error, iDirectAccess = CDirectScreenAccess::NewL(aWs, - aScreenDevice, - aWindow, - *this)); - DEBUG_INT("MMA::CMMACameraWindow::MdcDSAResourcesCallback, error = %d", error); - if (KErrNone != error) - { - return; - } this->UIStartViewFinder(aWs, aScreenDevice, aWindow); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_akn/baseline/src/cmmadisplay.cpp --- a/javauis/mmapi_akn/baseline/src/cmmadisplay.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/mmapi_akn/baseline/src/cmmadisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -151,7 +151,7 @@ // If visible then set a new clip rect if (iVisible && iContainerVisible) { - iClipRect.SetRect(TPoint(0,0),iWindow->WindowRect().Size()); + iClipRect = iWindow->DrawRect(); if (!iClipRect.IsEmpty()) { @@ -205,7 +205,7 @@ // If visible then set a new clip rect if (iVisible) { - iClipRect.SetRect(TPoint(0,0),iWindow->WindowRect().Size()); + iClipRect = iWindow->DrawRect(); if (!iClipRect.IsEmpty()) { diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationframepositioningcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationframepositioningcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements FramePositioningControl for animation +* +*/ + + +#ifndef CMMAANIMATIONFRAMEPOSITIONINGCONTROL_H +#define CMMAANIMATIONFRAMEPOSITIONINGCONTROL_H + +// INTERNAL INCLUDES +#include "cmmaanimationplayer.h" +#include "cmmaframepositioningcontrol.h" // base class + + +// CONSTANTS + +// FORWARD DECLARATIONS +class MIHLImageViewer; + +// CLASS DECLARATION +/** +* This class implements FramePositioningControl for video player +*/ +NONSHARABLE_CLASS(CMMAAnimationFramePositioningControl) : + public CMMAFramePositioningControl +{ +public: + static CMMAAnimationFramePositioningControl* NewL(CMMAAnimationPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAAnimationFramePositioningControl(); + +protected: + /** + * Constructor. + */ + CMMAAnimationFramePositioningControl(CMMAAnimationPlayer* aPlayer); + + void ConstructL(CMMAAnimationPlayer* aPlayer); + +public: // From CMMAFramePositioningControl + TInt SeekL(TInt aFrameNumber); + TInt SkipL(TInt aFramesToSkip); + void MapFrameToTimeL(TInt aFrameNumber, TInt64* aMediaTime); + TInt MapTimeToFrameL(TInt64* aMediaTime); + +private: // New methods + TInt FindFrame(MIHLImageViewer* aViewer, TInt aFrameNumber); + +private: // Data + CMMAAnimationPlayer* iPlayer; + +}; + + +#endif // CMMAANIMATIONFRAMEPOSITIONINGCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,230 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing animated images. +* +*/ + + +#ifndef CMMAANIMATIONPLAYER_H +#define CMMAANIMATIONPLAYER_H + +// INCLUDES +#include +#include "cmmaplayer.h" +#include "mmmaguiplayer.h" +#include "mmmasnapshot.h" +#include "rmmatempfile.h" +#include "MIHLViewerObserver.h" +#include "MIHLImageViewer.h" + +// FORWARD DECLARATIONS +class MMAFunctionServer; +class CMMAAnimationWindow; +class MIHLFileImage; +class MIHLBitmap; +class CFbsBitmap; + +// CONSTANTS +_LIT(KMMAVideoPlayer, "VideoPlayer"); + +NONSHARABLE_CLASS(MMMAAnimationObserver) +{ +public: // new methods + /** + * Listener for animation advancing + * @param aFrame current frame + * @param aMediaTime current media time + */ + virtual void AnimationAdvancedL(TInt aFrame, TInt64 aMediaTime) = 0; +}; + +// CLASS DECLARATION +/** +* This class is used for playing animated images. +* +*/ +NONSHARABLE_CLASS(CMMAAnimationPlayer): public CMMAPlayer, + public MMMAGuiPlayer, + public MMMASnapshot, + public MIHLViewerObserver +{ +public: // Construction + static CMMAAnimationPlayer* NewLC(); + static CMMAAnimationPlayer* NewLC(const TDesC& aFileName); + + // Destructor + ~CMMAAnimationPlayer(); + +protected: + // C++ constructor + CMMAAnimationPlayer(); + void ConstructL(); + +public: // from CMMAPlayer + void SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster); + void RealizeL(); + void PrefetchL(); + void StartL(); + void StopL(TBool aPostEvent); + void DeallocateL(); + void GetDuration(TInt64* aDuration); + const TDesC& Type(); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + +public: // from CMMAPlayer/MMMASourceStreamListener + void ReadCompletedL(TInt aStatus, const TDesC8& aData); + +public: // new methods + void PrefetchFileL(); + void PrefetchDataL(const TDesC8& aData); + + /** + * Check whether this player is playing from a file locator + * @return ETrue if is a file player, EFalse otherwise + */ + TBool IsFilePlayer(); + + // Finds current frame for given media time + TInt FindFrame(TInt64 aTime); + + // Calculates media time for specified frame + TInt64 MediaTimeForFrame(TInt aFrameIndex); + + // Frame duration of specified frame + TTimeIntervalMicroSeconds32 FrameDuration(TInt aFrameIndex); + + MIHLImageViewer* Viewer(); + + // Setter for frame listener, used for stop time control + void SetAnimationObserver(MMMAAnimationObserver* aAnimationObserver); + + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + TInt RateL(); + +private: // new methods + void PrepareViewerL(); + void ProcessCurrentFrameL(); + +public: // From MMMAGuiPlayer + void SetDisplayL(MMMADisplay* aDisplay); + TSize SourceSize(); + void NotifyWithStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData); + + MMMASnapshot* SnapshoterL(); + +public: // From MMMASnapshot + MMMASnapshot::TEncoding TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings); + CFbsBitmap* SnapshotBitmap(); + HBufC8* SnapshotEncoded(); + +public: // From MIHLViewerObserver + virtual void ViewerBitmapChangedL(); + virtual void ViewerError(TInt aError); + + private: // Data + + /** + * Display to draw animation. + */ + MMMADisplay* iDisplay; + + /** + * Window to draw animation. + */ + CMMAAnimationWindow* iWindow; + + /** + * Dimensions of animation. + */ + TSize iSourceSize; + + /** + * Animated image to play. Owned. + */ + MIHLFileImage* iImage; + + /** + * Destination bitmap for animation. Owned. + */ + MIHLBitmap* iBitmap; + + /** + * Animation viewer. Owned. + */ + MIHLImageViewer* iViewer; + + /** + * Bitmap for snapshot. Ownership is transferred for + * snapshot requester, but owned if not null. + */ + CFbsBitmap* iSnapshotBitmap; + + /** + * File system session for IHL interfacing + */ + RFs iFSession; + + /** + * Animation frame count. Held locally for optimization. + */ + TInt iFrameCount; + + /** + * Possible file name, owned + */ + HBufC* iFileName; + + /** + * Current Media Time + */ + TInt64 iMediaTime; + + /** + * Animation listener + */ + MMMAAnimationObserver* iAnimationObserver; + + /** + * Current rate + */ + TInt iCurrentRate; + + /** + * Hold the information whether playback should be started + * from beginning on next start or from current position + */ + TBool iEndReached; + + /** + * EndOfMedia will be delivered when next frame arrives if + * iSendEndOfMediaOnNextFrame is true + */ + TBool iSendEndOfMediaOnNextFrame; +}; + +#endif // CMMAANIMATIONPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,77 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating animation player +* +*/ + + +#ifndef CMMAANIMATIONPLAYERFACTORY_H +#define CMMAANIMATIONPLAYERFACTORY_H + +// INCLUDES +#include "mmmaplayerfactory.h" + +// CONSTANTS + +// FORWARD DECLARATIONS +class CMMAAnimationPlayer; + +// CLASS DECLARATION +/** +* This class is used for creating animation player. +* +*/ +NONSHARABLE_CLASS(CMMAAnimationPlayerFactory): public MMMAPlayerFactory +{ +public: // Constructor and destructor + static CMMAAnimationPlayerFactory* NewLC(); + ~CMMAAnimationPlayerFactory(); + +private: // Constructor + CMMAAnimationPlayerFactory(); + +public: // From MMMAPlayerFactory + + // Creates new player according to a content type. + virtual CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + // Creates new player according to a locator + virtual CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + // Creates new player according to a header data + virtual CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + // Gets player's supported content types. + virtual void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + // Gets player's supported protocols for the content type. + virtual void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +private: + // Create instance of animation player with sufficient controls + CMMAAnimationPlayer* CreateAnimationPlayerL(); + + // Create instance of animation player with sufficient controls, with specified file + CMMAAnimationPlayer* CreateAnimationPlayerL(const TDesC& aFileName); + + // Add animation controls to player + void AddControlsL(CMMAAnimationPlayer* aPlayer); + +}; + +#endif // CMMAANIMATIONPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationratecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationratecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements AnimationRateControl functionality. +* +*/ + + +#ifndef CMMAANIMATIONRATECONTROL_H +#define CMMAANIMATIONRATECONTROL_H + +// EXTERNAL INCLUDES + +// INTERNAL INCLUDES +#include "cmmaratecontrol.h" // base class + +// CONSTANTS + +class CMMAAnimationPlayer; + +// CLASS DECLARATION +/** +* This class implements AnimationRateControl interface. +* +* +*/ +NONSHARABLE_CLASS(CMMAAnimationRateControl): public CMMARateControl +{ +public: + /** + * Creates new CMMAAnimationRateControl. + * + * @param aPlayer Player that plays the content. + */ + static CMMAAnimationRateControl* NewL(CMMAAnimationPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAAnimationRateControl(); +protected: + /** + * Constructor. + * @param aPlayer Player that plays the content. + */ + CMMAAnimationRateControl(CMMAAnimationPlayer* aPlayer); + + /** + * Initializes this control. + */ + void ConstructL(); + +public: // From CMMARateControl + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + TInt RateL(); + +private: // Data + /** + * Used to control animation. + */ + CMMAAnimationPlayer* iPlayer; + +}; + + +#endif // CMMAANIMATIONRATECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationstoptimecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationstoptimecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling for animation player +* +*/ + + +#ifndef CMMAANIMATIONSTOPTIMECONTROL_H +#define CMMAANIMATIONSTOPTIMECONTROL_H + +// INCLUDES +#include "cmmaanimationplayer.h" +#include "cmmastoptimecontrol.h" + +// CLASS DECLARATION +/** +* This class is used for stoptime controlling for animation +* +* +*/ + +NONSHARABLE_CLASS(CMMAAnimationStopTimeControl): public CMMAStopTimeControl, + public MMMAAnimationObserver +{ +public: + static CMMAAnimationStopTimeControl* NewL(CMMAAnimationPlayer* aPlayer); + ~CMMAAnimationStopTimeControl(); + +protected: + CMMAAnimationStopTimeControl(CMMAAnimationPlayer* aPlayer); + +public: // from CMMAStopTimeControl + void SetStopTimeL(const TInt64& aTime); + +public: // from MMMAAnimationObserver + void AnimationAdvancedL(TInt aFrame, TInt64 aMediaTime); +}; + +#endif // CMMAANIMATIONSTOPTIMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationwindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/inc/cmmaanimationwindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This abstract class implements MMMADisplayWindow functionality +* in CFbsBitmap based displays. +* +*/ + + +#ifndef CMMAANIMATIONWINDOW_H +#define CMMAANIMATIONWINDOW_H + +// INCLUDES +#include +//#include "MMMADisplayWindow.h" +#include "cmmabitmapwindow.h" +#include "mmafunctionserver.h" + +// CONSTANTS + +// FORWARD DECLARATIONS +//class CFbsBitmap; + + +// CLASS DECLARATION +/** +* This abstract class implements MMMADisplayWindow functionality in +* CFbsBitmap based displays. +* +* +*/ + + +NONSHARABLE_CLASS(CMMAAnimationWindow): public CMMABitmapWindow +{ +public: // Constructors and destructors + ~CMMAAnimationWindow(); // Destructor () + + static CMMAAnimationWindow* NewL(MMAFunctionServer* aEventSource); + +protected: // Constructors and destructors + // Default constructor, protected to allow derivation + CMMAAnimationWindow(MMAFunctionServer* aEventSource); + +public: // new methods + /** + * Setter for viewer, used for changing the size + */ + void SetViewer(MIHLImageViewer* aViewer); + +public: // Methods derived from MMMADisplayWindow + void SetDestinationBitmapL(CFbsBitmap* aBitmap); + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDrawRect(const TRect& aRect); + void SetDrawRectThread(const TRect& aRect); + + /*private: + static void StaticSetDrawRect( + CMMAAnimationWindow* aWindow, + TRect aRect, + MMAFunctionServer* aEventSource );*/ + +protected: // Data + /** + * not owned, used for switching from UI thread to MMA thread + */ + MMAFunctionServer* iEventSource; + + /** + * Pointer to bitmap context, used for BitBlt instead of + * slow DrawRect + */ + CBitmapContext* iBitContext; + + /** + * Viewer used for setting new size, not owned + */ + MIHLImageViewer* iViewer; +}; + +#endif // CMMAANIMATIONWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationframepositioningcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationframepositioningcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,126 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements FramePositioningControl for animation +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "MIHLImageViewer.h" +#include "cmmaanimationframepositioningcontrol.h" + +CMMAAnimationFramePositioningControl* +CMMAAnimationFramePositioningControl::NewL(CMMAAnimationPlayer* aPlayer) +{ + CMMAAnimationFramePositioningControl* self = + new(ELeave) CMMAAnimationFramePositioningControl(aPlayer); + return self; +} + +CMMAAnimationFramePositioningControl:: +CMMAAnimationFramePositioningControl(CMMAAnimationPlayer* aPlayer) + : CMMAFramePositioningControl(aPlayer), iPlayer(aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationFramePositioningControl::CMMAAnimationFramePositioningControl"); +} + +CMMAAnimationFramePositioningControl::~CMMAAnimationFramePositioningControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationFramePositioningControl::~CMMAAnimationFramePositioningControl"); +} + +TInt CMMAAnimationFramePositioningControl::SeekL(TInt aFrameNumber) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAnimationFramePositioningControl::SeekL"); + MIHLImageViewer* viewer = iPlayer->Viewer(); + if (!viewer) + { + return KErrNotFound; + } + TInt frameNumber = FindFrame(viewer, aFrameNumber); + TInt64 mediaTime = iPlayer->MediaTimeForFrame(frameNumber); + // adjust wanted media time to get right frame (equal value returns one too small) + mediaTime++; + iPlayer->SetMediaTimeL(&mediaTime); + frameNumber = viewer->AnimationFrame(); + return frameNumber; +} + +TInt CMMAAnimationFramePositioningControl::SkipL(TInt aFramesToSkip) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAnimationFramePositioningControl::SkipL"); + MIHLImageViewer* viewer = iPlayer->Viewer(); + if (!viewer) + { + return KErrNotFound; + } + + TInt frameNumber = viewer->AnimationFrame(); + + SeekL(frameNumber + aFramesToSkip); + + // Calculate number of frames skipped + return viewer->AnimationFrame() - frameNumber; +} + +void CMMAAnimationFramePositioningControl::MapFrameToTimeL( + TInt aFrameNumber, + TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAnimationFramePositioningControl::MapFrameToTimeL"); + MIHLImageViewer* viewer = iPlayer->Viewer(); + if (!viewer || (aFrameNumber < 0) || + (aFrameNumber >= viewer->AnimationFrameCount())) + { + *aMediaTime = KErrNotFound; + } + else + { + *aMediaTime = iPlayer->MediaTimeForFrame(aFrameNumber); + } +} +TInt CMMAAnimationFramePositioningControl::MapTimeToFrameL( + TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAnimationFramePositioningControl::MapTimeToFrameL"); + MIHLImageViewer* viewer = iPlayer->Viewer(); + TInt64 duration; + iPlayer->GetDuration(&duration); + if (!viewer || (*aMediaTime < 0) || + (duration == KErrNotFound)) + { + return KErrNotFound; + } + return iPlayer->FindFrame(*aMediaTime); +} + +TInt CMMAAnimationFramePositioningControl::FindFrame(MIHLImageViewer* aViewer, TInt aFrameNumber) +{ + TInt frame = 0; + TInt count = aViewer->AnimationFrameCount(); + if (aFrameNumber >= count) + { + frame = count - 1; + } + else if (aFrameNumber > 0) + { + frame = aFrameNumber; + } + return frame; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,621 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing animated images. +* +*/ + + +// INCLUDE FILES +#include + +// For Image Handling Library (IHL) +#include "IHLImageFactory.h" +#include "MIHLFileImage.h" +#include "IHLViewerFactory.h" +#include "MIHLImageViewer.h" +#include "MIHLBitmap.h" +#include "IHLBitmapUtil.h" + +// MMAPI includes +#include "mmmadisplay.h" + +// Class header +#include "cmmaanimationplayer.h" +#include "cmmaanimationwindow.h" + +namespace +{ +const TInt64 KMMATimeUnknown = -1; +_LIT(KMMAAnimationContentType, "image/gif"); + +// Approximated minimum showing time of each frame is 0.12s +// this value basically depends on how fast device can load frames +// it is not quaranteed anyway that the media time is equal to +// clock time, so this needed to be only somewhat close + +_LIT(KVideoControlName, "VideoControl"); +} + +CMMAAnimationPlayer* CMMAAnimationPlayer::NewLC() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::NewLC"); + CMMAAnimationPlayer* self = new(ELeave) CMMAAnimationPlayer(); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAAnimationPlayer* CMMAAnimationPlayer::NewLC(const TDesC& aFileName) +{ + CMMAAnimationPlayer* self = NewLC(); + self->iFileName = aFileName.AllocL(); + return self; +} + +CMMAAnimationPlayer::~CMMAAnimationPlayer() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::~CMMAAnimationPlayer +"); + if (iViewer && iViewer->IsPlaying()) + { + iViewer->Stop(); + } + delete iWindow; + delete iSnapshotBitmap; + delete iViewer; + // viewer has reference to iImage, + // thus deletion order is important. + delete iBitmap; + delete iImage; + + delete iFileName; + + iFSession.Close(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::~CMMAAnimationPlayer -"); +} + +CMMAAnimationPlayer::CMMAAnimationPlayer() + : iFrameCount(0), iMediaTime(KMMATimeUnknown), iEndReached(EFalse), + iSendEndOfMediaOnNextFrame(EFalse) +{ +} + +void CMMAAnimationPlayer::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::ConstructL +"); + CMMAPlayer::ConstructL(); + HBufC* contentType = KMMAAnimationContentType().AllocL(); + SetContentType(contentType); + + // Connect to file session, needed also when playing from data + User::LeaveIfError(iFSession.Connect()); + + // File session must be share protected for IHL + User::LeaveIfError(iFSession.ShareProtected()); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::ConstructL -"); +} + +void CMMAAnimationPlayer::SetPlayerListenerObjectL( + jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster) +{ + CMMAPlayer::SetPlayerListenerObjectL(aListenerObject, + aJni, + aEventPoster); + + // this method must be called only ones + __ASSERT_DEBUG(!iWindow, User::Invariant()); + + // create window for animationplayer + // event poster is always MMAFunctionServer type. + iWindow = CMMAAnimationWindow::NewL( + static_cast< MMAFunctionServer* >(iEventPoster)); +} + +void CMMAAnimationPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::RealizeL"); + // For file locator file must be prefetched here because + // FramePositioningControl must know duration of media + // in realized state + if (iFileName) + { + TRAPD(err, PrefetchFileL()); + if (err != KErrNone) + { + User::Leave(err); + } + } + CMMAPlayer::RealizeL(); +} + +void CMMAAnimationPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::PrefetchL +"); + __ASSERT_DEBUG((iSourceStreams.Count() > 0) || iFileName, User::Invariant()); + + if (iFileName) + { + // file data is already fetched in when realizing + + // If initDisplayMode was called before prefetch, + // then the display must notified about source size. + if (iDisplay) + { + iDisplay->SourceSizeChanged(iSourceSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); + } + + // ChangeState(EPrefetched); + // PostActionCompleted(KErrNone); + // we can go to prefetched state immediately + PostActionCompletedFile(); + ChangeState(EPrefetched); + } + else + { + // Using TDes -- load the whole animation + iSourceStreams[ 0 ]->ReadAllL(); + } + + // CMMASourceStream will notify with ReadCompleted + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::PrefetchL -"); +} + +void CMMAAnimationPlayer::StartL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::StartL +"); + + // If end of media has been reached, then + // start from beginning + if (iEndReached) + { + iEndReached = EFalse; + iViewer->SetAnimationFrame(0); + iMediaTime = 0; + } + PostLongEvent(CMMAPlayerEvent::EStarted, iMediaTime); + + // process current frame + ProcessCurrentFrameL(); + + // progress to next frame (start playback) only if rate is not zero + if (iCurrentRate > 0) + { + iViewer->Play(); + } + ChangeState(EStarted); + PostActionCompletedStart(); + // PostActionCompleted(KErrNone); // java start return + + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::StartL -"); +} + +void CMMAAnimationPlayer::ProcessCurrentFrameL() +{ + if (iSendEndOfMediaOnNextFrame) + { + iSendEndOfMediaOnNextFrame = EFalse; + // we are reached the end + if (!iRepeatForever) + { + iRepeatCount++; + if (iRepeatCount >= iRepeatNumberOfTimes) + { + LOG( EJavaMMAPI, EInfo, "CMMAAnimationPlayer:ProcessCurrentFrameL: Reached repeat count, Stopping"); + // end looping, do not send stopped event + StopL(EFalse); + iViewer->SetAnimationFrame(iFrameCount - 1); + SetLoopCount(iRepeatNumberOfTimes); // reset loop count + + // Signal that end of media has been reached so on next + // start playback will be started from beginning. This is needed + // because if user sets media time to end of media, then start + // should not start from beginning but just deliver end of media. + // After that, the next start should start from beginning. + iEndReached = ETrue; + } + } + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, iMediaTime); + LOG( EJavaMMAPI, EInfo, "CMMAAnimationPlayer:ProcessCurrentFrameL: sent END_OF_MEDIA"); + + // Prevents this frame from being viewed if playback has terminated + // (e.g. not looping) + if (iEndReached) + { + return; + } + } + + // draw current frame to display if we have it + if (iDisplay) + { + const CFbsBitmap& bitmap = iBitmap->Bitmap(); + iDisplay->DrawFrameL(&bitmap); + } + + TInt currentFrame = iViewer->AnimationFrame(); + if (currentFrame == 0) + { + LOG( EJavaMMAPI, EInfo, "CMMAAnimationPlayer:ProcessCurrentFrameL: Reset mediatime"); + // reset media time when looping + iMediaTime = 0; + } + iMediaTime += FrameDuration(currentFrame).Int(); + + // Media time has gone over duration if user has + // set media time explicitely to duration. + if (iMediaTime > iDuration) + { + iMediaTime = iDuration; + } + + if (currentFrame == (iFrameCount - 1)) + { + // End has been reached, so EndOfMedia is sent when + // duration of last frame has passed + iSendEndOfMediaOnNextFrame = ETrue; + } + + // inform observer + if (iAnimationObserver) + { + iAnimationObserver->AnimationAdvancedL(iViewer->AnimationFrame(), iMediaTime); + } +} + +void CMMAAnimationPlayer::StopL(TBool aPostEvent) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::StopL +"); + iViewer->Stop(); + // adjust mediatime + if (aPostEvent) + { + PostLongEvent(CMMAPlayerEvent::EStopped, iMediaTime); + } + ChangeState(EPrefetched); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::StopL -"); +} + +void CMMAAnimationPlayer::DeallocateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::DeallocateL +"); + // If player is in starte state when deallocate is called, + // player is stopped from java side -> state is changed to + // prefetched. + if (iViewer) + { + if (iViewer->IsPlaying()) + iViewer->Stop(); + + delete iViewer; + iViewer = NULL; + } + + if (iState == EPrefetched) + { + ResetSourceStreams(); + iEndReached = EFalse; + iSendEndOfMediaOnNextFrame = EFalse; + ChangeState(ERealized); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::DeallocateL -"); +} + +void CMMAAnimationPlayer::GetDuration(TInt64* aDuration) +{ + *aDuration = iDuration; +} + +TInt CMMAAnimationPlayer::FindFrame(TInt64 aTime) +{ + __ASSERT_DEBUG(iImage, User::Invariant()); + + // if we are out of bounds + if (aTime > iDuration) + { + return KErrNotFound; + } + + TInt64 time = 0; + TInt fIndex = 0; + while ((time < aTime) && (fIndex < iFrameCount)) + { + time += FrameDuration(fIndex++).Int(); + } + + // adjust to previous frame + if (fIndex > 0) + { + fIndex--; + } + + return fIndex; +} + +TInt64 CMMAAnimationPlayer::MediaTimeForFrame(TInt aFrameIndex) +{ + __ASSERT_DEBUG((aFrameIndex <= iFrameCount) && (aFrameIndex >= 0), + User::Invariant()); + + TInt64 time = 0; + for (TInt fIndex = 0; fIndex < aFrameIndex; fIndex++) + { + time += FrameDuration(fIndex).Int(); + } + return time; +} + +TTimeIntervalMicroSeconds32 CMMAAnimationPlayer::FrameDuration(TInt aFrameIndex) +{ + __ASSERT_DEBUG(iImage, User::Invariant()); + TTimeIntervalMicroSeconds32 fDur = iImage->AnimationFrameDelay(aFrameIndex); + const TTimeIntervalMicroSeconds32 KMMAMinimumFrameTime = 120000; + + if (fDur < KMMAMinimumFrameTime) + { + fDur = KMMAMinimumFrameTime; + } + return fDur; +} + +void CMMAAnimationPlayer::SetMediaTimeL(TInt64* aTime) +{ + if (!iImage && !iViewer) + { + // not yet prefetched + *aTime = KErrNotSupported; + } + else + { + // Media time of last frame is not the same as duration of + // media, so if media time of duration is requested, then it must + // be given out altough media time of last frame is lower than that. + if (*aTime >= iDuration) + { + User::LeaveIfError(iViewer->SetAnimationFrame(iFrameCount - 1)); + iMediaTime = iDuration; + } + else + { + TInt frame = FindFrame(*aTime); + User::LeaveIfError(iViewer->SetAnimationFrame(frame)); + iMediaTime = MediaTimeForFrame(frame); + } + *aTime = iMediaTime; + iEndReached = EFalse; + iSendEndOfMediaOnNextFrame = EFalse; + } + +} + +void CMMAAnimationPlayer::GetMediaTime(TInt64* aMediaTime) +{ + *aMediaTime = iMediaTime; +} + +const TDesC& CMMAAnimationPlayer::Type() +{ + return KMMAVideoPlayer; +} + +void CMMAAnimationPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + TRAPD(err, PrefetchDataL(aData)); + if (err == KErrNone) + { + ChangeState(EPrefetched); + } + PostActionCompleted(err); + } +} + +void CMMAAnimationPlayer::PrefetchFileL() +{ + iImage = IHLImageFactory::OpenFileImageL(iFSession, *iFileName); + PrepareViewerL(); +} + +void CMMAAnimationPlayer::PrefetchDataL(const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAAnimationPlayer::PrefetchDataL aData size %d", + aData.Size()); + + // Create source image from data + iImage = IHLImageFactory::OpenBufferedFileImageL(iFSession, aData); + PrepareViewerL(); +} + +TBool CMMAAnimationPlayer::IsFilePlayer() +{ + if (iFileName != NULL) + { + return ETrue; + } + return EFalse; +} + +void CMMAAnimationPlayer::PrepareViewerL() +{ + // Non-animated gifs are not supported + if (!(iImage->IsAnimation())) + { + User::Leave(KErrNotSupported); + } + + // Store image dimensions + iSourceSize = iImage->Size(); + + // Create destination bitmap + iBitmap = IHLBitmap::CreateL(); + User::LeaveIfError(iBitmap->Create(iSourceSize, iImage->DisplayMode())); + + // Create image viewer + iViewer = IHLViewerFactory::CreateImageViewerL( + iSourceSize, + *iImage, // source + *iBitmap, // destination + *this); // reference to MIHLViewerObserver + + // Set viewer for window + iWindow->SetViewer(iViewer); + + // Store animation frame count locally + iFrameCount = iViewer->AnimationFrameCount(); + + // calculate duration + iDuration = MediaTimeForFrame(iFrameCount); + + // set media time to begin + iMediaTime = 0; + + // If init has been already done + if (iDisplay) + { + iDisplay->SourceSizeChanged(iSourceSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); + } +} + +MIHLImageViewer* CMMAAnimationPlayer::Viewer() +{ + return iViewer; +} + +void CMMAAnimationPlayer::SetAnimationObserver(MMMAAnimationObserver* aAnimationObserver) +{ + iAnimationObserver = aAnimationObserver; +} + +TInt CMMAAnimationPlayer::SetRateL(TInt aRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationPlayer::SetRateL"); + if ((iState == EStarted) && (iCurrentRate != aRate)) + { + if (aRate <= 0) + { + iViewer->Stop(); + } + else + { + iViewer->Play(); + } + } + iCurrentRate = aRate; + return iCurrentRate; +} + +TInt CMMAAnimationPlayer::RateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationPlayer::RateL"); + return iCurrentRate; +} + +void CMMAAnimationPlayer::SetDisplayL(MMMADisplay* aDisplay) +{ + // now it is ready to draw + iDisplay = aDisplay; + iDisplay->SetWindowL(iWindow); + + // if state < prefeteched then we dont know actual source size yet + // and it will be set after prefetch + if (iState >= EPrefetched || + (iFileName && iState == ERealized)) + { + iDisplay->SourceSizeChanged(iSourceSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); + } +} + +TSize CMMAAnimationPlayer::SourceSize() +{ + return iSourceSize; +} + +void CMMAAnimationPlayer::NotifyWithStringEvent( + CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) +{ + PostStringEvent(aEventType, aStringEventData); +} + +MMMASnapshot* CMMAAnimationPlayer::SnapshoterL() +{ + return this; +} + +MMMASnapshot::TEncoding CMMAAnimationPlayer::TakeSnapshotL(TRequestStatus* aStatus, + const TSize& /*aSize*/, + const CMMAImageSettings& /*aSettings*/) +{ + if (iBitmap) + { + // Bitmap has to be copied to get ownership of the bitmap instance. + iSnapshotBitmap = IHLBitmapUtil::CopyBitmapL(iBitmap->Bitmap()); + } + else + { + // When content comes from a stream, iBitmap is not available + // until prefetched state is entered. In this case an empty bitmap + // is returned instead. + iSnapshotBitmap = new(ELeave) CFbsBitmap(); + } + // notify the caller, error code or KErrNone + User::RequestComplete(aStatus, KErrNone); + + // Return raw bitmap encoding and thus SnapshotEncoded() should not + // get called later on. + return EBitmap; +} + +CFbsBitmap* CMMAAnimationPlayer::SnapshotBitmap() +{ + CFbsBitmap* bitmap = iSnapshotBitmap; + // ownership is transferred to caller + iSnapshotBitmap = NULL; + return bitmap; +} + +HBufC8* CMMAAnimationPlayer::SnapshotEncoded() +{ + // This method should never be called. + // Asserted in debug build to be sure. + __ASSERT_DEBUG(EFalse, User::Invariant()); + + return NULL; +} + +void CMMAAnimationPlayer::ViewerBitmapChangedL() +{ + if (iState == EStarted) + { + ProcessCurrentFrameL(); + } +} + +void CMMAAnimationPlayer::ViewerError(TInt /*aError*/) +{ + // Not implemented currently because + // not implemented by IHL either. +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,196 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating animation player. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideocontrol.h" +#include "cmmaanimationratecontrol.h" +#include "cmmaanimationstoptimecontrol.h" +#include "cmmaanimationframepositioningcontrol.h" +#include "cmmaanimationplayer.h" +#include "cmmaanimationplayerfactory.h" + +// Animation type info +_LIT(KMMAAnimationMimeTypeGIF, "image/gif"); +_LIT(KMMAAnimationSuffixGIF, "gif"); + +// header data and length +_LIT8(KMMAAnimationGIFVersion, "GIF89a"); +const TUint8 KMMAGifVersionLength = 6; + +CMMAAnimationPlayerFactory* CMMAAnimationPlayerFactory::NewLC() +{ + CMMAAnimationPlayerFactory* pFactory = + new(ELeave) CMMAAnimationPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAAnimationPlayerFactory::CMMAAnimationPlayerFactory() +{ +} + + +CMMAAnimationPlayerFactory::~CMMAAnimationPlayerFactory() +{ +} + +// Creates new player according to a content type. +CMMAPlayer* CMMAAnimationPlayerFactory::CreatePlayerL( + const TDesC& aContentType) +{ + CMMAPlayer* player = NULL; + if (aContentType == KMMAAnimationMimeTypeGIF) + { + player = CreateAnimationPlayerL(); + } + return player; +} + +// Creates new player according to a locator +CMMAPlayer* CMMAAnimationPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& /*aParameters*/) +{ + CMMAPlayer* player = NULL; + if (aProtocol == KMMAFileProtocol) + { + // filename ends to gif suffix + if (aMiddlePart.Right(KMMAAnimationSuffixGIF().Length()) == + KMMAAnimationSuffixGIF()) + { + player = CreateAnimationPlayerL(aMiddlePart); + } + else + { + // try to recognize from headerdata + RFs fs; + CleanupClose< RFs >::PushL(fs); + User::LeaveIfError(fs.Connect()); + + RFile file; + CleanupClose< RFile >::PushL(file); + + User::LeaveIfError(file.Open(fs, aMiddlePart, EFileRead)); + + TBuf8< KMMAGifVersionLength > header; + User::LeaveIfError(file.Read(header)); + + CleanupStack::PopAndDestroy(2); // fs, file + + if (header == KMMAAnimationGIFVersion()) + { + player = CreateAnimationPlayerL(aMiddlePart); + } + } + } + + return (CMMAPlayer*) player; +} + +// Creates new player according to a header data +CMMAPlayer* CMMAAnimationPlayerFactory::CreatePlayerL( + const TDesC8& aHeaderData) +{ + CMMAPlayer* player = NULL; + TPtrC8 header = aHeaderData.Left(KMMAAnimationGIFVersion().Length()); + if (header == KMMAAnimationGIFVersion()) + { + player = CreateAnimationPlayerL(); + } + return player; +} + +// Gets player's supported content types. +void CMMAAnimationPlayerFactory::GetSupportedContentTypesL( + const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) +{ + if (aProtocol == KNullDesC || + aProtocol == KMMAHttpProtocol || + aProtocol == KMMAHttpsProtocol || + aProtocol == KMMAFileProtocol) + { + aMimeTypeArray.AppendL(KMMAAnimationMimeTypeGIF); + } +} + +// Gets player's supported protocols for the content type. +void CMMAAnimationPlayerFactory::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + if (aContentType == KNullDesC || + aContentType == KMMAAnimationMimeTypeGIF) + { + aProtocolArray.AppendL(KMMAHttpProtocol); + aProtocolArray.AppendL(KMMAHttpsProtocol); + aProtocolArray.AppendL(KMMAFileProtocol); + } +} + +CMMAAnimationPlayer* CMMAAnimationPlayerFactory::CreateAnimationPlayerL(const TDesC& aFileName) +{ + CMMAAnimationPlayer* player = CMMAAnimationPlayer::NewLC(aFileName); + AddControlsL(player); + CleanupStack::Pop(); // player + return player; +} + +CMMAAnimationPlayer* CMMAAnimationPlayerFactory::CreateAnimationPlayerL() +{ + CMMAAnimationPlayer* player = CMMAAnimationPlayer::NewLC(); + AddControlsL(player); + CleanupStack::Pop(); // player + return player; +} + +void CMMAAnimationPlayerFactory::AddControlsL(CMMAAnimationPlayer* aPlayer) +{ + CMMAVideoControl* videoControl = new(ELeave) CMMAVideoControl(aPlayer); + CleanupStack::PushL(videoControl); + aPlayer->AddControlL(videoControl); + CleanupStack::Pop(videoControl); + + CMMAAnimationStopTimeControl* stopTimeControl = + CMMAAnimationStopTimeControl::NewL(aPlayer); + CleanupStack::PushL(stopTimeControl); + aPlayer->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + // Own RateControl + CMMAAnimationRateControl* rateControl = + CMMAAnimationRateControl::NewL(aPlayer); + CleanupStack::PushL(rateControl); + aPlayer->AddControlL(rateControl); + CleanupStack::Pop(rateControl); + + // FramePositioningControl is only supported for file locator + if (aPlayer->IsFilePlayer()) + { + CMMAAnimationFramePositioningControl* animationFramePositioningControl = + CMMAAnimationFramePositioningControl::NewL(aPlayer); + CleanupStack::PushL(animationFramePositioningControl); + aPlayer->AddControlL(animationFramePositioningControl); + CleanupStack::Pop(animationFramePositioningControl); + } + +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaanimationratecontrol.h" +#include "cmmaanimationplayer.h" + + +// ----------------------------------------------------------------------------- +// CMMAAnimationRateControl::NewL +// Two-phased constructor. +// ----------------------------------------------------------------------------- +// +CMMAAnimationRateControl* CMMAAnimationRateControl::NewL(CMMAAnimationPlayer* aPlayer) +{ + CMMAAnimationRateControl* self = new(ELeave) CMMAAnimationRateControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +// ----------------------------------------------------------------------------- +// CMMAAnimationRateControl::CMMAAnimationRateControl +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +CMMAAnimationRateControl::CMMAAnimationRateControl(CMMAAnimationPlayer* aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationRateControl::CMMAAnimationRateControl"); + iPlayer = aPlayer; +} + +// Destructor +CMMAAnimationRateControl::~CMMAAnimationRateControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationRateControl::~CMMAAnimationRateControl"); +} + +// ----------------------------------------------------------------------------- +// CMMAAnimationRateControl::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +// +void CMMAAnimationRateControl::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationRateControl::ConstructL"); + iPlayer->SetRateL(KMMADefaultRate); +} + +// ----------------------------------------------------------------------------- +// CMMAAnimationRateControl::SetRateL +// Set rate to minimum or default rate depending on parameter. Informs player +// that rate has changed. Returns set rate. +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CMMAAnimationRateControl::SetRateL(TInt aRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationRateControl::SetRateL"); + TInt rate = aRate; + + if (rate <= KMMAMinRate) + { + rate = KMMAMinRate; + } + else + { + rate = KMMADefaultRate; + } + return iPlayer->SetRateL(rate); +} + +// ----------------------------------------------------------------------------- +// CMMAAnimationRateControl::RateL +// Returns current rate. +// +// (other items were commented in a header). +// ----------------------------------------------------------------------------- +TInt CMMAAnimationRateControl::RateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationRateControl::RateL"); + return iPlayer->RateL(); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationstoptimecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationstoptimecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,66 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaanimationstoptimecontrol.h" +#include "cmmaplayer.h" + +CMMAAnimationStopTimeControl* CMMAAnimationStopTimeControl::NewL(CMMAAnimationPlayer* aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationStopTimeControl::NewL"); + CMMAAnimationStopTimeControl* control = + new(ELeave) CMMAAnimationStopTimeControl(aPlayer); + aPlayer->SetAnimationObserver(control); + return control; +} + + +CMMAAnimationStopTimeControl::~CMMAAnimationStopTimeControl() +{ +} + + +CMMAAnimationStopTimeControl::CMMAAnimationStopTimeControl(CMMAAnimationPlayer* aPlayer) + : CMMAStopTimeControl(aPlayer) +{ +} + +void CMMAAnimationStopTimeControl::SetStopTimeL(const TInt64& aTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationStopTimeControl::SetStopTimeL"); + iStopTime = aTime; +} + +void CMMAAnimationStopTimeControl::AnimationAdvancedL(TInt /*aFrame*/, TInt64 aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAnimationStopTimeControl::AnimationAdvancedL"); + if (aMediaTime > iStopTime) + { + iPlayer->StopL(EFalse); + iPlayer->PostLongEvent(CMMAPlayerEvent::EStoppedAtTime, aMediaTime); + iStopTime = iNoTimer; + } +} + + + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationwindow.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/animated_gif_notUsed/src/cmmaanimationwindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This abstract class implements MMMADisplayWindow functionality +* in CFbsBitmap based displays. +* +*/ + + +// Include Files +#include +#include +#include "cmmaanimationwindow.h" + +// Destructor (virtual by CBase) +CMMAAnimationWindow::~CMMAAnimationWindow() +{ + delete iBitContext; +} + +CMMAAnimationWindow* CMMAAnimationWindow::NewL( + MMAFunctionServer* aEventSource) +{ + CMMAAnimationWindow* self = + new(ELeave)CMMAAnimationWindow(aEventSource); + return self; +} + +CMMAAnimationWindow::CMMAAnimationWindow(MMAFunctionServer* aEventSource): + iEventSource(aEventSource) +{ +} + +void CMMAAnimationWindow::SetViewer(MIHLImageViewer* aViewer) +{ + iViewer = aViewer; +} + +void CMMAAnimationWindow::SetDestinationBitmapL(CFbsBitmap* aBitmap) +{ + CMMABitmapWindow::SetDestinationBitmapL(aBitmap); + User::LeaveIfError(iBitmapDevice->CreateBitmapContext(iBitContext)); +} + +void CMMAAnimationWindow::DrawFrameL(const CFbsBitmap* aBitmap) +{ + if (iBitmap) + { + iBitContext->BitBlt(iDrawRect.iTl, aBitmap); + } +} + +// Local wrapper function to SetDrawRect method +LOCAL_C void StaticSetDrawRect( + CMMAAnimationWindow* aWindow, + const TRect* aRect) +{ + aWindow->SetDrawRect(*aRect); +} + +void CMMAAnimationWindow::SetDrawRect(const TRect& aRect) +{ + iDrawRect = aRect; + if (iViewer) + { + TReal zoomRatio = 1.0; + if ((iViewer->SourceSize().iWidth - aRect.Width()) > + (iViewer->SourceSize().iHeight - aRect.Height())) + { + // calculate zoom ratio from width + zoomRatio = (TReal)aRect.Width() / (TReal)iViewer->SourceSize().iWidth; + } + else + { + // calculate zoom ratio from height + zoomRatio = (TReal)aRect.Height() / (TReal)iViewer->SourceSize().iHeight; + } + + iViewer->SetViewerSize(iDrawRect.Size()); + iViewer->SetZoomRatio(zoomRatio); + } +} + +void CMMAAnimationWindow::SetDrawRectThread(const TRect& aRect) +{ + iEventSource->ExecuteV(&StaticSetDrawRect, + this, + &aRect); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreammetadatacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreammetadatacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAAudioStreamMetaDataControl is a concrete class for getting +* metadata from an audio media. +* +*/ + +#ifndef CMMAAUDIOSTREAMMETADATACONTROL_H +#define CMMAAUDIOSTREAMMETADATACONTROL_H + +// INCLUDES +#include +#include +#include +#include "cmmametadatacontrol.h" + +// Constants +_LIT(KMetaDataSongTitle, "title"); +_LIT(KMetaDataArtist, "author"); +_LIT(KMetaDataAlbum, "album"); +_LIT(KMetaDataYear, "year of recording"); +_LIT(KMetaDataComment, "comment"); +_LIT(KMetaDataAlbumTrack, "album track"); +_LIT(KMetaDataGenre, "genre"); +_LIT(KMetaDataComposer, "composer"); +_LIT(KMetaDataCopyright, "copyright"); +_LIT(KMetaDataOriginalArtist, "original artist"); +_LIT(KMetaDataUrl, "url"); +_LIT(KMetaDataUserUrl, "user url"); +_LIT(KMetaDataJpeg, "front jpeg"); +_LIT(KMetaDataVendor, "vendor"); +_LIT(KMetaDataRating, "rating"); +_LIT(KMetaDataUniqueFileIdentifier, "unique file identifier"); +_LIT(KMetaDataDuration, "duration"); +_LIT(KMetaDataDate, "date"); + +const TInt KKeyStringMaxLength = 60; + + +// CLASS DECLARATION +/** +* This is a concrete class for getting metadata from an audio media. +* +* +*/ + +NONSHARABLE_CLASS(CMMAAudioStreamMetaDataControl): public CMMAMetaDataControl +{ +public: + CMMAAudioStreamMetaDataControl(CMetaDataUtility* aMetadaDataUtility); + ~CMMAAudioStreamMetaDataControl(); + +protected: // from CMMAMetaDataControl + + TInt KeyCountL(); + HBufC* KeyL(TInt aIndex); + + HBufC* KeyValueL(const TDesC& aKey); + +private: // new methods + HBufC* GetKeyL(TMetaDataFieldId aFieldId); + TMetaDataFieldId GetFieldId(const TDesC& aKey, TBool& aCompare); + +private: // data owned + CMetaDataUtility* iMetaDataUtility; + +}; + +#endif // CMMAAUDIOSTREAMMETADATACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreamplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreamplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for streaming audio. +* +*/ + +#ifndef CMMAAUDIOSTREAMPLAYER_H +#define CMMAAUDIOSTREAMPLAYER_H + +// INCLUDES +#include "cmmaemcaudioplayer.h" +#include "mmmastreamhandlerlistener.h" +#include "cmmaemcresolver.h" +#include + +class CMMADataSourceStream; +class CMMAStreamHandler; + + +// CLASS DECLARATION +/** +* This class is used for playing audio from stream source. +*/ +NONSHARABLE_CLASS(CMMAAudioStreamPlayer): public CMMAEMCAudioPlayer, + public MMMAStreamHandlerListener +{ +public: // Construction + /** + * Creates new player. + */ + static CMMAAudioStreamPlayer* NewLC( + CMMAEMCResolver* aResolver); + + // Destructor + ~CMMAAudioStreamPlayer(); + +protected: + // C++ constructor + CMMAAudioStreamPlayer(CMMAEMCResolver* aResolver); + void ConstructL(); + +private: // New methods + + /** + * Starts playback and posts started event. + */ + void PrivateStartL(); + +public: // New methods + /** + * Pause playback without sending stopped event or changing state + */ + TInt Pause(); + +public: // from CMMAPlayer + void DeallocateL(); + void StartL(); + void PrefetchL(); + CMMASourceStream* AddSourceStreamL(JNIEnv* aJNIEnv, + MMAFunctionServer* aEventSource, + jobject aReader); + + void GetDuration(TInt64* aDuration); + void StopL(TBool aPostEvent); + +protected: // From CMMAEMCAudioPlayer + void PlayCompleteL(TInt aError); + +public: + void AddDataSourceToStreamL(); + void CreateStreamL(); + CMetaDataUtility* MetaDataUtilityOwnership(); + +public: // from MMMAStreamHandlerListener + void PrepareComplete(TInt aError); + void StartComplete(TInt aError); + void HandleError(TInt aError); + +public: // from MControlObserver + void Event(MControl* aControl, + TUint aEventType, + TAny* aEventObject); + +private: // data + // owned stream handler + CMMAStreamHandler* iStreamHandler; + + // controller's state, prime panics if called twice + TBool iControllerPrimed; + + // created here and ownership is transferred to + // CMMAAudioStreamMetaDataControl by call to + // MetaDataUtilityOwnership() + CMetaDataUtility* iMetaDataUtility; +}; + +#endif // CMMAAUDIOSTREAMPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreamplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.emc/cmmaaudiostreamplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating stream player. +* +*/ + + +#ifndef CMMAAUDIOSTREAMPLAYERFACTORY_H +#define CMMAAUDIOSTREAMPLAYERFACTORY_H + +// INCLUDES +#include "cmmaemcplayerfactory.h" + +// CLASS DECLARATION +/** +* This class is used for creating stream player. +* +* +*/ +NONSHARABLE_CLASS(CMMAAudioStreamPlayerFactory): public CMMAEMCPlayerFactory +{ +public: // Constructor and destructor + static CMMAAudioStreamPlayerFactory* NewLC(); + ~CMMAAudioStreamPlayerFactory(); + +private: // Constructor + CMMAAudioStreamPlayerFactory(); + +public: // From CMMAEMCPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& /*aContentType*/); + CMMAPlayer* CreatePlayerL(const TDesC8& /*aHeaderData*/); + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + CMMAPlayer* CreatePlayerL( + CMMAEMCResolver* aResolver); + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + void MediaIdsL(RArray& aMediaIds); + +public: // new method + void SetSourceInfoL(const TUint8* aHeader, TInt aLength); + +private: // Data, owned + HBufC8* iHeaderData; + // + + +}; + +#endif // CMMAAUDIOSTREAMPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.emc/cmmastreamhandler.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.emc/cmmastreamhandler.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,199 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Streams data from Java to controller +* +*/ + +#ifndef CMMASTREAMHANDLER_H +#define CMMASTREAMHANDLER_H + +// INCLUDES +#include "cmmastreamrequest.h" +#include "mmmastreamrequestlistener.h" +#include "mmmastreamhandlerlistener.h" +#include +#include + +//EMC +#include "StreamControl.h" +#include "MMControlFactory.h" +#include "DataBufferSource.h" +#include "DataBuffer.h" +#include "SinkControl.h" +#include "StreamControlObserver.h" +#include "SourceControlObserver.h" + + +using namespace multimedia; +using multimedia ::MStreamControl; +using multimedia ::MDataBufferSource; +using multimedia ::MDataBuffer; +using multimedia ::CMultimediaFactory; +using multimedia ::MSinkControl; +using multimedia::MSourceControlObserver; +using multimedia::MStreamControlObserver; +using multimedia::MBufferProcessedEvent; + +//End EMC + + +// CONSTANTS +const TInt KMMAStreamHandlerBufferCount = 2; + +class CMMADataSourceStream; + +// CLASS DECLARATION +/** +* This class read data from CMMADataSourceStream and writes it to +* controller. +*/ +NONSHARABLE_CLASS(CMMAStreamHandler): public CBase, public MControlObserver, + public MMMAStreamRequestListener, public MMDUChunkDataObserver +{ +private: + // Streams internal state + enum TMMAStreamState + { + EMMAStreamPrepare = 0, + EMMAStreamPaused, + EMMAStreamStart, + EMMAStreamStarted, + EMMAStreamEof + }; + + // chunk data processed state + enum TMMAProcessedState + { + EMMANoneProcessed = 0, + EMMAMetaDataProcessed, + EMMABufferProcessed, + EMMABothProcessed + }; + +public: // Construction + /** + * Creates new player. + */ + static CMMAStreamHandler* NewL( + MMMAStreamHandlerListener& aListener, + MStreamControl& aMStreamControl, + MDataBufferSource& aMDataBufferSource, + CMultimediaFactory& aFactory, + CMetaDataUtility& aMetaDataUtility); + + // Destructor + ~CMMAStreamHandler(); + +protected: + // C++ constructor + CMMAStreamHandler(MMMAStreamHandlerListener& aResolver, + MStreamControl& aMStreamControl, + MDataBufferSource& aMDataBufferSource, + CMultimediaFactory& aFactory, + CMetaDataUtility& aMetaDataUtility); + void ConstructL(); + +protected: // New methods + +public: // New methods + /** + * Prepares stream to play. + */ + void Prepare(const TDesC8& aMimeType); + + /** + * Stops handling requests. After this call data received from source + * stream will be buffered until StartL is called. + */ + void Pause(); + + /** + * Stops handling requests and frees already read data + * without playing it. + */ + void Stop(); + + /** + * Starts handling requests + */ + void Start(); + + /** + * Sets source stream to read + */ + void SetSourceStream(CMMADataSourceStream* aSourceStream); + +public: // From MMMAStreamRequestListener + void WriteComplete(CMMAStreamRequest* aRequest); + void ReadComplete(CMMAStreamRequest* aRequest); + void HandleError(CMMAStreamRequest* aRequest, + TInt aError); + +public: // from MControlObserver + void Event(MControl* aControl, + TUint aEventType, + TAny* aEventObject); + TBool LastBufferWritten(); + +public: // from MMDUChunkDataObserver + void HandleChunkDataProcessed(TInt aError); + void HandleChunkDataReadyToBeParsed(); + void HandleChunkDataComplete(TInt aError); + +private: + /** + * Writes request to controller + */ + void WriteRequest(CMMAStreamRequest* aRequest); + +private: // data + // Owned write requests + RPointerArray< CMMAStreamRequest > iRequests; + + CMMAStreamRequest* iCurrentRequest; + + // not owned source stream + CMMADataSourceStream* iSourceStream; + + // EMC + // not owned + MStreamControl& iMStreamControl; + MDataBufferSource& iMDataBufferSource; + CMultimediaFactory& iFactory; + + // owned + MDataBuffer *iBuffer; + TBool iLastBufferWritten; + // + + // not owned listener + MMMAStreamHandlerListener& iListener; + + // not owned + CMetaDataUtility& iMetaDataUtility; + + // Stream's state + TMMAStreamState iState; + + // Processed state of current chunk data + TMMAProcessedState iProcessedState; + + // tells if metadata parsing can be started + TBool iMetaDataReadyToBeParsed; + + // to be removed once MDU supports all the reqd formats + TBool iMimeTypeSupportedByMDU; +}; + +#endif // CMMASTREAMHANDLER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.emc/cmmastreamrequest.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.emc/cmmastreamrequest.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Request used to write or read data +* +*/ + +#ifndef CMMASTREAMREQUEST_H +#define CMMASTREAMREQUEST_H + +// INCLUDES +#include +#include "mmmastreamrequestlistener.h" + +// CONSTANTS +const TInt KMMAStreamRequestBufferSize = 5120; + +/** + * - If IsActive returns ETrue, data is procedded in the server. + * - If IsActive returns EFalse and DataPtr is empty request is + * ready for reuse + * - If IsActive returns EFalse and DataPtr is not empty request + * is waiting to be written. + */ +class CMMAStreamRequest: public CBase +{ +public:// Constructor and destructor + /** + * @param aListener will be informed when request completes + */ + static CMMAStreamRequest* NewLC(MMMAStreamRequestListener* aListener); + + /** + * Destructor + */ + ~CMMAStreamRequest(); + +public: // new methods + /** + * @return TPtr to request's data + */ + TPtr8& DataPtr(); + + /** + * Completes read request. + * @param aError system error code + */ + void CompleteRead(TInt aError); + + /** + * MMMAStreamRequestListener will be informed when request is ready. + */ + void SetActive(TBool iActive); + TBool IsActive(); + + /** + * 1 if this is stream's last buffer + * @return reference to request buffer + */ + TPckgBuf< TInt >& RequestBuffer(); +public: + void WriteRequestComplete(TInt Err); + +private: // Constructor + CMMAStreamRequest(MMMAStreamRequestListener* aListener); + void ConstructL(); +private: // Data + // will be informed when request is complete + MMMAStreamRequestListener* iListener; + + // owned data + HBufC8* iData; + + // ptr to iData or NULL if data is processed. + TPtr8 iDataPtr; + + // Request buffer + TPckgBuf< TInt > iRequestBuffer; + + // Status of the buffer + TBool iActive; +}; + +#endif // CMMASTREAMREQUEST_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.mmf/CMMAAudioStreamPlayerFactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.mmf/CMMAAudioStreamPlayerFactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating stream player. +* +*/ + + +#ifndef CMMAAUDIOSTREAMPLAYERFACTORY_H +#define CMMAAUDIOSTREAMPLAYERFACTORY_H + +// INCLUDES +#include "CMMAMMFPlayerFactory.h" + +// CLASS DECLARATION +/** +* This class is used for creating stream player. +* +* +*/ +NONSHARABLE_CLASS(CMMAAudioStreamPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Constructor and destructor + static CMMAAudioStreamPlayerFactory* NewLC(); + ~CMMAAudioStreamPlayerFactory(); + +private: // Constructor + CMMAAudioStreamPlayerFactory(); + +public: // From CMMAMMFPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& /*aContentType*/); + CMMAPlayer* CreatePlayerL(const TDesC8& /*aHeaderData*/); + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + void MediaIdsL(RArray& aMediaIds); + + + +}; + +#endif // CMMAAUDIOSTREAMPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.mmf/cmmaaudiostreamplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.mmf/cmmaaudiostreamplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for streaming audio. +* +*/ + +#ifndef CMMAAUDIOSTREAMPLAYER_H +#define CMMAAUDIOSTREAMPLAYER_H + +// INCLUDES +#include "CMMAAudioPlayer.h" +#include "MMMAStreamHandlerListener.h" + +class CMMADataSourceStream; +class CMMAStreamHandler; + + +// CLASS DECLARATION +/** +* This class is used for playing audio from stream source. +*/ +NONSHARABLE_CLASS(CMMAAudioStreamPlayer): public CMMAAudioPlayer, + public MMMAStreamHandlerListener +{ +public: // Construction + /** + * Creates new player. + */ + static CMMAAudioStreamPlayer* NewLC( + CMMAMMFResolver* aResolver); + + // Destructor + ~CMMAAudioStreamPlayer(); + +protected: + // C++ constructor + CMMAAudioStreamPlayer(CMMAMMFResolver* aResolver); + void ConstructL(); + +private: // New methods + /** + * Loops through iControllerInfos and tries to open those + * @param aSourceUid Data source uid + * @param aSourceData Data for source + * @param aSinkUid Data sink uid + * @param aSinkData Data for sink. + * @param aPrioritySettings Controller's priority. + * @return KErrNone if controller was opened + */ + TInt DoOpen(TUid aSourceUid, + const TDesC8& aSourceData, + TUid aSinkUid, + const TDesC8& aSinkData, + TMMFPrioritySettings aPrioritySettings); + + /** + * Starts playback and posts started event. + */ + void PrivateStartL(); + +public: // New methods + /** + * Pause playback without sending stopped event or changing state + */ + TInt Pause(); + +public: // from CMMAPlayer + void StartL(); + void PrefetchL(); + CMMASourceStream* AddSourceStreamL(JNIEnv* aJNIEnv, + MMAFunctionServer* aEventSource, + jobject aReader); + void GetDuration(TInt64* aDuration); + void StopL(TBool aPostEvent); + +protected: // From CMMAAudioPlayer + void PlayCompleteL(TInt aError); + +public: // from MMMAStreamHandlerListener + void PrepareComplete(TInt aError); + void StartComplete(TInt aError); + void HandleError(TInt aError); + +private: // data + // owned stream handler + CMMAStreamHandler* iStreamHandler; + + // controller's state, prime panics if called twice + TBool iControllerPrimed; +}; + +#endif // CMMAAUDIOSTREAMPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.mmf/cmmastreamhandler.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.mmf/cmmastreamhandler.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Streams data from Java to controller +* +*/ + +#ifndef CMMASTREAMHANDLER_H +#define CMMASTREAMHANDLER_H + +// INCLUDES +#include +#include "CMMAStreamRequest.h" +#include "MMMAStreamRequestListener.h" +#include "MMMAStreamHandlerListener.h" + + +// CONSTANTS +const TInt KMMAStreamHandlerBufferCount = 2; + +class CMMADataSourceStream; + +// CLASS DECLARATION +/** +* This class read data from CMMADataSourceStream and writes it to +* controller. +*/ +NONSHARABLE_CLASS(CMMAStreamHandler): public CBase, + public MMMAStreamRequestListener +{ +private: + // Streams internal state + enum TMMAStreamState + { + EMMAStreamPrepare = 0, + EMMAStreamPaused, + EMMAStreamStart, + EMMAStreamStarted, + EMMAStreamEof + }; + +public: // Construction + /** + * Creates new player. + */ + static CMMAStreamHandler* NewL( + MMMAStreamHandlerListener& aListener, + RMMFController& aController); + + // Destructor + ~CMMAStreamHandler(); + +protected: + // C++ constructor + CMMAStreamHandler(MMMAStreamHandlerListener& aResolver, + RMMFController& aController); + void ConstructL(); + +protected: // New methods + +public: // New methods + /** + * Prepares stream to play. + */ + void PrepareL(); + + /** + * Stops handling requests. After this call data received from source + * stream will be buffered until StartL is called. + */ + void Pause(); + + /** + * Starts handling requests + */ + void StartL(); + + /** + * Data sink destination must be written to this reference + * before stream can be started. + * @return data sink destination reference + */ + TMMFMessageDestination& MessageDestination(); + + /** + * Sets source stream to read + */ + void SetSourceStream(CMMADataSourceStream* aSourceStream); + +public: // From MMMAStreamRequestListener + void WriteComplete(CMMAStreamRequest* aRequest); + void ReadComplete(CMMAStreamRequest* aRequest); + void HandleError(CMMAStreamRequest* aRequest, + TInt aError); +private: + /** + * Writes request to controller + */ + void WriteRequest(CMMAStreamRequest* aRequest); + +private: // data + // Owned write requests + RPointerArray< CMMAStreamRequest > iRequests; + + // not owned source stream + CMMADataSourceStream* iSourceStream; + + // Controller to write stream + RMMFController& iController; + + // added data source + TMMFMessageDestination iDataSourceHandle; + + // not owned listener + MMMAStreamHandlerListener& iListener; + + // Stream's state + TMMAStreamState iState; +}; + +#endif // CMMASTREAMHANDLER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc.mmf/cmmastreamrequest.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc.mmf/cmmastreamrequest.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Request used to write or read data +* +*/ + +#ifndef CMMASTREAMREQUEST_H +#define CMMASTREAMREQUEST_H + +// INCLUDES +#include +#include "MMMAStreamRequestListener.h" + +// CONSTANTS +const TInt KMMAStreamRequestBufferSize = 5120; + +/** + * - If CActive::IsActive returns ETrue, data is procedded in the server. + * - If CActive::IsActive returns EFalse and DataPtr is empty request is + * ready for reuse + * - If CActive::IsActive returns EFalse and DataPtr is not empty request + * is waiting to be written. + */ +class CMMAStreamRequest: public CActive +{ +public:// Constructor and destructor + /** + * @param aListener will be informed when request completes + */ + static CMMAStreamRequest* NewLC(MMMAStreamRequestListener* aListener); + + /** + * Destructor + */ + ~CMMAStreamRequest(); + +public: // new methods + /** + * @return TPtr to request's data + */ + TPtr8& DataPtr(); + + /** + * Completes read request. + * @param aError system error code + */ + void CompleteRead(TInt aError); + + /** + * MMMAStreamRequestListener will be informed when request is ready. + */ + void SetActive(); + + /** + * 1 if this is stream's last buffer + * @return reference to request buffer + */ + TPckgBuf< TInt >& RequestBuffer(); +public: // From CActive + void RunL(); + TInt RunError(TInt aError); + void DoCancel(); + +private: // Constructor + CMMAStreamRequest(MMMAStreamRequestListener* aListener); + void ConstructL(); +private: // Data + // will be informed when request is complete + MMMAStreamRequestListener* iListener; + + // owned data + HBufC8* iData; + + // ptr to iData or NULL if data is processed. + TPtr8 iDataPtr; + + // Request buffer + TPckgBuf< TInt > iRequestBuffer; +}; + +#endif // CMMASTREAMREQUEST_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc/cmmaaudiostreamratecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc/cmmaaudiostreamratecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements RateControl for HTTP stream audio player. +* +*/ + + +#ifndef CMMAAUDIOSTREAMRATECONTROL_H +#define CMMAAUDIOSTREAMRATECONTROL_H + +// INTERNAL INCLUDES +#include "cmmaratecontrol.h" // base class +#include "cmmaaudiostreamplayer.h" + +// CLASS DECLARATION +/** +* This class implements RateControl for http stream audio player. +* +*/ +NONSHARABLE_CLASS(CMMAAudioStreamRateControl): public CMMARateControl, + public MMMAPlayerStateListener +{ +public: + + static CMMAAudioStreamRateControl* NewL( + CMMAAudioStreamPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAAudioStreamRateControl(); + +protected: + + /** + * Constructor. + */ + CMMAAudioStreamRateControl(CMMAAudioStreamPlayer* aPlayer); + + void ConstructL(); + +public: // from MMMAPlayerStateListener + virtual void StateChanged(TInt aState); + +public: // New methods + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + virtual TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + virtual TInt RateL(); + + +private: // Member data + + /** + * Used to obtain RMMFController reference to stop/start + * playback. + */ + CMMAAudioStreamPlayer* iPlayer; + + /** + * Hold current rate value. + */ + TInt iCurrentRate; + +}; + +#endif // CMMAAUDIOSTREAMRATECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc/cmmadatasourcestream.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc/cmmadatasourcestream.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class for reading data from Java SourceStream to native side +* +*/ + + +#ifndef CMMADATASOURCESTREAM_H +#define CMMADATASOURCESTREAM_H + +#include "cmmasourcestream.h" + +class CMMADataSourceStreamEvent; +class MMMASourceStreamListener; +class MMMAEventPoster; +class CMMAStreamRequest; + +// CONSTANTS + +// CLASS DECLARATION +/** +* Class for reading data from Java SourceStream to native side +* +*/ +NONSHARABLE_CLASS(CMMADataSourceStream): public CMMASourceStream +{ +public: // Constructors and destructors + /** + * Object creation. Static method. + * + * @param aJNIEnv handle to used jni environment + * @param aEventPoster handle to event poster + * @param aJavaSourceStream handle to java SourceStream object + * @param aListener Handle to source stream listener + * + * @return CMMADataSourceStream object + */ + static CMMADataSourceStream* NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener, + MMAFunctionServer* aEventSource); + + /** + * Deletes owned objects + */ + ~CMMADataSourceStream(); // Destructor + +public: // New methods + /** + * Reads data from Java + */ + void Read(CMMAStreamRequest* aRequest); + + /** + * @return readed request + */ + CMMAStreamRequest* Request(); + +public: // From CMMASourceStream + + /** + * Overwrites CMMASourceStream's ResetData + * so iData will not be NULL, does nothing + */ + void ResetData(); + +protected: // Constructors and destructors + + /** + * Set variables + * @param aEventPoster handle to event poster + * @param aListener handle to source stream listener + */ + CMMADataSourceStream(MMMAEventPoster* aEventPoster, + MMMASourceStreamListener* aListener); + + /** + * 2nd phase constructor + * + * @param aJNIEnv used jni environment + * @param aJavaSourceStream handle to java source stream object + */ + void ConstructL(JNIEnv* aJNIEnv, MMAFunctionServer* aEventSource,jobject aJavaSourceStream); + + +protected: // From CMMASourceStream + + void WriteL(const TUint8* aData, + TInt aLength, TInt aState); + +protected: + // not owned request + CMMAStreamRequest* iRequest; +}; + +#endif // CMMADATASOURCESTREAM_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc/mmmastreamhandlerlistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc/mmmastreamhandlerlistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Listener for CMMAStreamHandler +* +*/ + +#ifndef MMMASTREAMHANDLERLISTENER_H +#define MMMASTREAMHANDLERLISTENER_H + +/** + * Listener for CMMAStreamHandler. + */ +NONSHARABLE_CLASS(MMMAStreamHandlerListener) +{ +public: + /** + * Called when stream is prepared. + * @param aError system error code + */ + virtual void PrepareComplete(TInt aError) = 0; + + /** + * Called when stream is started. + * @param aError system error code + */ + virtual void StartComplete(TInt aError) = 0; + + /** + * Called when error need to be handled. + * If stream is starting or preparing PrepareComplete or + * StartComplete will be called instead of this method. + * @param aError system error code + */ + virtual void HandleError(TInt aError) = 0; +}; + + +#endif // MMMASTREAMHANDLERLISTENER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/inc/mmmastreamrequestlistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/inc/mmmastreamrequestlistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Used to inform when CMMAStreamRequest completes +* +*/ + +#ifndef MMMASTREAMREQUESTLISTENER_H +#define MMMASTREAMREQUESTLISTENER_H + + +// INCLUDES +class CMMAStreamRequest; + +/** + * MMMAStreamRequestListener will be informed when CMMAStreamRequest is + * completed. + */ +NONSHARABLE_CLASS(MMMAStreamRequestListener) +{ +public: + /** + * Called when when stream write request is completed. + * @param aRequest request completed + */ + virtual void WriteComplete(CMMAStreamRequest* aRequest) = 0; + + /** + * Called when when stream read request is completed. + * @param aRequest request completed + */ + virtual void ReadComplete(CMMAStreamRequest* aRequest) = 0; + + /** + * Called when when stream request is completed. + * @param aError system error code + */ + virtual void HandleError(CMMAStreamRequest* aRequest, + TInt aError) = 0; + +}; + +#endif // MMMASTREAMREQUESTLISTENER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreammetadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreammetadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,274 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAAudioStreamMetaDataControl is a concrete class for getting +* metadata from an audio media. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaaudiostreammetadatacontrol.h" + +CMMAAudioStreamMetaDataControl::CMMAAudioStreamMetaDataControl( + CMetaDataUtility* aMetadaDataUtility) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioStreamMetaDataControl constructor called."); + // this class gets the ownership of MetaDataUtility + iMetaDataUtility = aMetadaDataUtility; +} + +CMMAAudioStreamMetaDataControl::~CMMAAudioStreamMetaDataControl() +{ + LOG( EJavaMMAPI, EInfo, "~CMMAAudioStreamMetaDataControl called."); + delete iMetaDataUtility; +} + +TInt CMMAAudioStreamMetaDataControl::KeyCountL() +{ + TInt entries = iMetaDataUtility->MetaDataCount(); + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamMetaDataControl::KeyCountL, count = %d", entries); + + return entries; +} + +HBufC* CMMAAudioStreamMetaDataControl::KeyL(TInt aIndex) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::KeyL +"); + HBufC* key = NULL; + + if (KeyCountL() > 0) + { + TMetaDataFieldId fieldId; + const CMetaDataFieldContainer& fieldcontainer = + iMetaDataUtility->MetaDataFieldsL(); + fieldcontainer.FieldIdAt(aIndex, fieldId); + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamMetaDataControl::KeyL, fieldId = %d", fieldId); + key = GetKeyL(fieldId); + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::KeyL -"); + return key; +} + +/* + * Get the value of given audio metadata key. The ownership of the created value + * (descriptor) is passed to the caller. + */ +HBufC* CMMAAudioStreamMetaDataControl::KeyValueL(const TDesC& aKey) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::KeyValueL +"); + HBufC* retVal = NULL; + + if (KeyCountL() > 0) + { + TBool found; + TMetaDataFieldId fieldId = GetFieldId(aKey, found); + if (found) + { + const CMetaDataFieldContainer& fieldcontainer = + iMetaDataUtility->MetaDataFieldsL(); + retVal = (fieldcontainer.Field(fieldId)).AllocL(); + } + } + + User::LeaveIfNull(retVal); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamMetaDataControl::KeyValueL, retVal = %S", retVal->Des().PtrZ()); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::KeyValueL -"); + return retVal; +} + +/* +* Get key string for the given fieldId +*/ +HBufC* CMMAAudioStreamMetaDataControl::GetKeyL(TMetaDataFieldId aFieldId) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::GetKeyL +"); + HBufC* keyString = NULL; + TBuf tempBuf; + + switch (aFieldId) + { + case EMetaDataSongTitle: + tempBuf.Copy(KMetaDataSongTitle); + keyString = tempBuf.AllocL(); + break; + case EMetaDataArtist: + tempBuf.Copy(KMetaDataArtist); + keyString = tempBuf.AllocL(); + break; + case EMetaDataAlbum: + tempBuf.Copy(KMetaDataAlbum); + keyString = tempBuf.AllocL(); + break; + case EMetaDataYear: + tempBuf.Copy(KMetaDataYear); + keyString = tempBuf.AllocL(); + break; + case EMetaDataAlbumTrack: + tempBuf.Copy(KMetaDataAlbumTrack); + keyString = tempBuf.AllocL(); + break; + case EMetaDataGenre: + tempBuf.Copy(KMetaDataGenre); + keyString = tempBuf.AllocL(); + break; + case EMetaDataComposer: + tempBuf.Copy(KMetaDataComposer); + keyString = tempBuf.AllocL(); + break; + case EMetaDataCopyright: + tempBuf.Copy(KMetaDataCopyright); + keyString = tempBuf.AllocL(); + break; + case EMetaDataOriginalArtist: + tempBuf.Copy(KMetaDataOriginalArtist); + keyString = tempBuf.AllocL(); + break; + case EMetaDataUrl: + tempBuf.Copy(KMetaDataUrl); + keyString = tempBuf.AllocL(); + break; + case EMetaDataUserUrl: + tempBuf.Copy(KMetaDataUserUrl); + keyString = tempBuf.AllocL(); + break; + case EMetaDataJpeg: + tempBuf.Copy(KMetaDataJpeg); + keyString = tempBuf.AllocL(); + break; + case EMetaDataVendor: + tempBuf.Copy(KMetaDataVendor); + keyString = tempBuf.AllocL(); + break; + case EMetaDataRating: + tempBuf.Copy(KMetaDataRating); + keyString = tempBuf.AllocL(); + break; + case EMetaDataUniqueFileIdentifier: + tempBuf.Copy(KMetaDataUniqueFileIdentifier); + keyString = tempBuf.AllocL(); + break; + case EMetaDataDuration: + tempBuf.Copy(KMetaDataDuration); + keyString = tempBuf.AllocL(); + break; + case EMetaDataDate: + tempBuf.Copy(KMetaDataDate); + keyString = tempBuf.AllocL(); + break; + default: + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::GetKeyL, default case should not occur"); + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::GetKeyL -"); + return keyString; +} + +/* +* Get fieldId for the given key string +*/ +TMetaDataFieldId CMMAAudioStreamMetaDataControl::GetFieldId(const TDesC& aKey, TBool& aCompare) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::GetFieldId +"); + TMetaDataFieldId fieldId = EUnknownMetaDataField; + aCompare = true; // found + + if (0 == aKey.Compare(KMetaDataSongTitle())) + { + fieldId = EMetaDataSongTitle; + } + else if (0 == aKey.Compare(KMetaDataArtist())) + { + fieldId = EMetaDataArtist; + } + else if (0 == aKey.Compare(KMetaDataAlbum())) + { + fieldId = EMetaDataAlbum; + } + else if (0 == aKey.Compare(KMetaDataArtist())) + { + fieldId = EMetaDataArtist; + } + else if (0 == aKey.Compare(KMetaDataYear())) + { + fieldId = EMetaDataYear; + } + else if (0 == aKey.Compare(KMetaDataComment())) + { + fieldId = EMetaDataComment; + } + else if (0 == aKey.Compare(KMetaDataAlbumTrack())) + { + fieldId = EMetaDataAlbumTrack; + } + else if (0 == aKey.Compare(KMetaDataGenre())) + { + fieldId = EMetaDataGenre; + } + else if (0 == aKey.Compare(KMetaDataComposer())) + { + fieldId = EMetaDataComposer; + } + else if (0 == aKey.Compare(KMetaDataCopyright())) + { + fieldId = EMetaDataCopyright; + } + else if (0 == aKey.Compare(KMetaDataOriginalArtist())) + { + fieldId = EMetaDataOriginalArtist; + } + else if (0 == aKey.Compare(KMetaDataUrl())) + { + fieldId = EMetaDataUrl; + } + else if (0 == aKey.Compare(KMetaDataUserUrl())) + { + fieldId = EMetaDataUserUrl; + } + else if (0 == aKey.Compare(KMetaDataJpeg())) + { + fieldId = EMetaDataJpeg; + } + else if (0 == aKey.Compare(KMetaDataVendor())) + { + fieldId = EMetaDataVendor; + } + else if (0 == aKey.Compare(KMetaDataRating())) + { + fieldId = EMetaDataRating; + } + else if (0 == aKey.Compare(KMetaDataUniqueFileIdentifier())) + { + fieldId = EMetaDataUniqueFileIdentifier; + } + else if (0 == aKey.Compare(KMetaDataDuration())) + { + fieldId = EMetaDataDuration; + } + else if (0 == aKey.Compare(KMetaDataDate())) + { + fieldId = EMetaDataDate; + } + else + { + aCompare = false; // not found + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamMetaDataControl::GetFieldId -"); + return fieldId; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreamplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreamplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,469 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for streaming audio. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaaudiostreamplayer.h" +#include "cmmadatasourcestream.h" +#include "mmafunctionserver.h" +#include "cmmastreamhandler.h" + +_LIT(KMMAStreamErrorMessage, "Internal error: %d"); + + +CMMAAudioStreamPlayer* CMMAAudioStreamPlayer::NewLC( + CMMAEMCResolver* aResolver) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::NewLC +"); + CMMAAudioStreamPlayer* self = new(ELeave) CMMAAudioStreamPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::NewLC -"); + return self; +} + +CMMAAudioStreamPlayer::~CMMAAudioStreamPlayer() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::~CMMAAudioStreamPlayer +"); + + if (iMStreamControl->GetState() > MStreamControl::CLOSED) + { + iMStreamControl->Close(); + } + + delete iStreamHandler; + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::~CMMAAudioStreamPlayer -"); +} + + +CMMAAudioStreamPlayer::CMMAAudioStreamPlayer( + CMMAEMCResolver* aResolver): + CMMAEMCAudioPlayer(aResolver) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::CMMAAudioStreamPlayer"); +} + +void CMMAAudioStreamPlayer::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::ConstructL +"); + iControllerPrimed = EFalse; + CMMAEMCAudioPlayer::ConstructL(); + iMetaDataUtility = CMetaDataUtility::NewL(); + iStreamHandler = CMMAStreamHandler::NewL(*this, + *iMStreamControl, + *iMDataBufferSource, + *iFactory, + *iMetaDataUtility); + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::ConstructL -"); +} + +CMMASourceStream* CMMAAudioStreamPlayer::AddSourceStreamL(JNIEnv* aJNIEnv, + MMAFunctionServer* aEventSource, + jobject aReader) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::AddSourceStreamL +"); + CMMADataSourceStream* sourceStream = CMMADataSourceStream::NewLC(aJNIEnv, + aEventSource, + aReader, + this, + aEventSource); + User::LeaveIfError(iSourceStreams.Append(sourceStream)); + CleanupStack::Pop(sourceStream); + iStreamHandler->SetSourceStream(sourceStream); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::AddSourceStreamL -"); + return sourceStream; +} + +CMetaDataUtility* CMMAAudioStreamPlayer::MetaDataUtilityOwnership() +{ + CMetaDataUtility* temp = iMetaDataUtility; + iMetaDataUtility = NULL; + return temp; +} + +void CMMAAudioStreamPlayer::DeallocateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::DeallocateL +"); + iStreamHandler->Stop(); + iControllerPrimed = EFalse; + CMMAEMCPlayerBase::DeallocateL(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::DeallocateL -"); +} + +void CMMAAudioStreamPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::PrefetchL +"); + __ASSERT_DEBUG(iSourceStreams.Count() > 0, User::Invariant()); + iStreamHandler->Prepare(*iMimeType); + LOG( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::PrefetchL -"); +} + +void CMMAAudioStreamPlayer::StartL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL +"); + if (iStreamHandler->LastBufferWritten() && + (iMStreamControl ->GetState() == MStreamControl::PAUSED)) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL If outer+"); + TInt64 time; + GetMediaTime(&time); + TInt err = iMStreamControl->Start(); + if (err == KErrNone && iState != EStarted) + { LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL If inner+"); + // move to started state and post started event + ChangeState(EStarted); + PostLongEvent(CMMAPlayerEvent::EStarted, time); + } + else + { LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL else inner+"); + HandleError(err); + } + } + else + { LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL else outer+"); + iStreamHandler->Start(); + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartL -"); +} + +void CMMAAudioStreamPlayer::StopL(TBool aPostEvent) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::Stop state %d", iState); + if (iState == EStarted) + { + User::LeaveIfError(Pause()); + // go back to prefetched state + ChangeState(EPrefetched); + if (aPostEvent) + { + TInt64 time; + GetMediaTime(&time); + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + } + LOG( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::Stop OK"); +} + +TInt CMMAAudioStreamPlayer::Pause() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Pause +"); + iStreamHandler->Pause(); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer:: iStreamControl State = %d",iMStreamControl->GetState()); + + TInt err = KErrNone; + if (iMStreamControl->GetState() != MStreamControl::PAUSED) + { + err = iMStreamControl->Pause(); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer:: iStreamControl Pause error = %d", err); + if ((!iActiveSchedulerWait->IsStarted()) && (err == KErrNone)) + { + iActiveSchedulerWait->Start(); + } + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Pause -"); + return err; +} + +void CMMAAudioStreamPlayer::PlayCompleteL(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::PlayCompleteL error %d", + aError); + + // Before controller is started it must be primed + iControllerPrimed = EFalse; + + TInt64 time; + GetDuration(&time); + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, time); + + ChangeState(EPrefetched); // ready to play again + + if (aError == KErrNone) + { + iRepeatCount++; + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } +} + +void CMMAAudioStreamPlayer::GetDuration(TInt64* aDuration) +{ + CMMAPlayer::GetDuration(aDuration); +} + +void CMMAAudioStreamPlayer::PrepareComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::PrepareComplete error %d", + aError); + + if (aError == KErrNone) + { + ChangeState(EPrefetched); + } + PostActionCompleted(aError); // java prefetch return +} + +void CMMAAudioStreamPlayer::StartComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete error %d", + aError); + + // do not start if player is deallocated or closed + // RateControl start can start controller in started state + if ((iState != EStarted) && + (iState != EPrefetched)) + { + PostActionCompleted(KErrNone); // java start return + return; + } + + TInt err = aError; + if (!iControllerPrimed) + { + // Prime must be called when player is started first time or restarted + err = iMStreamControl->Prime(); + + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete prime error %d", + err); + } + else + { + err = KErrNone; + } + + if (iControllerPrimed && (iState == EPrefetched)) + { + + TInt64 time; + if (err == KErrNone) + { + // must be primed before media time can be get + GetMediaTime(&time); + err = iMStreamControl->Start(); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete play error %d", + err); + + } + + // RateControl can start controller in started state, then Java event is + // not sent + if (err == KErrNone && iState != EStarted) + { // move to started state and post started event + PostLongEvent(CMMAPlayerEvent::EStarted, time); + ChangeState(EStarted); + } + else + { // post error event + HandleError(aError); + PostActionCompleted(aError); // java start return + } + } + +} + +void CMMAAudioStreamPlayer::HandleError(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::HandleError error %d", + aError); + + TName errorMessage; + errorMessage.Format(KMMAStreamErrorMessage, aError); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); +} + +void CMMAAudioStreamPlayer::Event(MControl* aControl, TUint aEventType, TAny* aEventObject) +{ + + switch (aEventType) + { + + case MStreamControlObserver::KStateChangedEvent: + { + MStateChangedEvent* evt = (MStateChangedEvent*)aEventObject; + MStreamControl* control1 = (MStreamControl*)(aControl); + switch (control1->GetState()) + { + case MStreamControl::CLOSED: + { + iPrevStreamControlState = MStreamControl::CLOSED; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :CLOSED"); + } + break; + + case MStreamControl::INITIALIZED: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :INITIALIZED"); + switch (iPrevStreamControlState) + { + case MStreamControl::CLOSED: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } + } + break; + + case MStreamControl::INITIALIZED: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + LOG( EJavaMMAPI, EInfo, "inner Switch case: MStreamControl::INITIALIZED "); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent:ErrorCode = %d ",evt->GetErrorCode()); + // error occured during prime operation + // move player back to prefetched state + if (iState == EStarted) + { + ChangeState(EPrefetched); + } + PostActionCompleted(evt->GetErrorCode()); // java start return + } + break; + + case MStreamControl::PRIMED: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + LOG( EJavaMMAPI, EInfo, "inner Switch case: MStreamControl::PRIMED "); + + } + break; + + case MStreamControl::EXECUTING: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + LOG( EJavaMMAPI, EInfo, "inner Switch case: MStreamControl::EXECUTING "); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent:ErrorCode = %d ",evt->GetErrorCode()); + if (KErrEof == evt->GetErrorCode()) + { + TRAPD(error, PlayCompleteL(KErrNone)); + if (KErrNone != error) + { + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::Event:PlayCompleteL Error = %d", error); + } + } + } + break; + + case MStreamControl::BUFFERING: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + LOG( EJavaMMAPI, EInfo, "inner Switch case: MStreamControl::BUFFERING "); + } + break; + + case MStreamControl::PAUSED: + { + iPrevStreamControlState = MStreamControl::INITIALIZED; + LOG( EJavaMMAPI, EInfo, "inner Switch case: MStreamControl::PAUSED "); + } + break; + } + } + break; + + case MStreamControl::PRIMED: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :PRIMED"); + iPrevStreamControlState = MStreamControl::PRIMED; + iControllerPrimed = ETrue; + TInt64 time; + // must be primed before media time can be get + GetMediaTime(&time); + TInt err = iMStreamControl->Start(); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::Event play error %d", + err); + + // RateControl can start controller in started state, then Java event is + // not sent + if (err == KErrNone && iState != EStarted) + { // move to started state and post started event + PostLongEvent(CMMAPlayerEvent::EStarted, time); + ChangeState(EStarted); + } + else + { + PostLongEvent(CMMAPlayerEvent::EStarted, time); + } + } + break; + + case MStreamControl::EXECUTING: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :EXECUTING"); + iPrevStreamControlState = MStreamControl::EXECUTING; + PostActionCompleted(KErrNone); // java start return + } + break; + + case MStreamControl::BUFFERING: + { + iPrevStreamControlState = MStreamControl::BUFFERING; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :BUFFERING"); + } + break; + + case MStreamControl::PAUSED: + { + iPrevStreamControlState = MStreamControl::PAUSED; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :PAUSED"); + } + break; + + default: + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::Event:KStateChangedEvent :DEFAULT"); + break; + } + } + break; + + case MControlObserver::KErrorEvent: + { + MErrorCode* evt = (MErrorCode*)aEventObject; + if (KErrNone != evt->GetErrorCode()) + { + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::Event:KErrorEvent, err = %d", evt->GetErrorCode()); + } + } + break; + } +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreamplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.emc/cmmaaudiostreamplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,168 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating streaming audio player. +* +*/ + + +// INCLUDE FILES +#include +#include "cmmaaudiostreamplayerfactory.h" +#include "cmmaaudiostreamplayer.h" +#include "cmmaemcaudiovolumecontrol.h" +#include "cmmastoptimecontrol.h" +#include + +#include "cmmaaudiostreammetadatacontrol.h" +#include "cmmaemcresolver.h" + +#ifdef __MMA_GENERIC_RATE_CONTROL__ +#include "cmmaaudiostreamratecontrol.h" +#endif // __MMA_GENERIC_RATE_CONTROL__ + +// CONSTANTS +_LIT(KMimetypeAMR,"audio/amr"); +_LIT(KMimetypeAMRWB,"audio/amr-wb"); +_LIT(KMimetypeAAC, "audio/aac"); +_LIT(KMimetype3GPP, "audio/3gpp"); +_LIT(KMimetype3GPP2, "audio/3gpp2"); +_LIT(KMimetypeMPEG, "audio/mpeg"); +_LIT(KMimetypeMP4, "audio/mp4"); +_LIT(KMimetypeXMSWMA, "audio/x-ms-wma"); +_LIT(KMimetypeRM, "audio/x-pn-realaudio"); + +CMMAAudioStreamPlayerFactory* CMMAAudioStreamPlayerFactory::NewLC() +{ + CMMAAudioStreamPlayerFactory* pFactory = + new(ELeave) CMMAAudioStreamPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAAudioStreamPlayerFactory::CMMAAudioStreamPlayerFactory() +{ + iHeaderData = NULL; +} + + +CMMAAudioStreamPlayerFactory::~CMMAAudioStreamPlayerFactory() +{ +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC& /*aContentType*/) +{ + // only http/https protocol is supported + return NULL; +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // only http and https protocols are supported + if ((aProtocol != KMMAHttpProtocol) && (aProtocol != KMMAHttpsProtocol)) + { + return NULL; + } + + return CMMAEMCPlayerFactory::CreatePlayerL(aProtocol, + aMiddlePart, + aParameters); +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC8& /*aHeaderData*/) +{ + // only http/https protocol is supported + return NULL; +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + CMMAEMCResolver* aResolver) +{ + aResolver->SetSourceInfoL(iHeaderData); + + HBufC* contentType = aResolver->ContentType(); + if (!contentType || + ((contentType->Des() != KMimetypeAMR) && + (contentType->Des() != KMimetypeAMRWB) && + (contentType->Des() != KMimetypeAAC) && + (contentType->Des() != KMimetypeXMSWMA) && + (contentType->Des() != KMimetypeRM) && + (contentType->Des() != KMimetypeMPEG) && + (contentType->Des() != KMimetype3GPP2) && + (contentType->Des() != KMimetype3GPP) && + (contentType->Des() != KMimetypeMP4))) + { + return NULL; + } + + CMMAAudioStreamPlayer* player = CMMAAudioStreamPlayer::NewLC(aResolver); + + CMMAEMCAudioVolumeControl* volumeControl = CMMAEMCAudioVolumeControl::NewL(*player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + + CMMAStopTimeControl* stopTimeControl = CMMAStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + +#ifdef __MMA_GENERIC_RATE_CONTROL__ + CMMAAudioStreamRateControl* rateControl = CMMAAudioStreamRateControl::NewL(player); + CleanupStack::PushL(rateControl); + player->AddControlL(rateControl); + CleanupStack::Pop(rateControl); +#endif // __MMA_GENERIC_RATE_CONTROL__ + + CMMAAudioStreamMetaDataControl* metadatacontrol = + new(ELeave) CMMAAudioStreamMetaDataControl(player->MetaDataUtilityOwnership()); + CleanupStack::PushL(metadatacontrol); + player->AddControlL(metadatacontrol); + CleanupStack::Pop(metadatacontrol); + + // delete isourceinfo; + // no longer required, can be destroyed here + if (iHeaderData) + { + delete iHeaderData; + iHeaderData = NULL; + } + + CleanupStack::Pop(player); + + return player; +} + +void CMMAAudioStreamPlayerFactory::GetSupportedContentTypesL(const TDesC& /*aProtocol*/, + CDesC16Array& /*aMimeTypeArray*/) +{ + // streaming player does not add new content types +} + +void CMMAAudioStreamPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeAudio)); +} + +void CMMAAudioStreamPlayerFactory::SetSourceInfoL(const TUint8* aHeader, TInt aLength) +{ + iHeaderData = HBufC8::NewL(aLength); + iHeaderData->Des().Copy(aHeader, aLength); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.emc/cmmastreamhandler.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.emc/cmmastreamhandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,416 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Streams data from Java to controller +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmastreamhandler.h" +#include "cmmadatasourcestream.h" +#include "mmafunctionserver.h" + + +CMMAStreamHandler* CMMAStreamHandler::NewL( + MMMAStreamHandlerListener& aListener, + MStreamControl& aMStreamControl, + MDataBufferSource& aMDataBufferSource, + CMultimediaFactory& aFactory, + CMetaDataUtility& aMetaDataUtility) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::NewL +"); + CMMAStreamHandler* self = new(ELeave) CMMAStreamHandler(aListener, + aMStreamControl, + aMDataBufferSource, + aFactory, + aMetaDataUtility); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::NewL -"); + return self; +} + +CMMAStreamHandler::~CMMAStreamHandler() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::~CMMAStreamHandler() +"); + iMDataBufferSource.RemoveObserver(*this); + if (iBuffer != NULL) + { + iFactory.DeleteDataBuffer(iBuffer); + iBuffer = NULL; + } + iRequests.ResetAndDestroy(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::~CMMAStreamHandler() -"); +} + +CMMAStreamHandler::CMMAStreamHandler(MMMAStreamHandlerListener& aListener, + MStreamControl& aMStreamControl, + MDataBufferSource& aMDataBufferSource, + CMultimediaFactory& aFactory, + CMetaDataUtility& aMetaDataUtility) + :iMStreamControl(aMStreamControl), + iMDataBufferSource(aMDataBufferSource), + iFactory(aFactory), + iListener(aListener), + iMetaDataUtility(aMetaDataUtility), + // to be removed once MDU supports all the reqd formats + iMimeTypeSupportedByMDU(ETrue) +{ + // ignore read/write completed before stream is prepared + iState = EMMAStreamPaused; + iMetaDataReadyToBeParsed = EFalse; +} + +void CMMAStreamHandler::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::ConstructL +"); + //Register source control to control observer to get the event + iMDataBufferSource.AddObserver(*this); + iLastBufferWritten = EFalse; + iBuffer = NULL; // initialize MDataBuffer type pointer + // create requests + for (TInt i = 0; i < KMMAStreamHandlerBufferCount; i++) + { + CMMAStreamRequest* requestToAppend = CMMAStreamRequest::NewLC(this); + iRequests.AppendL(requestToAppend); + CleanupStack::Pop(requestToAppend); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::ConstructL -"); +} + +void CMMAStreamHandler::Prepare(const TDesC8& aMimeType) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Prepare +"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Prepare state %d", iState); + iState = EMMAStreamPrepare; + // initialize MetaDataUtility + TInt error = iMetaDataUtility.InitChunkData(aMimeType, *this); + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::Prepare, error = %d", error); + if (error != KErrNone) + { + if (error == KErrArgument) + { + // MDU doesn't support aMimeType + // can be removed once MDU supports all the reqd formats + iMimeTypeSupportedByMDU = EFalse; + } + else + { + // MDU supports but some other error occured + iListener.PrepareComplete(error); + return; + } + } + else + { + // to be removed once MDU supports all the reqd formats + iMimeTypeSupportedByMDU = ETrue; + } + //reset request data for reading again from beginning + iRequests[0]->DataPtr().SetLength(0); + + // when read completes iListerner.PrepareComplete will be called + iSourceStream->Read(iRequests[ 0 ]); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Prepare -"); +} + +void CMMAStreamHandler::Start() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start +"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start state %d", iState); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start data source request=%d",(TInt)iSourceStream->Request()); + iState = EMMAStreamStart; + if (iSourceStream->Request()) + { // when read request is completed it will be written to server + iState = EMMAStreamStarted; + iListener.StartComplete(KErrNone); + return; + } + + TInt count = iRequests.Count(); + TBool started = EFalse; + for (TInt i = 0; i < count && !started; i++) + { + CMMAStreamRequest* r = iRequests[ i ]; + if (!r->IsActive() && r->DataPtr().Length() > 0) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start write request to server"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start request length=%d", + r->DataPtr().Length()); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start last buffer %d", + r->RequestBuffer()()); + + // data was not yet written to server + WriteRequest(r); + started = ETrue; + } + else if (r->IsActive()) // data is in server + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start data is in server"); + // atleast one request is not processed + started = ETrue; + } + } + if (started) // If allready started complete start + { + iListener.StartComplete(KErrNone); + iState = EMMAStreamStarted; + } + else + { + // Need to read data before start + iSourceStream->Read(iRequests[ 0 ]); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Start -"); +} + +void CMMAStreamHandler::Pause() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Pause +"); + // ignore read/write completes + iState = EMMAStreamPaused; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Pause -"); +} + +void CMMAStreamHandler::SetSourceStream(CMMADataSourceStream* aSourceStream) +{ + iSourceStream = aSourceStream; +} + +void CMMAStreamHandler::WriteComplete(CMMAStreamRequest* aRequest) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete +"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete state=%d", iState); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete request length=%d", + aRequest->DataPtr().Length()); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete last buffer %d", + aRequest->RequestBuffer()()); + if (iState == EMMAStreamStarted) + { + if (aRequest->RequestBuffer()() == 1) + { + iState = EMMAStreamEof; + } + else + { + iSourceStream->Read(aRequest); + } + } + // else, all other states ignore write complete + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete -"); +} + +void CMMAStreamHandler::ReadComplete(CMMAStreamRequest* aRequest) +{ + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::ReadComplete +"); + + if (iState == EMMAStreamPrepare) + { + + WriteRequest(aRequest); + iListener.PrepareComplete(KErrNone); + iState = EMMAStreamPaused; + } + else if (iState == EMMAStreamStart) + { + iState = EMMAStreamStarted; + // write first request to server + WriteRequest(aRequest); + iListener.StartComplete(KErrNone); + } + else if (iState == EMMAStreamStarted) + { + WriteRequest(aRequest); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::ReadComplete -"); + // else, all other states ignore read complete +} + +void CMMAStreamHandler::HandleError(CMMAStreamRequest* /*aRequest*/, + TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleError +"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleError state=%d", iState); + if (iState == EMMAStreamPrepare) + { + iListener.PrepareComplete(aError); + iState = EMMAStreamPaused; + } + else if (iState == EMMAStreamStart) + { + iListener.StartComplete(aError); + iState = EMMAStreamStarted; + } + else + { + iListener.HandleError(aError); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleError -"); +} + +void CMMAStreamHandler::WriteRequest(CMMAStreamRequest* aRequest) +{ + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteRequest +"); + iCurrentRequest = aRequest; //initialize the current StreamRequest for use in callback function + iProcessedState = EMMANoneProcessed; + + TInt state = iMStreamControl.GetState(); + if (!aRequest->IsActive()) + { + aRequest->SetActive(ETrue); + } + + //Create MDataBuffer and then pass it as a parameter of WriteData + if (iBuffer != NULL) + { + iFactory.DeleteDataBuffer(iBuffer); + iBuffer= NULL; + } + iFactory.CreateDataBuffer(KDataBufferSourceControl, KMMAStreamRequestBufferSize, iBuffer); + iBuffer->GetBufferPtr().Set(aRequest->DataPtr()); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteRequest: Size of the Data to be written is %d ",aRequest->DataPtr().Length()); + if (aRequest->RequestBuffer()() == 1) //set that it is the last buffer + { + iState = EMMAStreamEof; + iBuffer->SetLastBuffer(ETrue); + iLastBufferWritten = ETrue; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteRequest: LastBuffer"); + } + else + { + iBuffer->SetLastBuffer(EFalse); + iLastBufferWritten = EFalse; + } + + // When the buffer is processed by framework KBufferProcessedEvent + // will be delivered to registered observers + TInt err = iMDataBufferSource.WriteData(*iBuffer); + // to be removed once MDU supports all the reqd formats + if (iMimeTypeSupportedByMDU && !iMetaDataReadyToBeParsed) + { + err = iMetaDataUtility.ProcessChunkData(aRequest->DataPtr(), iLastBufferWritten); + } + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::WriteRequest, err = %d", err); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteRequest -"); +} + +void CMMAStreamHandler::Event(MControl* /*aControl*/, TUint aEventType, TAny* aEventObject) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Event "); + switch (aEventType) + { + + case MSourceControlObserver::KBufferProcessedEvent: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Event:KBufferProcessedEvent"); + MBufferProcessedEvent* evt = (MBufferProcessedEvent*)aEventObject; + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::Event:KBufferProcessedEvent:ErrorCode = %d ",evt->GetErrorCode()); + // can be removed once MDU supports all the reqd formats + if (!iMimeTypeSupportedByMDU || + (iProcessedState == EMMAMetaDataProcessed || iMetaDataReadyToBeParsed)) + { + iCurrentRequest->WriteRequestComplete(evt->GetErrorCode()); + iCurrentRequest->SetActive(EFalse); + iProcessedState = EMMABothProcessed; + } + else + { + iProcessedState = EMMABufferProcessed; + } + } + break; + + case MSourceControlObserver::KBitRateChangedEvent: + { + } + break; + + case MStreamControlObserver::KDurationChangedEvent: + { + } + break; + + default: + break; + + }; +} + +void CMMAStreamHandler::HandleChunkDataProcessed(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleChunkDataProcessed + "); + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::HandleChunkDataProcessed, aError = %d", aError); + if (iProcessedState == EMMABufferProcessed) + { + iCurrentRequest->WriteRequestComplete(aError); + iCurrentRequest->SetActive(EFalse); + iProcessedState = EMMABothProcessed; + } + else + { + iProcessedState = EMMAMetaDataProcessed; + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleChunkDataProcessed - "); +} + +void CMMAStreamHandler::HandleChunkDataReadyToBeParsed() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleChunkDataReadyToBeParsed + "); + iMetaDataReadyToBeParsed = ETrue; + TInt error = iMetaDataUtility.ParseChunkData(); + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::HandleChunkDataReadyToBeParsed, error = %d ", error); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleChunkDataReadyToBeParsed - "); +} + +void CMMAStreamHandler::HandleChunkDataComplete(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleChunkDataComplete"); + if (KErrNone != aError) + { + ELOG1( EJavaMMAPI, "MMA::CMMAStreamHandler::HandleChunkDataComplete, aError = %d ", aError); + iListener.HandleError(aError); + } + +} + +TBool CMMAStreamHandler::LastBufferWritten() +{ + return iLastBufferWritten; +} + +void CMMAStreamHandler::Stop() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Stop + "); + // forcefully complete all requests + // and release already read data. + Pause(); + iMetaDataUtility.CloseChunkData(); + TInt count = iRequests.Count(); + for (TInt i = 0; i < count; i++) + { + CMMAStreamRequest* r = iRequests[ i ]; + r->WriteRequestComplete(KErrNone); + r->SetActive(EFalse); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::Stop - "); +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.emc/cmmastreamrequest.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.emc/cmmastreamrequest.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Request used to write or read data +* +*/ + + +// INCLUDE FILES +#include +#include "cmmastreamrequest.h" +#include "mmmastreamrequestlistener.h" + +CMMAStreamRequest* CMMAStreamRequest::NewLC(MMMAStreamRequestListener* aListener) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::NewLC +"); + CMMAStreamRequest* self = new(ELeave)CMMAStreamRequest(aListener); + CleanupStack::PushL(self); + self->ConstructL(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::NewLC -"); + return self; +} + +CMMAStreamRequest::~CMMAStreamRequest() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::~CMMAStreamRequest +"); + delete iData; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::~CMMAStreamRequest -"); +} + +TPtr8& CMMAStreamRequest::DataPtr() +{ + return iDataPtr; +} + +void CMMAStreamRequest::CompleteRead(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::CompleteRead +"); + if (aError < KErrNone) + { + iListener->HandleError(this, aError); + } + else // OK + { + iListener->ReadComplete(this); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::CompleteRead -"); +} + +void CMMAStreamRequest::SetActive(TBool aActive) +{ + iActive = aActive; +} + +TBool CMMAStreamRequest::IsActive() +{ + return iActive; +} + +TPckgBuf< TInt >& CMMAStreamRequest::RequestBuffer() +{ + return iRequestBuffer; +} + +void CMMAStreamRequest::WriteRequestComplete(TInt Err) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::WriteRequestComplete +"); + if (Err == KErrNone) + { + // data is processed, set ready for reuse + iDataPtr.SetLength(0); + iListener->WriteComplete(this); + } + else // error + { + iListener->HandleError(this, Err); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::WriteRequestComplete -"); +} + +CMMAStreamRequest::CMMAStreamRequest(MMMAStreamRequestListener* aListener): + iListener(aListener), + iDataPtr(NULL, 0),iActive(EFalse) +{ + //Do Nothing +} + +void CMMAStreamRequest::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::ConstructL +"); + iData = HBufC8::NewL(KMMAStreamRequestBufferSize); + iDataPtr.Set(iData->Des()); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamRequest::ConstructL -"); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.mmf/cmmaaudiostreamplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.mmf/cmmaaudiostreamplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,309 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for streaming audio. +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "CMMAAudioStreamPlayer.h" +#include "CMMADataSourceStream.h" +#include "MMAFunctionServer.h" +#include "CMMAStreamHandler.h" + +const TInt KPlayerPriority = KAudioPriorityRecording; +_LIT(KMMAStreamErrorMessage, "Internal error: %d"); + +// Uid must be same as in S60StreamingSourceUIDs.hrh which is not exported from +// EnhancedAudioPlayerUtility/AudioStreaming/AudioStreamingSource. +const TUid KMMAMmfS60StreamingSourceUid = { 0x10207AF3 }; + + +CMMAAudioStreamPlayer* CMMAAudioStreamPlayer::NewLC( + CMMAMMFResolver* aResolver) +{ + CMMAAudioStreamPlayer* self = new(ELeave) CMMAAudioStreamPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAAudioStreamPlayer::~CMMAAudioStreamPlayer() +{ + delete iStreamHandler; +} + +CMMAAudioStreamPlayer::CMMAAudioStreamPlayer( + CMMAMMFResolver* aResolver): + CMMAAudioPlayer(aResolver) +{ +} + +void CMMAAudioStreamPlayer::ConstructL() +{ + CMMAAudioPlayer::ConstructL(); + iStreamHandler = CMMAStreamHandler::NewL(*this, iController); +} + +TInt CMMAAudioStreamPlayer::DoOpen(TUid aSourceUid, + const TDesC8& aSourceData, + TUid aSinkUid, + const TDesC8& aSinkData, + TMMFPrioritySettings aPrioritySettings) +{ + // Make sure any existing controller is closed. + iEventMonitor->Cancel(); + iController.Close(); + + // Try opening and configuring each controller in turn + TInt error = KErrNotSupported; + TInt index = 0; + + // Try controllers until found a good controller or out of list + while ((error != KErrNone) && + (index < iControllerInfos->Count())) + { + // Open the controller + error = iController.Open((*iControllerInfos)[ index ]->Uid(), + aPrioritySettings); + + // If the controller was opened without error, start receiving events from it. + if (!error) + { + iEventMonitor->Start(); + + // Add the data source to the controller. + error = iController.AddDataSource(aSourceUid, + aSourceData, + iStreamHandler->MessageDestination()); + } + + // Add the data sink + if (!error) + { + error = iController.AddDataSink(aSinkUid, aSinkData); + } + + // If an error occurred in any of the above, close the controller. + if (error) + { + iEventMonitor->Cancel(); + iController.Close(); + } + + index++; + } + + return error; +} + +CMMASourceStream* CMMAAudioStreamPlayer::AddSourceStreamL(JNIEnv* aJNIEnv, + MMAFunctionServer* aEventSource, + jobject aReader) +{ + CMMADataSourceStream* sourceStream = CMMADataSourceStream::NewLC(aJNIEnv, + aEventSource, + aReader, + this); + User::LeaveIfError(iSourceStreams.Append(sourceStream)); + CleanupStack::Pop(sourceStream); + iStreamHandler->SetSourceStream(sourceStream); + return sourceStream; +} + +void CMMAAudioStreamPlayer::PrefetchL() +{ + __ASSERT_DEBUG(iSourceStreams.Count() > 0, User::Invariant()); + + // player priority settings + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = KPlayerPriority; + prioritySettings.iPref = EMdaPriorityPreferenceTimeAndQuality; + prioritySettings.iState = EMMFStatePlaying; + + User::LeaveIfError(DoOpen(KMMAMmfS60StreamingSourceUid, + KNullDesC8, + KUidMmfAudioOutput, + KNullDesC8, + prioritySettings)); + iStreamHandler->PrepareL(); +} + +void CMMAAudioStreamPlayer::StartL() +{ + // If the player is in Prefetched state then it is implied that it has read "KMMAStreamRequestBufferSize" + // and it can be played + LOG1(EJavaMMAPI,EInfo,"CMMAAudioStreamPlayer::StartL() , state = %d",iState); + if (iState == EPrefetched) + { + + TInt64 time; + GetMediaTime(&time); + + // inform java side + PostLongEvent(CMMAPlayerEvent::EStarted, time); + + // go to started state + ChangeState(EStarted); + + PostActionCompleted(KErrNone); // java start return + } + iStreamHandler->StartL(); +} + +void CMMAAudioStreamPlayer::StopL(TBool aPostEvent) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::Stop state %d", iState); + if (iState == EStarted) + { + User::LeaveIfError(Pause()); + + // go back to prefetched state + ChangeState(EPrefetched); + if (aPostEvent) + { + TInt64 time; + GetMediaTime(&time); + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + + } + LOG( EJavaMMAPI, EInfo, "CMMAAudioStreamPlayer::Stop OK"); +} + +TInt CMMAAudioStreamPlayer::Pause() +{ + iStreamHandler->Pause(); + return iController.Pause(); +} + +void CMMAAudioStreamPlayer::PlayCompleteL(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::PlayCompleteL error %d", + aError); + + // Before controller is started it must be primed + iControllerPrimed = EFalse; + + TInt64 time; + GetDuration(&time); + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, time); + + ChangeState(EPrefetched); // ready to play again + + if (aError == KErrNone) + { + iRepeatCount++; + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } +} + +void CMMAAudioStreamPlayer::GetDuration(TInt64* aDuration) +{ + CMMAPlayer::GetDuration(aDuration); +} + +void CMMAAudioStreamPlayer::PrepareComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::PrepareComplete error %d", + aError); + if (aError == KErrNone) + { + ChangeState(EPrefetched); + } + PostActionCompleted(aError); // java prefetch return +} + +void CMMAAudioStreamPlayer::StartComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete error %d", + aError); + + // do not start if player is deallocated or closed + // RateControl start can start controller in started state + if ((iState != EStarted) && + (iState != EPrefetched)) + { + return; + } + + TInt err = aError; + if (!iControllerPrimed) + { + // Prime must be called when player is started first time or restarted + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioStreamPlayer::StartComplete PRIME"); + err = iController.Prime(); + iControllerPrimed = ETrue; + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete prime error %d", + err); + } + else + { + err = KErrNone; + } + + TInt64 time; + if (err == KErrNone) + { + // must be primed before media time can be get + GetMediaTime(&time); + err = iController.Play(); + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::StartComplete play error %d", + err); + } + + // RateControl can start controller in started state, then Java event is + // not sent + if (err == KErrNone && iState != EStarted) + { // move to started state and post started event + PostLongEvent(CMMAPlayerEvent::EStarted, time); + ChangeState(EStarted); + } + else + { // post error event + HandleError(aError); + } +} + +void CMMAAudioStreamPlayer::HandleError(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMAAudioStreamPlayer::HandleError error %d", + aError); + + TName errorMessage; + errorMessage.Format(KMMAStreamErrorMessage, aError); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.mmf/cmmaaudiostreamplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.mmf/cmmaaudiostreamplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,132 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating streaming audio player. +* +*/ + + +// INCLUDE FILES +#include +#include "CMMAAudioStreamPlayerFactory.h" +#include "CMMAAudioStreamPlayer.h" +#include "CMMAAudioVolumeControl.h" +#include "CMMAStopTimeControl.h" +#include "CMMAMMFResolver.h" +#include "CMMAAudioMetaDataControl.h" +#include "CMMAAudioStreamRateControl.h" + +// CONSTANTS +_LIT(KMMAAMRMimetype, "audio/amr"); +_LIT(KMMAAMRWBMimetype, "audio/amr-wb"); + +CMMAAudioStreamPlayerFactory* CMMAAudioStreamPlayerFactory::NewLC() +{ + CMMAAudioStreamPlayerFactory* pFactory = + new(ELeave) CMMAAudioStreamPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAAudioStreamPlayerFactory::CMMAAudioStreamPlayerFactory() +{ +} + + +CMMAAudioStreamPlayerFactory::~CMMAAudioStreamPlayerFactory() +{ +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC& /*aContentType*/) +{ + // only http protocol is supported + return NULL; +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // only http protocol is supported + if (aProtocol != KMMAHttpProtocol) + { + return NULL; + } + + return CMMAMMFPlayerFactory::CreatePlayerL(aProtocol, + aMiddlePart, + aParameters); +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + const TDesC8& /*aHeaderData*/) +{ + // only http protocol is supported + return NULL; +} + +CMMAPlayer* CMMAAudioStreamPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + // only amr streaming is supported + HBufC* contentType = aResolver->ContentType(); + if (!contentType || + ((contentType->Des() != KMMAAMRMimetype) && + (contentType->Des() != KMMAAMRWBMimetype))) + { + return NULL; + } + + CMMAAudioStreamPlayer* player = CMMAAudioStreamPlayer::NewLC(aResolver); + + CMMAAudioVolumeControl* volumeControl = CMMAAudioVolumeControl::NewL(player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + +// Amr stream player should support METADATACONTROL so adding this control to the player + CMMAAudioMetaDataControl* metaDataControl = + new(ELeave) CMMAAudioMetaDataControl(player->Controller()); + CleanupStack::PushL(metaDataControl); + player->AddControlL(metaDataControl); + CleanupStack::Pop(metaDataControl); + + CMMAStopTimeControl* stopTimeControl = CMMAStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + CMMAAudioStreamRateControl* rateControl = CMMAAudioStreamRateControl::NewL(player); + CleanupStack::PushL(rateControl); + player->AddControlL(rateControl); + CleanupStack::Pop(rateControl); + + CleanupStack::Pop(player); + + return player; +} + +void CMMAAudioStreamPlayerFactory::GetSupportedContentTypesL(const TDesC& /*aProtocol*/, + CDesC16Array& /*aMimeTypeArray*/) +{ + // streaming player does not add new content types +} + +void CMMAAudioStreamPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeAudio)); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.mmf/cmmastreamhandler.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.mmf/cmmastreamhandler.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,223 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Streams data from Java to controller +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "CMMAStreamHandler.h" +#include "CMMADataSourceStream.h" +#include "MMAFunctionServer.h" + +CMMAStreamHandler* CMMAStreamHandler::NewL( + MMMAStreamHandlerListener& aListener, + RMMFController& aController) +{ + CMMAStreamHandler* self = new(ELeave) CMMAStreamHandler(aListener, + aController); + self->ConstructL(); + return self; +} + +CMMAStreamHandler::~CMMAStreamHandler() +{ + iRequests.ResetAndDestroy(); +} + +CMMAStreamHandler::CMMAStreamHandler(MMMAStreamHandlerListener& aListener, + RMMFController& aController): + iController(aController), + iListener(aListener) +{ + // ignore read/write completed before stream is prepared + iState = EMMAStreamPaused; +} + +void CMMAStreamHandler::ConstructL() +{ + // create requests + for (TInt i = 0; i < KMMAStreamHandlerBufferCount; i++) + { + CMMAStreamRequest* requestToAppend = CMMAStreamRequest::NewLC(this); + iRequests.AppendL(requestToAppend); + CleanupStack::Pop(requestToAppend); + } +} + +void CMMAStreamHandler::PrepareL() +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::PrepareL state %d", iState); + iState = EMMAStreamPrepare; + + //reset request data for reading again from beginning + iRequests[0]->DataPtr().SetLength(0); + + // when read completes iListerner.PrepareComplete will be called + iSourceStream->Read(iRequests[ 0 ]); +} + +void CMMAStreamHandler::StartL() +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL state %d", iState); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL data source request=%d", + (TInt)iSourceStream->Request()); + + iState = EMMAStreamStart; + if (iSourceStream->Request()) + { // when read request is completed it will be written to server + iState = EMMAStreamStarted; + iListener.StartComplete(KErrNone); + return; + } + + TInt count = iRequests.Count(); + TBool started = EFalse; + for (TInt i = 0; i < count && !started; i++) + { + CMMAStreamRequest* r = iRequests[ i ]; + if (!r->IsActive() && r->DataPtr().Length() > 0) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL write request to server"); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL request length=%d", + r->DataPtr().Length()); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL last buffer %d", + r->RequestBuffer()()); + + // data was not yet written to server + WriteRequest(r); + started = ETrue; + } + else if (r->IsActive()) // data is in server + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::StartL data is in server"); + // atleast one request is not processed + started = ETrue; + } + } + if (started) // If allready started complete start + { + iListener.StartComplete(KErrNone); + iState = EMMAStreamStarted; + } + else + { + // Need to read data before start + iSourceStream->Read(iRequests[ 0 ]); + } +} + +void CMMAStreamHandler::Pause() +{ + // ignore read/write completes + iState = EMMAStreamPaused; +} + +TMMFMessageDestination& CMMAStreamHandler::MessageDestination() +{ + return iDataSourceHandle; +} + +void CMMAStreamHandler::SetSourceStream(CMMADataSourceStream* aSourceStream) +{ + iSourceStream = aSourceStream; +} + +void CMMAStreamHandler::WriteComplete(CMMAStreamRequest* aRequest) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete state=%d", iState); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete request length=%d", + aRequest->DataPtr().Length()); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::WriteComplete last buffer %d", + aRequest->RequestBuffer()()); + if (iState == EMMAStreamStarted) + { + if (aRequest->RequestBuffer()() == 1) + { + iState = EMMAStreamEof; + } + else + { + iSourceStream->Read(aRequest); + } + } + // else, all other states ignore write complete +} + +void CMMAStreamHandler::ReadComplete(CMMAStreamRequest* aRequest) +{ + if (iState == EMMAStreamPrepare) + { + WriteRequest(aRequest); + iListener.PrepareComplete(KErrNone); + iState = EMMAStreamPaused; + } + else if (iState == EMMAStreamStart) + { + iState = EMMAStreamStarted; + // write first request to server + WriteRequest(aRequest); + iListener.StartComplete(KErrNone); + } + else if (iState == EMMAStreamStarted) + { + WriteRequest(aRequest); + } + // else, all other states ignore read complete +} + +void CMMAStreamHandler::HandleError(CMMAStreamRequest* /*aRequest*/, + TInt aError) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAStreamHandler::HandleError state=%d", iState); + if (iState == EMMAStreamPrepare) + { + iListener.PrepareComplete(aError); + iState = EMMAStreamPaused; + } + else if (iState == EMMAStreamStart) + { + iListener.StartComplete(aError); + iState = EMMAStreamStarted; + } + else + { + iListener.HandleError(aError); + } +} + +void CMMAStreamHandler::WriteRequest(CMMAStreamRequest* aRequest) +{ + if (aRequest->RequestBuffer()() == 1) + { + iState = EMMAStreamEof; + } + + if (!aRequest->IsActive()) + { + aRequest->SetActive(); + } + + // Send write request to server, HandleRequestCompleteL is called when finished + iController.CustomCommandAsync(iDataSourceHandle, + 1, /*EProcessBuffer*/ + aRequest->DataPtr(), + aRequest->RequestBuffer(), + aRequest->iStatus); +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src.mmf/cmmastreamrequest.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src.mmf/cmmastreamrequest.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Request used to write or read data +* +*/ + + +// INCLUDE FILES +#include +#include "CMMAStreamRequest.h" +#include "MMMAStreamRequestListener.h" + +CMMAStreamRequest* CMMAStreamRequest::NewLC(MMMAStreamRequestListener* aListener) +{ + CMMAStreamRequest* self = new(ELeave)CMMAStreamRequest(aListener); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAStreamRequest::~CMMAStreamRequest() +{ + Cancel(); + delete iData; +} + +TPtr8& CMMAStreamRequest::DataPtr() +{ + return iDataPtr; +} + +void CMMAStreamRequest::CompleteRead(TInt aError) +{ + if (aError < KErrNone) + { + iListener->HandleError(this, aError); + } + else // OK + { + iListener->ReadComplete(this); + } +} + +void CMMAStreamRequest::SetActive() +{ + CActive::SetActive(); +} + +TPckgBuf< TInt >& CMMAStreamRequest::RequestBuffer() +{ + return iRequestBuffer; +} + +void CMMAStreamRequest::RunL() +{ + if (iStatus.Int() == KErrNone) + { + // data is processed, set ready for reuse + iDataPtr.SetLength(0); + iListener->WriteComplete(this); + } + else // error + { + iListener->HandleError(this, iStatus.Int()); + } +} + +TInt CMMAStreamRequest::RunError(TInt aError) +{ + iListener->HandleError(this, aError); + return KErrNone; +} + +void CMMAStreamRequest::DoCancel() +{ + // Complete this request + TRequestStatus* s = &iStatus; + User::RequestComplete(s, KErrCancel); +} + +CMMAStreamRequest::CMMAStreamRequest(MMMAStreamRequestListener* aListener): + CActive(EPriorityStandard), + iListener(aListener), + iDataPtr(NULL, 0) +{ + CActiveScheduler::Add(this); +} + +void CMMAStreamRequest::ConstructL() +{ + iData = HBufC8::NewL(KMMAStreamRequestBufferSize); + iDataPtr.Set(iData->Des()); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src/cmmaaudiostreamratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src/cmmaaudiostreamratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements RateControl for HTTP stream audio player. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaaudiostreamratecontrol.h" + +namespace +{ +const TInt KErrorMessageSize = 32; +_LIT(KErrDefaultError, "Symbian OS Error: %d"); +} + +CMMAAudioStreamRateControl* CMMAAudioStreamRateControl::NewL(CMMAAudioStreamPlayer* aPlayer) +{ + CMMAAudioStreamRateControl* self = new(ELeave) CMMAAudioStreamRateControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; +} + +CMMAAudioStreamRateControl::~CMMAAudioStreamRateControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamRateControl::~CMMAAudioStreamRateControl"); + if (iPlayer) + { + iPlayer->RemoveStateListener(this); + } +} + +CMMAAudioStreamRateControl::CMMAAudioStreamRateControl(CMMAAudioStreamPlayer* aPlayer) : + iPlayer(aPlayer), iCurrentRate(KMMADefaultRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamRateControl::CMMAAudioStreamRateControl"); +} + +void CMMAAudioStreamRateControl::ConstructL() +{ + iPlayer->AddStateListenerL(this); +} + +void CMMAAudioStreamRateControl::StateChanged(TInt aState) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamRateControl::StateChanged"); + if (aState == CMMAPlayer::EStarted && iCurrentRate == KMMAMinRate) + { + // do not post event to Java or change player state + TInt err = iPlayer->Pause(); + if (err != KErrNone) + { + ELOG1( EJavaMMAPI, "CMMAAudioStreamRateControl::StateChanged: Pause error %d", err); + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } + } +} + +TInt CMMAAudioStreamRateControl::SetRateL(TInt aRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAAudioStreamRateControl::SetRateL"); + TInt newRate; + if (aRate <= KMMAMinRate) + { + newRate = KMMAMinRate; + } + else + { + newRate = KMMADefaultRate; + } + + if ((iPlayer->State() == CMMAPlayer::EStarted) && + (newRate != iCurrentRate)) + { + if (newRate == KMMAMinRate) + { + // do not post event to Java or change player state + User::LeaveIfError(iPlayer->Pause()); + } + else + { + // do not post event to Java or change player state + iPlayer->StartL(); + } + } + iCurrentRate = newRate; + return iCurrentRate; +} + +TInt CMMAAudioStreamRateControl::RateL() +{ + return iCurrentRate; +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/audiostreaming/src/cmmadatasourcestream.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/audiostreaming/src/cmmadatasourcestream.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,146 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class for reading data from Java SourceStream to native side +* +*/ + +#include +#include "mmafunctionserver.h" +#include "cmmadatasourcestream.h" +#include "mmmasourcestreamlistener.h" +#include "cmmastreamrequest.h" +#include "cmmasourcestreamevent.h" + + +// CONSTRUCTION +CMMADataSourceStream* CMMADataSourceStream::NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener, + MMAFunctionServer* aEventSource + ) +{ + CMMADataSourceStream* self = new(ELeave) CMMADataSourceStream(aEventPoster, + aListener); + CleanupStack::PushL(self); + self->ConstructL(aJNIEnv, aEventSource, aJavaSourceStream); + return self; +} + + +CMMADataSourceStream::~CMMADataSourceStream() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADataSourceStream::~"); +} + + +// Default constructor +CMMADataSourceStream::CMMADataSourceStream(MMMAEventPoster* aEventPoster, + MMMASourceStreamListener* aListener): + CMMASourceStream(aEventPoster, aListener) +{ +} + + +inline void CMMADataSourceStream::ConstructL(JNIEnv* aJNIEnv,MMAFunctionServer* /*aEventSource*/, + jobject aJavaSourceStream) +{ + CMMASourceStream::ConstructL(aJNIEnv, aJavaSourceStream); + CreateDataBufferL(KMMAStreamRequestBufferSize); +} + +void CMMADataSourceStream::WriteL(const TUint8* aData, + TInt aLength, + TInt aState) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADataSourceStream::WriteL data length %d", aLength); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADataSourceStream::WriteL state %d", aState); + + if (!iRequest) + { + // there is no request to write + return; + } + + if (aState >= KErrNone) + { + if ((aState == CMMASourceStream::ECompleted) && + aLength == -1) + { + // Stream ended + iRequest->RequestBuffer() = 1; + } + else if ((iData->Length() == 0) && + (iRequest->DataPtr().Length() == 0)) + { + iRequest->DataPtr().Append(aData, aLength); + // read next + iEventPoster->PostEvent(iReadEvent, + CMMAEvent::ENotifyPriority); + return; + } + else if (iData->Length() == 0) + { + iData->Des().Append(aData, aLength); + } + } + + // complete read operation + CMMAStreamRequest* r = iRequest; + iRequest = NULL; + r->CompleteRead(aState); + LOG( EJavaMMAPI, EInfo, "MMA::CMMADataSourceStream::WriteL completed"); +} + +void CMMADataSourceStream::ResetData() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADataSourceStream::ResetData"); +} + +CMMAStreamRequest* CMMADataSourceStream::Request() +{ + return iRequest; +} + +void CMMADataSourceStream::Read(CMMAStreamRequest* aRequest) +{ + // Setting NULL, means that all read completes are ignored + if (!aRequest) + { + iRequest = NULL; + return; + } + + if (!iRequest) + { + iRequest = aRequest; + iRequest->RequestBuffer() = 0; + iReadEvent->SetLength(aRequest->DataPtr().MaxLength()); + + if (iData->Length() > 0) + { + // Previous read buffered data + iRequest->DataPtr().Append(*iData); + + // re-use buffer + iData->Des().SetLength(0); + } + + // data has been requested, note will be sent + iEventPoster->PostEvent(iReadEvent, CMMAEvent::ENotifyPriority); + } + // else java is already reading +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.dsa/cmmadsawindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.dsa/cmmadsawindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* in Direct Screen Access based displays for Helix engine. +* +*/ + + +#ifndef CMMADSAWINDOW_H +#define CMMADSAWINDOW_H + + +// INCLUDES +#include +#include +#include +#include "mmmadisplaywindow.h" +#include "mmafunctionserver.h" +#include "cmmaplayer.h" + +// CONSTANTS +const TInt KMMAVideoMinDimension = 32; // minimum video width and height + +// CLASS DECLARATION +/** +* This class implements MMMADisplayWindow functionality +* in Direct Screen Access based displays for Helix engine. +*/ +NONSHARABLE_CLASS(CMMADSAWindow): public CBase, + public MMMADisplayWindow +{ +public: // Constructors and destructors + static CMMADSAWindow* NewL( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer, + RMMFVideoPlayControllerCustomCommands* aVPCustomCommand); + + virtual ~CMMADSAWindow(); + +private: // Constructors and destructors + CMMADSAWindow( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer, + RMMFVideoPlayControllerCustomCommands* aVPCustomCommand); + + void ConstructL(); + +public: // New methods + TBool IsVisible() const; + +public: // Methods derived from MMMADisplayWindow + void SetDestinationBitmapL(CFbsBitmap* aBitmap); + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDrawRect(const TRect& aRect); + void SetDrawRectThread(const TRect& aRect); + const TRect& DrawRect(); + TSize WindowSize(); + void SetPosition(const TPoint& aPosition); + void SetVisible(TBool aVisible, TBool aUseEventServer = ETrue); + void SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType aThreadType); + const TRect& WindowRect(); + void ContainerDestroyed(); + /** + * Notifies window that any drawing + * via direct screen access must be aborted + */ + void AbortDSA(); + + /** + * Allows window to draw + * via direct screen access after MdcAbortDSA + */ + void ResumeDSA(); + +private: + static void StaticSetWindowPosition( + CMMADSAWindow* aWindow, + TPoint aPosition, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); + + static void SetWindowVisible( + CMMADSAWindow* aWindow, + TBool aVisible, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); + + static void StaticAbortDSA( + CMMADSAWindow* aWindow, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); + + static void StaticResumeDSA( + CMMADSAWindow* aWindow, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); +private: // Data + TRect iDrawRect; + TRect iClientRect; + + /** + * not owned, used for switching from UI thread to MMA thread + */ + MMAFunctionServer* iEventSource; + + /** + * We must depend on player's state because direct screen access may + * not be resumed before player is started. + */ + CMMAPlayer* iPlayer; + + /** + * not owned, used for controlling video position and visibility + */ + RMMFVideoPlayControllerCustomCommands* iVideoPlayControllerCustomCommands; + + /** + * Indicates if content need to be drawn. + */ + TBool iVisible; + + /** + * Indicates if DSA is aborted. + */ + TBool iDSAAborted; +}; + +#endif // CMMADSAWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.dsa/cmmavideoplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.dsa/cmmavideoplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing video. +* +*/ + + +#ifndef CMMAVIDEOPLAYER_H +#define CMMAVIDEOPLAYER_H + +// INCLUDES +#include "cmmaaudioplayer.h" +#include "mmmaguiplayer.h" +#include "mmmasnapshot.h" +#include "cmmadsawindow.h" + +// FORWARD DECLARATIONS +class MMAFunctionServer; + +// CONSTANTS +// Error code from MMF meaning that video is missing sound, +// but still can be played. +const TInt KNotCompleteVideoError = -12017; +_LIT(KMMAVideoPlayer, "VideoPlayer"); + +// CLASS DECLARATION +/** +* This class is used for playing video. +* +*/ + +NONSHARABLE_CLASS(CMMAVideoPlayer): public CMMAAudioPlayer, + public MMMAGuiPlayer, + public MMMASnapshot +{ +public: // Construction + static CMMAVideoPlayer* NewLC( + CMMAMMFResolver* aResolver); + + // Destructor + ~CMMAVideoPlayer(); + +protected: + // C++ constructor + CMMAVideoPlayer(CMMAMMFResolver* aResolver); + + void ConstructL(); + +public: // from CMMAPlayer + IMPORT_C void SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster); + void RealizeL(); + void PrefetchL(); + +protected: // from CMMAudioPlayer + IMPORT_C void ReadCompletedL(TInt aStatus, const TDesC8& aData); + void HandleEvent(const TMMFEvent& aEvent); + IMPORT_C const TDesC& Type(); + +public: // From MMMAGuiPlayer + IMPORT_C void SetDisplayL(MMMADisplay* aDisplay); + IMPORT_C TSize SourceSize(); + IMPORT_C void NotifyWithStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData); + + IMPORT_C MMMASnapshot* SnapshoterL(); + +public: // From MMMASnapshot + IMPORT_C MMMASnapshot::TEncoding TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings); + IMPORT_C CFbsBitmap* SnapshotBitmap(); + IMPORT_C HBufC8* SnapshotEncoded(); + +protected: // New methods + void CompletePrefetch(TInt aError); + void PrepareDisplay(); + void SourceSizeChanged(); + +protected: // Data + CMMADSAWindow* iDSAWindow; + RMMFVideoControllerCustomCommands iVideoControllerCustomCommands; + RMMFVideoPlayControllerCustomCommands iVideoPlayControllerCustomCommands; + +private: // Data + MMMADisplay* iDisplay; + + TSize iSourceSize; + + TFileName iFileExtension; + CFbsBitmap* iEmptySnapshotImage; + + CActiveSchedulerWait* iActiveSchedulerWait; +}; + +#endif // CMMAVIDEOPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmaemcaudioplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmaemcaudioplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + +#ifndef CMMAEMCAUDIOPLAYER_H +#define CMMAEMCAUDIOPLAYER_H + +// INCLUDES +#include "cmmaemcplayerbase.h" +#include "mmfbase.h" + +// CONSTANTS + +const TMdaPriorityPreference KMMAEMCPriorityPreference = + EMdaPriorityPreferenceTimeAndQuality; + +_LIT(KMMAEMCAudioPlayer, "EMCAudioPlayer"); + +// CLASS DECLARATION +/** +* This class is used for playing sounds +* +*/ + +NONSHARABLE_CLASS(CMMAEMCAudioPlayer): public CMMAEMCPlayerBase +{ +public: // Construction + /** + * Creates new player. + */ + static CMMAEMCAudioPlayer* NewLC( + CMMAEMCResolver* aResolver); + + // Destructor + IMPORT_C ~CMMAEMCAudioPlayer(); + +protected: + // C++ constructor + IMPORT_C CMMAEMCAudioPlayer(CMMAEMCResolver* aResolver); + IMPORT_C void ConstructL(); + +protected: // New methods + IMPORT_C virtual void PrefetchDataL(const TDesC8& aData); + IMPORT_C virtual void PrefetchFileL(); + IMPORT_C virtual void PlayCompleteL(TInt aError); + +public: // from CMMAPlayer + IMPORT_C void RealizeL(); + IMPORT_C void PrefetchL(); + + IMPORT_C const TDesC& Type(); + +public: // from CMMAPlayer/MMMASourceStreamListener + IMPORT_C void ReadCompletedL(TInt aStatus, const TDesC8& aData); +}; + +#endif // CMMAEMCAUDIOPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmaemcaudiovolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmaemcaudiovolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#ifndef CMMAEMCAUDIOVOLUMECONTROL_H +#define CMMAEMCAUDIOVOLUMECONTROL_H + +#include +#include "VolumeControl.h" +#include "cmmavolumecontrol.h" + +using multimedia::MVolumeControl; + +class CMMAEMCAudioPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + This class is used for setting volume to audio player + +----------------------------------------------------------------------------- +*/ + +NONSHARABLE_CLASS(CMMAEMCAudioVolumeControl): public CMMAVolumeControl +{ +public: // constructors and destructors + IMPORT_C static CMMAEMCAudioVolumeControl* NewL(CMMAEMCAudioPlayer& aPlayer); + +protected: + IMPORT_C CMMAEMCAudioVolumeControl(CMMAEMCAudioPlayer& aPlayer); + void ConstructL(); + + ~CMMAEMCAudioVolumeControl(); + +public: // from CMMAVolumeControl + IMPORT_C void DoSetLevelL(TInt aLevel); + IMPORT_C TInt DoGetLevelL(); + +private: // data + MVolumeControl* iVolCntrl; + + // not owned + CMMAEMCAudioPlayer& iPlayer; +}; + +#endif // CMMAEMCAUDIOVOLUMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmaemcplayerbase.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmaemcplayerbase.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,159 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + +#ifndef CMMAEMCPLAYERBASE_H +#define CMMAEMCPLAYERBASE_H + +// INCLUDES +#include +#include "cmmaplayer.h" +#include "e32base.h" +#include "f32file.h" +#include "StreamControl.h" +#include "Events.h" +//#include "ProgDLSource.h" +#include "MMControlFactory.h" +#include "ControlObserver.h" +#include "DataBufferSource.h" +#include "FileSource.h" +#include "DescriptorSource.h" +#include "DataBuffer.h" +#include "SinkControl.h" +#include "badesca.h" +#include "MimeTypes.h" +#include "StreamControlObserver.h" +#include "SourceControlObserver.h" + + +using multimedia ::MStreamControl; +using multimedia ::MControlObserver; +//using multimedia ::MProgDLSource; +using multimedia ::MDataBufferSource; +using multimedia ::MDescriptorSource; +using multimedia ::MDataBuffer; +using multimedia ::MControl; +using multimedia ::CMultimediaFactory; +using multimedia ::MSinkControl; +using multimedia ::MFileSource; +using multimedia::MSourceControlObserver; +using multimedia::MStreamControlObserver; + +class CMMAEMCResolver; +// CLASS DECLARATION +/** +* This is base class for players those use EMC +* +* +*/ + +NONSHARABLE_CLASS(CMMAEMCPlayerBase): public CMMAPlayer, + public MControlObserver +{ +protected: + // C++ constructor + CMMAEMCPlayerBase(CMMAEMCResolver* aResolver); + void ConstructL(); + + ~CMMAEMCPlayerBase(); +public: // new methods + /** + * Getter for StreamControl + */ + IMPORT_C MStreamControl * StreamControl(); + + /** + * Multimedia Factory getter + */ + IMPORT_C CMultimediaFactory* MMFactory(); + + /** + * Check whether this player is playing from a file locator + * @return ETrue if is a file player, EFalse otherwise + */ + TBool IsFilePlayer(); + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent); + void DeallocateL(); + void GetDuration(TInt64* aDuration); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + void CloseL(); + +private: //New methods + void CreateStreamL(); + void DetermineMimeTypeL(const TDesC& aFileName, TDes8& aMimeType); + void CleanupSource(); + void AddDataSourceToStreamL(); + +public: // from MControlObserver + void Event(MControl* aControl, + TUint aEventType, + TAny* aEventObject); + +protected: + + CActiveSchedulerWait* iActiveSchedulerWait; + + /** + * StreamControl infos, owned + */ + MStreamControl* iMStreamControl; + MDataBufferSource* iMDataBufferSource; + MDescriptorSource* iMDescriptorSource; + MFileSource* iMFileSource; + MSinkControl* iMAudioSink; + MStreamControl::TStreamState iPrevStreamControlState; + enum TSourceType + { + EFILESOURCE, + EDATABUFFERSOURCE, + EDESCRIPTORSOURCE + }; + TSourceType iSourceType; + RPointerArray iBuffers; + RArray iAvailable; + TBool iIsEOFReached; + TBool iAutoWriteBuffer; + TInt iBytesReadFromFile; + TInt iFileSizeInBytes; + CMultimediaFactory* iFactory; + + HBufC8* iMimeType; + HBufC8* iDescData; + + /** + * Filename used for playing directly from file, owned + */ + HBufC* iFileName; + + /** + * Cached media time + */ + TInt64 iMediaTime; + + /** + * The time that will be sent with CMMAPlayerEvent::EStarted + * (may be different from iMediaTime). + */ + TInt64 iStartedEventTime; +}; + +#endif // CMMAEMCPLAYERBASE_H + +// End of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmaemcplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmaemcplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating EMC-based players. +* +*/ + + +#ifndef CMMAEMCPLAYERFACTORY_H +#define CMMAEMCPLAYERFACTORY_H + +// INCLUDES +// #include Remove and replace with proper header file +#include "mmmaplayerfactory.h" + +class CMMAEMCResolver; + +// CLASS DECLARATION +/** +* This class is used for creating EMC-based players. +* +* +*/ +NONSHARABLE_CLASS(CMMAEMCPlayerFactory): public CBase, public MMMAPlayerFactory +{ +public: // Constructor and destructor + CMMAEMCPlayerFactory(); + ~CMMAEMCPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +protected: + /** + * Creates new CMMAPlayer instance with given resolver. + * @param aResolver Resolver that contains needed infos + * for creating player. + */ + virtual CMMAPlayer* CreatePlayerL(CMMAEMCResolver* aResolver) = 0; + + /** + * Returns list of allowed media IDs + */ + virtual void MediaIdsL(RArray& aMediaIds) = 0; + + /** + * Checks that is this protocol supported by this factory + */ + TBool IsSupportedProtocolL(const TDesC& aProtocol); + + /** + * Checks that is this content-type supported by this factory + */ + TBool IsSupportedContentTypeL(const TDesC& aContentType); +private: + /** + * File version of creating player from content type + */ + + CMMAPlayer* CreatePlayerL(const TDesC& aContentType, + const TDesC* aFileName); +#ifndef RD_JAVA_OMA_DRM_V2 + /** + * Tries to open DRM file + */ + CMMAPlayer* TryOpenDRMFileL(const TDesC& aFileName); +#endif // RD_JAVA_OMA_DRM_V2 + +}; + +#endif // CMMAEMCPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmaemcresolver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmaemcresolver.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,127 @@ +/* +* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +#ifndef CMMAEMCRESOLVER_H +#define CMMAEMCRESOLVER_H + +#include +#include "cmmaplayer.h" + +//Supported file extensions + +_LIT(K3g2FileExtension, ".3g2"); +_LIT(K3gpFileExtension, ".3gp"); +_LIT(KAacFileExtension, ".aac"); +_LIT(KAmrFileExtension, ".amr"); +_LIT(KAwbFileExtension, ".awb"); +_LIT(KM4aFileExtension, ".m4a"); +_LIT(KMp3FileExtension, ".mp3"); +_LIT(KMp4FileExtension, ".mp4"); +_LIT(KWmaFileExtension, ".wma"); +_LIT(KRmFileExtension, ".rm"); +_LIT(KRaFileExtension, ".ra"); + +const TInt KContentTypeMaxLength = 30; + + +// CLASS DECLARATION + +NONSHARABLE_CLASS(CMMAEMCResolver): public CBase + +{ +public: // Construction + /** + * Constructs a new mmf resolver object. + * @return The new object created. Note that the new object will be + * left on the cleanup stack. + */ + static CMMAEMCResolver* NewLC(); + +public: // New methods. + + HBufC* ContentTypeOwnership(); + + HBufC8* MimeTypeOwnership(); + + /** + * Returns content type + */ + HBufC* ContentType(); + + /** + * Sets filename + * @param aFileName File name to be set or NULL + */ + + void SetFileNameL(const TDesC* aFileName); + + /** + * Sets Mime Type + * @param aFileName File name to be set or NULL + */ + + void SetMimeTypeL(const TDesC* aFileName); + + /** + * Returns possible filename or NULL if not set + * Ownership is transfered. + * @return Content type or NULL if type is not available. + */ + HBufC* FileNameOwnership(); + + /** + * Get all supported content types. + * @param aMimeTypeArray Will contain supported mime types. + */ + void GetSupportedContentTypesL(CDesC16Array& aMimeTypeArray); + + +private: + + /** Finds content type from given File name. + */ + void ResolveContentTypeL(const TDesC& aFileName, TDes8& aMimeType); + + void ResolveContentTypeL(); + +private: + ~CMMAEMCResolver(); + +private: + + // Owned. Ownership can be transferred with ContentType method. + HBufC* iContentType; + + // Owned. Ownership can be transferred with MimeType method. + HBufC8* iMimeType; + + // Owned. Ownership can be transferred with FileName method. + HBufC* iFileName; + +public: // new method + void SetSourceInfoL(const HBufC8* aHeaderData); + +private: + TBool IsRealVideoTypeL(const TDesC8& aHeader); + + TBool IsRealMimeTypeSupported(const TDesC& aMimeType); + +private: // Data + const HBufC8* iHeaderData; // not owned +}; + +#endif // CMMAEMCRESOLVER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.emc/cmmamanager.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.emc/cmmamanager.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class uses player factories to generate different players +* +*/ + + +#ifndef CMMAMANAGER_H +#define CMMAMANAGER_H + +// EXTERNAL INCLUDES +#include + +// INTERNAL INCLUDES +#include "mmafunctionserver.h" +#include "mmmaplayerfactory.h" +//#include + +// FORWARD DECLARATIONS +class CMMAPlayer; + +// CLASS DECLARATION +/** +* This class uses player factories to generate different types of players. +*/ + +NONSHARABLE_CLASS(CMMAManager): public CBase, public MMMAPlayerFactory +{ +public: // Constructors and destructors + /** + * Deletes all owned members. + */ + virtual ~CMMAManager(); + + /** + * Static constructor + */ + static void StaticCreateManagerL(CMMAManager** aManager, + TInt aMIDletSuiteID); + +protected: + /** + * Initializes member variables to defaults. + */ + CMMAManager(); + + /** + * Second phase construct. + */ + void ConstructL(TInt aMIDletSuiteID); + +public: // From MMMAPlayerFactory + + /** + * @see MMAPlayerFactory + */ + + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); +public: // new methods + + void SetSourceInfoL(const TUint8* header, TInt aLength); + + /** + * Adds player factory to manager + * + * @param aPlayerFactory handle to player factory + */ + IMPORT_C void AddPlayerFactoryL(MMMAPlayerFactory* aPlayerFactory); + +private: + /** + * Array of player factories. Owned. + */ + RPointerArray< MMMAPlayerFactory > iPlayerFactories; +}; + +#endif // CMMAMANAGER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.mmf/cmmamanager.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.mmf/cmmamanager.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class uses player factories to generate different players +* +*/ + + +#ifndef CMMAMANAGER_H +#define CMMAMANAGER_H + +// EXTERNAL INCLUDES +#include + +// INTERNAL INCLUDES +#include "MMAFunctionServer.h" +#include "MMMAPlayerFactory.h" + + +// FORWARD DECLARATIONS +class CMMAPlayer; + +// CLASS DECLARATION +/** +* This class uses player factories to generate different types of players. +*/ + +NONSHARABLE_CLASS(CMMAManager): public CBase, public MMMAPlayerFactory +{ +public: // Constructors and destructors + /** + * Deletes all owned members. + */ + virtual ~CMMAManager(); + + /** + * Static constructor + */ + static void StaticCreateManagerL(CMMAManager** aManager, + TInt aMIDletSuiteID); + +protected: + /** + * Initializes member variables to defaults. + */ + CMMAManager(); + + /** + * Second phase construct. + */ + void ConstructL(TInt aMIDletSuiteID); + +public: // From MMMAPlayerFactory + + /** + * @see MMAPlayerFactory + */ + + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); +public: // new methods + + /** + * Adds player factory to manager + * + * @param aPlayerFactory handle to player factory + */ + IMPORT_C void AddPlayerFactoryL(MMMAPlayerFactory* aPlayerFactory); + +private: + /** + * Array of player factories. Owned. + */ + RPointerArray< MMMAPlayerFactory > iPlayerFactories; +}; + +#endif // CMMAMANAGER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.nga/cmmasurfacewindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.nga/cmmasurfacewindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,364 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* in graphics surface based displays for Helix engine. +* +*/ + +#ifndef CMMASURFACEWINDOW_H +#define CMMASURFACEWINDOW_H + + +// INCLUDES +#include +//#include +#include +#include +#include + +#include +#include +#include "mmmadisplaywindow.h" +#include "mmafunctionserver.h" +#include "cmmaplayer.h" +#include "cmmacanvasdisplay.h" + +// FORWARD DECLARATIONS +class RWsSession; +class CWsScreenDevice; +class RWindowBase; +class MMMADisplay; + +// CONSTANTS +const TInt KMMAVideoMinDimension = 32; // minimum video width and height + +// CLASS DECLARATION +/** +* This class implements MMMADisplayWindow functionality +* in video display to graphics surface based displays for Helix engine. +*/ +NONSHARABLE_CLASS(CMMASurfaceWindow): public CBase, + public MMMADisplayWindow/*, + public MUiEventConsumer*/ +{ +public: + /** + * indicates what method needs to be called in UI thread context. + */ + enum TUiCallbackType + { + ERemoveSurface = 1, + ESetDrawRect, + EInitVideoDisplay, + EResetSurfaceParameters, + ESetChangedSurfaceParameters, + ECleanVideoDisplay, + EDestroyWindow + }; + +private: + /** + * indicates different video display initialization states + * + * video display state transition can happen in following order: + * 1. when MIDlet code is: + * Player player = Manager.createPlayer(..); + * player.realize(); + * VideoControl vc = (VideoControl)player.getControl("VideoControl"); + * vc.initDisplayMode(..); + * player.start(); + * + * EUIResourcesAndSurfaceParametersNotSet + * EUIResourcesSetAndSurfaceParametersNotSet + * EUIResourcesAndSurfaceParametersSet + * + * OR + * + * 2. when MIDlet code is: + * Player player = Manager.createPlayer(..); + * player.start(); + * VideoControl vc = (VideoControl)player.getControl("VideoControl"); + * vc.initDisplayMode(..); + * + * EUIResourcesAndSurfaceParametersNotSet + * ESurfaceParametersSetAndUIResourcesNotSet + * EUIResourcesAndSurfaceParametersSet + * + * InitVideoDisplayL() should be called only after EUIResourcesAndSurfaceParametersSet + * state is reached. ie both UI resources and surface parameters becomes available. + * + * 3. for below mentioned MIDlet code case: + * Player player = Manager.createPlayer(..); + * player.start(); // state transition is + * + * EUIResourcesAndSurfaceParametersNotSet + * ESurfaceParametersSetAndUIResourcesNotSet + * note that InitVideoDisplayL() is not called and video is not displayed in this case. + */ + enum TVideoDisplayInitState + { + /** + * indicates ui resources and surface parameters are not yet set. + * UI resources are RWindowBase, CWsScreenDevice and RWsSession. + * Surface parameters are TSurfaceId, TRect and TVideoAspectRatio. + */ + EUIResourcesAndSurfaceParametersNotSet = 1, + /** + * indicates UI resources are set and surface parameters not yet set. + * UI resources are set when initDisplayMode() is called and RWindow becomes available. + */ + EUIResourcesSetAndSurfaceParametersNotSet, + /** + * indicates UI resources are not yet set and surface parameters are set. + * Surface parameters are set when player.start() is called. + */ + ESurfaceParametersSetAndUIResourcesNotSet, + /** + * indicates UI resources and surface parameters are set. + */ + EUIResourcesAndSurfaceParametersSet + }; + +public: // Constructors and destructors + static CMMASurfaceWindow* NewL( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); + + virtual ~CMMASurfaceWindow(); + +private: // Constructors and destructors + CMMASurfaceWindow( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer); + +public: // Methods derived from MMMADisplayWindow + void SetDestinationBitmapL(CFbsBitmap* aBitmap); + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDrawRect(const TRect& aRect); + void SetDrawRectThread(const TRect& aRect); + const TRect& DrawRect(); + TSize WindowSize(); + void SetPosition(const TPoint& aPosition); + void SetVisible(TBool aVisible, TBool aUseEventServer = ETrue); + void SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType aThreadType); + void SetVideoCropRegion(const TRect& aRect); + void SetRWindowRect(const TRect& aRect, MMMADisplay::TThreadType aThreadType); + const TRect& WindowRect(); + void ContainerDestroyed(); + void ContainerSet(); +/* +public: // from base class MUiEventConsumer + void MdcDSAResourcesCallback(RWsSession &aWs, + CWsScreenDevice &aScreenDevice, + RWindowBase &aWindow); + +*/ + void UICallback(TInt aCallbackId); + public: + virtual void ProcureWindowResourcesFromQWidget(RWsSession * aWs, + CWsScreenDevice* aScreenDevice, + RWindowBase* aWindow); + + virtual CMMAPlayer* UiPlayer(); + +public: // New methods + TBool IsVisible() const; + void SetDisplay(MMMADisplay *aDisplay); + + /** + * copies surface paramaters and intializes video display if + * RWindow is already set, ie if intDisplayMode already called in midlet. + * invokes InitVideoDisplayL() in UI thread context. + * + * @params aSurfaceId, aCropRect, aPixelAspectRatio surface paramaters. + */ + void SetSurfaceParameters(const TSurfaceId& aSurfaceId, + const TRect& aCropRect, + const TVideoAspectRatio& aPixelAspectRatio); + + /** + * invokes DoRemoveSurface() in UI thread context. + */ + void RemoveSurface(); + + /** + * updates members variables with new surface parameters and invokes + * DoSetChangedSurfaceParameters() in UI thread context. + * + * @params aSurfaceId, aCropRect, aPixelAspectRatio surface paramaters. + */ + void SetChangedSurfaceParameters(const TSurfaceId& aSurfaceId, + const TRect& aCropRect, + const TVideoAspectRatio& aPixelAspectRatio); + +private: // New methods + /** + * scales video to the required size. + * This method must always be executed in UI-Thread context. + * + * @param aRect rectangular size to which the video has to be scaled. + */ + void ScaleVideoL(const TRect& aRect); + + /** + * starts video rendering to a graphics surface. + * restarts video rendering to a graphics surafce with changed parameters. + * This method must always be executed in UI-Thread context. + */ + void RedrawVideoL(); + + /** + * utility function to invoke RedrawVideoL() function with in a TRAP harness. + * + * @param aSurfaceWindow reference to CMMASurfaceWindow instance on which RedrawVideoL() + * has to be invoked + * @return TInt Symbian OS error code, KErrNone if no error + */ + static TInt StaticRedrawVideo(CMMASurfaceWindow& aSurfaceWindow); + + /** + * creates new instance of CMediaClientVideoDisplay and intializes it with + * surfaces and windows. + * This method must always be executed in UI-Thread context. + */ + void InitVideoDisplayL(); + + /** + * updates CMediaClientVideoDisplay instance with new surface parameters. + * This method must always be executed in UI-Thread context. + */ + void DoSetChangedSurfaceParameters(); + + /** + * resets CMediaClientVideoDisplay instance with new surface parameters. + * This method must always be executed in UI-Thread context. + */ + void DoResetSurfaceParameters(); + + /** + * Removes Surface from RWindow + * This method must always be executed in UI-Thread context. + */ + void DoRemoveSurface(); + + /** + * removes surfaces and windows from CMediaClientVideoDisplay instance + * and deletes the instance. + * This method must always be executed in UI-Thread context. + */ + void CleanVideoDisplay(); + + /** + * Deletes this object. + * + * @since S60 v5.2 + */ + void Destroy(); + +private: // Data + /** + * drawing area where video is rendered. + */ + TRect iContentRect; + + /** + * parent rectangle used for positioning contentRect. + */ + TRect iParentRect; + + /** + * Symbian RWindow rect + */ + TRect iRWindowRect; + + /** + * not owned, used for switching from UI thread to MMA thread + */ + MMAFunctionServer* iEventSource; + + /** + * We must depend on player's state because direct screen access may + * not be resumed before player is started. + * not owned. + */ + CMMAPlayer* iPlayer; + + /** + * crop rectangle of video + */ + TRect iVideoCropRegion; + + /** + * owned, used for video display on surface + * this instance is created & accessed in UI thread only. + */ + CMediaClientVideoDisplay* iMediaClientVideoDisplay; + + /** + * Display instance used to invoke UI callbacks. + * Not owned. + */ + MMMADisplay* iDisplay; + + /** + * Window server session used by UI thread. + * Adjustable and usable from UI thread only. + * Not owned. + */ + RWsSession* iWs; + + /** + * Screen device used by UI thread. + * Adjustable and usable from UI thread only. + * Not owned. + */ + CWsScreenDevice* iScreenDevice; + + /** + * Window where video is displayed. + * Adjustable and usable from UI thread only. + * From UI thread. + * Not owned. + */ + RWindowBase* iWindow; + + /** + * The surface to be created for composition. + */ + TSurfaceId iSurfaceId; + + /** + * The dimensions of the crop rectangle, relative to the video image. + */ + TRect iCropRect; + + /** + * The pixel aspect ratio to display video picture. + */ + TVideoAspectRatio iPixelAspectRatio; + + /** + * indicates the video display initialization state. + * + */ + TVideoDisplayInitState iVideoDisplayInitState; + + /** + * Indicates if content need to be drawn. + */ + TBool iVisible; + +}; + +#endif // CMMASURFACEWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc.nga/cmmavideoplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc.nga/cmmavideoplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,124 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing video. +* +*/ + +#ifndef CMMAVIDEOPLAYER_H +#define CMMAVIDEOPLAYER_H + +// INCLUDES +#include "cmmaaudioplayer.h" +#include "mmmaguiplayer.h" +#include "mmmasnapshot.h" +#include "cmmasurfacewindow.h" +//#include + +// FORWARD DECLARATIONS +class MMAFunctionServer; + +// CONSTANTS +// Error code from MMF meaning that video is missing sound, +// but still can be played. +const TInt KNotCompleteVideoError = -12017; +_LIT(KMMAVideoPlayer, "VideoPlayer"); + +// CLASS DECLARATION +/** +* This class is used for playing video. +* +*/ +NONSHARABLE_CLASS(CMMAVideoPlayer): public CMMAAudioPlayer, + public MMMAGuiPlayer, + public MMMASnapshot +{ +public: // Construction + static CMMAVideoPlayer* NewLC( + CMMAMMFResolver* aResolver); + + // Destructor + ~CMMAVideoPlayer(); + +protected: + // C++ constructor + CMMAVideoPlayer(CMMAMMFResolver* aResolver); + + void ConstructL(); + +public: // from CMMAPlayer + IMPORT_C void SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster); + void RealizeL(); + void PrefetchL(); + +protected: // from CMMAudioPlayer + IMPORT_C void ReadCompletedL(TInt aStatus, const TDesC8& aData); + void HandleEvent(const TMMFEvent& aEvent); + IMPORT_C const TDesC& Type(); + +public: // From MMMAGuiPlayer + IMPORT_C void SetDisplayL(MMMADisplay* aDisplay); + IMPORT_C TSize SourceSize(); + IMPORT_C void NotifyWithStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData); + + IMPORT_C MMMASnapshot* SnapshoterL(); + +public: // From MMMASnapshot + IMPORT_C MMMASnapshot::TEncoding TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings); + IMPORT_C CFbsBitmap* SnapshotBitmap(); + IMPORT_C HBufC8* SnapshotEncoded(); + + protected: // New methods + void CompletePrefetch( TInt aError ); + void PrepareDisplay(); + public: + void SourceSizeChanged(); + +protected: // Data + CMMASurfaceWindow* iSurfaceWindow; + RMMFVideoControllerCustomCommands iVideoControllerCustomCommands; + RMMFVideoPlayControllerCustomCommands iVideoPlayControllerCustomCommands; + RMMFVideoPlaySurfaceSupportCustomCommands iVideoPlaySurfaceSupportCustomCommands; + +private: // Data + // not owned + MMMADisplay* iDisplay; + + TSize iSourceSize; + + TFileName iFileExtension; + + /** + * struct to keep track of Surface + */ + struct MMASurface + { + // owned, should be freed using + // RMMFVideoPlaySurfaceSupportCustomCommands::SurfaceRemoved(). + TSurfaceId iPrevSurfaceId; + TBool iPrevSurfaceAvailable; + } iMMASurface; + + // owned + CFbsBitmap* iEmptySnapshotImage; + + // owned + CActiveSchedulerWait* iActiveSchedulerWait; +}; + +#endif // CMMAVIDEOPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudiometadatacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudiometadatacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAAudioMetaDataControl is a concrete class for getting +* metadata from an audio media. +* +*/ + + +#ifndef CMMAAUDIOMETADATACONTROL_H +#define CMMAAUDIOMETADATACONTROL_H + +// INCLUDES +#include + +#include "cmmametadatacontrol.h" + +// CLASS DECLARATION +/** +* This is a concrete class for getting metadata from an audio media. +* +* +*/ + +NONSHARABLE_CLASS(CMMAAudioMetaDataControl): public CMMAMetaDataControl +{ +public: + CMMAAudioMetaDataControl(RMMFController& aController); + +protected: // from CMMAMetaDataControl + + TInt KeyCountL(); + HBufC* KeyL(TInt aIndex); + + HBufC* KeyValueL(const TDesC& aKey); + +private: + RMMFController& iController; +}; + +#endif // CMMAAUDIOMETADATACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudioplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudioplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,112 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + +#ifndef CMMAAUDIOPLAYER_H +#define CMMAAUDIOPLAYER_H + +// INCLUDES +#include "cmmammfplayerbase.h" +//#include + + +_LIT(KMMAAudioPlayer, "AudioPlayer"); + +/** +Mixin class for playback complete notifications. +*/ +class MPlaybackCompletedCallback +{ +public: + virtual void HandlePlaybackCompleteL() = 0; + virtual void ErrorPlaybackComplete(TInt aError) = 0; +}; + +/** +Active object used for give MMF server time to complete its playback +*/ +class CPlaybackCompletedCallback : public CTimer +{ +public:// Constructor and destructor + static CPlaybackCompletedCallback* NewL(MPlaybackCompletedCallback& aObs); + ~CPlaybackCompletedCallback(); + +public: // new methods + void Callback(); + +public: // From CTimer + void RunL(); + TInt RunError(TInt aError); + +private: // Constructor + CPlaybackCompletedCallback(MPlaybackCompletedCallback& aObs); + +private: // Data + MPlaybackCompletedCallback& iObs; +}; + +// CLASS DECLARATION +/** +* This class is used for playing sounds +* +*/ + +NONSHARABLE_CLASS(CMMAAudioPlayer): public CMMAMMFPlayerBase, + public MPlaybackCompletedCallback + +{ +public: // Construction + /** + * Creates new player. + */ + static CMMAAudioPlayer* NewLC( + CMMAMMFResolver* aResolver); + + // Destructor + ~CMMAAudioPlayer(); + +protected: + // C++ constructor + CMMAAudioPlayer(CMMAMMFResolver* aResolver); + void ConstructL(); + +protected: // New methods + IMPORT_C virtual void PrefetchDataL(const TDesC8& aData); + IMPORT_C virtual void PrefetchFileL(); + IMPORT_C virtual void PlayCompleteL(TInt aError); + +public: // from CMMAPlayer + void RealizeL(); + void PrefetchL(); + + const TDesC& Type(); + +public: // from CMMAPlayer/MMMASourceStreamListener + void ReadCompletedL(TInt aStatus, const TDesC8& aData); + +public: // from MMMFControllerEventMonitorObserver + void HandleEvent(const class TMMFEvent& aEvent); + +public: // from MPlaybackCompletedCallback + IMPORT_C void HandlePlaybackCompleteL(); + IMPORT_C void ErrorPlaybackComplete(TInt aError); + +private: // data + // Owned playback callback active object + CPlaybackCompletedCallback* iPlaybackCompleted; +}; + +#endif // CMMAAUDIOPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudioplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudioplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating wav player. +* +*/ + + +#ifndef CMMAAUDIOPLAYERFACTORY_H +#define CMMAAUDIOPLAYERFACTORY_H + +// INCLUDES +#include "cmmammfplayerfactory.h" + +// CLASS DECLARATION +/** +* This class is used for creating wav player. +* +* +*/ + +NONSHARABLE_CLASS(CMMAAudioPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Constructor and destructor + static CMMAAudioPlayerFactory* NewLC(); + ~CMMAAudioPlayerFactory(); + +private: // Constructor + CMMAAudioPlayerFactory(); + +public: // From CMMAMMFPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + void MediaIdsL(RArray& aMediaIds); + +}; + +#endif // CMMAAUDIOPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudiorecordcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudiorecordcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: RecordControl for AudioRecorder +* +*/ + + +#ifndef CMMAAUDIORECORDCONTROL_H +#define CMMAAUDIORECORDCONTROL_H + +// INCLUDES +#include "cmmarecordcontrol.h" +#include "cmmaaudiorecorder.h" + +// CLASS DECLARATION +/** +* RecordControl for AudioRecorder +* +* +*/ + +NONSHARABLE_CLASS(CMMAAudioRecordControl): public CMMARecordControl, + public MMMFControllerEventMonitorObserver +{ +public: + static CMMAAudioRecordControl* NewL(CMMAAudioRecorder* aRecorder); + ~CMMAAudioRecordControl(); + +protected: + CMMAAudioRecordControl(CMMAAudioRecorder* aRecorder); + +public: // From CMMARecordControl + void InitializeL(); + void DoStartRecordL(); + void DoStopRecordL(); + void DoResetL(); + TInt SetRecordSizeLimitL(TInt aSize); + +public: // From MMMFControllerEventMonitorObserver + void HandleEvent(const TMMFEvent& aEvent); + +private: // data + CMMAAudioRecorder* iRecorder; // not owned +}; + + +#endif // CMMAAUDIORECORDCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudiorecorder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudiorecorder.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for recording Audio +* +*/ + + +#ifndef CMMAAUDIORECORDER_H +#define CMMAAUDIORECORDER_H + +#include +#include "cmmammfplayerbase.h" +#include "cmmaplayerproperties.h" +#include "tmmaparametervalidator.h" +#include "rmmatempfile.h" + +class CMMAOutputStream; + +_LIT(KMMAAudioRecorder, "AudioRecorder"); + +// CLASS DECLARATION +/** +* This class is used for recording Audio +* +* +*/ +NONSHARABLE_CLASS(CMMAAudioRecorder): public CMMAMMFPlayerBase +{ +public: // Construction + static CMMAAudioRecorder* NewLC( + CMMAMMFResolver* aResolver, + CMMAAudioSettings* aAudioSettings, + TInt aMIDletSuiteID); + + // Destructor + ~CMMAAudioRecorder(); + +protected: + // C++ constructor + CMMAAudioRecorder( + CMMAMMFResolver* aResolver, TInt aMIDletSuiteID); + +protected: // new methods + void DoOpenL(); + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent = ETrue); + void PrefetchL(); + void GetDuration(TInt64* aDuration); + const TDesC& Type(); + void DeallocateL(); + +public: // new methods, for CMMAAudioRecordControl + void InitializeL(RFile* aFile, + MMMFControllerEventMonitorObserver* aObserver); + void Deinitialize(); + + void StartRecordL(); + void StopRecordL(); + void ResetL(); + TInt SetRecordSizeLimitL(TInt aSize); + +public: // from MMMFControllerEventMonitorObserver + void HandleEvent(const class TMMFEvent& aEvent); + +private: + // owned + CMMAAudioSettings* iSettings; + + RMMFAudioRecordControllerCustomCommands iAudioRecordControllerCustomCommands; + RMMFAudioControllerCustomCommands iAudioControllerRecCustomCommands; + + CMMAOutputStream* iOutputStream; + + TInt iRecordSizeLimit; + + // error code returned from RMMFController::Pause method. Used check if + // setting position is needed before recording. + TInt iPauseError; + + // Data sink info + TMMFMessageDestination iSinkInfo; + + // File to record + RFile iFile; + + // Pass events ahead + MMMFControllerEventMonitorObserver* iObserver; + + // Supplier of current controller + TPtrC iSupplier; + + // Wait for native events + CActiveSchedulerWait* iWait; + TInt iError; + + TBool iResetController; + + // flag to hold EOF status + TBool iEOFReached; +}; + +#endif // CMMAAUDIORECORDER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudiorecorderfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudiorecorderfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating audio recorder +* +*/ + + +#ifndef CMMAAUDIORECORDERFACTORY_H +#define CMMAAUDIORECORDERFACTORY_H + +// INCLUDES +#include "cmmammfplayerfactory.h" +#include "tmmaparametervalidator.h" + +// CLASS DECLARATION +/** +* This class is used for creating audio recorder +* +* +*/ + +NONSHARABLE_CLASS(CMMAAudioRecorderFactory): public CMMAMMFPlayerFactory +{ +public: // Constructors and destructor + static CMMAAudioRecorderFactory* NewLC(TInt aMIDletSuiteID); + ~CMMAAudioRecorderFactory(); + +private: // Constructor + CMMAAudioRecorderFactory(TInt aMIDletSuiteID); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + +public: // From CMMAMMFPlayerFactory + + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + + + void MediaIdsL(RArray& aMediaIds); + + + void PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection); + +private: // Data + CMMAAudioSettings* iSettings; // Owned settings + TInt iMIDletSuiteID; + +}; + +#endif // CMMAAUDIORECORDERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaaudiovolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaaudiovolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#ifndef CMMAAUDIOVOLUMECONTROL_H +#define CMMAAUDIOVOLUMECONTROL_H + +#include +#include "cmmavolumecontrol.h" +//#include +class CMMAAudioPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + This class is used for setting volume to audio player + +----------------------------------------------------------------------------- +*/ + +NONSHARABLE_CLASS(CMMAAudioVolumeControl): public CMMAVolumeControl +{ +public: + IMPORT_C static CMMAAudioVolumeControl* NewL(CMMAAudioPlayer* aPlayer); + +protected: + CMMAAudioVolumeControl(CMMAAudioPlayer* aPlayer); + void ConstructL(); + +public: // from CMMAVolumeControl + void DoSetLevelL(TInt aLevel); + TInt DoGetLevelL(); + +private: + RMMFAudioPlayDeviceCustomCommands iAudioPlayDeviceCommands; +}; + +#endif // CMMAAUDIOVOLUMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmabitmapwindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmabitmapwindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This abstract class implements MMMADisplayWindow functionality +* in CFbsBitmap based displays. +* +*/ + + +#ifndef CMMABITMAPWINDOW_H +#define CMMABITMAPWINDOW_H + +// INCLUDES +#include "mmmadisplaywindow.h" + +// CONSTANTS + +// FORWARD DECLARATIONS +class CFbsBitmap; +class CFbsBitmapDevice; +class CGraphicsContext; + +// CLASS DECLARATION +/** +* This abstract class implements MMMADisplayWindow functionality in +* CFbsBitmap based displays. +* +* +*/ + + +NONSHARABLE_CLASS(CMMABitmapWindow): public CBase, + public MMMADisplayWindow +{ +public: // Constructors and destructors + ~CMMABitmapWindow(); // Destructor () + + static CMMABitmapWindow* NewL(); + +protected: // Constructors and destructors + // Default constructor, protected to allow derivation + CMMABitmapWindow(); + +public: // Methods derived from MMMADisplayWindow + void SetDestinationBitmapL(CFbsBitmap* aBitmap); + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDrawRect(const TRect& aRect); + void SetDrawRectThread(const TRect& aRect); + const TRect& DrawRect(); + TSize WindowSize(); + void SetPosition(const TPoint& aPosition); + void SetVisible(TBool aVisible, TBool aUseEventServer = ETrue); + void SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType aThreadType); + const TRect& WindowRect(); + +protected: // Data + /** + * Pointer to the bitmap that is used for drawing. + * iBitmap is owned by this class. + */ + CFbsBitmap* iBitmap; + + /** + * Owned bitmap device + */ + CFbsBitmapDevice* iBitmapDevice; + + /** + * Owned bitmap context + */ + CGraphicsContext* iBitmapContext; + + /** + * Actual area used for drawing. Set by SetDrawRect method. + */ + TRect iDrawRect; + TRect iClientRect; + + inline TDisplayWindowType GetDisplayWindowType() const + { + return EDisplayWindowTypeIsBitmap; + } +}; + +#endif // CMMABITMAPWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmacameraplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmacameraplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,157 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing camera. +* +*/ + + +#ifndef CMMACAMERAPLAYER_H +#define CMMACAMERAPLAYER_H + +// INCLUDES +#include +#include "cmmaplayer.h" +#include "mmmaguiplayer.h" +#include "mmmasnapshot.h" +#include "cmmacamerawindow.h" + +// CONSTANTS +_LIT(KMMACameraPlayer, "CameraPlayer"); + +// CLASS DECLARATION +/** +* This class is used for playing camera. +* +* +*/ + +NONSHARABLE_CLASS(CMMACameraPlayer): public CMMAPlayer, + public MMMAGuiPlayer, + public MMMASnapshot, + public MCameraObserver +{ +public: // Construction + /** + * Creates new CMMACameraPlayer for the camera at certain index. + * Index must be smaller CCamera::CamerasAvailable(). + * @param aCameraIndex Index of the camera. + */ + static CMMACameraPlayer* NewLC(TInt aCameraIndex); + + // Destructor + ~CMMACameraPlayer(); + +protected: + // C++ constructor + CMMACameraPlayer(); + void ConstructL(TInt aCameraIndex); + +private: // new methods + TInt64 CurrentTime(); + void ResolveViewFinderSizeL(TSize& aSize); + void ResolveScreenSizeL(TSize& aSize); + void ResolveCaptureSizes(const CCamera::TFormat aFormat, + const TInt aNumImageSizesSupported, + const TSize& aRequestSize, + TSize& aSourceSize, + TInt& aSourceIndex, + TInt& aLargestIndex); + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent); + void DeallocateL(); + void RealizeL(); + void PrefetchL(); + void GetDuration(TInt64* aDuration); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + void CloseL(); + const TDesC& Type(); +public: // From MCameraObserver + void ReserveComplete(TInt aError); + void PowerOnComplete(TInt aError); + void ViewFinderFrameReady(CFbsBitmap& aFrame); + + void ImageReady(CFbsBitmap* aBitmap, + HBufC8* aData, + TInt aError); + + void FrameBufferReady(MFrameBuffer* aFrameBuffer, + TInt aError); + +public: // From MMMAGuiPlayer + void SetDisplayL(MMMADisplay* aDisplay); + TSize SourceSize(); + void NotifyWithStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData); + MMMASnapshot* SnapshoterL(); + +public: // From MMMASnapshot + MMMASnapshot::TEncoding TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings); + CFbsBitmap* SnapshotBitmap(); + HBufC8* SnapshotEncoded(); + +public: // New methods + TInt CameraHandle(); + /** + * Disables or enables viewfinder stopping. + * Needed when using recording. + * + * @param aStopViewFinder If true viewfinder will be really stopped. + */ + void SetViewFinderMode(TBool aStopViewFinder); + +private: // Data + /** + * Window used to render viewfinder. + * Owned. + */ + CMMACameraWindow* iWindow; + + /** + * Camera instance used for taking snapshots and recording. + * iWindow uses this to create duplicated camera instance. + * Owned. + */ + CCamera* iCamera; + MMMADisplay* iDisplay; + + // index to be used for size enumeration + TInt iSourceSizeIndex; + + TInt64 iMediaTime; + TInt64 iStartTime; + + TRequestStatus* iSnapshotStatus; + + // Owned. + CFbsBitmap* iSnapshotBitmap; + HBufC8* iSnapshotEncoded; + + TSize iSize; + TBool iStopViewFinder; + + // inner class for waiting realize, owned + class CRealizeWait : public CActiveSchedulerWait + { + public: + TInt iError; + }; + CRealizeWait* iRealizeWait; +}; + +#endif // CMMACAMERAPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmacameraplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmacameraplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating camera players. +* +*/ + + +#ifndef CMMACAMERAPLAYERFACTORY_H +#define CMMACAMERAPLAYERFACTORY_H + +// INCLUDES +#include +#include "cmmammfplayerfactory.h" +#include "tmmaparametervalidator.h" + +// CLASS DECLARATION +/** +* This class is used for creating camera players. +* +* +*/ + +NONSHARABLE_CLASS(CMMACameraPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Construction + static CMMACameraPlayerFactory* NewLC(); + ~CMMACameraPlayerFactory(); + +private: + CMMACameraPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +public: // From CMMAMMFPlayerFactory + + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + + + void MediaIdsL(RArray& aMediaIds); + + void PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection); + +private: // Data + CMMAAudioSettings* iAudioSettings; // Owned audio settings + TMMAVideoSettings iVideoSettings; // Video settings + TInt iCameraIndex; +}; + +#endif // CMMACAMERAPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmacamerawindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmacamerawindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,368 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* for Camera viewfinder usage. +* +*/ + + +#ifndef CMMACAMERAWINDOW_H +#define CMMACAMERAWINDOW_H + +// INCLUDES +#include +//#include +#include +#include "mmmadisplaywindow.h" +#include "mmmadisplay.h" +#include "jni.h" +#include "cmmacanvasdisplay.h" +// CONSTANTS + +// FORWARD DECLARATIONS +class CFbsBitmap; +class RWsSession; +class CWsScreenDevice; +class RWindowBase; +class MMMADisplay; +class CMMACanvasDisplay; + +// CLASS DECLARATION +/** +* This class implements MMMADisplayWindow functionality +* to use with CMMACameraPlayer. +* It duplicates its camera instance within the UI thread +* and displays the viewfinder using the UI +* DirectScreenAccess resources. +* +* @since S60 v5.0 +*/ + + +NONSHARABLE_CLASS(CMMACameraWindow): public CBase, + public MMMADisplayWindow, + public MCameraObserver, + // public MUiEventConsumer, + public MDirectScreenAccess +{ +public: + enum TUiCallbackType + { + EDeleteViewFinder = 1, + EHideViewFinder, + EShowViewFinder, + EResetViewFinder, + EDestroyWindow + }; + + /** + * Two-phased constructor. + * + * @param aCameraHandle A handle to existing CCamera instance. + */ + static CMMACameraWindow* NewL(TInt aCameraHandle); + + + /** + * Destructor. + */ + ~CMMACameraWindow(); + + /** + * Gets an information if the DirectViewFinder is started + * + * @since S60 v5.0 + * @return ETrue if DirectViewFinder is active + */ + TBool ViewFinderActive(); + + /** + * Notifies window about Started state change + * + * @since S60 v5.0 + * @param aStarted Indicates that camera player is in started state + */ + void SetStarted(TBool aStarted); + + /** + * Sets iDisplay + * Used to invoke callbacks in UI thread + * + * @since S60 v5.0 + * @param "aDisplay" A Display to be used for callbacks. + * When set, the duplicated CCamera is created in UI thread + * and the necessary DSA resources are got. + * When replacing an old Display (set earlier) + * all the old resources are deleted. + * NULL deletes all allocated UI resources. + */ + void SetDisplay(MMMADisplay *aDisplay); + + +// from base class MMMADisplayWindow + void SetDestinationBitmapL(CFbsBitmap* aBitmap); + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDrawRect(const TRect& aRect); + void SetDrawRectThread(const TRect& aRect); + const TRect& DrawRect(); + TSize WindowSize(); + void SetPosition(const TPoint& aPosition); + void SetVisible(TBool aVisible, TBool aUseEventServer = ETrue); + void SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType aThreadType); + void SetRWindowRect(const TRect& aRect, MMMADisplay::TThreadType aThreadType); + const TRect& WindowRect(); + TDisplayWindowType GetDisplayWindowType() const; + TBool IsVisible() const; + void ContainerSet(); + void ContainerDestroyed(); + + +// from base class MCameraObserver + void ReserveComplete(TInt aError); + void PowerOnComplete(TInt aError); + void ViewFinderFrameReady(CFbsBitmap& aFrame); + + void ImageReady(CFbsBitmap* aBitmap, + HBufC8* aData, + TInt aError); + + void FrameBufferReady(MFrameBuffer* aFrameBuffer, + TInt aError); + + +// from base class MUiEventConsumer + /* void MdcDSAResourcesCallback( + RWsSession &aWs, + CWsScreenDevice &aScreenDevice, + RWindowBase &aWindow); + */ + void UICallback(TInt aCallbackId); + + +// from base class MDirectScreenAccess + void AbortNow(RDirectScreenAccess::TTerminationReasons aReasons); + void Restart(RDirectScreenAccess::TTerminationReasons aReasons); + + +private: + /** + * Constructor. + * @see CMMACameraWindow::NewL() + */ + CMMACameraWindow(TInt aCameraIndex); + + /** + * Creates UI Camera - + * a new CCamera instance (duplicated from handle + * given to the constructor) + * Have to be called from the thread which UI Camera + * will be controlled from + * + * @since S60 v5.0 + * @param "aWs" WS session from the last MdcDSAResourcesCallback + * @param "aScreenDevice" Screen from the last MdcDSAResourcesCallback + * @param "aWindow" Window from the last MdcDSAResourcesCallback + */ + void UIStartViewFinder(RWsSession &aWs, CWsScreenDevice &aScreenDevice, RWindowBase &aWindow); + + /** + * If UI Camera have been created + * it starts/hides the DirectViewFinder + * Have to be called from UI thread in which UI Camera + * have been created! + * + * @since S60 v5.0 + * @param "aVisible" If true DirectViewFinder is started, else stopped + */ + void SetViewFinderVisibility(TBool aVisible); + + /** + * Stops the DirectViewFinder and deletes UI Camera instance + * Have to be called from UI thread in which UI Camera + * have been created before the CMMACameraWindow instance + * is deleted! + * + * @since S60 v5.0 + */ + void ReleaseUiResources(); + + /** + * The callback method invoked by starter timer + * + * @since S60 v5.0 + * @param aThis An instance of CMMACameraWindow + * @return Always returns EFalse + */ + static TInt StarterTimerCallback(TAny* aThis); + + /** + * Starts viewfinder. + * + * @since S60 v5.0 + */ + void StartViewFinder(); + + /** + * Resets (stops and starts) viewfinder + * + * @since S60 v5.0 + */ + void ResetViewFinder(); + + /** + * Draws the error message to specified area. + * Used in cases when viewfinder is unable to start + * + * @since S60 v5.0 + * @param aError Viewfinder error id + * @param aDrawRect Area to draw to + */ + void DrawViewFinderErrorL(const TInt aError, const TRect& aDrawRect); + + /** + * Deletes this object. + * + * @since S60 v5.0 + */ + void Destroy(); + +private: // data + /** + * Indicates the window visibility. + */ + TBool iVisible; + + /** + * Indicated that owning player is in Started state. + */ + TBool iStarted; + + /** + * Indicates that Direct viewfinder is displayed on screen. + */ + TBool iViewFinderVisible; + + /** + * Indicates that duplicated camera (iUICamera) is powered on. + */ + TBool iCameraPowerOn; + + /** + * Rectangle to display viewfinder on (Window coordinates). + */ + TRect iDrawRect; + + /** + * The area of the window. + */ + TRect iClientRect; + + /** + * The handle of original camera instance. + */ + TInt iCameraHandle; + + /** + * UI Camera instance + * Duplicated from iCameraHandle. + * Adjustable and usable from UI thread only. + * Own. + */ + CCamera* iUICamera; + + /** + * Display instance used to invoke UI callbacks. + * Not owned. + */ + MMMADisplay* iDisplay; + + /** + * Window server session used by UI thread. + * Adjustable and usable from UI thread only. + * Not owned. + */ + RWsSession* iWs; + + /** + * Screen device used by UI thread. + * Adjustable and usable from UI thread only. + * Not owned. + */ + CWsScreenDevice* iScreenDevice; + + /** + * Window to draw viewfinder on. + * Adjustable and usable from UI thread only. + * From UI thread. + * Not owned. + */ + RWindowBase* iWindow; + + /** + * The timer to delay viewfinder start + * to avoid many showing/hidding request + * (for instance when scrolling the viewfinder) + * Adjustable and usable from UI thread only. + * Own. + */ + CPeriodic* iStarterTimer; + + /** + * Direct screen access used to draw the error message. + * Adjustable and usable from UI thread only. + * Own. + */ + CDirectScreenAccess* iDirectAccess; + + /** + * Count of remaining allowed DSA restarts. + * In some cases (like screen orientation change) + * the DSA fails to start for some time. + * Therefore the start is tried more times. + */ + TUint iRemainingDSAStartAttempts; + + /** + * An icon used to display instead of viewfinder. + * in case that viewfinder start fails. + * Own. + */ + CFbsBitmap* iErrorIconBitmap; + + /** + * Bitmap mask of iErrorIconBitmap. + * Own. + */ + CFbsBitmap* iErrorIconMaskBitmap; + + + /** + * Symbian RWindow rect + */ + TRect iRWindowRect; + + /** + * jobject to MMACanvasDisplay java class + */ + jobject iJavaDisplayObject; + + /* + * class name of MMACanvasDisplay java class + */ + jclass iJavaDisplayClass; + + JNIEnv * iJni; +}; + +#endif // CMMACAMERAWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmacanvasdisplay.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmacanvasdisplay.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,77 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Draws to Canvas. +* +*/ + + +#ifndef CMMACANVASDISPLAY_H +#define CMMACANVASDISPLAY_H + +// INCLUDES +#include "cmmadisplay.h" +#include "jni.h" + +// FORWARD DECLARATIONS +class CFbsBitmap; +class CMMABitmapWindow; +//class MMAFunctionServer; +//class MMIDCanvas; + +// CLASS DECLARATION +/** +* Display for MMIDCanvas objects. +* +* +*/ + +NONSHARABLE_CLASS(CMMACanvasDisplay): public CMMADisplay +{ +public: // Constructors and destructors + static CMMACanvasDisplay* NewLC(MMAFunctionServer* aEventSource , jobject obj/*MMIDCanvas* aCanvas*/); + + ~CMMACanvasDisplay(); // Destructor () + + +public: // From MMMADisplay + //void SourceSizeChanged(const TSize& aSourceSize); + void SetFullScreenL(TBool aFullScreen); + void SetDisplayLocationL(const TPoint& aPosition); + TPoint DisplayLocation(); + void SetWindowL(MMMADisplayWindow* aWindow); + +private: + /** ask java side peer about the bound + Returns a rectangle describing the receiver's size + and location relative to its parent (or its display if its parent is null), + unless the receiver is a shell. In this case, the location is relative to the display + */ + TRect& CMMACanvasDisplay::BoundRect(); + TRect& CMMACanvasDisplay::ContainerWindowRect(); + +//public: +// void MdcContentBoundsChanged(const TRect& aRect); +protected: // Constructors and destructors + + // Default constructor, protected to allow derivation + CMMACanvasDisplay(MMAFunctionServer* aEventSource , jobject aJavaDisplayRef/*MMIDCanvas* aCanvas*/); + +private: // Data +// MMIDCanvas* iCanvas; + +//MMAFunctionServer* iEventSource; // not owned + +}; + +#endif // CMMACANVASDISPLAY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This is base interface for all controls. +* +*/ + + +#ifndef CMMACONTROL_H +#define CMMACONTROL_H + +// INCLUDES +// #include +// #include +#include "mmapiutils.h" +// CLASS DECLARATION +/** +* This is base interface for all controls. +* +* +*/ +class CMMAControl : public CBase +{ +public: + /** + * Static getter for Java class name. Java object will be created + * according to this name. Derived classes defines the class names. + * + * @see ClassName + * @param aControl Control to use. + * @return Java control class name. + */ + static const TDesC* ClassNameJni(CMMAControl* aControl); + + /** + * Sets associated Java object. + * + * @param aControl Control to use. + * @param aControlObject Java side control object. + */ + static void StaticSetHandle(CMMAControl* aControl, + jobject aControlObject); +public: + /** + * @see ClassNameJni + * @return Java control class name. + */ + virtual const TDesC& ClassName() const = 0; + + /** + * Return public class name. + */ + IMPORT_C virtual const TDesC& PublicClassName() const; + + /** + * Refresh this control. + */ + virtual void RefreshControl() + { + // do nothing + } + +private: + /** + * @see StaticSetHandle + * @param aControlObject Java side control object. + */ + void SetHandle(jobject aControlObject); + +protected: + /** + * Java side control object. + */ + jobject iControlObject; +}; + +#endif // CMMACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmadeleterefevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmadeleterefevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMADELETEREFEVENT_H +#define CMMADELETEREFEVENT_H + +//#include +#include "cmmaevent.h" + +class MMAFunctionServer; + +// CLASS DECLARATION +/** +* This class is used to delete references created with JNIEnv. +* Reference deletion needs JNI environvent, which can't be stored +* as an member variable. JNI environment is delivered to Dispatch +* method that deletes the reference. +* +* +* +*/ + +NONSHARABLE_CLASS(CMMADeleteRefEvent): public CMMAEvent +{ +public: + /** + * Default constructor. This event is always disposable. + * @param aDeleteRefObject Object which reference will be deleted. + */ + CMMADeleteRefEvent(jobject aDeleteRefObject); + +private: // from CJavaEvent + /** + * This method deletes iDeleteRefObject reference with JNIEnv::DeleteGlobalRef method. + * @param aJni JNI environment which is used to delete reference. + */ + void Dispatch(JNIEnv& aJni); + +protected: + // Object reference which will be deleted. + jobject iDeleteRefObject; +}; + +#endif // CMMADELETEREFEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmadisplay.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmadisplay.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,274 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplay +* +*/ + + +#ifndef CMMADISPLAY_H +#define CMMADISPLAY_H + +// INCLUDES +//#include +#include "mmmadisplay.h" +#include "mmafunctionserver.h" +#include "qwidget.h" +#include "jni.h" +#include "jutils.h" +#include "mmmaguiplayer.h" + +// FORWARD DECLARATIONS +class MMMADisplayWindow; + +// CLASS DECLARATION +/** +* This class implements MMMADisplay +* +* +*/ + +NONSHARABLE_CLASS(CMMADisplay): public CBase,public MMMADisplay + /*, + public MDirectContent*/ +{ +public: + // Constructors and destructors + ~CMMADisplay(); // Destructor () + +protected: // Constructors and destructors + // Default constructor, protected to allow derivation + CMMADisplay(); + + void Construct(MMAFunctionServer* eventSource ,jobject javadisplayref); + +public: // Methods derived from MMMADisplay + void DrawFrameL(const CFbsBitmap* aBitmap); + TSize DisplaySize(); + void SetDisplaySizeL(const TSize& aSize); + void SetVisible(TBool aValue); + void SetWindowL(MMMADisplayWindow* aWindow); + MMMADisplayWindow* Window(); + TBool IsVisible(); + TBool IsFullScreen(); + virtual void SetForeground(TBool aIsForeground, TBool aUseEventServer); + void SourceSizeChanged(const TSize& aSourceSize); + void SetUIPlayer(MMMAGuiPlayer* player); + TSize SourceSize(); + + /** + * Gets notification that there is container to draw assigned + * + * @return ETrue if container have been set + * EFalse if container is not set + */ + virtual TBool HasContainer(); + + /** + * Gets resources necessary to start DirectScreenAccess + * Doesn't run in mmapi event server thread! + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aThreadType" Indicates the thread type (UI or MMAPI) + */ + // void UIGetDSAResources( + // MUiEventConsumer& aConsumer, + // MMMADisplay::TThreadType aThreadType); + + /** + * Invokes a callback in UI thread + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aCallbackId" A number identifying the callback + */ + //virtual void UIGetCallback( + // MUiEventConsumer& aConsumer, + // TInt aCallbackId); +public: // Methods derived from MDirectContent + /** + * Not used method. + */ + // virtual void MdcContainerWindowChangedL(RWindow* aWindow); + + /** + * Same functionality is shared in canvas and item displays. + */ + // virtual void MdcContainerVisibilityChanged(TBool aVisible); + + /** + * Default implementation, panics in debug build. Must be written in + * derived classes if needed. + */ + // virtual void MdcItemContentRectChanged(const TRect& aContentRect, +// const TRect& aScreenRect); + + /** + * Notify content that container is about to be destoryed. + */ + // virtual void MdcContainerDestroyed(); + /** + * Notify player's window that any drawing + * via direct screen access must be aborted + */ + // void MdcAbortDSA(); + + /** + * Allow player's window to draw + * via direct screen access after MdcAbortDSA + */ + // void MdcResumeDSA(); + +protected:// New Methods + /** + * Scales drawarea to full screen. Aspect ratio of the source size + * will be maintained. + */ + TRect ScaleToFullScreen(const TSize& aFullScreenSize, + const TSize& aSourceSize); + + /** + * Set clipping region to LCDUI UI component according + * to current window drawrect so that the LCDUI component + * does not paint over the area that is occupied by video. + * Based on current visibility of video image, this method + * either sets or removes the clipping region. + * LCDUI component is then redrawn. + */ + void SetClippingRegion(); + /** + * MMAPI_UI 3.x req + * set content bound to eSWT control + */ + void SetContentBoundToJavaControl(const TRect& aRect); + /** + * Remove currently set clip region and refresh canvas + */ + void RemoveClippingRegion(); + + /** + * MMAPI_UI 3.x req + * removes content bound from eSWT control + */ + void RemoveContentBoundFromJavaControl(const TRect& aRect); + /** + * Add clip region + */ + void AddClippingRegion(); + /** + * MMAPI_UI 3.x req + * Redraw the java side eSWT control + */ + void RefreshJavaControl(const TRect& aRect); + + /** + * MMAPI_UI 3.x req + * Reset the rectangle dimension in eSWT control + */ + void ResetJavaRectObject(const TRect& aRect); + + /** + * Handling the change in container visibility + */ + void HandleContainerVisibilityChanged( TBool aVisible ); + +public: + /** + * called from java when shell visibility gets change + */ + void SetContainerVisibility(TBool aValue); + /** + * called from java to set the window resources + */ + void SetWindowResources(QWidget* qtWidget); + + /** + * Trigger a function call CalledBackInUiThread() from java in UI thread + * arg 'placeholder' is used to identify the function, to be called back from UI Thread + */ + void GetCallbackInUiThread(TInt placeholder); + + /** + * Called from java in UI thread context + * arg 'placeholder' is used to identify the function, to be called back from UI Thread + */ + void CalledBackInUiThread(TInt placeholder); + + void SourceSizeChanged(TInt aJavaControlWidth, TInt aJavaControlHeight); + void SetSourceSizeToDisplay(const TSize& aSourceSize); + void SetDisplayPosition(TInt uiControlLocationX,TInt uiControlLocationY,TInt videoControlLocationX,TInt videoControlLocationY); + +protected: // Data + + /** + * Not owned. + * Actual drawing place of the content. + */ + MMMADisplayWindow* iWindow; + + /** + * Source contents size. + */ + TSize iSourceSize; + + /** + * Indicates visibility set from from Java. + */ + TBool iVisible; + + /** + * Screenmode set from Java. + */ + TBool iFullScreen; + + /** + * Is native container visible. + */ + TBool iContainerVisible; + + /** + * Draw rect set from java. + */ + TRect iUserRect; + + /** + * Not owned, obtained from lcdui components. + */ + //MDirectContainer* iDirectContainer; + + /** + * Clip rectangle currently set to LCDUI. + * NOTE: need to be removed at last during destruction phase! + */ + TRect iClipRect; + /** + * Is midlet is in foreground ? + */ + TBool iIsForeground; + + /** + * Indicates that iUserRect has been changed + * during container invisibility + */ + TBool iResetDrawRect; + // not owned + MMAFunctionServer* iEventSource; + JNIEnv* iJni; + jobject iJavaDisplayObject; + jclass iJavaDisplayClass; + TSize fullScreenSize; + MMMAGuiPlayer* iUiPlayer; +}; + +#endif // CMMADISPLAY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmadurationupdater.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmadurationupdater.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Send update duration event if needed when player state changes +* +*/ + + +#ifndef CMMADURATIONUPDATER_H +#define CMMADURATIONUPDATER_H + +// INCLUDES +#include "mmmaplayerstatelistener.h" +#include "cmmaplayer.h" + +// CLASS DECLARATION +/** +* Checks if media duration has changed when player state changes and sends +* DURATION_UPDATED event to Java. +* +*/ +NONSHARABLE_CLASS(CMMADurationUpdater): + public CBase, public MMMAPlayerStateListener +{ +public: // Construction + static CMMADurationUpdater* NewL(CMMAPlayer& aPlayer); + ~CMMADurationUpdater(); + +private: // Construction + CMMADurationUpdater(CMMAPlayer& aPlayer); + void ConstructL(); + +public: // from MMMAPlayerStateListener + virtual void StateChanged(TInt aState); + +private: // Data + + /* The player which is monitored for duration changes */ + CMMAPlayer& iPlayer; + + /* Last obtained duration value */ + TInt iDuration; + + // to avoid event posting with streamable medias after first start + TBool iSecondStart; +}; + +#endif // CMMADURATIONUPDATER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMAEVENT_H +#define CMMAEVENT_H + +// #include +#include "mmapiutils.h" + +class MMAFunctionServer; + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +* +* +*/ + +NONSHARABLE_CLASS(CMMAEvent) // public CJavaEvent< MMAFunctionServer > +{ +public: + + enum {EEventPriority = 0, ENotifyPriority = 1, ELastPriority = 1}; + enum TDisposability { EDisposableEvent, EReusableEvent }; + + CMMAEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable = EDisposableEvent); + +protected: + CMMAEvent(TDisposability aDisposable); + +public: + void SetEventData(TInt aEventData); + + +public: // from CJavaEvent + virtual void Dispatch(JNIEnv& aJni); + +protected: + jobject iListenerObject; + jmethodID iHandleEventMethod; + TInt iEventData; +}; + +#endif // CMMAEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaframepositioningcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaframepositioningcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Abstract base class for FramePositioningControl +* +*/ + + +#ifndef CMMAFRAMEPOSITIONINGCONTROL_H +#define CMMAFRAMEPOSITIONINGCONTROL_H + +// EXTERNAL INCLUDES +#include "mmfcontroller.h" +#include "mmfstandardcustomcommands.h" + +// INTERNAL INCLUDES +#include "cmmacontrol.h" // base class + +// FORWARD DECLARATIONS +class CMMAPlayer; + +// CONSTANTS + + +// Constant for control name. Name is used in Java side to instantiate +// Java Class which uses CMMAFramePositioningControl. +_LIT(KMMAFramePositioningControlName, "FramePositioningControl"); + +// CLASS DECLARATION +/** +* Abstract base class for FramePositioningControls +*/ +NONSHARABLE_CLASS(CMMAFramePositioningControl): public CMMAControl +{ +public: + /** + * Destructor. + */ + ~CMMAFramePositioningControl(); + +protected: + /** + * Constructor. + */ + CMMAFramePositioningControl(CMMAPlayer* aPlayer); + +public: // From CMMAControl + const TDesC& ClassName() const; + +public: // New methods + virtual TInt SeekL(TInt aFrameNumber) = 0; + virtual TInt SkipL(TInt aFramesToSkip) = 0; + virtual void MapFrameToTimeL(TInt aValue, TInt64* aMediaTime) = 0; + virtual TInt MapTimeToFrameL(TInt64* aMediaTime) = 0; + +protected: // New methods + + /** + * Clamp media time between 0 and duration of media + * @param aMediaTime media time value to clamp + * @return KErrNotFound if duration of media is not known, + * otherwise KErrNone. + */ + virtual TInt ClampMediaTime(TInt64& aMediaTime); + +private: // Data + + // To be used by this class and not by children. + CMMAPlayer* iPlayer; + +}; + +#endif // CMMAFRAMEPOSITIONINGCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaitemdisplay.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaitemdisplay.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Bitmap display that draws to the Java CustomItem's bitmap. +* +*/ + + +#ifndef CMMAITEMDISPLAY_H +#define CMMAITEMDISPLAY_H + +// INCLUDES +#include "cmmadisplay.h" // base class + +//class MMIDCustomItem; + +// CLASS DECLARATION +/** +* Display that uses MMIDCustomItem. +* +* +*/ +NONSHARABLE_CLASS(CMMAItemDisplay): public CMMADisplay +{ +public: // Constructors and destructors + static CMMAItemDisplay* NewLC(/*MMIDCustomItem* aCustomItem*/); + + ~CMMAItemDisplay(); // Destructor () + +protected: // Constructors and destructors + // Default constructor, protected to allow derivation + CMMAItemDisplay(/*MMIDCustomItem* aCustomItem*/); + +public: // New methods + /** + * To be called when java display's size is changed. + * This method also informs when context for the item is + * created for the first time. + */ + static void SizeChangedL(CMMAItemDisplay* aDisplay, + TInt aWidth, + TInt aHeight); + + /** + * Sets source size to aSize. + */ + static void StaticSourceSize(CMMAItemDisplay* aDisplay, + TSize* aSize); + +public: // Methods derived from MMMADisplay + void SourceSizeChanged(const TSize& aSourceSize); + void SetFullScreenL(TBool aFullScreen); + void SetDisplayLocationL(const TPoint& aPosition); + TPoint DisplayLocation(); + void SetWindowL(MMMADisplayWindow* aWindow); +/* +public: // From MDirectContent + void MdcContentBoundsChanged(const TRect& aRect); + void MdcItemContentRectChanged(const TRect& aContentRect, + const TRect& aScreenRect); +private: // Data + MMIDCustomItem* iItem; + */ +}; + +#endif // CMMAITEMDISPLAY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmametadatacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmametadatacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This interface is for getting metadata from a media. +* +*/ + + +#ifndef CMMAMETADATACONTROL_H +#define CMMAMETADATACONTROL_H + +// INCLUDES +#include "cmmacontrol.h" + +// CLASS DECLARATION +/** +* This class is an abstract interface for getting metadata from a media. +* +* +*/ + +NONSHARABLE_CLASS(CMMAMetaDataControl): public CMMAControl +{ +protected: + CMMAMetaDataControl(); + +public: + /** + * Get the number of all metadata keys from given metadata control. + * + * @param aMetaDataControl Metadata control. + * @param aCount Address of an integer to store the metadata keys count + */ + static void StaticKeysCountL(CMMAMetaDataControl* aMetaDataControl, TInt *aCount); + + /** + * Get one metadata key from given metadata control. + * + * @param aMetaDataControl Metadata control. + * @param aValue Address of a pointer to a descriptor to which the + * value is put. Ownership of the descriptor is transferred to + * the caller. + * @param aIndex The index of the key to be fetched. + */ + static void StaticKeyL(CMMAMetaDataControl* aMetaDataControl, HBufC** aKey, TInt aIndex); + + /** + * Get the value associated with a single metadata key. + * + * @param aMetaDataControl Metadata control. + * @param aValue Address of a pointer to a descriptor to which the + * value is put. Ownership of the descriptor is transferred to + * the caller. + * @param aKey The key for which the value is to be fetched. + */ + static void StaticKeyValueL(CMMAMetaDataControl* aMetaDataControl, + HBufC** aValue, + TDesC* aKey); + +protected: + virtual TInt KeyCountL() = 0; + virtual HBufC* KeyL(TInt aIndex) = 0; + + virtual HBufC* KeyValueL(const TDesC& aKey) = 0; + +public: // From CMMAControl + const TDesC& ClassName() const; +}; + +#endif // CMMAMETADATACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidicontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidicontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,203 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a MIDIControl. +* +*/ + + +#ifndef CMMAMIDICONTROL_H +#define CMMAMIDICONTROL_H + +// EXTERNAL INCLUDES + +// INTERNAL INCLUDES +#include "cmmacontrol.h" // base class +#include "mmmaplayerstatelistener.h" +#include // MMidiClientUtilityObserver +#include + +// CONSTANTS + +// Constant for control name. Name is used in Java side to instantiate +// Java Class which uses CMMAMIDIControl. +_LIT(KMIDIControlName, "MIDIControl"); + +class CMMAMIDIPlayer; + +// Maximum volume defined in the Java API. +// It is used to convert volume values between native and java values. +static const TInt KMAXVolume = 127; + + + +// CLASS DECLARATION +/** +* This class implements MIDIControl interface. +* +* +*/ +NONSHARABLE_CLASS(CMMAMIDIControl): public CMMAControl, + public MMidiClientUtilityObserver +{ +private: + + class CChannelVolumeEventWait : public CBase, + public MTimeOutNotify + { + public: // Constructor and destructor + + static CChannelVolumeEventWait* NewL(); + + ~CChannelVolumeEventWait(); + + public: // Methods from base classes + + /** + * From MTimeOutNotify Timer expiration call back method + */ + void TimerExpired(); + + public: // New methods + + void StartWait(TInt aChannel); + + void StopWait(); + + void HandleVolumeChangedEvent(TInt aChannel); + + private: // Constructor + + CChannelVolumeEventWait(); + + void ConstructL(); + + private: // Data + + // Own. For waiting the correct volume changed event + CActiveSchedulerWait* iWait; + + // Own. Time-out for waiting volume changed event + CTimeOutTimer* iTimer; + + // Expected channel for volume event + TInt iChannel; + + }; + +public: + /** + * Creates new CMMAMIDIControl. + * + * @param aPlayer Player that plays the MIDI. + */ + static CMMAMIDIControl* NewL(CMMAMIDIPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAMIDIControl(); +protected: + /** + * Constructor. + * @param aPlayer Player that plays the MIDI. + */ + CMMAMIDIControl(CMMAMIDIPlayer* aPlayer); + + /** + * Initializes this control. + */ + void ConstructL(); + +public: // From CMMAControl + const TDesC& ClassName() const; + +public: // From MMMAPlayerStateListener + void StateChanged(TInt aState); + +public: // Static new methods + + /** + * Get volume for the given channel. The return value is + * independent of the player's volume. + * + * @param aChannel 0-15 + */ + TInt ChannelVolumeL(TInt aChannel); + + /** + * Set volume for given channel. + * + * @param aChannel 0-15 + * @param aVolume 0-127 + */ + void SetChannelVolumeL(TInt aChannel, TInt aVolume); + + /** + * Set program of a channel. + * + * @param aChannel 0-15 + * @param aBank 0-16383, or -1 for default bank + * @param aProgram 0-127 + */ + void SetProgramL(TInt aChannel, + TInt aBank, + TInt aProgram); + + /** + * Sends a long MIDI event to the device. + * This method passes the data directly to the receiving device. + * The data array's contents are not checked for validity. + * + * @param aData array of the bytes to send + * @return the number of bytes actually sent to the device + */ + TInt SendMIDIEventL(const TDesC8* aData); + + /** + * Reinitializes native midi engine with new sequence data. + * First closes midi engine and then opens it again with new + * data. The data array's contents are not checked for validity. + * + * @param aData midi sequence data for initialization + * @return KErrNone (return value is present only for + * method footprint) + */ + TInt ReInitializeMidiL(const TDesC8* aData); + +public: // from MMidiClientUtilityObserver + void MmcuoStateChanged(TMidiState aOldState,TMidiState aNewState,const TTimeIntervalMicroSeconds& aTime,TInt aError); + void MmcuoTempoChanged(TInt aMicroBeatsPerMinute); + void MmcuoVolumeChanged(TInt aChannel,TReal32 aVolumeInDecibels); + void MmcuoMuteChanged(TInt aChannel,TBool aMuted); + void MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& aMicroSeconds,TInt64 aMicroBeats); + void MmcuoMetaDataEntryFound(const TInt aMetaDataEntryId,const TTimeIntervalMicroSeconds& aPosition); + void MmcuoMipMessageReceived(const RArray& aMessage); + void MmcuoPolyphonyChanged(TInt aNewPolyphony); + void MmcuoInstrumentChanged(TInt aChannel,TInt aBankId,TInt aInstrumentId); + +private: // Data + /** + * Used to control MIDI events. + */ + CMMAMIDIPlayer* iPlayer; + + /** + * Own. Utility for waiting for channel volume events + */ + CChannelVolumeEventWait* iVolumeEventWait; + +}; + + +#endif // CMMAMIDICONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidimetadatacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidimetadatacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAMIDIMetaDataControl is a concrete class for getting +* metadata from midi engine. +* +*/ + + +#ifndef CMMAMIDIMETADATACONTROL_H +#define CMMAMIDIMETADATACONTROL_H + +// INCLUDES +#include + +#include "cmmamidiplayer.h" +#include "cmmametadatacontrol.h" + +// CLASS DECLARATION +/** +* This is a concrete class for getting metadata from midi engine. +* +* +*/ + +NONSHARABLE_CLASS(CMMAMIDIMetaDataControl): public CMMAMetaDataControl +{ +public: + CMMAMIDIMetaDataControl(CMMAMIDIPlayer* aPlayer); + +protected: // from CMMAMetaDataControl + + TInt KeyCountL(); + HBufC* KeyL(TInt aIndex); + + HBufC* KeyValueL(const TDesC& aKey); + +private: + /** + * Used to query metadata + */ + CMMAMIDIPlayer* iPlayer; +}; + +#endif // CMMAMIDIMETADATACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidipitchcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidipitchcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements PitchControl functionality. +* +*/ + + +#ifndef CMMAMIDIPITCHCONTROL_H +#define CMMAMIDIPITCHCONTROL_H + +// EXTERNAL INCLUDES + +// INTERNAL INCLUDES +#include "cmmacontrol.h" // base class + +// CONSTANTS + +// Constant for control name. Name is used in Java side to instantiate +// Java Class which uses CMMAMIDIPitchControl. +_LIT(KMIDIPitchControlName, "PitchControl"); + +// Maximum and minimun pitch values +const TInt KMIDIPitchControlMaxPitch = 2400; +const TInt KMIDIPitchControlMinPitch = -2400; + + +class CMMAMIDIPlayer; + +// CLASS DECLARATION +/** +* This class implements MIDIPitchControl interface. +* +* +*/ +NONSHARABLE_CLASS(CMMAMIDIPitchControl): public CMMAControl +{ +public: + /** + * Creates new CMMAMIDIPitchControl. + * + * @param aPlayer Player that plays the content. + */ + static CMMAMIDIPitchControl* NewL(CMMAMIDIPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAMIDIPitchControl(); +protected: + /** + * Constructor. + * @param aPlayer Player that plays the content. + */ + CMMAMIDIPitchControl(CMMAMIDIPlayer* aPlayer); + +public: // From CMMAControl + const TDesC& ClassName() const; + +public: // New methods + /** + * @return Pitch, if not available the default. + */ + TInt PitchL(); + + /** + * @param aPitch Pitch to set in milli-beats per minute. + * @return Actual Pitch set. + */ + TInt SetPitchL(TInt aPitch); + + /** + * @return The maximum rate supported. + */ + TInt MaxPitchL(); + + /** + * @return The minimum rate supported. + */ + TInt MinPitchL(); + +private: // Data + /** + * Used to control MIDI playback. + */ + CMMAMIDIPlayer* iPlayer; +}; + + +#endif // CMMAMIDIPITCHCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidiplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidiplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing MIDI. +* +*/ + + +#ifndef CMMAMIDIPLAYER_H +#define CMMAMIDIPLAYER_H + + +// INCLUDES +#include "cmmaplayer.h" +#include +#include + +// CONSTANTS +_LIT(KMMAMIDIPlayer, "MIDIPlayer"); + +const TMdaPriorityPreference KMMAMIDIPriorityPreference = + EMdaPriorityPreferenceTimeAndQuality; + +// FORWARD DECLARATIONS +class MMAFunctionServer; + +// CLASS DECLARATION +/** +* This class is used for playing MIDI. +* +* +*/ + +class CMMAMIDIPlayer : public CMMAPlayer, public MMidiClientUtilityObserver +{ +public: // Construction + static CMMAMIDIPlayer* NewLC(const TDesC& aContentType, + TFileName aFileName); + + // Destructor + ~CMMAMIDIPlayer(); + +protected: + // C++ constructor + CMMAMIDIPlayer(TFileName aFileName); + void ConstructL(const TDesC& aContentType); + +public: // new methods + IMPORT_C CMidiClientUtility* MidiClient() const; + void ReInitializeMidiEngineL(const TDesC8* aMidiSequence); + void addObserverL(MMidiClientUtilityObserver* aObserver); + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent); + void RealizeL(); + void PrefetchL(); + void DeallocateL(); + void GetDuration(TInt64* aDuration); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + void CloseL(); + const TDesC& Type(); + +public: // from CMMAPlayer/MMMASourceStreamListener + void ReadCompletedL(TInt aStatus, const TDesC8& aData); + void PlayCompleteL(TInt aError); + +public: // from MMidiClientUtilityObserver + void MmcuoStateChanged(TMidiState aOldState,TMidiState aNewState,const TTimeIntervalMicroSeconds& aTime,TInt aError); + void MmcuoTempoChanged(TInt aMicroBeatsPerMinute); + void MmcuoVolumeChanged(TInt aChannel,TReal32 aVolumeInDecibels); + void MmcuoMuteChanged(TInt aChannel,TBool aMuted); + void MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& aMicroSeconds,TInt64 aMicroBeats); + void MmcuoMetaDataEntryFound(const TInt aMetaDataEntryId,const TTimeIntervalMicroSeconds& aPosition); + void MmcuoMipMessageReceived(const RArray& aMessage); + void MmcuoPolyphonyChanged(TInt aNewPolyphony); + void MmcuoInstrumentChanged(TInt aChannel,TInt aBankId,TInt aInstrumentId); + +protected: + void CloseClientUtility(); + +private: // Data + CMidiClientUtility* iMidi; + + // CActiveShedulerWait object for reinitializing midi engine + CActiveSchedulerWait* iActiveSchedulerWait; + + // Array for subsequent MMidiClientUtilityObservers + RPointerArray iObservers; + + TFileName iFileName; + + /** + * Cached media time + */ + TInt64 iMediaTime; + + /** + * The time that will be sent with CMMAPlayerEvent::EStarted + * (may be different from iMediaTime). + */ + TInt64 iStartedEventTime; +}; + +#endif // CMMAMIDIPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidiplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidiplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating MIDI player. +* +*/ + + +#ifndef CMMAMIDIPLAYERFACTORY_H +#define CMMAMIDIPLAYERFACTORY_H + +// INCLUDES +#include "cmmammfplayerfactory.h" + +// CLASS DECLARATION +/** +* This class is used for creating MIDI player. +* +* +*/ + +NONSHARABLE_CLASS(CMMAMIDIPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Constructor and destructot + static CMMAMIDIPlayerFactory* NewLC(); + ~CMMAMIDIPlayerFactory(); + +private: // constructor + CMMAMIDIPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +public: // From CMMAMMFPlayerFactory + + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + + void MediaIdsL(RArray& aMediaIds); + + +private: // new methods + CMMAPlayer* CreateMidiFilePlayerL(const TDesC& aContentType, TFileName aFileName); + CMMAPlayer* CreateMidiSynthPlayerL(const TDesC& aContentType); +}; + +#endif // CMMAMIDIPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidistoptimecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidistoptimecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling +* +*/ + + +#ifndef CMMAMIDISTOPTIMECONTROL_H +#define CMMAMIDISTOPTIMECONTROL_H + +// INCLUDES +#include "cmmastoptimecontrol.h" + +// CLASS DECLARATION +/** +* This class is used for stoptime controlling for MIDI +* +* +*/ + +NONSHARABLE_CLASS(CMMAMIDIStopTimeControl): public CMMAStopTimeControl +{ +public: + static CMMAMIDIStopTimeControl* NewL(CMMAPlayer* aPlayer); + ~CMMAMIDIStopTimeControl(); + +protected: + CMMAMIDIStopTimeControl(CMMAPlayer* aPlayer); + +public: // from CMMAStopTimeControl + virtual void StopAtTimeL(); +}; + +#endif // CMMAMIDISTOPTIMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamiditempocontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamiditempocontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MIDITempoControl functionality. +* +*/ + + +#ifndef CMMAMIDITEMPOCONTROL_H +#define CMMAMIDITEMPOCONTROL_H + +// EXTERNAL INCLUDES +#include // MMidiClientUtilityObserver + +// INTERNAL INCLUDES +#include "cmmaratecontrol.h" // base class +#include "mmmaplayerstatelistener.h" + +// CONSTANTS + +// Constant for control name. Name is used in Java side to instantiate +// Java Class which uses CMMAMIDITempoControl. +_LIT(KMIDITempoControlName, "TempoControl"); + +class CMMAMIDIPlayer; + +// CLASS DECLARATION +/** +* This class implements MIDITempoControl interface. +* +* +*/ +NONSHARABLE_CLASS(CMMAMIDITempoControl): public CMMARateControl, + public MMidiClientUtilityObserver, public MMMAPlayerStateListener +{ +public: + /** + * Creates new CMMAMIDITempoControl. + * + * @param aPlayer Player that plays the content. + */ + static CMMAMIDITempoControl* NewL(CMMAMIDIPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAMIDITempoControl(); +protected: + /** + * Constructor. + * @param aPlayer Player that plays the content. + */ + CMMAMIDITempoControl(CMMAMIDIPlayer* aPlayer); + + /** + * Initializes this control. + */ + void ConstructL(); + +public: // From CMMAControl + const TDesC& ClassName() const; + +public: // From CMMARateControl + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + TInt RateL(); + + /** + * @return The maximum rate supported. + */ + TInt MaxRateL(); + + /** + * @return The minimum rate supported. + */ + TInt MinRateL(); + +public: // New methods + /** + * @return Tempo, if not available the default. + */ + TInt TempoL(); + + /** + * @param aTempo Tempo to set in milli-beats per minute. + * @return Actual Tempo set. + */ + TInt SetTempoL(TInt aTempo); + +public: // From MMMAPlayerStateListener + void StateChanged(TInt aState); + +public: // from MMidiClientUtilityObserver + void MmcuoStateChanged(TMidiState aOldState,TMidiState aNewState,const TTimeIntervalMicroSeconds& aTime,TInt aError); + void MmcuoTempoChanged(TInt aMicroBeatsPerMinute); + void MmcuoVolumeChanged(TInt aChannel,TReal32 aVolumeInDecibels); + void MmcuoMuteChanged(TInt aChannel,TBool aMuted); + void MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& aMicroSeconds,TInt64 aMicroBeats); + void MmcuoMetaDataEntryFound(const TInt aMetaDataEntryId,const TTimeIntervalMicroSeconds& aPosition); + void MmcuoMipMessageReceived(const RArray& aMessage); + void MmcuoPolyphonyChanged(TInt aNewPolyphony); + void MmcuoInstrumentChanged(TInt aChannel,TInt aBankId,TInt aInstrumentId); + +private: // Data + /** + * Used to control MIDI playback. + */ + CMMAMIDIPlayer* iPlayer; + + /** + * Current tempo. Unit of the variable is milli-beat. + * Tempo cannot be set to the midi client before the player is + * prefetched. Thus, when the player is in REALIZED state, tempo is + * saved to this variable and set to the client when the player is + * prefetched. + */ + TInt iTempo; + +}; + + +#endif // CMMAMIDITEMPOCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmamidivolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmamidivolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to midi player +* +*/ + + +#ifndef CMMAMIDIVOLUMECONTROL_H +#define CMMAMIDIVOLUMECONTROL_H + +#include +#include "cmmavolumecontrol.h" + +class CMMAMIDIPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + This class is used for setting volume to audio player + +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(CMMAMIDIVolumeControl): public CMMAVolumeControl +{ +public: + static CMMAMIDIVolumeControl* NewL(CMMAMIDIPlayer* aPlayer); + +protected: + CMMAMIDIVolumeControl(CMMAMIDIPlayer* aPlayer); + void ConstructL(); + + +public: // from CMMAVolumeControl + void DoSetLevelL(TInt aLevel); + TInt DoGetLevelL(); + +private: + CMMAMIDIPlayer* iPlayer; +}; + +#endif // CMMAMIDIVOLUMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmammfplayerbase.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmammfplayerbase.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,120 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + +#ifndef CMMAMMFPLAYERBASE_H +#define CMMAMMFPLAYERBASE_H + +// INCLUDES +#include +#include "cmmaplayer.h" + +class CMMAMMFResolver; +// CLASS DECLARATION +/** +* This is base class for players those use MMF +* +* +*/ + +class CMMAMMFPlayerBase : public CMMAPlayer, + public MMMFControllerEventMonitorObserver +{ +protected: + // C++ constructor + CMMAMMFPlayerBase(CMMAMMFResolver* aResolver); + void ConstructL(); + + ~CMMAMMFPlayerBase(); +public: // new methods + /** + * Getter for RMMFController + */ + IMPORT_C RMMFController& Controller(); + + /** + * Check whether this player is playing from a file locator + * @return ETrue if is a file player, EFalse otherwise + */ + TBool IsFilePlayer(); + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent); + void DeallocateL(); + IMPORT_C void GetDuration(TInt64* aDuration); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + void CloseL(); + +protected: // New methods + + /** + * Loops through iControllerInfos and tries to open those + * @param aSourceUid Data source uid + * @param aSourceData Data for source + * @param aSinkUid Data sink uid + * @param aSinkData Data for sink. + * @param aPrioritySettings Controller's priority. + * @return KErrNone if controller was opened + */ + IMPORT_C virtual TInt DoOpen(TUid aSourceUid, + const TDesC8& aSourceData, + TUid aSinkUid, + const TDesC8& aSinkData, + TMMFPrioritySettings aPrioritySettings); + +public: // from MMMFControllerEventMonitorObserver + void HandleEvent(const class TMMFEvent& aEvent); + +protected: + + /** + * Controller infos, owned + */ + RMMFControllerImplInfoArray* iControllerInfos; + + /** + * Used to control mmf plugin. + */ + RMMFController iController; + + /** + * Owned member. + * Event monitor is used to monitor iController for events. + * If an event occurs, this class will be notified via the + * MMMFControllerEventMonitorObserver interface + */ + CMMFControllerEventMonitor* iEventMonitor; + + /** + * Filename used for playing directly from file, owned + */ + HBufC* iFileName; + + /** + * Cached media time + */ + TInt64 iMediaTime; + + /** + * The time that will be sent with CMMAPlayerEvent::EStarted + * (may be different from iMediaTime). + */ + TInt64 iStartedEventTime; +}; + +#endif // CMMAMMFPLAYERBASE_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmammfplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmammfplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating MMF-based players. +* +*/ + + +#ifndef CMMAMMFPLAYERFACTORY_H +#define CMMAMMFPLAYERFACTORY_H + +// INCLUDES +#include +#include "mmmaplayerfactory.h" + +class CMMAMMFResolver; + +// CLASS DECLARATION +/** +* This class is used for creating MMF-based players. +* +* +*/ +class CMMAMMFPlayerFactory: public CBase, public MMMAPlayerFactory +{ +public: // Constructor and destructor + IMPORT_C CMMAMMFPlayerFactory(); + IMPORT_C ~CMMAMMFPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +protected: + + /** + * Creates new CMMAPlayer instance with given resolver. + * @param aResolver Resolver that contains needed mmf controller infos + * for creating player. + */ + virtual CMMAPlayer* CreatePlayerL(CMMAMMFResolver* aResolver) = 0; + + /** + * Returns list of allowed media IDs + */ + virtual void MediaIdsL(RArray& aMediaIds) = 0; + + /** + * Returns Match type for media IDs. + * CMMFPluginSelectionParameters::EAllowOnlySuppliedMediaIds is the default. + */ + virtual CMMFPluginSelectionParameters::TMediaIdMatchType + MediaIdMatchType(); + + /** + * This method is called before mmf controller implementation array + * is created. With this the actual factories can e.g. select either + * set required play or record format support. Play format support is + * the default. + */ + IMPORT_C virtual void PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection); + + /** + * Creates CMMAPlayer with given format selection parameters + */ + IMPORT_C virtual CMMAPlayer* CreatePlayerL(CMMFFormatSelectionParameters* aFormatSelect, + const TDesC* aFileName = NULL); + + /** + * Checks that is this protocol supported by this factory + */ + TBool IsSupportedProtocolL(const TDesC& aProtocol); + + /** + * Checks that is this content-type supported by this factory + */ + TBool IsSupportedContentTypeL(const TDesC& aContentType); +private: + /** + * File version of creating player from content type + */ + + CMMAPlayer* CreatePlayerL(const TDesC& aContentType, + const TDesC* aFileName); +#ifndef RD_JAVA_OMA_DRM_V2 + /** + * Tries to open DRM file + */ + CMMAPlayer* TryOpenDRMFileL(const TDesC& aFileName); +#endif // RD_JAVA_OMA_DRM_V2 + +}; + +#endif // CMMAMMFPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmammfratecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmammfratecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements RateControl for MMF players. +* +*/ + + +#ifndef CMMAMMFRATECONTROL_H +#define CMMAMMFRATECONTROL_H + +// INTERNAL INCLUDES +#include "cmmaratecontrol.h" // base class +#include "cmmammfplayerbase.h" + +// CLASS DECLARATION +/** +* This class implements RateControl for MMF players. +* +*/ +NONSHARABLE_CLASS(CMMAMMFRateControl): public CMMARateControl, + public MMMAPlayerStateListener +{ +public: + + static CMMAMMFRateControl* NewL(CMMAMMFPlayerBase* aPlayer); + + /** + * Destructor. + */ + ~CMMAMMFRateControl(); + +protected: + + /** + * Constructor. + */ + CMMAMMFRateControl(CMMAMMFPlayerBase* aPlayer); + + void ConstructL(); + +public: // from MMMAPlayerStateListener + virtual void StateChanged(TInt aState); + +public: // New methods + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + virtual TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + virtual TInt RateL(); + + +private: // Member data + + /** + * Used to obtain RMMFController reference to stop/start + * playback. + */ + CMMAMMFPlayerBase* iPlayer; + + /** + * Hold current rate value. + */ + TInt iCurrentRate; + +}; + +#endif // CMMAMMFRATECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmammfresolver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmammfresolver.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,166 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +#ifndef CMMAMMFRESOLVER_H +#define CMMAMMFRESOLVER_H + +// INCLUDES +#include +#include "cmmaplayer.h" + + +_LIT(KRmFileExtension, ".rm"); +_LIT(KRaFileExtension, ".ra"); + +// CLASS DECLARATION +/** +* This class can be used to get RMMFControllerImplInfoArray and content +* types from MMF. +*/ +NONSHARABLE_CLASS(CMMAMMFResolver): public CBase + +{ +public: // Construction + /** + * Constructs a new mmf resolver object. + * @return The new object created. Note that the new object will be + * left on the cleanup stack. + */ + static CMMAMMFResolver* NewLC(); + +public: // New methods. + /** + * Retrieves all controller plugins that support the requirements of + * the caller. + */ + void ListImplementationsL(); + + /** + * Returns implementations. + * Array will not contain any implementation if ListImplementationsL() + * is not called. + * @return Found implementations. + */ + RMMFControllerImplInfoArray* Implementations(); + + /** + * Returns implementations. Notice: Ownership is transferred to caller. + * Array will not contain any implementation if ListImplementationsL() + * is not called. + * @return Found implementations. Ownership is transferred. + */ + RMMFControllerImplInfoArray* ImplementationsOwnership(); + + /** + * Returns content type that was found in ListImplementationsL method. + * Ownership is transfered. + * @return Content type or NULL if type is not available. + */ + HBufC* ContentTypeOwnership(); + + /** + * Returns content type that was found in ListImplementationsL method. + * @return Content type or NULL if type is not available. + */ + HBufC* ContentType(); + + /** + * Sets filename + * @param aFileName File name to be set or NULL + */ + + void SetFileNameL(const TDesC* aFileName); + + /** + * Returns possible filename or NULL if not set + * Ownership is transfered. + * @return Content type or NULL if type is not available. + */ + HBufC* FileNameOwnership(); + + /** + * Get all supported content types. + * @param aMimeTypeArray Will contain supported mime types. + */ + void GetSupportedContentTypesL(CDesC16Array& aMimeTypeArray); + + /** + * Return selection parameters. + */ + CMMFControllerPluginSelectionParameters* + SelectionParameters(); + + /** + * Sets the play format support required. + * @param aRequiredSupport The play format support required. + */ + void SetRequiredPlayFormatSupportL( + CMMFFormatSelectionParameters& aRequiredSupport); + + /** + * Sets the record format support required. + * @param aRequiredSupport The record format support required. + */ + void SetRequiredRecordFormatSupportL( + CMMFFormatSelectionParameters& aRequiredSupport); + +private: + /** + * Returns record or play formats according to the setup. + */ + const RMMFFormatImplInfoArray* Formats( + CMMFControllerImplementationInformation* aImplementation); + /** + * Finds content type from iImplementations array. + */ + void ResolveContentTypeL(); + +private: + TBool IsRealVideoTypeL(const TDesC& aFileName); + + TBool IsRealMimeTypeSupported(const TDesC& aMimeType); + +protected: + // C++ constructor + CMMAMMFResolver(); + void ConstructL(); + +private: + ~CMMAMMFResolver(); + +private: + // Owned. Ownership can be tranferred with ImplementationsOwnership + // method. + RMMFControllerImplInfoArray* iImplementations; + + // Owned. Ownership can be transferred with ContentType method. + HBufC* iContentType; + + // Owned. Ownership can be transferred with FileName method. + HBufC* iFileName; + + // Owned. + CMMFControllerPluginSelectionParameters* iControllerSelection; + + // The required play format support + CMMFFormatSelectionParameters* iRequiredPlayFormatSupport; + + // The required record format support + CMMFFormatSelectionParameters* iRequiredRecordFormatSupport; +}; + +#endif // CMMAMMFRESOLVER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaoutputstream.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaoutputstream.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,152 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class to handle OutputStream operations. +* +*/ + + +#ifndef CMMAOUTPUTSTREAM_H +#define CMMAOUTPUTSTREAM_H + +// EXTERNAL INCLUDES +//#include +#include +#include "MMAFunctionServer.h" + +// FORWARD DECLARATIONS +class CMMAOutputStreamEvent; +class MMMAEventPoster; + +// CLASS DECLARATION +/** +* Class to handle OutputStream operations. +* MMF writes to the stream and Java-class reads the stream. +* +* +*/ + +NONSHARABLE_CLASS(CMMAOutputStream): public CBase +{ +private: + /** + * Status code to be delivered to Java + */ + enum TStatus + { + EMoreData = 1, + ECompleted = 2 + }; + +public: // Constructors and destructors + /** + * Object creation. Static method. + * + * @param aJNIEnv handle to used jni environment + * @param aEventPoster handle to event poster + * @param aJavaOutputStreamWriter handle to java Outputstream object + * + * @return CMMAOutputStream object + */ + static CMMAOutputStream* NewL(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter); + + /** + * The same as NewL with cleanup stack + * @see NewL + */ + static CMMAOutputStream* NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter); + + + /** + * Object creation. Static method. + * + * @param aOutputStream handle to used output stream + * @param aJNIEnv handle to used jni environment + * @param aEventPoster handle to event poster + * @param aJavaOutputStreamWriter handle to java Outputstream object + */ + static void CreateL(CMMAOutputStream** aOutputStream, + MMAFunctionServer* aEventSource, + JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter); + + /** + * Deletes owned objects + */ + ~CMMAOutputStream(); // Destructor + +private: // Constructors and destructors + /** + * Default constructor, initializes variables + */ + CMMAOutputStream(MMMAEventPoster* aEventPoster); + + /** + * Finishes construction + * + * @param aJNIEnv handle to used jni environment + * @param aJavaOutputStreamWriter handle to java Outputstream object + */ + void ConstructL(JNIEnv* aJNIEnv, + jobject aJavaOutputStreamWriter); + +public: // New methods + /** + * Read data from c++ to aOutputData (passed from java side) + */ + virtual void ReadDataL(TUint8* aOutputData, + TInt* aBufferSize, + TInt* aReadStatus); + +public: // New methods + /** + * Write data to a stream. + */ + void WriteL(const TDesC8& aData); + + /** + * Commit Java stream + */ + void Commit(); + +private: // Data + /** + * Owned. + * Event which notifies Java when data is available or read continues. + */ + CMMAOutputStreamEvent* iWriteEvent; + + /** + * Pointer to event source + */ + MMMAEventPoster* iEventSource; + + /** + * Ptr to iData member. Moved when data is read. + */ + TPtr8 iPtr; + + /** + * Owned. + * Pointer to data to be written to Java side. + */ + HBufC8* iData; +}; + + +#endif // CMMAOUTPUTSTREAM_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaoutputstreamevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaoutputstreamevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMAOUTPUTSTREAMEVENT_H +#define CMMAOUTPUTSTREAMEVENT_H + +#include "cmmaevent.h" + + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +* +* +*/ + +NONSHARABLE_CLASS(CMMAOutputStreamEvent): public CMMAEvent +{ +public: + enum TMMAOutputStreamState + { + EMMAEventActive, // event is waiting dispatching + EMMAEventNotActive, // not added to event server + EMMADeleteEvent // dispatch deletes this event + }; +public: + CMMAOutputStreamEvent(jmethodID aHandleEventMethod, + jobject aNotifyObject); + + // status of the source stream + void SetStatus(TInt aStatus); + + // length of the available output stream data + void SetLength(TInt aLength); + + /** + * Sets new state. + * @param aState TMMAOutputStreamState. + */ + void SetState(TMMAOutputStreamState aState); + + TMMAOutputStreamState State(); +private: // from CJavaEvent + void Dispatch(JNIEnv& aJni); + +private: + jmethodID iHandleEventMethod; + jobject iListenerObject; + TInt iLength; + TInt iStatus; + + /** + * State of this event. + */ + TMMAOutputStreamState iState; +}; + +#endif // CMMAOUTPUTSTREAMEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,475 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is base class for all players. +* +*/ + + +#ifndef CMMAPLAYER_H +#define CMMAPLAYER_H + +// INCLUDES +#include "cmmacontrol.h" +#include "cmmasourcestream.h" +#include "cmmaplayerevent.h" +#include "mmmasourcestreamlistener.h" +#include "mmmaplayerstatelistener.h" + +// FORWARD DECLARATIONS +class CMMADurationUpdater; + +// CONTANTS + +// Not enough stream to realize to player +const TInt KErrNotEnoughStreams = -7002; + +/** + * Used in set loop count to indicate forever loop. + */ +const TInt KJavaRepeatForever = -1; + +/** + * Returned to Java if duration or mediatime is unknown. + */ +const TInt KTimeUnknown = -1; + +// CLASS DECLARATION +/** +* This class is base class for all players. +* +* +*/ + +class CMMAPlayer : public CBase, + public MMMASourceStreamListener + +{ +public: + /** + * Player state. Same that in Java side. + */ + enum TPlayerState + { + EClosed = 0, + EUnrealized = 100, + ERealized = 200, + EPrefetched = 300, + EStarted = 400 + }; + +public: + /** + * Deletes all owned members. + */ + virtual ~CMMAPlayer(); +protected: + /** + * Initializes member variables to defaults. + */ + CMMAPlayer(); + + /** + * Second phase construct. + */ + void ConstructL(); + +public: // static methods + /** + * Creates and adds source stream to the player. New stream will be + * owned by this player. + * + * @param aJniEnv Used to create source stream. + * @param aPlayer Player to use. + * @param aEventSource Used to create source stream. + * @param aReader Java side stream object. + * @param aSourceStream New stream's pointer will be set to this. + */ + static void StaticAddSourceStreamL(JNIEnv* aJniEnv, + CMMAPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aReader, + CMMASourceStream** aSourceStream); + + /** + * Sets Java listener object that will be used to post player events + * and control specific events. + * + * @param aPlayer Player to use. + * @param aListenerObject Java side listener object. + * @param aJni Used to get method ids. + * @param aPoster Used to post events. + */ + static void StaticSetPlayerListenerObjectL(CMMAPlayer* aPlayer, + MMAFunctionServer* aEventsource, + jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aPoster); + + /** + * Initializes action completed callbacks. + * + * @param aPlayer Player to use. + * @param aPlayerObject Java side Player object. + * @param aJni Used to get method id. + */ + static void StaticInitPlayerL(CMMAPlayer* aPlayer, + MMAFunctionServer* aEventsource, + jobject aPlayerObject, + JNIEnv* aJni); + + /** + * Static getter for control objects. + * + * @param aPlayer Player to use. + * @param aIndex Control's index. + */ + IMPORT_C static CMMAControl* StaticControl(CMMAPlayer* aPlayer, + TInt aIndex); + +public: // New methods + + /** + * Realizes the player. Implementations do not necessarily add + * functionality in this method. If successful player is in + * ERealized state. + */ + virtual void RealizeL(); + + /** + * Prefetches data. Usually data from source stream will be read. When + * prefetch completes action completed event will be delivered. If + * successful player is in EPrefetched state. + */ + virtual void PrefetchL() = 0; + + /** + * Start playing. Started event will be posted. If there is no error + * player will be in EStarted state. + */ + virtual void StartL() = 0; + + /** + * Stops playing. After this player may be restarted with StartL method. + * After this player is in EPrefetched state. + * + * @param aPostEvent Indicates if java be informed. + */ + virtual void StopL(TBool aPostEvent) = 0; + + /** + * Releases resources. Player state can be changed. + */ + virtual void DeallocateL() = 0; + + /** + * Close the Player and release its resources. After this player is in + * EClosed state and cannot be used anymore. + */ + virtual void CloseL(); + + /** + * Gets duration. + * + * @param aDuration Duration or KTimeUnknown if not specified. + */ + virtual void GetDuration(TInt64* aDuration); + + /** + * Sets media time. + * + * @param aTime Time to set. When method returns parameter contains + * actual media time set. + */ + virtual void SetMediaTimeL(TInt64* aTime); + + /** + * Gets media time. + * + * @param aMediaTime When method returns parameter contains the media + * time. + */ + virtual void GetMediaTime(TInt64* aMediaTime); + + /** + * Sets loop count. + * + * @param aCount Indicates the number of times the content will be + * played. KJavaRepeatForever indicates looping + * indefintely. + */ + IMPORT_C virtual void SetLoopCount(TInt aCount); + + /** + * Get the content type of the media that's being played back by this + * Player. + * @return The content type being played back by this Player. NULL if + * content type is not available. + */ + HBufC* ContentType() const; + +public: // new methods + /** + * Sets Java listener object that will be used to post player events + * and control specific events. + * + * @param aListenerObject Java side listener object. + * @param aJni Used to get method ids. + * @param aPoster Used to post events. + */ + virtual void SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aPoster); + + /** + * Returns total count of the controls owned by this player. + * + * @return Count of the controls. + */ + IMPORT_C TInt ControlCount(); + + /** + * Gets control. Ownership is not tranferred. + * + * @param aIndex Control index. + */ + IMPORT_C CMMAControl* Control(TInt aIndex); + + /** + * Adds new control. Ownership is transferred to this class. + * + * @param aControl New control. + */ + IMPORT_C virtual void AddControlL(CMMAControl* aControl); + + /** + * Adds listener. All listeners will informed when player state changes. + * + * @param aListener New listener. + */ + IMPORT_C void AddStateListenerL(MMMAPlayerStateListener* aListener); + + /** + * Removes a player state listener. + * + * @param aListener Listener to be removed. + */ + IMPORT_C void RemoveStateListener(MMMAPlayerStateListener* aListener); + + /** + * @return Player's state. + */ + inline TInt State(); + + /** + * Returns player's type. Player types are defined in derived player + * headers. + * @return Player type. + */ + virtual const TDesC& Type(); + + /** + * Sets player's content type, which can be queried with ContentType + * method. Ownership is transfered. + * @param aContentType Player's content type. + */ + void SetContentType(HBufC* aContentType); + + /** + * Reset all source streams. + */ + void ResetSourceStreams(); + + /** + * Refresh all the controls. + */ + void RefreshControls(); + /** + * delete all the controls. + */ + void DeleteControls(); + +public: // methods for informing java player listeners + + /** + * Post event which event data will be Long java object. + * + * @param aEventType Event's type specified in CMMAPlayerEvent. + * @param aLongEventData Event data context. + */ + void PostLongEvent(CMMAPlayerEvent::TEventType aEventType, + const TInt64& aLongEventData); + + /** + * Post event which event data will be string. + * + * @param aEventType Event's type specified in CMMAPlayerEvent. + * @param aStringEventData Event data context. + */ + IMPORT_C void PostStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData); + + /** + * Post event which event data will be a java object. + * + * @param aEventType Event's type specified in CMMAPlayerEvent. + * @param aEventData Java object. + */ + IMPORT_C void PostObjectEvent(CMMAPlayerEvent::TEventType aEventType, + const jobject aEventData); + + /** + * Completes action and allows Java side to continue. + * + * @param aError of the action or KErrNone. + */ + IMPORT_C void PostActionCompleted(TInt aError); + + IMPORT_C void PostActionCompletedFile(); //LC work for S60 3.2 + + IMPORT_C void PostActionCompletedStart(); +protected: // new methods + /** + * @see StaticAddSourceStreamL + */ + IMPORT_C virtual CMMASourceStream* AddSourceStreamL(JNIEnv* aJniEnv, + MMAFunctionServer* aEventSource, + jobject aReader); + + /** + * Changes player's state and informs all MMMAPlayerStateListeners. + * + * @param aState New state. + */ + void ChangeState(TPlayerState aState); + +public: // from MMMASourceStreamListener + virtual void ReadCompletedL(TInt aStatus, const TDesC8& aData); + +protected: // Memeber data + /** + * Array of controls. All controls are owned by this class. + */ + RPointerArray< CMMAControl > iControls; + + /** + * Array of streams. All streams are owned by this class. + */ + RPointerArray< CMMASourceStream > iSourceStreams; + + + /** + * Array of listeners. Not owned. + */ + RPointerArray< MMMAPlayerStateListener > iStateListeners; + + /** + * Used to inform java side of completion. + * Owned. + */ + CMMAEvent* iActionCompletedEvent; + + /** + * Used to inform java side of completion. + * Owned. + */ + CMMAEvent* iActionCompletedFileEvent; + + CMMAEvent* iActionCompletedStartEvent; + + /** + * Player state listener object. + */ + jobject iListenerObject; + + /** + * java method postEvent(String,Object) + */ + jmethodID iPostEvent; + /** + * java method postObjectEvent(int,Object) + */ + jmethodID iPostObjectEvent; + + /** + * java method postLongEvent(int,long) + */ + jmethodID iPostLongEvent; + + /** + * java method postStringEvent(int,String) + */ + jmethodID iPostStringEvent; + + /** + * java method postControlEvent(int,String) + */ + jmethodID iPostControlEvent; + + /** + * Not owned. + */ + MMMAEventPoster* iEventPoster; + + /** + * Total number of wanted loops. + */ + TInt iRepeatNumberOfTimes; + + /** + * Indicates if looping indefintely. + */ + TBool iRepeatForever; + + /** + * Current loop count. + */ + TInt iRepeatCount; + + /** + * Content duration in microseconds. + */ + TInt64 iDuration; + + /** + * Current state of the player. + */ + TPlayerState iState; + + /** + * Event for notificating Java that memory allocation has failed. + * Owned. + */ + CMMAPlayerEvent* iOOMErrorEvent; + + /** + * The content type being played back by this Player. + * Owned. May be NULL until type is available. + */ + HBufC* iContentType; + + /** + * Player state listener that sends duration update event to Java + * if duration has changed when player state changes. + */ + CMMADurationUpdater* iDurationUpdater; + +}; + + +inline TInt CMMAPlayer::State() +{ + return iState; +} + +#endif // CMMAPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaplayerevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaplayerevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,121 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMAPLAYEREVENT_H +#define CMMAPLAYEREVENT_H + +// INCLUDES +#include "cmmaevent.h" + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +*/ + +NONSHARABLE_CLASS(CMMAPlayerEvent): public CMMAEvent +{ +public: + enum TEventType + { + EStarted = 0, + EStopped = 1, + EStoppedAtTime = 2, + EEndOfMedia = 3, + EDurationUpdated = 4, + EAudioDeviceUnavailable = 5, + EVolumeChanged = 6, + ESizeChanged = 7, + EError = 8, + EClosed = 9, + ERecordStarted = 10, + ERecordStopped = 11, + EPrivateDataAvailable = 12, + EPrivateDataOverwritten = 13, + EBufferingStarted = 14, + EBufferingEStopped = 15, + ERecordError = 16, + ENOKIA_EXTERNAL_VOLUME_EVENT = 17, // Event ID for Nokia volume key + EAudioOutputPreferenceChangeEvent =18 // Event ID for Audio Routing Preference Change + }; + +private: + enum TEventParams + { + ENormal = 0, // string and object + EString, // int and string + ELong, // int and long + EObject // int and object + }; + +public: + /** + * Constructor. One of set methods must be called before sending this + * event. + * @param aNotifyObject Java Objects. + * @param aHandleEventMethod Java method. + * @param aDisposable Defaults to disposable event. + */ + CMMAPlayerEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable = EDisposableEvent); + + /** + * Destructor. + */ + ~CMMAPlayerEvent(); + + /** + * Sets event data. + * @param aEventType Type of the event. + * @param aEventData Data to be send to Java + */ + void SetLongEvent(TEventType aEventType, const TInt64& aEventData); + + /** + * Sets event data. + * @param aEventType Type of the event. + * @param aEventData Data to be send to Java + */ + void SetStringEventL(TEventType aEventType, const TDesC& aEventData); + + /** + * Sets event data. + * @param aEventType Type of the event. + * @param aEventData Data to be send to Java + */ + void SetObjectEventL(TEventType aEventType, const jobject aEventData); +private: // from CJavaEvent + void Dispatch(JNIEnv& aJni); + +private: // Data + TEventType iEventType; + TEventParams iEventParams; + + // Used when sending ELong event. + TInt64 iLongEventData; + + // Owned event data. Used when sending EString event. + HBufC* iStringEventData; + // Owned event type. Used when sending ENormal event. + HBufC* iStringEventType; + + // Used when sending ENormal or EObject event. + jobject iObjectEventData; +}; + +#endif // CMMAPLAYEREVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaplayerproperties.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaplayerproperties.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,255 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for storing and parsing properties +* +*/ + + +#ifndef CMMAPLAYERPROPERTIES_H +#define CMMAPLAYERPROPERTIES_H + +// INCLUDES +#include + +// STRUCTS + +/** + * These structs are used for storing array of strings + */ +NONSHARABLE_STRUCT(TMMAStaticStr) +{ + TInt iLength; + const TText* iStr; + + inline const TPtrC operator()() const + { + return TPtrC(iStr, iLength); + } +}; + +NONSHARABLE_STRUCT(TMMAStaticStrArray) +{ + const TMMAStaticStr* iStr; + inline const TPtrC operator()() const + { + return TPtrC(iStr->iStr, iStr->iLength); + } +}; + +#define MMA_PARAMETER_ARRAY(name) const TMMAStaticStrArray name[] = +#define MMA_PARAMETER_STR(name, s) static const TMMAStaticStr name = {sizeof(L##s)/sizeof(TText)-1, (TText*)L##s} +#define MMA_PARAMETER_ARRAY_SIZE(name) (sizeof(name)/sizeof((name)[0])) + +// CLASS DECLARATION +/** +* This class is base class for storing and validating +*/ + +NONSHARABLE_CLASS(MMMAParameterRule) +{ +public: + /** + * Validates key-value pair based on rule. If derived class is leaf with specified key + * then it must store value if it is valid. + */ + virtual TBool ValidateAndStoreL(const TDesC& aKey, const TDesC& aValue) = 0; + + /** + * Compares key-value pair based on rule and stored value. + */ + virtual TBool Compare(const TDesC& aKey, const TDesC& aValue) = 0; + virtual TBool Compare(const TDesC& aKey, const TInt aValue) = 0; + + /** + * Gets value for specified key, returns EFalse if specified key is not found + */ + virtual TBool FindProperty(const TDesC& aKey, TPtrC& aValue) = 0; + virtual TBool FindProperty(const TDesC& aKey, TInt& aValue) = 0; +}; + +// CLASS DECLARATION +/** +* This class is used for storing and parsing properties +* The property string is in format "name=value&name=value&..." +* +*/ + +NONSHARABLE_CLASS(CMMAPlayerProperties): public CBase +{ +public:// Construction and destruction + /** + * Two-phased constructor. + */ + static CMMAPlayerProperties* NewL(const TDesC& aProperties, + MMMAParameterRule& aRule); + /** + * Destructor. + */ + ~CMMAPlayerProperties(); + +protected: // default constructor and second phase construction + CMMAPlayerProperties(const TDesC& aProperties, MMMAParameterRule& aRule); + +public: // new methods + /** + * Gets property for given key. Returns EFalse if key cannot + * be found + */ + TBool GetProperty(const TDesC& aKey, TInt& aValue) const; + TBool GetProperty(const TDesC& aKey, TPtrC& aValue) const; + + /** + * Compares that given key and value pair can be found in + * given properties string. Notice that this returns EFalse also + * if given key is not found. + */ + TBool Compare(const TDesC& aKey, const TInt& aValue) const; + TBool Compare(const TDesC& aKey, const TDesC& aValue) const; + + /** + * Validates given properties with given rule(s), leaves with + * KErrArgument if properties was not valid. + */ + + void ValidateL() const; + +private: //data + // properties + const TDesC& iProperties; + // rule composition + MMMAParameterRule& iRule; +}; + + + +// CLASS DECLARATION +/** +* Composite class for storing rule set +*/ + +NONSHARABLE_CLASS(CMMAParameterRuleSet): public CBase, public MMMAParameterRule +{ +public: // Construction and destruction + /** + * Two-phased constructor. + */ + static CMMAParameterRuleSet* NewLC(); + + /** + * Destructor. + */ + ~CMMAParameterRuleSet(); + +protected: // default constructor and second phase construction + CMMAParameterRuleSet(); + virtual void ConstructL(); + +public: // From MMMAParameterRule + TBool ValidateAndStoreL(const TDesC& aKey, const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TInt aValue); + TBool FindProperty(const TDesC& aKey, TPtrC& aValue); + TBool FindProperty(const TDesC& aKey, TInt& aValue); + +public: // new methods + void AppendRuleL(MMMAParameterRule* aRule); + +private: // data + // list of rules in this composite, owned + CArrayPtrSeg< MMMAParameterRule >* iRules; +}; + +// CLASS DECLARATION +/** +* Base class for property rules +*/ +NONSHARABLE_CLASS(TMMAParameterRuleBase): public MMMAParameterRule +{ +public: // constructor + TMMAParameterRuleBase(const TDesC& aKey); + +public: // From MMMAParameterRule + TBool ValidateAndStoreL(const TDesC& aKey, const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TInt aValue); + TBool FindProperty(const TDesC& aKey, TPtrC& aValue); + TBool FindProperty(const TDesC& aKey, TInt& aValue); + +protected: // new methods + /** + * Returns EFalse if value is not valid for this rule + * Derived class must also store value if it is accepted + */ + virtual TBool ValidateValueL(const TDesC& aValue) = 0; + +protected: //data + const TDesC& iKey; + TBool iAssigned; +}; + +// CLASS DECLARATION +/** +* Rule for TInt +*/ +NONSHARABLE_CLASS(TMMAParameterRuleInt): public TMMAParameterRuleBase +{ +public: // constructors + TMMAParameterRuleInt(const TDesC& aKey); + + TMMAParameterRuleInt(const TDesC& aKey, + const TInt aLowerLimit); + + TMMAParameterRuleInt(const TDesC& aKey, + const TInt aLowerLimit, + const TInt aUpperLimit); + +public: // From MMMAParameterRule + TBool ValidateValueL(const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TInt aValue); + TBool FindProperty(const TDesC& aKey, TInt& aValue); + + + +private: // data + TInt iValue; + const TInt iUpperLimit; + const TInt iLowerLimit; +}; + +// CLASS DECLARATION +/** +* Rule for TDesC +*/ +NONSHARABLE_CLASS(TMMAParameterRuleDes): public TMMAParameterRuleBase +{ +public: // constructors + TMMAParameterRuleDes(const TDesC& aKey); + + TMMAParameterRuleDes(const TDesC& aKey, + const TMMAStaticStrArray* aValidValues, + const TInt aArraySize); + +public: // From MMMAParameterRule + TBool ValidateValueL(const TDesC& aValue); + TBool Compare(const TDesC& aKey, const TDesC& aValue); + TBool FindProperty(const TDesC& aKey, TPtrC& aValue); + + +private: // data + TPtrC iValue; + // not owned + const TMMAStaticStrArray* iValidValues; + const TInt iArraySize; +}; +#endif // CMMAPLAYERPROPERTIES_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmaratecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmaratecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for RateControl implementations. +* +*/ + + +#ifndef CMMARATECONTROL_H +#define CMMARATECONTROL_H + +// EXTERNAL INCLUDES + +// INTERNAL INCLUDES +#include "cmmacontrol.h" // base class + +// CONSTANTS + +static const TInt KMMADefaultRate = 100000; +static const TInt KMMAMinRate = 0; + +// Constant for control name. Name is used in Java side to instantiate +// Java Class which uses CMMARateControl. +_LIT(KMMARateControlName, "RateControl"); + + +// CLASS DECLARATION +/** +* This class is the base class for RateControl implementations. +* +* +*/ +NONSHARABLE_CLASS(CMMARateControl): public CMMAControl +{ +public: + /** + * Destructor. + */ + ~CMMARateControl(); + +protected: + /** + * Constructor. + */ + CMMARateControl(); + +public: // From CMMAControl + virtual const TDesC& ClassName() const; + +public: // New methods + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + virtual TInt SetRateL(TInt aRate) = 0; + + /** + * @return The current playback rate in "milli-percentage". + */ + virtual TInt RateL() = 0; + + /** + * @return The maximum rate supported. + */ + virtual TInt MaxRateL(); + + /** + * @return The minimum rate supported. + */ + virtual TInt MinRateL(); + +}; + + +#endif // CMMARATECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmarecordcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmarecordcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,209 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a RecordControl. +* +*/ + + +#ifndef CMMARECORDCONTROL_H +#define CMMARECORDCONTROL_H + +// INTERNAL INCLUDES +#include +#include "cmmaoutputstream.h" +#include "cmmacontrol.h" +#include "mmmaplayerstatelistener.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; + +// CONSTANTS + +// Too fast start and stop can cause problems, +// 0.5s is enough to make pause work. +const TInt KMinRecordPauseInterval = 500000; + +_LIT(KMMARecordTempDirectory, "d:\\"); // CSI: 25 dir for temporary recording file # +_LIT(KMMARecordErrorMsg, "Recording error: %d"); +const TInt KRecordErrorMessageSize = 25; + +// CLASS DECLARATION +/** +* This class is the native side of the RecordControl Java class. This class +* delegates static method calls to virtual methods which are implemented in +* derived classes. This class only implements ClassName method. +* +* +*/ +NONSHARABLE_CLASS(CMMARecordControl): + public CMMAControl, + public MMMAPlayerStateListener +{ +protected: + // Internal state of this class. + enum TRecordState + { + // recorder has not been initialized (startRecord has not been called) + ERecordUninitialized = 1, //Recorder uninitialized + // recorder has been initialized (startRecord) however, + // recodring has been stopped after that (stopRecord) + ERecordInitialized, + // recorder has been initialized (startRecord) but player is not in + // STARTED state + ERecordStandBy, + // recorder has been initialized (startRecord) and player is in + // STARTED state. i.e. recording is ON + ERecordRecording + }; + +protected: // proteced constructor and destructor for preventing direct use + CMMARecordControl(CMMAPlayer* aPlayer); + ~CMMARecordControl(); + void ConstructL(); + + /** + * Waits until recording can be paused after start. + * @param aMediaTime Current media time. + */ + void WaitForPauseL(const TInt64& aMediaTime); + +public: // new methods + /** + * Start recording. + */ + virtual void StartRecordL(); + + /** + * Stops recording. + */ + virtual void StopRecordL(); + + /** + * Completes current recording. The rest of the data will written + * to the output stream. This method may not be called when recording. + */ + virtual void CommitL(); + + /** + * Erase current recording. + */ + virtual void ResetL(); + + /** + * Set the output stream where the data will be recorded. + * Existing stream will be deleted. + * @param aStream New stream to use. + */ + virtual void SetRecordStream(CMMAOutputStream* aStream); + + /** + * Return the content type of the recorded media. + * @return Content type used for recording. + */ + virtual HBufC* GetContentTypeL(); + +public: // new pure virtual methods + + /** + * Set the record size limit. This limits the size of the recorded + * media to the number of bytes specified. + * + * When recording is in progress, commit will be called implicitly + * in the following cases: + * - Record size limit is reached + * - If the requested size is less than the already recorded size + * - No more space is available. + * + * Once a record size limit has been set, + * it will remain so for future recordings until it is + * changed by another setRecordSizeLimit call. + * + * @param aSize New size limit. + * @return Actual value set. + */ + virtual TInt SetRecordSizeLimitL(TInt aSize) = 0; + + /** + * Start the recording in implementation + */ + virtual void DoStartRecordL() = 0; + + /** + * Start the recording in implementation + */ + virtual void DoStopRecordL() = 0; + + /** + * Initialize native recorder + */ + virtual void InitializeL() = 0; + + /** + * Reset recorder + */ + virtual void DoResetL() = 0; + +public: // From CMMAControl + const TDesC& ClassName() const; + + +public: // from MMMAPlayerListener + void StateChanged(TInt aState); + +protected: // new methods + /** + * Sends record error event to Java + */ + void Error(TInt aErrorCode); + + /** + * Handles situation when record size limit is reached + */ + void HandleRecordSizeLimit(); + +private: // new methods + void NextStateL(TInt aPlayerState); + +protected: // Members + // Current state of recording + TRecordState iState; + + // Where to record + RFile iFile; + TFileName iFilename; + + // Recording player + CMMAPlayer* iPlayer; + + // Rfs used for creating temp file and deleting it + RFs iFs; +private: // Members + + // Stream to write data, owned + CMMAOutputStream* iOutputStream; + + /** + * Start time of recording. + */ + TInt64 iStartTime; + + /** + * Owned. Used to wait before pause if it + * is called too fast after starting. + */ + RTimer iRecordPauseTimer; +}; + + +#endif // CMMARECORDCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmasnapshot.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmasnapshot.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,177 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class takes snapshot and resizes bitmap if needed. +* +*/ + +#ifndef CMMASNAPSHOT_H +#define CMMASNAPSHOT_H + +// INCLUDES +#include +#include "tmmaparametervalidator.h" +#include "mmmasnapshot.h" + +// FORWARD DECLARATIONS +class MMMAGuiPlayer; +class MMMAEventPoster; +class MMMASnapshotReadyCallback; + + +// CLASS DECLARATION +/** +* This class takes snapshot from MMMAGuiPlayer and resizes bitmap +* if needed. Then bitmap is converted to wanted image format and posted +* to java side. This class is used only from CMMAVideoControl and +* this class is made to separate many asynchronous calls from control and +* resource releasing. +* +* +*/ + +NONSHARABLE_CLASS(CMMASnapshot): public CActive +{ +private: // private state + enum TMMASnapshotState + { + EIdle, + ETakingSnapshot, + EResizing, + EEncoding + }; +public: + /** + * Creates new CMMASnapshot which will be associated to gui player. + * + * @param aGuiPlayer Player used to take snapshot bitmap. + * @param aCallBack Will be informed when completed. + */ + static CMMASnapshot* NewL(MMMAGuiPlayer* aGuiPlayer, + MMMASnapshotReadyCallback& aCallBack); + /** + * Destructor. + */ + virtual ~CMMASnapshot(); + +private: + /** + * Creates required member variables. + */ + void ConstructL(); + + /** + * Contructs new CMMASnapshot. + * + * @param aGuiPlayer Used to take snapshot bitmap. + * @param aCallBack Will be informed when completed. + */ + CMMASnapshot(MMMAGuiPlayer* aGuiPlayer, + MMMASnapshotReadyCallback& aCallBack); + +public: // new methods + /** + * Takes snapshot from player and converts it to according to + * the properties. + * + * @param aProperties Snapshot's properties. + */ + void TakeSnapShotL(const TDesC& aProperties); + + /** + * Caller takes the ownership of the buffer. + * + * @return Image buffer. Ownership is transferred. + */ + HBufC8* ImageBuffer(); + + +private:// New methods + /** + * Resizing image to size of settings + */ + void ResizeL(); + + /** + * Encodes bitmap to wanted mime-type + */ + void EncodeL(); + + /** + * Called when snapshot is ready or error occures. This method will + * inform also the MMMASnapshotReadyCallback interface. + * + * @param aError Error code for the caller class. + */ + void Completed(TInt aError); + +public: // CActive + void RunL(); + TInt RunError(TInt aError); + void DoCancel(); + +private: + /** + * Bitmap encoder, owned + */ + CImageEncoder* iEncoder; + + /** + * Bitmap will be got from gui player and ownership is + * transfers to this class, owned + */ + CFbsBitmap* iBitmap; + + /** + * Bitmap scaler, owned + */ + CBitmapScaler* iScaler; + + /** + * Buffer used for storing encoded data, owned + */ + HBufC8* iBuffer; + + /** + * Bitmap settings, owned + */ + CMMAImageSettings* iSettings; + + /** + * Snapshot encoding + */ + MMMASnapshot::TEncoding iEncoding; + + /** + * GUI player interface, used for taking snapshot, not owned + */ + MMMAGuiPlayer* iGUIPlayer; + + /** + * When snapshot is ready or error occures callback will be informed. + */ + MMMASnapshotReadyCallback& iCallBack; + + /** + * Internal state + */ + TMMASnapshotState iState; +}; + +#endif // CMMASNAPSHOT_H + + + + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmasnapshotevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmasnapshotevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMASNAPSHOTEVENT_H +#define CMMASNAPSHOTEVENT_H + +// INCLUDES +#include "cmmaevent.h" + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +* +* +*/ +NONSHARABLE_CLASS(CMMASnapshotEvent): public CMMAEvent +{ +public: + CMMASnapshotEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TInt aError, + HBufC8* aImage, + TDisposability aDisposable = EDisposableEvent); + + ~CMMASnapshotEvent(); + +private: // from CJavaEvent + void Dispatch(JNIEnv& aJni); + +private: // data + HBufC8* iImageBuffer; +}; + +#endif // CMMASNAPSHOTEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmasourcestream.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmasourcestream.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class for reading data from Java SourceStream to native side +* +*/ + + +#ifndef CMMASOURCESTREAM_H +#define CMMASOURCESTREAM_H + +//#include +#include "MMAFunctionServer.h" + +class CMMASourceStreamEvent; +class MMMASourceStreamListener; +class MMMAEventPoster; + +// CONSTANTS +const TInt KMMAReadAllData = -1; + +// CLASS DECLARATION +/** +* Class for reading data from Java SourceStream to native side +* +* +*/ +NONSHARABLE_CLASS(CMMASourceStream): public CBase +{ +public: + /** + * Status of the source stream reader + */ + enum TStatus + { + EReadAll = 1, + ERead = 2, + EMoreData = 3, + ECompleted = 4, + EClosed = 5 + }; + +public: // Constructors and destructors + /** + * Object creation. Static method. + * + * @param aJNIEnv handle to used jni environment + * @param aEventPoster handle to event poster + * @param aJavaSourceStream handle to java SourceStream object + * @param aListener Handle to source stream listener + * + * @return CMMASourceStream object + */ + static CMMASourceStream* NewL(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener); + + /** + * The same as NewL with cleanup stack + * @see NewL + */ + static CMMASourceStream* NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener); + + /** + * Deletes owned objects + */ + ~CMMASourceStream(); // Destructor + +protected: // Constructors and destructors + + /** + * Set variables + * @param aEventPoster handle to event poster + * @param aListener handle to source stream listener + */ + CMMASourceStream(MMMAEventPoster* aEventPoster, + MMMASourceStreamListener* aListener); + + /** + * 2nd phase constructor + * + * @param aJNIEnv used jni environment + * @param aJavaSourceStream handle to java source stream object + */ + void ConstructL(JNIEnv* aJNIEnv, jobject aJavaSourceStream); + +public: // New methods + /** + * Writes data to from java buffer to native side + * + * @param aData data passed by Java side + * @param aLength size of passed data + * @param state of this class + */ + virtual void WriteL(const TUint8* aData, + TInt aLength, TInt aState); + /** + * Read aLength bytes from Java source stream + * + * @param aLength size of read + */ + void ReadL(TInt aLength); + + /** + * Read all data from Java source stream, clears buffer + */ + void ReadAllL(); + + /** + * Reset all data + */ + virtual void ResetData(); + + /** + * Creates data buffer + * + * @param aBufferSize data buffer size + */ + void CreateDataBufferL(TInt aBufferSize); + + +protected: // New methods + + /** + * Prepare whatever is necessary for reading + */ + virtual void PrepareReadL(); + +protected: + CMMASourceStreamEvent* iReadEvent; + MMMAEventPoster* iEventPoster; + MMMASourceStreamListener* iListener; + +protected: + /** + * Buffer where data from java side will be read, Owned + */ + HBufC8* iData; + + /** + * number of bytes coming from java stream, KMMAReadAllData is whole stream + */ + TInt iReadLength; + + /** + * current position + */ + TInt iBufferPosition; +}; + +#endif // CMMASOURCESTREAM_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmasourcestreamevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmasourcestreamevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + +#ifndef CMMASOURCESTREAMEVENT_H +#define CMMASOURCESTREAMEVENT_H + +// INCLUDES +#include "cmmaevent.h" + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +* +* +*/ + +NONSHARABLE_CLASS(CMMASourceStreamEvent): public CMMAEvent +{ +public: + CMMASourceStreamEvent(jmethodID aHandleEventMethod, + jobject aNotifyObject); + + // length of the requested source stream data + void SetLength(TInt aLength); + +private: // from CJavaEvent + void Dispatch(JNIEnv& aJni); + +private: + jmethodID iHandleEventMethod; + jobject iListenerObject; + TInt iLength; +}; + +#endif // CMMASOURCESTREAMEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmastoptimecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmastoptimecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling +* +*/ + + +#ifndef CMMASTOPTIMECONTROL_H +#define CMMASTOPTIMECONTROL_H + +// INCLUDES +#include "cmmacontrol.h" +#include "mmmaplayerstatelistener.h" + +class CMMAPlayer; + +// CLASS DECLARATION +/** +* This class is used for stoptime controlling +* +* +*/ + +NONSHARABLE_CLASS(CMMAStopTimeControl): public CMMAControl, MMMAPlayerStateListener +{ +protected: + /** + * Protected class for timing. + */ + class CStopTimer : public CTimer + { + public: + static CStopTimer* NewL(CMMAStopTimeControl* aControl); + + private: + CStopTimer(CMMAStopTimeControl* aControl); + void ConstructL(); + + public: // From CTimer + void RunL(); + + protected: + CMMAStopTimeControl* iControl; + }; + +public: + static CMMAStopTimeControl* NewL(CMMAPlayer* aPlayer); + ~CMMAStopTimeControl(); + +protected: + CMMAStopTimeControl(CMMAPlayer* aPlayer); + void ConstructL(); + +public: // new methods + static void StaticGetStopTime(CMMAStopTimeControl* aControl, + TInt64* aTime); + static void StaticSetStopTimeL(CMMAStopTimeControl* aControl, + TInt64* aTime); + virtual void StopAtTimeL(); + +protected: + virtual void GetStopTime(TInt64& aTime); + virtual void SetStopTimeL(const TInt64& aTime); + virtual void StartTimer(const TInt64& aTime); + +public: // From CMMAControl + const TDesC& ClassName() const; + +public: // From MMMAPlayerStateListener + void StateChanged(TInt aState); + +protected: + CMMAPlayer* iPlayer; + TInt64 iStopTime; // Stop time in microseconds + const TInt64 iNoTimer; + +private: + CStopTimer* iTimer; + +}; + +#endif // CMMASTOPTIMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideocontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideocontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,235 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a VideoControl. +* +*/ + + +#ifndef CMMAVIDEOCONTROL_H +#define CMMAVIDEOCONTROL_H + +// INCLUDES +#include "cmmacontrol.h" +#include "mmmasnapshotreadycallback.h" + +// mobitv fix // 3.x QT based UI +//#include "CMIDToolkit.h" +//#include "lcdui.h" +// FORWARD DECLARATIONS +class MMIDComponent; +class MMMAEventPoster; +class MMMAGuiPlayer; +class MMMADisplay; +class CMMASnapshot; +class MMAFunctionServer; +class CMMAEvent; + +// CLASS DECLARATION +/** +* This class is native side of the VideoControl java object. +* +* +*/ +class CMMAVideoControl : + public CMMAControl, + public MMMASnapshotReadyCallback/*, // 3.x QT based UI + public MMIDEnvObserver*/ +{ +public: + /** + * @param aGuiPlayer Player that will be used. + */ + IMPORT_C CMMAVideoControl(MMMAGuiPlayer* aGuiPlayer); + + /** + * Deletes owned objects and removes global reference to + * associated displayable object. + */ + IMPORT_C ~CMMAVideoControl(); + + /** + * Finishes video control construction. This construction step + * must be called from JNI, because JNIEnv is needed to create + * callback methods to Java side. + * + * @param aVideoControl Used video control. + * @param aControlObject Corresponding Java object. + * @param aJni JNI environment used. + * @param aEventPoster Used to post repaint and + * snapshot ready events. + */ + static void ConstructL(CMMAVideoControl* aVideoControl, + jobject aControlObject, + MMAFunctionServer* aEventSource, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster/*, + CMIDToolkit* aToolkit*/); // mobitv fix // 3.x QT based UI + +public: // New methods + /** + * Initializes display. Called when java display mode is initialized. + * Created MMMADisplay object and sets it to associated gui player. + * + * @param aVideoControl Used video control. + * @param aComponent Component that will be used to create display. + * @param aDisplayHandle Java handle to created display will be set to + * this variable. Still owned by video control. + * @param aDeleteRefEvent Event posted in the destructor. + */ + static void StaticInitL(CMMAVideoControl* aVideoControl, + jobject javaDisplayObject, + MMAFunctionServer* aEventSource, + TInt* aDisplayHandle, + CMMAEvent* aDeleteRefEvent); + + /** + * Dynamic display mode initialization. + * @see StaticInitL + * @param aVideoControl Used video control. + * @param aContentHandle Will contain handle to MMMADirectContent + * @param aDeleteRefEvent Event posted in the destructor. + */ + static void StaticInitDynamicModeL(CMMAVideoControl* aVideoControl, + TInt* aContentHandle, + MMAFunctionServer* aEventSource, + jobject aGUIObject, + CMMAEvent* aDeleteRefEvent); + + + /** + * Gets property according to property type. + * + * @param aControl Used video control. + * @param aPropertyType Type defined in Java header. + * @param aReturnValue Property value will be set to this parameter. + */ + static void StaticGetPropertyL(CMMAVideoControl* aControl, + TInt aPropertyType, + TInt* aReturnValue); + + /** + * Sets property that is defined by type. Amount of propery + * parameters used depends on property type. + * + * @param aControl Used video control. + * @param aPropertyType Type defined in Java header. + * @param aPropertyA First value. + * @param aPropertyB Second value. + */ + static void StaticSetPropertyL(CMMAVideoControl* aControl, + TInt aPropertyType, + TInt aPropertyA, + TInt aPropertyB); + + /** + * Takes snapshot from the associated gui player. When ready + * Java side will be informed with iSnapshotReadyMethod. + * + * @param aControl Used video control. + * @param aProperties Properties used to create snapshot. + */ + static void TakeSnapShotL(CMMAVideoControl* aControl, + const TDesC* aProperties); + static void StaticSetForegroundL(CMMAVideoControl* aControl, + TInt aForeground) ; + +public: // From MMMASnapshotReadyCallback + IMPORT_C void SnapshotReady(); + +public: // From CMMAControl + IMPORT_C const TDesC& ClassName() const; +public: + TBool IsForeground(); + void SetDisplayHandleToJavaPeer(MMAFunctionServer* eventSource ,jobject javaVideoControlPeer); + +protected: + // 3.x QT based UI + // void RegisterForegroundListenerL(CMIDToolkit* aToolkit); // mobitv fix + +//public: // from MMIDEnvObserver + + // void HandleSwitchOnL(TBool /*aSwitchOn*/); + + //Handles the case when the MIDlet is brought to the foreground. + // void HandleForegroundL(TBool /*aForeground*/); + + // Handles a change to resources which are shared accross the environment. +// void HandleResourceChangeL(TInt /*aType*/); + +private: + + void SetForeground(TBool aForeground, TBool aUseEventServer); + +protected: + /** + * Not owned. + */ + MMMAEventPoster* iEventPoster; + + /** + * Not owned. + */ + MMMAGuiPlayer* iGuiPlayer; + + /** + * Not owned. + */ + JNIEnv* iJni; + + /** + * Owned object. Used to control displayable object. + */ + MMMADisplay* iDisplay; + + /** + * Owned object. Created when snapshot is taken and destroyed + * when snapshot is ready. Destroyed also in destuctor if control is + * destroyed when taking snapshot. + */ + CMMASnapshot* iSnapshot; + + /** + * Java video control object. + */ + jobject iListenerObject; + + /** + * Used inform Java side when snapshot is ready or error occures. + */ + jmethodID iSnapshotReadyMethod; + + /** + * Owned object. Not created by the class. + * Event is used to destroy reference to associated displayable object, + * when video control is destroyed. + */ + CMMAEvent* iDeleteRefEvent; + + /** + * When video display is set to full screen mode, old + * video position & size is stored to this member. When + * full screen mode is turned off, this member is used to + * find out if display size has been changed during full + * screen mode. This is needed to generate a SIZE_CHANGED + * event. + */ + TSize iOldDisplaySize; + // mobitv fix + //CMIDToolkit* iToolkit; + // MMIDEnv* iMidEnv; + TBool iIsForeground; + +}; + +#endif // CMMAVIDEOCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideoframepositioningcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideoframepositioningcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements FramePositioningControl for video player +* +*/ + + +#ifndef CMMAVIDEOFRAMEPOSITIONINGCONTROL_H +#define CMMAVIDEOFRAMEPOSITIONINGCONTROL_H + +// INTERNAL INCLUDES +#include "cmmavideoplayer.h" +#include "cmmaframepositioningcontrol.h" // base class + +// CONSTANTS + +// CLASS DECLARATION +/** +* This class implements FramePositioningControl for video player +*/ +NONSHARABLE_CLASS(CMMAVideoFramePositioningControl) : + public CMMAFramePositioningControl +{ +public: + static CMMAVideoFramePositioningControl* NewL(CMMAVideoPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMAVideoFramePositioningControl(); + +protected: + /** + * Constructor. + */ + CMMAVideoFramePositioningControl(CMMAVideoPlayer* aPlayer); + +public: // From CMMAFramePositioningControl + TInt SeekL(TInt aFrameNumber); + TInt SkipL(TInt aFramesToSkip); + void MapFrameToTimeL(TInt aFrameNumber, TInt64* aMediaTime); + TInt MapTimeToFrameL(TInt64* aMediaTime); + +private: // New methods + /** + * Get framerate of video and check that it is > 0 . + */ + void GetAndCheckFrameRateL(TReal32& aFrameRate); + +private: + CMMAVideoPlayer* iPlayer; + +}; + + +#endif // CMMAVIDEOFRAMEPOSITIONINGCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideoplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideoplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating video player. +* +*/ + + +#ifndef CMMAVIDEOPLAYERFACTORY_H +#define CMMAVIDEOPLAYERFACTORY_H + +// INCLUDES +#include "cmmammfplayerfactory.h" +// CONSTANTS + +// CLASS DECLARATION +/** +* This class is used for creating video player. +* +* +*/ + +NONSHARABLE_CLASS(CMMAVideoPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Constructor and destructor + static CMMAVideoPlayerFactory* NewLC(); + ~CMMAVideoPlayerFactory(); + +private: // Constructor + CMMAVideoPlayerFactory(); + +public: // New methods + +#ifdef RD_JAVA_OMA_DRM_V2 + CMMAPlayer* CreatePlayerWithFileL(const TDesC& aContentType, + const TDesC* aFileName); +#endif // RD_JAVA_OMA_DRM_V2 + +public: // From CMMAMMFPlayerFactory + + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + + + void MediaIdsL(RArray& aMediaIds); + +private: //data +#ifdef RD_JAVA_OMA_DRM_V2 + const TDesC* iFileName; +#endif // RD_JAVA_OMA_DRM_V2 +}; + +#endif // CMMAVIDEOPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideorecordcontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideorecordcontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,151 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a RecordControl. +* +*/ + + +#ifndef CMMAVIDEORECORDCONTROL_H +#define CMMAVIDEORECORDCONTROL_H + +// EXTERNAL INCLUDES +#include + +// INTERNAL INCLUDES +#include "cmmarecordcontrol.h" +#include "tmmaparametervalidator.h" + +// FORWARD DECLARATIONS +class CMMAPlayer; +class CMMAPlayerProperties; +class CMMAMMFResolver; + +// CLASS DECLARATION +/** +* This class implements RecordControl interface for camera player. +* +* +*/ +NONSHARABLE_CLASS(CMMAVideoRecordControl): public CMMARecordControl, + public MVideoRecorderUtilityObserver +{ + +public: + /** + * Creates new CMMAVideoRecordControl. + * + * @param aPlayer Player that controls the camera. + * @param aProperties Properties given in java player creation. + * @param aCameraHandle Handle to a camera, which is used as a source. + */ + static CMMAVideoRecordControl* NewL(CMMAPlayer* aPlayer, + CMMAMMFResolver* aResolver, + const TMMAVideoSettings& aVideoSettings, + CMMAAudioSettings* aAudioSettings, + TInt aCameraHandle); +protected: + CMMAVideoRecordControl(CMMAPlayer* aPlayer, + TInt aCameraHandle); + ~CMMAVideoRecordControl(); + + /** + * Initializes this control. + * @param aProperties Properties given in java player creation. + */ + void ConstructL(RMMFControllerImplInfoArray& aRMMFControllerInfos, + const TMMAVideoSettings& aVideoSettings, + CMMAAudioSettings* aAudioSettings); + +public: // From CMMARecordControl + void InitializeL(); + void DoStartRecordL(); + void DoStopRecordL(); + void DoResetL(); + TInt SetRecordSizeLimitL(TInt aSize); + +public: // From MVideoRecorderUtilityObserver + /** + * Notification to the client that the opening of the video clip has completed, + * successfully, or otherwise + * + * @param "aError" + * The status of the video recorder after initialisation. + * This is either KErrNone if the open has completed successfully, + * or one of the system wide error codes + */ + void MvruoOpenComplete(TInt aError); + + /** + * Notification that video recorder is ready to begin recording. This callback + * is generated in response to a call to Prepare. + * + * @param "aError" + * This is either KErrNone if the video recorder has been prepared for + * recording successfully, or one of the system wide error codes + */ + void MvruoPrepareComplete(TInt aError); + + /** + * Notification that video recording has completed. This is not called if + * recording is explicitly stopped by calling Stop. + * + * @param "aError" + * This is either KErrNone if recording was completed successfully, + * or one of the system wide error codes + */ + void MvruoRecordComplete(TInt aError); + + /** + * General event notification from controller. These events are specified by + * the supplier of the controller + * + * @param "aEvent" + * The event sent by the controller + */ + void MvruoEvent(const TMMFEvent& aEvent); + +private: // New methods + + /** + * Actually sets record size limit + * Will set local member to KNoUserDefinedRecordSize (-1) + * @param aSize New record size limit + */ + void DoSetRecordSizeLimitL(TInt aSize); + +private: // Data + TInt iCameraHandle; // camera that is used as an image source + + // Actual recording utility, owned + CVideoRecorderUtility* iRecorder; + + CActiveSchedulerWait* iActiveSchedulerWait; + + /** + * Global error code, used for getting error codes from callbacks + */ + TInt iError; + + /** + * Record size limit, will be KNoUserDefinedRecordSize (-1) when + * user has not set limits + */ + TInt iRecordSizeLimit; + + TMMAVideoSettings iVideoSettings; // Video settings + +}; + + +#endif // CMMAVIDEORECORDCONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideourlplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideourlplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,189 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing URL videos +* +*/ + + +#ifndef CMMAVIDEOURLPLAYER_H +#define CMMAVIDEOURLPLAYER_H + + +// INCLUDES +#include "cmmavideoplayer.h" +#include "mmmaguiplayer.h" +#include + +// FORWARD DECLARATIONS +class MMAFunctionServer; + +// CLASS DECLARATION +/** +* This class is used for playing video. +* +* +*/ + +class CMMAVideoUrlPlayer: public CMMAVideoPlayer +{ +protected: + /** + * Protected abstract base class for url player delegates. + */ + class CMMAVideoUrlPlayerDelegate : public CBase + { + public: + virtual ~CMMAVideoUrlPlayerDelegate(); + + protected: + /** + * C++ constructor + */ + CMMAVideoUrlPlayerDelegate(CMMAVideoUrlPlayer& aPlayer); + + public: + /** + * Handles StartL call for url player. + */ + virtual void StartL() = 0; + + /** + * Handles StopL call for url player. + * + * @param aPostEvent post event to Java side + */ + virtual void StopL(TBool aPostEvent) = 0; + + /** + * Gets media time for url player. + * + * @param aMediaTime When method returns parameter contains the media + * time. + */ + virtual void GetMediaTime(TInt64* aMediaTime) = 0; + + /** + * Handles events for url player. + * + * @param aEvent event type + */ + virtual void HandleEvent(const TMMFEvent& aEvent) = 0; + + protected: // data + CMMAVideoUrlPlayer& iPlayer; + }; + + /** + * Delegate class for non-live video streams + */ + class CMMAVideoUrlPlayerClipStreamDelegate : + public CMMAVideoUrlPlayerDelegate + { + public: + CMMAVideoUrlPlayerClipStreamDelegate(CMMAVideoUrlPlayer& aPlayer); + virtual ~CMMAVideoUrlPlayerClipStreamDelegate(); + + public: // from CMMAVideoUrlPlayerDelegate + void StartL(); + void StopL(TBool aPostEvent); + void GetMediaTime(TInt64* aMediaTime); + void HandleEvent(const TMMFEvent& aEvent); + }; + + /** + * Delegate class for live video streams + */ + class CMMAVideoUrlPlayerLiveStreamDelegate : + public CMMAVideoUrlPlayerDelegate + { + public: + static CMMAVideoUrlPlayerLiveStreamDelegate* + NewL(CMMAVideoUrlPlayer& aPlayer); + + virtual ~CMMAVideoUrlPlayerLiveStreamDelegate(); + + protected: + CMMAVideoUrlPlayerLiveStreamDelegate(CMMAVideoUrlPlayer& aPlayer); + void ConstructL(); + + public: // from CMMAVideoUrlPlayerDelegate + void StartL(); + void StopL(TBool aPostEvent); + void GetMediaTime(TInt64* aMediaTime); + void HandleEvent(const TMMFEvent& aEvent); + + private: // data + CActiveSchedulerWait* iActiveSchedulerWait; + + /** + * RTSP live stream returns current media time + * from the server, but local media time must + * start from zero. Thus start media time is + * cached here. + */ + TInt64 iMediaStartTime; + + /** + * Hold player stop time value. It is otherwise + * forgotten when player is stopped. + */ + TInt64 iStoppedAtTime; + }; + +public: // Construction + static CMMAVideoUrlPlayer* NewLC( + CMMAMMFResolver* aResolver, + const TDesC& aUrl); + + // Destructor + IMPORT_C ~CMMAVideoUrlPlayer(); + +protected: + // C++ constructor + IMPORT_C CMMAVideoUrlPlayer(CMMAMMFResolver* aResolver); + IMPORT_C void ConstructL(const TDesC& aUrl); + +public: // from CMMAPlayer + IMPORT_C void RealizeL(); + IMPORT_C void PrefetchL(); + IMPORT_C void StartL(); + IMPORT_C void StopL(TBool aPostEvent); + IMPORT_C void GetMediaTime(TInt64* aMediaTime); + IMPORT_C void DeallocateL(); + IMPORT_C void CloseL(); + +protected: // New Methods + void FindActiveIap(const TUint aConnectionCount, TUint& aActiveIap); + virtual TBool IsLiveStreamL(); + + /** + * Handles events from delegate classes to + * superclass HandleEvent. + * + * @param aEvent event data + */ + void HandleEventToParent(const TMMFEvent& aEvent); + +protected: // From CMMAVideoPlayer + IMPORT_C void HandleEvent(const TMMFEvent& aEvent); + +protected: // Data + HBufC* iUrl; // Owned url + RConnection iConnection; + RSocketServ iSocketServ; + TThreadPriority iOrigPriority; + CMMAVideoUrlPlayerDelegate* iPlayerDelegate; +}; + +#endif // CMMAVIDEOURLPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavideourlplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavideourlplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating video player. +* +*/ + + +#ifndef CMMAVIDEOURLPLAYERFACTORY_H +#define CMMAVIDEOURLPLAYERFACTORY_H + +// INCLUDES +#include "cmmammfplayerfactory.h" +// CONSTANTS + + +// CLASS DECLARATION +/** +* This class is used for creating URL video players +* +* +*/ + +NONSHARABLE_CLASS(CMMAVideoUrlPlayerFactory): public CMMAMMFPlayerFactory +{ +public: // Constructor and destructor + static CMMAVideoUrlPlayerFactory* NewLC(); + ~CMMAVideoUrlPlayerFactory(); + +private: // Constructor + CMMAVideoUrlPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +public: // From CMMAMMFPlayerFactory + CMMAPlayer* CreatePlayerL( + CMMAMMFResolver* aResolver); + + + void MediaIdsL(RArray& aMediaIds); + + CMMFPluginSelectionParameters::TMediaIdMatchType + MediaIdMatchType(); + +private: // Data + HBufC* iUrl; // owned url +}; + +#endif // CMMAVIDEOURLPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/cmmavolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/cmmavolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for volume setting +* +*/ + + +#ifndef CMMAVOLUMECONTROL_H +#define CMMAVOLUMECONTROL_H + +// INCLUDES +#include "cmmacontrol.h" +#include "mmmaplayerstatelistener.h" + +// CONSTANS +_LIT(KMMAVolumeControlName, "VolumeControl"); +const TInt KMMAVolumeMaxLevel = 100; + +class CMMAPlayer; + +// CLASS DECLARATION +/** +* This class is used for volume setting +* +* +*/ + +class CMMAVolumeControl : public CMMAControl, + public MMMAPlayerStateListener +{ +public: + static void StaticSetLevelL(CMMAVolumeControl* aVolumeControl, + TInt aLevel); + static void StaticGetLevelL(CMMAVolumeControl* aVolumeControl, + TInt* aLevel); + + ~CMMAVolumeControl(); + +protected: + CMMAVolumeControl(CMMAPlayer* aPlayer); + void ConstructBaseL(); + + /** + * Sets the level to player. + * @param aLevel Sound level to set. + */ + virtual void DoSetLevelL(TInt aLevel) = 0; + + /** + * Get volume level from player. + * @return Current level. + */ + virtual TInt DoGetLevelL() = 0; + +public: // From CMMAControl + const TDesC& ClassName() const; + + /** + * Refresh volume control. + */ + void RefreshControl(); + +public: // From MMMAPlayerStateListener + void StateChanged(TInt aState); + + +public: // New methods + /** + * Adds new volume level to volume control. Actual volume level will + * be calculated using all levels added to the control. + * @return Index for new level. + */ + IMPORT_C TInt AddLevelL(); + + /** + * Sets new volume level for certain level index. After level is set + * new actual level is calculated and commited to player in derived + * class. + * @param aLevelIndex Level's index + * @param aVolumeLevel New volume level for level index. Level must be + * between 0 and 100. + */ + IMPORT_C void SetVolumeLevelL(TInt aLevelIndex, + TInt aVolumeLevel); + void GetVolumeLevelL(TInt aLevelIndex, + TInt* aVolumeLevel); + + + +private: // New methods + + /** + * Refresh volume level, basically set the volume level again. + */ + void RefreshVolume(); + + /** + * Sets level if player is started and sends java event level + * changed. + * @param aLevel Sound level to set. + */ + void SetLevelL(TInt aLevel); + + /** + * Calculates new overall level using all values in iLevels array. + * @return Current level. + */ + TInt CalculateLevel(); +protected: // data + CMMAPlayer* iPlayer; + + // Previous level setted to player. Used to check if level is changed. + TInt iLevel; + + // Array containing all levels. + RArray< TInt > iLevels; + +}; + +#endif // CMMAVOLUMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmafunctionserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmafunctionserver.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,194 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class provides CJavaEventSource services +* +*/ + + +#ifndef CMMAEVENTSOURCE_H +#define CMMAEVENTSOURCE_H + +// INCLUDES +#include "mmmaeventposter.h" +//#include +#include "functionserver.h" +#include "legacyeventserverwrapper.h" +#include +// FORWARD DECLARATIONS +class CApaWindowGroupName; +class CMMAPlayer; +class MMMAPlayerInstanceObserver; +#ifdef RD_JAVA_VOLUME_CONTROL +class CMMAGlobalVolume; +#endif // RD_JAVA_VOLUME_CONTROL + +// CLASS DECLARATION +/** +* This class provides CJavaEventSource services. +* +* +*/ + +class MMAFunctionServer : public java::util::FunctionServer,public LegacyEventServerWrapper, + public MMMAEventPoster +{ +public: + /** + * Default constructor. + */ + MMAFunctionServer(JNIEnv& aJni, jobject aPeer); + + /** + * Destructor. + */ + ~MMAFunctionServer(); + +public: // From CJavaEventSource, construction + /** + * Normal construction, Invoked from base class. + * Method is defined in the base class. + */ + void ConstructL(JNIEnv& aJni, + jobject aPeer + ); + + /** + * Server side construction. + */ + void ConstructSvrL(); + static TInt NewL(JNIEnv& aJni, jobject aPeer); + + void Dispose(); + + TBool IsDisposed() const + { + return iDisposed; + } + +public: // new methods + /** + * Adds object to cleanup. Added objects are deleted when event source + * is deleted. + * + * @param aEventSource Event source to use. + * @param aHandle Java handle to CBase object + */ + IMPORT_C static void StaticAddObjectFromHandleL(MMAFunctionServer* aEventSource, + TInt aHandle); + + /** + * Adds player object to cleanup. Added objects are deleted when event + * source is deleted. An object added to the event source must be + * deleted with DisposePlayer method. + * + * @param aEventSource Event source to use. + * @param aHandle Java handle to CBase object + */ + void AddPlayerL(CMMAPlayer* aPlayer); + + /** + * Removes player from array and deletes it. + * + * @param aPlayer Player to be deleted. + */ + void DisposePlayer(CMMAPlayer* aPlayer); + + /** + * Sets player instance observer. + * @param aObserver Will be informed when player is created or deleted. + */ + IMPORT_C void SetPlayerInstanceObserver(MMMAPlayerInstanceObserver* aObserver); + + /** + * Return reference to the array containing all players. + * @return All players + */ + IMPORT_C RPointerArray< CMMAPlayer >& Players(); + + /** + * Realeases resources. + */ + void Release(); + + /** + * Returns player pointer for java player handle if the native player + * peer exists. Otherwise returns null. + * @param aPlayerHandle Java side player handle integer + * @param CMMAPlayer* player pointer + */ + CMMAPlayer* FindPlayer(TInt aPlayerHandle); + + /** + * Sets MMA global volume handler + * @param aGlobalVolume Global volume handler. The onwership is + * transferred to this class + */ +#ifdef RD_JAVA_VOLUME_CONTROL + void SetGlobalVolume(CMMAGlobalVolume* aGlobalVolume); +#endif // RD_JAVA_VOLUME_CONTROL + + java::util::FunctionServer* getFunctionServer() const; + + JNIEnv* getValidJniEnv(); + jobject getPeer(); +private: + /** + * @see StaticAddObjectFromHandleL + * @param aHandle Java handle to CBase object + */ + void AddObjectFromHandleL(TInt aHandle); + +private: // from CJavaEventSource + void FinalizeSvr(); + +public: // MMMAEventPoster + void PostEvent(CMMAEvent* aEvent, TInt aPriority); + +private: + bool mVmAttached; + java::util::FunctionServer* iServer; +private: + /** + * Objects added with StaticAddObjectFromHandleL. Will be destroyed + * in server finalization. + */ + RPointerArray< CBase > iObjects; + + // Owned array of players. + RPointerArray< CMMAPlayer > iPlayers; + + /** + * MMA needs ui framework. Window group must be hidden from the + * user. + */ + CApaWindowGroupName* iWgName; + + /** + * Used to check if session was connected in the constructor. + */ + TBool iFbsSessionConnected; + TBool iDisposed; + + // Not owned. Will be informed if it is set. + MMMAPlayerInstanceObserver* iInstanceObserver; + + JavaVM* iJavaVM; + + // Global volume handler. Owned +#ifdef RD_JAVA_VOLUME_CONTROL + CMMAGlobalVolume* iGlobalVolume; +#endif // RD_JAVA_VOLUME_CONTROL +}; + +#endif // CMMAEVENTSOURCE_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmacontainer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmacontainer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +#ifndef MMMACONTAINER_H +#define MMMACONTAINER_H + +class MMMADirectContent; +class MUiEventConsumer; + +/** +A container on which content can be displayed. +Content can be drawn to container using direct screen access or frame buffer +mode. +*/ +class MMMAContainer +{ +public: + /** + Remove the content. This will called when the Player is closed. + */ + virtual void MdcRemoveContent() = 0; + + /** + Get the visiblity of the container. The content must not be displayed + when it's container is invisible. + If this changes MdcContainerVisibilityChanged should be called. + @returns "aVisible" ETrue if the container is visible, EFalse if it is invisible. + */ + virtual TBool MdcContainerVisibility() const = 0; + + /** + Repaint frame buffer to screen. + */ + virtual void MdcRepaint() const = 0; + + /** + Get the bounds of the area that the content can occupy. + The content should be clipped to this area. + @param aContentRect Maximum area the content can occupy in screen co-ordinates. + @param aParentRect Visible part of the parent in screen co-ordinates. + */ + virtual void MdcGetContentRect(TRect& aControlRect, + TRect& aParentRect) const = 0; + + /** + This method is called when content knows its preferred size. This method + will be called for example when video content obtains its size. Container + must inform new content rect using content's MdcContentBoundsChanged method. + @param aPreferredSize preferred size for the content. + */ + virtual void MdcInvalidate(const TSize& aPreferredSize) = 0; + + /** + Set the size of the render region for the video clip to be fullscreen. + After this call MESWTDirectContent must be informed about new draw area. + @param aFullScreen Indicates whether or not to render in full screen mode + */ + virtual void MdcSetDisplayFullScreen(TBool aFullScreen) = 0; + + /** + * Invokes callback aConsumer->MdcDSAResourcesCallback in UI thread. + * Used in case when MMAPI needs to start DSA within UI thread. + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aIsInUiThread" Notifies that the method runs in UI thread + */ + virtual void MdcGetDSAResources( + MUiEventConsumer& aConsumer, + TBool aIsInUiThread) = 0; + + /** + * Invokes callback aConsumer->MdcUICallback in UI thread. + * Used in case when MMAPI needs to run some operation within UI thread. + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aCallbackId" A number identifying the callback + */ + virtual void MdcGetUICallback( + MUiEventConsumer& aConsumer, + const TInt aCallbackId) = 0; + + /** + * Get the bounds of the content window. + * + * @returns The rect of the content window in screen co-ordinates. + */ + virtual TRect MdcContainerWindowRect() const = 0; +}; + + +#endif // MMMACONTAINER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmadirectcontent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmadirectcontent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +#ifndef MMMADIRECTCONTENT_H +#define MMMADIRECTCONTENT_H + +class MMMAContainer; + +/** + * Content, such as a video clip or camera view finder, which is displayed on + * a container. + */ +class MMMADirectContent +{ +public: + /** + * Notify content that container visiblity has changed. The content must not + * be displayed when it's container is invisible. + * @param "aVisible" ETrue if the container is visible, EFalse if it is invisible. + */ + virtual void MdcContainerVisibilityChanged(TBool aVisible) = 0; + + /** + * Notify content that content rect is changed. + * @param aContentRect Maximum area the content can occupy in screen + * co-ordinates. + * @param aParentRect area that can be used to draw content in screen + * co-ordinates. + */ + virtual void MdcContentRectChanged(const TRect& aContentRect, + const TRect& aParentRect) = 0; + + /** + * Notify content that container is about to be destoryed. + */ + virtual void MdcContainerDestroyed() = 0; + + /** + * Sets new container for content. Content may not support changing + * container. + * @parma aContainer New container for content + */ + virtual void MdcSetContainer(MMMAContainer* aContainer) = 0; + + /** + * This is used in bitmap mode. DSA mode content return allways NULL. + * @return Bitmap to draw or NULL if not available. + */ + virtual CFbsBitmap* MdcFrameBuffer() const = 0; + + /** + * This is used get preferred size when container need content size + * @return source size which preferred size for container + */ + virtual TSize MdcSourceSize() = 0; + + /** + * Notify content that the rect of a window has changed. + * + * @param aRect New rect of a window. + */ + virtual void MdcContainerWindowRectChanged(const TRect& aRect) = 0; +}; + +#endif // MMMADIRECTCONTENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmadisplay.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmadisplay.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,205 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface for displays, which can show images. +* +*/ + + +#ifndef MMMADISPLAY_H +#define MMMADISPLAY_H + +#include "jni.h" +// FORWARD DECLARATIONS +class CFbsBitmap; +class MMMADisplayWindow; +class MUiEventConsumer; +class MMMAGuiPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + + Interface for displays, which can show images. Display properties + can be changed through this interface. + +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(MMMADisplay) +{ +public: + /** + * Describes the currently running thread type. + */ + enum TThreadType + { + EMmaThread = 0, // MMAPI thread + EUiThread = 1 // UI thread (LCDUI or ESWT) + }; + + /** + * Display can be deleted through this interface. + */ + virtual ~MMMADisplay() + { + }; + + /** + * Draws bitmap. Implementation may ignore aBitmap + * parameter and implements own drawing procedure. This method must also redraw + * the display if needed. + * + * @param aBitmap Bitmap to be drawn. + */ + virtual void DrawFrameL(const CFbsBitmap* aBitmap) = 0; + + /** + * Getter for display's size. + * + * @return Display size. + */ + virtual TSize DisplaySize() = 0; + + /** + * Sets display size or leaves if not supported or + * size cannot be changed. + * + * @param aSize New size for the display. + */ + virtual void SetDisplaySizeL(const TSize& aSize) = 0; + + /** + * Sets display location. + * + * @param aPosition New position for the display. + */ + virtual void SetDisplayLocationL(const TPoint& aPosition) = 0; + + /** + * Returns position where display is drawn. + * + * @return Display location. + */ + virtual TPoint DisplayLocation() = 0; + + /** + * Sets display fullscreen mode on/off. + * + * @param aFullScreen Fullscreen mode. + */ + virtual void SetFullScreenL(TBool aFullScreen) = 0; + + /** + * Sets display visible or hides it. + * + * @param aVisible ETrue if display is visible, + * EFalse if display is invisible. + */ + virtual void SetVisible(TBool aVisible) = 0; + + /** + * Called when source size is changed. This is also called when + * source size is available for the first time. + * + * @param aSourceSize New content's size. + */ + virtual void SourceSizeChanged(const TSize& aSourceSize) = 0; + + virtual TSize SourceSize() = 0; + + virtual void SetUIPlayer(MMMAGuiPlayer* player) = 0; + /** + * Sets display's window. Ownership is not transfered. + * + * @param aWindow New window used for drawing. + **/ + virtual void SetWindowL(MMMADisplayWindow* aWindow) = 0; + + /** + * Getter for window. + * + * @return Display's window or NULL if not set. + */ + virtual MMMADisplayWindow* Window() = 0; + + /** + * Returns visibility of the display. + * + * @return ETrue if display is visible, + * EFalse if display is invisible. + */ + virtual TBool IsVisible() = 0; + + /** + * Returns fullscreen state of the display. + * + * @return ETrue if display is fullscreen, + * EFalse if display is not fullscreen. + */ + virtual TBool IsFullScreen() = 0; + /** + *Sets the foreground state of the midlet + * + * @param ETrue if midlet is in foreground, + * EFalse if midlet is in background + */ + virtual void SetForeground(TBool aForeground, TBool aUseEventServer) = 0; + + /** + * Gets notification that there is container to draw assigned + * + * @return ETrue if container have been set + * EFalse if container is not set + */ + virtual TBool HasContainer() = 0; + + /** + * Gets resources necessary to start DirectScreenAccess + * Doesn't run in mmapi event server thread! + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aThreadType" Indicates the thread type (UI or MMAPI) + */ + /* virtual void UIGetDSAResources( + MUiEventConsumer& aConsumer, + TThreadType aThreadType) = 0; +*/ + /** + * Invokes a callback in UI thread + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aCallbackId" A number identifying the callback + */ + /* virtual void UIGetCallback( + MUiEventConsumer& aConsumer, + TInt aCallbackId) = 0; + */ + + /** + * Trigger a function call CalledBackInUiThread() from java in UI thread + * arg 'placeholder' is used to identify the function, to be called back from UI Thread + */ + virtual void GetCallbackInUiThread(TInt placeholder) = 0; + + /** + * Called from java in UI thread context + * arg 'placeholder' is used to identify the function, to be called back from UI Thread + */ + virtual void CalledBackInUiThread(TInt placeholder) = 0; +}; + +#endif // MMMADISPLAY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmadisplaywindow.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmadisplaywindow.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,253 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Abstract base class for windows. +* +*/ + + +#ifndef MMMADISPLAYWINDOW_H +#define MMMADISPLAYWINDOW_H + + +#include "mmmadisplay.h" +#include "qwidget.h" +#include "COECNTRL.h" +#include "COEMAIN.h" +// FORWARD DECLARATIONS +class CFbsBitmap; +class CMMAPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + + Abstract base class for windows. + +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(MMMADisplayWindow) +{ +public: + + enum TDisplayWindowType + { + EDisplayWindowTypeNotSet = -1, + EDisplayWindowTypeIsDSA, + EDisplayWindowTypeIsBitmap, + EDisplayWindowTypeIsCamera, + }; + + /** + * Can be deleted through this interface. + */ + virtual ~MMMADisplayWindow() + { + }; + + /** + * Sets destination bitmap for DrawFrameL method + * + * @param aBitmap destination Bitmap where DrawFrameL draws. + */ + virtual void SetDestinationBitmapL(CFbsBitmap* aBitmap) = 0; + + /** + * Draws bitmap to the rect set with SetDrawRectL + * method. Bitmap may be scaled to fill whole rect. Implementation + * may ignore aBitmap parameter and implements own + * drawing procedure. + * + * @param aBitmap Bitmap to be drawn. + */ + virtual void DrawFrameL(const CFbsBitmap* aBitmap) = 0; + + /** + * Sets drawing area which is used in DrawFrameL method. + * + * THE CALL CANNOT ORIGINATE FROM UI THREAD. + * (including the call via MMA event server) + * + * use SetDrawRectThread when in UI thread + * + * @param aRect New drawing area. + */ + virtual void SetDrawRect(const TRect& aRect) = 0; + + /** + * Calls SetDrawRect method through event source. This method must + * be called instead of SetDrawRect if not executing in MMA + * thread. + * + * THE CALL CANNOT ORIGINATE FROM MMA THREAD. + * (including the call via UI event server) + * + * @param aRect New drawing area. + */ + virtual void SetDrawRectThread(const TRect& aRect) = 0; + + /** + * Sets drawing position which is used in DrawFrameL method. + * + * @param aPosition New drawing position. + */ + virtual void SetPosition(const TPoint& aPosition) = 0; + + /** + * Sets window visible or invisible. This method can be called from + * MMA event server thread or from other context. aUseEventServer + * must be set to EFalse if caller is already in MMA event server. + * + * @param aVisible visiblity + * @param aUseEventServer Indicates if method must called through event + * server. + */ + virtual void SetVisible(TBool aVisible, TBool aUseEventServer = ETrue) = 0; + + /** + * Returns rect which is used for drawing frames. + * + * @return Drawing area + */ + virtual const TRect& DrawRect() = 0; + + /** + * Returns whole window's size. + * + * @return Size of the window. + */ + virtual TSize WindowSize() = 0; + + /** + * Sets window size. + * + * @param aRect Windows size. + */ + virtual void SetWindowRect(const TRect& aRect, MMMADisplay::TThreadType aThreadType) = 0; + + /** + * Gets window rect. + * + * @returns Windows rect. + */ + virtual const TRect& WindowRect() = 0; + + virtual CMMAPlayer* UiPlayer() + { + } + + #ifdef RD_JAVA_NGA_ENABLED + /** + * Sets Crop region. used only in CMMASurfaceWindow + * + * @since S60 v5.2 + */ + virtual void SetVideoCropRegion(const TRect& /*aRect*/) + { + // Empty + } + + /** + * Sets RWindow rect. used only in CMMASurfaceWindow. + * can be called from either MMA ES thread context or + * UI thread context. + * + * @since S60 v5.2 + */ + virtual void SetRWindowRect(const TRect& /*aRect*/, + MMMADisplay::TThreadType /*aThreadType*/) + { + // Empty + } +#endif + + /** + * + */ + virtual TDisplayWindowType GetDisplayWindowType() const + { + return EDisplayWindowTypeNotSet; + } + + /** + * Gets window visible or invisible. + * @retrun ETrue if visible else EFalse. Default implementation always returns ETrue + */ + virtual TBool IsVisible() const + { + return ETrue; + } + + /** + * Informs window that container which is window drawn on + * is set from now. Implementation is now able to invoke + * any UI callbacks + * + * @since S60 v5.0 + */ + virtual void ContainerSet() + { + // Empty + } + + /** + * Informs window that container which is window drawn on + * is going to be deleted. Implementation should abort any + * DirectScreenAccess and delete all the objects + * instantiated within UI thread. + * Called wihout mmapi event server directly from UI thread. + * By default it doesn't do anything. + * + * @since S60 v5.0 + */ + virtual void ContainerDestroyed() + { + // Empty + } + + /** + * Notifies window that any drawing + * via direct screen access must be aborted + */ + virtual void AbortDSA() + { + // default empty implementation + } + + /** + * Allows window to draw + * via direct screen access after MdcAbortDSA + */ + virtual void ResumeDSA() + { + // default empty implementation + } + + /** + * gets window resources from QT + */ + virtual void ProcureWindowResourcesFromQWidget(RWsSession * aWs, + CWsScreenDevice* aScreenDevice, + RWindowBase* aWindow) + { + // default empty implementation + } + + virtual void UICallback( TInt aCallbackId ) + { + } +}; + +#endif // MMMADISPLAYWINDOW_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmaeventposter.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmaeventposter.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This header is event poster +* +*/ + + +#ifndef MMMAEVENTPOSTER_H +#define MMMAEVENTPOSTER_H + +// INCLUDES +#include "cmmaevent.h" +#include + +NONSHARABLE_CLASS(MMMAEventPoster) +{ +public: + /** + * Posts event to the Java side. + * + * @param aEvent Event to be sent. + * @param aPriority Priority used to send the event. + */ + virtual void PostEvent(CMMAEvent* aEvent, + TInt aPriority = CMMAEvent::EEventPriority) = 0; + virtual JNIEnv* getValidJniEnv() = 0; +}; + + +#endif // MMMAEVENTPOSTER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmaguiplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmaguiplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface for players which shows picture. +* +*/ + + +#ifndef MMMAGUIPLAYER_H +#define MMMAGUIPLAYER_H + +#include "cmmaplayerevent.h" + +// FORWARD DECLARATIONS +class MMMADisplay; +class CFbsBitmap; +class MMMASnapshot; +class MMAFunctionServer; +class CMIDToolkit; + +// CLASS DEFINITION +/** + Interface for players which shows picture. Player will be notified + throw this interface when display state is changed. +*/ +NONSHARABLE_CLASS(MMMAGuiPlayer) +{ +protected: // Constructors and destructors + /** + * Do not allow delete through this interface + */ + virtual ~MMMAGuiPlayer() {}; + +public: // Abstract methods + /** + * Sets display to the player. Player must likely will create window + * for the display. Called when display is available for the player. + * + * @param aDisplay Display which can be used. + */ + virtual void SetDisplayL(MMMADisplay* aDisplay) = 0; + + /** + * Returns size of the content. Content size may not available + * before player is initialized. + * + * @return Size of the source content. + */ + virtual TSize SourceSize() = 0; + + /** + * Returns inferface that is used for taking snapshots from the player. + * Method can leave if player creates a snapshoter object when this + * method is called. + * + * @return Interface for taking snaphots. + */ + virtual MMMASnapshot* SnapshoterL() = 0; + + /** + * Method sends event to the Java. This can be used to notify errors + * to the Java side. + * + * @param aEventType Type of the event. + * @param aStringEventData Data of the event. + */ + virtual void NotifyWithStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) = 0; + + // No data in MClass!! + +}; + +#endif // MMMAGUIPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmamuteobserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmamuteobserver.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface for mute observers +* +*/ + +#ifndef MMMAMUTEOBSERVER_H +#define MMMAMUTEOBSERVER_H + +// CLASS DECLARATION +/** +* Interface for receiving mute notification from CMMAMuteNotifier. +* +* +*/ + +class MMMAMuteObserver +{ +public: + + /** + * Handles mute notification according to received parameter. + * @param aMuted true if mute should be on, false if not + */ + virtual void HandleMuteNotification(TBool aMuted) = 0; + +}; + +#endif // MMMAMUTEOBSERVER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmaplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmaplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface for all player factories. +* +*/ + + +#ifndef MMMAPLAYERFACTORY_H +#define MMMAPLAYERFACTORY_H + +// INCLUDES +#include // CDesC16Array + +// CONSTANTS +_LIT(KMMAHttpProtocol, "http"); +_LIT(KMMAHttpsProtocol, "https"); +_LIT(KMMAFileProtocol, "file"); +_LIT(KMMACaptureProtocol, "capture"); +_LIT(KMMADeviceProtocol, "device"); + +// CLASS DEFINITION +class CMMAPlayer; + +/* +----------------------------------------------------------------------------- + + DESCRIPTION + Interface for all player factories. + +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(MMMAPlayerFactory) +{ +public: + + /** + * Allow delete through this interface. + */ + virtual ~MMMAPlayerFactory() {}; + + /** + * Creates new player according to a content type. + * + * @param aContentType Player's content type. + * @return New instance of CMMAPlayer or null if factory cannot + * create it + */ + virtual CMMAPlayer* CreatePlayerL(const TDesC& aContentType) = 0; + + /** + * Creates new player according to a locator + * + * @param aProtocol protocol part from the locator. + * @param aMiddlePart middle part from the locator. + * @param aParameters parameters part from the locator. + * @return New instance of CMMAPlayer or null if factory cannot + * create it + */ + virtual CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) = 0; + + /** + * Creates new player according to a header data + * + * @param aHeaderData Header data from the content + * @return New instance of CMMAPlayer or null if factory cannot + * create it + */ + virtual CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData) = 0; + + /** + * Gets player's supported content types. + * + * @param aProtocol The input protocol for the supported content types. + * @param aMimeTypeArray Will contain supported mime types for protocol. + */ + virtual void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) = 0; + + /** + * Gets player's supported protocols for the content type. + * + * @param aContentType The content type for the supported protocols. + * @param aProtocolArray Will contain supported protocols for content type. + */ + virtual void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray) = 0; +}; + +#endif // MMMAPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmaplayerinstanceobserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmaplayerinstanceobserver.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +#ifndef MMMAPLAYERINSTANCEOBSERVER_H +#define MMMAPLAYERINSTANCEOBSERVER_H + +// FORWARD DECLARATIONS +class CMMAPlayer; + + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + + Interface used to inform external components about player instances. +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(MMMAPlayerInstanceObserver) +{ +public: + /** + * Adds new player to observer. + * + * @param aPlayer Player instance to add. + */ + virtual void AddPlayerNotifyL(CMMAPlayer* aPlayer) = 0; + + /** + * Removes player from observer. + * + * @param aPlayer Player instance to remove. + */ + virtual void RemovePlayerNotify(CMMAPlayer* aPlayer) = 0; + +protected: + /** + * Deletion through this interface is not allowed. + */ + virtual ~MMMAPlayerInstanceObserver() {}; +}; + +#endif // MMMAPLAYERINSTANCEOBSERVER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmaplayerstatelistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmaplayerstatelistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This interface is used for informing player state changes +* +*/ + + +#ifndef MMMAPLAYERSTATELISTENER_H +#define MMMAPLAYERSTATELISTENER_H + +#include + +// CLASS DEFINITION +/** + + This interface is used for informing player state changes + +*/ +NONSHARABLE_CLASS(MMMAPlayerStateListener) +{ +public: + /** + * Called when player state is changed. Used states are defined in + * the player header file. Enumeration is not used to provide + * expandability. + * + * @param aState New state of the player. + */ + virtual void StateChanged(TInt aState) = 0; + +protected: // Constructors and destructors + /** + * May not delete through this interface, + * because destructor is protected. + */ + virtual ~MMMAPlayerStateListener() + { + }; +}; + + +#endif // MMMAPLAYERSTATELISTENER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmasnapshot.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmasnapshot.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,79 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This header is for shapshots. +* +*/ + + +#ifndef MMMASNAPSHOT_H +#define MMMASNAPSHOT_H + +// FORWARD DECLARATIONS +class CFbsBitmap; +class CMMAImageSettings; + +// CLASS DEFINITION +/** + +*/ + +NONSHARABLE_CLASS(MMMASnapshot) +{ +public: // Type definitions + enum TEncoding + { + EBitmap = 0, // Raw image format + EEncoded // Encoded image format + }; + +protected: // Constructors and destructors + virtual ~MMMASnapshot() {}; // Do not allow delete through this interface + +public: // Abstract methods + /** + * Takes snapshot. + * + * @param aStatus Status will be informed when + * bitmap is ready or error occures. + * @param aSize Snapshot size. If size is not specified (width=-1 or + * height=-1) default size is used. + * @return Returns snapshot image's encoding type based on the requested MIME-type and + * snapshot size. Returned encoding type may differ from the requested as + * raw bitmap type is used if possibly requested encoding type is not found. + */ + virtual TEncoding TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings) = 0; + + /** + * Returns snapshot image. + * + * @returns Snapshot bitmap or NULL if TakeSnapshotL is not called or it failed. + * Caller takes ownership of the bitmap. + */ + virtual CFbsBitmap* SnapshotBitmap() = 0; + + /** + * Returns encoded snapshot image + * + * @return Encoded snapshot image or NULL if TakeSnapshotL is not called or if it failed + * Caller takes ownership of the pointer. + */ + virtual HBufC8* SnapshotEncoded() = 0; + + // No data in MClass!! + +}; + +#endif // MMMASNAPSHOT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmasnapshotreadycallback.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmasnapshotreadycallback.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This header is snapshot callback +* +*/ + + +#ifndef MMMASNAPSHOTREADYCALLBACK_H +#define MMMASNAPSHOTREADYCALLBACK_H + +NONSHARABLE_CLASS(MMMASnapshotReadyCallback) +{ +public: + /** + * Called when snapshot is ready. Error situations + * must be checked separately. + */ + virtual void SnapshotReady() = 0; + +protected: + virtual ~MMMASnapshotReadyCallback() + { + }; +}; + +#endif // MMMASNAPSHOTREADYCALLBACK_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/mmmasourcestreamlistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/mmmasourcestreamlistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This interface is used for informing player that +* CMMASourceStream is ready +* +*/ + + +#ifndef MMMASOURCESTREAMLISTENER_H +#define MMMASOURCESTREAMLISTENER_H + +// CLASS DEFINITION +/** + + This interface is used for informing player that CMMASourceStream is ready + +*/ +NONSHARABLE_CLASS(MMMASourceStreamListener) // usually not derived +{ +public: // New methods + /** + * This method will be called when source stream read operation + * is ready or error occures. + * + * @param aStatus Status of the reading operation or one of the system + * error codes. + * @param aData Reference to read data. If an error occured reference + * to zero length descriptor. + */ + virtual void ReadCompletedL(TInt aStatus, const TDesC8& aData) = 0; + +protected: // Destructor + /** + * Do not allow delete trough this interface. + */ + virtual ~MMMASourceStreamListener() + { + }; +}; + +#endif // MMMASOURCESTREAMLISTENER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/rmmatempfile.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/rmmatempfile.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +#ifndef RMMATEMPFILE_H +#define RMMATEMPFILE_H + +// INCLUDES +#include +#include + +// CLASS DECLARATION +/** +* This is used to create and delete temporary files. +*/ +NONSHARABLE_CLASS(RMMATempFile): public RSessionBase +{ +public: + /** + * Default constructor. + */ + RMMATempFile(); + + /** + * Connects to systemams server. This method must be called before + * other methods may be used. + */ + void ConnectL(); + + /** + * Creates temp file to server. After this call reference to file can + * be obtained with File() method. + */ + void CreateL(); + + /** + * Return reference to created file. + * @return Reference to created file object. + */ + RFile& File(); + + /** + * Sets midlet suite. Used to create temp file folder in systemams + * server. + * @param aMIDletSuiteID midlet suite id + */ + void SetMIDletSuiteID(TInt aMIDletSuiteID); + + /** + * Closes server session and deletes temp file. + */ + void Close(); + +private: + // temp file's path + TFileName iFileName; + + // file created in CreateL method. + RFile iFile; + + // Handle to file. + TInt iFileHandle; + + // midlet suite id + TInt iMidletSuiteID; +}; + +#endif // RMMATEMPFILE_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/inc/tmmaparametervalidator.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/inc/tmmaparametervalidator.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,130 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for parsing and validating properties +* +*/ + + +#ifndef TMMAPARAMETERVALIDATOR_H +#define TMMAPARAMETERVALIDATOR_H + +// INCLUDES +#include +#include +#include +// STRUCTS + +/** + * These structs are used for storing settings + */ + +// Default values for recorder +const TInt KDefaultBits = -1; +const TInt KDefaultRate = -1; +const TInt KDefaultChannels = -1; + + +NONSHARABLE_STRUCT(CMMAAudioSettings): public CBase +{ + + ~CMMAAudioSettings(); + + TUid iController; + TUid iEncoding; + TFourCC iDataType; + TInt iRate; + TInt iChannels; + TBool iStreamableFormat; + HBufC *iContentType; +}; + +NONSHARABLE_STRUCT(TMMAVideoSettings) +{ + TPtrC iEncoding; + TReal32 iFps; + TInt iWidth; + TInt iHeight; + inline void operator=(const TMMAVideoSettings& aSettings) + { + iEncoding.Set(aSettings.iEncoding); + iFps = aSettings.iFps; + iHeight = aSettings.iHeight; + iWidth = aSettings.iWidth; + } +}; +/** + * Container for image settings + */ + +NONSHARABLE_CLASS(CMMAImageSettings): public CBase +{ +public: // destructor + ~CMMAImageSettings(); + // this is basicly struct owning some data + // so there is no point to make getters/setters +public: + HBufC8* iMimeType; //owned + HBufC8* iType; // owned + TInt iWidth; + TInt iHeight; + CFrameImageData* iImageData; //owned +}; + +// CLASS DECLARATION +/** +* This class is used for parsing and validating properties +* The property string is in format "name=value&name=value&..." +* +*/ + +NONSHARABLE_CLASS(TMMAParameterValidator) +{ +public:// New methods + /** + * Validates audio properties. Accepted keys are: + * "encoding", "rate", "bits", "channels", "endian", "signed" + * Properties string must start with "encoding" parameter + * Leaves with KErrArgument if parameters are not valid. + */ + static CMMAAudioSettings *ValidateAudioPropertiesL(const TDesC& aProperties); + + /** + * Validates video properties. Accepted keys are: + * "encoding", "fps", "width", "height" + * Properties string must start with "encoding" parameter + * Leaves with KErrArgument if parameters are not valid. + */ + static TMMAVideoSettings ValidateVideoPropertiesL(const TDesC& aProperties); + + /** + * Validates image properties. Accepted keys are: + * "encoding", "width", "height", "quality", "progressive", "interlaced", "type", "colors" + * Properties string must start with "encoding" parameter + * Leaves with KErrArgument if parameters are not valid. + */ + static CMMAImageSettings* ValidateImagePropertiesL(const TDesC& aProperties); + +private: // New methods + /** + * Every properties must start with "encoding=" + */ + static void CheckEncodingL(const TDesC& aProperties); + + /** + * Creates new HBufC8 and copies data to it from aDes. + */ + static HBufC8* CreateHBufC8FromUnicodeL(const TDesC& aDes); +}; + +#endif // TMMAPARAMETERVALIDATOR_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/BufferDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/BufferDataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,167 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Buffered DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.Control; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.protocol.SourceStream; +import java.io.IOException; + +/** + * BufferDataSource is used to read header from DataSource's SourceStream. + * This class delegates all method calls to DataSource given in constructor + * except getStream method which returns buffered SourceStream. + */ +public class BufferDataSource extends DataSource +{ + // delegated source + protected DataSource iDataSource; + + // buffers DataSource's first stream. + protected BufferSourceStream iSourceStream; + + /** + * Constructor. + * @param aDataSource delegated DataSource + */ + public BufferDataSource(DataSource aDataSource) throws IOException + { + super(aDataSource.getLocator()); + iDataSource = aDataSource; + SourceStream ss = aDataSource.getStreams()[ 0 ]; + iSourceStream = new BufferSourceStream(ss); + } + + /** + * Return header data. + * @return header data + */ + public byte[] getHeader() throws IOException + { + return iSourceStream.getHeader(); + } + + public int readAndBuffer(byte[] aBuffer, int aOffset, int aLength) throws IOException + { + return iSourceStream.readAndBuffer(aBuffer, aOffset, aLength); + } + + /** + * from DataSource + * @return Content Type + * @see DataSource + */ + public String getContentType() + { + return iDataSource.getContentType(); + } + + /** + * from DataSource + * Connect to the stream + * @throws IOException + * @see DataSource + */ + public void connect() throws IOException + { + iDataSource.connect(); + } + + /** + * from DataSource + * Disconnect from the stream + */ + public void disconnect() + { + iDataSource.disconnect(); + } + + /** + * from DataSource + * Put DataSource to STARTED state + * @throws IOException Throw if DataSource is in wrong state + * @see DataSource + */ + public void start() throws IOException + { + iDataSource.start(); + } + + /** + * from DataSource + * Stops DataSource + * @see DataSource + */ + public void stop() throws IOException + { + iDataSource.stop(); + } + + /** + * from DataSource + * return sourceStreams of the DataSource + * + * @return set of source streams + * @see DataSource + */ + public SourceStream[] getStreams() + { + // return all streams from delegated DataSource except first + // buffered stream. + SourceStream[] originalStreams = iDataSource.getStreams(); + SourceStream[] streams = new SourceStream[ originalStreams.length ]; + System.arraycopy(originalStreams, 0, + streams, 0, originalStreams.length); + streams[ 0 ] = iSourceStream; + return streams; + } + + /** + * from interface Controllable + * Method return controls of the DataSource + * @return Control + * @see Controllable + * @see DataSource + */ + public Control[] getControls() + { + return iDataSource.getControls(); + } + + /** + * from interface Controllable + * Return a control by the Control Type, not supported + * @param controlType type of the control + * @return Control + */ + public Control getControl(String aControlType) + { + return iDataSource.getControl(aControlType); + } + /** + * @author d35kumar + * @return + */ + public DataSource getDataSource(){ + return iDataSource; + } + +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/BufferSourceStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/BufferSourceStream.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,171 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: SourceStream that buffers data from another SourceStream. +* +*/ + + +package com.nokia.microedition.media; + +import java.io.IOException; +import javax.microedition.media.protocol.SourceStream; + +/** + * SourceStream that buffers data from another SourceStream. + * + */ +public class BufferSourceStream extends InputStreamSourceStream +{ + // Deferred buffer size + private static final int BUFFER_SIZE = 5120; + + // Stream to buffer + SourceStream iSourceStream; + + byte[] iBuffer; + + // stream read position + int iPos; + + /** + * Constructor. + * @param aInputStream An InputStream + */ + public BufferSourceStream(SourceStream aSourceStream) + { + iSourceStream = aSourceStream; + } + + /** + * Return header data. + * @return header data + */ + public byte[] getHeader() throws IOException + { + byte[] tmpBuffer = new byte[ BUFFER_SIZE ]; + int bytesInBuffer = BUFFER_SIZE; + + // Read into iBuffer first if iBuffer doesn't already contain + // first 256 bytes + if (iBuffer == null) + { + bytesInBuffer = readAndBuffer(tmpBuffer, 0, 256); + + if (bytesInBuffer < 0) + { + throw new IOException(); + } + } + else if (iBuffer.length < 256) + { + bytesInBuffer = readAndBuffer(tmpBuffer, iBuffer.length, (256 - iBuffer.length)); + + if (bytesInBuffer == -1) + { + bytesInBuffer = iBuffer.length; + } + } + + // tmpBuffer will be overwritten here + System.arraycopy(iBuffer, 0, + tmpBuffer, 0, bytesInBuffer); + + return tmpBuffer; + } + + + public int readAndBuffer(byte[] aBuffer, int aOffset, int aLength) throws IOException + { + int bytesInBuffer = iSourceStream.read(aBuffer, aOffset, aLength); + + if (iBuffer == null) + { + iBuffer = new byte[bytesInBuffer]; + + System.arraycopy(aBuffer, aOffset, + iBuffer, 0, bytesInBuffer); + } + else if (bytesInBuffer >= 0) + { + byte[] tempBuffer = iBuffer; + iBuffer = new byte[iBuffer.length + bytesInBuffer]; + + System.arraycopy(tempBuffer, 0, + iBuffer, 0, tempBuffer.length); + System.arraycopy(aBuffer, aOffset, + iBuffer, tempBuffer.length, bytesInBuffer); + tempBuffer = null; // relese tempBuffer + } + + return bytesInBuffer; + } + + /** + * Read from Input Stream + * @param buffer Input Stream + * @param offset where reading starts + * @param length length of read data + * @return bytes read + * @throws IOException + */ + public int read(byte[] aBuffer, int aOffset, int aLength) throws IOException + { + // bytes read from internal buffer + int bytesFromBuffer = 0; + + + if ((iBuffer != null) && // read from iBuffer if getHeader is called + (iPos < iBuffer.length)) + { + // Need to read from buffer + if (aLength < iBuffer.length - iPos) + { + // aLength bytes can be read from buffer + bytesFromBuffer = aLength; + } + else + { + // aLength cannot be read from buffer + // read all there is available + bytesFromBuffer = iBuffer.length - iPos; + } + + System.arraycopy(iBuffer, iPos, + aBuffer, aOffset, bytesFromBuffer); + + // move stream position + iPos += bytesFromBuffer; + return bytesFromBuffer; + } + + // bytes read from iSourceStream + int bytesFromStream = 0; + // Check if bytes are needed from SourceStream + if (bytesFromBuffer < aLength) + { + bytesFromStream = iSourceStream.read(aBuffer, + bytesFromBuffer, + aLength - bytesFromBuffer); + if (bytesFromStream != -1) + { + // move stream position, if not end of stream + iPos += bytesFromStream; + } + } + + return bytesFromStream; + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/ManagerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/ManagerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,668 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.microedition.media; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Vector; +import java.util.Enumeration; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.TimeBase; +import javax.microedition.media.Player; +import javax.microedition.media.MediaException; +//import com.symbian.lcdjava.lang.ObjectExtensions; +//import com.symbian.epoc.events.MIDEventServer; +//import com.symbian.midp.runtime.ToolkitInvoker; +//import com.symbian.midp.runtime.ToolkitObserver; + +import com.nokia.microedition.media.animation.AnimationPlayerFactory; +import com.nokia.microedition.media.protocol.ProtocolFactory; +import com.nokia.microedition.media.tone.PlayToneImpl; + +import com.nokia.microedition.volumekeys.ForegroundListener; +import com.nokia.mj.impl.rt.support.Finalizer; + +//To get the shutdown event from the midlet +import com.nokia.mj.impl.rt.support.ApplicationUtils; +import com.nokia.mj.impl.rt.support.ApplicationInfo; +import com.nokia.mj.impl.rt.support.ShutdownListener; +import com.nokia.mj.impl.utils.Logger; + +/** + * ManagerImpl implements the functionality specified in + * javax.microedition.media.Manager class. + * This class is a singleton and instance can be got with getInstance method. + */ +public class ManagerImpl implements PlugIn +{ + // ManagerImpl native instance + private static int sManagerHandle; + + // CMMAEventSource + private static int iFunctionSourceHandle; + + // Static instance, can be got with getInstace method + private static ManagerImpl sManager; + + private final TimeBase iSystemTimeBase = new SystemTimeBase(); + + private final Vector iPlugIns = new Vector(); + private final ProtocolFactory iProtocolFactory = new ProtocolFactory(); + private final ForegroundListener iForegroundListener; + private Finalizer iFinalizer; + + Finalizer registerForFinalization() + { + return new Finalizer() + { + public void finalizeImpl() + { + doFinalize(); + } + }; + } + + // Play tone implementation + private PlayToneImpl iPlayToneImpl = new PlayToneImpl(); + + static + { + // This is called when class is loaded for the first time + sManager = new ManagerImpl(); + + try + { + // Invoke external components + Setup.setup(iFunctionSourceHandle); + } + catch (OutOfMemoryError oome) + { + // External setup failed clean MMA native resources and throw oome + sManager.doFinalize(); + throw oome; + } + } + + /** + * This private constructor can be called only from staic block. + */ + private ManagerImpl() + { + // Will cause registeredFinalize() to be called when ObjectExtensions + // is finalized. + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"ManagerImpl constructor before loading library"); + com.nokia.mj.impl.rt.support.Jvm.loadSystemLibrary("javamobilemedia"); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"ManagerImpl constructor library loaded.. going to register for finalizer"); + //ObjectExtensions.registerForFinalization(this); + iFinalizer = registerForFinalization(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"ManagerImpl constructor ... after registering for finalizer"); + + // Event server contructor needs new String object, + // otherwise it don't work.. + + iFunctionSourceHandle = _createEventSource(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"ManagerImpl.java : iFunctionSourceHandle is " + iFunctionSourceHandle); + if (iFunctionSourceHandle < NativeError.KErrNone) + { + throw new OutOfMemoryError("SymbianOS error: " + iFunctionSourceHandle); + } + + sManagerHandle = _createManager(iFunctionSourceHandle, + ApplicationInfo.getInstance().getSuiteUid().hashCode()); + if (sManagerHandle < NativeError.KErrNone) + { + throw new OutOfMemoryError(); + } + //Use ShutdownListener to get notification of exit and release the resource + //MMAPI UI 3.x work + + setShutdownListener(); + // support for gif animation player + iPlugIns + .addElement(new com.nokia.microedition.media.animation.AnimationPlayerFactory()); + + // ManagerImpl is also a PlugIn that getAllSupportedContentTypes, + // getAllSupportedProtocols and createPlayer methods can be used + // through PlugIn interface. + iPlugIns.addElement(this); + + // support for device://tone and jts + iPlugIns.addElement( + new com.nokia.microedition.media.protocol.device.tone.Protocol()); + + // Create foreground listener which listens the state of the midlet + // This feature is a part of the media keys feature so it is flagged + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"before constructing ForegroundListener...."); + iForegroundListener = new ForegroundListener(iFunctionSourceHandle); + iForegroundListener.init(); + } + + + private void setShutdownListener() + { + // Get the insatnce of ApplicationUtils. + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + + // Get the name of the application. + appUtils.addShutdownListener(new ShutdownListener() + { + //The method that gets called when Application is shutting down + public void shuttingDown() + { + + doFinalize(); + + + } + }); + + } + + /** + * Returns MMA event source handle + */ + public static int getEventSource() + { + return iFunctionSourceHandle; + } + /** + * Returns native handle to Manager + */ + public static int getHandle() + { + return sManagerHandle; + } + + /** + * Return ManagerImpl instance + */ + public static ManagerImpl getInstance() + { + return sManager; + } + + /** + * Adds new PlugIn to PlugIns array. + * @param aPlugIn New PlugIn. + */ + public void addPlugIn(PlugIn aPlugIn) + { + iPlugIns.addElement(aPlugIn); + } + + + + + /** + * This will be called when ObjectExtensions is finalized. + */ + synchronized final void doFinalize() + { + _dispose(iFunctionSourceHandle); + iFunctionSourceHandle = 0; + } + + /** + * This method is called in Toolkit's destroyNotify call. + * This will release convenient native resources. All native resource + * will be deleted in registeredFinalize() method. + */ + synchronized final void release() + { + // _release(iFunctionSourceHandle); + } + + /** + * Create String array from Vector and remove String duplicates. + * @param aVector Vector containing String objects. + */ + private String[] createStringArray(Vector aVector) + { + // remove all duplicates from the vector + for (int i = 0; i < aVector.size(); i++) + { + String element = (String)aVector.elementAt(i); + for (int j = i + 1; j < aVector.size();) + { + if (element.equals((String)aVector.elementAt(j))) + { + aVector.removeElementAt(j); + } + else + { + j++; + } + } + } + + // Create new array for vector elements and copy elements + String[] s = new String[ aVector.size()]; + aVector.copyInto(s); + return s; + } + + /** + * Return the list of supported content types for the given protocol. + *

            + * See content types for the syntax + * of the content types returned. + * See protocol name for the syntax + * of the protocol used. + *

            + * For example, if the given protocol + * is "http", + * then the supported content types that can be played back + * with the http protocol will be returned. + *

            + * If null is passed in as the protocol, + * all the supported content types for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given protocol is an invalid or + * unsupported protocol, then an empty array will be returned. + * + * @param aProtocol The input protocol for the supported content types. + * @return The list of supported content types for the given protocol. + */ + public String[] getAllSupportedContentTypes(String aProtocol) + { + if ((aProtocol != null) && (aProtocol.length() == 0)) + { + // No supported types for 0 length string. + return new String[ 0 ]; + } + Vector contentTypes = new Vector(); + + Enumeration plugIns = iPlugIns.elements(); + + // go through all plugins and get content types + while (plugIns.hasMoreElements()) + { + PlugIn plugIn = (PlugIn)plugIns.nextElement(); + String[] types = plugIn.getSupportedContentTypes(aProtocol); + + // Add all types to vector + for (int i = 0; i < types.length; i++) + { + contentTypes.addElement(types[ i ]); + } + } + return createStringArray(contentTypes); + } + + /** + * Return the list of supported protocols given the content + * type. The protocols are returned + * as strings which identify what locators can be used for creating + * Player's. + *

            + * See protocol name for the syntax + * of the protocols returned. + * See content types for the syntax + * of the content type used. + *

            + * For example, if the given content_type + * is "audio/x-wav", then the supported protocols + * that can be used to play back audio/x-wav + * will be returned. + *

            + * If null is passed in as the + * content_type, + * all the supported protocols for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given content_type is an invalid or + * unsupported content type, then an empty array will be returned. + * + * @param aContentType The content type for the supported protocols. + * @return The list of supported protocols for the given content type. + */ + public String[] getAllSupportedProtocols(String aContentType) + { + String contentType = aContentType; + if ((contentType != null) && contentType.equals("")) + { + return new String[ 0 ]; + } + + Vector protocols = new Vector(); + Enumeration plugIns = iPlugIns.elements(); + while (plugIns.hasMoreElements()) + { + PlugIn plugIn = (PlugIn)plugIns.nextElement(); + String[] types = plugIn.getSupportedProtocols(aContentType); + for (int i = 0; i < types.length; i++) + { + protocols.addElement(types[ i ]); + } + } + return createStringArray(protocols); + } + + /** + * From PlugIn. Get MMA supported protocols. + */ + public String[] getSupportedProtocols(String aContentType) + { + String[] protocols = _getSupportedProtocols(iFunctionSourceHandle, + sManagerHandle, + aContentType); + NativeError.checkOOM(protocols); + return protocols; + } + + /** + * From PlugIn. Get MMA supported types. + */ + public String[] getSupportedContentTypes(String aProtocol) + { + String[] types = _getSupportedContentTypes(iFunctionSourceHandle, + sManagerHandle, + aProtocol); + NativeError.checkOOM(types); + return types; + } + + /** + * From PlugIn. + */ + public InternalPlayer createPlayer(DataSource aSource) + throws MediaException, IOException + { + InternalPlayer player = null; + if (aSource.getContentType() != null) + { + // Create player from content type + if (isValidContentType(aSource.getContentType())) + { + player = NativePlayerFactory.createPlayer(aSource.getContentType(), + aSource); + } + else + { + throw new MediaException( + "Content type not supported: " + aSource.getContentType()); + } + } + + if ((player == null) && + (aSource.getLocator() != null)) + { + // Create player from locator + player = NativePlayerFactory.createPlayer( + new Locator(aSource.getLocator()), + aSource); + } + + if (player == null) + { + // Could not create player from content-type or locator, + // try to create player from header data + player = NativePlayerFactory.createPlayer( + ((BufferDataSource)aSource).getHeader(), + aSource); + } + + return player; + } + + /** + * From PlugIn. Empty implemation. + */ + public void preparePlayer(InternalPlayer aPlayer) throws MediaException + { + } + + /** + * This method calls preparePlayer to all PlugIns. + */ + private void pluginsPreparePlayer(InternalPlayer aPlayer) + throws MediaException + { + + + // Call preparePlayer to all plugins + Enumeration plugins = iPlugIns.elements(); + while (plugins.hasMoreElements()) + { + ((PlugIn)plugins.nextElement()).preparePlayer(aPlayer); + } + } + + /** + * Create a Player from an input locator. + * + * @param aLocator A locator string in URI syntax that describes + * the media content. + * @return A new Player. + * @exception IllegalArgumentException Thrown if locator + * is null. + * @exception MediaException Thrown if a Player cannot + * be created for the given locator. + * @exception IOException Thrown if there was a problem connecting + * with the source pointed to by the locator. + * @exception SecurityException Thrown if the caller does not + * have security permission to create the Player. + */ + public Player createPlayer(String aLocator) + throws IOException, MediaException + { + if (aLocator == null) + { + throw new IllegalArgumentException("Locator is null."); + } + InternalPlayer player = iProtocolFactory.createPlayer( + new Locator(aLocator)); + if (player == null) + { + throw new MediaException("Locator not supported: " + + aLocator); + } + pluginsPreparePlayer(player); + return player; + } + + /** + * Create a InternalPlayer for a DataSource. + */ + public InternalPlayer createInternalPlayer(DataSource aSource) + throws IOException, MediaException + { + // Throw IllegalArgumentException if source is null. + if (aSource == null) + { + throw new IllegalArgumentException("DataSource is null."); + } + aSource.connect(); // Ensure that external source is connected. + if (aSource.getStreams() == null || + aSource.getStreams().length == 0) + { + // There must be atleast one stream in the DataSource + throw new MediaException( + "There must be at least one stream in datasource"); + } + + BufferDataSource bdc = null; + if (aSource instanceof BufferDataSource) + { + bdc = (BufferDataSource)aSource; + } + else + { + bdc = new BufferDataSource(aSource); + } + + InternalPlayer player = null; + Enumeration plugins = iPlugIns.elements(); + // Loop through all plugins, stop if player was created + while (plugins.hasMoreElements() && + (player == null)) + { + PlugIn tmp = (PlugIn)plugins.nextElement(); + player = tmp.createPlayer(bdc); + } + + if (player == null) + { + // MMA or plugins could not create player + bdc.disconnect(); + + throw new MediaException("Could not create player."); + } + + return player; + } + + /** + * Create a Player to play back media from an + * InputStream. + *

            + * The type argument + * specifies the content-type of the input media. If + * null is given, Manager will + * attempt to determine the type. However, since determining + * the media type is non-trivial for some media types, it + * may not be feasible in some cases. The + * Manager may throw a MediaException + * to indicate that. + * + * @param aStream The InputStream that delivers the + * input media. + * @param aType The ContentType of the media. + * @return A new Player. + * @exception IllegalArgumentException Thrown if stream + * is null. + * @exception MediaException Thrown if a Player cannot + * be created for the given stream and type. + * @exception IOException Thrown if there was a problem reading data + * from the InputStream. + * @exception SecurityException Thrown if the caller does not + * have security permission to create the Player. + */ + public Player createPlayer(InputStream aStream, String aType) + throws IOException, MediaException + { + if (aStream == null) + { + throw new IllegalArgumentException("InputStream is null."); + } + + InputStreamSourceStream sourceStream = + new InputStreamSourceStream(aStream); + + // Create data source without locator. + DataSource dataSource = new InputStreamDataSource(sourceStream, + aType); + InternalPlayer player = createInternalPlayer(dataSource); + + if (player != null) + { + // Call preparePlayer to all plugins + pluginsPreparePlayer(player); + } + + return player; + } + + /** + * Play back a tone as specified by a note and its duration. + * A note is given in the range of 0 to 127 inclusive. The frequency + * of the note can be calculated from the following formula: + *

            +     *     SEMITONE_CONST = 17.31234049066755 = 1/(ln(2^(1/12)))
            +     *     note = ln(freq/8.176)*SEMITONE_CONST
            +     *     The musical note A = MIDI note 69 (0x45) = 440 Hz.
            +     * 
            + * This call is a non-blocking call. Notice that this method may + * utilize CPU resources significantly on devices that don't + * have hardware support for tone generation. + * + * @param aNote Defines the tone of the note as specified by the + * above formula. + * @param aDuration The duration of the tone in milli-seconds. + * Duration must be positive. + * @param aVolume Audio volume range from 0 to 100. 100 represents + * the maximum + * volume at the current hardware level. Setting the volume to a + * value less + * than 0 will set the volume to 0. Setting the volume to greater than + * 100 will set the volume to 100. + * + * @exception IllegalArgumentException Thrown if the given note or + * duration is out of range. + * @exception MediaException Thrown if the tone cannot be played + * due to a device-related problem. + */ + public void playTone(int aNote, int aDuration, int aVolume) + throws MediaException + { + iPlayToneImpl.playTone(aNote, aDuration, aVolume); + } + + /** + * Get the time-base object for the system. + * @return The system time base. + */ + public TimeBase getSystemTimeBase() + { + return iSystemTimeBase; + } + + public boolean isValidContentType(String contentType) + { + for (int i=0; i < contentType.length(); i++) + { + if ((contentType.charAt(i) >= 0 && contentType.charAt(i) <= 31) || contentType.charAt(i) == 127) + return false; + } + return true; + } + + + +// MMAPI UI 3.x req +/** + * get midlet state + */ + + public boolean isForground() + { + return iForegroundListener.isForeground(); + } + + private native int _createManager(int aEventSourceHandle, + int aMIDletSuiteID); + private native int _createEventSource(); + private native void _dispose(int aEventSourceHandle); + + /** + * Releases native resources. + * @param aEventSourceHandle Handle to native CMMAEventSource instance. + */ + private native void _release(int aFunctionSourceHandle); + + private static native String[] _getSupportedContentTypes(int aFunctionSourceHandle, + int aManagerHandle, + String aContentType); + + private static native String[] _getSupportedProtocols(int aFunctionSourceHandle, + int aManagerHandle, + String aProtocol); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/control/MetaDataControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/control/MetaDataControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,194 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements functionalities defined in the +* MetaDataControl interface (included in +* javax.microedition.media.control package). +* +*/ + + +package com.nokia.microedition.media.control; + +import java.util.Vector; +import java.util.Enumeration; + +// CLASS DEFINITION +/** + * The MetaDataControl class implements functionalities defined + * in the MetaDataControl interface (included in + * javax.microedition.media.control package). + */ + +public class MetaDataControl + extends ControlImpl + implements javax.microedition.media.control.MetaDataControl +{ + + /** + * The metadata keys received from the native side. It is assumed that + * the keys will not change during the lifetime of a media clip or + * stream. Key data is used so frequently that we want to buffer it + * here at Java side. + */ + private String[] iKeys = null; + private static final String[] DEFAULT_DATA = { MetaDataControl.AUTHOR_KEY, + MetaDataControl.COPYRIGHT_KEY, + MetaDataControl.DATE_KEY, + MetaDataControl.TITLE_KEY + }; + private static final String DEFAULT_DATA_VALUE = "unknown"; + + // Static initialization + + /** + * Creates an instance of MetaDataControl. + */ + public MetaDataControl() + { + } + + /** + * Returns acceptable metadata keys. + * + * The keys can be used for getting specific metadata value associated to each key. + * + * @See javax.microedition.media.control.MetaDataControl + * interface documentation for details. + * + * @return Acceptable key values. + * + */ + public String[] getKeys() + { + checkState(); + + int keyCount = _getKeysCount(iEventSource, iControlHandle); + + if (keyCount < 0) // can't read key count + { + iKeys = DEFAULT_DATA; + return iKeys; + } + + Vector keys = new Vector(keyCount + 1); + + for (int i = 0; i < keyCount; i++) + { + String currentKey = _getKey(iEventSource, iControlHandle, i); + if (currentKey == null) // can't read key value + { + iKeys = DEFAULT_DATA; + return iKeys; + } + keys.addElement(currentKey); + } + + // Check if the default keys are already in the key vector + // and if not, then add them + + for (int i = 0; i < DEFAULT_DATA.length; i++) + { + checkAddKey(keys, DEFAULT_DATA[ i ]); + } + + iKeys = new String[ keys.size()]; + keys.copyInto(iKeys); + + return iKeys; + } + + /** + * Check if there is already a key in vector and if not, then + * add one. + * @param aKeys vector containing keys to be checked and which to add + * new key + * @param aKey key string to be added if not already present in aKeys + */ + private void checkAddKey(Vector aKeys, String aKey) + { + for (Enumeration e = aKeys.elements(); e.hasMoreElements();) + { + String currentElement = (String)e.nextElement(); + if (currentElement.equals(aKey)) + { + return; + } + } + // Otherwise add the key + aKeys.addElement(new String(aKey)); + } + + /** + * Fetches a value of the given metadata key. + * + * See javax.microedition.media.control.MetaDataControl + * interface documentation for details. + * + * @param aKey Key of the metadata value to be returned. + * + * @return Value of the metadata. + * + * @exception IllegalArgumentException Thrown if the given key is + * null or invalid. + */ + public String getKeyValue(String aKey) + { + checkState(); + if (null == aKey) + { + throw new IllegalArgumentException("Key cannot be null"); + } + + getKeys(); // Buffer the keys if not present + + int arrLen = iKeys.length; + int i = 0; + + // Check if the given key is valid and return the value. + while (i < arrLen) + { + if (iKeys[ i ].equals(aKey)) + { + String value = _getKeyValue(iEventSource, iControlHandle, aKey); + + // if key is ok but value is null then this key does not really + // exist and it must be checked whether it is one from DEFAULT_DATA + if (value == null) + { + for (int j = 0; j < DEFAULT_DATA.length; j++) + { + if (aKey.equals(DEFAULT_DATA[ j ])) + { + return(DEFAULT_DATA_VALUE); + } + } + } + return value; + } + ++i; + } + + // No match - invalid key. + throw new IllegalArgumentException("Invalid non-null key"); + } + + private native int _getKeysCount(int aEventSource, + int aControlHandle); + private native String _getKey(int aEventSource, + int aControlHandle, + int aIndex); + private native String _getKeyValue(int aEventSource, + int aControlHandle, + String aKey); +} //end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/EMCSourceInfo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/EMCSourceInfo.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,178 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.microedition.media.protocol; + +import javax.microedition.media.protocol.SourceStream; +import com.nokia.microedition.media.HttpDataSource; +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.BufferDataSource; +import java.io.IOException; + +public class EMCSourceInfo +{ + + // media file header + byte[] header; + + public EMCSourceInfo(BufferDataSource datasource) throws IOException, MediaException + { + // datasource.getLocator().getMiddlePart() check if it is 3gp/mp4/rm + Locator locator = new Locator(datasource.getLocator()); + String extension = getExtension(locator.getMiddlePart()); + + + if (extension.equals("rm")) + { + + // read first 5120 bytes of data and pass to native side*/ + header = new byte[ 5120 ]; + int bytesRead = datasource.readAndBuffer(header, 0, 5120); + if (bytesRead != 5120) + { + throw new IOException("Reading from HTTP server failed"); + } + + } + else if (extension.equals("3gp") || extension.equals("mp4")) // 3gp/mp4 + { + + byte[] moovbox = new byte[ 512 ]; + int bytesRead = datasource.readAndBuffer(moovbox, 0, 512); + if (bytesRead != 512) + { + throw new IOException("Reading from HTTP server failed"); + } + String str = new String(moovbox); + int pos = str.indexOf("moov"); + + if (pos == -1) + { + + return; // moov box not in first 512 bytes, not a streaming profile + + } + else + { + + // ************** extract filetype length + int byte1 = moovbox[0]<0?(256 + moovbox[0]):moovbox[0]; + int byte2 = moovbox[1]<0?(256 + moovbox[1]):moovbox[1]; + int byte3 = moovbox[2]<0?(256 + moovbox[2]):moovbox[2]; + int byte4 = moovbox[3]<0?(256 + moovbox[3]):moovbox[3]; + + byte1 = byte1 * 16777216; + byte2 = byte2 * 65536; + byte3 = byte3 * 256; + byte4 = byte4 * 1; + + int filetype = byte1 + byte2 + byte3 + byte4; + if (filetype < 0) + { + + return; + } + + // ************** extract moovbox length + byte1 = moovbox[pos-4]<0?(256 + moovbox[pos-4]):moovbox[pos-4]; + byte2 = moovbox[pos-3]<0?(256 + moovbox[pos-3]):moovbox[pos-3]; + byte3 = moovbox[pos-2]<0?(256 + moovbox[pos-2]):moovbox[pos-2]; + byte4 = moovbox[pos-1]<0?(256 + moovbox[pos-1]):moovbox[pos-1]; + + byte1 = byte1 * 16777216; + byte2 = byte2 * 65536; + byte3 = byte3 * 256; + byte4 = byte4 * 1; + + int moovboxlen = byte1 + byte2 + byte3 + byte4; + if (moovboxlen < 0) + { + + return; + } + + // ************** + + // no. of bytes: total header length + int nob = filetype + moovboxlen; + if (nob < 0) + { + + return; + } + + header = new byte[nob]; + System.arraycopy(moovbox, 0, header, 0, 512); + moovbox = null; + bytesRead = datasource.readAndBuffer(header, 512, nob-512); + if (bytesRead != nob-512) + { + throw new IOException(); + } + } + } + else + { + + return; + } + } + + private String getExtension(String locator) + { + int index = locator.lastIndexOf('.'); + if (index == -1) return ""; + + try + { + + return locator.substring(index + 1); + + } + catch (IndexOutOfBoundsException ex) + { + //ignore + } + + return ""; + } + + public void writeInfo(int eventsourcehandle, int managerhandle) throws MediaException + { + int err = 0; + + if (header != null) + { + + err = _writeHeaderData(eventsourcehandle, managerhandle, header); + + } + + if (err != 0) + { + + throw new MediaException( + "Could not create player, Symbian OS error: " + err); + } + } + + private native int _writeHeaderData(int aEventsourcehandle, int aManagerHandle, byte[] header); + +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/http/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/http/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements TimeBase +* +*/ + + +package com.nokia.microedition.media.protocol.http; + + + + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.protocol.ConnectorProtocol; +import com.nokia.microedition.media.HttpDataSource; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.BufferDataSource; +import com.nokia.microedition.media.protocol.EMCSourceInfo; + +public class Protocol extends ConnectorProtocol +{ + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + HttpDataSource dataSource = new HttpDataSource(aLocator); + BufferDataSource bdc = new BufferDataSource(dataSource); + (new EMCSourceInfo(bdc)).writeInfo(ManagerImpl.getEventSource(), ManagerImpl.getHandle()); + return ManagerImpl.getInstance().createInternalPlayer(bdc); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/https/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.emc/com/nokia/microedition/media/protocol/https/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements TimeBase +* +*/ + + +package com.nokia.microedition.media.protocol.https; + + + + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.protocol.ConnectorProtocol; +import com.nokia.microedition.media.HttpDataSource; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.BufferDataSource; +import com.nokia.microedition.media.protocol.EMCSourceInfo; + +public class Protocol extends ConnectorProtocol +{ + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + HttpDataSource dataSource = new HttpDataSource(aLocator); + BufferDataSource bdc = new BufferDataSource(dataSource); + (new EMCSourceInfo(bdc)).writeInfo(ManagerImpl.getEventSource(), ManagerImpl.getHandle()); + return ManagerImpl.getInstance().createInternalPlayer(bdc); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/BufferDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/BufferDataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Buffered DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.Control; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.protocol.SourceStream; +import java.io.IOException; + +/** + * BufferDataSource is used to read header from DataSource's SourceStream. + * This class delegates all method calls to DataSource given in constructor + * except getStream method which returns buffered SourceStream. + */ +public class BufferDataSource extends DataSource +{ + // delegated source + protected DataSource iDataSource; + + // buffers DataSource's first stream. + protected BufferSourceStream iSourceStream; + + /** + * Constructor. + * @param aDataSource delegated DataSource + */ + public BufferDataSource(DataSource aDataSource) throws IOException + { + super(aDataSource.getLocator()); + iDataSource = aDataSource; + SourceStream ss = aDataSource.getStreams()[ 0 ]; + iSourceStream = new BufferSourceStream(ss); + } + + /** + * Return header data. + * @return header data + */ + public byte[] getHeader() throws IOException + { + return iSourceStream.getHeader(); + } + + /** + * from DataSource + * @return Content Type + * @see DataSource + */ + public String getContentType() + { + return iDataSource.getContentType(); + } + + /** + * from DataSource + * Connect to the stream + * @throws IOException + * @see DataSource + */ + public void connect() throws IOException + { + iDataSource.connect(); + } + + /** + * from DataSource + * Disconnect from the stream + */ + public void disconnect() + { + iDataSource.disconnect(); + } + + /** + * from DataSource + * Put DataSource to STARTED state + * @throws IOException Throw if DataSource is in wrong state + * @see DataSource + */ + public void start() throws IOException + { + iDataSource.start(); + } + + /** + * from DataSource + * Stops DataSource + * @see DataSource + */ + public void stop() throws IOException + { + iDataSource.stop(); + } + + /** + * from DataSource + * return sourceStreams of the DataSource + * + * @return set of source streams + * @see DataSource + */ + public SourceStream[] getStreams() + { + // return all streams from delegated DataSource except first + // buffered stream. + SourceStream[] originalStreams = iDataSource.getStreams(); + SourceStream[] streams = new SourceStream[ originalStreams.length ]; + System.arraycopy(originalStreams, 0, + streams, 0, originalStreams.length); + streams[ 0 ] = iSourceStream; + return streams; + } + + /** + * from interface Controllable + * Method return controls of the DataSource + * @return Control + * @see Controllable + * @see DataSource + */ + public Control[] getControls() + { + return iDataSource.getControls(); + } + + /** + * from interface Controllable + * Return a control by the Control Type, not supported + * @param controlType type of the control + * @return Control + */ + public Control getControl(String aControlType) + { + return iDataSource.getControl(aControlType); + } + +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/BufferSourceStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/BufferSourceStream.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,138 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: SourceStream that buffers data from another SourceStream. +* +*/ + + +package com.nokia.microedition.media; + +import java.io.IOException; +import javax.microedition.media.protocol.SourceStream; + +/** + * SourceStream that buffers data from another SourceStream. + * + */ +public class BufferSourceStream extends InputStreamSourceStream +{ + // Deferred buffer size + private static final int BUFFER_SIZE = 5120; + + // Stream to buffer + SourceStream iSourceStream; + + byte[] iBuffer; + + // stream read position + int iPos; + + /** + * Constructor. + * @param aInputStream An InputStream + */ + public BufferSourceStream(SourceStream aSourceStream) + { + iSourceStream = aSourceStream; + } + + /** + * Return header data. + * @return header data + */ + public byte[] getHeader() throws IOException + { + // Read header if this method is called for the first time + if (iBuffer == null) + { + byte[] tmpBuffer = new byte[ BUFFER_SIZE ]; + + int bytesInBuffer = iSourceStream.read(tmpBuffer, 0, BUFFER_SIZE); + + // bytesInBuffer is the total number of bytes read into the buffer, + // or -1 if there is no more data because the end of the stream has + // been reached. + if (bytesInBuffer >= 0) + { + iBuffer = new byte[ bytesInBuffer ]; + + System.arraycopy(tmpBuffer, 0, + iBuffer, 0, bytesInBuffer); + } + else + { + throw new IOException(); + } + } + return iBuffer; + } + + /** + * Read from Input Stream + * @param buffer Input Stream + * @param offset where reading starts + * @param length length of read data + * @return bytes read + * @throws IOException + */ + public int read(byte[] aBuffer, int aOffset, int aLength) throws IOException + { + // bytes read from internal buffer + int bytesFromBuffer = 0; + + + if ((iBuffer != null) && // read from iBuffer if getHeader is called + (iPos < iBuffer.length)) + { + // Need to read from buffer + if (aLength < iBuffer.length - iPos) + { + // aLength bytes can be read from buffer + bytesFromBuffer = aLength; + } + else + { + // aLength cannot be read from buffer + // read all there is available + bytesFromBuffer = iBuffer.length - iPos; + } + + System.arraycopy(iBuffer, iPos, + aBuffer, aOffset, bytesFromBuffer); + + // move stream position + iPos += bytesFromBuffer; + return bytesFromBuffer; + } + + // bytes read from iSourceStream + int bytesFromStream = 0; + // Check if bytes are needed from SourceStream + if (bytesFromBuffer < aLength) + { + bytesFromStream = iSourceStream.read(aBuffer, + bytesFromBuffer, + aLength - bytesFromBuffer); + if (bytesFromStream != -1) + { + // move stream position, if not end of stream + iPos += bytesFromStream; + } + } + + return bytesFromStream; + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/ManagerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/ManagerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,675 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.microedition.media; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Vector; +import java.util.Enumeration; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.TimeBase; +import javax.microedition.media.Player; +import javax.microedition.media.MediaException; + +//import com.symbian.lcdjava.lang.ObjectExtensions; +//import com.symbian.epoc.events.MIDEventServer; +//import com.symbian.midp.runtime.ToolkitInvoker; +//import com.symbian.midp.runtime.ToolkitObserver; + +import com.nokia.microedition.media.protocol.ProtocolFactory; +import com.nokia.microedition.media.tone.PlayToneImpl; +import com.nokia.microedition.volumekeys.ForegroundListener; +import com.nokia.mj.impl.rt.support.Finalizer; + +//To get the shutdown event from the midlet +import com.nokia.mj.impl.rt.support.ApplicationUtils; +import com.nokia.mj.impl.rt.support.ApplicationInfo; +import com.nokia.mj.impl.rt.support.ShutdownListener; + +/** + * ManagerImpl implements the functionality specified in + * javax.microedition.media.Manager class. + * This class is a singleton and instance can be got with getInstance method. + */ +public class ManagerImpl implements PlugIn +{ + // ManagerImpl native instance + private static int sManagerHandle; + + // CMMAEventSource + private static int iFunctionSourceHandle; + + // Static instance, can be got with getInstace method + private static ManagerImpl sManager; + + private final TimeBase iSystemTimeBase = new SystemTimeBase(); + + private final Vector iPlugIns = new Vector(); + private final ProtocolFactory iProtocolFactory = new ProtocolFactory(); + private final ForegroundListener iForegroundListener; + private Finalizer iFinalizer; + + Finalizer registerForFinalization() + { + return new Finalizer() + { + public void finalizeImpl() + { + doFinalize(); + } + }; + } + + // Play tone implementation + private PlayToneImpl iPlayToneImpl = new PlayToneImpl(); + + static + { + + try{ + com.nokia.mj.impl.rt.support.Jvm.loadSystemLibrary("javalegacyutils"); + } + catch(Exception e) + { + System.out.println("loading javalegacyutils failed....."); + } + System.out.println("inside static block of ManagerImpl.java"); + // This is called when class is loaded for the first time + sManager = new ManagerImpl(); + try + { + // Invoke external components + Setup.setup(iFunctionSourceHandle); + } + catch (OutOfMemoryError oome) + { + // External setup failed clean MMA native resources and throw oome + sManager.doFinalize(); + throw oome; + } + } + + /** + * This private constructor can be called only from staic block. + */ + private ManagerImpl() + { + // Will cause registeredFinalize() to be called when ObjectExtensions + // is finalized. + + + com.nokia.mj.impl.rt.support.Jvm.loadSystemLibrary("javamobilemedia"); + //ObjectExtensions.registerForFinalization(this); + iFinalizer = registerForFinalization(); + + // Event server contructor needs new String object, + // otherwise it don't work.. + + iFunctionSourceHandle = _createEventSource(); + if (iFunctionSourceHandle < NativeError.KErrNone) + { + throw new OutOfMemoryError("Symbian OS error: " + sEventSourceHandle); + } + + sManagerHandle = _createManager(iFunctionSourceHandle, + ApplicationInfo.getInstance().getSuiteUid().hashCode()); + if (sManagerHandle < NativeError.KErrNone) + { + throw new OutOfMemoryError(); + } + //Use ShutdownListener to get notification of exit and release the resource + //MMAPI UI 3.x work + + setShutdownListener(); + + // ManagerImpl is also a PlugIn that getAllSupportedContentTypes, + // getAllSupportedProtocols and createPlayer methods can be used + // through PlugIn interface. + iPlugIns.addElement(this); + + // support for device://tone and jts + iPlugIns.addElement( + new com.nokia.microedition.media.protocol.device.tone.Protocol()); + + // Create foreground listener which listens the state of the midlet + // This feature is a part of the media keys feature so it is flagged + System.out.println("before constructing ForegroundListener...."); + iForegroundListener = new ForegroundListener(iFunctionSourceHandle); + iForegroundListener.init(); + } + + /** + * Returns MMA event source handle + */ + public static int getEventSource() + { + return iFunctionSourceHandle; + } + /** + * Returns native handle to Manager + */ + public static int getHandle() + { + return sManagerHandle; + } + + /** + * Return ManagerImpl instance + */ + public static ManagerImpl getInstance() + { + return sManager; + } + + /** + * Adds new PlugIn to PlugIns array. + * @param aPlugIn New PlugIn. + */ + public void addPlugIn(PlugIn aPlugIn) + { + iPlugIns.addElement(aPlugIn); + } + + + + + /** + * This will be called when ObjectExtensions is finalized. + */ + synchronized final void doFinalize() + { + _dispose(iFunctionSourceHandle); + iFunctionSourceHandle = 0; + } + + /** + * This method is called in Toolkit's destroyNotify call. + * This will release convenient native resources. All native resource + * will be deleted in registeredFinalize() method. + */ + synchronized final void release() + { + _release(iFunctionSourceHandle); + } + + /** + * Create String array from Vector and remove String duplicates. + * @param aVector Vector containing String objects. + */ + private String[] createStringArray(Vector aVector) + { + // remove all duplicates from the vector + for (int i = 0; i < aVector.size(); i++) + { + String element = (String)aVector.elementAt(i); + for (int j = i + 1; j < aVector.size();) + { + if (element.equals((String)aVector.elementAt(j))) + { + aVector.removeElementAt(j); + } + else + { + j++; + } + } + } + + // Create new array for vector elements and copy elements + String[] s = new String[ aVector.size()]; + aVector.copyInto(s); + return s; + } + + /** + * Return the list of supported content types for the given protocol. + *

            + * See content types for the syntax + * of the content types returned. + * See protocol name for the syntax + * of the protocol used. + *

            + * For example, if the given protocol + * is "http", + * then the supported content types that can be played back + * with the http protocol will be returned. + *

            + * If null is passed in as the protocol, + * all the supported content types for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given protocol is an invalid or + * unsupported protocol, then an empty array will be returned. + * + * @param aProtocol The input protocol for the supported content types. + * @return The list of supported content types for the given protocol. + */ + public String[] getAllSupportedContentTypes(String aProtocol) + { + if ((aProtocol != null) && (aProtocol.length() == 0)) + { + // No supported types for 0 length string. + return new String[ 0 ]; + } + Vector contentTypes = new Vector(); + + Enumeration plugIns = iPlugIns.elements(); + + // go through all plugins and get content types + while (plugIns.hasMoreElements()) + { + PlugIn plugIn = (PlugIn)plugIns.nextElement(); + String[] types = plugIn.getSupportedContentTypes(aProtocol); + + // Add all types to vector + for (int i = 0; i < types.length; i++) + { + contentTypes.addElement(types[ i ]); + } + } + return createStringArray(contentTypes); + } + + /** + * Return the list of supported protocols given the content + * type. The protocols are returned + * as strings which identify what locators can be used for creating + * Player's. + *

            + * See protocol name for the syntax + * of the protocols returned. + * See content types for the syntax + * of the content type used. + *

            + * For example, if the given content_type + * is "audio/x-wav", then the supported protocols + * that can be used to play back audio/x-wav + * will be returned. + *

            + * If null is passed in as the + * content_type, + * all the supported protocols for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given content_type is an invalid or + * unsupported content type, then an empty array will be returned. + * + * @param aContentType The content type for the supported protocols. + * @return The list of supported protocols for the given content type. + */ + public String[] getAllSupportedProtocols(String aContentType) + { + String contentType = aContentType; + if ((contentType != null) && contentType.equals("")) + { + return new String[ 0 ]; + } + + Vector protocols = new Vector(); + Enumeration plugIns = iPlugIns.elements(); + while (plugIns.hasMoreElements()) + { + PlugIn plugIn = (PlugIn)plugIns.nextElement(); + String[] types = plugIn.getSupportedProtocols(aContentType); + for (int i = 0; i < types.length; i++) + { + protocols.addElement(types[ i ]); + } + } + return createStringArray(protocols); + } + + /** + * From PlugIn. Get MMA supported protocols. + */ + public String[] getSupportedProtocols(String aContentType) + { + String[] protocols = _getSupportedProtocols(iFunctionSourceHandle, + sManagerHandle, + aContentType); + NativeError.checkOOM(protocols); + return protocols; + } + + /** + * From PlugIn. Get MMA supported types. + */ + public String[] getSupportedContentTypes(String aProtocol) + { + String[] types = _getSupportedContentTypes(iFunctionSourceHandle, + sManagerHandle, + aProtocol); + NativeError.checkOOM(types); + return types; + } + + /** + * From PlugIn. + */ + public InternalPlayer createPlayer(DataSource aSource) + throws MediaException, IOException + { + InternalPlayer player = null; + if (aSource.getContentType() != null) + { + // Create player from content type + if (isValidContentType(aSource.getContentType())) + { + player = NativePlayerFactory.createPlayer(aSource.getContentType(), + aSource); + } + else + { + throw new MediaException( + "Content type not supported: " + aSource.getContentType()); + } + } + + if ((player == null) && + (aSource.getLocator() != null)) + { + // Create player from locator + player = NativePlayerFactory.createPlayer( + new Locator(aSource.getLocator()), + aSource); + } + + if (player == null) + { + // Could not create player from content-type or locator, + // try to create player from header data + player = NativePlayerFactory.createPlayer( + ((BufferDataSource)aSource).getHeader(), + aSource); + } + + return player; + } + + /** + * From PlugIn. Empty implemation. + */ + public void preparePlayer(InternalPlayer aPlayer) throws MediaException + { + + } + + /** + * This method calls preparePlayer to all PlugIns. + */ + private void pluginsPreparePlayer(InternalPlayer aPlayer) + throws MediaException + { + // Call preparePlayer to all plugins + Enumeration plugins = iPlugIns.elements(); + while (plugins.hasMoreElements()) + { + ((PlugIn)plugins.nextElement()).preparePlayer(aPlayer); + } + } + + /** + * Create a Player from an input locator. + * + * @param aLocator A locator string in URI syntax that describes + * the media content. + * @return A new Player. + * @exception IllegalArgumentException Thrown if locator + * is null. + * @exception MediaException Thrown if a Player cannot + * be created for the given locator. + * @exception IOException Thrown if there was a problem connecting + * with the source pointed to by the locator. + * @exception SecurityException Thrown if the caller does not + * have security permission to create the Player. + */ + public Player createPlayer(String aLocator) + throws IOException, MediaException + { + if (aLocator == null) + { + throw new IllegalArgumentException("Locator is null."); + } + InternalPlayer player = iProtocolFactory.createPlayer( + new Locator(aLocator)); + if (player == null) + { + throw new MediaException("Locator not supported: " + + aLocator); + } + pluginsPreparePlayer(player); + return player; + } + + /** + * Create a InternalPlayer for a DataSource. + */ + public InternalPlayer createInternalPlayer(DataSource aSource) + throws IOException, MediaException + { + // Throw IllegalArgumentException if source is null. + if (aSource == null) + { + throw new IllegalArgumentException("DataSource is null."); + } + aSource.connect(); // Ensure that external source is connected. + if (aSource.getStreams() == null || + aSource.getStreams().length == 0) + { + // There must be atleast one stream in the DataSource + throw new MediaException( + "There must be at least one stream in datasource"); + } + + BufferDataSource bdc = new BufferDataSource(aSource); + + InternalPlayer player = null; + Enumeration plugins = iPlugIns.elements(); + // Loop through all plugins, stop if player was created + while (plugins.hasMoreElements() && + (player == null)) + { + PlugIn tmp = (PlugIn)plugins.nextElement(); + player = tmp.createPlayer(bdc); + } + + if (player == null) + { + // MMA or plugins could not create player + bdc.disconnect(); + + throw new MediaException("Could not create player."); + } + + return player; + } + + /** + * Create a Player to play back media from an + * InputStream. + *

            + * The type argument + * specifies the content-type of the input media. If + * null is given, Manager will + * attempt to determine the type. However, since determining + * the media type is non-trivial for some media types, it + * may not be feasible in some cases. The + * Manager may throw a MediaException + * to indicate that. + * + * @param aStream The InputStream that delivers the + * input media. + * @param aType The ContentType of the media. + * @return A new Player. + * @exception IllegalArgumentException Thrown if stream + * is null. + * @exception MediaException Thrown if a Player cannot + * be created for the given stream and type. + * @exception IOException Thrown if there was a problem reading data + * from the InputStream. + * @exception SecurityException Thrown if the caller does not + * have security permission to create the Player. + */ + public Player createPlayer(InputStream aStream, String aType) + throws IOException, MediaException + { + if (aStream == null) + { + throw new IllegalArgumentException("InputStream is null."); + } + + InputStreamSourceStream sourceStream = + new InputStreamSourceStream(aStream); + + // Create data source without locator. + DataSource dataSource = new InputStreamDataSource(sourceStream, + aType); + InternalPlayer player = createInternalPlayer(dataSource); + + if (player != null) + { + // Call preparePlayer to all plugins + pluginsPreparePlayer(player); + } + + return player; + } + + /** + * Play back a tone as specified by a note and its duration. + * A note is given in the range of 0 to 127 inclusive. The frequency + * of the note can be calculated from the following formula: + *

            +     *     SEMITONE_CONST = 17.31234049066755 = 1/(ln(2^(1/12)))
            +     *     note = ln(freq/8.176)*SEMITONE_CONST
            +     *     The musical note A = MIDI note 69 (0x45) = 440 Hz.
            +     * 
            + * This call is a non-blocking call. Notice that this method may + * utilize CPU resources significantly on devices that don't + * have hardware support for tone generation. + * + * @param aNote Defines the tone of the note as specified by the + * above formula. + * @param aDuration The duration of the tone in milli-seconds. + * Duration must be positive. + * @param aVolume Audio volume range from 0 to 100. 100 represents + * the maximum + * volume at the current hardware level. Setting the volume to a + * value less + * than 0 will set the volume to 0. Setting the volume to greater than + * 100 will set the volume to 100. + * + * @exception IllegalArgumentException Thrown if the given note or + * duration is out of range. + * @exception MediaException Thrown if the tone cannot be played + * due to a device-related problem. + */ + public void playTone(int aNote, int aDuration, int aVolume) + throws MediaException + { + iPlayToneImpl.playTone(aNote, aDuration, aVolume); + } + + /** + * Get the time-base object for the system. + * @return The system time base. + */ + public TimeBase getSystemTimeBase() + { + return iSystemTimeBase; + } + + public boolean isValidContentType(String contentType) + { + for (int i=0; i < contentType.length(); i++) + { + if ((contentType.charAt(i) >= 0 && contentType.charAt(i) <= 31) || contentType.charAt(i) == 127) + return false; + } + return true; + } + + + +/** + * Registers for shutdown listener + */ + private void setShutdownListener() + { + // Get the instance of ApplicationUtils. + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + + // add the listener + appUtils.addShutdownListener(new ShutdownListener() + { + public void shuttingDown() + { + try + { + System.out.println("Shutting down.........."); + // Do cleaning... + release(); + } + catch (Exception ex) + { + // catch the exception and call dispose + } + + if (iFunctionSourceHandle != 0) + { + _dispose(iFunctionSourceHandle); + iFunctionSourceHandle = 0; + } + } + + }); + } // end setShutdownListener() + + +// MMAPI UI 3.x req +/** + * get midlet state + */ + + public boolean isForground() + { + return iForegroundListener.isForeground(); + } + + + private native int _createManager(int aEventSourceHandle, + int aMIDletSuiteID); + private native int _createEventSource(); + private native void _dispose(int aEventSourceHandle); + + /** + * Releases native resources. + * @param aEventSourceHandle Handle to native CMMAEventSource instance. + */ + private native void _release(int aFunctionSourceHandle); + + private static native String[] _getSupportedContentTypes(int aFunctionSourceHandle, + int aManagerHandle, + String aContentType); + + private static native String[] _getSupportedProtocols(int aFunctionSourceHandle, + int aManagerHandle, + String aProtocol); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/control/MetaDataControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/control/MetaDataControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,197 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements functionalities defined in the +* MetaDataControl interface (included in +* javax.microedition.media.control package). +* +*/ + + +package com.nokia.microedition.media.control; + +import java.util.Vector; +import java.util.Enumeration; + +// CLASS DEFINITION +/** + * The MetaDataControl class implements functionalities defined + * in the MetaDataControl interface (included in + * javax.microedition.media.control package). + */ + +public class MetaDataControl + extends ControlImpl + implements javax.microedition.media.control.MetaDataControl +{ + + /** + * The metadata keys received from the native side. It is assumed that + * the keys will not change during the lifetime of a media clip or + * stream. Key data is used so frequently that we want to buffer it + * here at Java side. + */ + private String[] iKeys = null; + private static final String[] DEFAULT_DATA = { MetaDataControl.AUTHOR_KEY, + MetaDataControl.COPYRIGHT_KEY, + MetaDataControl.DATE_KEY, + MetaDataControl.TITLE_KEY + }; + private static final String DEFAULT_DATA_VALUE = "unknown"; + + // Static initialization + + /** + * Creates an instance of MetaDataControl. + */ + public MetaDataControl() + { + } + + /** + * Returns acceptable metadata keys. + * + * The keys can be used for getting specific metadata value associated to each key. + * + * @See javax.microedition.media.control.MetaDataControl + * interface documentation for details. + * + * @return Acceptable key values. + * + */ + public String[] getKeys() + { + checkState(); + // Get the keys only if not yet buffered. + if (null == iKeys) + { + int keyCount = _getKeysCount(iEventSource, iControlHandle); + + if (keyCount < 0) // can't read key count + { + iKeys = DEFAULT_DATA; + return iKeys; + } + + Vector keys = new Vector(keyCount + 1); + + for (int i = 0; i < keyCount; i++) + { + String currentKey = _getKey(iEventSource, iControlHandle, i); + if (currentKey == null) // can't read key value + { + iKeys = DEFAULT_DATA; + return iKeys; + } + keys.addElement(currentKey); + } + + // Check if the default keys are already in the key vector + // and if not, then add them + + for (int i = 0; i < DEFAULT_DATA.length; i++) + { + checkAddKey(keys, DEFAULT_DATA[ i ]); + } + + iKeys = new String[ keys.size()]; + keys.copyInto(iKeys); + } + return iKeys; + } + + /** + * Check if there is already a key in vector and if not, then + * add one. + * @param aKeys vector containing keys to be checked and which to add + * new key + * @param aKey key string to be added if not already present in aKeys + */ + private void checkAddKey(Vector aKeys, String aKey) + { + for (Enumeration e = aKeys.elements(); e.hasMoreElements();) + { + String currentElement = (String)e.nextElement(); + if (currentElement.equals(aKey)) + { + return; + } + } + // Otherwise add the key + aKeys.addElement(new String(aKey)); + } + + /** + * Fetches a value of the given metadata key. + * + * See javax.microedition.media.control.MetaDataControl + * interface documentation for details. + * + * @param aKey Key of the metadata value to be returned. + * + * @return Value of the metadata. + * + * @exception IllegalArgumentException Thrown if the given key is + * null or invalid. + */ + public String getKeyValue(String aKey) + { + checkState(); + if (null == aKey) + { + throw new IllegalArgumentException("Key cannot be null"); + } + + getKeys(); // Buffer the keys if not present + + int arrLen = iKeys.length; + int i = 0; + + // Check if the given key is valid and return the value. + while (i < arrLen) + { + if (iKeys[ i ].equals(aKey)) + { + String value = _getKeyValue(iEventSource, iControlHandle, aKey); + + // if key is ok but value is null then this key does not really + // exist and it must be checked whether it is one from DEFAULT_DATA + if (value == null) + { + for (int j = 0; j < DEFAULT_DATA.length; j++) + { + if (aKey.equals(DEFAULT_DATA[ j ])) + { + return(DEFAULT_DATA_VALUE); + } + } + } + return value; + } + ++i; + } + + // No match - invalid key. + throw new IllegalArgumentException("Invalid non-null key"); + } + + private native int _getKeysCount(int aEventSource, + int aControlHandle); + private native String _getKey(int aEventSource, + int aControlHandle, + int aIndex); + private native String _getKeyValue(int aEventSource, + int aControlHandle, + String aKey); +} //end of file + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/protocol/http/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/protocol/http/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements TimeBase +* +*/ + + +package com.nokia.microedition.media.protocol.http; + + + + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.protocol.ConnectorProtocol; +import com.nokia.microedition.media.HttpDataSource; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ManagerImpl; + +public class Protocol extends ConnectorProtocol +{ + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + HttpDataSource dataSource = new HttpDataSource(aLocator); + return ManagerImpl.getInstance().createInternalPlayer(dataSource); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/protocol/https/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc.mmf/com/nokia/microedition/media/protocol/https/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements TimeBase +* +*/ + + +package com.nokia.microedition.media.protocol.https; + + + + +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.protocol.ConnectorProtocol; +import com.nokia.microedition.media.HttpDataSource; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ManagerImpl; + +public class Protocol extends ConnectorProtocol +{ + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + HttpDataSource dataSource = new HttpDataSource(aLocator); + return ManagerImpl.getInstance().createInternalPlayer(dataSource); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/ConnectorDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/ConnectorDataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,162 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is an imlementation of DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.MediaException; +import java.io.IOException; +import javax.microedition.io.StreamConnection; +import javax.microedition.io.Connection; +import javax.microedition.io.Connector; +import javax.microedition.io.ConnectionNotFoundException; +import com.nokia.mj.impl.utils.Logger; + +/** + * DataSource that uses Connector to create connections and + * InputStreams. + */ +public class ConnectorDataSource extends InputStreamDataSource +{ + // Connection object. + StreamConnection iConnection; + + /** + * Constructor. + * @param aLocator Locator to connect. + */ + public ConnectorDataSource(Locator aLocator) + throws IOException, MediaException + { + super(aLocator.getLocatorString()); + open(); // open iConnection + iSourceStream = new InputStreamSourceStream( + iConnection.openInputStream()); + } + + /** + * Open connection and initialize + */ + protected void open() throws IOException, MediaException + { + try + { + Connection connection = Connector.open(getLocator(), + Connector.READ); + + // derived classes may do additional checks + checkConnection(connection); + + // Only StreamConnection is supported + iConnection = (StreamConnection)connection; + } + catch (ConnectionNotFoundException cnfe) + { + // ConnectionNotFoundException extends IOException, + // we must throw MediaException in this case. + throw new MediaException( + "Connection could not be found, " + cnfe.getMessage()); + } + catch (IllegalArgumentException iae) + { + // IllegalArgumentException can be thrown only if + // connector or stream is null. + throw new MediaException( + "Connector stream is null, " + iae.getMessage()); + } + catch (ClassCastException cce) + { + // Returned connection object was not StreamConnection + // or connection was not supported in checkConnection method. + throw new MediaException(cce.getMessage()); + } + } + + /** + * from DataSource + * Connect to the stream + * @throws IOException + * @see DataSource + */ + public void connect() throws IOException + { + // if connection is not null source is already connected. + if (iConnection == null) + { + try + { + open(); + iSourceStream.setStream(iConnection.openInputStream()); + } + catch (MediaException me) + { + // MediaException cannot be thrown from this method. + throw new IOException( + "failed to connect to stream, " + me.getMessage()); + } + } + } + + /** + * from DataSource + * Disconnect from the stream + */ + public void disconnect() + { + // If iConnection is null disconnect is already called. + if (iConnection != null) + { + try + { + iSourceStream.close(); + } + catch (IOException ioe) + { + // disconnect cannot throw any exception and because source will + // be disconnected in Player's close or deallocate which can't + // throw exceptions we have to hide the exception. + Logger.WLOG(Logger.EJavaMMAPI, + "MMA::ConnectorDataSource::disconnect failed ", ioe); + } + try + { + iConnection.close(); + // source is disconnected and may be reconnected + iConnection = null; + } + catch (IOException ioe) + { + // disconnect cannot throw any exception and because source will + // be disconnected in Player's close or deallocate which can't + // throw exceptions we have to hide the exception. + Logger.WLOG(Logger.EJavaMMAPI, + "MMA::ConnectorDataSource::disconnect failed ", ioe); + } + } + } + + /** + * Protected method to connection object in derived classes. + * @param aConnection Connection to check + */ + protected void checkConnection(Connection aConnection) throws IOException + { + // This class does not do additional checks. + } +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/ControlContainer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/ControlContainer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,316 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.microedition.media; + +import javax.microedition.media.Control; +import javax.microedition.media.Controllable; +import com.nokia.microedition.media.control.ControlImpl; +import javax.microedition.media.Player; +import java.util.Hashtable; +import java.util.Enumeration; +import com.nokia.mj.impl.utils.Logger; + +/** + * ControlContainer class creates java control objects according to a classname + * which is got from native control object. Created controls are accessible + * through Controllable interface which is implemented in this class. + */ +public class ControlContainer implements Controllable +{ + /** + * Default control package. Used when getting control with + * getControl method which appends default control package if package is + * not specified. + */ + static final String CONTROL_DEFAULT_PACKAGE = + "javax.microedition.media.control."; + + + /** + * Default control package. Used when getting control with + * getControl method which appends default control package if package is + * not specified. + */ + static final String CONTROL_IMPLEMENTATION_PACKAGE = + "com.nokia.microedition.media.control."; + /** + * Hashtable containing controls identified with a full package name. + * All control names starts with iDefaultPackage. + */ + private final Hashtable iControls = new Hashtable(); + + /** + * Creates new ControlContainer. + */ + private ControlContainer() + { + } + + /** + * Create new ControlContainer and populates the controls. + * + * If native control name does not contain package name default + * com.nokia.microedition.media.control. package is used. + * If control name starts with . (.package.ClassName), Java control is not + * created. If control name contains valid package name and classname Java + *instance will be created. + * + * + * @param aPlayer Player which will contain the controls. + * @param aEventSourceHandle Handle to native event source. + * @param aNativeHandle Handle to native control source. + */ + public static final ControlContainer populateControls( + Player aPlayer, + int aEventSourceHandle, + int aNativeHandle) + { + ControlContainer container = new ControlContainer(); + + // Get amount of controls in native object. + int controlCount = _getControlsCount(aNativeHandle); + + // Create java object for each native objects. + for (int i = 0; i < controlCount; i++) + { + // Get handle to native object at index i + int controlHandle = _getControlHandle(aNativeHandle, + i); + + // Get public class name for the control. + String realClassName = _getPublicControlClassName(controlHandle); + + // If null public control name was returned, Java control is not + // created. This allows extensions to use existing Player's + // native control array. + if (realClassName == null) + { + continue; + } + + // Get the implementation class name for the control which will + // be used to create java object. + String className = _getControlClassName(controlHandle); + + // Add package if it does not exists + if (className.indexOf('.') < 0) + { + className = CONTROL_IMPLEMENTATION_PACKAGE + className; + realClassName = CONTROL_DEFAULT_PACKAGE + className; + } + + // create java instance + Control control = createControl(aPlayer, + className, + controlHandle, + aEventSourceHandle); + container.iControls.put(realClassName, control); + } + + // population succeed, return created collection + return container; + } + + /** + * Adds new control + */ + public void addControl(Control aControl, String aControlName) + { + iControls.put(aControlName, aControl); + } + + /** + * Disposes all the controls + */ + public void dispose() + { + Enumeration controls = iControls.elements(); + while (controls.hasMoreElements()) + { + Object control = controls.nextElement(); + + // only ControlImpl derived classes need to be notified. + if (control instanceof ControlImpl) + { + ((ControlImpl)control).notifyDispose(); + } + } + } + + /** + * Implements method defined in javax.microedition.media.Controllable. + * + * @see javax.microedition.media.Controllable + * @param aControlType the class name of the Control. The class name should + * be given either as the fully-qualified name of the class; or if the + * package of the class is not given, the package + * javax.microedition.media.control is assumed. + * @return the object that implements the control, or null. + */ + public Control getControl(String aControlType) + { + if (aControlType == null) + { + throw new IllegalArgumentException("argument is null"); + } + + String controlType = aControlType; + + // check if package name exists + if (controlType.indexOf(".") == -1) + { + // add package name + controlType = CONTROL_DEFAULT_PACKAGE + aControlType; + } + Control control = (Control)iControls.get(controlType); + + // If control does not exists with default name, check if there is + // is a control with same type ( extends the given class name ). + if (control == null) + { + try + { + // try to create class for control + Class controlClass = Class.forName(controlType); + + Enumeration elements = iControls.elements(); + + // search if any control is same type that requested control + while (elements.hasMoreElements() && + control == null) + { + Control tmpControl = (Control)elements.nextElement(); + if (controlClass.isInstance(tmpControl)) + { + // control is found + control = tmpControl; + } + } + } + catch (ClassNotFoundException cnfe) // the class could not be found + { + // Exception is ignored and null is returned from this method + Logger.ELOG(Logger.EJavaMMAPI, + "ControlContainer::getControl ", cnfe); + } + catch (Error e) // the function failed for any other reason. + { + // Error is ignored and null is returned from this method + Logger.ELOG(Logger.EJavaMMAPI, + "ControlContainer::getControl " , e); + } + } + return control; + } + + /** + * Implements method defined in javax.microedition.media.Controllable. + * + * @see javax.microedition.media.Controllable + * @return the collection of Control objects. + */ + public Control[] getControls() + { + Control[] controls = new Control[ iControls.size()]; + Enumeration elements = iControls.elements(); + int i = 0; + // Put all controls to array + while (elements.hasMoreElements()) + { + controls[ i ] = (Control)elements.nextElement(); + i++; + } + return controls; + } + + /** + * Creates new Control instance. + * All control classes must be in iPrivatePackage package and + * extend the ControlImpl base class. Created control is initialized + * with native control handle and eventsource handle. + * + * @param aPlayer Player which will contain the controls. + * @param aClassName Control's class name without the package. + * @param aControlHandle Handle to native control. + * @param aEventSourceHandle Handle to native control source. + * @return created control + */ + static private final Control createControl(Player aPlayer, + String aClassName, + int aControlHandle, + int aEventSourceHandle) + { + ControlImpl control = null; + + // Try to make control instance. If instantion fails, it is an internal + // error and can only occur in development time. + try + { + Class controlClass = + Class.forName(aClassName); + control = (ControlImpl)controlClass.newInstance(); + control.setHandles(aPlayer, aEventSourceHandle, aControlHandle); + } + catch (InstantiationException ie) + { + throw new OutOfMemoryError("Instantiation failed, " + ie.getMessage()); + } + catch (IllegalAccessException iae) + { + throw new OutOfMemoryError("Illegal access, " + iae.getMessage()); + } + catch (ClassNotFoundException cnfe) + { + throw new OutOfMemoryError("Class not found, " + cnfe.getMessage()); + } + return control; + } + + /** + * Return the amount of controls in native control source. + * + * @param aNativeHandle Handle to native control source object. + */ + private static native int _getControlsCount(int aNativeHandle); + + /** + * Return native handle to control at specified index. + * + * @param aNativeHandle Handle to native control source object. + * @param aControlIndex Control's index. + */ + private static native int _getControlHandle(int aNativeHandle, + int aControlIndex); + + + /** + * Returns the control class name that can be used to instantiate Java + * object. + * + * @param aControlHandle Handle to native control. + */ + private static native String _getControlClassName(int aControlHandle); + + /** + * Returns the control class name that is the public name for the control. + * + * @param aControlHandle Handle to native control. + */ + private static native String _getPublicControlClassName(int aControlHandle); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/HttpDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/HttpDataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,113 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is an imlementation of DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.MediaException; +import java.io.IOException; +import javax.microedition.io.Connection; +import javax.microedition.io.HttpConnection; +import javax.microedition.media.Control; + +/** + * This class extends ConnectorDataSource and adds http connection + * return value checking. + */ +public class HttpDataSource extends ConnectorDataSource implements SeekControl +{ + private static final String SEEK_CONTROL = "SeekControl"; + + // true when closed + boolean iClosed = false; + + /** + * Default constructor + */ + public HttpDataSource(Locator aLocator) + throws IOException, MediaException + { + super(aLocator); + } + + /** + * From ConnectorDataSource + * @see ConnectorDataSource + */ + protected void checkConnection(Connection aConnection) throws IOException + { + // Must handle also HTTP response codes + HttpConnection httpConnection = (HttpConnection)aConnection; + if (httpConnection.getResponseCode() != HttpConnection.HTTP_OK) + { + throw new IOException( + "Could not connect to source, " + httpConnection.getResponseMessage()); + } + } + + /** + * From SeekControl + */ + public void seek(int aWhere) throws IOException + { + // Only seek to start is supported. + if (aWhere == 0) + { + disconnect(); + + // do not connect if stream is closed + if (!iClosed) + { + connect(); + } + + if (iClosed) + { + // disconnect if stream was closed during connect operation + disconnect(); + } + } + else + { + throw new IOException("Internal error, invalid position: " + aWhere); + } + } + + /** + * From SeekControl + */ + public void close() + { + iClosed = true; + } + + /** + * From Controllable + */ + public Control getControl(String aControlType) + { + Control control = null; + if (aControlType.equals(SEEK_CONTROL)) + { + control = this; + } + // else return null + return control; + } +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamDataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,163 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is an imlementation of DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.Control; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.protocol.SourceStream; +import java.io.IOException; + +/** + * DataSource which has InputStreamSourceStream. + */ +public class InputStreamDataSource extends DataSource +{ + // DataSource's stream + protected InputStreamSourceStream iSourceStream; + + // string that describes the content-type of the media that the source + // is providing. + protected String iContentType; + + /** + * Constructor. + * @param aSourceStream SourceSteam + * @param aType Content type. + */ + public InputStreamDataSource(InputStreamSourceStream aSourceStream, + String aType) + { + super(null); // no locator + iSourceStream = aSourceStream; + iContentType = aType; + } + + /** + * Constructor with Locator and stream + * @param aLocator Locator + * @param aSourceStream SourceSteam + * @param aType Content type. + */ + public InputStreamDataSource(String aLocator, + InputStreamSourceStream aSourceStream, + String aType) + { + super(aLocator); + iSourceStream = aSourceStream; + iContentType = aType; + } + + + /** + * Constructor with locator + * @param aLocator Locator + */ + public InputStreamDataSource(String aLocator) + { + super(aLocator); + } + + /** + * from DataSource + * @return Content Type + * @see DataSource + */ + public String getContentType() + { + return iContentType; + } + + /** + * from DataSource + * Connect to the stream + * @throws IOException + * @see DataSource + */ + public void connect() throws IOException + { + } + + /** + * from DataSource + * Disconnect from the stream + */ + public void disconnect() + { + } + + /** + * from DataSource + * Put DataSource to STARTED state + * @throws IOException Throw if DataSource is in wrong state + * @see DataSource + */ + public void start() throws IOException + { + } + + /** + * from DataSource + * Stops DataSource + * @see DataSource + */ + public void stop() + { + } + + /** + * from DataSource + * return sourceStreams of the DataSource + * + * @exception IllegalStateException Thrown if the source is not connected. + * @return set of source streams + * @see DataSource + */ + public SourceStream[] getStreams() + { + SourceStream[] streams = new SourceStream[ 1 ]; + streams[ 0 ] = iSourceStream; + return streams; + } + + /** + * from interface Controllable + * Method return controls of the DataSource + * @return Control + * @see Controllable + * @see DataSource + */ + public Control[] getControls() + { + return new Control[ 0 ]; + } + + /** + * from interface Controllable + * Return a control by the Control Type, not supported + * @param aControlType type of the control + * @return Control + */ + public Control getControl(String aControlType) + { + return iSourceStream.getControl("SeekControl"); + } + +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamSeekControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamSeekControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to mark and seek the inputstream. At present it is +* implemented to mark and seek to the front of the stream and not anywhere +* in the middle as the use case only demands such a beahaviour. +* +*/ + + +package com.nokia.microedition.media; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Class InputStreamSeekControl used to mark and seek the inputstream + */ +public class InputStreamSeekControl implements SeekControl +{ + + + private InputStream iInputStream; + + /** + * Constructor + */ + public InputStreamSeekControl() + { + + iInputStream = null; + } + + /* + * Constructor + * @param aInputStream - inputstream used by the InputStream class + * that needs to be marked and streamed + */ + public InputStreamSeekControl(InputStream aInputStream) + { + + iInputStream = aInputStream; + + if (iInputStream.markSupported() == true) + { + iInputStream.mark(0); + } + } + + /* + * Method seeks to the start of the inputstream. + * @param aWhere - is ignored as the seeking takes place to + * the begining always + */ + public void seek(int aWhere) throws IOException + { + + + if (iInputStream.markSupported() == true) + { + iInputStream.reset(); + } + } + + public void close() + { + + // intentionally left blank + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamSourceStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InputStreamSourceStream.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,205 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: SourceStream that reads InputStream +* +*/ + + +package com.nokia.microedition.media; + +import com.nokia.microedition.media.InputStreamSeekControl; + +import java.io.IOException; +import java.io.InputStream; +import javax.microedition.media.protocol.ContentDescriptor; +import javax.microedition.media.protocol.SourceStream; +import javax.microedition.media.Control; + +/** + * This class implements SourceStream interface. From the interface + * only read and getSeekType method will be used. This class is used + * to read InputStream. + */ +public class InputStreamSourceStream implements SourceStream +{ + // Stream used to read the content. + protected InputStream iInputStream = null; + + private static final String SEEK_CONTROL = "SeekControl"; + + private InputStreamSeekControl iSeekControl; + /** + * Constructor. + * @param aInputStream An InputStream + */ + public InputStreamSourceStream(InputStream aInputStream) + { + setStream(aInputStream); + iSeekControl = new InputStreamSeekControl(aInputStream); + } + + /** + * Constructor. + */ + public InputStreamSourceStream() + { + } + + /** + * Sets new InputStream. + * @param aInputStream An InputStream + */ + public final void setStream(InputStream aInputStream) + { + iInputStream = aInputStream; + } + + /** + * Closes the InputStream. This method can only be called if MMA + * must close the stream. + * + * @throws NullPointerException if setStream is not called. + * @throws IOException If an I/O error occurs + */ + public void close() throws IOException + { + iInputStream.close(); + } + + /** + * Read from Input Stream + * @param aBuffer Input Stream + * @param aOffset where reading starts + * @param aLength length of read data + * @return bytes read + * @throws IOException + */ + public int read(byte[] aBuffer, int aOffset, int aLength) throws IOException + { + return iInputStream.read(aBuffer, aOffset, aLength); + } + + /** + * Seek type of the stream + * @return seek type based on the inputstream's capability + */ + public int getSeekType() + { + if (iInputStream != null && iInputStream.markSupported() == true) + { + + return SEEKABLE_TO_START; + } + else + { + return NOT_SEEKABLE; + } + } + + /** + * From interface SourceStream. Method not implemented. + * @see SourceStream + * @return size of the stream available + */ + public int getTransferSize() + { + return 0; + } + + /** + * From interface SourceStream. Method not implemented. + * @see SourceStream + * @param aWhere where to seek + * @return seeked position, allways the current position + * @throws IOException + */ + public long seek(long aWhere) throws IOException + { + return 0; + } + + /** + * From interface SourceStream. Method not implemented. + * @see SourceStream + * @return current position + */ + public long tell() + { + return 0; + } + + /** + * From interface SourceStream. Method not implemented. + * @see SourceStream + * @return The content type + * @see ContentDescriptor + */ + public ContentDescriptor getContentDescriptor() + { + // Return empty content descriptor. + // This method is not used. + return new ContentDescriptor(""); + } + + /** + * From interface SourceStream. Method not implemented. + * @see SourceStream + * @return content length which is allways 0 + */ + public long getContentLength() + { + return 0; + } + + /** + * From interface Controllable. Method not implemented. + * @see SourceStream + * @see Controllable + */ + public Control[] getControls() + { + Control [] aControls = new Control[1]; + + aControls[0] = iSeekControl; + + return aControls; + } + + /** + * From interface Controllable. Method not implemented. + * @param aControlType wanted control type + * @return Control null + * @See Controllable + */ + public Control getControl(String aControlType) + { + if (aControlType == SEEK_CONTROL && getSeekType() == SEEKABLE_TO_START) + { + return iSeekControl; + } + else + { + return null; + } + } + /** + * @author d35kumar + * @return + */ + public InputStream getInputStream(){ + return iInputStream; + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InternalPlayer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/InternalPlayer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: InternalPlayer +* +*/ + +package com.nokia.microedition.media; + +import javax.microedition.media.Control; +import javax.microedition.media.Player; +import javax.microedition.media.MediaException; + +/** + * Internal inteface for MMA players. All players used in MMA must implement + * this interface. + */ +public interface InternalPlayer extends Player +{ + /** + * Adds new Control to player. + * @param aControl New Control to add. + * @param aControlType Fully-qualified name of the control class. + * @exception MediaException Thrown if new Control cannot be added to + * InternalPlayer. + */ + void addControl(Control aControl, String aControlType) + throws MediaException; + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/Locator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/Locator.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,113 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.MediaException; + +/** + * Locator parsing class + */ +public class Locator +{ + private static final String PROTOCOL_SEPARATOR = "://"; + private static final char PARAMETER_SEPARATOR = '?'; + private final String iLocator; + + /** + * Constructor + * @param aLocator Locator to be parsed + */ + public Locator(String aLocator) + { + iLocator = aLocator; + } + /** + * Parses the protocol part of the locator e.g. returns + * "capture" from "capture://audio?encoding=amr" locator + * @return parsed protocol + * @throw MediaException if Protocol cannot + * be parsed from the locator + */ + public String getProtocol() throws MediaException + { + // Find protocol separator + int pSep = iLocator.indexOf(PROTOCOL_SEPARATOR); + + // Protocol must exist + if (pSep == -1) + { + throw new MediaException( + "Could not create player, URI separator not found"); + } + return iLocator.substring(0, pSep); + } + + /** + * Parses the middle part of the locator e.g. returns + * "audio" from "capture://audio?encoding=amr" locator + * @return parsed middle part + * @throw MediaException if middle part cannot + * be parsed from the locator + */ + public String getMiddlePart() throws MediaException + { + // Find possible parameter separator + int parSep = iLocator.indexOf(PARAMETER_SEPARATOR); + + // No parameters + if (parSep == -1) + { + parSep = iLocator.length(); + } + + return iLocator.substring(getProtocol().length() + + PROTOCOL_SEPARATOR.length(), parSep); + } + + /** + * Parses possible parameters of the locator e.g. returns + * "encoding=amr" from "capture://audio?encoding=amr" locator + * @return parsed parameters or null if there is + * not parameters + */ + public String getParameters() + { + // Find possible parameter separator + int parSep = iLocator.indexOf(PARAMETER_SEPARATOR); + + String locator = null; + + // Null is returned if there is no parameters + if (parSep != -1) + { + locator = iLocator.substring(parSep + 1); + } + + return locator; + } + + /** + * Returns the whole locator string + * @return locator used to create this instance + */ + public String getLocatorString() + { + return iLocator; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/MMAInvokeListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/MMAInvokeListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media; + +/** + * This interface is used notify other components when MMA event source is + * created. + */ +public interface MMAInvokeListener +{ + /** + * This method is called when MMA is invoked for the first time. + * @param aEventSourceHandle Handle to native MMA event source. + */ + void notifyInvoke(int aEventSourceHandle); +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/NativeError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/NativeError.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,247 @@ +/* +* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Landmark store manager for handling landmark stores + * +*/ + + +package com.nokia.microedition.media; + +import java.io.IOException; + +/** + * A utility class for declaring and handling native SymbianOS error codes. All + * error codes that are used in Java from native code should be declared here + * and referenced from this class. + */ +public final class NativeError +{ + public static final String NATIVE_ERROR_MESSAGE = "OS error = "; + + // SymbianOS error codes + public static final int KErrNone = 0; + + public static final int KErrNotFound = -1; + + public static final int KErrGeneral = -2; + + public static final int KErrCancel = -3; + + public static final int KErrNoMemory = -4; + + public static final int KErrNotSupported = -5; + + public static final int KErrArgument = -6; + + public static final int KErrOverflow = -9; + + public static final int KErrAlreadyExists = -11; + + public static final int KErrPathNotFound = -12; + + public static final int KErrDied = -13; + + public static final int KErrNotReady = -18; + + public static final int KErrCorrupt = -20; + + public static final int KErrAccessDenied = -21; + + public static final int KErrWrite = -23; + + public static final int KErrEof = -25; + + public static final int KErrDiskFull = -26; + + public static final int KErrBadName = -28; + + public static final int KErrCommsLineFail = -29; + + public static final int KErrTimedOut = -33; + + public static final int KErrDisconnected = -36; + + public static final int KErrTooBig = -40; + + public static final int KErrDivideByZero = -41; + + public static final int KErrHardwareNotAvailable = -44; + + // Not intended to be constructed + private NativeError() + { + } + + /** + * Checks for basic native error codes that map to standard Java exceptions + * and throws the exception if the error code matches. Otherwise throws an + * IOException. + * + * @param aError + * Possible error code. + * @return Value passed in is returned if not an error. + */ + public static int checkIO(int aError, + String aErrorMessage) throws IOException + { + if (aError < KErrNone) + { + switch (aError) + { + case KErrNoMemory: + throw new OutOfMemoryError(aErrorMessage + + Integer.toString(aError)); + // KErrArgument must throw IllegalArgumentException + // otherwise lcdui will break, so don't change this. + case KErrArgument: + throw new IllegalArgumentException(aErrorMessage + + Integer.toString(aError)); + case KErrDivideByZero: + throw new ArithmeticException(aErrorMessage + + Integer.toString(aError)); + default: + throw new IOException(aErrorMessage + errorMessage(aError)); + } + } + return aError; + } + + /** + * Checks for basic native error codes that map to standard Java exceptions + * and throws the exception if the error code matches. Otherwise throws + * basic Error class. + * + * @param aError + * Possible error code. + * @param aThrowAlways + * Determines whether a default exception is thrown if the error + * code is not recognised. + * @return Value passed in is returned if not an error. + * @throws Error + * If the error code does not match any exception thrown in + * checkExplicitOnly, a default exception is thrown here. + */ + public static int check(int aError, String aErrorMessage) + { + if (aError < KErrNone) + { + checkExplicitOnly(aError); + throw new Error(aErrorMessage + errorMessage(aError)); + } + return aError; + } + + + /** + * Checks if the object is a null reference, and throws OutOfMemoryError + * if this is the case. Useful for checking for OOM when Java objects + * returned from a native method. + * + * @param aObject Object that may be null. + * @return Value passed in is returned if not an error. + */ + public static Object checkOOM( Object aObject ) + { + if ( aObject == null ) + { + throw new OutOfMemoryError(); + } + return aObject; + } + + /** + * Checks if the error code represents out of memory, and throws Java Error + * if true. Does not throw anything otherwise. + * + * @param aError Possible error code. + * @return Value passed in is returned if not an out of memory error. + */ + public static int checkOOMOnly(int aError) + { + if (aError == KErrNoMemory) + { + throw new OutOfMemoryError(); + } + return aError; + } + + /** + * Checks for basic native error codes that map to standard Java + * exceptions and throws the exception if the error code matches. + * Otherwise throws basic Error class. + * + * @param aError Possible error code. + * @param aThrowAlways Determines whether a default exception is thrown + * if the error code is not recognised. + * @return Value passed in is returned if not an error. + * @throws Error If the error code does not match any exception thrown + * in checkExplicitOnly, a default exception is thrown here. + */ + public static int check(int aError) + { + if (aError < KErrNone) + { + checkExplicitOnly(aError); + throw new Error(errorMessage(aError)); + } + return aError; + } + + /** + * Checks for basic native error codes that map to standard Java + * exceptions and throws the exception if the error code matches. + * Otherwise just returns the error. + * + * @param aError Possible error code. + * @return Value passed in is returned if not an error. + * @throws OutOfMemoryError If aError equals KErrNoMemory. + * @throws IllegalArgumentException If aError equals KErrArgument + * @throws ArithmeticException If aError equals KErrDivideByZero + */ + public static int checkExplicitOnly( int aError ) + { + if ( aError < KErrNone ) + { + switch ( aError ) + { + case KErrNoMemory: + throw new OutOfMemoryError(); + // KErrArgument must throw IllegalArgumentException + // otherwise lcdui will break, so don't change this. + case KErrArgument: + throw new IllegalArgumentException(); + case KErrDivideByZero: + throw new ArithmeticException(); + default: + // Do nothing + } + } + return aError; + } + + /** + * Returns a string formatted with generic text to indicate where the error + * code comes from and the error code given. + * + * @param A + * native error code. + * @return A string containing the error code. + */ + public static String errorMessage(int aError) + { + String result = NATIVE_ERROR_MESSAGE.concat(Integer.toString(aError)); + return result; + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/NativePlayerFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/NativePlayerFactory.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,152 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.MediaException; +import javax.microedition.media.protocol.DataSource; + +/** + * Factory for creating native and java instances of the players + */ +public class NativePlayerFactory +{ + /** + * Do not allow contruction. + */ + private NativePlayerFactory() + { + } + + /** + * Creates native and java instances with Locator + * @param aLocator Locator used for creating native player + * @param aSource The DataSource that provides the media content. + * @return new instance of InternalPlayer + */ + public static InternalPlayer createPlayer(Locator aLocator, + DataSource aSource) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + int playerHandle = _createPlayerLocator(ManagerImpl.getEventSource(), + ManagerImpl.getHandle(), + aLocator.getProtocol(), + aLocator.getMiddlePart(), + aLocator.getParameters()); + return createPlayer(playerHandle, aSource); + } + + /** + * Creates native and java instances with Locator + * @param aLocator Locator used for creating native player + * @return new instance of InternalPlayer + */ + public static InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + return createPlayer(aLocator, null); + } + + /** + * Creates native and java instances with content-type + * @param aContentType Content type for creating native counter-part + * @param aSource The DataSource that provides the media content. + * @return new instance of InternalPlayer + */ + public static InternalPlayer createPlayer(String aContentType, + DataSource aSource) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + int playerHandle = _createPlayerContentType(ManagerImpl.getEventSource(), + ManagerImpl.getHandle(), + aContentType); + return createPlayer(playerHandle, aSource); + } + + /** + * Creates native and java instances with header data + * @param aHeaderData HeaderData used for recognizing content + * @param aSource The DataSource that provides the media content. + * @return new instance of InternalPlayer + */ + public static InternalPlayer createPlayer(byte[] aHeaderData, + DataSource aSource) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + int playerHandle = _createPlayerHeaderData(ManagerImpl.getEventSource(), + ManagerImpl.getHandle(), + aHeaderData); + return createPlayer(playerHandle, aSource); + } + + /** + * Creates java instance from native handle and DataSource + */ + private static InternalPlayer createPlayer(int aPlayerHandle, + DataSource aSource) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + // if aPlayerHandle is 0 null will be returned + InternalPlayer player = null; + + if (aPlayerHandle < 0) + { + // negative handle indicates native error code + throw new MediaException( + "Could not create player, Symbian OS error: " + + aPlayerHandle); + } + else if (aPlayerHandle > 0) + { + // Native player was created + if (aSource == null) + { + player = new PlayerImpl(aPlayerHandle); + } + else + { + player = new SourcePlayer(aSource, aPlayerHandle); + } + } + return player; + } + + private static native int _createPlayerLocator(int aEventSource, + int aManagerHandle, + String aProtocol, + String aMiddlePart, + String aParameters); + + private static native int _createPlayerContentType(int aEventSource, + int aManagerHandle, + String aContentType); + + private static native int _createPlayerHeaderData(int aEventSource, + int aManagerHandle, + byte[] aHeaderData); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerBase.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerBase.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,284 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is general player implementation of Player interface +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.TimeBase; +import javax.microedition.media.MediaException; +import javax.microedition.media.Manager; +import com.nokia.mj.impl.utils.Logger; + +/** + * This abstract player implementation must be derived. This class implements + * general player functionality such as state checking. + */ +public abstract class PlayerBase implements InternalPlayer +{ + protected TimeBase iTimeBase; + + // state as defined in Player interface + // at first player is unrealized + protected int iState = UNREALIZED; + + /** + * Constructor + */ + protected PlayerBase() + { + } + + /** + * Every method has to check if player is closed with this method + */ + protected void closeCheck() + { + if (iState == CLOSED) + { + throw new IllegalStateException("Player is CLOSED."); + } + } + + /** + * This method is from methods that are + * not allowed to be called, when player + * is in UNREALIZED state + */ + protected void unrealizedCheck() + { + if (getState() == UNREALIZED) + { + throw new IllegalStateException("Player is UNREALIZED."); + } + } + + /** + * From Player + * @see Player + */ + public TimeBase getTimeBase() + { + closeCheck(); + unrealizedCheck(); + + // set default timebase + if (iTimeBase==null) + { + iTimeBase = Manager.getSystemTimeBase(); + } + + return iTimeBase; + } + + /** + * From Player + * @see Player + */ + public void setTimeBase(TimeBase aMaster) throws MediaException + { + closeCheck(); + unrealizedCheck(); + + // A MediaException is thrown if + // setTimeBase is called on a STARTED Player. + if (getState() == STARTED) + { + throw new IllegalStateException("Player is STARTED"); + } + + if (aMaster == null) + { + // set default timebase + iTimeBase = Manager.getSystemTimeBase(); + } + else + { + if (aMaster instanceof SystemTimeBase) + { + iTimeBase = aMaster; + return; + } + else + { + // default doesn't support any other TimeBases + throw new MediaException("Invalid timebase or timebase not supported"); + } + } + } + + /** + * From Player + * @see Player + */ + public void realize() throws MediaException + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"+ PlayerBase.realize() "); + closeCheck(); + int state = getState(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"+ PlayerBase.realize() after getstate() "); + + // If realize is called when the Player is in the + // REALIZED, PREFETCHTED or STARTED state, + // the request will be ignored. + if (state == UNREALIZED) + { + doRealize(); + } + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"- PlayerBase.realize() "); + } + + /** + * Called from realize method. This method must be implemented in + * derived class. + * @see realize + */ + abstract protected void doRealize() throws MediaException; + + /** + * From Player + * @see Player + */ + public void prefetch() throws MediaException + { + realize(); + + // prefetch must be ignored in other states + if (getState() == REALIZED) + { + doPrefetch(); + } + } + + /** + * Called from prefetch method. + * @see prefetch + */ + abstract protected void doPrefetch() throws MediaException; + + /** + * interface Player + * @see Player + */ + public void deallocate() + { + try + { + stop(); + } + catch (MediaException me) + { + // if stop fails we can do nothing + Logger.ELOG(Logger.EJavaMMAPI, + "MMA::PlayerBase: Stop failed in deallocate.", me); + } + if (getState() == PREFETCHED) + { + doDeallocate(); + } + } + + /** + * Called from deallocate method. + */ + abstract protected void doDeallocate(); + + /** + * interface Player + * @see Player + */ + public void stop() throws MediaException + { + closeCheck(); + if (getState() == STARTED) + { + doStop(); + } + } + + /** + * Called from realize method. + */ + abstract protected void doStop() throws MediaException; + + /** + * interface Player + * @see Player + */ + public void close() + { + /* + Releases all resources and cease all activity. + The close method indicates that the Player will no + longer be used and can shut itself down. + Methods invoked on a closed Player will throw RuntimeExceptions. + */ + if (iState != CLOSED) + { + deallocate(); + iState = CLOSED; + doClose(); + } + } + + /** + * Called from close method. + */ + abstract protected void doClose(); + + /** + * interface Player. + * Derived classes may use this method to check parameter and state. + * @see Player + */ + public void setLoopCount(int aCount) + { + closeCheck(); + // -1 is valid count value meaning indefinitely looping + if ((aCount == 0) || + (aCount < -1)) + { + throw new java.lang.IllegalArgumentException( + "Invalid loop count " + aCount + ", loop count cannot be 0 or < -1"); + } + if (getState() == STARTED) + { + throw new IllegalStateException("Player is STARTED"); + } + } + + /** + * interface Player + * @see Player + */ + public long setMediaTime(long aNow) throws MediaException + { + closeCheck(); + unrealizedCheck(); + + long now = aNow; + + if (now < 0) + { + // Setting the media time to negative values + // will effectively set the media time to zero. + now = 0; + } + return now; + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,487 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is native player implementation of Player interface +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.PlayerListener; +import javax.microedition.media.MediaException; +import com.nokia.microedition.media.NativeError; +import com.nokia.mj.impl.rt.support.Finalizer; +import com.nokia.mj.impl.utils.Logger; + +public class PlayerImpl extends PlayerBase +{ + // CMMAPlayer handle + protected int iPlayerHandle; + + // Controls container + protected ControlContainer iControls; + + // object for waiting native asynchronous method calls + protected Object iLockObject = new Object(); + protected Object iPrefetchLockObject = new Object(); + + // native error code + protected int iError; + + protected PlayerListenerImpl iPlayerListenerImpl; + + private Finalizer mFinalizer; + + private boolean iWaitFlag = true; + + private boolean iStartWaitFlag = true; + + /** + * Constructor + * @param aPlayerHandle handle to player (CMMAPlayer) + */ + public PlayerImpl(int aPlayerHandle) + { + iPlayerHandle = aPlayerHandle; + + iPlayerListenerImpl = new PlayerListenerImpl(this); + + // Initialize player + int err = _initPlayer(iPlayerListenerImpl, + ManagerImpl.getEventSource(), + iPlayerHandle); + if (err < NativeError.KErrNone) + { + throw new OutOfMemoryError(NativeError.errorMessage(err)); + } + + mFinalizer = new Finalizer() + { + public void finalizeImpl() + { + doFinalize(); + } + }; + + iControls = ControlContainer.populateControls(this, + ManagerImpl.getEventSource(), + iPlayerHandle); + } + + private void doFinalize() + { + if (mFinalizer != null) + { + registeredFinalize(); + mFinalizer = null; + } + } + + /** + * This method is called when garbage collection occurs + * to delete native object + */ + protected void registeredFinalize() + { + close(); + } + + /** + * Returns native player handle. + * @return Native player handle. + */ + public int getPlayerHandle() + { + return iPlayerHandle; + } + + /** + * @return Player's PlayerListenerImpl + */ + public PlayerListenerImpl getPlayerListenerImpl() + { + return iPlayerListenerImpl; + } + + /** + * Adds control to the player. + * @param aControl Player's control + * @param aControlName Identifies the control. Name must contain + * full package information + */ + public void addControl(javax.microedition.media.Control aControl, + String aControlName) + { + iControls.addControl(aControl, aControlName); + } + + /** + * interface Controllable + * Return controls + * @return list of controls + * @see Controllable + */ + public javax.microedition.media.Control[] getControls() + { + closeCheck(); + unrealizedCheck(); + return iControls.getControls(); + } + + /** + * interface Controllable + * get control by content type + * @param aControlType content type of wanted control + * @return control + * @see Controllable + * @see Control + */ + public javax.microedition.media.Control getControl(String aControlType) + { + closeCheck(); + unrealizedCheck(); + return iControls.getControl(aControlType); + } + + /** + * interface Player + * @see Player + */ + public void addPlayerListener(PlayerListener aPlayerListener) + { + closeCheck(); + iPlayerListenerImpl.addPlayerListener(aPlayerListener); + } + + /** + * From Player + * @see Player + */ + public void removePlayerListener(PlayerListener aPlayerListener) + { + closeCheck(); + iPlayerListenerImpl.removePlayerListener(aPlayerListener); + } + + /** + * From Player + * @see Player + */ + public int getState() + { + int state = CLOSED; + if (iState != CLOSED) + { + state = _getState(ManagerImpl.getEventSource(), iPlayerHandle); + } + return state; + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doRealize() throws MediaException + { + int err = _realize(ManagerImpl.getEventSource(), iPlayerHandle); + + if (err < NativeError.KErrNone) + { + throw new MediaException( + "Realize failed, Symbian OS error: " + err); + } + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doPrefetch() throws MediaException + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doPrefetch"); + synchronized(iPrefetchLockObject) + { + if (PREFETCHED == getState()) + return; + synchronized (iLockObject) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doPrefetch inside try"+Thread.currentThread().getName()); + //int retval[] = new int[1]; + int err = _prefetch(ManagerImpl.getEventSource(), iPlayerHandle); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doPrefetch err = " + err); + if (err < NativeError.KErrNone) + { + throw new MediaException( + "Prefetch failed, Symbian OS error: " + err); + } + if(iWaitFlag) + { + try + { + // wait until actionCompleted( int aError ) is called + iLockObject.wait(); + } + catch (InterruptedException ie) + { + // cannot occur + } + } + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doPrefetch Sync end"); + } // end synchronized (iLockObject) + } + if (iError < NativeError.KErrNone) + { + throw new MediaException( + "Prefetch failed, Symbian OS error: " + iError); + } + } + + /** + * Notify that action is completed. Called from native side. + * @param aError error code + */ + private void actionCompleted(int aError) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"actionCompleted callback11 aError ="+ aError + " "+Thread.currentThread().getName()); + iError = aError; + + synchronized (iLockObject) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"actionCompleted callback inside synchronized (iLockObject)"); + iLockObject.notify(); + } + } + + private void actionCompletedFile() + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : actionCompletedFile"); + iWaitFlag = false; + + } + + private void actionCompletedStart() + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : actionCompletedStart"); + iStartWaitFlag = false; + + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doDeallocate() + { + int ret = _deallocate(ManagerImpl.getEventSource(), iPlayerHandle); + if (ret < NativeError.KErrNone) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo, + "_deallocate() failed: err=" + ret); + } + } + + /** + * From Player. + * @see Player + */ + public void start() throws MediaException + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : start()"); + prefetch(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl, start, state = "+getState()); + // Only preteched player may be started. If player is already started + // this method returns silently. + if (getState() == PREFETCHED) + { + synchronized (iLockObject) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl, before calling native _start() thread is =" +Thread.currentThread().getName()); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl, before calling native _start()"); + int err = _start(ManagerImpl.getEventSource(), iPlayerHandle); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl, before calling native _start( ) returned : err = "+err); + if (err < NativeError.KErrNone) + { + throw new MediaException( + "Start failed, Symbian OS error: " + err); + } + if (iError < NativeError.KErrNone) + { + throw new MediaException( + "Start failed, Symbian OS error: " + iError); + } + if(iStartWaitFlag) + { + try + { + // wait until actionCompleted( int aError ) is called + iLockObject.wait(); // only for tck run + } + catch (InterruptedException ie) + { + // cannot occur + } + + } + } + } + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doStop() throws MediaException + { + /* + Stops the Player. It will pause the playback at the current media time. + Calling start will resume the playback from where it is stopped. + If stop is called on a stopped Player, the request is ignored. + */ + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doStop()"); + int err = _stop(ManagerImpl.getEventSource(), iPlayerHandle); + if (err < NativeError.KErrNone) + { + throw new MediaException( + "Stop failed, Symbian OS error: " + err); + } + // After this request is completed, + // the Player is in the PREFETCHED state. + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doClose() + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doclose() 1"); + _close(ManagerImpl.getEventSource(), iPlayerHandle); + + if (iPlayerHandle > NativeError.KErrNone) // construction has succeed + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doclose() 2"); + // notify the controls + iControls.dispose(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doclose() 3"); + + // delete the native object + _dispose(ManagerImpl.getEventSource(), iPlayerHandle); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerImpl.java : doclose() 4"); + iPlayerHandle = 0; // Do not use native object anymore + } + } + /** + * interface Player + * @see Player + */ + public void setLoopCount(int aCount) + { + super.setLoopCount(aCount); + _setLoopCount(ManagerImpl.getEventSource(), iPlayerHandle, aCount); + } + + /** + * interface Player + * @see Player + */ + public long getDuration() + { + closeCheck(); + long duration = _duration(ManagerImpl.getEventSource(), iPlayerHandle); + if (duration < NativeError.KErrNone) + { + duration = TIME_UNKNOWN; + } + return duration; + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public long setMediaTime(long aNow) throws MediaException + { + long time = _setMediaTime(ManagerImpl.getEventSource(), + iPlayerHandle, + super.setMediaTime(aNow)); + if (time < NativeError.KErrNone) + { + throw new MediaException( + "Could not set media time, Symbian OS error: " + time); + } + return time; + } + + /** + * interface Player + * @see Player + */ + public long getMediaTime() + { + closeCheck(); + long time = _getMediaTime(ManagerImpl.getEventSource(), iPlayerHandle); + if (time < NativeError.KErrNone) + { + time = TIME_UNKNOWN; + } + return time; + } + + + /** + * interface Player + * @see Player + */ + public String getContentType() + { + closeCheck(); + unrealizedCheck(); + + return _getContentType(iPlayerHandle); + } + + // JNI + private native int _initPlayer(Object aPlayerListenerObject, + int aEventSource, + int aPlayerHandle); + + private static native int _start(int aEventPoster, int aPlayer); + private static native int _stop(int aEventPoster, int aPlayer); + private static native int _close(int aEventPoster, int aPlayer); + private static native int _prefetch(int aEventPoster, int aPlayer); + + private static native int _setLoopCount(int aEventPoster, int aPlayer, + int aLoopCount); + + private static native int _realize(int aEventPoster, int aPlayer); + private static native long _duration(int aEventPoster, int aPlayer); + private static native long _setMediaTime(int aEventPoster, int aPlayer, + long aNow); + + private static native int _deallocate(int aEventPoster, int aPlayer); + private static native long _getMediaTime(int aEventPoster, int aPlayer); + private static native int _getState(int aEventPoster, int aPlayer); + + protected static native int _addSourceStream(int aEventPoster, + int aPlayerHandle, + Object aSourceStreamReader); + + private static native String _getContentType(int aPlayerHandle); + + private static native void _dispose(int aEventSourceHandle, + int aObjectHandle); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerListenerImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlayerListenerImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,266 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is player listener implementation +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.Player; +import javax.microedition.media.PlayerListener; +import javax.microedition.media.Control; +import javax.microedition.media.control.VideoControl; +import java.util.Vector; +import java.util.Enumeration; +//import com.symbian.midp.runtime.MIDletExecutor; +//import com.symbian.midp.runtime.MIDletInstance; +import com.nokia.mj.impl.utils.Logger; + + +public class PlayerListenerImpl +{ + // PlayerListener event types that come from native side + protected static final int E_STARTED = 0; + protected static final int E_STOPPED = 1; + protected static final int E_STOPPED_AT_TIME = 2; + protected static final int E_END_OF_MEDIA = 3; + protected static final int E_DURATION_UPDATED = 4; + protected static final int E_AUDIO_DEVICE_UNAVAILABLE = 5; + protected static final int E_VOLUME_CHANGED = 6; + protected static final int E_SIZE_CHANGED = 7; + protected static final int E_ERROR = 8; + protected static final int E_CLOSED = 9; + protected static final int E_RECORD_STARTED = 10; + protected static final int E_RECORD_STOPPED = 11; + protected static final int E_PRIVATE_DATA_AVAILABLE = 12; + protected static final int E_PRIVATE_DATA_OVERWRITTEN = 13; + protected static final int E_BUFFERING_STARTED = 14; + protected static final int E_BUFFERING_STOPPED = 15; + protected static final int E_RECORD_ERROR = 16; + // For global volume info + protected static final int E_NOKIA_EXTERNAL_VOLUME_EVENT = 17; + // for Audio Routing preferences change + protected static final int E_AUDIO_ROUTING_PREFERENCE_CHANGED_EVENT = 18; + + private static final String KVideoControlClassName = + "javax.microedition.media.control.VideoControl"; + + // maps int event types to String event types + private static Vector sEventTypes; + + static + { + sEventTypes = new Vector(19); // there's 17 event types + 1 global volume event + 1 Audio Routing Preference Change Event + sEventTypes.addElement(PlayerListener.STARTED); // E_STARTED + sEventTypes.addElement(PlayerListener.STOPPED); // E_STOPPED + sEventTypes.addElement(PlayerListener.STOPPED_AT_TIME); // E_STOPPED_AT_TIME + sEventTypes.addElement(PlayerListener.END_OF_MEDIA); // E_END_OF_MEDIA + sEventTypes.addElement(PlayerListener.DURATION_UPDATED); // E_DURATION_UPDATED + sEventTypes.addElement(PlayerListener.DEVICE_UNAVAILABLE); // E_AUDIO_DEVICE_UNAVAILABLE + sEventTypes.addElement(PlayerListener.VOLUME_CHANGED); // E_VOLUME_CHANGED + sEventTypes.addElement(PlayerListener.SIZE_CHANGED); // E_SIZE_CHANGED + sEventTypes.addElement(PlayerListener.ERROR); // E_ERROR + sEventTypes.addElement(PlayerListener.CLOSED); // E_CLOSED + sEventTypes.addElement(PlayerListener.RECORD_STARTED); // E_RECORD_STARTED + sEventTypes.addElement(PlayerListener.RECORD_STOPPED); // E_RECORD_STOPPED + sEventTypes.addElement(null); // E_PRIVATE_DATA_AVAILABLE + sEventTypes.addElement(null); // E_PRIVATE_DATA_OVERWRITTEN + sEventTypes.addElement(PlayerListener.BUFFERING_STARTED); // E_BUFFERING_STARTED + sEventTypes.addElement(PlayerListener.BUFFERING_STOPPED); // E_BUFFERING_STOPPED + sEventTypes.addElement(PlayerListener.RECORD_ERROR); // E_RECORD_ERROR + sEventTypes.addElement("com.nokia.external.volume.event"); // E_NOKIA_EXTERNAL_VOLUME_EVENT + sEventTypes.addElement("com.nokia.audiooutputchange.event"); // E_AUDIO_ROUTING_PREFERENCE_CHANGED_EVENT + } + + private Vector iPlayerListeners = new Vector(); + private Player iPlayer; + + /** + * Constructor + * @param aPlayer Handle to player + */ + public PlayerListenerImpl(Player aPlayer) + { + iPlayer = aPlayer; + } + + /** + * Adds PlayerListener + * @param aPlayerListener Listener that will be added + * @see PlayerListener + */ + public synchronized void addPlayerListener(PlayerListener aPlayerListener) + { + if (aPlayerListener == null) + { + return; + } + if (!iPlayerListeners.contains(aPlayerListener)) + { + iPlayerListeners.addElement(aPlayerListener); + } + } + + + /** + * Removes PlayerListener + * @param aPlayerListener Listener that will be removed + * @see PlayerListener + */ + public synchronized void removePlayerListener(PlayerListener aPlayerListener) + { + iPlayerListeners.removeElement(aPlayerListener); + } + + /** + * Deliveres event to all registered PlayerListeners + * @param aEventType type defined in PlayerListener + * @param aEventData data for event + */ + public synchronized void postEvent(String aEventType, Object aEventData) + { + Enumeration listeners = iPlayerListeners.elements(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerListenerImpl.java::PostEvent" + listeners); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlayerListenerImpl.java::PostEvent" + aEventType + aEventData ); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"PlaerListenerImpl.java::PostEvent, this = "+this +" iPlayerListeners = "+iPlayerListeners); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Listeners count = "+iPlayerListeners.size()); + while (listeners.hasMoreElements()) + { + PlayerListener listener = (PlayerListener)listeners.nextElement(); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"listener = "+listener); + + CallBackThread obj = new CallBackThread(aEventType,aEventData,listener,iPlayer); + Thread t = new Thread(obj); + t.start(); + } + } + + /** + * Posts a long event. Called from native implementation. + * @param aEventType Event type + * @param aEventData Event data + */ + private void postLongEvent(int aEventType, long aEventData) + { + // event has come after this has been gc'd + if (this == null) + { + return; + } + Long eventData = new Long(aEventData); + postEvent(getEventType(aEventType), eventData); + } + + /** + * Posts a string event. Called from native implementation. + * @param aEventType Event type + * @param aEventData Event data + */ + private void postStringEvent(int aEventType, String aEventData) + { + // event has come after this has been gc'd + if (this == null) + { + return; + } + if (aEventType == E_SIZE_CHANGED) + { + VideoControl vc = (VideoControl)iPlayer.getControl(KVideoControlClassName); + postEvent(getEventType(aEventType), vc); + } + else + { + postEvent(getEventType(aEventType), aEventData); + } + } + + /** + * Posts object event. Called from native implementation. + * @param aEventType Event type + * @param aEventData Event data + */ + private void postObjectEvent(int aEventType, Object aEventData) + { + // event has come after this has been gc'd + if (this == null) + { + return; + } + postEvent(getEventType(aEventType), aEventData); + } + + /** + * Posts a control event. Called from native implementation. + * @param aEventType Event type + * @param aEventData Event data + */ + private void postControlEvent(int aEventType, String aEventData) + { + // event has come after this has been gc'd + if (this == null) + { + return; + } + Control eventData = iPlayer.getControl(aEventData); + postEvent(getEventType(aEventType), eventData); + } + + /** + * Converts int eventType to String eventType + * @param aEventType event type to be converted + * @return converted event type + */ + private String getEventType(int aEventType) + { + String eventType = null; + eventType = (String)sEventTypes.elementAt(aEventType); + return eventType; + } + + class CallBackThread extends Thread + { + private String iEventType; + private Object iEventData; + private PlayerListener iListener; + private Player iPlayer; + + public CallBackThread(String aEventType, Object aEventData, PlayerListener aListener, Player aPlayer) + { + iEventType = aEventType; + iEventData = aEventData; + iListener = aListener; + iPlayer = aPlayer; + + + } + + public void doCallBack() + { + + + } + public void run() + { + iListener.playerUpdate(iPlayer, + iEventType, + iEventData); + + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"after calling midlet playerupdate"); + + + } + + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlugIn.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/PlugIn.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,121 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: PlugIn used to extend mma +* +*/ + + +package com.nokia.microedition.media; + +import java.io.IOException; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.MediaException; + +/** + * This interface can be used extend Mobile Media API. This interface must + * be registered to ManagerImpl with addPlugIn + * method. ManagerImpl instance can be obtained with + * ManagerImpl.getInstance method. + * getSupportedContentTypes and getSupportedProtocols + * methods will be called when equivalent Manager methods are called. + * + * @see ManagerImpl.addPlugin + */ +public interface PlugIn +{ + /** + * Return the list of supported content types for the given protocol. + *

            + * See content types for the syntax + * of the content types returned. + * See protocol name for the syntax + * of the protocol used. + *

            + * For example, if the given protocol + * is "http", + * then the supported content types that can be played back + * with the http protocol will be returned. + *

            + * If null is passed in as the protocol, + * all the supported content types for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given protocol is an invalid or + * unsupported protocol, then an empty array will be returned. + * + * @param aProtocol The input protocol for the supported content types. + * @return The list of supported content types for the given protocol. + */ + String[] getSupportedContentTypes(String aProtocol); + + /** + * Return the list of supported protocols given the content + * type. The protocols are returned + * as strings which identify what locators can be used for creating + * Player's. + *

            + * See protocol name for the syntax + * of the protocols returned. + * See content types for the syntax + * of the content type used. + *

            + * For example, if the given content_type + * is "audio/x-wav", then the supported protocols + * that can be used to play back audio/x-wav + * will be returned. + *

            + * If null is passed in as the + * content_type, + * all the supported protocols for this implementation + * will be returned. The returned array must be non-empty. + *

            + * If the given content_type is an invalid or + * unsupported content type, then an empty array will be returned. + * + * @param aContentType The content type for the supported protocols. + * @return The list of supported protocols for the given content type. + */ + String[] getSupportedProtocols(String aContentType); + + /** + * Create a Player for a DataSource. + * This method will be called if MMA was not able to create + * Player for the DataSource. + * + * @param aDataSource The DataSource that provides + * the media content. + * @return A new Player. + * @exception IllegalArgumentException Thrown if source + * is null. + * @exception MediaException Thrown if a Player cannot + * be created for the given DataSource. + * @exception IOException Thrown if there was a problem connecting + * with the source. + * @exception SecurityException Thrown if the caller does not + * have security permission to create the Player. + */ + InternalPlayer createPlayer(DataSource aDataSource) + throws MediaException, IOException; + + /** + * Method used to prepare player. This method is used only for + * MMA internal extensions. If PlugIn does not support given player + * this method must not do anything. + * + * @param aPlayer Player to prepare. + * @exception MediaException Thrown if a InternalPlayer cannot + * be prepared. + */ + void preparePlayer(InternalPlayer aPlayer) throws MediaException; +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SeekControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SeekControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Interface to seek stream. +* +*/ + +package com.nokia.microedition.media; + +import java.io.IOException; +import javax.microedition.media.Control; + +/** + * Interface to seek stream to wanted position. + */ +public interface SeekControl extends Control +{ + /** + * Seeks stream to wanted position. + * @param aWhere position in the stream. + * @throw IOException Thrown if an I/O error occurs. + */ + void seek(int aWhere) throws IOException; + + /** + * Close controlled stream. + */ + void close(); +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/Setup.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/Setup.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,90 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class setup MMA plugins. +* +*/ + + +package com.nokia.microedition.media; + +import com.nokia.mj.impl.utils.Logger; + +/** + * Class used to setup external components. + */ +public class Setup +{ + // Class names used to invoke external components. + private static final String[] MMA_PLUGINS = + { + //"com.nokia.amms.MMAInvokeListenerImpl" + }; + + /** + * Private constructor not to allow construction. + */ + private Setup() + { + } + + /** + * Setup external components. + * @param aEventSourceHandle Native handle MMA event source. + */ + public static void setup(int aEventSourceHandle) + { + // Go through all plugins + for (int i = 0; i < MMA_PLUGINS.length; i++) + { + invokeComponent(aEventSourceHandle, MMA_PLUGINS[ i ]); + } + } + + /** + * Invokes other component. This method returns without creating the + * components if the class is not found. + * + * @param aEventSourceHandle Handle to native mma event source. + * @param aClassName Full class name to create. Class must have public + * default constructor and implement MMAInvokeListener interface. + * @throws OutOfMemoryError if component cannot be created. + */ + private static void invokeComponent(int aEventSourceHandle, String aClassName) + { + try + { + Class invokerClass = + Class.forName(aClassName); + MMAInvokeListener invoker = + (MMAInvokeListener)invokerClass.newInstance(); + invoker.notifyInvoke(aEventSourceHandle); + } + catch (InstantiationException ie) + { + throw new OutOfMemoryError("Instantiation failed, " + ie.toString()); + } + catch (IllegalAccessException iae) + { + throw new OutOfMemoryError("Illegal access, " + iae.toString()); + } + catch (ClassNotFoundException cnfe) + { + // If invoker class cannot be found, plugin is not added to J2ME + // build and MMA is used without it. + Logger.ELOG(Logger.EJavaMMAPI, "MMA::Setup:: ", cnfe); + } + } +} +// End of File + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SourcePlayer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SourcePlayer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,128 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is player with DataSource +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.protocol.SourceStream; +import javax.microedition.media.MediaException; +import java.io.IOException; +import com.nokia.microedition.media.protocol.SourceStreamReader; +import com.nokia.mj.impl.utils.Logger; +/** + * This class add to PlayerImpl DataSource handling. + */ +public class SourcePlayer extends PlayerImpl +{ + // + protected DataSource iDataSource; + + // Used to SourceStream to native side + protected SourceStreamReader iSourceStreamReader; + + /** + * Constructor + * @param aDataSource Handle to DataSource + * @param aPlayerHandle handle to player (CMMAPlayer) + */ + public SourcePlayer(DataSource aDataSource, + int aPlayerHandle) throws MediaException + { + super(aPlayerHandle); + iDataSource = aDataSource; + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"SourcePlayer player handle = " + aPlayerHandle); + // Create reader for the stream + iSourceStreamReader = new SourceStreamReader( + aDataSource.getStreams()[ 0 ], + aDataSource, // Controllable object + ManagerImpl.getEventSource(), + aPlayerHandle); + + // Create SourceStreamReader in native side + int nativeHandle = _addSourceStream(ManagerImpl.getEventSource(), + iPlayerHandle, + iSourceStreamReader); + + // Failed to create a native-side CMMASourceStream + if (nativeHandle <= 0) + { + throw new MediaException("Could not create Player, Symbian OS error: " + + nativeHandle); + } + + // Assing java object to corresponding native object + iSourceStreamReader.setHandle(nativeHandle); + } + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doPrefetch() throws MediaException + { + // DataSource connect must reset its SourceStream if DataSource is + // disconnected. + try + { + iDataSource.connect(); + } + catch (IOException ioe) + { + throw new MediaException("IOException occurred, " + ioe.getMessage()); + } + + super.doPrefetch(); + } + + /** + * interface PlayerImpl + * @see PlayerImpl + */ + public void doDeallocate() + { + if (iDataSource.getStreams()[ 0 ].getSeekType() == + SourceStream.NOT_SEEKABLE) + { + // if stream is not seekable we have to disconnect the whole source + // and re-connect it if prefetch is called + iDataSource.disconnect(); + } + else + { + // stream is RANDOM_ACCESSIBLE or SEEKABLE_TO_START and can be + // seeked to beginning of the stream + iSourceStreamReader.resetStream(); + } + + super.doDeallocate(); + } + + /** + * interface Player + * @see Player + */ + public void close() + { + super.close(); + // close threads from SourceStreamReaders + iSourceStreamReader.close(); + iDataSource.disconnect(); + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SystemTimeBase.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/SystemTimeBase.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements TimeBase +* +*/ + + +package com.nokia.microedition.media; + +import javax.microedition.media.TimeBase; + +public class SystemTimeBase implements TimeBase +{ + + /** + * Constructor + */ + public SystemTimeBase() + { + } + + /** + * From TimeBase interface + * @return current time + */ + public long getTime() + { + return System.currentTimeMillis(); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/AnimationPlayer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/AnimationPlayer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,592 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Hashtable; + +import javax.microedition.media.Control; +import javax.microedition.media.MediaException; +import javax.microedition.media.PlayerListener; +import javax.microedition.media.protocol.DataSource; + +import org.eclipse.ercp.swt.mobile.MobileShell; +import org.eclipse.swt.SWTException; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import com.nokia.microedition.media.BufferDataSource; +import com.nokia.microedition.media.InputStreamDataSource; +import com.nokia.microedition.media.InputStreamSourceStream; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.PlayerBase; +import com.nokia.microedition.media.PlayerListenerImpl; + +/** + * @author d35kumar + * + */ +public class AnimationPlayer extends PlayerBase { + // GIF image information, array length will be equal to the number of frames in image + protected ImageData [] iImageData; + // number of times we need to repeat the animation + // by default it's value is one + private int iTotalLoopCount=1; + // this holds all control related to this player + Hashtable iControls= new Hashtable(); + // Current frame index of the Animation file + private int iFrameindex; + // Current Loop Count + private int iCurrentLoopCount; + // Display object of the eSWT API, creating this object will integrate the current java code with eSWT API. + Display iDisplay; + // Control object of ESWT API, return from LCDUIInvoker. + org.eclipse.swt.widgets.Control iControl; + // Constants used everywhere to compare the string + private static final String ANIMATION_CONTENT_TYPE = "image/gif"; + + private final String fVideoControl=VideoControl.class.getName(); + private final String fFramePositioningControl=FramePositioningControl.class.getName(); + private final String fStopTimeControl=StopTimeControl.class.getName(); + private final String fRateControl=RateControl.class.getName(); + /** + * Default control package. Used when getting control with + * getControl method which appends default control package if package is + * not specified. + */ + static final String CONTROL_DEFAULT_PACKAGE = + "javax.microedition.media.control."; + + //For Player listener + protected PlayerListenerImpl iPlayerListenerImpl; + //Image to be displayed, again object of eSWT API. + protected Image iImage; + // Actual dimension of the image, this should be initialized while creating the player + // as user can change the size of the image later, in that case too, getSourceheight and getSourceWidth + // of VideoControl should return the actual width and height of the image + Point iSourceDimension; + long iMediaTime; + + // Display Location, of the image + private Point iDisplayLocation= new Point(0,0); + + + /** + * + * @param ds DataSource which contains the data to be displayed + */ + public AnimationPlayer(DataSource ds){ + final String DEBUG_STR="AnimationPlayer::AnimationPlayer(DataSource)"; + System.out.println(DEBUG_STR+"+"); + iPlayerListenerImpl= new PlayerListenerImpl(this); + //TODO check if we can do it in better way + // this is temporary solution + // for this I have written two functions getDataSource and getInputStream function + BufferDataSource bds =(BufferDataSource )ds; + InputStreamDataSource isds=(InputStreamDataSource)bds.getDataSource(); + InputStreamSourceStream isss=(InputStreamSourceStream )isds.getStreams()[0]; + InputStream is = isss.getInputStream(); + + if(is!=null){ + ImageLoader imageLoader= new ImageLoader(); + iImageData=imageLoader.load(is); + //iRepeatCount=imageLoader.repeatCount; + iSourceDimension= new Point(imageLoader.logicalScreenWidth, imageLoader.logicalScreenHeight); + } + pupulateControl(); + System.out.println(DEBUG_STR+"-"); + } + + /** + * + * @param locator + * @throws SWTException + */ + public AnimationPlayer(String locator) throws SWTException{ + final String DEBUG_STR="AnimationPlayer::AnimationPlayer(Locator )"; + System.out.println(DEBUG_STR+"+"); + ImageLoader imageLoader= new ImageLoader(); + System.out.println(DEBUG_STR+"Locator string is "+locator); + // Following line may throw SWTException + iImageData=imageLoader.load(locator); + //iRepeatCount=imageLoader.repeatCount; + iSourceDimension= new Point(imageLoader.logicalScreenWidth, imageLoader.logicalScreenHeight); + pupulateControl(); + System.out.println(DEBUG_STR+"-"); + } + + /** + * Moved the player to close state and releases all resources, called from PlayerBase class + */ + protected void doClose() { + final String DEBUG_STR="AnimationPlayer::doClose()"; + System.out.println(DEBUG_STR+"+"); + iState=CLOSED; + iPlayerListenerImpl.postEvent(PlayerListener.CLOSED, null); + System.out.println(DEBUG_STR+"-"); + } + + protected void doDeallocate() { + // what to do here, nullify image data and display etc??? + } + + protected void doPrefetch() throws MediaException { + final String DEBUG_STR="AnimationPlayer::doPrefetch()"; + System.out.println(DEBUG_STR+"+"); + iState=PREFETCHED; + System.out.println(DEBUG_STR+"-"); + } + + protected void doRealize() throws MediaException { + final String DEBUG_STR="AnimationPlayer::doRealize()"; + System.out.println(DEBUG_STR+"+"); + iState=REALIZED; + // this is temporary solution implement it in proper way + iImage=new Image(iDisplay, iImageData[0]); + System.out.println(DEBUG_STR+"-"); + } + + protected void doStop() throws MediaException { + final String DEBUG_STR="AnimationPlayer::doStop()"; + System.out.println(DEBUG_STR+"+"); + // since after stopping the player the player state will move to pre-fetched state + iState=PREFETCHED; + iPlayerListenerImpl.postEvent(PlayerListener.STOPPED, new Long(iMediaTime * 10000)); + System.out.println(DEBUG_STR+"-"); + } + + public void addControl(Control aControl, String aControlType) + throws MediaException { + iControls.put(aControlType, aControl); + } + + public void addPlayerListener(PlayerListener aPlayerListener) { + closeCheck(); + iPlayerListenerImpl.addPlayerListener(aPlayerListener); + } + + /** + * Returns the Content type("image/GIF") supported for by this player, + */ + public String getContentType() { + closeCheck(); + unrealizedCheck(); + return ANIMATION_CONTENT_TYPE; + } + + /** + * This function will return, total time in microseconds this player can be played + */ + public long getDuration() { + closeCheck(); + long time = TIME_UNKNOWN; + int totalNoOfFrames = iImageData.length; + for (int i = 0; i < totalNoOfFrames; i++) { + time += iImageData[i].delayTime; + } + // Since we have to return it in microsecond multiply it with 1000; + return time * 10000; + } + + /** + * This returned the total time taken, till now, to play the video. + */ + public long getMediaTime() { + return iMediaTime*10000; + } + + public int getState() { + return iState; + } + + /** + * Removes the specified playerListner from this player + */ + public void removePlayerListener(PlayerListener aPlayerListener) { + closeCheck(); + iPlayerListenerImpl.removePlayerListener(aPlayerListener); + } + public void start() throws MediaException { + final String DEBUG_STR = "AnimationPlayer::start()"; +// prefetch(); + initialize(); + addPaintListener(iControl); + iState = STARTED; + Thread thread = new Thread("Animation") { + int frameIndex = iFrameindex; + int loopCount = iCurrentLoopCount; + GC gc=null; + public void run() { + final int noOfFrames = iImageData.length; + while (frameIndex < noOfFrames && (loopCount < iTotalLoopCount) + && (iState == STARTED)) { + final int delayTimeForNextFrame = iImageData[frameIndex].delayTime; + System.out.println("\n\n\n************" + DEBUG_STR + + "Inside the while loop " + frameIndex + "/" + + noOfFrames); + // Since we are going to display first frame, notify all + // PlayerListener that Player has started + if (frameIndex == 0) { + iPlayerListenerImpl.postEvent(PlayerListener.STARTED, + new Long(iMediaTime * 10000)); + } + iDisplay.asyncExec(new Runnable() { + public void run() { + System.out.println(DEBUG_STR+"Inside run method"); + try { + if (gc == null)gc = new GC(iImage); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(DEBUG_STR+"Inside run method246"); + Image tempImage = new Image(iDisplay, + iImageData[frameIndex]); + System.out.println(DEBUG_STR+"Inside run method246"); + gc.drawImage(tempImage, 0, 0); + tempImage.dispose(); + frameIndex = (frameIndex + 1) % noOfFrames; + System.out.println(DEBUG_STR+"Inside run method253>>>>>>>>>"+frameIndex); + iControl.redraw(); + // update the mediaTime, as Animation progress + iMediaTime += delayTimeForNextFrame; + // If imageIndex becomes zero it means, all frames + // has been displayed + // So increase the loopCount + if (frameIndex == 0) { + // send the END_OF_MEDIA event to all listener + iPlayerListenerImpl.postEvent( + PlayerListener.END_OF_MEDIA, new Long( + iMediaTime * 10000)); + loopCount++; + // since player is again going to start from the + // first frame + // so media time should be set to zero + iMediaTime = 0; + } + System.out + .println(DEBUG_STR + + "end of asynchronous block imageIndex is " + + frameIndex + " and loop count is" + + loopCount ); + } + }); + try { + Thread.sleep(delayTimeForNextFrame * 10); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out + .println("**********************End of while loop\n\n\n"); + } + iCurrentLoopCount=loopCount; + System.out.println(DEBUG_STR + "Came out side the while loop " + + iState); + } + }; + thread.start(); + System.out.println(DEBUG_STR + "-"); + // }catch(Exception e){ + // System.out.println(DEBUG_STR+"Exception caught"+e); + // e.printStackTrace(); + // } + } + + /** + * This function is also being called from VideoControl class, + * Since on each event + * @param aControl + * @throws MediaException + */ + void addPaintListener(org.eclipse.swt.widgets.Control aControl) throws MediaException{ + final String DEBUG_STR="AnimationPlayer::addPaintListener()"; + iControl=aControl; + // iDisplay and IControl shouldn't be null here + System.out.println(DEBUG_STR+" Control is "+iControl+" Display "+iDisplay); + // Following line should never execute + // TODO check what message to provide in case of Exception + if(iControl==null) + throw new MediaException("Update this message"); + iDisplay.syncExec(new Runnable(){ + public void run() { + // if user is writing his MIDlet using eSWT API, then the Control object will be MobileShell + // and in that case it is mandatory to open the shell +// if(iControl instanceof MobileShell){ + if(iControl instanceof Shell){ + ((Shell)iControl).open(); + } + iControl.addPaintListener(new PaintListener(){ + public void paintControl(PaintEvent pe) { +// System.out.println(DEBUG_STR+"paintControl() paintEvent is "+pe); +// System.out.println(DEBUG_STR+"paintControl() Display location is "+iDisplayLocation.x+", "+iDisplayLocation.y); + if(iImage!=null){ + pe.gc.drawImage(iImage, iDisplayLocation.x, iDisplayLocation.y); + } + } + }); + } + }); + } + /** + * + */ + public Control getControl(String aControlType) { + if (aControlType == null) { + throw new IllegalArgumentException("argument is null"); + } + + String controlType = aControlType; + + // check if package name exists + if (controlType.indexOf(".") == -1) + { + // add package name + controlType = CONTROL_DEFAULT_PACKAGE + aControlType; + } + Control control = (Control)iControls.get(controlType); + // If control does not exists with default name, check if there is + // is a control with same type ( extends the given class name ). + if (control == null) { + try { + // try to create class for control + Class controlClass = Class.forName(controlType); + Enumeration elements = iControls.elements(); + // search if any control is same type that requested control + while (elements.hasMoreElements()) { + Control tmpControl = (Control) elements.nextElement(); + if (controlClass.isInstance(tmpControl)) { + // control is found + control = tmpControl; + } + } + } catch (ClassNotFoundException cnfe) // the class could not be + // found + { + // Exception is ignored and null is returned from this method + } catch (Error e) // the function failed for any other reason. + { + // Error is ignored and null is returned from this method + } + } + return control; + } + /** + * Returns all the control associated with this player + */ + public Control[] getControls() { + Control control[]= new Control[iControls.size()]; + Enumeration enumeration= iControls.elements(); + byte index=0; + while(enumeration.hasMoreElements()){ + control[index++]=(Control)enumeration.nextElement(); + } + return control; + } + /** + * + */ + public void setLoopCount(int aCount){ + super.setLoopCount(aCount); + iTotalLoopCount=aCount; + } + /** + * From PlayerBase + * @see PlayerBase + */ + public long setMediaTime(long aNow) throws MediaException { + long now = super.setMediaTime(aNow); + int totalFrames = iImageData.length; + int totalTime = 0; + for (int i = 0; i < totalFrames; i++) { + if (now < totalTime) { + iFrameindex=i; + break; + } + totalTime += iImageData[i].delayTime * 10000; + } + return totalTime; + } + ////////////////////////////////////////////////////////////////////////////////////// + // Following functions are for internal use, and not exposed to MIDlet developer////// + ///////////////////////////////////////////////////////////////////////////////////// + /** + * + */ + private void doStart(){ + + } + + + /** + * This function is responsible for creating all controls and adding it into Controls hashtable. + */ + private void pupulateControl(){ + final String DEBUG_STR="AnimationPlayer::pupulateControl()"; + System.out.println(DEBUG_STR+"+"); + VideoControl videoControl= new VideoControl(this); + FramePositioningControl fpc= new FramePositioningControl(this); + StopTimeControl stc= new StopTimeControl(this); + RateControl rc= new RateControl(this); + try { + addControl(videoControl, fVideoControl); + addControl(fpc, fFramePositioningControl); + addControl(stc, fStopTimeControl); + addControl(rc,fRateControl); + } catch (MediaException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(DEBUG_STR+"-"); + } + /** + * This function initialize iControl and iDisplay object if it is null, + * otherwise return immediately. + * + * In case of Canvas, eSWT control will be returned immediately from VideoControl(vc.getControl()), + * but in case of CustomItem we need to keep polling, eSWT doesn't return the control for CustomItem + * until CustomItem is appended to Form. + */ + + private void initialize() { + final String DEBUG_STR = "AnimationPlayer::initialize()"; + System.out.println(DEBUG_STR + "+"); + System.out.println(DEBUG_STR + " Control is " + iControl + + " display is " + iDisplay); + if (iControl == null || iDisplay == null) { + VideoControl vc = (VideoControl) getControl(fVideoControl); + iDisplay = vc.getiDisplay(); + // in case of CustomItem, + while ((iControl = vc.getControl()) == null) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + System.out.println(DEBUG_STR + "-"); + } + + /** + * This function will be called from setDisplaySize(int width, int height) of animation/VideoControl class + * When MIDlet developer will try to alter the size of the image + * @param width : to be set of the video(Animated GIF) + * @param height : height to be set of video(Animated GIF) + */ + void updateImageData(int width, int height){ + final String DEBUG_STR= "AnimationPlayer::updateImageData(int width, int height)"; + System.out.println(DEBUG_STR+"+"); + int noOfFrames= iImageData.length; + for(int i=0;i"+data[i]); + } + System.out.println(DEBUG_STR+"After reading all pixel value"); + int[] byteArray=new int[imageWidth*imageHeight]; + //int dataLength=data.length; + + for(int i=0;i>>>>"+byteArray.length); + return byteArray; + } + + /** + * Returns Point object, which contains the width and height of the image + * Called from VideoControl to get the image width and height, + * so that Item will be created exactly of same dimension + */ + org.eclipse.swt.graphics.Point getImageDimension(){ + return new org.eclipse.swt.graphics.Point(iImageData[0].width, iImageData[0].height); + } + + /** + * This returns the imageData array, + * called from FramePositioningControl class to calculate the frame time + */ + ImageData[] getImageData(){ + return iImageData; + } + + /** + * + * @param aDisplayLocation x,y coordinate where image is to be displayed + */ + void setDisplayLocation(int aX, int aY){ + iDisplayLocation=new Point(aX,aY); + } + + /** + * @return the position of the image to be displayed + */ + Point getiDisplayLocation() { + return iDisplayLocation; + } + /** + * Called from VideoControl to get the dimension of original image size + * @return + */ + Point getSourceDimension() { + return iSourceDimension; + } + + /** + * @return the iPlayerListenerImpl + */ + PlayerListenerImpl getiPlayerListenerImpl() { + return iPlayerListenerImpl; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/AnimationPlayerFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/AnimationPlayerFactory.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. + * This component and the accompanying materials are made available + * under the terms of "Eclipse Public License v1.0" + * which accompanies this distribution, and is available + * at the URL "http://www.eclipse.org/legal/epl-v10.html". + * + * Initial Contributors: + * Nokia Corporation - initial contribution. + * + * Contributors: + * + * Description: This class has been implemented for playing the GIF animation + * Earlier implementation were dependent on native API, but now AnimationPlayer + * will be not use any native code, and all the implementation here is using eswt API + * + */ + +package com.nokia.microedition.media.animation; + +import java.io.IOException; + +import javax.microedition.media.MediaException; +import javax.microedition.media.protocol.DataSource; + +import org.eclipse.swt.SWTException; + +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.PlugIn; + +/** + * This class is used for playing GIF image animation. This class also + * implements PlugIn interface which is used from ManagerImpl. + * Entire Animation playing is written using eSWT API. + * There is no call to native. + * + */ +public class AnimationPlayerFactory implements PlugIn { + + // Used to recognize supported locators. + // private static final String ANIMATION_FILE_EXTENSION = ".gif"; + + // Used to get supported protocols and content type. + private static final String ANIMATION_CONTENT_TYPE = "image/gif"; + private static final String ANIMATION_HTTP_PROTOCOL = "http"; + private static final String ANIMATION_HTTPS_PROTOCOL = "https"; + private static final String ANIMATION_FILE_PROTOCOL = "file"; + // There is no need to read the first 6 byte and compare it with following string +// private static final String ANIMATION_GIF_HEADER="GIF89a"; + + /** + * From PlugIn + */ + public InternalPlayer createPlayer(DataSource aDataSource) + throws MediaException, IOException { + final String DEBUG_STR="AnimationPlayerFactory::createPlayer()"; + System.out.println(DEBUG_STR+"+"); + InternalPlayer player = null; + System.out.println(DEBUG_STR+"data source object is "+aDataSource); + String contentType = aDataSource.getContentType(); + System.out.println(DEBUG_STR+"Content type is "+contentType); + // There is no difference in if and else block + // in first if block only checking if the content type is available + // Player is being created in the same way + + // First try to create player from content type + if (contentType != null){ + if(contentType.equals(ANIMATION_CONTENT_TYPE)) { + player = new AnimationPlayer(aDataSource); + System.out.println(DEBUG_STR+"Player created from content type"+contentType); + } +// else{ +// throw new MediaException("Content type not supported: " + contentType); +// } + } //Since it was not possible to identify the player from content type, identify it from it's header + // Is there any need to create player through Locator? + + else { + // We need only 6 bytes to identify whether it's GIF image data or not. + // But the problem here is that if we will read even a single byte from stream + // that stream won't be useful for loading the image data through ImageLoader class + // So better solution is to let the ImageLoader.load(InputStream ) get called + // if it successfully load the image, then it means that stream is intended for this player only + // otherwise it will throw the SWTException, catch it and return properly + try{ + player = new AnimationPlayer(aDataSource); + System.out.println(DEBUG_STR+"Player created from content type"); + }catch(SWTException e){ + // Simply ignore the exception + e.printStackTrace(); + } + } + System.out.println(DEBUG_STR+"-"); + return player; + } + + /** + * @param locator + * @return Interplayer object + */ + public InternalPlayer createPlayer(String locator ){ + final String DEBUG_STR="AnimationPlayerFactory::createPlayer(String locator )"; + System.out.println(DEBUG_STR+"+"); + InternalPlayer player = null; + try{ + player = new AnimationPlayer(locator); + }catch(SWTException e){ + // just ignore it + e.printStackTrace(); + } + System.out.println(DEBUG_STR+"returning player "+player); + System.out.println(DEBUG_STR+"-"); + return player; + } + + + /** + * From PlugIn + */ + public String[] getSupportedContentTypes(String aProtocol) { + String[] types = new String[0]; + if (aProtocol == null || aProtocol.equals(ANIMATION_HTTP_PROTOCOL) + || aProtocol.equals(ANIMATION_HTTPS_PROTOCOL) + || aProtocol.equals(ANIMATION_FILE_PROTOCOL)) { + types = new String[1]; + types[0] = ANIMATION_CONTENT_TYPE; + } + return types; + } + + /** + * From PlugIn + */ + public String[] getSupportedProtocols(String aContentType) { + String[] protocols = new String[0]; + if ((aContentType == null) + || aContentType.equals(ANIMATION_CONTENT_TYPE)) { + protocols = new String[3]; + protocols[0] = ANIMATION_HTTP_PROTOCOL; + protocols[1] = ANIMATION_HTTPS_PROTOCOL; + protocols[2] = ANIMATION_FILE_PROTOCOL; + } + // else empty array is returned + return protocols; + } + + /** + * From PlugIn. Empty implementation. + */ + public void preparePlayer(InternalPlayer aPlayer) throws MediaException { + // tone does not extend existing players + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/FramePositioningControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/FramePositioningControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import javax.microedition.media.Player; + +import org.eclipse.swt.graphics.ImageData; + +import com.nokia.microedition.media.control.ControlImpl; + +/** + * @author d35kumar + * + */ +public class FramePositioningControl extends ControlImpl implements + javax.microedition.media.control.FramePositioningControl { + + ImageData[] iImagedata; + /** + * + */ + FramePositioningControl(Player aPlayer) { + iPlayer=aPlayer; + iImagedata=((AnimationPlayer)iPlayer).getImageData(); + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.FramePositioningControl#mapFrameToTime(int) + */ + public long mapFrameToTime(int aFrameNumber) { + checkState(); + long time=0; + int totalNoOfFrames=iImagedata.length; + // if invalid parameter is passed + if(aFrameNumber<0 || aFrameNumber>totalNoOfFrames) + return -1; + for(int i=0;i aMediaTime){ + frameNumber=i-1; + break; + } + time+=iImagedata[i].delayTime*10000; + } + return frameNumber; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.FramePositioningControl#seek(int) + */ + public int seek(int aFrameNumber) { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.FramePositioningControl#skip(int) + */ + public int skip(int aFramesToSkip) { + // TODO Auto-generated method stub + return 0; + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/ProxyControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/ProxyControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,323 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import org.eclipse.ercp.swt.mobile.MobileShell; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ControlListener; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.events.TraverseListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Shell; + +/** + * This class will act like a proxy Control + * @author d35kumar + */ +class ProxyControl extends Control { + + /** + * this will be actual Shell, for which this class is acting like proxy + */ + Control iControl; + + public ProxyControl() { + super(Display.getDefault().getActiveShell(), SWT.BORDER); + } + + /** + * Actual Control will be created here + */ + public boolean setParent(Composite parent){ + iControl= new Shell((Shell)parent); + return true; + } + + /** + * + */ + public void addControlListener(ControlListener aListener){ + if(iControl!=null){ + iControl.addControlListener(aListener); + } + } + /** + * + */ + public void addFocusListener(FocusListener listener){ + if(iControl!=null)iControl.addFocusListener(listener); + } + /** + * + */ + public void addKeyListener(KeyListener listener){ + if(iControl!=null)iControl.addKeyListener(listener); + } + public void addMouseListener(MouseListener listener){ + if(iControl!=null)iControl.addMouseListener(listener); + } + public void addMouseMoveListener(MouseMoveListener listener){ + if(iControl!=null)iControl.addMouseMoveListener(listener); + } + /** + * + */ + public void addPaintListener(PaintListener aListener){ + if(iControl!=null)iControl.addPaintListener(aListener); + + } + + public void addTraverseListener(TraverseListener listener){ + if(iControl!=null)iControl.addTraverseListener(listener); + } + public Point computeSize(int wHint, + int hHint){ + Point point=null; + if(iControl!=null)point=iControl.computeSize(wHint, hHint); + System.out.println("ProxyControl::computeSize()"+point); + return point; + } + + public Point computeSize(int wHint, + int hHint, + boolean changed){ + Point point=null; + if(iControl!=null)point=iControl.computeSize(wHint, hHint,changed); + System.out.println("ProxyControl::computeSize()"+point+"Bolean changed "+changed); + return point; + } + + public Color getBackground(){ + Color color=null; + if(iControl!=null)color=iControl.getBackground(); + System.out.println("ProxyControl::getBackground()"); + return color; + } + public int getBorderWidth(){ + if(iControl!=null)return iControl.getBorderWidth(); + else return 0; + } + public Rectangle getBounds(){ + if(iControl!=null) return iControl.getBounds(); + else return null; + } + public boolean getEnabled(){ + if(iControl!=null) return iControl.getEnabled(); + else return false; + } + public Font getFont(){ + if(iControl!=null)return iControl.getFont(); + else return null; + } + public Color getForeground(){ + if(iControl!=null) return iControl.getForeground(); + else return null; + } + + public java.lang.Object getLayoutData(){ + if(iControl!=null) return iControl.getLayoutData(); + else return null; + } + + public Point getLocation(){ + if(iControl!=null) return iControl.getLocation(); + else return null; + } + + public Menu getMenu(){ + if(iControl!=null) return iControl.getMenu(); + else return null; + } + public Composite getParent(){ + if(iControl!=null) return iControl.getParent(); + else return null; + } + public Shell getShell(){ + if(iControl!=null) return iControl.getShell(); + else return null; + } + public Point getSize(){ + if(iControl!=null) return iControl.getSize(); + else return null; + } + + public java.lang.String getToolTipText(){ + if(iControl!=null) return iControl.getToolTipText(); + else return null; + } + public boolean getVisible(){ + if(iControl!=null) return iControl.getVisible(); + else return false; + } + public boolean isEnabled(){ + if(iControl!=null) return iControl.isEnabled(); + else return false; + } + + public boolean isFocusControl(){ + if(iControl!=null) return iControl.isFocusControl(); + else return false; + } + public boolean isReparentable(){ + if(iControl!=null) return iControl.isReparentable(); + else return false; + } + + public boolean isVisible(){ + if(iControl!=null)return iControl.isVisible(); + else return false; + } + public void moveAbove(Control control){ + if(iControl!=null) iControl.moveAbove(control); + } + public void moveBelow(Control control){ + if(iControl!=null) iControl.moveBelow(control); + } + public void pack(){ + if(iControl!=null) iControl.pack(); + } + public void pack(boolean changed){ + if(iControl!=null) iControl.pack(changed); + } + public void redraw(){ + if(iControl!=null) iControl.redraw(); + } + public void redraw(int x, + int y, + int width, + int height, + boolean all){ + if(iControl!=null) iControl.redraw(x,y,width,height, all); + } + public void removeControlListener(ControlListener listener){ + if(iControl!=null) iControl.removeControlListener(listener); + } + public void removeFocusListener(FocusListener listener){ + if(iControl!=null) iControl.removeFocusListener(listener); + } + public void removeMouseListener(MouseListener listener){ + if(iControl!=null) iControl.removeMouseListener(listener); + } + public void removeMouseMoveListener(MouseMoveListener listener){ + if(iControl!=null) iControl.removeMouseMoveListener(listener); + } + public void removePaintListener(PaintListener listener){ + if(iControl!=null)iControl.removePaintListener(listener); + } + public void removeTraverseListener(TraverseListener listener){ + if(iControl!=null)iControl.removeTraverseListener(listener); + } + public void setBounds(int x, + int y, + int width, + int height){ + if(iControl!=null)iControl.setBounds(x, y, width, height); + } + public void setBounds(Rectangle rect){ + if(iControl!=null)iControl.setBounds(rect); + } + public void setCapture(boolean capture){ + if(iControl!=null)iControl.setCapture(capture); + } + public void setEnabled(boolean enabled){ + if(iControl!=null)iControl.setEnabled(enabled); + } + public boolean setFocus(){ + if(iControl!=null) return iControl.setFocus(); + else return false; + } + public void setFont(Font font){ + if(iControl!=null)iControl.setFont(font); + } + public void setForeground(Color color){ + if(iControl!=null)iControl.setForeground(color); + } + public void setLayoutData(java.lang.Object layoutData){ + if(iControl!=null)iControl.setLayoutData(layoutData); + } + public void setLocation(int x, + int y){ + if(iControl!=null)iControl.setLocation(x, y); + } + + public void setLocation(Point location){ + if(iControl!=null)iControl.setLocation(location); + } + public void setMenu(Menu menu){ + if(iControl!=null)iControl.setMenu(menu); + } + public void setRedraw(boolean redraw){ + if(iControl!=null)iControl.setRedraw(redraw); + } + public void setSize(int width, + int height){ + if(iControl!=null) iControl.setSize(width, height); + } + + public void setSize(Point size){ + if(iControl!=null) iControl.setSize(size); + } + public void setToolTipText(java.lang.String string){ + if(iControl!=null)iControl.setToolTipText(string); + } + public void setVisible(boolean visible){ + if(iControl!=null)iControl.setVisible(visible); + } + public Point toControl(int x, + int y){ + if(iControl!=null)return iControl.toControl(x, y); + else return null; + } + public Point toControl(Point point){ + if(iControl!=null) return iControl.toControl(point); + else return null; + } + public Point toDisplay(int x, + int y){ + if(iControl!=null)return iControl.toDisplay(x,y); + else return null; + } + public Point toDisplay(Point point){ + if(iControl!=null)return iControl.toDisplay(point); + else return null; + } + public boolean traverse(int traversal){ + if(iControl!=null)return iControl.traverse(traversal); + else return false; + } + public void update(){ + if(iControl!=null)iControl.update(); + } + + public void checkSubclass() { + // do nothing,sub-classing allowed + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/RateControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/RateControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import javax.microedition.media.Player; + +import com.nokia.microedition.media.control.ControlImpl; + +/** + * @author d35kumar + * + */ +public class RateControl extends ControlImpl implements + javax.microedition.media.control.RateControl { + + + /** + * + * @param aPlayer + */ + public RateControl(Player aPlayer){ + this.iPlayer=aPlayer; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.RateControl#getMaxRate() + */ + public int getMaxRate() { + checkState(); + return 0; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.RateControl#getMinRate() + */ + public int getMinRate() { + checkState(); + return 0; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.RateControl#getRate() + */ + public int getRate() { + checkState(); + return 0; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.RateControl#setRate(int) + */ + public int setRate(int aMillirate) { + checkState(); + return 0; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/StopTimeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/StopTimeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import javax.microedition.media.Player; + +import com.nokia.microedition.media.control.ControlImpl; + +/** + * @author d35kumar + * + */ +public class StopTimeControl extends ControlImpl implements + javax.microedition.media.control.StopTimeControl { + + long iStopTime=RESET; + /** + * + */ + public StopTimeControl(Player aPlayer) { + this.iPlayer=aPlayer; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.StopTimeControl#getStopTime() + */ + public long getStopTime() { + checkState(); + return iStopTime; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.StopTimeControl#setStopTime(long) + */ + public void setStopTime(long aStopTime) { + checkState(); + if (iPlayer.getState() == Player.STARTED && getStopTime() != RESET) { + throw new IllegalStateException( + "Player is STARTED or setStopTime() is already called successfully"); + } + iStopTime = aStopTime; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/VideoControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/VideoControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,548 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +/** + * + */ +package com.nokia.microedition.media.animation; + +import javax.microedition.lcdui.Item; +import javax.microedition.media.MediaException; +import javax.microedition.media.Player; +import javax.microedition.media.PlayerListener; + +import org.eclipse.ercp.swt.mobile.MobileShell; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +//import com.nokia.microedition.media.control.ApplicationUtils; +import com.nokia.microedition.media.control.ControlImpl; +import com.nokia.microedition.media.control.MMAGUIFactory; +import com.nokia.mj.impl.rt.support.Finalizer; +import com.nokia.mj.impl.media.PlayerPermission; +import com.nokia.mj.impl.nokialcdui.ItemControlStateChangeListener; +import com.nokia.mj.impl.nokialcdui.LCDUIInvoker; + +//import com.nokia.mj.impl.media.PlayerPermission; +import com.nokia.mj.impl.rt.support.ApplicationUtils; + +/** + * @author d35kumar + * + */ +public class VideoControl extends ControlImpl implements + javax.microedition.media.control.VideoControl , ItemControlStateChangeListener{ + + // Following variable has been taken from VideoControl class + private static final String GUI_OBJECT_CLASS_NAME = + "javax.microedition.lcdui.Item"; + // lcdui package used with UiToolkitRegister + private static String LCDUI_PACKAGE = + "javax.microedition.lcdui"; + // eswt package used with UiToolkitRegister + private static String ESWT_PACKAGE = "org.eclipse.swt.widgets"; + // ToolkitRegister class name used with eswt and lcdui + private static String DISPLAY = ".Display"; + + // class name used to check if eswt is included + private static String LISTENER = ".Listener"; + + // class name used to check if eswt is included + private static String ESWT_CONTROL = ".control"; + // class name used with dynamic display mode initialization + private static String GUI_FACTORY_CLASS_NAME = ".Factory"; + + private static final int NOT_INITIALIZED = -1; + protected int iStatus = NOT_INITIALIZED; + private static final int UNDEFINED_RETURN_VALUE=0; + // For integrating with eSWT API + private Display iDisplay; +// private Shell iShell; + + private Control iControl; + + // Global??? yes because we need to remove it from player listener, while finalizer will be called + private VideoItem iVideoItem; + + private Finalizer mFinalizer = new Finalizer(){ + public void finalizeImpl(){ + doFinalize(); + } + }; + + /** + * Constructor of VideoControl + * @param player + */ + public VideoControl(Player player){ + this.iPlayer=player; + } + + /** + * + */ + private void doFinalize() { + if (mFinalizer != null) { + registeredFinalize(); + mFinalizer = null; + } + } + + /** + * + */ + final void registeredFinalize() { + if (iVideoItem != null) { + iPlayer.removePlayerListener(iVideoItem); + } + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#getDisplayHeight() + */ + public int getDisplayHeight() { + checkState(); + if (iStatus == NOT_INITIALIZED) { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + return ((AnimationPlayer)iPlayer).getImageDimension().x; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#getDisplayWidth() + */ + public int getDisplayWidth() { + checkState(); + if (iStatus == NOT_INITIALIZED) { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + return ((AnimationPlayer)iPlayer).getImageDimension().x; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#getDisplayX() + */ + public int getDisplayX() { + checkState(); + if (iStatus == NOT_INITIALIZED) + { + return UNDEFINED_RETURN_VALUE; + } + return ((AnimationPlayer)iPlayer).getiDisplayLocation().x; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#getDisplayY() + */ + public int getDisplayY() { + checkState(); + if (iStatus == NOT_INITIALIZED) + { + return UNDEFINED_RETURN_VALUE; + } + return ((AnimationPlayer)iPlayer).getiDisplayLocation().y; + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#getSnapshot(java.lang.String) + */ + public byte[] getSnapshot(String aImageType) throws MediaException { + final String DEBUG_STR="VideoControl::getSnapshot(String aImageType)"; + System.out.println(DEBUG_STR+"+"); + checkState(); + if (iStatus == NOT_INITIALIZED) { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + int imageData[]=((AnimationPlayer)iPlayer).getCurrentFrame(aImageType); + byte bytArry[]= new byte[imageData.length]; + int pixelCount=bytArry.length; + System.out.println(DEBUG_STR+"imageData receved is "+imageData); + for(int i=0;i>>>>>> Control is "+iControl); + // in case of customItem, we are getting canvasExtension as control + // and in this case we need to ignore the setDisplayLocation call. + // it is also possible that iControl may be null( it will be null until and unless + // notifyControlAvailable function is not get called) + if(iControl==null || (iControl instanceof org.eclipse.swt.internal.extension.CanvasExtension)) + return ; + ((AnimationPlayer)iPlayer).setDisplayLocation(aX, aY); + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#setDisplaySize(int, int) + */ + public void setDisplaySize(int aWidth, int aHeight) throws MediaException { + final String DEBUG_STR="VideoControl::setDisplaySize(int aWidth, int aHeight)"; + System.out.println(DEBUG_STR+"width "+aWidth+" aHeight "+aHeight); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + if (aWidth <= 0 || aHeight <= 0) + { + throw new IllegalArgumentException( + "Width and height must be positive"); + } + ((AnimationPlayer) iPlayer).updateImageData(aWidth,aHeight); + // Since the DisplaySize is being changed, we need to change the + // size of VideoItem as well + // if the videoItem is not null, it means currently we are playing animation on form + if(iVideoItem!=null)// means it is for customItem + iVideoItem.setPreferredSize(aWidth, aHeight); + // Notify to all player listener that video Size has been changed + ((AnimationPlayer) iPlayer).getiPlayerListenerImpl().postEvent(PlayerListener.SIZE_CHANGED, this); + System.out.println(DEBUG_STR+"-"); + } + + /* (non-Javadoc) + * @see javax.microedition.media.control.VideoControl#setVisible(boolean) + */ + public void setVisible(final boolean aVisible) { + if (iControl != null) { + iDisplay.syncExec(new Runnable() { + public void run() { + iControl.setVisible(aVisible); + System.out.println("VideoControl::setVisible()"+aVisible); + } + }); + } + } + /** + * + * @return Display object retrieved from ESWT + */ + public Display getiDisplay() { + return iDisplay; + } + + /** + * + * @return + */ + public Control getControl() { + return iControl; + } + /** + * Function of ItemStateChangeListener + * @param ctrl + * @param item + */ + public void notifyControlAvailable(Control ctrl,Item item){ + final String DEBUG_STR= "VideoControl::notifyControlAvailable(Control ctrl,Item item)"; + System.out.println(DEBUG_STR+"+"); + iControl=ctrl; + System.out.println(DEBUG_STR+"Control is "+ctrl.hashCode()+ " Item is "+item); + //TODO is it proper here to put the below line in try/catch?, remove if we can + // otherwise it may deteriorate the performance, as in case of CustomItem on each + // repaint, eSWT control is getting destroyed, and reconstructed + try { + ((AnimationPlayer)iPlayer).addPaintListener(iControl); + } catch (MediaException e) { + // TODO What to do here + e.printStackTrace(); + } + System.out.println(DEBUG_STR+"-"); + } + /** + * Function of ItemStateChangeListener + * We don't need to do anything in this function + * @param item + */ + public void notifyControlDisposed(Item item){ + final String DEBUG_STR= "VideoControl::notifyControlDisposed(Item item)"; + System.out.println(DEBUG_STR+"+"); +// System.out.println(DEBUG_STR+"Item Disposed is "+item); +// System.out.println(DEBUG_STR+"-"); + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/VideoItem.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/animation/VideoItem.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package com.nokia.microedition.media.animation; + +import javax.microedition.lcdui.CustomItem; +import javax.microedition.lcdui.Graphics; +import javax.microedition.media.Player; +import javax.microedition.media.PlayerListener; +import org.eclipse.swt.graphics.Point; + + +/** + * + */ +/** + * @author d35kumar + * + */ + +public class VideoItem extends CustomItem implements PlayerListener { + + /** + * Width of this item + */ + + int iWidth; + + /** + * Height of this item + */ + int iHeight; + + /** + * + * @param dimension + */ + protected VideoItem(Point dimension ) { + super(""); + iWidth=dimension.x; + iHeight=dimension.y; + } + + /** + * + * @param w + * @param h + */ + protected VideoItem(int w, int h) { + super(""); + iWidth=w; + iHeight=h; + } + /** + * @return the minimum content width of the item, used by form while layouting the item + */ + protected int getMinContentWidth() { + return iWidth; + } + + /** + * @return the minimum content height of the item, used by form while layouting the item + */ + protected int getMinContentHeight() { + return iHeight; + } + + /** + * @return the preferred content width of the item, used by form while layouting the item + */ + protected int getPrefContentWidth(int height) { + return iWidth; + } + + /** + * @return the preferred content height of the item, used by form while layouting the item + */ + + protected int getPrefContentHeight(int width) { + return iHeight; + } + /** + * This is dummy implementation of the paint method. + */ + int count; + protected void paint(Graphics g, int w, int h) { + //TODO remove this code later + // this is added just for testing purpose + g.setColor(0x00a000); + g.fillRect(0,0,w,h); + g.setColor(0xFFFFFF); + g.drawString("paint"+(count++), w>>1, h>>1, Graphics.BASELINE|Graphics.HCENTER); + } + + /** + * Whenever player will be resized this function will be invoked and it will call the invalidate method of custom item + */ + public void playerUpdate(Player aPlayer, String aEvent, Object aEventData) { + System.out.println("VideoItem::playerUpdate() Event is "+aEvent+"Event Data is "+aEventData); + if (aEvent == SIZE_CHANGED) { + invalidate(); + } + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/BaseDisplay.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/BaseDisplay.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,154 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.control; + +import org.eclipse.swt.widgets.*; +import javax.microedition.lcdui.*; +import org.eclipse.swt.graphics.Rectangle; + + +public abstract class BaseDisplay +{ + // represents native side of display and initialized by derived class + protected int nativeDisplayHandle; + protected org.eclipse.swt.widgets.Control eswtCanvasControl; + private Rectangle rect; + private int[] rectDimension = new int[ 4 ]; + public BaseDisplay() + { + rect = new Rectangle(0,0,0,0); + } +/* protected void setESWTControl() + { + eswtCanvasControl = + } + */ + public void GetCallbackInUiThread(int placeholder) + { + System.out.println("inside BaseDisplay : GetCallbackInUiThread +"); + final int val = placeholder; + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + _nativeMethodCallInUiThread(nativeDisplayHandle , val); + } + }); + } + catch(Exception e) + { + System.out.println("inside BaseDisplay : GetCallbackInUiThread....exception is " + e.toString()); + } + System.out.println("inside BaseDisplay : GetCallbackInUiThread -"); + } + + public void setContentBound() + { + System.out.println("inside BaseDisplay : setContentBound +"); + try{ + + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + eswtCanvasControl.setBounds(rect); + } + }); + } + catch(Exception e) + { + System.out.println("inside BaseDisplay : setContentBound....exception is " + e.toString()); + } + System.out.println("inside BaseDisplay : setContentBound -"); + } + + + public void removeContentBound() + { + System.out.println("inside BaseDisplay : removeContentBound +"); + try{ + + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + Rectangle emptyRect = new Rectangle(0,0,0,0); + eswtCanvasControl.setBounds(emptyRect); + } + }); + } + catch(Exception e) + { + System.out.println("inside BaseDisplay : removeContentBound....exception is " + e.toString()); + } + System.out.println("inside BaseDisplay : removeContentBound -"); + } + + public void redrawControl() + { + System.out.println("inside BaseDisplay : redrawControl +"); + try{ + + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + // redraw entire bounds of receiver + eswtCanvasControl.redraw(); + } + }); + } + catch(Exception e) + { + System.out.println("inside BaseDisplay : redrawControl....exception is " + e.toString()); + } + System.out.println("inside BaseDisplay : redrawControl -"); + } + /* called from native to reset the java side rect + Before the call of this function array is updated from native side + which can be used to refresh the UI screen rect and/or + set/remove bound rect + */ + public void setRect() + { + + rect.x = rectDimension[0]; + rect.y = rectDimension[1]; + rect.width = rectDimension[2]; + rect.height = rectDimension[3]; + + System.out.println("BaseDisplay : setRect rect is reset with values: x =" + rect.x +"y ="+ rect.y +"width ="+rect.width+"height = "+ rect.height); + + } + + // abstract functions implemented by concrete class + protected abstract void setDisplaySize(int aWidth, int aHeight); + protected abstract void setDisplayFullScreen(final boolean aFullScreenMode); + protected abstract void setDisplayLocation(int aX, int aY); + protected abstract void setVisible(boolean aVisible); + protected abstract int getDisplayHeight(); + protected abstract int getDisplayWidth(); + protected abstract int getDisplayX(); + protected abstract int getDisplayY(); + protected abstract int getSourceWidth(); + protected abstract int getSourceHeight(); + protected abstract void getBoundRect(); + protected abstract void setWindowResources(); + protected abstract void setNativeHandle(int handle); + // Native methods + private native void _nativeMethodCallInUiThread(int nativeDisplayHandle , int placeholder); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/ControlImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/ControlImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is an implementation of control +* +*/ + +package com.nokia.microedition.media.control; + +import javax.microedition.media.Player; + +public class ControlImpl implements javax.microedition.media.Control +{ + protected Player iPlayer; + protected int iControlHandle; + protected int iEventSource; + + /** + * Constructor + */ + public ControlImpl() + { + } + + /** + * Called when the Player is disposed + */ + public void notifyDispose() + { + } + + /** + * Set handles + * @param aPlayer Player instance + * @param aEventSource Handle to event source + * @param aControlHandle Handle Handle to control + */ + public void setHandles(Player aPlayer, + int aEventSource, + int aControlHandle) + { + iPlayer = aPlayer; + iEventSource = aEventSource; + iControlHandle = aControlHandle; + + _setHandle(aEventSource, aControlHandle, this); + } + + /** + * Throws IllegalStateException if player is closed and control + * cannot be used anymore. + * @throws IllegalStateException if Player is closed. + */ + protected void checkState() + { + if (iPlayer.getState() == Player.CLOSED) + { + throw new IllegalStateException("Player is CLOSED."); + } + } + + private static native void _setHandle(int aEventSourceHandle, + int aControlHandle, + Object aControl); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/FramePositioningControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/FramePositioningControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,182 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: FramePositioningControl controls frame position. +* +*/ + +package com.nokia.microedition.media.control; +import javax.microedition.media.Player; +import javax.microedition.media.MediaException; + + +/** + * FramePositioningControl methods cannot throw any exceptions. + * If an error occurs in native side, native side return default value. + */ +public class FramePositioningControl extends ControlImpl + implements javax.microedition.media.control.FramePositioningControl +{ + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + protected static final int NOT_FOUND = -1; // value to return on error condition + + /** + * @see FramePositioningControl + */ + public int seek(int aFrameNumber) + { + checkState(); + + int frameNumber = _seek(iControlHandle, iEventSource, aFrameNumber); + + // in case of error + if (frameNumber < 0) + { + if (aFrameNumber <= 0) + { + frameNumber = 0; + } + else + { + frameNumber = Integer.MAX_VALUE; + } + } + + return frameNumber; + } + + /** + * @see FramePositioningControl + */ + public int skip(int aFramesToSkip) + { + checkState(); + + // Array will be used for input and output. + // For output, room is needed for return value + // and error code, thus length of 2. + + int[] values = new int[ 2 ]; + values[ 0 ] = aFramesToSkip; + values[ 1 ] = NO_ERROR; + + int[] framesSkipped = + _skip(iControlHandle, + iEventSource, + values); + + if (framesSkipped[ 1 ] != NO_ERROR) + { + throw new Error("skip() failed"); + } + + return framesSkipped[ 0 ]; + } + + /** + * @see FramePositioningControl + */ + public long mapFrameToTime(int aFrameNumber) + { + checkState(); + + long frameMediaTime = + _mapFrameToTime(iControlHandle, + iEventSource, + aFrameNumber); + if (frameMediaTime < NO_ERROR) + { + frameMediaTime = NOT_FOUND; // error value + } + + return frameMediaTime; // -1 if error + } + + /** + * @see FramePositioningControl + */ + public int mapTimeToFrame(long aMediaTime) + { + checkState(); + + // mapTimeToFrame(0) must not fail and must return + // the frame number of the first frame. + + if (aMediaTime == 0) + { + return 0; + } + + int frameNumber = + _mapTimeToFrame(iControlHandle, + iEventSource, + aMediaTime); + if (frameNumber < NO_ERROR) + { + frameNumber = NOT_FOUND; // error value + } + + return frameNumber; + } + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native FramePositioningControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aFrameNumber Frame number to seek + * @return Number of frame that is actually seeked to + */ + private native int _seek(int iControlHandle, + int iEventSource, + int aFrameNumber); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native FramePositioningControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aValues element 0 Number of frames to skip + * @return element 0 Actual number of frames skipped. + * element 1 Error code + */ + private native int[] _skip(int iControlHandle, + int iEventSource, + int[] aValues); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native FramePositioningControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aFrameNumber The input frame number for conversion + * @return The converted media time in microseconds for the given frame + * (-1 on error). + */ + private native long _mapFrameToTime(int iControlHandle, + int iEventSource, + int aFrameNumber); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native FramePositioningControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aMediaTime The input media time for the conversion in microseconds. + * @return The converted frame number for the given media time (-1 on error). + */ + private native int _mapTimeToFrame(int iControlHandle, + int iEventSource, + long aMediaTime); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MIDIControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MIDIControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,469 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: MIDIControl. +* +*/ + + +package com.nokia.microedition.media.control; + +import javax.microedition.media.MediaException; +import javax.microedition.media.Player; + + +public class MIDIControl extends ControlImpl + implements javax.microedition.media.control.MIDIControl +{ + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + protected static final int NOT_FOUND = -1; + + /** + * Max data value for midi events. + */ + private static final int MAX_VALUE = 127; + + /** + * Min data value for midi event types. + */ + private static final int MIN_TYPE = 0x80; + + /** + * Max data value for midi event types. + */ + private static final int MAX_TYPE = 0xFF; + + /** + * Midi type reserved for system. + */ + private static final int RESERVED_TYPE_A = 0xF0; + + /** + * Midi type reserved for system. + */ + private static final int RESERVED_TYPE_B = 0xF7; + + /** + * Max channel number. + */ + private static final int MAX_CHANNEL = 15; + + /** + * Max bank number. + */ + private static final int MAX_BANK = 16383; + + /** + * Constant to use the default bank. Also the minimum bank value accepted. + */ + private static final int DEFAULT_BANK = -1; + + /** + * Constant value for the default bank. + */ + private static final int DEFAULT_BANK_NUMBER = 0x3c80; + + /** + * Constant MIDI control ID value for volume. + */ + private static final int CONTROL_VOLUME = 0x07; + + /** + * @see MIDIControl + */ + public boolean isBankQuerySupported() + { + return false; + } + + /** + * @see MIDIControl + */ + public int[] getProgram(int aChannel) + throws MediaException + { + checkPlayerState(); + checkChannel(aChannel); + // this method is not currently supported + throw new MediaException("Not supported"); + } + + /** + * @see MIDIControl + */ + public int getChannelVolume(int aChannel) + { + checkPlayerState(); + checkChannel(aChannel); + + // Native side returns -1 if current volume cannot be + // determined for sure + + int volume = + _getChannelVolume(iControlHandle, iEventSource, aChannel); + + // return 0-127, or -1 if not known + if (volume < NOT_FOUND) + { + volume = NOT_FOUND; + } + return volume; + } + + /** + * @see MIDIControl + */ + public void setProgram(int aChannel, int aBank, int aProgram) + { + checkPlayerState(); + checkChannel(aChannel); + checkBank(aBank); + checkProgram(aProgram); + + // Handle query for default bank + if (aBank == DEFAULT_BANK) + { + aBank = DEFAULT_BANK_NUMBER; + } + + int err = _setProgram(iControlHandle, iEventSource, aChannel, aBank, aProgram); + + if (err < NO_ERROR) + { + throw new Error("setProgram() failed, Symbian OS error: " + err); + } + } + + /** + * @see MIDIControl + */ + public synchronized void setChannelVolume(int aChannel, int aVolume) + { + checkPlayerState(); + checkChannel(aChannel); + + // Volume must be between 0 - MAX_VALUE + if (aVolume < 0 || + aVolume > MAX_VALUE) + { + throw new IllegalArgumentException("Invalid volume " + aVolume + + ", valid range is 0 <= volume <= 127"); + } + + int err = _setChannelVolume(iControlHandle, iEventSource, aChannel, aVolume); + if (err < NO_ERROR) + { + throw new Error("setChannelVolume() failed, SymbianO S error: " + err); + } + } + + /** + * @see MIDIControl + */ + public int[] getBankList(boolean aCustom) + throws MediaException + { + checkPlayerState(); + // this method is not currently supported + throw new MediaException("Not supported"); + } + + /** + * @see MIDIControl + */ + public int[] getProgramList(int aBank) + throws MediaException + { + checkPlayerState(); + checkBank(aBank); + // this method is not currently supported + throw new MediaException("Not supported"); + } + + /** + * @see MIDIControl + */ + public String getProgramName(int aBank, int aProg) + throws MediaException + { + checkPlayerState(); + checkBank(aBank); + checkProgram(aProg); + // this method is not currently supported + throw new MediaException("Not supported"); + } + + /** + * @see MIDIControl + */ + public String getKeyName(int aBank, int aProg, int aKey) + throws MediaException + { + checkPlayerState(); + checkBank(aBank); + checkProgram(aProg); + checkKey(aKey); + // this method is not currently supported + throw new MediaException("Not supported"); + } + + /** + * Short midi events are delegated to the longMidiEvent method. + * + * @see MIDIControl + */ + public void shortMidiEvent(int aType, int aData1, int aData2) + { + checkPlayerState(); + + // Data parameters must be between 0 to MAX_VALUE + if (aData1 < 0 || + aData1 > MAX_VALUE || + aData2 < 0 || + aData2 > MAX_VALUE) + { + throw new IllegalArgumentException( + "Invalid data, valid range is 0 <= data <= 127"); + } + + // Check type: + // must be MIN_TYPE..MAX_TYPE, excluding RESERVED_TYPE_A and + // RESERVED_TYPE_B, which are reserved for system exclusive. + if (aType == RESERVED_TYPE_A || + aType == RESERVED_TYPE_B || + aType < MIN_TYPE || + aType > MAX_TYPE) + { + throw new IllegalArgumentException("Invalid midi type " + aType + + ", valid range is 0x80 <= type <= 0xFF or 0xF0 or 0xF7"); + } + + // Format to long MIDI event + byte[] data = new byte[ 3 ]; + + // aType and datas are checked to fit in a byte range 0..127 + data[ 0 ] = (byte)aType; + data[ 1 ] = (byte)aData1; + data[ 2 ] = (byte)aData2; + + // Send short midi event as a long midi event. + // Length of short midi event is 3. + longMidiEvent(data, 0, 3); + } + + /** + * @see MIDIControl + */ + public int longMidiEvent(byte[] aData, int aOffset, int aLength) + { + checkPlayerState(); + + // Check parameters + if ((aData == null) || + (aData.length < aOffset + aLength) || // Do not exceed array length + (aOffset < 0) || // Offset may not be negative + (aLength < 0)) // Length may not be negative + { + throw new IllegalArgumentException("Illegal array"); + } + + // Zero length, just return + if (aLength == 0) + { + return 0; + } + + // Send to the native side. + int retVal = _sendMidiEvent(iControlHandle, + iEventSource, + aData, + aOffset, + aLength); + + if (retVal < NO_ERROR) + { + return -1; + } + + return retVal; + } + + /** + * Restarts native MIDI engine and initializes it with specified sequence. + * For internal use. + */ + public void reInitializeMidi(byte[] aMidiSequence, int aOffset, int aLength) + { + int retVal = _reInitializeMidi(iControlHandle, + iEventSource, + aMidiSequence, + aOffset, + aLength); + if (retVal < NO_ERROR) + { + throw new IllegalStateException(); + } + + } + + /** + * Checks program parameter. + */ + private void checkProgram(int aProgram) + { + // Program must be between 0 - MAX_VALUE + if (aProgram < 0 || + aProgram > MAX_VALUE) + { + throw new IllegalArgumentException("Invalid program " + + aProgram + ", valid range is 0 <= program <= 127"); + } + } + + /** + * Checks bank parameter. + */ + private void checkBank(int aBank) + { + // Bank must be between DEFAULT_BANK - MAX_BANK + if (aBank < DEFAULT_BANK || + aBank > MAX_BANK) + { + throw new IllegalArgumentException("Invalid bank " + + aBank + ", valid range is 1 <= bank <= 16383"); + } + } + + /** + * Checks channel parameter. + */ + private void checkChannel(int aChannel) + { + // Channel must be between 0 - MAX_CHANNEL + if (aChannel < 0 || + aChannel > MAX_CHANNEL) + { + throw new IllegalArgumentException("Invalid channel " + + aChannel + ", valid range is 0 <= channel <= 15"); + } + } + + /** + * Checks key number parameter. + */ + private void checkKey(int aKey) + { + // Channel must be between 0 - MAX_VALUE + if (aKey < 0 || + aKey > MAX_VALUE) + { + throw new IllegalArgumentException("Invalid key " + + aKey + ", valid range is 0 <= key <= 127"); + } + } + + /** + * Checks that player has been prefetched. + */ + private void checkPlayerState() + { + // Player must be in PREFETCHED or STARTED state. + int state = iPlayer.getState(); + if (state != Player.PREFETCHED && + state != Player.STARTED) + { + throw new IllegalStateException( + "Player must be in PREFETCHED or STARTED state"); + } + } + + // + // Native methods + // + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native MIDIControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aChannel number of channel which is subject to program change. + * @param aBank bank to be set. + * @param aProgram program to be set. + * @return error code. Negative is error occured. + */ + private native int _setProgram(int aControlHandle, + int aEventSourceHandle, + int aChannel, + int aBank, + int aProgram); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native MIDIControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aChannel channel which volume to get + * @return The channel volume. -1 if an error occured or if not known. + */ + private native int _getChannelVolume(int aControlHandle, + int aEventSourceHandle, + int aChannel); + + /** + * Native Implementation. + * @param aControlHandle Pointer to the native MIDIControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aChannel channel which volume to set + * @param aVolume volume to set + */ + private native int _setChannelVolume(int aControlHandle, + int aEventSource, + int aChannel, + int aVolume); + + /** + * Native implementation. Array length will asserted only in debug builds. + * + * @param aControlHandle Pointer to the native MIDIControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aData Array of the bytes to send. + * @param aOffset Start offset in data array. + * @param aLength Number of bytes to be sent. + * @return The number of bytes actually sent to the device. + * -1 if an error occured. + * KErrArgument if IllegalArgument exception must be thrown + */ + private native int _sendMidiEvent(int aControlHandle, + int aEventSourceHandle, + byte[] aData, + int aOffset, + int aLength); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native MIDIControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aMidiSequence Array of the bytes containing midi sequence + * for initialization + * @param aOffset Start offset in data array. + * @param aLength Number of bytes to be sent. + * @return Native error code. + */ + private native int _reInitializeMidi(int aControlHandle, + int aEventSourceHandle, + byte[] aMidiSequence, + int aOffset, + int aLength); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMACanvasDisplay.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMACanvasDisplay.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,415 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.control; + +import org.eclipse.swt.*; +import org.eclipse.swt.widgets.*; +import javax.microedition.lcdui.*; +import org.eclipse.ercp.swt.mobile.MobileShell; +import org.eclipse.swt.graphics.Rectangle; + + + +public class MMACanvasDisplay extends BaseDisplay +{ + + private int iEventSourceHandle; + private MMAPIeSWTObserver eswtObserver; + private int x; + private int y; + private int qwidgetHandle; + private int eSWTcontrolLocationX; + private int eSWTcontrolLocationY; + + // index 0 : x-coordinate of topleft corner of display + // index 1 : y-coordinate of topleft corner of display + // index 3 : width of display + // index 4 : height of display + + private int[] displayboundarr = new int[ 4 ]; + // represents native side of display + + + public MMACanvasDisplay(int aEventSourceHandle , javax.microedition.lcdui.Canvas canvas) + { + iEventSourceHandle = aEventSourceHandle; + eswtObserver = new MMAPIeSWTObserver(); + eswtCanvasControl = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtControl(canvas); + //super.setESWTControl(eswtCanvasControl); + } + + private void addListeners() + { + eswtObserver.addControlListenerToControl(eswtCanvasControl); + eswtObserver.addShellListenerToControl(eswtCanvasControl); + eswtObserver.addDisposeListenerToControl(eswtCanvasControl); + } + + public void setNativeHandle( int handle) + { + System.out.println("MMACanvasDisplay.java : setNativeHandle :" + handle); + nativeDisplayHandle = handle; + eswtObserver.setDisplayToObserver(this); + addListeners(); + } + + public void setDisplaySize(int aWidth, int aHeight) + { + final int width = aWidth; + final int height = aHeight; + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + org.eclipse.swt.graphics.Point size = new org.eclipse.swt.graphics.Point(width,height); + eswtCanvasControl.redraw(); + + System.out.println("inside videoControl's setDisplaySize redraw called"); + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + + +System.out.println("inside videoControl's setDisplaySize +"); + _setDisplaySize(nativeDisplayHandle, + iEventSourceHandle, + aWidth, + aHeight); +System.out.println("inside videoControl's setDisplaySize -"); + } + + public void setDisplayFullScreen(final boolean aFullScreenMode) + { + try{ + + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + eswtCanvasControl.setBounds(disp.getClientArea()); + new MobileShell(disp).setFullScreenMode(aFullScreenMode); + // instruct native to switch to full screen mode + _setFullScreenMode(nativeDisplayHandle,aFullScreenMode); + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + + } + + public void setDisplayLocation(int aX, int aY) + { + + final int videoControlLocationX = aX; + final int videoControlLocationY = aY; + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + org.eclipse.swt.graphics.Point topleftposition = eswtCanvasControl.getLocation(); + eSWTcontrolLocationX = topleftposition.x; + eSWTcontrolLocationY = topleftposition.y; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + // To Avoid UI thread block + System.out.println("inside videoControl's setDisplaySize before calling _setPosition " ); + _setPosition(nativeDisplayHandle, + iEventSourceHandle, + eSWTcontrolLocationX, + eSWTcontrolLocationY, + videoControlLocationX, + videoControlLocationY); + System.out.println("inside videoControl's setDisplaySize after calling _setPosition " ); + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + System.out.println("inside videoControl's setDisplaySize before redraw() " ); + eswtCanvasControl.redraw(); + System.out.println("inside videoControl's setDisplaySize after redraw() " ); + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplayLocation in redraw()....exception is " + e.toString()); + } + + + System.out.println("inside videoControl's setDisplayLocation coming out of setDisplayLocation()"); + } + + + public void setVisible(boolean aVisible) + { + try{ + final boolean visible = aVisible; + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.asyncExec(new Runnable() { + public void run() { + //eswtCanvasControl.setVisible(visible); + // call native side to set the visibiity + _setVisible(nativeDisplayHandle,visible); + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + //System.out.println("inside videoControl's setVisible before native call"); + // _setVisible(nativeDisplayHandle,aVisible); + // System.out.println("inside videoControl's setVisible after native call"); + } + + public int getDisplayHeight() + { + + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + + public void run() { + y = eswtCanvasControl.getSize().y; + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + return y; + + } + + public int getDisplayWidth() + { + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + x = eswtCanvasControl.getSize().x; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + + return x; + + } + public int getDisplayX() + { + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + x = eswtCanvasControl.getLocation().x; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + return x; + + } + + public int getDisplayY() + { + + + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + y = eswtCanvasControl.getLocation().y; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + return y; + } + + public int getSourceWidth() + { + // return width of the source video + + return 0; + + } + + public int getSourceHeight() + { + // return height of the source video + + return 0; + } + + public void getBoundRect() + { + System.out.println("MMACanvasDisplay.java :getBoundRect()"); + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + Rectangle boundrect = eswtCanvasControl.getBounds(); + displayboundarr[0] = boundrect.x ; + displayboundarr[1] = boundrect.y ; + displayboundarr[2] = boundrect.width ; + displayboundarr[3] = boundrect.height ; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + System.out.println("MMACanvasDisplay.java :getBoundRect() x =" + displayboundarr[0] + "y ="+ displayboundarr[1] +"width ="+ displayboundarr[2] +"height =" + displayboundarr[3] ); + } + + +public void getContainerRect() + { + // this function is not used for canvas case assuming that in case of canvas Bound rect and container rect is same. + // to do: need to confirm + getBoundRect(); + + } + +public void setContainerVisibilityToNative(final boolean active) + { + System.out.println("MMACanvasDisplay.java : SetContainerVisibilityToNative + "); + new Thread(){ + public void run(){ + System.out.println("MMACanvasDisplay.java : SetContainerVisibilityToNative execute the native function in new thread "); + _setContainerVisible(iEventSourceHandle,nativeDisplayHandle,active); + } + }.start(); + + System.out.println("MMACanvasDisplay.java : SetContainerVisibilityToNative - "); + } + +public void setWindowResources() +{ + System.out.println("MMACanvasDisplay.java: setWindowResources windowHandle "); + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + + disp.syncExec(new Runnable() { + public void run() { + Shell shell = eswtCanvasControl.getShell(); + qwidgetHandle = Internal_PackageSupport.topHandle(shell); + x = eswtCanvasControl.getSize().x; + y = eswtCanvasControl.getSize().y; + _setWindowToNative(nativeDisplayHandle,qwidgetHandle); + System.out.println("MMACanvasDisplay.java: setWindowResources qwidgetHandle is " + qwidgetHandle); + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + _setNativeWindowSize(nativeDisplayHandle,iEventSourceHandle,x,y); + +} + +/* +// dummy + +public void dummy() +{ + _nativeDummy(); +} +*/ +/* + public void getDisplaySize(int width, int height) + { + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + x = eswtCanvasControl.getSize().x; + y = eswtCanvasControl.getSize().y; + + } + }); + } + catch(Exception e) + { + System.out.println("inside videoControl's setDisplaySize....exception is " + e.toString()); + } + + width = x; + height = y; + } + + */ + // Native methods + + + private native void _setVisible(int nativeDisplayHandle, + boolean value); + + private native void _setContainerVisible(int iEventSourceHandle, + int nativeDisplayHandle, + boolean value); + private native void _setFullScreenMode(int nativeDisplayHandle, boolean value); + private native void _setWindowToNative(int nativeDisplayHandle,int qwidgetHandle); + private native void _setNativeWindowSize(int nativeDisplayHandle,int iEventSourceHandle, int width,int height); + private native void _setPosition(int nativeDisplayHandle, + int iEventSourceHandle, + int uiControlLocationX, + int uiControlLocationY, + int videoControlLocationX, + int videoControlLocationY); + private native void _setDisplaySize(int nativeDisplayHandle, + int iEventSourceHandle, + int eSWTcontrolLocationX, + int eSWTcontrolLocationY); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMAGUIFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMAGUIFactory.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.microedition.media.control; + +/** + * This interface provides extension point for GUIControl.USE_GUI_PRIMITIVE + * display mode. + */ +public interface MMAGUIFactory +{ + /** + * Initializes display mode and returns Object that can be used with + * GUI. + * @return Associated GUI object + */ + Object initDisplayMode(); + + /** + * MMA will set content for container with this method after display + * mode is initialized. + * @param aHandle MMMADirectContent native handle. + * @throw NullPointerException if initDisplayMode has not been called. + */ + void setContentHandle(int aHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMAPIeSWTObserver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/MMAPIeSWTObserver.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,218 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +package com.nokia.microedition.media.control; + +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.events.*; +import com.nokia.microedition.volumekeys.*; + + +public class MMAPIeSWTObserver +{ + //MMAPILCDUIInvokerImpl mmapiLcduiInvoker; + + mmacontrollistener cntrlsner ; + mmashelllistener shellsner ; + mmadisposelistener displsner; + +MMACanvasDisplay display; + + + public MMAPIeSWTObserver() + { + //mmapiLcduiInvoker = new MMAPILCDUIInvokerImpl(); + } + + public void setDisplayToObserver(MMACanvasDisplay display) + { + this.display = display; + cntrlsner = new mmacontrollistener(display); + shellsner = new mmashelllistener(display); + displsner = new mmadisposelistener(display); + } + + public void addControlListenerToControl(final Control eSWTControl) + { + + System.out.println("MMAPIeSWTObserver.java :addControlListenerToControl +"); + //mmapiLcduiInvoker.AddControlListenerToControl(eSWTControl,(org.eclipse.swt.events.ControlListener)this); + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + eSWTControl.addControlListener(cntrlsner); + } + }); + } + catch(Exception e) + { + System.out.println("addControlListenerToControl....exception is " + e.toString()); + } + + System.out.println("MMAPIeSWTObserver.java :addControlListenerToControl -"); + + } + + public void addShellListenerToControl(final Control eSWTControl) + { + System.out.println("MMAPIeSWTObserver.java :addShellListenerToControl +"); + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + eSWTControl.getShell().addShellListener(shellsner); + } + }); + } + catch(Exception e) + { + System.out.println("addShellListenerToControl....exception is " + e.toString()); + } + + System.out.println("MMAPIeSWTObserver.java :addShellListenerToControl -"); + + } + + + public void addDisposeListenerToControl(final Control eSWTControl) + { + System.out.println("MMAPIeSWTObserver.java :addDisposeListenerToControl +"); + //mmapiLcduiInvoker.AddDisposeListenerToControl(eSWTControl,(org.eclipse.swt.events.DisposeListener)this); + + try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.syncExec(new Runnable() { + public void run() { + eSWTControl.addDisposeListener(displsner); + } + }); + } + catch(Exception e) + { + System.out.println("addShellListenerToControl....exception is " + e.toString()); + } + System.out.println("MMAPIeSWTObserver.java :addDisposeListenerToControl -"); + + } + + public void removeControlListenerToControl(Control eSWTControl) + { + System.out.println("MMAPIeSWTObserver.java :removeControlListenerToControl +"); + //mmapiLcduiInvoker.RemoveControlListenerToControl(eSWTControl,(org.eclipse.swt.events.ControlListener)this); + System.out.println("MMAPIeSWTObserver.java :removeControlListenerToControl -"); + + } + public void removeShellListenerToControl(Control eSWTControl) + { + System.out.println("MMAPIeSWTObserver.java :removeShellListenerToControl +"); + //mmapiLcduiInvoker.RemoveShellListenerToControl(eSWTControl,(org.eclipse.swt.events.ShellListener)this); + System.out.println("MMAPIeSWTObserver.java :removeShellListenerToControl -"); + + } + public void removeDisposeListenerToControl(Control eSWTControl) + { + System.out.println("MMAPIeSWTObserver.java :removeDisposeListenerToControl +"); + //mmapiLcduiInvoker.RemoveDisposeListenerToControl(eSWTControl,(org.eclipse.swt.events.DisposeListener)this); + System.out.println("MMAPIeSWTObserver.java :removeDisposeListenerToControl -"); + + } + +} + + +// Control Listener + +class mmacontrollistener implements ControlListener +{ + + private MMACanvasDisplay display; + mmacontrollistener(MMACanvasDisplay display) + { + this.display = display; + + } + // from ControlListener + public void controlMoved(ControlEvent e) + { + System.out.println("MMAPIeSWTObserver.java :controlMoved callback"); + } + + public void controlResized(ControlEvent e) + { + System.out.println("MMAPIeSWTObserver.java :controlResized callback"); + } +} + +// ShellListener +class mmashelllistener implements ShellListener +{ + private MMACanvasDisplay display; + mmashelllistener(MMACanvasDisplay display) + { + this.display = display; + + } + // from ShellListener + public void shellActivated(ShellEvent e) + { + System.out.println("MMAPIeSWTObserver.java :shellActivated callback"); + display.setContainerVisibilityToNative(true); + } + + public void shellClosed(ShellEvent e) + { + System.out.println("MMAPIeSWTObserver.java :shellClosed callback"); + } + + public void shellDeactivated(ShellEvent e) + { + System.out.println("MMAPIeSWTObserver.java :shellDeactivated callback"); + display.setContainerVisibilityToNative(false); + } + + public void shellDeiconified(ShellEvent e) + { + System.out.println("MMAPIeSWTObserver.java :shellDeiconified callback"); + } + + public void shellIconified(ShellEvent e) + { + System.out.println("MMAPIeSWTObserver.java :shellIconified callback"); + } + + +} + +// DisposeListener + +class mmadisposelistener implements DisposeListener +{ + private MMACanvasDisplay display; + mmadisposelistener(MMACanvasDisplay display) + { + this.display = display; + } + + // from DisposeListener + public void widgetDisposed(DisposeEvent e) + { + System.out.println("MMAPIeSWTObserver.java :widgetDisposed callback"); + } + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/PitchControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/PitchControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,138 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: PitchControl controls the pitch. +* +*/ + +package com.nokia.microedition.media.control; + +/** + * TempoControl or RateControl methods cannot throw any exceptions. + * If an error occurs in native side, native side return default value. + */ +public class PitchControl extends ControlImpl + implements javax.microedition.media.control.PitchControl +{ + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + protected static final int PITCH_OFFSET = 1000000; + + /** + * @see PitchControl + */ + public int setPitch(int aMillisemitones) + { + checkState(); + int pitch = + _setPitch(iControlHandle, iEventSource, aMillisemitones); + if (pitch < NO_ERROR) + { + throw new Error("setPitch() failed, Symbian OS error: " + + pitch); + } + return pitch - PITCH_OFFSET; + } + + /** + * @see PitchControl + */ + public int getPitch() + { + checkState(); + int pitch = _getPitch(iControlHandle, iEventSource); + if (pitch < NO_ERROR) + { + throw new Error( + "getPitch() failed, SymbianOS error: " + pitch); + } + return pitch - PITCH_OFFSET; + } + + /** + * @see PitchControl + */ + public int getMaxPitch() + { + checkState(); + int pitch = _getMaxPitch(iControlHandle, iEventSource); + if (pitch < NO_ERROR) + { + throw new Error( + "getMaxPitch() failed, SymbianOS error: " + + pitch); + } + return pitch - PITCH_OFFSET; + } + + /** + * @see PitchControl + */ + public int getMinPitch() + { + checkState(); + int pitch = _getMinPitch(iControlHandle, iEventSource); + if (pitch < NO_ERROR) + { + throw new Error( + "getMinPitch() failed, SymbianOS error: " + + pitch); + } + return pitch - PITCH_OFFSET; + } + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native PitchControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aMillisemitones The number of semi tones to raise the playback + * pitch. + * @return The actual pitch raise set + */ + private native int _setPitch(int aControlHandle, + int aEventSourceHandle, + int aMillisemitones); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native PitchControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return the current playback pitch raise in "milli-semitones". + */ + private native int _getPitch(int aControlHandle, + int aEventSourceHandle); + + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native PitchControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return the maximum pitch raise in "milli-semitones". + */ + private native int _getMaxPitch(int aControlHandle, + int aEventSourceHandle); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native PitchControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return the minimum pitch raise in "milli-semitones". + */ + private native int _getMinPitch(int aControlHandle, + int aEventSourceHandle); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/RateControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/RateControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,136 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: RateControl controls the rate. +* +*/ + +package com.nokia.microedition.media.control; +import javax.microedition.media.Player; + +/** + * RateControl or RateControl methods cannot throw any exceptions. + * If an error occurs in native side, native side return default value. + */ +public class RateControl extends ControlImpl + implements javax.microedition.media.control.RateControl +{ + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + + /** + * @see RateControl + */ + public int setRate(int aMilliRate) + { + checkState(); + int rate = _setRate(iControlHandle, iEventSource, aMilliRate); + if (rate < NO_ERROR) + { + throw new Error( + "setRate() failed, Symbian OS error: " + rate); + } + return rate; + } + + /** + * @see RateControl + */ + public int getRate() + { + checkState(); + int rate = _getRate(iControlHandle, iEventSource); + if (rate < NO_ERROR) + { + throw new Error( + "getRate() failed, Symbian OS error: " + rate); + } + return rate; + } + + /** + * @see RateControl + */ + public int getMaxRate() + { + checkState(); + int rate = _getMaxRate(iControlHandle, iEventSource); + if (rate < NO_ERROR) + { + throw new Error( + "getMaxRate() failed, Symbian OS error: " + + rate); + } + return rate; + } + + /** + * @see RateControl + */ + public int getMinRate() + { + checkState(); + int rate = _getMinRate(iControlHandle, iEventSource); + if (rate < NO_ERROR) + { + throw new Error( + "getMinRate() failed, Symbian OS error: " + + rate); + } + return rate; + } + + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native RateControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aMilliRate The playback rate to set + * @return The actual rate set. + */ + private native int _setRate(int aControlHandle, + int aEventSourceHandle, + int aMilliRate); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native RateControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return The current playback rate. + */ + private native int _getRate(int aControlHandle, + int aEventSourceHandle); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native RateControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return The maximum rate. + */ + private native int _getMaxRate(int aControlHandle, + int aEventSourceHandle); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native RateControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return The minimum rate. + */ + private native int _getMinRate(int aControlHandle, + int aEventSourceHandle); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/RecordControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/RecordControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,634 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class controls the recording of the media from a Player. +* +*/ + + +package com.nokia.microedition.media.control; + +import java.io.IOException; +import java.io.OutputStream; +import javax.microedition.media.MediaException; +import javax.microedition.media.PlayerListener; +import javax.microedition.io.Connector; +import javax.microedition.io.Connection; +import javax.microedition.io.StreamConnection; +import javax.microedition.io.HttpConnection; +import javax.microedition.io.ConnectionNotFoundException; +import com.nokia.microedition.media.protocol.OutputStreamWriter; +import com.nokia.microedition.media.PlayerImpl; +import com.nokia.mj.impl.media.PlayerPermission; +import com.nokia.mj.impl.utils.Logger; +import com.nokia.mj.impl.rt.support.ApplicationUtils; + +/** + * RecordControl controls the recording of media + * from a Player. RecordControl records + * what's currently being played by the Player. + *

            + *

            Example

            + *
            + *
            + * try {
            + *    // Create a Player that captures live audio.
            + *    Player p = Manager.createPlayer("capture://audio");
            + *    p.realize();
            + *    // Get the RecordControl, set the record stream,
            + *    // start the Player and record for 5 seconds.
            + *    RecordControl rc = (RecordControl)p.getControl("RecordControl");
            + *    ByteArrayOutputStream output = new ByteArrayOutputStream();
            + *    rc.setRecordStream(output);
            + *    rc.startRecord();
            + *    p.start();
            + *    Thread.currentThread().sleep(5000);
            + *    rc.commit();
            + *    p.close();
            + * } catch (IOException ioe) {
            + * } catch (MediaException me) {
            + * } catch (InterruptedException ie) { }
            + * 
            + *
            + * + * @see javax.microedition.media.Player + */ +public class RecordControl extends ControlImpl + implements javax.microedition.media.control.RecordControl, Runnable +{ + + protected static final int ERROR_NONE = 0; // native side returns if OK + + private OutputStreamWriter iOutputStreamWriter; + private Connection iConnection; + private boolean iStarted = false; + + // commit() must be allowed when RecordControl is already + // committed from native side + private boolean iIgnoreCommitState = false; + + private static final String REQUEST_NAME = "User-Agent"; + private static final String REQUEST_VALUE = + "Profile/MIDP-2.0 Configuration/CLDC-1.0"; + private static final String CONTENT_TYPE = "Content-Type"; + + private static final String RECORD_CONTROL_PERMISSION = + "javax.microedition.media.control.RecordControl"; + + /** + * RecordControl constructor + */ + public RecordControl() + { + } + + /** + * Called when the Player is disposed + */ + public void notifyDispose() + { + try + { + closeStream(); + } + catch (IOException ioe) + { + // cannot throw error here + Logger.WLOG(Logger.EJavaMMAPI, + "Closing stream failed: ", ioe); + } + } + + private void closeStream() throws IOException + { + if (iOutputStreamWriter != null) + { + // wait until the StreamWriter events are fully handled + iOutputStreamWriter.close(); + } + try + { + if (iConnection != null) + { + // If stream was created with setRecordLocation( String aLocator ) + // method there is connection object and we have to close + // the OutputStream. Stream set with setRecordStream may not be + // closed. Any open streams would cause the connection to be + // held open until they themselves are closed. + iOutputStreamWriter.closeStream(); + } + } + finally + { + iOutputStreamWriter = null; + if (iConnection != null) + { + iConnection.close(); + iConnection = null; + } + } + } + + /** + * Set the output stream where the data will be + * recorded. + * + * @param aStream The output stream where the data will be recorded. + * @exception IllegalStateException Thrown if one of the following + * conditions is true: + *
              + *
            • + * startRecord has been called and commit has + * not been called. + *
            • + * setRecordLocation has been called and commit has + * not been called. + *
            + * + * @exception IllegalArgumentException Thrown if + * stream is null. + * + */ + public void setRecordStream(OutputStream aStream) + { + checkState(); + if (null == aStream) + { + throw new IllegalArgumentException("Stream is null"); + } + + // Stream is already set (and not commited) + if (iOutputStreamWriter != null) + { + throw new IllegalStateException( + "Stream is already set but not commited yet"); + } + + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + PlayerPermission per = new PlayerPermission("audio/video recording","record"); + appUtils.checkPermission(per); + + privateSetRecordStream(aStream); + } + + /** + * Private method for setting record stream. + * Called from setRecordStream and setRecordLocation methods. + * @param aStream The output stream where the data will be recorded. + */ + private void privateSetRecordStream(OutputStream aStream) + { + int playerHandle = ((PlayerImpl)iPlayer).getPlayerHandle(); + // Create a writer for OutputStream + iOutputStreamWriter = new OutputStreamWriter(aStream, + iEventSource, + this, + playerHandle); + + // Set the writer to the native object + int handle = _setRecordStream(iEventSource, + iControlHandle, + iOutputStreamWriter); + if (handle < ERROR_NONE) + { + iOutputStreamWriter = null; + throw new IllegalArgumentException( + "setRecordStream() failed, Symbian OS error: " + handle); + } + else + { + iOutputStreamWriter.start(handle); + } + } + + /** + * Set the output location where the data will be recorded. + * + * @param aLocator The locator specifying where the + * recorded media will be saved. The locator must be + * specified as a URL. + * @exception IllegalStateException Thrown if one of the following + * conditions is true: + *
              + *
            • + * startRecord has been called and commit has + * not been called. + *
            • + * setRecordStream has been called and commit has + * not been called. + *
            + * @exception IllegalArgumentException Thrown if locator + * is null. + * @exception IOException Thrown if protocol is valid but the + * media cannot be created at the specified location. + * @exception MediaException Thrown if the locator is not in URL syntax + * or it specifies a protocol that is not supported. + * @exception SecurityException Thrown if the caller does not + * have security permission to set the record location. + */ + public void setRecordLocation(String aLocator) + throws IOException, MediaException + { + checkState(); + if (aLocator == null) + { + throw new IllegalArgumentException("Locator is null"); + } + + // Stream is already set (and not commited) + if (iOutputStreamWriter != null) + { + throw new IllegalStateException( + "Record location is already set but not commited yet"); + } + + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + PlayerPermission per = new PlayerPermission("audio/video recording","record"); + appUtils.checkPermission(per); + + Connection conn; + try + { + conn = Connector.open(aLocator, Connector.WRITE); + } + catch (IllegalArgumentException iae) + { + throw new MediaException("Locator not supported: " + aLocator); + } + catch (ConnectionNotFoundException cnfe) + { + throw new MediaException("" + cnfe); + } + + // Using HTTP post + if (conn instanceof HttpConnection) + { + HttpConnection hc = (HttpConnection)conn; + + // Set the request method and headers + hc.setRequestMethod(HttpConnection.POST); + hc.setRequestProperty(REQUEST_NAME, REQUEST_VALUE); + hc.setRequestProperty(CONTENT_TYPE, getContentType()); + + // Getting the output stream may flush the headers + privateSetRecordStream(hc.openOutputStream()); + } + else if (conn instanceof StreamConnection) + { + // Using StreamConnection + StreamConnection sc = (StreamConnection)conn; + privateSetRecordStream(sc.openOutputStream()); + } + else + { + conn.close(); + throw new MediaException("Unsupported connection type"); + } + iConnection = conn; + } + + + /** + * Return the content type of the recorded media. + * + * The content type is given in the + * content type syntax. + * + * @return The content type of the media. + */ + public String getContentType() + { + checkState(); + return _getContentType(iEventSource, iControlHandle); + } + + + /** + * Start recording the media. + *

            + * If the Player is already started, startRecord + * will immediately start the recording. If the Player + * is not already started, startRecord will not + * record any media. It will put the recording in a "standby" mode. + * As soon as the Player is started, + * the recording will start right away. + *

            + * If startRecord is called when the recording has + * already started, it will be ignored. + *

            + * When startRecord returns, the recording has started + * and a RECORD_STARTED event will be delivered through the + * PlayerListener. + *

            + * If an error occurs while recording is in progress, + * RECORD_ERROR event will be delivered via the PlayerListener. + * + * @exception IllegalStateException Thrown if any of the following + * conditions is true: + *

              + *
            • + * if setRecordLocation or setRecordStream has + * not been called for the first time. + *
            • + * If commit has been called and + * setRecordLocation or setRecordStream + * has not been called. + *
            + */ + public void startRecord() + { + checkState(); + // Ignore if startRecord is called when the recording has already started + if (iStarted) + { + return; + } + + if (iOutputStreamWriter==null) + { + throw new IllegalStateException( + "Output stream or location not set yet"); + } + + int rval = _startRecord(iEventSource, iControlHandle); + if (rval != ERROR_NONE) + { + throw new RuntimeException("startRecord() failed, Symbian OS error: " + rval); + } + iStarted = true; + iIgnoreCommitState = false; + } + + /** + * Stop recording the media. stopRecord will not + * automatically stop the Player. It only stops + * the recording. + *

            + * Stopping the Player does not imply + * a stopRecord. Rather, the recording + * will be put into a "standby" mode. Once the Player + * is re-started, the recording will resume automatically. + *

            + * After stopRecord, startRecord can + * be called to resume the recording. + *

            + * If stopRecord is called when the recording has + * already stopped, it will be ignored. + *

            + * When stopRecord returns, the recording has stopped + * and a RECORD_STOPPED event will be delivered through the + * PlayerListener. + */ + public void stopRecord() + { + checkState(); + // If stopRecord is called when the recording has already stopped, + // it will be ignored. + if (!iStarted) + { + return; + } + + int rval = _stopRecord(iEventSource, iControlHandle); + if (rval != ERROR_NONE) + { + throw new RuntimeException("stopRecord() failed, Symbian OS error: " + rval); + } + iStarted = false; + } + + /** + * Complete the current recording. + *

            + * If the recording is in progress, commit + * will implicitly call stopRecord. + *

            + * To record again after commit has been called, + * setRecordLocation or setRecordStream + * must be called. + * + * @exception IOException Thrown if an I/O error occurs during commit. + * The current recording is not valid. To record again, + * setRecordLocation or setRecordStream + * must be called. + * + */ + public void commit() throws IOException + { + checkState(); + // If commit has been called and setRecordLocation or setRecordStream + // has not been called. + if (null == iOutputStreamWriter) + { + if (iIgnoreCommitState) + { + return; + } + throw new IllegalStateException( + "setRecordLocation() or setRecordStream() not called before calling commit()"); + } + + // If the recording is in progress, commit will implicitly call stopRecord + if (iStarted) + { + stopRecord(); + } + + int rval = _commit(iEventSource, iControlHandle); + + try + { + // Do not commit Java stream if native commit failed. + if (rval == ERROR_NONE) + { + iOutputStreamWriter.commit(); + } + } + finally + { + closeStream(); + } + if (rval != ERROR_NONE) + { + throw new IOException("commit() failed, Symbian OS error: " + rval); + } + } + + /** + * From Runnable. + * This method is called when commit is started from native code + * (record size limit is reached). + */ + public void run() + { + // Recording is already stopped. + iStarted = false; + try + { + commit(); + } + catch (Exception e) + { + // Because this method is called from new Thread no exceptions + // can be thrown. + ((PlayerImpl)iPlayer).getPlayerListenerImpl().postEvent( + PlayerListener.RECORD_ERROR, "Commit failed" + e); + + Logger.ELOG(Logger.EJavaMMAPI, "MMA::RecordControl::run failed: ", e); + } + iIgnoreCommitState = true; + } + + /** + * Set the record size limit. This limits the size of the + * recorded media to the number of bytes specified. + *

            + * When recording is in progress, commit will be + * called implicitly in the following cases: + *

              + *
            • Record size limit is reached + *
            • If the requested size is less than the already recorded size + *
            • No more space is available. + *
            + *

            + * Once a record size limit has been set, it will remain so + * for future recordings until it is changed by another + * setRecordSizeLimit call. + *

            + * To remove the record size limit, set it to + * Integer.MAX_VALUE. + * By default, the record size limit is not set. + *

            + * Only positive values can be set. Zero or negative values + * are invalid and an IllegalArgumentException + * will be thrown. + * + * @param aSize The record size limit in number of bytes. + * @return The actual size limit set. + * @exception IllegalArgumentException Thrown if the given size + * is invalid. + * @exception MediaException Thrown if setting the record + * size limit is not supported. + */ + public int setRecordSizeLimit(int aSize) throws MediaException + { + checkState(); + if (aSize <= 0) + { + throw new IllegalArgumentException("Size should be > 0"); + } + int rval = _setRecordSizeLimit(iEventSource, + iControlHandle, + aSize); + + // @exception MediaException Thrown if setting the record + // size limit is not supported. + + // Negative values are errors + if (rval < ERROR_NONE) + { + throw new MediaException( + "Setting record size limit is not supported, Symbian OS error: " + rval); + } + + // Returns 0, if the buffer cannot be resized + // Commit the buffer now + if (rval==0) + { + try + { + commit(); + } + catch (IOException ioe) + { + // Converts IOE to ME + throw new MediaException("IOException occurred during commit, " + ioe); + } + + rval = aSize; // return the requested size + } + + // Special case; do not return the actual size set when using MAX_VALUE + // (this was in TCK tests; RecordControl/SetRecordSizeLimit ) + if (aSize == Integer.MAX_VALUE) + { + return Integer.MAX_VALUE; + } + + return rval; + } + + /** + * Erase the current recording. + *

            + * If the recording is in progress, reset + * will implicitly call stopRecord. + *

            + * Calling reset after commit + * will have no effect on the current recording. + *

            + * If the Player that is associated with this + * RecordControl is closed, reset + * will be called implicitly. + * + * @exception IOException Thrown if the current recording + * cannot be erased. The current recording is not valid. + * To record again, setRecordLocation or + * setRecordStream must be called. + * + */ + public void reset() throws IOException + { + checkState(); + if (null == iOutputStreamWriter) + { + return; + } + + // If the recording is in progress, reset will implicitly call stopRecord + if (iStarted) + { + stopRecord(); + } + + int rval = _reset(iEventSource, iControlHandle); + if (rval < ERROR_NONE) + { + // IOException thrown if the current recording cannot be erased. + // To record again, setRecordLocation or setRecordStream must be called. + // closing the stream + closeStream(); + throw new IOException("reset() failed, Symbian OS error: " + rval); + } + } + + + private static native int _startRecord(int aEventSource, int aControlHandle); + private static native int _stopRecord(int aEventSource, int aControlHandle); + + private static native int _setRecordStream(int aEventSource, + int aControlHandle, + OutputStreamWriter aWriter); + + private static native String _getContentType(int aEventSource, + int aControlHandle); + + private static native int _commit(int aEventSource, int aControlHandle); + + private static native int _setRecordSizeLimit(int aEventSource, + int aControlHandle, + int aSize); + + private static native int _reset(int aEventSource, int aControlHandle); +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/StopTimeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/StopTimeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class allows one to specify a preset stop time for a Player +* +*/ + +package com.nokia.microedition.media.control; + +/** + * StopTimeControl allows one to specify a preset stop time for + * a Player. + *

            + */ +public class StopTimeControl extends ControlImpl + implements javax.microedition.media.control.StopTimeControl +{ + /** + * StopTimeControl constructor + */ + public StopTimeControl() + { + } + + /** + * Gets the last value successfully set by setStopTime. + * + * Returns the constant RESET if no stop time is set. + * This is the default. + * + * @return The current stop time in microseconds. + * @see #setStopTime + */ + public long getStopTime() + { + checkState(); + long time = _getStopTime(iEventSource, iControlHandle); + return time; + } + + /** + * + * Sets the media time at which you want the Player + * to stop. + * The Player will stop when its media time + * reaches the stop-time. + * A STOPPED_AT_TIME event + * will be delivered through the PlayerListener. + *

            + * The Player is guaranteed + * to stop within one second past the preset stop-time + * (i.e. stop-time <= current-media-time <= stop-time + 1 sec.); + * unless the current media time is already passed the preset stop time + * when the stop time is set. + * If the current media time is already past the stop time set, + * the Player will stop immediately. A + * STOPPED_AT_TIME event will be delivered. + * After the Player stops due to the stop-time set, + * the previously set stop-time will be cleared automatically. + * Alternatively, the stop time can be explicitly removed by + * setting it to: RESET. + *

            + * + * You can always call setStopTime on a stopped + * Player. + * To avoid a potential race condition, it is illegal to + * call setStopTime on a started Player if a + * media stop-time has already been set. + * + * @param aStopTime The time in microseconds at which you want the + * Player to stop, in media time. + * @exception IllegalStateException Thrown if + * aStopTime is called on a started + * Player and the + * media stop-time has already been set. + * @see #getStopTime + */ + public void setStopTime(long aStopTime) throws IllegalStateException + { + checkState(); + if (iPlayer.getState() == iPlayer.STARTED && getStopTime() != RESET) + { + throw new IllegalStateException( + "Player is STARTED or setStopTime() is already called successfully"); + } + + // Set native object to stop at time + _setStopTime(iEventSource, iControlHandle, aStopTime); + } + + private static native long _getStopTime(int aEventSourceHandle, + int aControlHandle); + + private static native int _setStopTime(int aEventSourceHandle, + int aControlHandle, + long aTime); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/TempoControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/TempoControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: TempoControl is used to control the tempo. +* +*/ + +package com.nokia.microedition.media.control; +import javax.microedition.media.Player; + +/** + * TempoControl or RateControl methods cannot throw any exceptions. + * If an error occurs in native side, native side return default value. + */ +public class TempoControl extends RateControl + implements javax.microedition.media.control.TempoControl +{ + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + + // Tempo holder for PREFETCHED state. Initially set to default value. + private static final int DEFAULT_TEMPO = 120000; + + /** + * @see TempoControl + */ + public int setTempo(int aMilliTempo) + { + checkState(); + // _setTempo returns real value (STARTED) or user set value + // (PREFETCHED). In latter case user set value is adjusted + // in native side according to max/min bounds of tempo. + int tempo = _setTempo(iControlHandle, iEventSource, aMilliTempo); + + if (tempo < NO_ERROR) + { + throw new Error( + "setTempo() failed, Symbian OS error: " + tempo); + } + return tempo; + } + + /** + * @see TempoControl + */ + public int getTempo() + { + checkState(); + + int tempo = _getTempo(iControlHandle, iEventSource); + return tempo; + } + + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native TempoControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @param aMilliTempo The tempo specified in milli-beats per minute + * @return The actual tempo set. + */ + private native int _setTempo(int aControlHandle, + int aEventSourceHandle, + int aMilliTempo); + + /** + * Native implementation. + * + * @param aControlHandle Pointer to the native TempoControl object. + * @param aEventSourceHandle Pointer to the native event source object. + * @return The tempo. + */ + private native int _getTempo(int aControlHandle, + int aEventSourceHandle); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VideoControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VideoControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,881 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: VideoControl is used to control the display of video. +* +*/ + +package com.nokia.microedition.media.control; + +import javax.microedition.media.Player; +import javax.microedition.media.MediaException; +import javax.microedition.lcdui.Canvas; +import javax.microedition.lcdui.Display; +import javax.microedition.midlet.MIDlet; +import com.nokia.microedition.media.NativeError; + +//import com.symbian.midp.runtime.MIDletExecutor; +import com.nokia.mj.impl.media.PlayerPermission; +import com.nokia.mj.impl.rt.support.ApplicationUtils; + + +import javax.microedition.lcdui.Displayable; +import javax.microedition.lcdui.Display; +//import com.symbian.midp.runtime.MIDletInstance; + +//import com.symbian.midp.runtime.ToolkitInvoker; + +import com.nokia.mj.impl.rt.support.Finalizer; +import com.nokia.mj.impl.utils.Logger; + +// MMAPI 3.x UI req. +import com.nokia.microedition.media.*; + +import org.eclipse.swt.*; +import org.eclipse.swt.widgets.*; +import javax.microedition.lcdui.*; +import org.eclipse.ercp.swt.mobile.MobileShell; + + + + +public class VideoControl + extends ControlImpl + implements javax.microedition.media.control.VideoControl +{ + private static final String GUI_OBJECT_CLASS_NAME = + "javax.microedition.lcdui.Item"; + private static final int NOT_INITIALIZED = -1; + private static final int ERROR_ARGUMENT = -6; // KErrArgument + + // use contans to avoid making native methods + // which has same prototypes + + // getter constants for native side + private static final int PROPERTY_DISPLAY_WIDTH = 1; + private static final int PROPERTY_DISPLAY_HEIGHT = 2; + private static final int PROPERTY_DISPLAY_X = 3; + private static final int PROPERTY_DISPLAY_Y = 4; + private static final int PROPERTY_SOURCE_WIDTH = 5; + private static final int PROPERTY_SOURCE_HEIGHT = 6; + + // setter constants for native side + private static final int SET_DISPLAY_SIZE = 20; + private static final int SET_DISPLAY_LOCATION = 21; + private static final int SET_DISPLAY_VISIBLE_TRUE = 22; + private static final int SET_DISPLAY_VISIBLE_FALSE = 23; + private static final int SET_DISPLAY_FULLSCREEN_TRUE = 24; + private static final int SET_DISPLAY_FULLSCREEN_FALSE = 25; + + // MMA API defines return values like 'return value is undefined' + // then UNDEFINED_RETURN_VALUE is returned + private static final int UNDEFINED_RETURN_VALUE = 0; + + // class name used with dynamic display mode initialization + private static String GUI_FACTORY_CLASS_NAME = ".Factory"; + + // lcdui package used with UiToolkitRegister + private static String LCDUI_PACKAGE = + "javax.microedition.lcdui"; + + // eswt package used with UiToolkitRegister + private static String ESWT_PACKAGE = "org.eclipse.swt.widgets"; + + // ToolkitRegister class name used with eswt and lcdui + private static String DISPLAY = ".Display"; + + // class name used to check if eswt is included + private static String LISTENER = ".Listener"; + + // class name used to check if eswt is included + private static String ESWT_CONTROL = ".control"; + + protected int iStatus = NOT_INITIALIZED; + + // Needed for getting native handle from lcdui components + //com.symbian.midp.runtime.ToolkitInvoker iToolkitInvoker; + + private VideoItem iVideoItem; + private Canvas iVideoCanvas; + + BaseDisplay display; +// private MIDletInstance iMIDletInstance; + + // error code used asynchronous native calls + private int iError; + + // used in asynchronous getSnapshot method + private byte[] iImageData; + private int iToolkitHandle = 0; + + // toolkit, stored as object as we don't have access to Toolkit class. + private Object iToolkit; + // for midlet foreground statelistening + //ToolkitInvoker iTlkitInvoker; + + private Finalizer mFinalizer = new Finalizer() + { + public void finalizeImpl() + { + doFinalize(); + } + }; + + public VideoControl() + { + // iToolkitInvoker = com.symbian.midp.runtime.ToolkitInvoker.getToolkitInvoker(); +// lcduiinvoker = new com.nokia.microedition.volumekeys.MMAPILCDUIInvokerImpl(); + // eswtObserver = new MMAPIeSWTObserver(); + } + + private void doFinalize() + { + if (mFinalizer != null) + { + registeredFinalize(); + mFinalizer = null; + } + } + + final void registeredFinalize() + { + if (iVideoItem != null) + { + iPlayer.removePlayerListener(iVideoItem); + iVideoItem.iNativeHandle = 0; + } + } + + public void setHandles(Player aPlayer, int aEventSource, int aControlHandle) + { + iPlayer = aPlayer; + iEventSource = aEventSource; + iControlHandle = aControlHandle; + iToolkitHandle = 0; // TODO: remove once implementation is done. + int error = _construct(iControlHandle, + aEventSource, + iToolkitHandle); + + NativeError.check(error); + } + + /** + * from Interface VideoControl + * + */ + public void setDisplaySize(int aWidth, int aHeight) throws MediaException + { + // checkState(); + + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + if (aWidth <= 0 || aHeight <= 0) + { + throw new IllegalArgumentException( + "Width and height must be positive"); + } + + + + System.out.println("before display.setDisplaySize()"); + + + //canvasdisplay.setDisplaySize( aWidth, aHeight); + display.setDisplaySize( aWidth, aHeight); + + System.out.println("after display.setDisplaySize()"); + /* + int ret = setDisplayProperty(aWidth, aHeight, SET_DISPLAY_SIZE); + if (ret < 0) + { + throw new MediaException("setDisplaySize() failed, SymbianOS error: " + + ret); + } + if (iStatus == USE_GUI_PRIMITIVE && + iVideoItem != null) // with dynamic display mode item can be null + { + iVideoItem.privateInvalidate(); + } + + */ + } + + /** + * from Interface VideoControl + * + */ + public void setDisplayFullScreen(boolean aFullScreenMode) throws MediaException + { + // checkState(); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + /* + int ret; + if (aFullScreenMode) + { + ret = setDisplayProperty(SET_DISPLAY_FULLSCREEN_TRUE); + } + else + { + ret = setDisplayProperty(SET_DISPLAY_FULLSCREEN_FALSE); + } + + if (ret < 0) + { + throw new MediaException(); + } + + */ + System.out.println("inside setDisplayFullScreen()"); + //canvasdisplay.setDisplayFullScreen( aFullScreenMode); + display.setDisplayFullScreen( aFullScreenMode); + + + } + + /** + * from Interface VideoControl + * + */ + public void setDisplayLocation(int aX, int aY) + { + // checkState(); + System.out.println("VideoControl.java :: setDisplayLocation x, y = " + aX + ","+ aY); + if (iStatus == USE_GUI_PRIMITIVE) + { + // In USE_GUI_PRIMITIVE mode, this call will be ignored. + return; + } + if (iStatus != USE_DIRECT_VIDEO) + { + // This method only works when the USE_DIRECT_VIDEO mode is set. + throw new IllegalStateException(); + } + /* + // cannot fail -> ignore return value + setDisplayProperty(aX, aY, SET_DISPLAY_LOCATION); + */ + + System.out.println("inside setDisplayLocation()"); + //canvasdisplay.setDisplayLocation( aX , aY); + display.setDisplayLocation( aX , aY); + + } + + /** + * from Interface VideoControl + * + */ + public void setVisible(boolean aVisible) + { + // checkState(); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + /*if (aVisible) + { + // Update the foreground or background state of the midlet before + // setting the visibility of the control + updateForeground(); + // cannot fail -> ignore return value + setDisplayProperty(SET_DISPLAY_VISIBLE_TRUE); + } + else + { + // cannot fail -> ignore return value + setDisplayProperty(SET_DISPLAY_VISIBLE_FALSE); + } + */ + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo, + " before display.setVisible()"); + System.out.println("inside setVisible()"); + if(aVisible) + { + // set the Midlet BG/FG status to native + updateForeground(); + } + display.setVisible( aVisible ); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo, + "after display.setVisible()"); + + + + } + + /** + * from Interface VideoControl + * + */ + public int getDisplayWidth() + {/* + checkState(); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + int width = getControlProperty(PROPERTY_DISPLAY_WIDTH); + return width; + */ + //return canvasdisplay.getDisplayWidth( ); + return display.getDisplayWidth( ); + } + + /** + * from Interface VideoControl + * + */ + public int getDisplayHeight() + { + /* checkState(); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + int height = getControlProperty(PROPERTY_DISPLAY_HEIGHT); + return height; + + */ + return display.getDisplayHeight( ); + } + + /** + * from Interface VideoControl + * + */ + public int getDisplayX() + { + /* checkState(); + if (iStatus == NOT_INITIALIZED) + { + return UNDEFINED_RETURN_VALUE; + } + int x = getControlProperty(PROPERTY_DISPLAY_X); + return x; + */ + return display.getDisplayX( ); + } + + /** + * from Interface VideoControl + * + */ + public int getDisplayY() + { + /* + checkState(); + if (iStatus == NOT_INITIALIZED) + { + return UNDEFINED_RETURN_VALUE; + } + int y = getControlProperty(PROPERTY_DISPLAY_Y); + return y; + + */ + return display.getDisplayY( ); + } + + /** + * from Interface VideoControl + * + */ + public int getSourceWidth() + { + /* checkState(); + int width = getControlProperty(PROPERTY_SOURCE_WIDTH); + if (width <= 0) + { + width = 1; + } + return width; + + */ + return display.getSourceWidth( ); + } + + /** + * from Interface VideoControl + * + */ + public int getSourceHeight() + { + /*checkState(); + int height = getControlProperty(PROPERTY_SOURCE_HEIGHT); + if (height <= 0) + { + height = 1; + } + return height; + */ + return display.getSourceHeight( ); + + } + + /** + * from Interface VideoControl + * + */ + synchronized public byte[] getSnapshot(String aImageType) throws MediaException + { + checkState(); + if (iStatus == NOT_INITIALIZED) + { + throw new IllegalStateException( + "VideoControl.initDisplayMode() not called yet"); + } + + // starts native side. Native will release wait lock if + // _getSnapshot doesn't leave. + int error = _getSnapshot(iControlHandle, + iEventSource, aImageType); + if (error == ERROR_ARGUMENT) + { + throw new MediaException("Unsupported image type: " + aImageType); + } + else if (error < 0) + { + throw new MediaException("getSnapshot() failed, Symbian OS error: " + error); + } + + synchronized (this) + { + try + { + // wait native side + wait(); + } + catch (Exception e) + { + throw new MediaException("" + e); + } + } + if (iError < 0) + { + throw new MediaException("Symbian OS error: " + iError); + } + + // Check the permission here, so 'the moment' is not lost? + //Security.ensurePermission(PERMISSION, PERMISSION, PERM_ARGS); + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + PlayerPermission per = new PlayerPermission("audio/video recording","snapshot"); + appUtils.checkPermission(per); + + return iImageData; + } + + /** + * from Interface VideoControl + * + */ + public Object initDisplayMode(int aMode, Object aArg) + { + checkState(); + if (iStatus != NOT_INITIALIZED) + { + // IllegalStateException - Thrown if initDisplayMode is + // called again after it has previously been called successfully. + throw new IllegalStateException( + "initDisplayMode() already called successfully"); + } + + if (aMode == USE_GUI_PRIMITIVE) + { + Object guiObject = null; + if (aArg == null) + { + guiObject = initNullMode(); + } + else + { + if (aArg.equals(GUI_OBJECT_CLASS_NAME)) + { + guiObject = initLCDUI(); + } + else // try load dynamic display mode + { + guiObject = initDynamicDisplayMode(aArg); + } + } + + iStatus = USE_GUI_PRIMITIVE; + return guiObject; + } + else if (aMode == USE_DIRECT_VIDEO) + { + if (aArg != null) + { + if (!(aArg instanceof javax.microedition.lcdui.Canvas)) + { + throw new java.lang.IllegalArgumentException( + "For USE_DIRECT_VIDEO mode argument should be of type Canvas"); + } + } + else + { + throw new java.lang.IllegalArgumentException( + "For USE_DIRECT_VIDEO mode argument should not be null"); + } + iVideoCanvas = (Canvas)aArg; + // MMAPI UI 3.x req. + + display = new MMACanvasDisplay(iEventSource , iVideoCanvas); + + System.out.println("VideoControl.java: after eswt control got from canvas has added observer"); + + int handle = initNativeDisplay(iVideoCanvas, display); + // here actual listener is added to display + display.setNativeHandle(handle); + // Window resource initialization is done to the native video player + display.setWindowResources(); + iStatus = USE_DIRECT_VIDEO; + + /*( try + { + this.setVisible(false); + } + + catch (IllegalStateException ex) { } + */ + return null; + } + else + { + // java.lang.IllegalArgumentException - Thrown if the mode is invalid. + throw new java.lang.IllegalArgumentException( + "Mode not supported or invalid, " + + "valid modes are USE_DIRECT_VIDEO and USE_GUI_PRIMITIVE"); + } + } + + /** + * Called from java for early initialization of native handle to java peer + * Because it will be used to make a jni call + */ + public void setNativeDisplayHandleToJavaPeer(int handle) + { + System.out.println("VideoControl.java: setNativeDisplayHandleToJavaPeer handle =" + handle); + display.setNativeHandle(handle); + } + + /** + * Initializes native display. + * + */ + private int initNativeDisplay(Object aGuiObject, Object mmadisplay) + { + int handle = _initDisplayMode(iControlHandle, + iEventSource, + mmadisplay, + aGuiObject); + NativeError.check(handle); + return handle; + } + + /** + * Gets control property from native side. + * @param aPropertyType One of the types defined in this class + * + */ + private int getControlProperty(int aPropertyType) + { + return _getControlProperty(iControlHandle, + iEventSource, + aPropertyType); + } + + /** + * Sets two properties to native side. + * + * @param aParamA Specific parameter A for property type. + * @param aParamB Specific parameter B for property type. + * @param aPropertyType One of the types defined in this class + */ + private int setDisplayProperty(int aParamA, int aParamB, int aPropertyType) + { + return _setDisplayProperty(iControlHandle, + iEventSource, + aParamA, + aParamB, + aPropertyType); + } + + /** + * Sets one property to native side. + * + * @param aPropertyType One of the types defined in this class + */ + private int setDisplayProperty(int aPropertyType) + { + return _setDisplayProperty(iControlHandle, + iEventSource, + 0, + 0, + aPropertyType); + } + + /** + * Called from native side when snapshot is ready + * + */ + private void snapshotReady(int aError, byte[] aImageData) + { + iImageData = aImageData; + iError = aError; + + synchronized (this) + { + notify(); + } + } + + /** + * This method will try to use dynamic class loading to instantiate GUI + * object for given mode. + * @param aMode parameter for display mode + * @return GUI object + */ + private Object initDynamicDisplayMode(Object aMode) + { + MMAGUIFactory guiFactory = null; + try + { + String className = ((String)aMode).toLowerCase() + + GUI_FACTORY_CLASS_NAME; + Class guiClass = Class.forName(className); + guiFactory = (MMAGUIFactory)guiClass.newInstance(); + } + catch (ClassNotFoundException cnfe) + { + // if the class could not be found + throw new IllegalArgumentException( + "Mode not supported or invalid, " + + "valid modes are USE_DIRECT_VIDEO and USE_GUI_PRIMITIVE"); + } + catch (IllegalAccessException iae) + { + // if the class or initializer is not accessible + throw new IllegalArgumentException("Mode: " + aMode + + " caused " + iae); + } + catch (InstantiationException ie) + { + // if an application tries to instantiate an abstract class or an + // interface, or if the instantiation fails for some other reason + throw new IllegalArgumentException("Mode: " + aMode + + " caused " + ie); + } + catch (ClassCastException cce) + { + // Thrown to indicate that the code has attempted to cast an + // object to a subclass of which it is not an instance. + throw new IllegalArgumentException("Mode: " + aMode + + " caused " + cce); + } + + Object guiObject = guiFactory.initDisplayMode(); + // initNativeDisplay return handle MMMADirectContainer, 0 parameter + // indicates that dynamic display will be used + // MMAPI UI 3.x req. + // guiFactory.setContentHandle(initNativeDisplay(guiObject, 0)); + return guiObject; + } + + /** + * Initializes LCDUI display mode. + * @return LCDUI Item + */ + private Object initLCDUI() + { + iVideoItem = new VideoItem(iEventSource); + iPlayer.addPlayerListener(iVideoItem); + + // MMAPI UI 3.x req. + // int handle = initNativeDisplay(iVideoItem, + // 1 /*iToolkitInvoker.itemGetHandle(iVideoItem)*/); + + // iVideoItem.setNativeHandle(handle); + + iStatus = USE_GUI_PRIMITIVE; + return iVideoItem; + } + + /** + * Initializes USE_GUI_PRIMITIVE mode when null parameter is given to + * initDisplayMode method. + * UI toolkit gets selected when application uses UI toolkit + * first time. After this selection null parameter must be + * interpreted as the selected UI toolkit. initDisplayMode call + * with null parameter before the selection must cause + * IllegalArgumentException if there are several toolkits. + * @return GUI object + */ + private Object initNullMode() + { + String toolkit = null; + + Object guiObject = null; + + // If lcdui was selected init it even if there might be several + // toolkits. This is done to support existing applications. + if ((LCDUI_PACKAGE + DISPLAY).equals(toolkit)) + { + guiObject = initLCDUI(); + } + else + { + try + { + // Several UI toolkits are supported if there are eSWT classes + // and eSWT direct content component + // Trying to load eSWT Listener interface or eSWT GUI factory + // does not cause any initialization to eSWT. + Class.forName(ESWT_PACKAGE + LISTENER); + Class.forName(ESWT_PACKAGE + + ESWT_CONTROL + + GUI_FACTORY_CLASS_NAME); + + // check if eSWT was selected + if ((ESWT_PACKAGE + DISPLAY).equals(toolkit)) + + { + guiObject = initDynamicDisplayMode( + ESWT_PACKAGE + + ESWT_CONTROL + + GUI_FACTORY_CLASS_NAME); + } + else + { + // If no toolkit is registered and if lcdui library exists select it + try + { + Class.forName(LCDUI_PACKAGE + DISPLAY); + + guiObject = initLCDUI(); + } + catch (ClassNotFoundException cnfe) + { + // If there are several toolkits and none is selected + // IllegalArgumentException must be thrown + throw new IllegalArgumentException( + "UI toolkit is not available or found."); + } + } + } + catch (ClassNotFoundException cnfe) + { + // Only lcdui is supported + guiObject = initLCDUI(); + } + } + return guiObject; + } + + + // private int updateForeground() // MMAPI UI 3.x changes + private void updateForeground() + { + + int isFG = 1; +/* + // Check whether display is initialized + checkState(); + if (iStatus == NOT_INITIALIZED) + { + return visible; + } + + iMIDletInstance = MIDletExecutor.getCurrentMIDlet(); + MIDlet midlet = iMIDletInstance.getMIDlet(); + //Displayable displayable; + if (midlet == null) + { + return visible; + } + else + { + Displayable displayable = Display.getDisplay(midlet).getCurrent(); + + if (displayable != null && displayable.isShown()) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo, + "VideoControl.updateForeground isShown() = 1"); + // visible + } + else + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo, + "VideoControl.updateForeground isShown() = 0"); + // not visible + visible = 0; + } + + // Set the foreground state + _setForeground(iControlHandle, + iEventSource, + visible); + } + + return visible; + */ + + // MMAPI UI 3.x req. + // Get the midlet position BG/FG + boolean visible = ManagerImpl.getInstance().isForground(); + if(visible) + isFG = 1; + else + isFG = 0; + + _setForeground(iControlHandle, + iEventSource, + isFG); + // return visible; + } + + private native int _construct(int aControlHandle, + int aEventSourceHandle, + int aToolkitHandle); + + private native int _getControlProperty(int aControlHandle, + int aEventSourceHandle, + int aPropertyType); + + private native int _setDisplayProperty(int aControlHandle, + int aEventSourceHandle, + int aParamA, + int aParamB, + int aPropertyType); + + private native int _getSnapshot(int aControlHandle, + int aEventSourceHandle, + String aProperties); + + private native int _initDisplayMode(int aControlHandle, + int aEventSourceHandle, + Object aJavaDisplay, + Object aJavaDisplayObject); + private native int _setForeground(int aControlHandle, + int aEventSourceHandle, + int aIsForeground); + + private native boolean _isESWT(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VideoItem.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VideoItem.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,182 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Item for VideoControl. +* +*/ + + +package com.nokia.microedition.media.control; + +import javax.microedition.lcdui.CustomItem; +import javax.microedition.lcdui.Graphics; +import javax.microedition.media.PlayerListener; +import javax.microedition.media.Player; +import javax.microedition.lcdui.*; + +/** + * Item for VideoControl. + * This class native equivalent is CMIDItemDisplay. + * All drawing is done in native. + * CustomItem has its native bitmap after it is layouted to + * the form and then SizeChanged method is called and native side + * gets the bitmap for item. + * + */ +public class VideoItem extends CustomItem implements PlayerListener +{ + int iNativeHandle; + + private int iEventSourceHandle; + + public VideoItem(int aEventSourceHandle) + { + super(""); // we don't have title + iEventSourceHandle = aEventSourceHandle; + } + + // from PlayerListener + public void playerUpdate(Player aPlayer, String aEvent, Object aEventData) + { + if (aEvent == SIZE_CHANGED) + { + invalidate(); + } + } + + /** + * From class CustomItem + * + */ + protected int getMinContentHeight() + { + int minHeight = 0; + if (iNativeHandle != 0) + { + minHeight = _getMinContentHeight(iEventSourceHandle, + iNativeHandle); + } + return minHeight; + } + + /** + * From class CustomItem + * + */ + protected int getMinContentWidth() + { + int minWidth = 0; + if (iNativeHandle != 0) + { + minWidth = _getMinContentWidth(iEventSourceHandle, + iNativeHandle); + } + return minWidth; + } + + /** + * From class CustomItem + * + */ + protected int getPrefContentHeight(int aWidth) + { + int prefHeight = 0; + if (iNativeHandle != 0) + { + prefHeight = _getPrefContentHeight(iEventSourceHandle, + iNativeHandle, + aWidth); + } + return prefHeight; + } + + /** + * From class CustomItem + * + */ + protected int getPrefContentWidth(int aHeight) + { + int prefWidth = 0; + if (iNativeHandle != 0) + { + prefWidth = _getPrefContentWidth(iEventSourceHandle, + iNativeHandle, + aHeight); + } + return prefWidth; + } + + /** + * From class CustomItem + * + * Empty implementation because drawing is done in native side. + * Must be implemented because this method is abstract. + * + */ + protected void paint(Graphics aGrapchics, int aWidth, int aHeight) + { + } + + /** + * From class CustomItem + * + */ + protected void sizeChanged(int aWidth, int aHeight) + { + if (iNativeHandle != 0) + { + _sizeChanged(iEventSourceHandle, + iNativeHandle, + aWidth, + aHeight); + } + } + + /** + * Package private method for invalidating the Form owning this item. + */ + void privateInvalidate() + { + invalidate(); + } + + /** + * Sets native CMIDItemDisplay handle. + */ + void setNativeHandle(int aHandle) + { + iNativeHandle = aHandle; + } + + // Native methods + + /** + * Informs got size to native side. + */ + private native int _sizeChanged(int aEventSourceHandle, + int aNativeHandle, + int aWidth, + int aHeight); + + // Getters for layout. + private native int _getMinContentWidth(int aEventSourceHandle, + int aNativeHandle); + private native int _getMinContentHeight(int aEventSourceHandle, + int aNativeHandle); + private native int _getPrefContentWidth(int aEventSourceHandle, + int aNativeHandle, + int aTentativeWidth); + private native int _getPrefContentHeight(int aEventSourceHandle, + int aNativeHandle, + int aTentativeHeigth); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VolumeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/control/VolumeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,120 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Item for VideoControl. +* +*/ + + +package com.nokia.microedition.media.control; + +public class VolumeControl extends ControlImpl + implements javax.microedition.media.control.VolumeControl +{ + private static final int MAX_VOLUME = 100; + private static final int UNDEFINED_VOLUME = -1; + + // these constants come from native side + protected static final int NO_ERROR = 0; // native side returns if OK + + private int iLevel; + private boolean iMuted; + + public VolumeControl() + { + iLevel = UNDEFINED_VOLUME; + } + + public boolean isMuted() + { + checkState(); + return iMuted; + } + + public int getLevel() + { + checkState(); + + // If the control is muted the cached volume level is returned + // because the native implemnetation doesn't directly support + // muting. The mute is applied by setting volume level to zero + if (!iMuted) + { + int level = _getLevel(iEventSource, iControlHandle); + if (level < NO_ERROR) + { + throw new Error("getLevel() failed, Symbian OS error: " + level); + } + // Cache the returned volume level due to mute handling + iLevel = level; + } + + return iLevel; + } + + + public int setLevel(int aLevel) + { + checkState(); + int level = aLevel; + + if (level < 0) + { + level = 0; + } + else if (level > MAX_VOLUME) + { + level = MAX_VOLUME; + } + + if (!iMuted) + { + int error = _setLevel(iEventSource, iControlHandle, level); + if (error < NO_ERROR) + { + throw new Error("setLevel() failed, Symbian OS error: " + error); + } + } + iLevel = level; + return level; + } + + public void setMute(boolean aMuted) + { + checkState(); + if (aMuted != iMuted) + { + if (iLevel == UNDEFINED_VOLUME) + { + getLevel(); + } + iMuted = aMuted; + int level = 0; + if (!iMuted) + { + level = iLevel; + } + // else level is 0 + + int error = _setLevel(iEventSource, iControlHandle, level); + if (error < NO_ERROR) + { + throw new Error("setMute() failed, Symbian OS error: " + error); + } + } + } + + private static native int _setLevel(int aEventSource, int aControlHandle, + int aLevel); + private static native int _getLevel(int aEventSource, int aControlHandle); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ConnectorProtocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ConnectorProtocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Protocol used with locators that needs Connector. +* +*/ + + +package com.nokia.microedition.media.protocol; + +import javax.microedition.media.MediaException; + +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ConnectorDataSource; +import com.nokia.microedition.media.ManagerImpl; + +/** + * Protocol used with locators that needs Connector. + */ +public class ConnectorProtocol implements Protocol +{ + /** + * Default constructor. + */ + public ConnectorProtocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + ConnectorDataSource dataSource = new ConnectorDataSource(aLocator); + return ManagerImpl.getInstance().createInternalPlayer(dataSource); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/NativeBase.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/NativeBase.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol; + +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.NativePlayerFactory; +import javax.microedition.media.MediaException; + +/** + * Base class for native based protocols + */ +public class NativeBase implements Protocol +{ + /** + * Protected constructor. + */ + protected NativeBase() + { + } + + /** + * From Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + return NativePlayerFactory.createPlayer(aLocator); + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/OutputStreamWriter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/OutputStreamWriter.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,315 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class gets data from java classes and passes stream +* to CMMASourceStream on C++ side +* +*/ + + +package com.nokia.microedition.media.protocol; + +import java.io.IOException; +import java.io.OutputStream; + +public class OutputStreamWriter extends Thread +{ + /** + * Private helper class to handle case when notify comes before + * wait + */ + private class WaitObject + { + static final int NOTIFIED = 1; + public int iStatus = NO_ERROR; + + public synchronized void doWait() + { + if (iStatus == OutputStreamWriter.NO_ERROR) + { + try + { + super.wait(); + } + catch (InterruptedException ex) + { + iStatus = OutputStreamWriter.GENERAL_ERROR; + } + } + } + + public synchronized void doNotify() + { + super.notify(); + iStatus = NOTIFIED; + } + } + /** + * Size of the buffer (transferred bytes) the same size as in c++ side + */ + private static final int BUFFER_MAXSIZE = 4096; + + /** + * Status code. Negative values are error codes. + * Values >= NO_ERROR are status codes. + */ + private static final int NO_ERROR = 0; + + /** + * Status code. Stream is ended. + */ + private static final int COMPLETED = 2; + + /** + * Status code. Stream is closed. + */ + private static final int CLOSED = -2002; + + /** + * Error status code. + */ + private static final int GENERAL_ERROR = -2003; + + /** + * IO error status code. + */ + private static final int IO_ERROR = -2004; + + /** + * This constant indicates native commit. + */ + private static final int COMMIT = -10000; + + /** + * Stream status. + * >= 0 indicates no error + * < 0 indicates error + */ + private int iStatus = NO_ERROR; + + /** + * Stream where output will be written. + */ + private OutputStream iOutputStream; + + /** + * Native handle. + */ + private int iHandle; + + /** + * Native event source handle. + */ + private int iEventSourceHandle; + + /** + * Used to wait native object to start writing. + */ + private WaitObject iWaitObject = new WaitObject(); + + /** + * Used to wait in commit method until all data is read. + */ + private WaitObject iCommitWaitObject = new WaitObject(); + + /** + * Runnable object that does stream commit. + */ + private Runnable iRunnable; + + /** + * Player handle is needed to check if native player object is deleted. + */ + private int iPlayerHandle; + + /** + * Constructor + * + * @param aOutputStream a Stream to be passed to C++ side + * @param aEventsourceHandle handle to event source + * @param aRunnable is called when native commit is done + * @param aPlayerHandle Used to check if player is already deleted. + */ + public OutputStreamWriter(OutputStream aOutputStream, + int aEventSourceHandle, + Runnable aRunnable, + int aPlayerHandle) + { + iOutputStream = aOutputStream; + iEventSourceHandle = aEventSourceHandle; + iRunnable = aRunnable; + iPlayerHandle = aPlayerHandle; + } + + /** + * Sets handle to native object (CMMAOutputStream) and starts read thread. + * + * @param aHandle handle (CMMAOutputStream) + */ + public void start(int aHandle) + { + if (aHandle <= 0) + { + // Handle must be positive integer. + throw new IllegalArgumentException("Could not start player, " + aHandle); + } + iHandle = aHandle; + start(); + } + + /** + * From Thread + */ + public void run() + { + // buffer for the data copied from native + byte[] buffer = new byte[ BUFFER_MAXSIZE ]; + + // used get read size from native + int[] outputStreamSize = new int[ 1 ]; + + // Wait until native side starts writing or + // stream is closed. + iWaitObject.doWait(); + if (iWaitObject.iStatus != WaitObject.NOTIFIED) + { + // some error has occured + iStatus = iWaitObject.iStatus; + } + // Read data until stream is completed or error occures. + while (iStatus >= NO_ERROR && + iStatus != COMPLETED) + { + // Read data from native. + iStatus = _readData(iHandle, + iEventSourceHandle, + buffer, + outputStreamSize, + BUFFER_MAXSIZE, + iPlayerHandle); + + // Write data to Java stream. + try + { + // Don't write if no bytes was read or error occured + if (outputStreamSize[ 0 ] > 0 && + iStatus >= NO_ERROR) + { + iOutputStream.write(buffer, 0, outputStreamSize[ 0 ]); + } + } + catch (IOException ioe) + { + // Error writing to stream + iStatus = IO_ERROR; + } + catch (Throwable t) + { + // For example when OutputStream is closed + iStatus = IO_ERROR; + } + } + + // Notify object waiting commit to complete. + iCommitWaitObject.doNotify(); + } + + /** + * Close stops run() thread + */ + public void close() + { + iStatus = CLOSED; + // release wait + iWaitObject.doNotify(); + } + + /** + * Close the OutputStream. + * @throws IOException If an I/O error occurs + */ + public void closeStream() throws IOException + { + iOutputStream.close(); + } + + /** + * Wait until all data is written from native side and flush the stream. + */ + public void commit() throws IOException + { + if (iStatus < NO_ERROR) + { + throw new IOException( + "Current recording cannot be completed, Symbian OS error: " + iStatus); + } + iCommitWaitObject.doWait(); + if (iCommitWaitObject.iStatus != WaitObject.NOTIFIED) + { + // error happened in waiting + iStatus = iCommitWaitObject.iStatus; + } + if (iStatus < NO_ERROR) + { + throw new IOException( + "Current recording cannot be completed, Symbian OS error: " + iStatus); + } + iOutputStream.flush(); + iStatus = CLOSED; + } + + /** + * C++ side notifies that data is available. Java makes a byte array + * and passes it to c++ side. Native side fills the byte array. + * + * @param alength native side notifies how many bytes are ready to be read + * @param aStatus Status of the stream reading + * + */ + private void write(int aLength, int aStatus) + { + if (aStatus == COMMIT && iStatus >= NO_ERROR) + { + (new Thread(iRunnable)).start(); + } + else if (this != null && + iStatus >= NO_ERROR) + { + iStatus = aStatus; + + // notify the write-loop that data is available + iWaitObject.doNotify(); + } + } + + /** + * _readData passes c++ side a byte array and native side + * fills it with output stream data. + * + * @param aHandle Handle + * @param aEventSourceHandle Event source + * @param aData byte array for output stream data + * @param aLength length of byte array + * @param aStatus status + * @return return value + */ + static private native int _readData(int aHandle, + int aEventSourceHandle, + byte[] aData, + int[] aOutputStreamSize, + int aLength, + int aPlayerHandle); + +} + +//end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol; + +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.Locator; +import javax.microedition.media.MediaException; + +/** + * Interface for player creation from locator + */ +public interface Protocol +{ + /** + * Creates a new instance of the player from given locator + * @param aLocator Locator for creating Player. + * @return Fully constructed new Player + */ + abstract InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException; +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ProtocolFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ProtocolFactory.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol; + +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.Locator; +import javax.microedition.media.MediaException; + +/** + * Factory for creating the Protocols + */ +public class ProtocolFactory +{ + private Protocol iConnectorProtocol = null; + + public static final String PROTOCOL_CLASS_NAME = ".Protocol"; + public static final String PROTOCOL_BASE_PACKAGE = + "com.nokia.microedition.media.protocol."; + + /** + * Constructor + */ + public ProtocolFactory() + { + iConnectorProtocol = new ConnectorProtocol(); + } + + /** + * Factory method for creating player from locator + * Tries to load assosiated Protocol first, if this fails + * then we try to create player by using Connector + * @param aLocator Media locator + * @return Player according to locator or null if cannot create + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + InternalPlayer player = null; + try + { + Class protocolClass = + Class.forName(PROTOCOL_BASE_PACKAGE + + aLocator.getProtocol() + PROTOCOL_CLASS_NAME); + Protocol protocol = (Protocol)protocolClass.newInstance(); + player = protocol.createPlayer(aLocator); + } + catch (InstantiationException ie) + { + throw new MediaException("Instantiation failed: " + ie); + } + catch (IllegalAccessException iae) + { + throw new MediaException("Illegal access: " + iae); + } + catch (ClassNotFoundException cnfe) + { + // we did not find specified Protocol, trying to create player + // with connector + player = iConnectorProtocol.createPlayer(aLocator); + } + return player; + } +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ProtocolPackage.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/ProtocolPackage.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol; + +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.Locator; +import javax.microedition.media.MediaException; + +/** + * Base class for Protocols those can contain different Protocols + * e.g. "capture" protocol can handle also sub-protocols, depending + * on what type of Player is created. + * This class instantiates those automatically + */ +public class ProtocolPackage implements Protocol +{ + /** + * Protected to allow this class class to be extended. + */ + protected ProtocolPackage() + { + } + + /** + * Implementation from Protocol class, this method will create + * new protocol and call it's createPlayer + * @param aLocator identifies player + * @return new player + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + InternalPlayer player = null; + try + { + Class protocolClass = + Class.forName(ProtocolFactory.PROTOCOL_BASE_PACKAGE + + getProtocolName(aLocator) + "." + + getPackageName(aLocator) + + ProtocolFactory.PROTOCOL_CLASS_NAME); + Protocol protocol = (Protocol)protocolClass.newInstance(); + player = protocol.createPlayer(aLocator); + } + catch (InstantiationException ie) + { + throw new MediaException("Internal error: " + ie); + } + catch (IllegalAccessException iae) + { + throw new MediaException("Internal error: " + iae); + } + catch (ClassNotFoundException cnfe) + { + throw new MediaException("Unable to create Player with locator: " + + aLocator.getLocatorString()); + } + return player; + } + + /** + * Returns the name of the package, this will be used for + * creating sub-protocol with name. e.g. with locator "capture://audio" + * this will return "audio" + * + * This method can be overridden if there is need for returning something else + * than middle part of the locator + * @return Middle part of the locator + */ + protected String getPackageName(Locator aLocator) throws MediaException + { + return aLocator.getMiddlePart(); + } + + /** + * Returns the name of the protocol, this will be used for + * creating sub-protocol with name. e.g. with locator "capture://audio" + * this will return "capture" + * + * This method can be overridden if there is need for returning something else + * than protocol of the locator + * @return Protocol of the locator + */ + protected String getProtocolName(Locator aLocator) throws MediaException + { + return aLocator.getProtocol(); + } + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/SeekThread.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/SeekThread.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Thread that calls SeekControl's seek method. +* +*/ + +package com.nokia.microedition.media.protocol; + +import com.nokia.microedition.media.SeekControl; +import com.nokia.mj.impl.utils.Logger; + +/** + * Thread that calls SeekControl's seek method. + */ +class SeekThread extends Thread +{ + // control to call in run method + final private SeekControl iSeekControl; + + // object to notify when seek is ready + final private Object iWaitObject; + + /** + * Public constructor. + * @param aWwaitObject Object to notify when ready + * @param aSeekControl Control to seek. + */ + public SeekThread(Object aWaitObject, + SeekControl aSeekControl) + { + iWaitObject = aWaitObject; + iSeekControl = aSeekControl; + } + + /** + * From Thread class. + */ + public void run() + { + try + { + iSeekControl.seek(0); + } + catch (Exception e) + { + // If seek fails, stream cannot be read and SeekControl's target + // read must return -1 or throw an exception. + Logger.ELOG(Logger.EJavaMMAPI, + "MMA::SourceStreamReader::read seek exception ", e); + } + + // notify that seek is ready + synchronized (iWaitObject) + { + iWaitObject.notify(); + } + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/SourceStreamReader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/SourceStreamReader.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,290 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: SourceStreamReader gets data from java classes and passes +* stream to CMMASourceStream on C++ side +* +*/ + + +package com.nokia.microedition.media.protocol; + +import java.io.IOException; +import javax.microedition.media.protocol.SourceStream; +import javax.microedition.media.Controllable; +import javax.microedition.media.Control; +import com.nokia.microedition.media.SeekControl; +import com.nokia.microedition.media.InputStreamSeekControl; +import com.nokia.mj.impl.utils.Logger; + +public class SourceStreamReader extends Thread +{ + Thread t1 = null; + // these states are the same in c++ side + private static final int NO_ERROR = 0; + private static final int ERR_GENERAL = -2; // KErrGeneral + private static final int ERR_EOF = -25; // KErrEof + private static final int READ_ALL = -1; + private static final int MORE_DATA = 3; + private static final int COMPLETED = 4; + private static final int CLOSED = -45; // KErrSessionClosed + + // size of the buffer (transferred bytes) + // MMF currently requests data in 4k blocks + private static final int BUFFER_SIZE = 4096; + + private static final String SEEK_CONTROL = "SeekControl"; + + private SourceStream iSourceStream; + private byte[] iBuffer; + private int iLength; // Length of stream c++ requested + private int iHandle; // handle to CMMASourceStream + private int iStatus = NO_ERROR; // source stream status + private int iEventSourceHandle; + private boolean iIsActive; + private int iPlayerHandle; + + private Object iWaitObject = new Object(); + + // DataSource that SourceStream belongs to + private Controllable iControllable; + + /** + * Constructor + * + * @param aSourceStream a Stream to be passed to C++ side + * @param aEventSourceHandle handle to the event source + */ + public SourceStreamReader(SourceStream aSourceStream, + Controllable aControllable, + int aEventSourceHandle, + int aPlayerHandle) + { + iSourceStream = aSourceStream; + iControllable = aControllable; + iEventSourceHandle = aEventSourceHandle; + iBuffer = new byte[ BUFFER_SIZE ]; + iPlayerHandle = aPlayerHandle; + } + + /** + * Sets handle to CMMASourceStream + * + * @param aHandle handle to CMMASourceStream + */ + public void setHandle(int aHandle) + { + iHandle = aHandle; + } + + /** + * Run method for a thread which writes data to C++ + */ + public void run() + { + int length = 0; + do + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run()"); + iStatus = MORE_DATA; + try + { + length = iSourceStream.read(iBuffer, 0, iLength); + } + catch (IOException ioe) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), io exception"); + ioe.printStackTrace(); + iStatus = ERR_GENERAL; + } + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), length = "+length); + if (iStatus == CLOSED) + { + return; + } + // no more data because end of file has been reach + if (length == -1) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"no more data because end of file has been reach"); + iStatus = COMPLETED; + } + // synchronized (iWaitObject) + // { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), calling jni _write"+"status =" + iStatus + "length =" + length); + + int err = _write(iHandle, + iEventSourceHandle, + iBuffer, + length, + iStatus, + iPlayerHandle); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), calling jni _write ret = "+err); + if (err != 0) + { + // error in writing, closing thread + iIsActive = false; + iStatus = CLOSED; + break; + } + // wait for next native read + // try + // { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), calling wait()"); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"Source stream reader run(), calling wait() thread is =" +Thread.currentThread().getName()); + // iWaitObject.wait(); + //} + /*catch (InterruptedException ex) + { + // MIDP's object does not have interrupt + }*/ + // } + } + while (length>0); + } + + /** + * Close stops run() thread + */ + public void close() + { + iIsActive = false; + iStatus = CLOSED; + + // If Controllable has SeekControl it must be closed + Control control = iControllable.getControl(SEEK_CONTROL); + if (control != null) + { + SeekControl sc = (SeekControl)control; + sc.close(); + } + + synchronized (iWaitObject) + { + iWaitObject.notify(); + } + } + + /** + * Resets streams to point start of the media. Player deallocate needs + * this. + */ + public void resetStream() + { + try + { + SeekControl control = (SeekControl)iControllable.getControl(SEEK_CONTROL); + control.seek(0); + } + catch (IOException ioe) + { + // Stream may be broken, we can't do anything for it here. + // It will be noticed by the player when changing state from deallocate + Logger.ELOG(Logger.EJavaMMAPI, + "SourceStreamReader: resetStream: ", ioe); + } + } + + + /** + * Native side request data from Java with read method. + * + * @param aBytes native side notifies how many bytes should be sent to it + * @param aStatus Status of the stream reading + */ + private void read(int aBytes, int aStatus) + { + // Try to read but SourceStream is already completed or closed? + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"SourceStreamReader:: read() , callback detected ,iStatus = "+iStatus+" aBytes = "+aBytes); + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"thread id = "+Thread.currentThread().getName()); + if (iStatus == CLOSED) + { + // Inform the native object; attempting to read pass the end of the stream + _write(iHandle, iEventSourceHandle, new byte[ 0 ], 0, ERR_EOF, iPlayerHandle); + return; + } + + if (aBytes == READ_ALL) + { + iLength = BUFFER_SIZE; + } + else + { + iLength = aBytes; + } + + if (aBytes > iBuffer.length) + { + // native request larger buffer + iBuffer = new byte[ aBytes ]; + } + + if (iStatus == COMPLETED) + { + // Stream is already read ones and need to be seeked to start + Control control = iControllable.getControl(SEEK_CONTROL); + if (control != null) + { + // start new seak thread, thread will notify iWaitObject + // when completed + (new SeekThread(iWaitObject, + (SeekControl)control)).start(); + } + else + { + // stream is not seekable, so informing native object + _write(iHandle, iEventSourceHandle, new byte[ 0 ], 0, + ERR_EOF, iPlayerHandle); + } + } + else if (iIsActive) + { + // notify to while() write -loop that data is requested + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"SourceStreamReader:: read() before sync(iWaitObjet() "); + synchronized (iWaitObject) + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"SourceStreamReader:: read() notifying iWaitObject"); + iWaitObject.notify(); + } + } + else + { + Logger.LOG(Logger.EJavaMMAPI, Logger.EInfo,"SourceStreamReader, creating new Thread"); + iIsActive = true; + t1 = new Thread(this); + t1.start(); + // start(); + } + + } + + + /** + * _write writes data to the C++ side + * + * @param aHandle Handle + * @param aEventSourceHandle EventSourceHandle + * @param aData Source stream + * @param aBytesRead how many bytes is read + * @param aStatus stream status + * @return return value + */ + static private native int _write(int aHandle, + int aEventSourceHandle, + byte[] aData, + int aBytesRead, + int aStatus, + int aPlayerHandle); + +} + +// end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol.capture; + +/** + * Protocol class for handling "capture://" protocol + */ +public class Protocol extends com.nokia.microedition.media.protocol.ProtocolPackage +{ + + /** + * Constructor + */ + public Protocol() + { + }; + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/audio/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/audio/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is capture://audio protocol +* +*/ + + +package com.nokia.microedition.media.protocol.capture.audio; + +import com.nokia.microedition.media.protocol.NativeBase; + +/** + * This class is capture://audio protocol. + */ +public class Protocol extends NativeBase +{ + /** + * Default constructor. + */ + public Protocol() + { + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/devcam0/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/devcam0/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is capture://devcam0 protocol +* +*/ + + +package com.nokia.microedition.media.protocol.capture.devcam0; + +import com.nokia.microedition.media.protocol.NativeBase; + +/** + * This class is capture://devcam0 protocol. + */ +public class Protocol extends NativeBase +{ + /** + * Default constructor. + */ + public Protocol() + { + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/devcam1/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/devcam1/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is capture://devcam1 protocol +* +*/ + + +package com.nokia.microedition.media.protocol.capture.devcam1; + +import com.nokia.microedition.media.protocol.NativeBase; + +/** + * This class is capture://devcam1 protocol. + */ +public class Protocol extends NativeBase +{ + /** + * Default constructor. + */ + public Protocol() + { + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/video/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/capture/video/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is capture://video protocol +* +*/ + + +package com.nokia.microedition.media.protocol.capture.video; + +import com.nokia.microedition.media.protocol.NativeBase; + +/** + * This class is capture://video protocol. + */ +public class Protocol extends NativeBase +{ + /** + * Default constructor. + */ + public Protocol() + { + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.protocol.device; + +/** + * Protocol class for handling "capture://" protocol + */ +public class Protocol extends com.nokia.microedition.media.protocol.ProtocolPackage +{ + + /** + * Constructor + */ + public Protocol() + { + }; + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/midi/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/midi/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is device://midi protocol +* +*/ + + +package com.nokia.microedition.media.protocol.device.midi; + +import com.nokia.microedition.media.protocol.NativeBase; + +/** + * This class is device://midi protocol. + */ +public class Protocol extends NativeBase +{ + /** + * Default constructor. + */ + public Protocol() + { + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/tone/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/device/tone/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,151 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is device://tone protocol +* +*/ + + +package com.nokia.microedition.media.protocol.device.tone; + +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.PlugIn; +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.tone.TonePlayer; +import javax.microedition.media.MediaException; +import javax.microedition.media.Manager; +import java.io.IOException; +import javax.microedition.media.protocol.DataSource; + +/** + * This class is device://tone protocol. This class also implements PlugIn + * interface which is used from ManagerImpl. + */ +public class Protocol + implements com.nokia.microedition.media.protocol.Protocol, + PlugIn +{ + // Used to recognize supported locators. + private static final String TONE_FILE_EXTENSION = ".jts"; + + // Used to get supported protocols. jts supports same protocols than midi. + private static final String MIDI_CONTENT_TYPE = "audio/midi"; + + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + if (aLocator.getParameters() != null) + { + // device://tone may not have properties. + throw new MediaException( + "Could not create player, parameters not supported: " + + aLocator.getParameters()); + } + return new TonePlayer(); + } + + /** + * From PlugIn + */ + public String[] getSupportedContentTypes(String aProtocol) + { + String[] types = new String[ 0 ]; + + if ((aProtocol == null) || + isSupportedProtocol(aProtocol)) + { + types = new String[ 1 ]; + types[ 0 ] = TonePlayer.TONE_CONTENT_TYPE; + } + // else empty array is returned + return types; + } + + /** + * Returns true if protocol is supported. + * @return true if protocol is supported. + */ + private boolean isSupportedProtocol(String aProtocol) + { + // get all supported protocols + String[] protocols = getSupportedProtocols(null); + boolean isSupported = false; + // protocol is supported if it is found from protols array + for (int i = 0; i < protocols.length && + !isSupported; i++) + { + if (protocols[ i ].equals(aProtocol)) + { + isSupported = true; + } + } + return isSupported; + } + + /** + * From PlugIn + */ + public String[] getSupportedProtocols(String aContentType) + { + String[] protocols = new String[ 0 ]; + if ((aContentType == null) || + aContentType.equals(TonePlayer.TONE_CONTENT_TYPE)) + { + // tone and midi supports same protocols. + protocols = Manager.getSupportedProtocols( + MIDI_CONTENT_TYPE); + } + // else empty array is returned + return protocols; + } + + /** + * From PlugIn + */ + public InternalPlayer createPlayer(DataSource aDataSource) + throws MediaException, IOException + { + InternalPlayer player = null; + String contentType = aDataSource.getContentType(); + String locator = aDataSource.getLocator(); + if ((contentType != null && + contentType.equals(TonePlayer.TONE_CONTENT_TYPE)) || + (locator != null && + locator.endsWith(TONE_FILE_EXTENSION))) + { + player = new TonePlayer(aDataSource); + } + return player; + } + + /** + * From PlugIn. Empty implementation. + */ + public void preparePlayer(InternalPlayer aPlayer) throws MediaException + { + // tone does not extend existing players + } +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/file/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/file/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,110 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: file protocol +* +*/ + + +package com.nokia.microedition.media.protocol.file; + +import javax.microedition.media.MediaException; + +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.ManagerImpl; +import com.nokia.microedition.media.NativePlayerFactory; +import com.nokia.microedition.media.ConnectorDataSource; +import com.nokia.microedition.media.tone.TonePlayer; +import javax.microedition.io.file.FileConnection; +import javax.microedition.io.Connector; +import java.io.IOException; + + +/** + * This class presents file protocol + */ +public class Protocol implements + com.nokia.microedition.media.protocol.Protocol +{ + private static final String FILE = "file://"; + private static final String DRM_SUFFIX = "dcf"; + private static final String DRM_PARAMS = "?drm=enc"; + private static final String JTS_SUFFIX = "jts"; + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + FileConnection fileConnection = null; + try + { + if ((aLocator.getParameters() == null) && + (aLocator.getMiddlePart().endsWith(DRM_SUFFIX) + )) + { + // DRM file, adding parameters to locator + fileConnection = (FileConnection)Connector.open(aLocator.getLocatorString(),Connector.READ); + } + else if (aLocator.getMiddlePart().endsWith(JTS_SUFFIX)) + { + // JTS file, this format is handled in Java side, so creating player in traditional way + ConnectorDataSource dataSource = new ConnectorDataSource(aLocator); + return new TonePlayer(dataSource); + } + else + { + fileConnection = (FileConnection)Connector.open(aLocator.getLocatorString(), + Connector.READ); + } + String fileAndPath = getPathAndFileName(fileConnection); + Locator newLocator = new Locator(fileAndPath); + return NativePlayerFactory.createPlayer(newLocator, null); + } + finally + { + if (null != fileConnection) + { + fileConnection.close(); + } + } + } + + /** + * Internal operation to construct path + fileName from the URI of the file. + * Note: This operation removes parameter of the URI just like old + * FileConnectionImpl.getPathAndFileName() operation (used in older releases). + */ + private String getPathAndFileName(FileConnection aFileConn) + { + String path = aFileConn.getPath(); + // Path always starts with '/' character. This has to be skipped away because + // otherwise this is converted to '\\' below. FILE constant contains this first + // character('/') of the path. + path = path.substring(1); + String pathAndFileName = path + aFileConn.getName(); + pathAndFileName = pathAndFileName.replace('/','\\'); + return FILE + pathAndFileName; + } +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/rtsp/Protocol.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/protocol/rtsp/Protocol.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: rtsp protocol +* +*/ + + +package com.nokia.microedition.media.protocol.rtsp; + +import javax.microedition.media.MediaException; + +import com.nokia.microedition.media.Locator; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.protocol.NativeBase; +import com.nokia.mj.impl.media.RTSPPermission; +import com.nokia.mj.impl.rt.support.ApplicationUtils; + +/** + * This class presents rtsp protocol and adds security prompt. + */ +public class Protocol extends NativeBase +{ + private static final String RTSP_CONNECTION_PERMISSION = + "javax.microedition.io.Connector.rtsp"; + + /** + * Default constructor. + */ + public Protocol() + { + } + + /** + * From interface Protocol + * @see Protocol + */ + public InternalPlayer createPlayer(Locator aLocator) + throws java.io.IOException, + MediaException, + java.lang.SecurityException + { + ApplicationUtils appUtils = ApplicationUtils.getInstance(); + RTSPPermission per = new RTSPPermission("network usage"); + appUtils.checkPermission(per); + return super.createPlayer(aLocator); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/BlockEndEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/BlockEndEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence BLOCK_END events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Event processor class for tone sequence BLOCK_END events + */ +public class BlockEndEvent extends Event +{ + BlockEndEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + public int advance(int aPosition) + throws MidiSequenceException, IllegalArgumentException + { + int retVal = doValidate(aPosition); + if (retVal == 0) + { + return 0; + } + // if stack is already empty, we cannot revert back. Thus + // this BLOCK_END must be invalid + if (iReturnPositionStack.empty()) + { + throw new IllegalArgumentException("Illegal BLOCK_END"); + } + // If valid, go back to last position before entering block + int lastPos = ((Integer)iReturnPositionStack.pop()).intValue(); + retVal = lastPos - aPosition; + return retVal; + } + + /** + * Child class defined functionality for validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + int type = iSequence[ aPosition ]; + int data = iSequence[ aPosition + 1 ]; + int retVal = 0; + + if (type == ToneControl.BLOCK_END) + { + leaveBlock(data); // fails if block number is incorrect + retVal = EVENT_SIZE; + } + return retVal; + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, BlockStart, PlayBlock, Volume, Repeat + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + throw new IllegalArgumentException( + "Validation failed, invalid position found in sequence"); + } + + if (type >= ToneControl.SILENCE || + type == ToneControl.BLOCK_START || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + + throw new IllegalArgumentException( + "Illegal event found; sequence is corrupted"); + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/BlockStartEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/BlockStartEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence BLOCK_START events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Event processor class for tone sequence BLOCK_START events + */ +public class BlockStartEvent extends Event +{ + BlockStartEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + public int advance(int aPosition) + throws MidiSequenceException, IllegalArgumentException + { + return doValidate(aPosition); + } + + /** + * Child class defined functionality for validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + int type = iSequence[ aPosition ]; + int data = iSequence[ aPosition + 1 ]; + int retVal = 0; + + if (type == ToneControl.BLOCK_START) + { + if (data > MidiToneConstants.TONE_MAX_BLOCK || + data < MidiToneConstants.TONE_MIN_BLOCK) + { + throw new IllegalArgumentException( + "Illegal sequence, block number not in range, valid range is 0 <= tempo <= 127"); + } + enterBlock(data); + retVal = EVENT_SIZE; + } + return retVal; + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, PlayBlock, Volume, Repeat + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + throw new IllegalArgumentException( + "Validation failed, invalid position found in sequence"); + } + + if (type >= ToneControl.SILENCE || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + throw new IllegalArgumentException( + "Illegal event found; sequence is corrupted"); + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/Event.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/Event.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,198 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Base class for tone event processors +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; +import java.util.Stack; +import java.util.Hashtable; +import com.nokia.mj.impl.utils.Logger; + + +/** + * Base class for tone event processors + */ +public abstract class Event +{ + // CONSTANTS + + /* Size of single tone event in bytes */ + public static final byte EVENT_SIZE = 2; + + // MEMBER DATA + + /* Hold original tone sequence bytes */ + protected byte[] iSequence; + + /* Holds the new tone sequence converted to MIDI */ + protected MidiSequence iMidiSequence; + + /* Holds block position index in iSequence associated with block + number as key. Both are Integer. */ + protected static Hashtable iBlocksHashtable; + + /* Stack for tone event processors. Used by the method advance. */ + protected static Stack iReturnPositionStack; + + /* Current block number holder for validating blocks. If not in any + block, the value is -1. Manipulated by accessor methods. */ + private static Stack iCurrentBlockNumStack; + + /* Defines which event types (byte code) are accepted after this event. + List is very probably overridden by child events. Defaults to none. */ +// protected int[] ACCEPTED_EVENTS = {}; + + // Static initialization + static + { + iBlocksHashtable = new Hashtable(); + iReturnPositionStack = new Stack(); + iCurrentBlockNumStack = new Stack(); + } + + protected Event(byte[] aSequence, MidiSequence aMidiSequence) + { + iSequence = aSequence; + iMidiSequence = aMidiSequence; + } + + /** + * Reset events for reuse + */ + public void reset() + { + if (!iReturnPositionStack.empty()) + { + iReturnPositionStack = new Stack(); + } + if (!iBlocksHashtable.isEmpty()) + { + iBlocksHashtable = new Hashtable(); + } + if (!iCurrentBlockNumStack.isEmpty()) + { + iCurrentBlockNumStack = new Stack(); + } + } + + /** + * Process events step by step. Does not validate and does not go + * through whole sequence, but only those positions that are + * needed for playing. + * @param aPosition position where to process + * @return int offset of position after processing, relative to aPosition. + * If zero, no processing has happened. + */ + public abstract int advance(int aPosition) + throws MidiSequenceException, IllegalArgumentException; + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected abstract int doValidate(int aPosition) + throws IllegalArgumentException; + + /** + * Validate sequence step by step. Does not process events, but can do + * initialization along validation. Validation includes: Check event + * type, parameters and that next event type after this one is allowed + * to be there. + * @param aPosition position where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + public int validate(int aPosition) + throws IllegalArgumentException + { + int nextPos = 0; + try + { + nextPos = doValidate(aPosition); + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + Logger.WLOG(Logger.EJavaMMAPI, "MMA: Event: validate: AIOOBE"); + // just return + return nextPos; + } + + if (nextPos < 0) + { + // doValidate must never return negative value + throw new Error(); + } + + if (nextPos != 0) + { + // check that event type in next position is allowed + checkEventAtNextPosition(aPosition + nextPos); + } + return nextPos; + } + + /** + * Check whether event or end of sequence at next position + * is legal after this type of event. Throws + * IllegalArgumentException if not accepted. + * @param aPosition position of next event + */ + + protected abstract void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException; + + /** + * Called when entering a block. + * @param aBlockNum number of block to enter + */ + protected void enterBlock(int aBlockNum) + { + iCurrentBlockNumStack.push(new Integer(aBlockNum)); + } + + /** + * Called when leaving a block. + * @param aBlockNum number of block to leave + * @exception IllegalArgumentException if aBlockNum does not + * correspond to last block entered or if no block has been + * entered. + */ + protected void leaveBlock(int aBlockNum) throws IllegalArgumentException + { + if (iCurrentBlockNumStack.isEmpty()) + { + Logger.ELOG(Logger.EJavaMMAPI, + "MMA: Event: leaveBlock: Not inside block, IAE"); + throw new IllegalArgumentException( + "Illegal Sequence, invalid block number found"); + } + + if (aBlockNum != + (((Integer)iCurrentBlockNumStack.pop()).intValue())) + { + Logger.ELOG(Logger.EJavaMMAPI, + "MMA: Event: leaveBlock: Incorrect block number, IAE"); + throw new IllegalArgumentException( + "Illegal Sequence, invalid block number found"); + } + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/EventList.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/EventList.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,136 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is holder/handler for other event types +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; +import java.util.Vector; +import java.util.Enumeration; + +/** + * This class is holder/handler for other event types + */ +public class EventList extends Event +{ + + // CONSTANTS + + private static final int EVENT_PROCESSOR_COUNT = 6; + + // MEMBERS + + private Vector iEvents; + + EventList(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + + iEvents = new Vector(EVENT_PROCESSOR_COUNT); + + iEvents.addElement( + new ToneEvent(aSequence, aMidiSequence)); + iEvents.addElement( + new BlockStartEvent(aSequence, aMidiSequence)); + iEvents.addElement( + new BlockEndEvent(aSequence, aMidiSequence)); + iEvents.addElement( + new PlayBlockEvent(aSequence, aMidiSequence)); + iEvents.addElement( + new RepeatEvent(aSequence, aMidiSequence)); + iEvents.addElement( + new VolumeEvent(aSequence, aMidiSequence)); + } + + public int advance(int aPosition) throws MidiSequenceException + { + // first check that we have at least two bytes left in iSequence + // in aPosition. + if (iSequence.length - aPosition < EVENT_SIZE) + { + // return with 0 if end of sequence is reached + return 0; + } + + Event event = null; + int retVal = 0; + + for (Enumeration e = iEvents.elements(); e.hasMoreElements();) + { + event = (Event)e.nextElement(); + retVal = event.advance(aPosition); + if (retVal != 0) + { + return retVal; + } + } + // if none of event processors accepts data at current position, + // parameter data is illegal. + throw new IllegalArgumentException("Illegal event found, sequence is corrupted"); + } + + + /** + * Inherited from Event. + * Special definition for validate. EventList is the main + * class performing the actual validation and is thus + * excempt from the usual validation process. + * @param aPosition position to validate + */ + public int validate(int aPosition) + throws IllegalArgumentException + { + Event event = null; + int retVal = 0; + for (Enumeration e = iEvents.elements(); e.hasMoreElements();) + { + event = (Event)e.nextElement(); + retVal = event.validate(aPosition); + if (retVal != 0) + { + return retVal; + } + } + // if none of event processors accepts data at current position, + // parameter data is illegal. + throw new IllegalArgumentException("Illegal event found, sequence is corrupted"); + } + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + throw new Error("Illegal validation call"); + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + throw new Error("Illegal validation call"); + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiSequence.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiSequence.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,446 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class represents midi sequence +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; +import java.io.ByteArrayOutputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +/** + * This class represents midi sequence + */ +public class MidiSequence +{ + // CONSTANTS + + /* Value of minute expressed as microseconds */ + private static final int MINUTE_AS_MICROSECONDS = 60000000; + + /* MIDI events track stream granularity */ + private static final int MIDI_EVENTS_TRACK_GRANULARITY = 100; + + // MIDI constants + + /* Note value used for silence events. This will not be audible */ + public static final byte MIDI_SILENCE_NOTE = 0; + + // MIDI file constants + + /* Maximum length of midi sequence events. After this has been + met, no new events are accepted by writeMidiEvent. This is not + a hard limit anyway (may be exceeded by the last written event), + so it's only here to guard memory use and possible infinite + sequence */ + + private static final int MIDI_EVENTS_MAX_BYTE_COUNT = 32768; + + /* Length of MIDI file header. This includes following: + MThd block id, MThd length, midi format, MTrk chunk amount and PPQN */ + private static final byte FILE_HEADER_LENGTH = 14; + + /* Length of MTrk block. This includes: MTrk block id, MTrk length */ + private static final byte MTRK_HEADER_LENGTH = 8; + + /* Length of MIDI track header. This includes: + tempo change, tempo value, program change */ + private static final int TRACK_HEADER_LENGTH = 10; + + /* Length of MIDI track trailer */ + private static final int TRACK_TRAILER_LENGTH = 4; + + // MIDI file header constants + + /* Header block for MThd */ + private static final byte[] MIDI_HEADER_MTHD = + { 0x4D, 0x54, 0x68, 0x64 }; + + /* Header block for MThd block length; value is 6 */ + private static final byte[] MIDI_HEADER_MTHD_LENGTH = + { 0x00, 0x00, 0x00, 0x06 }; + + /* Header block for used MIDI format; format is 0 */ + private static final byte[] MIDI_HEADER_MIDI_FORMAT = + { 0x00, 0x00 }; + + /* Header block for amount of MTrk blocks used */ + private static final byte[] MIDI_HEADER_MTRK_CHUNK_AMOUNT = + { 0x00, 0x01 }; + + /* Value for first byte in PPQN block in midi file header */ + private static final byte MIDI_HEADER_PPQN_FIRST_BYTE = 0x00; + + // MIDI track constants + + /* Header block for MTrk */ + private static final byte[] MIDI_HEADER_MTRK = + { 0x4D, 0x54, 0x72, 0x6B }; + + /* Tempo change command. Includes delta time ( 0x00 ) + and command (0xFF5103) */ + private static final byte[] TRACK_HEADER_TEMPO_CHANGE = + { 0x00, (byte)0xFF, 0x51, 0x03 }; + + /* Track end meta event */ + private static final byte[] TRACK_TRAILER = + { 0x00, (byte)0xFF, 0x2F, 0x00 }; + + /* Length of single midi event without the variable length + delta time */ + private static final int MIDI_EVENT_COMMAND_LENGTH = 3; + + /* Channel mask for setting correct channel in writeMidiEvent */ + private static final byte MIDI_EVENT_CHANNEL_MASK = (byte)0xF0; + + /* Maximum value for midi variable length quantity */ + private static final int MIDI_VARIABLE_LENGTH_MAX_VALUE = 0x0FFFFFFF; + + // Tone constants + + /* Tone resolution is expressed in pulses per full note, whereas + midi resolution is pulses per quarter note. Thus we must divide tone + empo by 4. For tone, 64 is considered default */ + private static final byte TONE_DEFAULT_RESOLUTION = 64; // 64/4 = 16(ppqn) + + /* Default tempo for tone is 30. For bpm value it is multiplied by 4 */ + private static final byte TONE_DEFAULT_TEMPO = 30; // 4*30 = 120 (bpm) + + /* Tone multiplier is used for both dividing resolution and multiplying + tempo to get equivalent midi values */ + private static final byte TONE_MULTIPLIER = 1; + + // MEMBER DATA + + /* Midi channel for generated MIDI sequence */ + private byte iChannel; + + /* Tempo in MIDI terms */ + private int iTempo; + + /* Resolution in MIDI terms */ + private int iResolution; + + /* Instrument used to represent tone */ + private byte iInstrument; + + /* Counter for written midi events */ + private int iMidiEventsByteCount; + + /* MIDI sequence written using writeEvent( ) */ + private ByteArrayOutputStream iMidiTrackEvents; + + /* Tone sequence duration */ + private int iDuration; + + /** + * Constructor + * @param aChannel MIDI channel which is assigned to generate track + * @param aInstrument Instrument used to represent tone + */ + MidiSequence(byte aChannel, byte aInstrument) + { + iChannel = aChannel; + iInstrument = aInstrument; + iTempo = TONE_DEFAULT_TEMPO * TONE_MULTIPLIER; + iResolution = TONE_DEFAULT_RESOLUTION / TONE_MULTIPLIER; + iMidiTrackEvents = new ByteArrayOutputStream( + MIDI_EVENTS_TRACK_GRANULARITY); + } + + /** + * Get midi stream + */ + public ByteArrayInputStream getStream() throws IOException + { + iMidiTrackEvents.flush(); + byte[] midiTrackEvents = iMidiTrackEvents.toByteArray(); + ByteArrayOutputStream concateStream = + new ByteArrayOutputStream( + FILE_HEADER_LENGTH + + MTRK_HEADER_LENGTH + + TRACK_HEADER_LENGTH + + midiTrackEvents.length + + TRACK_TRAILER_LENGTH); + + writeHeader(concateStream, midiTrackEvents.length); + concateStream.write(midiTrackEvents); + writeTrailer(concateStream); + + ByteArrayInputStream midi = new ByteArrayInputStream( + concateStream.toByteArray()); + + concateStream.close(); + return midi; + } + + /** + * Get midi file data as byte[] + */ + public byte[] getByteArray() throws IOException + { + iMidiTrackEvents.flush(); + byte[] midiTrackEvents = iMidiTrackEvents.toByteArray(); + ByteArrayOutputStream concateStream = + new ByteArrayOutputStream( + FILE_HEADER_LENGTH + + MTRK_HEADER_LENGTH + + TRACK_HEADER_LENGTH + + midiTrackEvents.length + + TRACK_TRAILER_LENGTH); + + writeHeader(concateStream, midiTrackEvents.length); + concateStream.write(midiTrackEvents); + writeTrailer(concateStream); + + byte[] midi = concateStream.toByteArray(); + concateStream.close(); + return midi; + } + + /** + * Set tempo + * @param aTempo tempo in tone sequence terms + */ + public void setTempo(int aTempo) + { + if (aTempo < MidiToneConstants.TONE_TEMPO_MIN || + aTempo > MidiToneConstants.TONE_TEMPO_MAX) + { + throw new IllegalArgumentException("Tempo is out of range, " + + "valid range is 5 <= tempo <= 127"); + } + iTempo = aTempo * TONE_MULTIPLIER; + } + + /** + * Set resolution + * @param aResolution resolution in tone sequence terms + */ + public void setResolution(int aResolution) + { + if (aResolution < MidiToneConstants.TONE_RESOLUTION_MIN || + aResolution > MidiToneConstants.TONE_RESOLUTION_MAX) + { + throw new IllegalArgumentException("Resolution is out of range, " + + "valid range is 1 <= resolution <= 127"); + } + iResolution = aResolution / TONE_MULTIPLIER; + } + + /* + * Write midi event to stream. This method writes both variable length + * delta time and midi event. + * @param aLength time between last event and this event (delta time) + * @param aCommand MIDI command byte + * @param aEvent First MIDI command parameter + * @param aData Second MIDI command parameter + */ + public void writeMidiEvent(int aLength, + byte aCommand, + byte aEvent, + byte aData) + throws MidiSequenceException + { + if (iMidiEventsByteCount > MIDI_EVENTS_MAX_BYTE_COUNT) + { + throw new MidiSequenceException(); + } + iMidiEventsByteCount += writeVarLen(iMidiTrackEvents, aLength); + + // Write down cumulative count of event lengths (sum will + // make up duration of this midi sequence. Only audible events + // are counted, which means only those delta times which + // are associated to NOTE_OFF events + if (aCommand == MidiToneConstants.MIDI_NOTE_OFF) + { + iDuration += aLength; + } + + // attach correct channel number + aCommand &= MIDI_EVENT_CHANNEL_MASK; + aCommand |= iChannel; + + iMidiTrackEvents.write(aCommand); + iMidiTrackEvents.write(aEvent); + iMidiTrackEvents.write(aData); + iMidiEventsByteCount += MIDI_EVENT_COMMAND_LENGTH; + } + + /** + * Write time interval value as MIDI variable length data to byte array. + * @param aOut output stream + * @param aValue time before the event in question happens, relative to + * current time. Must be between 0 and 0x0FFFFFFF + */ + private int writeVarLen(ByteArrayOutputStream aOut, int aValue) + { + if ((aValue > MIDI_VARIABLE_LENGTH_MAX_VALUE) || (aValue < 0)) + { + throw new IllegalArgumentException("Input(time) value is not within range"); + } + + // Variable to hold count of bytes written to output stream. + // Value range is 1-4. + int byteCount = 0; + + // variable length quantity can any hold unsigned integer value which + // can be represented with 7-28 bits. It is written out so that 7 low + // bytes of each byte hold part of the value and 8th byte indicates + // whether it is last byte or not (0 if is, 1 if not). Thus a variable + // length quantity can be 1-4 bytes long. + + int buffer = aValue & 0x7F; // put low 7 bytes to buffer + + // check if bits above 7 first are significant, 7 bits at time. If + // they are, buffer is shifted 8 bits left and the new 7 bits are + // appended to beginning of buffer. The eigth byte from right is + // set 1 to indicate that that there is at least another 7 bits + // on left (bits 9-15) which are part of the quantity. + + // Example. Integer 00000100 11111010 10101010 01010101 + // 1) Set low 7 bytes to buffer => 1010101 + // 2) Check if there is more significant bytes in the integer. If + // is, continue. + // 3) Shift buffer 8 left => 1010101 00000000 + // 4) Append next 7 bytes to beginning of buffer + // buffer => 1010101 01010100 + // 5) Set 8th bit 1 to indicate that there is another 7 bits on left + // buffer => 1010101 11010100 + // 6) repeat from step 2 + + aValue >>= 7; + while (aValue != 0) + { + buffer <<= 8; + buffer |= ((aValue & 0x7F) | 0x80); + aValue >>= 7; + } + + // write the buffer out as 1-4 bytes. + while (true) + { + aOut.write(buffer); + byteCount++; + + // check if the indicator bit (8th) is set. + // If it is, continue writing. + int tempBuf = buffer & 0x80; + if (tempBuf != 0) + { + buffer >>= 8; + } + else + { + break; + } + } + return byteCount; + } + + /** + * Writes midi header + * @param aOut output stream + * @param aMidiEventsLength lenght of midi event content in bytes + */ + private void writeHeader( + ByteArrayOutputStream aOut, + int aMidiEventsLength) + throws IOException + { + // MIDI FILE HEADER + + // write 'MThd' block id + aOut.write(MIDI_HEADER_MTHD); + + // write MThd block length + aOut.write(MIDI_HEADER_MTHD_LENGTH); + + // write midi format; format is 0 + aOut.write(MIDI_HEADER_MIDI_FORMAT); + + // write MTrk chunk amount; only one track + aOut.write(MIDI_HEADER_MTRK_CHUNK_AMOUNT); + + // write PPQN resolution (pulses per quarternote) + aOut.write(MIDI_HEADER_PPQN_FIRST_BYTE); + aOut.write(iResolution); + + // MTrk HEADER + + // write 'MTrk' for the only track + aOut.write(MIDI_HEADER_MTRK); + + // calculate real track length + int trackLength = TRACK_HEADER_LENGTH + + aMidiEventsLength + + TRACK_TRAILER_LENGTH; + + // write track length in bytes. + // Literal numeric values (24,16,8) indicate shift offset in bits + // 0xFF is used to mask out everything but the lowest byte. + aOut.write((trackLength >> 24) & 0xFF); + aOut.write((trackLength >> 16) & 0xFF); + aOut.write((trackLength >> 8) & 0xFF); + aOut.write(trackLength & 0xFF); + + // TRACK HEADER + + // write tempo change at beginning + aOut.write(TRACK_HEADER_TEMPO_CHANGE); + + // calculate tempo in microseconds per quarter note + int mpqn = MINUTE_AS_MICROSECONDS / iTempo; + + // write tempo value + // Literal numeric values (16,8) indicate shift offset in bits + // 0xFF is used to mask out everything but the lowest byte. + aOut.write((mpqn >> 16) & 0xFF); + aOut.write((mpqn >> 8) & 0xFF); + aOut.write(mpqn & 0xFF); + + // change program at beginning (at delta time 0) + writeVarLen(aOut, 0); + aOut.write((byte)(MidiToneConstants.MIDI_PROGRAM_CHANGE | iChannel)); + aOut.write(iInstrument); // instrument number + } + + /** + * Write midi trailer + * @param aOut output stream + */ + private void writeTrailer(ByteArrayOutputStream aOut) throws IOException + { + aOut.write(TRACK_TRAILER); + } + + /** + * Return duration accumulated so far. + * @return long duration in microseconds + */ + public long getCumulativeDuration() + { + // duration * seconds in minute * microseconds in second / + // (resolution * tempo) + long duration = (long)iDuration * 60 * 1000000 / (iResolution * iTempo); + return duration; + } + + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiSequenceException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiSequenceException.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,27 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Exception class for internal use +* +*/ + + +package com.nokia.microedition.media.tone; + +/** + * Exception class for internal use + */ +public class MidiSequenceException extends Exception +{ + +} // end of class \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiToneConstants.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/MidiToneConstants.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,105 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Midi and tone related constants +* +*/ + + +package com.nokia.microedition.media.tone; + +/** + * MIDI and tone related common constants + */ +public class MidiToneConstants +{ + // Fully qualified name for ToneControl + public static final String TONE_CONTROL_FULL_NAME = + "javax.microedition.media.control.ToneControl"; + + // Fully qualified name for MIDIControl + public static final String MIDI_CONTROL_FULL_NAME = + "javax.microedition.media.control.MIDIControl"; + + // MIDI constants + + // Note on message ID + public static final byte MIDI_NOTE_ON = (byte)0x90; + + // Note off message ID + public static final byte MIDI_NOTE_OFF = (byte)0x80; + + // Control change message ID + public static final byte MIDI_CONTROL_CHANGE = (byte)0xB0; + + // Program change message ID + public static final byte MIDI_PROGRAM_CHANGE = (byte)0xC0; + + // MIDI Main volume control ID for control change message + public static final byte MIDI_CONTROL_MAIN_VOLUME = 0x07; + + // MIDI velocity for tone notes + public static final byte MIDI_MAX_VELOCITY = 127; + public static final byte MIDI_MIN_VELOCITY = 0; + + // Maximum and minimum MIDI volume values + public static final byte MIDI_MAX_VOLUME = 127; + public static final byte MIDI_MIN_VOLUME = 0; + + // Maximum and minimum MIDI volume values + public static final byte MIDI_MAX_TONE = 127; + public static final byte MIDI_MIN_TONE = 0; + + // MIDI instrument used to play tone events + public static final byte MIDI_TONE_INSTRUMENT = 39; + + // MIDI bank for instrument used to play tone events + public static final byte MIDI_TONE_BANK = -1; + + // MIDI channel used to play tone events + public static final byte MIDI_TONE_CHANNEL = 0; + + // Tone MidiToneConstants + + // Maximum and minimum tone volume values + public static final byte TONE_MAX_VOLUME = 100; + public static final byte TONE_MIN_VOLUME = 0; + + // Maximum and minimum tone note values + public static final byte TONE_MAX_NOTE = 127; + public static final byte TONE_MIN_NOTE = 0; + + // Maximum and minimum block number values + public static final byte TONE_MAX_BLOCK = 127; + public static final byte TONE_MIN_BLOCK = 0; + + /* Minimum and maximum values for note duration */ + public static final int TONE_SEQUENCE_NOTE_MAX_DURATION = 127; + public static final int TONE_SEQUENCE_NOTE_MIN_DURATION = 1; + + /* Minimun tone sequence length */ + public static final int TONE_SEQUENCE_MIN_LENGTH = 4; + + /* Supported tone version number */ + public static final int TONE_SEQUENCE_SUPPORTED_VERSION = 1; + + /* Minimum and maximum tone tempo values */ + public static final int TONE_TEMPO_MIN = 5; + public static final int TONE_TEMPO_MAX = 127; + + /* Minimum and maximum tone resolution values */ + public static final int TONE_RESOLUTION_MIN = 1; + public static final int TONE_RESOLUTION_MAX = 127; + + +} // end of class \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/PlayBlockEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/PlayBlockEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,138 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence PLAY_BLOCK events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Processor for play block events + */ +public class PlayBlockEvent extends Event +{ + + // CONSTANTS + + /* Maximum and minimum values for block number */ + public static final int PLAY_BLOCK_MAX_VALUE = 127; + public static final int PLAY_BLOCK_MIN_VALUE = 0; + + PlayBlockEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + /** + * Inherited from Event + */ + public int advance(int aPosition) + { + int retVal = doValidate(aPosition); + if (retVal != 0) + { + // Push the position to stack that is going to be + // played after this play block has completed + iReturnPositionStack.push(new Integer(aPosition + EVENT_SIZE)); + + int data = iSequence[ aPosition + 1 ]; + retVal = findBlock(data) - aPosition; + } + return retVal; + } + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + // it is already checked that there is at least two bytes left + int type = iSequence[ aPosition ]; + int data = iSequence[ aPosition + 1 ]; + int retVal = 0; + + if (type == ToneControl.PLAY_BLOCK) + { + if (data < PLAY_BLOCK_MIN_VALUE || + data > PLAY_BLOCK_MAX_VALUE) + { + throw new IllegalArgumentException( + "Block number out of range"); + } + findBlock(data); // for check only + retVal = EVENT_SIZE; + } + return retVal; + } + + /** + * Find block + * @param block number + * @return position of corresponding BLOCK_START event + * @exception IllegalArgumentException if block is not found + */ + private int findBlock(int aBlockNumber) + { + for (int i = 0; i < iSequence.length; i += EVENT_SIZE) + { + if (iSequence[ i ] == ToneControl.BLOCK_START && + iSequence[ i + 1 ] == aBlockNumber) + { + return i; + } + } + // if block is not found, input is illegal + throw new IllegalArgumentException("No block found, sequence is corrupted"); + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, BlockEnd PlayBlock, Volume, Repeat or end of sequence + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + return; // end of sequence is OK + } + + + if (type >= ToneControl.SILENCE || + type == ToneControl.BLOCK_END || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + throw new IllegalArgumentException("Illegal event found, sequence is corrupted"); + } +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/PlayToneImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/PlayToneImpl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Manager.playTone implementation +* +*/ + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.Manager; +import javax.microedition.media.Player; +import javax.microedition.media.PlayerListener; +import javax.microedition.media.control.ToneControl; +import javax.microedition.media.MediaException; +import java.io.IOException; +import java.io.ByteArrayInputStream; +import java.util.Vector; + +/** + * Manager.playTone implementation + * + */ +public class PlayToneImpl implements PlayerListener +{ + + // MEMBERS + private static final String TONE_SEQUENCE_CONTENT_TYPE = "audio/x-tone-seq"; + private static final int TONE_SEQUENCE_VERSION = 1; + private static final int TONE_SEQUENCE_RESOLUTION = 64; + private static final int TONE_SEQUENCE_TEMPO = 30; + private static final int DURATION_DIVIDE = 240000; + private static final String CANNOT_PLAY_TONE = "Cannot play tone"; + + // Holds tone players + private Vector iPlayers = new Vector(); + + /** + * Constructor + */ + public PlayToneImpl() + { + } + + /** + * Play tone. + * @see javax.microedition.media.Manager.playTone() + */ + synchronized public void playTone(int aNote, int aDuration, int aVolume) + throws MediaException + { + if (aVolume < MidiToneConstants.TONE_MIN_VOLUME) + { + aVolume = MidiToneConstants.TONE_MIN_VOLUME; + } + else if (aVolume > MidiToneConstants.TONE_MAX_VOLUME) + { + aVolume = MidiToneConstants.TONE_MAX_VOLUME; + } + + if (aNote > MidiToneConstants.TONE_MAX_NOTE || + aNote < MidiToneConstants.TONE_MIN_NOTE) + { + throw new IllegalArgumentException("Note is out of range, " + + "valid range is 0 <= Note <= 127"); + } + + if (aDuration <= 0) + { + throw new IllegalArgumentException("Duration must be positive"); + } + + int duration = aDuration * TONE_SEQUENCE_RESOLUTION * + TONE_SEQUENCE_TEMPO / DURATION_DIVIDE; + + if (duration < MidiToneConstants.TONE_SEQUENCE_NOTE_MIN_DURATION) + { + duration = MidiToneConstants.TONE_SEQUENCE_NOTE_MIN_DURATION; + } + else if (duration > MidiToneConstants.TONE_SEQUENCE_NOTE_MAX_DURATION) + { + duration = MidiToneConstants.TONE_SEQUENCE_NOTE_MAX_DURATION; + } + + byte[] sequence = + { + ToneControl.VERSION, TONE_SEQUENCE_VERSION, + ToneControl.TEMPO, TONE_SEQUENCE_TEMPO, + ToneControl.RESOLUTION, TONE_SEQUENCE_RESOLUTION, + ToneControl.SET_VOLUME, (byte)aVolume, + (byte)aNote, (byte)duration + }; + + Player p = null; + try + { + p = Manager.createPlayer( + new ByteArrayInputStream(sequence), + TONE_SEQUENCE_CONTENT_TYPE); + } + catch (IOException ioe) + { + iPlayers.removeElement(p); + throw new MediaException(CANNOT_PLAY_TONE + " " + ioe.getMessage()); + } + + p.addPlayerListener(this); + iPlayers.addElement(p); + try + { + p.start(); + } + catch (MediaException me) + { + iPlayers.removeElement(p); + throw me; + } + } + + /** + * @see javax.microedition.media.PlayerListener.playerUpdate() + */ + public void playerUpdate(Player aPlayer, java.lang.String aEvent, + java.lang.Object aEventData) + { + if ((aEvent == END_OF_MEDIA) || (aEvent == ERROR)) + { + aPlayer.close(); + iPlayers.removeElement(aPlayer); + } + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/RepeatEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/RepeatEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence REPEAT events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Event processor class for tone sequence REPEAT events + */ +public class RepeatEvent extends Event +{ + + // CONSTANTS + + /* Maximum and minimum tone repeat multiplier values */ + public static final int REPEAT_MIN_MULTIPLIER = 2; + public static final int REPEAT_MAX_MULTIPLIER = 127; + + /** + * RepeatEvent constructor + * @param aSequence tone sequence byte array (input) + * @param aMidiSequence midi sequence object where to output midi events. + */ + + RepeatEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + /** + * Inherited from Event + */ + public int advance(int aPosition) + throws MidiSequenceException + { + // it is already checked that there is at least two bytes left + byte type = iSequence[ aPosition ]; + byte data = iSequence[ aPosition + 1 ]; + int retVal = doValidate(aPosition); + if (retVal == 0) + { + return 0; + } + for (int i = 0; i < data; i++) + { + retVal = ToneEvent.staticAdvance(aPosition + EVENT_SIZE, + iSequence, + iMidiSequence); + // This would go unnoticed if not checked here. + if (retVal == 0) + { + throw new IllegalArgumentException( + "Illegal sequence, processing events for playing failed"); + } + retVal = EVENT_SIZE + EVENT_SIZE; + } + return retVal; + } + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + byte type = iSequence[ aPosition ]; + byte data = iSequence[ aPosition + 1 ]; + int retVal = 0; + if (type == ToneControl.REPEAT) + { + if (data < REPEAT_MIN_MULTIPLIER || data > REPEAT_MAX_MULTIPLIER) + { + throw new IllegalArgumentException( + "Repeat multiplier out of range, valid range is 2 <= multiplier <= 127"); + } + + // Check that there is two more bytes available + if (iSequence.length - (aPosition + EVENT_SIZE) < EVENT_SIZE) + { + throw new IllegalArgumentException( + "Illegal ToneControl.REPEAT event, " + + "there should be two more bytes available after REPEAT event"); + } + retVal = EVENT_SIZE + EVENT_SIZE; + } + return retVal; + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, BlockEnd, PlayBlock, Volume, Repeat or + // end of sequence + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + return; // end of sequence is ok for this event + } + + if (type >= ToneControl.SILENCE || + type == ToneControl.BLOCK_END || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + + throw new IllegalArgumentException( + "Illegal event found; sequence is corrupted"); + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/ToneEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/ToneEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,183 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence audible note events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Event processor class for tone sequence note events (both audible & silent) + */ +public class ToneEvent extends Event +{ + /** + * ToneEvent constructor + * @param aSequence tone sequence byte array (input) + * @param aMidiSequence midi sequence object where to output midi events. + */ + ToneEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + /** + * Inherited from Event + */ + public int advance(int aPosition) + throws MidiSequenceException + { + return staticAdvance(aPosition, iSequence, iMidiSequence); + } + + /** + * Static version of advance( ) to be used by RepeatEvent + */ + public static int staticAdvance(int aPosition, + byte[] aToneSequence, + MidiSequence aMidiSequence) + throws MidiSequenceException + { + int retVal = doStaticValidate(aPosition, aToneSequence); + if (retVal == 0) + { + return 0; + } + // it is already checked that there is at least two bytes left + byte type = aToneSequence[ aPosition ]; + byte data = aToneSequence[ aPosition + 1 ]; + + if (type == ToneControl.SILENCE) + { + retVal = processToneEvent(type, data, true, aMidiSequence); + } + else if (type >= MidiToneConstants.TONE_MIN_NOTE && + type <= MidiToneConstants.TONE_MAX_NOTE) + { + retVal = processToneEvent(type, data, false, aMidiSequence); + } + return retVal; + } + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + return doStaticValidate(aPosition, iSequence); + } + + /** + * Implementation for doValidate, for static context. + * @param aPosition position where to validate + * @param aToneSequence sequence which to validate + */ + private static int doStaticValidate(int aPosition, byte[] aToneSequence) + { + byte type = aToneSequence[ aPosition ]; + byte data = aToneSequence[ aPosition + 1 ]; + int retVal = 0; + + if (type >= ToneControl.SILENCE && + type <= MidiToneConstants.TONE_MAX_NOTE) + { + if (data < MidiToneConstants.TONE_SEQUENCE_NOTE_MIN_DURATION || + data > MidiToneConstants.TONE_SEQUENCE_NOTE_MAX_DURATION) + { + throw new IllegalArgumentException( + "Note duration out of range, valid range is 1 <= duration <=127"); + } + retVal = EVENT_SIZE; + } + return retVal; + } + + /** + * Writes tone event into MIDI sequence. + * @param aType tone event type + * @param aData tone event parameter + * @param aSilent whether this event is silent (note value -1) or not. + * @param aMidiSequence midi sequence to write midi events to + */ + private static int processToneEvent( + byte aType, + byte aData, + boolean aSilent, + MidiSequence aMidiSequence) throws MidiSequenceException + { + // If this is a silent note, two NOTE_OFFs are written into midi sequence. + // otherwise NOTE_ON and NOTE_OFF. + + byte firstMidiEventType = MidiToneConstants.MIDI_NOTE_ON; + if (aSilent) + { + firstMidiEventType = MidiToneConstants.MIDI_NOTE_OFF; + } + + // write 'note on' on delta time 0 + aMidiSequence.writeMidiEvent(0, + firstMidiEventType, + aType, + MidiToneConstants.MIDI_MAX_VELOCITY); + // write 'note off' after delta time represented by 'data' variable + aMidiSequence.writeMidiEvent(aData, + MidiToneConstants.MIDI_NOTE_OFF, + aType, + MidiToneConstants.MIDI_MAX_VELOCITY); + + // N.B.! Above MIDI_NOTE_ON and MIDI_NOTE_OFF can be written without channel + // value because MidiSequence attached correct channel value to them anyway. + return EVENT_SIZE; + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, BlockEnd, PlayBlock, Volume, Repeat or + // end of sequence + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + return; // end of sequence is ok for this event + } + + if (type >= ToneControl.SILENCE || + type == ToneControl.BLOCK_END || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + + throw new IllegalArgumentException( + "Illegal event found; sequence is corrupted"); + } + +} // end of class diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/TonePlayer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/TonePlayer.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,509 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.PlayerListener; +import javax.microedition.media.MediaException; +import javax.microedition.media.control.ToneControl; +import javax.microedition.media.protocol.DataSource; +import javax.microedition.media.protocol.SourceStream; +import javax.microedition.media.Manager; +import javax.microedition.media.Player; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import com.nokia.microedition.media.PlayerBase; +import com.nokia.microedition.media.InternalPlayer; +import com.nokia.microedition.media.tone.ToneSequence; +import com.nokia.microedition.media.control.MIDIControl; +import com.nokia.microedition.media.PlayerListenerImpl; +import java.util.Vector; +import com.nokia.mj.impl.utils.Logger; + + +/** + * Player that is created with Manager.TONE_DEVICE_LOCATOR locator or + * with jts content. + */ +public class TonePlayer extends PlayerBase implements ToneControl, PlayerListener +{ + // This is allways tone's content type + public static final String TONE_CONTENT_TYPE = + "audio/x-tone-seq"; + + private static final String TONE_LOCATOR_SUFFIX = ".jts"; + + // MIDI player used to play tone + private InternalPlayer iMidiPlayer; + + // Internal MIDI player listener + private PlayerListenerImpl iPlayerListenerImpl; + + // MIDI control used to reset native midi engine. + private MIDIControl iMIDIControl; + + // Tone sequence processed to midi sequence + private byte[] iMidiSequence; + + // Tone sequence duration + private long iDuration; + + // Granularity for tone sequence reader + private static final int SEQUENCE_READ_GRANULARITY = 1024; // 1 KB + + // Empty midi sequence for midi player initialization + private static final byte[] EMPTY_MIDI_SEQUENCE = + { + 0x4D,0x54,0x68,0x64,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x01,0x00,0x10, + 0x4D,0x54,0x72,0x6B,0x00,0x00,0x00,0x12,0x00,(byte)0xFF,0x51,0x03, + 0x07,(byte)0xA1,0x20,0x00,(byte)0xC0,0x01,0x00,(byte)0x80,0x40, + 0x7F,0x00,(byte)0xFF,0x2F,0x00 + }; + + private static final String[] TONE_FORBIDDEN_CONTROLS = + { "javax.microedition.media.control.MetaDataControl" }; + + // For checking whether a control is allowed for tone player + static final String CONTROL_DEFAULT_PACKAGE = + "javax.microedition.media.control."; + + /** + * Create player without content. + */ + public TonePlayer() throws MediaException + { + initializeMidi(); + } + + + /** + * Create player from DataSource. + * @param aDataSource DataSource with audio/x-tone-seq content. + */ + public TonePlayer(DataSource aDataSource) throws MediaException + { + initializeMidi(); + + // Read .JTS file data from data source + SourceStream input = (aDataSource.getStreams())[ 0 ]; + byte[] sequenceTemp = new byte[ SEQUENCE_READ_GRANULARITY ]; + ByteArrayOutputStream sequenceStream = + new ByteArrayOutputStream(SEQUENCE_READ_GRANULARITY); + byte[] sequence = null; // container for read tone sequence + int readCount = 0; + + // Read data in SEQUENCE_READ_GRANULARITY sized blocks + try + { + while (readCount >= 0) + { + readCount = input.read(sequenceTemp, 0, SEQUENCE_READ_GRANULARITY); + if (readCount > 0) + { + sequenceStream.write(sequenceTemp, 0, readCount); + } + } + sequenceStream.flush(); + sequence = sequenceStream.toByteArray(); + sequenceStream.close(); + } + catch (IOException ioe) + { + Logger.ELOG(Logger.EJavaMMAPI, + "MMA::TonePlayer: TonePlayer( DataSource ): " + ioe.toString()); + throw new IllegalArgumentException(); + } + + setSequence(sequence); + } + + + /** + * Private method for initializing internal midi player + */ + private void initializeMidi() throws MediaException + { + // Create concrete PlayerListenerImpl for listeners of + // this TonePlayer + iPlayerListenerImpl = new PlayerListenerImpl(this); + iMidiSequence = EMPTY_MIDI_SEQUENCE; + + try + { + ByteArrayInputStream in = new ByteArrayInputStream(iMidiSequence); + iMidiPlayer = (InternalPlayer)Manager.createPlayer(in, "audio/midi"); + } + catch (IOException ioe) + { + throw new IllegalStateException(); + } + + // we only have controls from MIDI player this far, so ToneControl + // must be added. + + addControl(this, MidiToneConstants.TONE_CONTROL_FULL_NAME); + + // register this TonePlayer as MIDI player listener + iMidiPlayer.addPlayerListener(this); + } + + + /** + * @see ToneControl + */ + public void setSequence(byte[] aSequence) + { + // player must not be prefetched or started + int state = getState(); + if (state == javax.microedition.media.Player.PREFETCHED) + { + throw new IllegalStateException("Player is PREFETCHED"); + } + if (state == javax.microedition.media.Player.STARTED) + { + throw new IllegalStateException("Player is STARTED"); + } + + try + { + // process tone sequence into midi sequence + ToneSequence tone = new ToneSequence(aSequence); + tone.process(); + iMidiSequence = tone.getByteArray(); + iDuration = tone.getDuration(); + } + catch (Exception e) + { + Logger.ELOG(Logger.EJavaMMAPI, + "MMA: TonePlayer: setSequence: !! Exception: " + e); + throw new IllegalArgumentException("Illegal sequence"); + } + } + + + /** + * Adds control to the player. + * @param aControl Player's control + * @param aControlName Identifies the control. Name must contain + * full package information + */ + public void addControl(javax.microedition.media.Control aControl, + String aControlName) throws MediaException + { + iMidiPlayer.addControl(aControl, aControlName); + } + + + /** + * interface Controllable + * Return controls + * @return list of controls + * @see Controllable + */ + public javax.microedition.media.Control[] getControls() + { + closeCheck(); + unrealizedCheck(); + + // Get all controls but discard forbidden ones + javax.microedition.media.Control[] allControls = + iMidiPlayer.getControls(); + javax.microedition.media.Control[] controls = null; + + Vector controlVector = new Vector(allControls.length); + + for (int i = 0; i < allControls.length; i++) + { + // Add only allowed controls to control vector + if (isAllowedControl(allControls[ i ].getClass())) + { + controlVector.addElement(allControls[ i ]); + } + + controls = + new javax.microedition.media.Control[ controlVector.size()]; + + controlVector.copyInto(controls); + } + return controls; + } + + + /** + * interface Controllable + * get control by content type + * @param aControlType content type of wanted control + * @return control + * @see Controllable + * @see Control + */ + public javax.microedition.media.Control getControl(String aControlType) + { + closeCheck(); + unrealizedCheck(); + + if (aControlType == null) + { + throw new IllegalArgumentException("argument was null"); + } + + // If not fully qualified name, then supply default package + String controlType = null; + if (aControlType.indexOf(".") == -1) + { + controlType = CONTROL_DEFAULT_PACKAGE + aControlType; + } + else + { + controlType = aControlType; + } + + Class controlClass = null; + try + { + controlClass = Class.forName(controlType); + } + catch (ClassNotFoundException cnfe) + { + return null; + } + + if (isAllowedControl(controlClass)) + { + return iMidiPlayer.getControl(controlType); + } + else + { + return null; + } + } + + + /** + * interface Player + * @see Player + */ + public void addPlayerListener(PlayerListener aPlayerListener) + { + closeCheck(); + iPlayerListenerImpl.addPlayerListener(aPlayerListener); + } + + + /** + * From Player + * @see Player + */ + public void removePlayerListener(PlayerListener aPlayerListener) + { + closeCheck(); + iPlayerListenerImpl.removePlayerListener(aPlayerListener); + } + + + /** + * From Player + * @see Player + */ + public int getState() + { + return iMidiPlayer.getState(); + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doRealize() throws MediaException + { + iMidiPlayer.realize(); + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doPrefetch() throws MediaException + { + + // we get javax.microedition control which is cast to com.nokia control + iMIDIControl = (MIDIControl) + iMidiPlayer.getControl(MidiToneConstants.MIDI_CONTROL_FULL_NAME); + + // reinitialize midi engine with the sequence currently + // in iMidiSequence + + iMIDIControl.reInitializeMidi( + iMidiSequence, 0, iMidiSequence.length); + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doDeallocate() + { + iMidiPlayer.deallocate(); + } + + + /** + * From Player. + * @see Player + */ + public void start() throws MediaException + { + prefetch(); + iMidiPlayer.start(); + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doStop() throws MediaException + { + iMidiPlayer.stop(); + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public void doClose() + { + iDuration = 0; + iMidiPlayer.close(); + } + + + /** + * interface Player + * @see Player + */ + public void setLoopCount(int aCount) + { + iMidiPlayer.setLoopCount(aCount); + } + + + /** + * interface Player + * @see Player + */ + public long getDuration() + { + closeCheck(); + + int state = iMidiPlayer.getState(); + + // Return TIME_UNKNOWN if player is realized and a midi + // sequence has been explicitely set. + if (state == Player.REALIZED && + !(iMidiSequence.equals(EMPTY_MIDI_SEQUENCE))) + { + iDuration = Player.TIME_UNKNOWN; + } + else if (state == Player.PREFETCHED || + state == Player.STARTED) + { + iDuration = iMidiPlayer.getDuration(); + } + return iDuration; + } + + + /** + * From PlayerBase + * @see PlayerBase + */ + public long setMediaTime(long aNow) throws MediaException + { + return iMidiPlayer.setMediaTime(aNow); + } + + + /** + * interface Player + * @see Player + */ + public long getMediaTime() + { + closeCheck(); + return iMidiPlayer.getMediaTime(); + } + + + /** + * interface Player + * @see Player + */ + public String getContentType() + { + closeCheck(); + unrealizedCheck(); + return TONE_CONTENT_TYPE; + } + + /** + * from PlayerListener + * @see PlayerListener + */ + public void playerUpdate(Player player, + java.lang.String event, + java.lang.Object eventData) + { + iPlayerListenerImpl.postEvent(event, eventData); + } + + /** + * Check whether a control is allowed for tone player. + * @param aControl instance of control to check + * @return boolean allowed or not + */ + private boolean isAllowedControl(Class aControlClass) + { + for (int i = 0; i < TONE_FORBIDDEN_CONTROLS.length; i++) + { + Class forbidden = null; + try + { + forbidden = Class.forName(TONE_FORBIDDEN_CONTROLS[ i ]); + } + catch (ClassNotFoundException cnfe) + { + // This should never happen + throw new Error("Control class not found"); + } + + if (forbidden.isAssignableFrom(aControlClass)) + { + // Not allowed + return false; + } + } + // else + return true; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/ToneSequence.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/ToneSequence.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,198 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class represents tone sequence for tone to midi conversion +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Stack; +import com.nokia.mj.impl.utils.Logger; + + +/** + * This class represents tone sequence for tone to midi conversion + */ +public class ToneSequence +{ + // MEMBER DATA + + /* Hold original tone sequence bytes */ + private byte[] iToneSequence; + + /* Holds the new tone sequence converted to MIDI */ + private MidiSequence iMidiSequence; + + /* Event list used to hold tone event processors */ + private EventList iEventList; + + ToneSequence(byte[] aSequence) + { + iToneSequence = aSequence; + iMidiSequence = new MidiSequence(MidiToneConstants.MIDI_TONE_CHANNEL, + MidiToneConstants.MIDI_TONE_INSTRUMENT); + iEventList = new EventList(iToneSequence, iMidiSequence); + } + + public void process() + { + // Reset static base class variables of events before processing. + iEventList.reset(); + + // Check input; tone sequence must be even length + // ie. multiple of event size + if ((iToneSequence.length % Event.EVENT_SIZE) != 0) + { + throw new IllegalArgumentException( + "Illegal sequence, tone sequence must be multiple of single tone event size (2)"); + } + + // Validate header bytes + + // Next check that have correct VERSION and possibly + // VERSION and RESOLUTION. + int checkPos = 0; + + // First two bytes must belong to VERSION + if (iToneSequence[ checkPos ] != ToneControl.VERSION || + iToneSequence[ checkPos + 1 ] != + MidiToneConstants.TONE_SEQUENCE_SUPPORTED_VERSION) + { + throw new IllegalArgumentException( + "Illegal sequence, first two bytes must belong to version"); + } + + // Next two may be TEMPO or RESOLUTION + checkPos += Event.EVENT_SIZE; + + if (iToneSequence[ checkPos ] == ToneControl.TEMPO) + { + iMidiSequence.setTempo(iToneSequence[ checkPos + 1 ]); + checkPos += Event.EVENT_SIZE; + } + + // Continue checking RESOLUTION + if (iToneSequence[ checkPos ] == ToneControl.RESOLUTION) + { + iMidiSequence.setResolution(iToneSequence[ checkPos + 1 ]); + checkPos += Event.EVENT_SIZE; + } + + // Validate rest of the sequence + + int count = 0; // Offset to new position in tone sequence. >= 0 + while (checkPos < iToneSequence.length) + { + count = iEventList.validate(checkPos); + checkPos += count; + if (count == 0) + { + // if end of tone sequence is reached, zero is + // OK. Otherwise this indicates error + if (checkPos != iToneSequence.length) + { + throw new IllegalArgumentException( + "Validation failed, sequence corrupted"); + } + break; + } + } + + // Find start of sequence + int position = 0; // current position on tone sequence + + for (int i = iToneSequence.length - Event.EVENT_SIZE; + i >= 0; + i -= Event.EVENT_SIZE) + { + // There cannot be any lower value command bytes in tone sequence + // than REPEAT + if (iToneSequence[ i ] < ToneControl.REPEAT) + { + throw new IllegalArgumentException( + "Illegal sequence, lower value command than ToneControl.REPEAT found"); + } + + if (iToneSequence[ i ] < ToneControl.SILENCE && + iToneSequence[ i ] != ToneControl.PLAY_BLOCK && + iToneSequence[ i ] != ToneControl.SET_VOLUME && + iToneSequence[ i ] != ToneControl.REPEAT) + { + position = i + Event.EVENT_SIZE; + // stop the for loop + break; + } + } + + // No start position found + if (position < Event.EVENT_SIZE) + { + throw new IllegalArgumentException( + "Illegal sequence, no start position found"); + } + + count = 0; // offset to new position in tone sequence. +/- + try + { + while (position > 0 && position < iToneSequence.length) + { + count = iEventList.advance(position); + position += count; + if (count == 0) + { + // if end of tone sequence is reached, zero is + // OK. Otherwise this indicates error + if (position != iToneSequence.length) + { + throw new IllegalArgumentException( + "Validation failed, sequence corrupted"); + } + break; + } + } + } + catch (MidiSequenceException mse) + { + // This exception indicates that we have reached the maximum + // midi sequence length and thus must stop processing. Currently + // processed midi sequence is however available by getStream. + // So no action is needed here. + Logger.WLOG(Logger.EJavaMMAPI, + "MMA: ToneSequence: MIDI maximum lenght reached."); + } + } + + public ByteArrayInputStream getStream() throws IOException + { + return iMidiSequence.getStream(); + } + + public byte[] getByteArray() throws IOException + { + return iMidiSequence.getByteArray(); + } + + /** + * Get duration of tone sequence + */ + public long getDuration() + { + return iMidiSequence.getCumulativeDuration(); + } +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/VolumeEvent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/microedition/media/tone/VolumeEvent.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Event processor class for tone sequence VOLUME events +* +*/ + + +package com.nokia.microedition.media.tone; + +import javax.microedition.media.control.ToneControl; + +/** + * Event processor class for tone sequence VOLUME events + */ +public class VolumeEvent extends Event +{ + /** + * ToneEvent constructor + * @param aSequence tone sequence byte array (input) + * @param aMidiSequence midi sequence object where to output midi events. + */ + VolumeEvent(byte[] aSequence, MidiSequence aMidiSequence) + { + super(aSequence, aMidiSequence); + } + + /** + * Inherited from Event + */ + public int advance(int aPosition) throws MidiSequenceException + { + int retVal = doValidate(aPosition); + { + if (retVal == 0) + { + return 0; + } + } + // it is already checked that there is at least two bytes left + byte type = iSequence[ aPosition ]; + byte data = iSequence[ aPosition + 1 ]; + + // calculate equivalent midi TONE_VOLUME + float vol = (float)MidiToneConstants.MIDI_MAX_VOLUME / + (float)MidiToneConstants.TONE_MAX_VOLUME * (float)data; + + byte volume = (byte) vol; + if (volume < MidiToneConstants.MIDI_MIN_VOLUME) + { + volume = MidiToneConstants.MIDI_MIN_VOLUME; + } + + if (volume > MidiToneConstants.MIDI_MAX_VOLUME) + { + volume = MidiToneConstants.MIDI_MAX_VOLUME; + } + // write TONE_VOLUME change on delta time 0 + iMidiSequence.writeMidiEvent( + 0, + MidiToneConstants.MIDI_CONTROL_CHANGE, + MidiToneConstants.MIDI_CONTROL_MAIN_VOLUME, + volume); + + // N.B.! Above MIDI_CONTROL_CHANGE can be written without channel + // value because MidiSequence will attach correct channel value to them anyway. + return EVENT_SIZE; + } + + /** + * Child class defined functionality for validate + * @param aPosition position in tone sequence array where to validate + * @return new position offset related to aPosition in tone sequence + * array. Must be positive. + */ + protected int doValidate(int aPosition) + throws IllegalArgumentException + { + byte type = iSequence[ aPosition ]; + byte data = iSequence[ aPosition + 1 ]; + int retVal = 0; + if (type == ToneControl.SET_VOLUME) + { + if (data < MidiToneConstants.TONE_MIN_VOLUME || + data > MidiToneConstants.TONE_MAX_VOLUME) + { + throw new IllegalArgumentException( + "Volume is out of range, valid range is 0 <= volume <= 100"); + } + retVal = EVENT_SIZE; + } + return retVal; + } + + /** + * Child class defined functionality for checkEventAtNextPosition + * @param aPosition position in tone sequence array where to check + */ + protected void checkEventAtNextPosition(int aPosition) + throws IllegalArgumentException + { + // After this event there can be: + // Tone, BlockEnd, PlayBlock, Volume, Repeat or + // end of sequence + + int type = 0; + try + { + type = iSequence[ aPosition ]; + } + catch (ArrayIndexOutOfBoundsException aioobe) + { + return; // end of sequence is ok for this event + } + + if (type >= ToneControl.SILENCE || + type == ToneControl.BLOCK_END || + type == ToneControl.PLAY_BLOCK || + type == ToneControl.SET_VOLUME || + type == ToneControl.REPEAT) + { + return; + } + throw new IllegalArgumentException( + "Illegal event found; sequence is corrupted"); + } + +} // end of class + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/media/PlayerPermission.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/media/PlayerPermission.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: + * +*/ + + +package com.nokia.mj.impl.media; + +import java.security.Permission; +import java.security.PermissionCollection; +import com.nokia.mj.impl.security.common.PermissionBase; +import com.nokia.mj.impl.security.utils.SecurityPromptMessage; + +public class PlayerPermission extends PermissionBase +{ + String iAction; + + public PlayerPermission(String aUri, String aAction) + { + super(aUri); + iAction = aAction ; + } + + /** + * Returns the question (as localized text) associated with the security + * prompt + * + * @return the localized text associated with the security prompt + */ + public String getSecurityPromptQuestion(int aInteractionMode) + { + return (SecurityPromptMessage.getInstance()).getText( + SecurityPromptMessage.QUESTION_ID_AUDIO_VIDEO_RECORDING, + null); + } + + + public String toString() + { + if (iAction.compareTo("record") == 0) + { + return "javax.microedition.media.control.RecordControl"; + } + else if (iAction.compareTo("snapshot") == 0) + { + return "javax.microedition.media.control.VideoControl.getSnapshot"; + } + return ""; + } + + public boolean implies(Permission p) + { + if (p instanceof PlayerPermission) + { + PlayerPermission per = (PlayerPermission)p; + return matchActions(iAction, per.iAction); + } + return false; + } + + public boolean equals(Object obj) + { + return true; + } + + public int hashCode() + { + return 0; + } + + public String getActions() + { + return iAction; + } + + public PermissionCollection newPermissionCollection() + { + return null; + } +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/media/RTSPPermission.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/media/RTSPPermission.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: + * +*/ + + +package com.nokia.mj.impl.media; + +import java.security.Permission; +import java.security.PermissionCollection; +import com.nokia.mj.impl.security.common.PermissionBase; +import com.nokia.mj.impl.security.utils.SecurityPromptMessage; + +public class RTSPPermission extends PermissionBase +{ + public RTSPPermission(String aUri) + { + super(aUri); + } + + /** + * Returns the question (as localized text) associated with the security + * prompt + * + * @return the localized text associated with the security prompt + */ + public String getSecurityPromptQuestion(int aInteractionMode) + { + return (SecurityPromptMessage.getInstance()).getText( + SecurityPromptMessage.QUESTION_ID_NETWORK_USAGE, + null); + } + + + public String toString() + { + return "javax.microedition.io.Connector.rtsp"; + } + + public boolean implies(Permission p) + { + if (p instanceof RTSPPermission) + { + return true; + } + return false; + } + + public boolean equals(Object obj) + { + return true; + } + + public int hashCode() + { + return 0; + } + + public String getActions() + { + return ""; + } + + public PermissionCollection newPermissionCollection() + { + return null; + } +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/properties/mobilemedia/DynamicPropertyHandler.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/com/nokia/mj/impl/properties/mobilemedia/DynamicPropertyHandler.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +package com.nokia.mj.impl.properties.mobilemedia; + +import com.nokia.mj.impl.rt.support.SystemPropertyProvider; +import javax.microedition.media.Manager; + +/** + * A class for handling dynamic system properties of MobileMedia API. + */ +public class DynamicPropertyHandler implements SystemPropertyProvider +{ + + /* + * Constants for identifying the asked property. + */ + private static String AUDIO_ENCODINGS = "audio.encodings"; + private static String SUPPORTS_VIDEO_CAPTURE = "supports.video.capture"; + private static String VIDEO_ENCODINGS = "video.encodings"; + + // start of the audio content types + private static final String AUDIO = "audio"; + + // special audio encoding strings which are defined in the JSR + private static final String AUDIO_ENCODINGS_JSR = + " encoding=pcm encoding=ulaw encoding=gsm"; + + // start of the video content types + private static final String VIDEO = "video"; + + + /* (non-Javadoc) + * @see com.nokia.mj.impl.rt.DynamicProperty#getProperty(com.nokia.mj.impl.rt.DynamicPropertyInfo) + */ + public String getProperty(String propertyName) + { + String propertyValue = null; + + if (propertyName.equals(AUDIO_ENCODINGS)) + { + propertyValue = getSupportedCaptureEncodings(AUDIO) + + AUDIO_ENCODINGS_JSR; + } + else if (propertyName.equals(SUPPORTS_VIDEO_CAPTURE)) + { + propertyValue = getSupportedCaptureEncodings(VIDEO); + // video capture is supported only if there is supported encodings + propertyValue = String.valueOf(propertyValue != null); + } + else if (propertyName.equals(VIDEO_ENCODINGS)) + { + propertyValue = getSupportedCaptureEncodings(VIDEO); + } + return propertyValue; + } + + public boolean isStatic(String key) + { + // All property values of MobileMedia API do not change during the + // lifetime of the application. + return true; + } + + // capture protocol + private static final String CAPTURE = "capture"; + + // encoding for media strings + private static final String ENCODING = "encoding="; + + /** + * Returns supported capture encodings. + * @param aPrefix Capture format type. + * @return the supported capture encodings. + */ + private String getSupportedCaptureEncodings(String aPrefix) + { + // get supported content types from all capture:// protocols + String[] cTypes = Manager.getSupportedContentTypes(CAPTURE); + + StringBuffer sBuffer = new StringBuffer(); + + // go through all types + for (int i = 0; i < cTypes.length; i++) + { + if (cTypes[ i ].startsWith(aPrefix)) + { + // if video type appent to buffer encoding= + content type + sBuffer.append(ENCODING + cTypes[ i ] + " "); + } + } + String encodings = null; + + // if no types was found null must be returned + if (sBuffer.length() > 0) + { + // substring is taken to remove last empty space added in previous + // for loop + encodings = sBuffer.toString().substring(0, + sBuffer.length() - 1); + } + return encodings; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Control.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Control.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,23 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +public interface Control +{ +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Controllable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Controllable.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +public interface Controllable +{ + + public Control[] getControls(); + + public Control getControl(String aControlType); + +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Manager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Manager.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +*/ + + +package javax.microedition.media; + +import java.io.IOException; +import com.nokia.microedition.media.ManagerImpl; +import javax.microedition.media.protocol.DataSource; +import java.io.InputStream; + +public final class Manager +{ + private static ManagerImpl sInstance; + + static + { + sInstance = ManagerImpl.getInstance(); + } + + final public static String TONE_DEVICE_LOCATOR = "device://tone"; + + final public static String MIDI_DEVICE_LOCATOR = "device://midi"; + + + private Manager() + { + } + + public static String[] getSupportedContentTypes(String aProtocol) + { + return sInstance.getAllSupportedContentTypes(aProtocol); + } + + public static String[] getSupportedProtocols(String aContentType) + { + return sInstance.getAllSupportedProtocols(aContentType); + } + + public static Player createPlayer(String aLocator) + throws IOException, MediaException + { + return sInstance.createPlayer(aLocator); + } + + public static Player createPlayer(DataSource aSource) + throws IOException, MediaException + { + return sInstance.createInternalPlayer(aSource); + } + + public static Player createPlayer(InputStream aStream, String aType) + throws IOException, MediaException + { + return sInstance.createPlayer(aStream, aType); + } + + static public void playTone(int aNote, int aDuration, int aVolume) + throws MediaException + { + sInstance.playTone(aNote, aDuration, aVolume); + } + + public static TimeBase getSystemTimeBase() + { + return sInstance.getSystemTimeBase(); + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/MediaException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/MediaException.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +public class MediaException extends Exception +{ + + public MediaException() + { + super(); + } + + public MediaException(String aReason) + { + super(aReason); + } + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Player.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/Player.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +public interface Player extends Controllable +{ + + public static final int UNREALIZED=100; + public static final int REALIZED=200; + public static final int PREFETCHED=300; + public static final int STARTED=400; + public static final int CLOSED=0; + public static final long TIME_UNKNOWN=-1; + + public void realize() throws MediaException; + + public void prefetch() throws MediaException; + + public void start() throws MediaException; + + public void stop() throws MediaException; + + public void deallocate(); + + public void close(); + + public long setMediaTime(long aTime) throws MediaException; + + public long getMediaTime(); + + public int getState(); + + public long getDuration(); + + public String getContentType(); + + public void setLoopCount(int aCount); + + public void addPlayerListener(PlayerListener aPlayerListener); + + public void removePlayerListener(PlayerListener aPlayerListener); + + /** + * The following methods do not belong to the MIDP-NG multimedia subset + */ + + public void setTimeBase(TimeBase aTimeBase) throws MediaException; + + public TimeBase getTimeBase(); + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/PlayerListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/PlayerListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +public interface PlayerListener +{ + + public static final String STARTED="started"; + public static final String STOPPED="stopped"; + public static final String END_OF_MEDIA="endOfMedia"; + public static final String DURATION_UPDATED="durationUpdated"; + public static final String DEVICE_UNAVAILABLE="deviceUnavailable"; + public static final String DEVICE_AVAILABLE="deviceAvailable"; + public static final String VOLUME_CHANGED="volumeChanged"; + public static final String ERROR="error"; + public static final String CLOSED="closed"; + + + /** + * The following constants do not belong to the MIDP-NG multimedia subset + */ + + public static final String STOPPED_AT_TIME="stoppedAtTime"; + public static final String SIZE_CHANGED="sizeChanged"; + public static final String RECORD_STARTED="recordStarted"; + public static final String RECORD_STOPPED="recordStopped"; + public static final String RECORD_ERROR="recordError"; + public static final String BUFFERING_STARTED="bufferingStarted"; + public static final String BUFFERING_STOPPED="bufferingStopped"; + + /** + * This method belongs to the MIDP-NG multimedia subset + */ + + public void playerUpdate(Player aPlayer, String aEvent, Object aEventData); + +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/TimeBase.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/TimeBase.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +package javax.microedition.media; + +/** + * This class does not belong to the MIDP-NG multimedia subset + */ + +public interface TimeBase +{ + public long getTime(); +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/FramePositioningControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/FramePositioningControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface FramePositioningControl + extends javax.microedition.media.Control +{ + int seek(int aFrameNumber); + + int skip(int aFramesToSkip); + + long mapFrameToTime(int aFrameNumber); + + int mapTimeToFrame(long aMediaTime); +} + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/GUIControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/GUIControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,26 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface GUIControl extends javax.microedition.media.Control +{ + int USE_GUI_PRIMITIVE = 0; + + Object initDisplayMode(int aMode, Object aArg); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/MIDIControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/MIDIControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +import javax.microedition.media.MediaException; + +public interface MIDIControl extends javax.microedition.media.Control +{ + int NOTE_ON = 0x90; // 144 + + int CONTROL_CHANGE = 0xB0; // 176 + + boolean isBankQuerySupported(); + + int[] getProgram(int aChannel) + throws MediaException; + + int getChannelVolume(int aChannel); + + void setProgram(int aChannel, int aBank, int aProgram); + + void setChannelVolume(int aChannel, int aVolume); + + int[] getBankList(boolean aCustom) + throws MediaException; + + int[] getProgramList(int aBank) + throws MediaException; + + String getProgramName(int aBank, int aProg) + throws MediaException; + + String getKeyName(int aBank, int aProg, int aKey) + throws MediaException; + + void shortMidiEvent(int aType, int aData1, int aData2); + + int longMidiEvent(byte[] aData, int aOffset, int aLength); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/MetaDataControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/MetaDataControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + +package javax.microedition.media.control; + +public interface MetaDataControl extends javax.microedition.media.Control +{ + String AUTHOR_KEY = "author"; + + String COPYRIGHT_KEY = "copyright"; + + String DATE_KEY = "date"; + + String TITLE_KEY = "title"; + + String[] getKeys(); + + String getKeyValue(String aKey); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/PitchControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/PitchControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,30 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface PitchControl extends javax.microedition.media.Control +{ + int setPitch(int aMillisemitones); + + int getPitch(); + + int getMaxPitch(); + + int getMinPitch(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/RateControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/RateControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface RateControl extends javax.microedition.media.Control +{ + int setRate(int aMillirate); + + int getRate(); + + int getMaxRate(); + + int getMinRate(); +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/RecordControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/RecordControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + +package javax.microedition.media.control; + +import java.io.IOException; +import java.io.OutputStream; +import javax.microedition.media.MediaException; + +public interface RecordControl extends javax.microedition.media.Control +{ + void setRecordStream(OutputStream aStream); + + void setRecordLocation(String aLocator) + throws IOException, MediaException; + + String getContentType(); + + void startRecord(); + + void stopRecord(); + + void commit() throws IOException; + + int setRecordSizeLimit(int aSize) throws MediaException; + + void reset() throws IOException; +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/StopTimeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/StopTimeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface StopTimeControl extends javax.microedition.media.Control +{ + long RESET = Long.MAX_VALUE; + + void setStopTime(long aStopTime); + + long getStopTime(); +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/TempoControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/TempoControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,26 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface TempoControl extends RateControl +{ + int setTempo(int aMillitempo); + + int getTempo(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/ToneControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/ToneControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface ToneControl extends javax.microedition.media.Control +{ + byte VERSION = -2; + + byte TEMPO = -3; + + byte RESOLUTION = -4; + + byte BLOCK_START = -5; + + byte BLOCK_END = -6; + + byte PLAY_BLOCK = -7; + + byte SET_VOLUME = -8; + + byte REPEAT = -9; + + byte C4 = 60; + + byte SILENCE = -1; + + void setSequence(byte[] aSequence); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/VideoControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/VideoControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +import javax.microedition.media.MediaException; + +public interface VideoControl extends GUIControl +{ + int USE_DIRECT_VIDEO = 1; + + Object initDisplayMode(int aMode, Object aArg); + + void setDisplayLocation(int aX, int aY); + + int getDisplayX(); + + int getDisplayY(); + + void setVisible(boolean aVisible); + + void setDisplaySize(int aWidth, int aHeight) + throws MediaException; + + void setDisplayFullScreen(boolean aFullScreenMode) throws MediaException; + + int getSourceWidth(); + + int getSourceHeight(); + + int getDisplayWidth(); + + int getDisplayHeight(); + + byte[] getSnapshot(String aImageType) throws MediaException; +} + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/VolumeControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/control/VolumeControl.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,30 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.control; + +public interface VolumeControl extends javax.microedition.media.Control +{ + void setMute(boolean aMute); + + boolean isMuted(); + + int setLevel(int aLevel); + + int getLevel(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/ContentDescriptor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/ContentDescriptor.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.protocol; + +public class ContentDescriptor +{ + private String iEncoding; + + public ContentDescriptor(String aContentType) + { + iEncoding = aContentType; + } + + public String getContentType() + { + return iEncoding; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/DataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/DataSource.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.protocol; + +import javax.microedition.media.Controllable; +import java.io.IOException; + +abstract public class DataSource implements Controllable +{ + private String iSourceLocator; + + public DataSource(String aLocator) + { + iSourceLocator = aLocator; + } + + public abstract String getContentType(); + + public abstract void connect() throws IOException; + + public abstract void disconnect(); + + public abstract void start() throws IOException; + + public abstract void stop() throws IOException; + + public abstract SourceStream[] getStreams(); + + public String getLocator() + { + return iSourceLocator; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/SourceStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/javasrc/javax/microedition/media/protocol/SourceStream.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Please refer JSR 135 for more details. +* +*/ + + +package javax.microedition.media.protocol; + +import java.io.IOException; +import javax.microedition.media.Controllable; + +public interface SourceStream extends Controllable +{ + int NOT_SEEKABLE = 0; + + int SEEKABLE_TO_START = 1; + + int RANDOM_ACCESSIBLE = 2; + + ContentDescriptor getContentDescriptor(); + + long getContentLength(); + + int read(byte[] aB, int aOff, int aLen) + throws IOException; + + int getTransferSize(); + + long seek(long aWhere) throws IOException; + + long tell(); + + int getSeekType(); +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.dsa/cmmadsawindow.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.dsa/cmmadsawindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,359 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* in Direct Screen Access based displays for Helix engine. +* +*/ + + +// Include Files +#include +#include "cmmadsawindow.h" +#include "cmmaplayer.h" + +CMMADSAWindow* CMMADSAWindow::NewL( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer, + RMMFVideoPlayControllerCustomCommands* aVPCustomCommand) +{ + CMMADSAWindow* self = + new(ELeave) CMMADSAWindow(aEventSource, + aPlayer, + aVPCustomCommand); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +// Destructor (virtual by CBase) +CMMADSAWindow::~CMMADSAWindow() +{ + LOG( EJavaMMAPI, EInfo, "CMMADSAWindow::~CMMADSAWindow"); +} + +CMMADSAWindow::CMMADSAWindow( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer, + RMMFVideoPlayControllerCustomCommands* aVPCustomCommand) + : iEventSource(aEventSource), iPlayer(aPlayer), + iVideoPlayControllerCustomCommands(aVPCustomCommand), + iDSAAborted(EFalse) +{ + // Nothing to do. +} + +void CMMADSAWindow::ConstructL() +{ + iClientRect.SetRect(0, 0, 0, 0); + + // Empty rect until video size is known + iDrawRect.SetRect(0, 0, 0, 0); +} + + +void CMMADSAWindow::SetDestinationBitmapL(CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing +} + +void CMMADSAWindow::DrawFrameL(const CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing +} + +// Local wrapper function to SetDrawRect method +LOCAL_C void StaticSetDrawRect( + CMMADSAWindow* aWindow, + const TRect* aRect, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + RPointerArray< CMMAPlayer > players = aEventSource->Players(); + // Invoke SetDrawRect only if the player has not been cleaned + if (players.Find(aPlayer) != KErrNotFound) + { + aWindow->SetDrawRect(*aRect); + } +} + +void CMMADSAWindow::SetDrawRectThread(const TRect& aRect) +{ + // Call through event source changes thread to MMA event source thread + // and new rect can be set with RMMFVideoPlayControllerCustomCommands + // MMA player may be deleted after ExecuteV and before the static method + // is called so Event source is used to check if a cleanup has + // already been done for the player (for example due to MIDlet exit) + iEventSource->ExecuteV(&StaticSetDrawRect, + this, + &aRect, + iEventSource, + iPlayer); +} + +void CMMADSAWindow::SetDrawRect(const TRect& aRect) +{ + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + + // setting video draw rect and adjusting it to window + iDrawRect = aRect; + TRect drawRect = iDrawRect; + drawRect.Move(iClientRect.iTl); + + if (!iVideoPlayControllerCustomCommands) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: no VideoPlayControllerCustomCommands set, aborting -"); + return; + } + + if (iVisible) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: Abort DSA"); + iVideoPlayControllerCustomCommands->DirectScreenAccessEvent(EAbortDSA); + } + + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: drawRect TL %d %d", + drawRect.iTl.iX, drawRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: drawRect BR %d %d", + drawRect.iBr.iX, drawRect.iBr.iY); + + // Area where should be drawn is the intersection of drawRect and iClientRect. + TRect areaRect = iClientRect; + areaRect.Intersection(drawRect); + + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: areaRect TL %d %d", + areaRect.iTl.iX, areaRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: areaRect BR %d %d", + areaRect.iBr.iX, areaRect.iBr.iY); + + if (iVisible && !iDSAAborted) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: SetDisplayWindow( drawRect, areaRect )"); + iVideoPlayControllerCustomCommands->SetDisplayWindow( + drawRect , areaRect); + + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: Update region (areaRect)"); + RRegion region(areaRect); + iVideoPlayControllerCustomCommands->UpdateDisplayRegion(region); + region.Close(); + + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: Resume DSA"); + iVideoPlayControllerCustomCommands->DirectScreenAccessEvent(EResumeDSA); + } + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetDrawRect: -"); +} + +const TRect& CMMADSAWindow::DrawRect() +{ + return iDrawRect; +} + +TSize CMMADSAWindow::WindowSize() +{ + return iClientRect.Size(); +} + +void CMMADSAWindow::SetPosition(const TPoint& aPosition) +{ + // changing to MMA thread + // MMA player may be deleted after ExecuteV and before the static method + // is called so Event source is used to check if a cleanup has + // already been done for the player (for example due to MIDlet exit) + iEventSource->ExecuteV(&CMMADSAWindow::StaticSetWindowPosition, + this, + aPosition, + iEventSource, + iPlayer); +} + +void CMMADSAWindow::StaticSetWindowPosition( + CMMADSAWindow* aWindow, + TPoint aPosition, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + RPointerArray< CMMAPlayer > players = aEventSource->Players(); + // Invoke SetDrawRect only if the player has not been cleaned + if (players.Find(aPlayer) != KErrNotFound) + { + aWindow->SetDrawRect(TRect(aPosition, aWindow->iDrawRect.Size())); + } +} + +TBool CMMADSAWindow::IsVisible() const +{ + LOG1( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::IsVisible %d ", iVisible); + return iVisible; +} + +void CMMADSAWindow::SetVisible(TBool aVisible, TBool aUseEventServer) +{ + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetVisible avisible=%d useES=%d +", aVisible, aUseEventServer); + // Event server may not be used if we already in mma event server thread + if (aUseEventServer) + { + // MMA player may be deleted after ExecuteV and before the static method + // is called so Event source is used to check if a cleanup has + // already been done for the player (for example due to MIDlet exit) + iEventSource->ExecuteV(&CMMADSAWindow::SetWindowVisible, + this, + aVisible, + iEventSource, + iPlayer); + } + else + { + SetWindowVisible(this, aVisible, iEventSource, iPlayer); + } + LOG1( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetVisible %d -", aVisible); +} + +void CMMADSAWindow::SetWindowVisible( + CMMADSAWindow* aWindow, + TBool aVisible, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + LOG1( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible aVisible %d", aVisible); + RPointerArray< CMMAPlayer > players = aEventSource->Players(); + // Invoke SetDrawRect only if the player has not been cleaned + if (players.Find(aPlayer) != KErrNotFound) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible : Player found"); + if (aVisible != aWindow->iVisible) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible: Changed visibility"); + aWindow->iVisible = aVisible; + } + if (aVisible) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible: aVisible = 1"); + const TRect drawRect = aWindow->DrawRect(); + + aWindow->SetDrawRect(drawRect); + } + else + { + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible: aVisible = 0"); + TRect emptyRect(0, 0, 0, 0); + + RRegion region(emptyRect); + aWindow->iVideoPlayControllerCustomCommands->UpdateDisplayRegion(region); + region.Close(); + LOG( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowVisible: Abort DSA"); + + aWindow->iVideoPlayControllerCustomCommands-> + DirectScreenAccessEvent(EAbortDSA); + } + + } +} + +void CMMADSAWindow::SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType /*aThreadType*/) +{ + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowRect aRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMADSAWindow::SetWindowRect aRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + + iClientRect = aRect; +} + +const TRect& CMMADSAWindow::WindowRect() +{ + return iClientRect; +} + + +void CMMADSAWindow::AbortDSA() +{ + iDSAAborted = ETrue; + + // Always runs in UI thread + iEventSource->ExecuteV(&StaticAbortDSA, + this, + iEventSource, + iPlayer); +} + + +void CMMADSAWindow::ResumeDSA() +{ + iDSAAborted = EFalse; + + // Always runs in UI thread + iEventSource->ExecuteV(&StaticResumeDSA, + this, + iEventSource, + iPlayer); +} + + +void CMMADSAWindow::StaticAbortDSA( + CMMADSAWindow* aWindow, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + RPointerArray< CMMAPlayer > players = aEventSource->Players(); + // Invoke SetDrawRect only if the player has not been cleaned + if (players.Find(aPlayer) != KErrNotFound && + aWindow->iVisible && aWindow->iVideoPlayControllerCustomCommands) + { + TRect emptyRect(0, 0, 0, 0); + + RRegion region(emptyRect); + aWindow->iVideoPlayControllerCustomCommands->UpdateDisplayRegion(region); + region.Close(); + aWindow->iVideoPlayControllerCustomCommands->DirectScreenAccessEvent(EAbortDSA); + } +} + + +void CMMADSAWindow::StaticResumeDSA( + CMMADSAWindow* aWindow, + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + RPointerArray< CMMAPlayer > players = aEventSource->Players(); + // Invoke SetDrawRect only if the player has not been cleaned + if (players.Find(aPlayer) != KErrNotFound && + aWindow->iVisible && aWindow->iVideoPlayControllerCustomCommands) + { + TRect drawRect = aWindow->iDrawRect; + drawRect.Move(aWindow->iClientRect.iTl); + + // Area where should be drawn is the intersection of drawRect and iClientRect. + TRect areaRect = aWindow->iClientRect; + areaRect.Intersection(drawRect); + + aWindow->iVideoPlayControllerCustomCommands->SetDisplayWindow( + drawRect , areaRect); + + RRegion region(areaRect); + aWindow->iVideoPlayControllerCustomCommands->UpdateDisplayRegion(region); + region.Close(); + + aWindow->iVideoPlayControllerCustomCommands->DirectScreenAccessEvent(EResumeDSA); + } +} + +void CMMADSAWindow::ContainerDestroyed() +{ + SetVisible(EFalse, ETrue); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.dsa/cmmavideoplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.dsa/cmmavideoplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,403 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing video. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmavideoplayer.h" +#include "mmmadisplay.h" +#include "mmafunctionserver.h" +#include "cmmadsawindow.h" + +// CONSTANTS +_LIT(KVideoControlName, "VideoControl"); + +CMMAVideoPlayer* CMMAVideoPlayer::NewLC( + CMMAMMFResolver* aResolver) +{ + CMMAVideoPlayer* self = + new(ELeave) CMMAVideoPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAVideoPlayer::~CMMAVideoPlayer() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoPlayer::~CMMAVideoPlayer"); + if (iDisplay) + { + TRAPD(err, iDisplay->SetWindowL(NULL)); + if (err != KErrNone) + { + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + } + delete iDSAWindow; + delete iEmptySnapshotImage; + delete iActiveSchedulerWait; +} + +CMMAVideoPlayer::CMMAVideoPlayer( + CMMAMMFResolver* aResolver): + CMMAAudioPlayer(aResolver), + iVideoControllerCustomCommands(iController), + iVideoPlayControllerCustomCommands(iController) +{ +} + +void CMMAVideoPlayer::ConstructL() +{ + CMMAAudioPlayer::ConstructL(); + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; +} + +EXPORT_C void CMMAVideoPlayer::SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster) +{ + CMMAPlayer::SetPlayerListenerObjectL(aListenerObject, + aJni, + aEventPoster); + + // this method must be called only ones + __ASSERT_DEBUG(!iDSAWindow, User::Invariant()); + + // create window for videoplayer + // event poster is always MMAFunctionServer type. + + iDSAWindow = CMMADSAWindow::NewL( + static_cast< MMAFunctionServer* >(iEventPoster), + this, + &iVideoPlayControllerCustomCommands); +} + +EXPORT_C void CMMAVideoPlayer::SetDisplayL(MMMADisplay* aDisplay) +{ + // now it is ready to draw + iDisplay = aDisplay; + iDisplay->SetWindowL(iDSAWindow); + + // if state < prefeteched then we dont know actual source size yet + // and it will be set after prefetch + if (iState >= EPrefetched) + { + SourceSizeChanged(); + } +} +void CMMAVideoPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::RealizeL"); + // DataSource must have at least 1 stream or + // we must have file to play + if ((iSourceStreams.Count() == 0) && !iFileName) + { + User::Leave(KErrNotEnoughStreams); + } + + // If file locator is used, then file is prefetched + // in realized state so that FramePositioningControl + // can acquire frame count in REALIZED state + if (iFileName) + { + PrefetchFileL(); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + // If the player has not changed state during wait, + // Then there is an error condition. + if (iState != ERealized) + { + User::Leave(KErrNotSupported); + } + } + else + { + CMMAPlayer::RealizeL(); + } +} + +void CMMAVideoPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrefetchL"); + if (iFileName) + { + // File has already been prefetched when realizing + + // If initDisplayMode was called before prefetch, + // then the display must notified about source size. + if (iDisplay) + { + SourceSizeChanged(); + } + + ChangeState(EPrefetched); + PostActionCompleted(KErrNone); + } + else + { + // Using TDes -- load the whole video + iSourceStreams[ 0 ]->ReadAllL(); + } + // CMMASourceStream will notify with ReadCompleted +} + +EXPORT_C void CMMAVideoPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoPlayer::ReadCompletedL: status = %d", aStatus); + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + TRAPD(err, PrefetchDataL(aData)); + if (err != KErrNone) + { + PostActionCompleted(err); + } + // action completed event will be delivered from handleEvent + } +} + +void CMMAVideoPlayer::HandleEvent(const TMMFEvent& aEvent) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoPlayer::HandleEvent %d", aEvent.iEventType.iUid); + + // KNotCompleteVideoError can be notified when video is not complete + // ( missing sound ) but still can be played. Because + // CMMAAudioPlayer::HandleEvent fails with all negative error codes, + // do not call it with KNotCompleteVideoError error when preparing. + if ((aEvent.iErrorCode != KNotCompleteVideoError) || + (aEvent.iEventType != KMMFEventCategoryVideoPrepareComplete)) + { + CMMAAudioPlayer::HandleEvent(aEvent); + } + + // video opened, preparing + if (aEvent.iEventType == KMMFEventCategoryVideoOpenComplete) + { + if (aEvent.iErrorCode == KErrNone) + { + TInt prepareError(iVideoPlayControllerCustomCommands.Prepare()); + if (prepareError != KErrNone) + { + // opening failed, notifying java + PostActionCompleted(prepareError); + } + } + else + { + // opening failed, notifying java + PostActionCompleted(aEvent.iErrorCode); + } + } + // final state of prefetch ( prepare completed ) + else if (aEvent.iEventType == KMMFEventCategoryVideoPrepareComplete) + { + // This callback must be handled differently depending on whether + // player is created for a file locator or for a stream. When file + // locator is used, this callback is made in realized state. For + // stream it is made in prefetched state. + PrepareDisplay(); + if (iFileName) + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: Using filename, change state to REALIZED"); + + // If there is an error condition, then the player state is not + // changed, which indicates the error condition to StartL when + // the ActiveSchedulerWait returns. KNotCompleteVideoError is not + // considered as an error condition, instead it indicates that some + // elements of the media cannot be played (e.g. video OR audio) + if (aEvent.iErrorCode == KErrNone || + aEvent.iErrorCode == KNotCompleteVideoError) + { + ChangeState(ERealized); + } + __ASSERT_DEBUG(iActiveSchedulerWait->IsStarted(), User::Invariant()); + iActiveSchedulerWait->AsyncStop(); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: Not using filename, change state to PREFETCHED"); + CompletePrefetch(aEvent.iErrorCode); + } + } + else // in case of any other event + { + if (aEvent.iErrorCode != KErrNone) + { + PostActionCompleted(aEvent.iErrorCode); //some other error + } + } +} + +void CMMAVideoPlayer::CompletePrefetch(TInt aError) +{ + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::CompletePrefetch + error = %d",aError); + // Post KNotCompleteVideoError as KErrNone to the Java side, because + // video can be played. + if (aError == KNotCompleteVideoError) + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch KNotCompleteVideoError "); + // release java + PostActionCompleted(KErrNone); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch CompleteVideoError "); + // release java + PostActionCompleted(aError); + } + + if (aError == KErrNone || aError == KNotCompleteVideoError) + { + ChangeState(EPrefetched); + } + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch - "); +} + +void CMMAVideoPlayer::PrepareDisplay() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrepareDisplay +"); + // construction should have leaved if iDSAWindow does not exist + __ASSERT_DEBUG(iDSAWindow, + User::Panic(_L("CMMVideoPlayer::iDSAWindow is null"), + KErrArgument)); + + // Video must be initially not visible + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrepareDisplay: Initially aborting DSA"); + iVideoPlayControllerCustomCommands.DirectScreenAccessEvent(EAbortDSA); + + //First place where we are certain that source size can be fetched + TSize sourceSize; + + TInt err = iVideoControllerCustomCommands.GetVideoFrameSize(sourceSize); + + ELOG1( EJavaMMAPI, "MID::CMMAVideoPlayer::PrepareDisplay: GetVideoFrameSize err = %d", err); + + // Still we did not get the size of video + if ((err != KErrNone) || + (sourceSize.iWidth <= 0) || + (sourceSize.iHeight <= 0)) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: No sourcesize found, using DSAWindow size"); + // setting size to window size (client rect) + sourceSize = iDSAWindow->WindowSize(); + } + + // If 1x1 was got (the default size of form), it must be replaced + // with a valid size as controller will not accept 1x1. + if ((sourceSize.iWidth < KMMAVideoMinDimension) || + (sourceSize.iHeight < KMMAVideoMinDimension)) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: Unacceptable source size, using failsafe"); + // This is a special case and ought to be used only in + // the rare case that real size is not got from stream. + sourceSize = TSize(KMMAVideoMinDimension, KMMAVideoMinDimension); + } + + iSourceSize = sourceSize; + + // If init has been already done + if (iDisplay) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: display exists, changing source size"); + SourceSizeChanged(); + } + + // Setting (in)visible if something has changed the DSA state + // (e.g. prepare). If initDisplayMode is not called, this will always + // set visibility to false. + iDSAWindow->SetVisible(iDSAWindow->IsVisible(), EFalse); + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrepareDisplay -"); +} + +EXPORT_C const TDesC& CMMAVideoPlayer::Type() +{ + return KMMAVideoPlayer; +} + +EXPORT_C TSize CMMAVideoPlayer::SourceSize() +{ + return iSourceSize; +} + +EXPORT_C MMMASnapshot::TEncoding CMMAVideoPlayer::TakeSnapshotL(TRequestStatus* aStatus, + const TSize& /*aSize*/, + const CMMAImageSettings& /*aSettings*/) +{ + if (iEmptySnapshotImage) + { + // Ealier snapshot was not got with SnapshotBitmap method. + User::Leave(KErrInUse); + } + // frame can't be got from video player, but TCK requires that it should + // be available. So returning empty image + iEmptySnapshotImage = new(ELeave) CFbsBitmap(); + User::LeaveIfError(iEmptySnapshotImage->Create(TSize(1, 1), + EColor4K)); + + + User::RequestComplete(aStatus, KErrNone); + + // Return raw bitmap encoding and thus SnapshotEncoded() should not + // get called later on. + return EBitmap; +} + +EXPORT_C CFbsBitmap* CMMAVideoPlayer::SnapshotBitmap() +{ + // snapshot is not supported, returning empty image + CFbsBitmap* image = iEmptySnapshotImage; + + // ownership is transferred to caller + iEmptySnapshotImage = NULL; + return image; +} + +EXPORT_C HBufC8* CMMAVideoPlayer::SnapshotEncoded() +{ + // This method should never be called. + // Asserted in debug build to be sure. + __ASSERT_DEBUG(EFalse, User::Invariant()); + + return NULL; +} + +EXPORT_C void CMMAVideoPlayer::NotifyWithStringEvent( + CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) +{ + PostStringEvent(aEventType, aStringEventData); +} + +EXPORT_C MMMASnapshot* CMMAVideoPlayer::SnapshoterL() +{ + return this; +} + +void CMMAVideoPlayer::SourceSizeChanged() +{ + iDisplay->SourceSizeChanged(iSourceSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmaemcaudioplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmaemcaudioplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,178 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cmmaemcaudioplayer.h" + +CMMAEMCAudioPlayer* CMMAEMCAudioPlayer::NewLC( + CMMAEMCResolver* aResolver) +{ + CMMAEMCAudioPlayer* self = new(ELeave) CMMAEMCAudioPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +EXPORT_C CMMAEMCAudioPlayer::~CMMAEMCAudioPlayer() +{ +} + +EXPORT_C CMMAEMCAudioPlayer::CMMAEMCAudioPlayer( + CMMAEMCResolver* aResolver): + CMMAEMCPlayerBase(aResolver) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::CMMAEMCAudioPlayer"); +} + +EXPORT_C void CMMAEMCAudioPlayer::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::ConstructL +"); + CMMAEMCPlayerBase::ConstructL(); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::ConstructL -"); +} + +EXPORT_C void CMMAEMCAudioPlayer::PrefetchDataL(const TDesC8& /*aData*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::PrefetchDataL +"); + + User::LeaveIfError(iMStreamControl->Prime()); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::PrefetchDataL -"); +} + +EXPORT_C void CMMAEMCAudioPlayer::PrefetchFileL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::Prefetching from file"); +} + +EXPORT_C void CMMAEMCAudioPlayer::PlayCompleteL(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::PlayCompleteL +"); + TInt64 time; + GetDuration(&time); + iMediaTime = time; + iStartedEventTime = 0; + + ChangeState(EPrefetched); // ready to play again + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, time); + + if (aError == KErrNone) + { + iRepeatCount++; + + // priming again for allowing e.g. media time setting + User::LeaveIfError(iMStreamControl->Prime()); + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + + TInt64 position(0); + User::LeaveIfError(iMStreamControl->SetPosition(position)); + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCAudioPlayer::PlayCompleteL -"); +} + +EXPORT_C void CMMAEMCAudioPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::RealizeL +"); + // DataSource must have at least 1 stream or + // we must have file to play + if ((iSourceStreams.Count() == 0) && !iFileName) + { + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::RealizeL : Not Enough Streams"); + User::Leave(KErrNotEnoughStreams); + } + User::LeaveIfError(iMStreamControl->Open()); + + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + CMMAPlayer::RealizeL(); + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::RealizeL -"); +} + +EXPORT_C void CMMAEMCAudioPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::PrefetchL +"); + __ASSERT_DEBUG((iSourceStreams.Count() > 0) || iFileName, User::Invariant()); + + if (iFileName) + { + // prefetching the file + PrefetchFileL(); + // we can go to prefetched state immediately + ChangeState(EPrefetched); + PostActionCompleted(KErrNone); + } + else + { + // Using TDes -- load the whole sound + iSourceStreams[ 0 ]->ReadAllL(); + } + // CMMASourceStream will notify with ReadCompleted + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::PrefetchL -"); +} + +EXPORT_C const TDesC& CMMAEMCAudioPlayer::Type() +{ + // Should be used in AMMS Implementation to differentiate between + // this new kind of player with others + return KMMAEMCAudioPlayer; +} + +// +// CMMASourceStreamReader finished read operation +// This is called when ReadL is completed in Prefetch() +// +EXPORT_C void CMMAEMCAudioPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::ReadCompletedL +"); + LOG1( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::ReadCompletedL: status = %d", aStatus); + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + TRAPD(err, PrefetchDataL(aData)); + if (err == KErrNone) + { + ChangeState(EPrefetched); + } + PostActionCompleted(err); + } + LOG( EJavaMMAPI, EInfo, "CMMAEMCAudioPlayer::ReadCompletedL -"); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmaemcaudiovolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmaemcaudiovolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#include +#include "StreamControl.h" +#include "EffectControl.h" +#include "MMControlFactory.h" +#include "cmmaemcaudiovolumecontrol.h" +#include "cmmaemcaudioplayer.h" + +using multimedia ::KVolumeEffectControl; +using multimedia ::MStreamControl; +using multimedia ::MEffectControl; +using multimedia ::CMultimediaFactory; + +EXPORT_C CMMAEMCAudioVolumeControl* CMMAEMCAudioVolumeControl::NewL(CMMAEMCAudioPlayer& aPlayer) +{ + CMMAEMCAudioVolumeControl* self = new(ELeave)CMMAEMCAudioVolumeControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; +} + +EXPORT_C CMMAEMCAudioVolumeControl::CMMAEMCAudioVolumeControl(CMMAEMCAudioPlayer& aPlayer) + : CMMAVolumeControl(&aPlayer), iPlayer(aPlayer) +{ +} + +void CMMAEMCAudioVolumeControl::ConstructL() +{ + ConstructBaseL(); + MStreamControl* streamControl = iPlayer.StreamControl(); + CMultimediaFactory* mmFactory = iPlayer.MMFactory(); + + MEffectControl* temp(NULL); + User::LeaveIfError(mmFactory->CreateEffectControl(KVolumeEffectControl, temp)); + iVolCntrl = static_cast(temp); + User::LeaveIfError(streamControl->AddEffect(*iVolCntrl)); +} + +CMMAEMCAudioVolumeControl::~CMMAEMCAudioVolumeControl() +{ + MStreamControl* streamControl = iPlayer.StreamControl(); + CMultimediaFactory* mmFactory = iPlayer.MMFactory(); + + if ((NULL != streamControl) && (NULL != iVolCntrl)) + { + streamControl->RemoveEffect(*iVolCntrl); + } + + MEffectControl* temp = static_cast(iVolCntrl); + + if (NULL != mmFactory) + { + mmFactory->DeleteEffectControl(temp); + } +} + +EXPORT_C void CMMAEMCAudioVolumeControl::DoSetLevelL(TInt aLevel) +{ + TInt maxVolume = 0; + User::LeaveIfError(iVolCntrl->GetMaxVolume(maxVolume)); + // aLevel is the desired volume in range 0..100 + TInt volLevel = aLevel * maxVolume / KMMAVolumeMaxLevel; + User::LeaveIfError(iVolCntrl->SetVolume(volLevel)); + User::LeaveIfError(iVolCntrl->Apply()); +} + +EXPORT_C TInt CMMAEMCAudioVolumeControl::DoGetLevelL() +{ + TInt maxVolume = 0; + User::LeaveIfError(iVolCntrl->GetMaxVolume(maxVolume)); + __ASSERT_DEBUG(maxVolume != 0, User::Invariant()); + TInt volume = 0; + User::LeaveIfError(iVolCntrl->GetVolume(volume)); + // result is in range 0..100 + return (volume * KMMAVolumeMaxLevel / maxVolume); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmaemcplayerbase.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmaemcplayerbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,358 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +//#include +#include +#include +#include "cmmaemcplayerbase.h" +#include "cmmaemcresolver.h" + +using namespace multimedia; + +using multimedia::MSourceControlObserver; +using multimedia::MStreamControlObserver; + +CMMAEMCPlayerBase::~CMMAEMCPlayerBase() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::~CMMAEMCPlayerBase +"); + + if (iMStreamControl) + { + iMStreamControl->RemoveObserver(*this); + if (iMStreamControl->GetState() > 0) + { + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::~CMMAEMCPlayerBase: iMStreamControl's state = %d",iMStreamControl->GetState()); + TInt err = iMStreamControl->Close(); + ELOG1( EJavaMMAPI, "MMA::CMMAEMCPlayerBase::~CMMAEMCPlayerBase: Close() err = %d",err); + } + } + + if (iFactory) + { + CleanupSource(); + + MSinkControl* objPtr1 = iMAudioSink; + iMStreamControl->RemoveSink(*objPtr1); + + iFactory->DeleteSinkControl(objPtr1); + iMAudioSink = NULL; + + //before deleting Stream Control all the controls need to be deleted + if (iControls.Count() > 0) + iControls.ResetAndDestroy(); + + iFactory->DeleteStreamControl(iMStreamControl); + delete iFactory; + } + + delete iFileName; + + delete iActiveSchedulerWait; + + delete iMimeType; + + delete iDescData; + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::~CMMAEMCPlayerBase -"); +} + + +CMMAEMCPlayerBase::CMMAEMCPlayerBase( + CMMAEMCResolver* aResolver) : + iMediaTime(KTimeUnknown), iStartedEventTime(0) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase +"); + // content type ownership is transferred + iDescData = NULL; + iContentType = aResolver->ContentTypeOwnership(); + iMimeType = aResolver->MimeTypeOwnership(); // 8-bit version of iContentType + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::ContentType-- %S" ,iContentType->Des().PtrZ()); + + // file name ownership is transferred + iFileName = aResolver->FileNameOwnership(); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::FileName-- %S" ,iFileName->Des().PtrZ()); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase -"); +} + +void CMMAEMCPlayerBase::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::ConstructL +"); + CMMAPlayer::ConstructL(); + iSourceType = EDATABUFFERSOURCE; //Currently it only support Http + + TInt status=CMultimediaFactory::CreateFactory(iFactory); + CreateStreamL(); + AddDataSourceToStreamL(); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::ConstructL -"); +} + +void CMMAEMCPlayerBase::CreateStreamL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::CreateStreamL +"); + if (iMStreamControl) + User::Leave(KErrAlreadyExists); + TInt err = iFactory->CreateStreamControl(KStreamControl,iMStreamControl); + User::LeaveIfError(err); + //If the state of iMStreamControl changes,iPrevStreamControlState will keep its previous state + iPrevStreamControlState = MStreamControl::CLOSED; + iMStreamControl->AddObserver(*this); + + MSinkControl* tempSinkCtrl(NULL); + err = iFactory->CreateSinkControl(KMMFAudioOutputSinkControl,tempSinkCtrl); + User::LeaveIfError(err); + iMAudioSink = tempSinkCtrl; + iMStreamControl->AddSink(*iMAudioSink); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::CreateStreamL -"); +} + +void CMMAEMCPlayerBase::AddDataSourceToStreamL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::AddDataSourceToStreamL +"); + if (iMStreamControl == NULL) + { + User::Leave(KErrNotReady); + } + + TInt err(KErrNone); + MSourceControl* tempCtrl(NULL); + + switch (iSourceType) + { + case EFILESOURCE: + { + err = iFactory->CreateSourceControl(KFileSourceControl, tempCtrl); + User::LeaveIfError(err); + iMFileSource = static_cast(tempCtrl); + iMimeType->Des().FillZ(); + User::LeaveIfError(iMFileSource->Open(*iFileName, *iMimeType)); + iMFileSource->AddObserver(*this); + break; + } + case EDATABUFFERSOURCE: + { + err = iFactory->CreateSourceControl(KDataBufferSourceControl, tempCtrl); + User::LeaveIfError(err); + + iMDataBufferSource = static_cast(tempCtrl); + MDataBuffer* headerData = NULL; + User::LeaveIfError(iMDataBufferSource->Open(*iMimeType, *headerData)); + iMDataBufferSource->AddObserver(*this); + break; + } + case EDESCRIPTORSOURCE: + { + err = iFactory->CreateSourceControl(KDescriptorSourceControl, tempCtrl); + User::LeaveIfError(err); + iMDescriptorSource = static_cast(tempCtrl); + TInt size = 0; + // iFile.Size(size); will be used when Descriptor support will be implemented + + if (iDescData) + { + delete iDescData; + iDescData = NULL; + } + iDescData = HBufC8::NewL(size); + TPtr8 des = iDescData->Des(); + //iFile.Read(des); + User::LeaveIfError(iMDescriptorSource->Open(*iMimeType,*iDescData)); + iMDescriptorSource->AddObserver(*this); + break; + } + default: + break; + } + + iMStreamControl->AddSource(*tempCtrl); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::AddDataSourceToStreamL -"); +} + +void CMMAEMCPlayerBase::CleanupSource() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::CleanupSource +"); + if (iMDataBufferSource) + { + iMDataBufferSource->RemoveObserver(*this); + MSourceControl* objPtr = iMDataBufferSource; + iMStreamControl->RemoveSource(*objPtr); //added + objPtr->Close(); + iFactory->DeleteSourceControl(objPtr); + iMDataBufferSource = NULL; + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::CleanupSource -"); +} + +EXPORT_C MStreamControl* CMMAEMCPlayerBase::StreamControl() +{ + return iMStreamControl; +} + +EXPORT_C CMultimediaFactory* CMMAEMCPlayerBase::MMFactory() +{ + return iFactory; +} + +TBool CMMAEMCPlayerBase::IsFilePlayer() +{ + return EFalse; +} + +void CMMAEMCPlayerBase::StartL() +{ + // empty implementation + // should be overwritten in derived class +} + +void CMMAEMCPlayerBase::StopL(TBool /*aPostEvent*/) +{ + // empty implementation + // should be overwritten in derived class +} + +void CMMAEMCPlayerBase::DeallocateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::DeallocateL +"); + if (iState == EPrefetched) + { + // Change state first to enable AMMS to delete Effect API classes + ChangeState(ERealized); + + TInt err = iMStreamControl->Stop(); + ELOG1( EJavaMMAPI, "CMMAEMCPlayerBase::DeallocateL iMStreamControl->Stop = %d", err); + ResetSourceStreams(); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::DeallocateL -"); +} + + +void CMMAEMCPlayerBase::GetDuration(TInt64* aDuration) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::GetDuration +"); + if (iDuration == KTimeUnknown) + { + TInt64 duration(0); + TInt err = iMStreamControl->GetDuration(duration); + if (!err) + { + iDuration = duration; + } + } + *aDuration = iDuration; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerBase::GetDuration -"); +} + +void CMMAEMCPlayerBase::SetMediaTimeL(TInt64* aTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::SetMediaTimeL +"); + + // Negative values are not checked here + // because it's done already in Java side. + + // Get clip duration + TInt64 duration; + User::LeaveIfError(iMStreamControl->GetDuration(duration)); + LOG1( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::SetMediaTimeL iMStreamControl->GetDuration=%d", duration); + + TInt64 position; + + // If the desired media time is beyond the duration, + // the time is set to the end of the media. + if (*aTime > duration) + { + position = duration; + } + else + { + position = *aTime; + } + + // The controller must be in the PRIMED or PLAYING state + User::LeaveIfError(iMStreamControl->SetPosition(position)); + + // Reset cached media time, because actual set position may be + // something else than aTime. + iMediaTime = KTimeUnknown; + + // Inform about the position change to the StateListeners + ChangeState(iState); + + // Get the actual media time + GetMediaTime(aTime); + + iStartedEventTime = iMediaTime; + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::SetMediaTimeL -"); +} + +void CMMAEMCPlayerBase::GetMediaTime(TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::GetMediaTimeL +"); + TInt64 position(0); + + if (iMediaTime == KTimeUnknown || iState == EStarted) + { + + TInt error(iMStreamControl->GetPosition(position)); + + if (error == KErrNone) + { + TInt64 newTime = position; + + // Sanity check for media time going backwards or beyond the + // duration. + // Some native controls may return zero media time for + // a few moments just before playback will complete. + if (newTime < iMediaTime || + (iDuration > 0 && newTime > iDuration)) + { + GetDuration(&iMediaTime); + } + else + { + // set return value + iMediaTime = newTime; + } + } + else + { + ELOG1( EJavaMMAPI, "CMMAEMCPlayerBase::GetMediaTimeL: error=%d, returning TIME_UNKNOWN", error); + // cannot get media time + iMediaTime = KTimeUnknown; + } + } + *aMediaTime = iMediaTime; + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::GetMediaTimeL -"); +} + +void CMMAEMCPlayerBase::CloseL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::CloseL +"); + CMMAPlayer::CloseL(); + + iMStreamControl->Close(); + LOG( EJavaMMAPI, EInfo, "CMMAEMCPlayerBase::CloseL -"); +} + +void CMMAEMCPlayerBase::Event(MControl* /*aControl*/, TUint /*aEventType*/, TAny* /*aEventObject*/) +{ + //Not Called +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmaemcplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmaemcplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,192 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating EMC-based players. +* +*/ + + +// INCLUDE FILES +#include +#include + +#ifndef RD_JAVA_OMA_DRM_V2 +#include +#endif // RD_JAVA_OMA_DRM_V2 + +#include "cmmaemcplayerfactory.h" +#include "cmmaemcresolver.h" +#include "MimeTypes.h" + +// CONSTANTS +// Granularity used to create initial arrays. +const TInt KGranularity = 8; +_LIT(KContentTypePacketSrcNotIncluded, "application/x-ext-packetsrc"); + +CMMAEMCPlayerFactory::CMMAEMCPlayerFactory() +{ +} + +CMMAEMCPlayerFactory::~CMMAEMCPlayerFactory() +{ +} + +CMMAPlayer* CMMAEMCPlayerFactory::CreatePlayerL(const TDesC& aContentType) +{ + return CreatePlayerL(aContentType, NULL); +} + +CMMAPlayer* CMMAEMCPlayerFactory::CreatePlayerL(const TDesC& /*aContentType*/, + const TDesC* /*aFileName*/) +{ + return (CMMAPlayer*)NULL; +} + +CMMAPlayer* CMMAEMCPlayerFactory::CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC&) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerFactory::CreatePlayerL aMiddlePart = %S", + aMiddlePart.Ptr()); + CMMAEMCResolver* emcresolver = + CMMAEMCResolver::NewLC(); + + emcresolver ->SetFileNameL(&aMiddlePart); + + CMMAPlayer* player = NULL; + if (aProtocol == KMMAFileProtocol) + { + + //player = CreatePlayerL( emcresolver, &aMiddlePart ); + +#ifndef RD_JAVA_OMA_DRM_V2 + // if opening is failed, it might be DRM file, trying it + if (!player) + { + player = TryOpenDRMFileL(aMiddlePart); + } +#endif // RD_JAVA_OMA_DRM_V2 + + } + else + { + player = CreatePlayerL(emcresolver); + } + + CleanupStack::PopAndDestroy(emcresolver); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerFactory::CreatePlayerL aMiddlePart ok"); + return player; +} + +#ifndef RD_JAVA_OMA_DRM_V2 +CMMAPlayer* CMMAEMCPlayerFactory::TryOpenDRMFileL(const TDesC& aFileName) +{ + // we are most likely going to play this file + ContentAccess::TIntent intent = ContentAccess::EPlay; + + CContent* contentObj = CContent::NewL(aFileName); + CleanupStack::PushL(contentObj); + CData* dataObj = contentObj->OpenContentL(intent); + CleanupStack::PushL(dataObj); + User::LeaveIfError(dataObj->EvaluateIntent(intent)); + TBuf8 mimeType; + CMMAPlayer* player = NULL; + if (dataObj->GetMimeTypeL(mimeType)) + { + // we use 16bit mimeType + HBufC* mimeTypeBuf = HBufC::NewLC(mimeType.Length()); + mimeTypeBuf->Des().Copy(mimeType); + player = CreatePlayerL(*mimeTypeBuf, &aFileName); + CleanupStack::PopAndDestroy(mimeTypeBuf); + } + CleanupStack::PopAndDestroy(2); //dataObj, contentObj + return player; +} +#endif // RD_JAVA_OMA_DRM_V2 + +CMMAPlayer* CMMAEMCPlayerFactory::CreatePlayerL(const TDesC8& /*aHeaderData*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAEMCPlayerFactory::CreatePlayerL header data +"); + + return (CMMAPlayer*)NULL; +} + +void CMMAEMCPlayerFactory::GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) +{ + //CMMAEMCResolver class should contain the constant array of all supported mimetype defined in EMC api MimeTypes.h + if (!IsSupportedProtocolL(aProtocol)) + { + return; + } + CMMAEMCResolver* emcresolver = CMMAEMCResolver::NewLC(); + emcresolver->GetSupportedContentTypesL(aMimeTypeArray); + + CleanupStack::PopAndDestroy(emcresolver); +} + +void CMMAEMCPlayerFactory::GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + // Check that this is supported content type + if (!IsSupportedContentTypeL(aContentType)) + { + return; + } + aProtocolArray.AppendL(KMMAHttpProtocol); + aProtocolArray.AppendL(KMMAHttpsProtocol); +} + +TBool CMMAEMCPlayerFactory::IsSupportedProtocolL(const TDesC& aProtocol) +{ + // With null desc we are getting all + if (aProtocol == KNullDesC) + { + return ETrue; + } + CDesC16ArraySeg* protocols = new(ELeave) CDesC16ArraySeg(KGranularity); + CleanupStack::PushL(protocols); + GetSupportedProtocolsL(KNullDesC, *protocols); + TInt pos = KErrNotFound; + // Find returns 0 if there contentType is found + TBool retValue = (protocols->Find(aProtocol, pos) == 0); + CleanupStack::PopAndDestroy(protocols); + return retValue; +} + +TBool CMMAEMCPlayerFactory::IsSupportedContentTypeL(const TDesC& aContentType) +{ + // With null desc we are getting all + if (aContentType == KNullDesC) + { + return ETrue; + } + + // Content type application/x-ext-packetsrc + // must not be supported at the moment. + if (aContentType == KContentTypePacketSrcNotIncluded) + { + return EFalse; + } + + CDesC16ArraySeg* contentTypes = new(ELeave) CDesC16ArraySeg(KGranularity); + CleanupStack::PushL(contentTypes); + GetSupportedContentTypesL(KNullDesC, *contentTypes); + TInt pos = KErrNotFound; + // Find returns 0 if there contentType is found + TBool retValue = (contentTypes->Find(aContentType, pos) == 0); + CleanupStack::PopAndDestroy(contentTypes); + return retValue; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmaemcresolver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmaemcresolver.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,329 @@ +/* +* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaemcresolver.h" +#include "hxmetadatautil.h" +#include "apgcli.h" +#include "apmrec.h" + +using namespace multimedia; + +_LIT(KRVMimeType1, "video/x-pn-realvideo"); +_LIT(KRVMimeType2, "video/x-realvideo"); +_LIT(KRVMimeType3, "video/vnd.rn-realvideo"); + +// CONSTANTS + +CMMAEMCResolver* CMMAEMCResolver::NewLC() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: NewLC ++"); + CMMAEMCResolver* self = new(ELeave)CMMAEMCResolver(); + CleanupStack::PushL(self); + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: NewLC --"); + return self; +} + +CMMAEMCResolver::~CMMAEMCResolver() +{ + delete iContentType; + + delete iFileName; + + delete iMimeType; +} + +HBufC* CMMAEMCResolver::ContentTypeOwnership() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: ContentTypeOwnership ++"); + HBufC* ct = iContentType; + iContentType = NULL; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: ContentTypeOwnership --"); + return ct; +} + +HBufC8* CMMAEMCResolver::MimeTypeOwnership() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: MimeTypeOwnership ++"); + HBufC8* mt = iMimeType; + iMimeType = NULL; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: MimeTypeOwnership --"); + return mt; +} + +HBufC* CMMAEMCResolver::ContentType() +{ + return iContentType; +} + +void CMMAEMCResolver::SetFileNameL(const TDesC* aFileName) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: SetFileNameL ++"); + HBufC* fn = NULL; + if (aFileName) + { + fn = aFileName->AllocL(); + } + delete iFileName; + iFileName = fn; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: SetFileNameL --"); +} + +HBufC* CMMAEMCResolver::FileNameOwnership() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: FileNameOwnership ++"); + HBufC* fn = iFileName; + iFileName = NULL; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: FileNameOwnership --"); + return fn; +} + +void CMMAEMCResolver::SetMimeTypeL(const TDesC* aFileName) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: SetMimeTypeL +"); + if (iContentType) + { + delete iContentType; + iContentType = NULL; + } + iContentType = HBufC::NewL(KContentTypeMaxLength); + TBuf8 mimeType; + ResolveContentTypeL(*aFileName,mimeType); + iContentType->Des().Copy(mimeType); + iMimeType = HBufC8::NewL(mimeType.Length()); //8 bit Descriptor of iContentType + iMimeType->Des().Copy(mimeType); + + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: SetMimeTypeL -"); +} + +void CMMAEMCResolver::ResolveContentTypeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver::ResolveContentTypeL +"); + + if (iContentType) + { + delete iContentType; + iContentType = NULL; + } + if (iMimeType) + { + delete iMimeType; + iMimeType = NULL; + } + + iContentType = HBufC::NewL(KContentTypeMaxLength); + iMimeType = HBufC8::NewL(KContentTypeMaxLength); + + if (iFileName->Right(4).Compare(KAacFileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeAAC); + iMimeType->Des().Copy(KMimetypeAAC); + } + else if (iFileName->Right(4).Compare(KAmrFileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeAMR); + iMimeType->Des().Copy(KMimetypeAMR); + } + else if (iFileName->Right(4).Compare(KAwbFileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeAMRWB); + iMimeType->Des().Copy(KMimetypeAMRWB); + } + else if (iFileName->Right(4).Compare(KWmaFileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeXMSWMA); + iMimeType->Des().Copy(KMimetypeXMSWMA); + } + else if (iFileName->Right(3).Compare(KRaFileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeRM); + iMimeType->Des().Copy(KMimetypeRM); + } + else if (iFileName->Right(4).Compare(KMp3FileExtension()) == 0) + { + iContentType->Des().Copy(KMimetypeMPEG); + iMimeType->Des().Copy(KMimetypeMPEG); + } + else if (iHeaderData) + { + RApaLsSession ls; + TInt err; + err = ls.Connect(); + + if (iFileName->Right(3).Compare(KRmFileExtension()) == 0) + { + TBool res = IsRealVideoTypeL(*iHeaderData); + + if (!res) + { + iContentType->Des().Copy(KMimetypeRM); + iMimeType->Des().Copy(KMimetypeRM); + } + else + { + iContentType->Des().Copy(KNullDesC); + iMimeType->Des().Copy(KNullDesC8); + } + } + else if ((iFileName->Right(4).Compare(K3gpFileExtension()) == 0) || + (iFileName->Right(4).Compare(KMp4FileExtension()) == 0)) + { + TDataRecognitionResult result; + err = ls.RecognizeData(*iFileName, *iHeaderData, result); + if (!err && (result.iConfidence >= CApaDataRecognizerType::EProbable)) + { + iContentType->Des().Copy(result.iDataType.Des8()); + iMimeType->Des().Copy(result.iDataType.Des8()); + } + else + { + iContentType->Des().Copy(KNullDesC); + iMimeType->Des().Copy(KNullDesC8); + } + } + ls.Close(); + } + else + { + iContentType->Des().Copy(KNullDesC); + iMimeType->Des().Copy(KNullDesC8); + } + + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver::ResolveContentTypeL -"); +} +// + +void CMMAEMCResolver::ResolveContentTypeL(const TDesC& /*aFileName*/, TDes8& /*aMimeType*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: ResolveContentTypeL"); +} + +void CMMAEMCResolver::GetSupportedContentTypesL(CDesC16Array& aMimeTypeArray) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: GetSupportedContentTypesL +"); + // All supported mimetypes are taken from "MimeTypes.h" + TBuf16 tempBuf; + tempBuf.Copy(KMimetype3GPP); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetype3GPP2); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeAAC); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeAMR); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeAMRWB); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeMPEG); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeMP4); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeXMSWMA); + aMimeTypeArray.AppendL(tempBuf); + tempBuf.Zero(); + tempBuf.Copy(KMimetypeRM); + aMimeTypeArray.AppendL(tempBuf); + LOG( EJavaMMAPI, EInfo, "MMA:CMMAEMCResolver :: GetSupportedContentTypesL -"); +} + +// EMC - II +void CMMAEMCResolver::SetSourceInfoL(const HBufC8* aHeaderData) +{ + iHeaderData = aHeaderData; + ResolveContentTypeL(); +} + +TBool CMMAEMCResolver::IsRealVideoTypeL(const TDesC8& aHeader) +{ + TBool result = EFalse; + + CHXMetaDataUtility *putil; + putil = CHXMetaDataUtility::NewL(); + CleanupStack::PushL(putil); + TRAPD(err, putil->OpenDesL((TDesC8 &)aHeader)); + ELOG1( EJavaMMAPI, "MMA:CMMAEMCResolver::IsRealVideoTypeL, err = %d", err); + + if (err != KErrNone) + { + CleanupStack::Pop(putil); + putil->ResetL(); + delete putil; + return EFalse; + } + + TUint count = 0; + putil->GetMetaDataCount(count); + + TUint i; + HXMetaDataKeys::EHXMetaDataId id; + + for (i = 0; i < count; i++) + { + HBufC* pDes = NULL; + + putil->GetMetaDataAt(i, id, pDes); + + if (id == HXMetaDataKeys::EHXMimeType) + { + if (IsRealMimeTypeSupported(*pDes)) + { + result = ETrue; + } + } + } + + CleanupStack::Pop(putil); + + putil->ResetL(); + delete putil; + + return result; +} + +TBool CMMAEMCResolver::IsRealMimeTypeSupported(const TDesC& aMimeType) +{ + TBool match = EFalse; + + if (!aMimeType.Compare(KRVMimeType1())) + { + match = ETrue; + return match; + } + if (!aMimeType.Compare(KRVMimeType2())) + { + match = ETrue; + return match; + } + if (!aMimeType.Compare(KRVMimeType3())) + { + match = ETrue; + return match; + } + + return match; +} +// +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/cmmamanager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/cmmamanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,234 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class uses player factories to generate different players +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmamanager.h" +#include "cmmaaudioplayerfactory.h" +#include "cmmavideoplayerfactory.h" +#include "cmmaaudiorecorderfactory.h" +#include "cmmacameraplayerfactory.h" +#include "cmmamidiplayerfactory.h" +#include "cmmavideourlplayerfactory.h" +#include "cmmaaudiostreamplayerfactory.h" +//#include "cmmaanimationplayerfactory.h" + +#ifdef RD_JAVA_OMA_DRM_V2 +#include "cmmadrmplayerfactory.h" +#endif // RD_JAVA_OMA_DRM_V2 + +// index of CMMAAudioStreamPlayerFactory in iPlayerFactories +// if CMMAAudioStreamPlayerFactory is moved in iPlayerFactories +// this constant should be updated accordingly +const TInt KAudioStreamPlayerFactoryIndex = 2; + +CMMAManager::~CMMAManager() +{ + iPlayerFactories.ResetAndDestroy(); + iPlayerFactories.Close(); +} + +CMMAManager::CMMAManager() +{ +} + +void CMMAManager::ConstructL(TInt aMIDletSuiteID) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAManager::ConstructL +"); + // + // Create and insert known player factories + // + + CMMAVideoUrlPlayerFactory* videoUrlPlayerFactory = CMMAVideoUrlPlayerFactory::NewLC(); + AddPlayerFactoryL(videoUrlPlayerFactory); + CleanupStack::Pop(); // videoUrlPlayerFactory + + CMMAMIDIPlayerFactory* midiPlayerFactory = CMMAMIDIPlayerFactory::NewLC(); + AddPlayerFactoryL(midiPlayerFactory); + CleanupStack::Pop(); // midiPlayerFactory + + CMMAAudioStreamPlayerFactory* audioStreamPlayerFactory = + CMMAAudioStreamPlayerFactory::NewLC(); + AddPlayerFactoryL(audioStreamPlayerFactory); + CleanupStack::Pop(); // audioStreamPlayerFactory + + CMMAVideoPlayerFactory* videoPlayerFactory = CMMAVideoPlayerFactory::NewLC(); + AddPlayerFactoryL(videoPlayerFactory); + CleanupStack::Pop(); // videoPlayerFactory + + CMMAAudioPlayerFactory* audioPlayerFactory = CMMAAudioPlayerFactory::NewLC(); + AddPlayerFactoryL(audioPlayerFactory); + CleanupStack::Pop(); // audioPlayerFactory + + CMMAAudioRecorderFactory* audioRecorderFactory = + CMMAAudioRecorderFactory::NewLC(aMIDletSuiteID); + AddPlayerFactoryL(audioRecorderFactory); + CleanupStack::Pop(); // audioRecorderFactory + +/* + CMMAAnimationPlayerFactory* animationPlayerFactory = + CMMAAnimationPlayerFactory::NewLC(); + AddPlayerFactoryL(animationPlayerFactory); + CleanupStack::Pop(); // animationPlayerFactory +*/ + + // Add camera playerfactory only if there is a camera + if (CCamera::CamerasAvailable() > 0) + { + CMMACameraPlayerFactory* cameraPlayerFactory = + CMMACameraPlayerFactory::NewLC(); + AddPlayerFactoryL(cameraPlayerFactory); + CleanupStack::Pop(); // cameraPlayerFactory + } + +#ifdef RD_JAVA_OMA_DRM_V2 + CMMADRMPlayerFactory* drmPlayerFactory = + CMMADRMPlayerFactory::NewLC(videoPlayerFactory); + AddPlayerFactoryL(drmPlayerFactory); + CleanupStack::Pop(); // drmPlayerFactory +#endif // RD_JAVA_OMA_DRM_V2 + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAManager::ConstructL -"); +} + +void CMMAManager::StaticCreateManagerL(CMMAManager** aManager, + TInt aMIDletSuiteID) +{ + CMMAManager* self = new(ELeave) CMMAManager(); + + CleanupStack::PushL(self); + self->ConstructL(aMIDletSuiteID); + CleanupStack::Pop(); + + *aManager = self; +} + +/** + * Use factories to create a player from content type + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC& aContentType) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aContentType); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * Use factories to create a player from locator + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aProtocol, + aMiddlePart, + aParameters); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * Use factories to create a player from header data + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC8& aHeaderData) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aHeaderData); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * From MMMAPlayerFactory. Get all supported protocols + */ +void CMMAManager::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aSupportedProtocols) +{ + // Query supported protocols from all player factories + for (TInt i = 0; i < iPlayerFactories.Count(); i++) + { + iPlayerFactories[ i ]->GetSupportedProtocolsL(aContentType, + aSupportedProtocols); + } +} + +/** + * From MMMAPlayerFactory. Get all supported content types + */ +void CMMAManager::GetSupportedContentTypesL( + const TDesC& aProtocol, + CDesC16Array& aContentTypes) +{ + // Get all supported content types from PlayerFactories + for (TInt i = 0; i < iPlayerFactories.Count(); i++) + { + iPlayerFactories[ i ]->GetSupportedContentTypesL(aProtocol, + aContentTypes); + } +} + +EXPORT_C void CMMAManager::AddPlayerFactoryL(MMMAPlayerFactory* aPlayerFactory) +{ + User::LeaveIfError(iPlayerFactories.Append(aPlayerFactory)); +} + +void CMMAManager::SetSourceInfoL(const TUint8* aHeader, TInt aLength) +{ + + if (iPlayerFactories.Count() > KAudioStreamPlayerFactoryIndex) + { + // assumption - iPlayerFactories[KAudioStreamPlayerFactoryIndex] is CMMAAudioStreamPlayerFactory + CMMAAudioStreamPlayerFactory* audiostreamplayerfactory = + static_cast(iPlayerFactories[ KAudioStreamPlayerFactoryIndex ]); + audiostreamplayerfactory->SetSourceInfoL(aHeader, aLength); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.emc/emcsourceinfo.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.emc/emcsourceinfo.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,79 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +#include + +#include + +#include "com_nokia_microedition_media_protocol_EMCSourceInfo.h" +#include "cmmamanager.h" + +LOCAL_C void SetHeaderDataL( + CMMAManager* aManager, + const TUint8* aHeader, + TInt aLength) +{ + aManager->SetSourceInfoL(aHeader, aLength); +} + +/* + * Class: com_nokia_microedition_media_protocol_http_EMCSourceInfo + * Method: _writeHeaderData + * Signature: (II[B)V + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_protocol_EMCSourceInfo__1writeHeaderData +(JNIEnv* aJni, jobject, jint aEventSourceHandle, jint aManagerHandle, jbyteArray aHeader) +{ + // Development time check. + __ASSERT_DEBUG((aEventSourceHandle > 0) && (aManagerHandle > 0), User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager* >(aManagerHandle); + + if (aHeader) + { + // Get pointer to Java header data + jbyte* data = aJni->GetByteArrayElements(aHeader, NULL); + + // if data is null Java data could not be obtained to native and + // KErrNoMemory is returned to Java + if (!data) + { + return KErrNoMemory; + } + + TInt headerDataLength = aJni->GetArrayLength(aHeader); + + TInt err = eventSource->ExecuteTrap(&SetHeaderDataL, + manager, + (const TUint8*)data, + headerDataLength); + + // release bytes got with GetByteArrayElements + aJni->ReleaseByteArrayElements(aHeader, + data, + 0); + + return err; + } + else + { + // if aHeader is NULL, this method should not have been called + // from java + return KErrBadHandle; + } +} diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.mmf/cmmamanager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.mmf/cmmamanager.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,225 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class uses player factories to generate different players +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "CMMAManager.h" +#include "CMMAAudioPlayerFactory.h" +#include "CMMAVideoPlayerFactory.h" +#include "CMMAAudioRecorderFactory.h" +#include "CMMACameraPlayerFactory.h" +#include "CMMAMidiPlayerFactory.h" +#include "CMMAVideoUrlPlayerFactory.h" + +#ifdef __MMA_AUDIOSTREAMING__ +#include "CMMAAudioStreamPlayerFactory.h" +#endif // __MMA_AUDIOSTREAMING__ + +#ifdef __MMA_ANIMATED_GIF__ +#include "CMMAAnimationPlayerFactory.h" +#endif // __MMA_ANIMATED_GIF__ + +#ifdef RD_JAVA_OMA_DRM_V2 +#include "CMMADRMPlayerFactory.h" +#endif // RD_JAVA_OMA_DRM_V2 + +CMMAManager::~CMMAManager() +{ + iPlayerFactories.ResetAndDestroy(); + iPlayerFactories.Close(); +} + +CMMAManager::CMMAManager() +{ +} + +void CMMAManager::ConstructL(TInt aMIDletSuiteID) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAManager::ConstructL +"); + // + // Create and insert known player factories + // + + CMMAVideoUrlPlayerFactory* videoUrlPlayerFactory = CMMAVideoUrlPlayerFactory::NewLC(); + AddPlayerFactoryL(videoUrlPlayerFactory); + CleanupStack::Pop(); // videoUrlPlayerFactory + + CMMAMIDIPlayerFactory* midiPlayerFactory = CMMAMIDIPlayerFactory::NewLC(); + AddPlayerFactoryL(midiPlayerFactory); + CleanupStack::Pop(); // midiPlayerFactory + + CMMAVideoPlayerFactory* videoPlayerFactory = CMMAVideoPlayerFactory::NewLC(); + AddPlayerFactoryL(videoPlayerFactory); + CleanupStack::Pop(); // videoPlayerFactory + +#ifdef __MMA_AUDIOSTREAMING__ + CMMAAudioStreamPlayerFactory* audioStreamPlayerFactory = + CMMAAudioStreamPlayerFactory::NewLC(); + AddPlayerFactoryL(audioStreamPlayerFactory); + CleanupStack::Pop(); // audioStreamPlayerFactory +#endif // __MMA_AUDIOSTREAMING__ + + CMMAAudioPlayerFactory* audioPlayerFactory = CMMAAudioPlayerFactory::NewLC(); + AddPlayerFactoryL(audioPlayerFactory); + CleanupStack::Pop(); // audioPlayerFactory + + CMMAAudioRecorderFactory* audioRecorderFactory = + CMMAAudioRecorderFactory::NewLC(aMIDletSuiteID); + AddPlayerFactoryL(audioRecorderFactory); + CleanupStack::Pop(); // audioRecorderFactory + +#ifdef __MMA_ANIMATED_GIF__ + CMMAAnimationPlayerFactory* animationPlayerFactory = + CMMAAnimationPlayerFactory::NewLC(); + AddPlayerFactoryL(animationPlayerFactory); + CleanupStack::Pop(); // animationPlayerFactory +#endif // __MMA_ANIMATED_GIF__ + + // Add camera playerfactory only if there is a camera + if (CCamera::CamerasAvailable() > 0) + { + CMMACameraPlayerFactory* cameraPlayerFactory = + CMMACameraPlayerFactory::NewLC(); + AddPlayerFactoryL(cameraPlayerFactory); + CleanupStack::Pop(); // cameraPlayerFactory + } + +#ifdef RD_JAVA_OMA_DRM_V2 + CMMADRMPlayerFactory* drmPlayerFactory = + CMMADRMPlayerFactory::NewLC(videoPlayerFactory); + AddPlayerFactoryL(drmPlayerFactory); + CleanupStack::Pop(); // drmPlayerFactory +#endif // RD_JAVA_OMA_DRM_V2 + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAManager::ConstructL -"); +} + +void CMMAManager::StaticCreateManagerL(CMMAManager** aManager, + TInt aMIDletSuiteID) +{ + CMMAManager* self = new(ELeave) CMMAManager(); + + CleanupStack::PushL(self); + self->ConstructL(aMIDletSuiteID); + CleanupStack::Pop(); + + *aManager = self; +} + +/** + * Use factories to create a player from content type + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC& aContentType) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aContentType); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * Use factories to create a player from locator + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aProtocol, + aMiddlePart, + aParameters); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * Use factories to create a player from header data + * + */ +CMMAPlayer* CMMAManager::CreatePlayerL(const TDesC8& aHeaderData) +{ + // Try all factories, in order + TInt factoryCount = iPlayerFactories.Count(); + for (TInt i = 0; i < factoryCount; i++) + { + CMMAPlayer* player = iPlayerFactories[ i ]->CreatePlayerL(aHeaderData); + if (player) + { + return player; + } + } + // No PlayerFactory accepted the content type + return NULL; +} + +/** + * From MMMAPlayerFactory. Get all supported protocols + */ +void CMMAManager::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aSupportedProtocols) +{ + // Query supported protocols from all player factories + for (TInt i = 0; i < iPlayerFactories.Count(); i++) + { + iPlayerFactories[ i ]->GetSupportedProtocolsL(aContentType, + aSupportedProtocols); + } +} + +/** + * From MMMAPlayerFactory. Get all supported content types + */ +void CMMAManager::GetSupportedContentTypesL( + const TDesC& aProtocol, + CDesC16Array& aContentTypes) +{ + // Get all supported content types from PlayerFactories + for (TInt i = 0; i < iPlayerFactories.Count(); i++) + { + iPlayerFactories[ i ]->GetSupportedContentTypesL(aProtocol, + aContentTypes); + } +} + +EXPORT_C void CMMAManager::AddPlayerFactoryL(MMMAPlayerFactory* aPlayerFactory) +{ + User::LeaveIfError(iPlayerFactories.Append(aPlayerFactory)); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.nga/cmmasurfacewindow.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.nga/cmmasurfacewindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,728 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* in graphics surface based displays for Helix engine. +* +*/ + +// Include Files +#include +#include "cmmasurfacewindow.h" +#include "cmmaplayer.h" + +// Used for iDisplay member +#include "mmmadisplay.h" + +CMMASurfaceWindow* CMMASurfaceWindow::NewL( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer) +{ + CMMASurfaceWindow* self = + new(ELeave) CMMASurfaceWindow(aEventSource, + aPlayer); + return self; +} + +// Destructor (virtual by CBase) +CMMASurfaceWindow::~CMMASurfaceWindow() +{ + // It's not allowed to delete any nonsharable object here. + // This must be done in Destroy(). + // If the iDisplay is set, + // instance should be deleted by sending + // event from UI to be received by MUiEventConsumer. +} + +CMMASurfaceWindow::CMMASurfaceWindow( + MMAFunctionServer* aEventSource, + CMMAPlayer* aPlayer): + iEventSource(aEventSource), + iPlayer(aPlayer), + iVideoDisplayInitState(EUIResourcesAndSurfaceParametersNotSet) +{ + // Empty rect until video size is known + iContentRect.SetRect(0, 0, 0, 0); + iParentRect.SetRect(0, 0, 0, 0); + iRWindowRect.SetRect(0, 0, 0, 0); +} + +void CMMASurfaceWindow::SetDestinationBitmapL(CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing +} + +void CMMASurfaceWindow::DrawFrameL(const CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing +} + +void CMMASurfaceWindow::SetDrawRectThread( const TRect& aRect ) + { + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDrawRectThread TL %d %d", + aRect.iTl.iX, aRect.iTl.iY ); + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDrawRectThread BR %d %d", + aRect.iBr.iX, aRect.iBr.iY ); + + iContentRect = aRect; + + TInt error = StaticRedrawVideo(*this); + if ( KErrNone != error ) + { + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::SetDrawRectThread, StaticRedrawVideo error = %d", error); + } + } + +void CMMASurfaceWindow::SetRWindowRect(const TRect& aRect, + MMMADisplay::TThreadType aThreadType) +{ + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetRWindowRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetRWindowRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + + iRWindowRect = aRect; + + if (MMMADisplay::EMmaThread == aThreadType) + { + if (iDisplay) + { + /* iDisplay->UIGetCallback( *this, + CMMASurfaceWindow::ESetDrawRect); + */ + // MMAPI UI 3.x req. + iDisplay->GetCallbackInUiThread( (TInt)CMMASurfaceWindow::ESetDrawRect ); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetRWindowRect after GetCallbackInUiThread " ); + + } + } + else if (MMMADisplay::EUiThread == aThreadType) + { + /*TInt error = StaticRedrawVideo(*this); + if (KErrNone != error) + { + LOG1(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetRWindowRect, StaticRedrawVideo error = %d", error); + } + */ + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetRWindowRect else GetCallbackInUiThread + " ); + iDisplay->GetCallbackInUiThread( (TInt)CMMASurfaceWindow::ESetDrawRect ); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetRWindowRect else GetCallbackInUiThread -" ); + } +} + +void CMMASurfaceWindow::SetDrawRect( const TRect& aRect ) + { + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDrawRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY ); + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDrawRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY ); + + iContentRect = aRect; + if ( iDisplay ) + { + // iDisplay->UIGetCallback( *this, + // CMMASurfaceWindow::ESetDrawRect ); + // MMAPI UI 3.x req. + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ESetDrawRect); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetDrawRect, after GetCallbackInUiThread"); + } + } + +TInt CMMASurfaceWindow::StaticRedrawVideo(CMMASurfaceWindow& aSurfaceWindow) +{ + TRAPD(error, aSurfaceWindow.RedrawVideoL()); + return error; +} + +void CMMASurfaceWindow::RedrawVideoL() +{ + if (!iMediaClientVideoDisplay) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::RedrawVideoL: no MediaClientVideoDisplay set, aborting -" ); + return; + } + + if (iWindow) + { + TRect contentRect; + if (iVisible) + { + contentRect = iContentRect; + ScaleVideoL(contentRect); + } + else + { + TRect emptyRect(0,0,0,0); + contentRect = emptyRect; + } + + // align parent rect with respect to RWindow + TRect relativeParentRect; + relativeParentRect = iParentRect; + relativeParentRect.Move(-iRWindowRect.iTl); + + // setting video draw rect and adjusting it to window + TRect drawRect = contentRect; + drawRect.Move(relativeParentRect.iTl); + + // Area where should be drawn is the intersection of drawRect and relativeParentRect. + TRect areaRect = relativeParentRect; + areaRect.Intersection(drawRect); + + iMediaClientVideoDisplay->SetWindowClipRectL(*iWindow, + areaRect, + iVideoCropRegion); + + iMediaClientVideoDisplay->SetVideoExtentL(*iWindow, + areaRect, + iVideoCropRegion); + + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::RedrawVideoL: RedrawWindows() areaRect is %d X %d",areaRect.Width(),areaRect.Height() ); + + iMediaClientVideoDisplay->RedrawWindows(iVideoCropRegion); + } +} + +void CMMASurfaceWindow::ScaleVideoL(const TRect& aRect) +{ + // return without scaling incase cropregion dimensions are zero + if (!(iVideoCropRegion.Width() && iVideoCropRegion.Height())) + { + return; + } + + TReal32 numerator = 1.0f * (aRect.Width() - iVideoCropRegion.Width()); + TReal32 denominator = 1.0f * iVideoCropRegion.Width(); + // new video width percent(relative to the original width) to + // which video has to be scaled. + TReal32 scaleWidthPercent = 100.0f + (100.0f * (numerator/denominator)); + + numerator = 1.0f * (aRect.Height() - iVideoCropRegion.Height()); + denominator = 1.0f * iVideoCropRegion.Height(); + // new video height percent(relative to the original height) to + // which video has to be scaled. + TReal32 scaleHeightPercent = 100.0f + (100.0f * (numerator/denominator)); + + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow:: scaleWidthPercent, scaleHeightPercent %d %d", + scaleWidthPercent, scaleHeightPercent ); + + iMediaClientVideoDisplay->SetScaleFactorL(scaleWidthPercent, + scaleHeightPercent, + iVideoCropRegion); +} + +const TRect& CMMASurfaceWindow::DrawRect() +{ + return iContentRect; +} + +TSize CMMASurfaceWindow::WindowSize() +{ + return iParentRect.Size(); +} + +void CMMASurfaceWindow::SetPosition(const TPoint& aPosition) +{ + iContentRect = TRect(aPosition, iContentRect.Size()); + TInt error = StaticRedrawVideo(*this); + if (KErrNone != error) + { + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::SetPosition, StaticRedrawVideo error = %d", error); + } +} + +TBool CMMASurfaceWindow::IsVisible() const + { + LOG1( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::IsVisible %d ", iVisible ); + return iVisible; + } + +void CMMASurfaceWindow::SetVisible(TBool aVisible, TBool aUseEventServer) +{ + LOG1( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetVisible aVisible %d", aVisible ); + RPointerArray< CMMAPlayer > players = iEventSource->Players(); + + if (players.Find(iPlayer) != KErrNotFound) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetVisible : Player found"); + if (aVisible != iVisible) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetVisible: Changed visibility" ); + iVisible = aVisible; + if (iDisplay) + { + //MMAPI UI 3.x req. + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ESetDrawRect); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetVisible,GetCallbackInUiThread"); + } + + + /* if (aUseEventServer) + { + TInt error = StaticRedrawVideo(*this); + if (KErrNone != error) + { + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::SetVisible, StaticRedrawVideo error = %d", error); + } + } + else // in MMA thread, so switch to UI thread + { + if (iDisplay) + { + //iDisplay->UIGetCallback(*this, + // CMMASurfaceWindow::ESetDrawRect ); + //MMAPI UI 3.x req. + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ESetDrawRect); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::SetVisible,GetCallbackInUiThread"); + } + } + */ + } + } +} + +void CMMASurfaceWindow::SetWindowRect(const TRect& aRect,MMMADisplay::TThreadType /*aThreadType*/) +{ + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetWindowRect aRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetWindowRect aRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + + iParentRect = aRect; +} + +void CMMASurfaceWindow::SetVideoCropRegion(const TRect& aRect) +{ + // video size + iVideoCropRegion = aRect; +} + +const TRect& CMMASurfaceWindow::WindowRect() +{ + return iParentRect; +} + +void CMMASurfaceWindow::ContainerDestroyed() +{ + // We are in UI thread context now. + CleanVideoDisplay(); +} + +void CMMASurfaceWindow::SetDisplay(MMMADisplay *aDisplay) +{ + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDisplay +" ); + + if (iDisplay != aDisplay) + { + if (iDisplay) + { + // Clear the resources created within the old Display + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ECleanVideoDisplay ); + } + + // Set the new Display + iDisplay = aDisplay; + + /*if ( iDisplay ) + { + // Get a DSA resources for the new Display + //iDisplay->UIGetDSAResources( *this, MMMADisplay::EMmaThread ); + CMMACanvasDisplay* display = static_cast< CMMACanvasDisplay* >( iDisplay ); + + display->GetWindowResources( this, MMMADisplay::EMmaThread ); + } + + */ + } + + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::SetDisplay -" ); + } + +void CMMASurfaceWindow::ContainerSet() + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ContainerSet" ); + // We are in UI thread now + + // Container was probably not set when + // iDisplay was set, + // we can now try get the DSA stuff again + if (iDisplay) + { + // Get a DSA stuff for the new Display +// iDisplay->UIGetDSAResources( *this, MMMADisplay::EUiThread ); + } + } + +void CMMASurfaceWindow::Destroy() + { + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::Destroy" ); + // Delete itself + delete this; + } + +void CMMASurfaceWindow::ProcureWindowResourcesFromQWidget(RWsSession * aWs, + CWsScreenDevice* aScreenDevice, + RWindowBase* aWindow) + { + iWs = aWs; + iScreenDevice = aScreenDevice; + iWindow = aWindow; + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget" ); + switch ( iVideoDisplayInitState ) + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -7" ); + case EUIResourcesAndSurfaceParametersNotSet: + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -8" ); + iVideoDisplayInitState = + EUIResourcesSetAndSurfaceParametersNotSet; + } + break; + case ESurfaceParametersSetAndUIResourcesNotSet: + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -9" ); + iVideoDisplayInitState = + EUIResourcesAndSurfaceParametersSet; + } + break; + // can not occur + case EUIResourcesSetAndSurfaceParametersNotSet: + case EUIResourcesAndSurfaceParametersSet: + default: + {LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -10" ); + __ASSERT_DEBUG( EFalse, User::Invariant() ); + } + break; + } + + if( iVideoDisplayInitState == EUIResourcesAndSurfaceParametersSet ) + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -11" ); + TRAPD(error, InitVideoDisplayL()); + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::ProcureWindowResourcesFromQWidget -12" ); + if ( KErrNone != error ) + { + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::MdcDSAResourcesCallback, error = %d", error); + } + } + + } +/* +void CMMASurfaceWindow::MdcDSAResourcesCallback( + RWsSession &aWs, + CWsScreenDevice &aScreenDevice, + RWindowBase &aWindow ) + { + LOG(EJavaMMAPI,EInfo, "MID::CMMASurfaceWindow::MdcDSAResourcesCallback" ); + + // We are in UI thread context now. + iWs = &aWs; + iScreenDevice = &aScreenDevice; + iWindow = &aWindow; + + switch ( iVideoDisplayInitState ) + { + case EUIResourcesAndSurfaceParametersNotSet: + { + iVideoDisplayInitState = + EUIResourcesSetAndSurfaceParametersNotSet; + } + break; + case ESurfaceParametersSetAndUIResourcesNotSet: + { + iVideoDisplayInitState = + EUIResourcesAndSurfaceParametersSet; + } + break; + // can not occur + case EUIResourcesSetAndSurfaceParametersNotSet: + case EUIResourcesAndSurfaceParametersSet: + default: + { + __ASSERT_DEBUG( EFalse, User::Invariant() ); + } + break; + } + + if( iVideoDisplayInitState == EUIResourcesAndSurfaceParametersSet ) + { + TRAPD(error, InitVideoDisplayL()); + if ( KErrNone != error ) + { + LOG1(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::MdcDSAResourcesCallback, error = %d", error); + } + } + } +*/ +void CMMASurfaceWindow::UICallback( TInt aCallbackId ) + { + // We are in UI thread context now. + LOG1( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::MdcUICallback CallbackId = %d", aCallbackId ); + + TInt error = KErrNone; + switch (aCallbackId) + { + case ERemoveSurface: + { + DoRemoveSurface(); + } + break; + case ESetDrawRect: + { + error = StaticRedrawVideo(*this); + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::MdcUICallback,StaticRedrawVideo error = %d", error); + } + break; + case EInitVideoDisplay: + { + TRAP(error, InitVideoDisplayL()); + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::MdcUICallback,InitVideoDisplayL error = %d", error); + } + break; + case ESetChangedSurfaceParameters: + { + DoSetChangedSurfaceParameters(); + } + break; + case EResetSurfaceParameters: + { + DoResetSurfaceParameters(); + } + break; + case ECleanVideoDisplay: + { + CleanVideoDisplay(); + } + break; + case EDestroyWindow: + { + Destroy(); + } + break; + default: + { + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + break; + } +} + +void CMMASurfaceWindow::SetSurfaceParameters(const TSurfaceId& aSurfaceId, + const TRect& aCropRect, + const TVideoAspectRatio& aPixelAspectRatio) +{ + iSurfaceId = aSurfaceId; + iCropRect = aCropRect; + iPixelAspectRatio = aPixelAspectRatio; + + switch ( iVideoDisplayInitState ) + { + case EUIResourcesAndSurfaceParametersNotSet: + { + iVideoDisplayInitState = + ESurfaceParametersSetAndUIResourcesNotSet; + } + break; + case EUIResourcesSetAndSurfaceParametersNotSet: + { + iVideoDisplayInitState = + EUIResourcesAndSurfaceParametersSet; + } + break; + // control reaches below two switch cases when + // playback is looped using setLoopCount() in java. + case ESurfaceParametersSetAndUIResourcesNotSet: + { + } + break; + // update surface parameters and return with out calling + // InitVideoDisplayL again. + case EUIResourcesAndSurfaceParametersSet: + { + // iDisplay->UIGetCallback( *this, CMMASurfaceWindow::EResetSurfaceParameters ); + //MMAPI UI 3.x req. + LOG(EJavaMMAPI,EInfo,"CMMASurfaceWindow::SetSurfaceParameters : switch case EUIResourcesAndSurfaceParametersSet +"); + iDisplay->GetCallbackInUiThread( (TInt)CMMASurfaceWindow::EResetSurfaceParameters ); + LOG(EJavaMMAPI,EInfo,"CMMASurfaceWindow::SetSurfaceParameters : switch case EUIResourcesAndSurfaceParametersSet -"); + return; + } + // break; not reachable + default: // can not occur + { + __ASSERT_DEBUG( EFalse, User::Invariant() ); + } + break; + } + + if ( iVideoDisplayInitState == EUIResourcesAndSurfaceParametersSet ) + { + //iDisplay->UIGetCallback( *this, CMMASurfaceWindow::EInitVideoDisplay ); + //MMAPI UI 3.x req. + iDisplay->GetCallbackInUiThread( (TInt)CMMASurfaceWindow::EInitVideoDisplay ); + LOG(EJavaMMAPI,EInfo,"CMMASurfaceWindow::SetSurfaceParameters,EUIResourcesAndSurfaceParametersSet"); + } + } + +void CMMASurfaceWindow::SetChangedSurfaceParameters(const TSurfaceId& aSurfaceId, + const TRect& aCropRect, + const TVideoAspectRatio& aPixelAspectRatio) +{ + iSurfaceId = aSurfaceId; + iCropRect = aCropRect; + iPixelAspectRatio = aPixelAspectRatio; + + if (iDisplay) + { + //iDisplay->UIGetCallback(*this, CMMASurfaceWindow::ESetChangedSurfaceParameters); + LOG(EJavaMMAPI,EInfo,"CMMASurfaceWindow::SetChangedSurfaceParameters + "); + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ESetChangedSurfaceParameters); + LOG(EJavaMMAPI,EInfo,"CMMASurfaceWindow::SetChangedSurfaceParameters - "); + + } +} + +void CMMASurfaceWindow::RemoveSurface() +{ + if (iDisplay) + { + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::ERemoveSurface); + } +} + +void CMMASurfaceWindow::DoRemoveSurface() +{ + if (iMediaClientVideoDisplay) + { + iMediaClientVideoDisplay->RemoveSurface(); + LOG(EJavaMMAPI,EInfo,"MID::CMMASurfaceWindow::DoRemoveSurface, Surface Removed"); + + } +} + +void CMMASurfaceWindow::DoResetSurfaceParameters() +{ + __ASSERT_DEBUG((iMediaClientVideoDisplay != NULL), User::Invariant()); + + if (iMediaClientVideoDisplay) + { + iMediaClientVideoDisplay->RemoveSurface(); + TInt error = iMediaClientVideoDisplay->SurfaceCreated(iSurfaceId, + iCropRect, + iPixelAspectRatio, + iVideoCropRegion); + + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::DoResetSurfaceParameters,SurfaceCreated error = %d", error); + + iMediaClientVideoDisplay->RedrawWindows(iVideoCropRegion); + } +} + +void CMMASurfaceWindow::DoSetChangedSurfaceParameters() +{ + if (iMediaClientVideoDisplay) + { + TInt error = iMediaClientVideoDisplay->SurfaceParametersChanged(iSurfaceId, + iCropRect, + iPixelAspectRatio); + + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::DoSetChangedSurfaceParameters,SurfaceParametersChanged, error = %d", error); + + iMediaClientVideoDisplay->RedrawWindows(iVideoCropRegion); + } +} + +void CMMASurfaceWindow::InitVideoDisplayL() +{ + if (iVideoDisplayInitState != EUIResourcesAndSurfaceParametersSet) + { + User::Leave(KErrNotReady); + } + + // check that this is the first time we are creating instance. + if (iMediaClientVideoDisplay) + { + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + + iMediaClientVideoDisplay = + CMediaClientVideoDisplay::NewL(iScreenDevice->GetScreenNumber(), + iSurfaceId, + iCropRect, + iPixelAspectRatio); + + // video is not scaled untill user requests explicitly + // so retain same video width & height. + TReal32 scaleWidthPercent = 100.0f; + TReal32 scaleHeightPercent = 100.0f; + + // video rotation feature not supported in MMAPI + TVideoRotation videoRotation(EVideoRotationNone); + // no automatic scaling, can be controlled only via VideoControl + TAutoScaleType autoScaleType = EAutoScaleNone; + + // always align video to the top left corner of the display area + TInt horizontalPosition(EHorizontalAlignLeft); + TInt verticalPosition(EVerticalAlignTop); + + TInt error = iMediaClientVideoDisplay->SurfaceCreated(iSurfaceId, + iCropRect, + iPixelAspectRatio, + iVideoCropRegion); + + ELOG1( EJavaMMAPI, "MID::CMMASurfaceWindow::InitVideoDisplayL error = %d", error ); + User::LeaveIfError(error); + + iMediaClientVideoDisplay->AddDisplayWindowL(iWindow, + iContentRect, + iVideoCropRegion, + iContentRect, + scaleWidthPercent, + scaleHeightPercent, + videoRotation, + autoScaleType, + horizontalPosition, + verticalPosition, + (RWindow*)iWindow); + + RedrawVideoL(); +} + +void CMMASurfaceWindow::CleanVideoDisplay() +{ + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::CleanVideoDisplay +" ); + + SetVisible(EFalse, ETrue); + if (iMediaClientVideoDisplay) + { + if (iWindow) + { + iMediaClientVideoDisplay->RemoveDisplayWindow(*iWindow); + } + iMediaClientVideoDisplay->RemoveSurface(); + delete iMediaClientVideoDisplay; + + iMediaClientVideoDisplay = NULL; + iWindow = NULL; + iScreenDevice = NULL; + iWs = NULL; + } + + LOG( EJavaMMAPI, EInfo, "MID::CMMASurfaceWindow::CleanVideoDisplay -" ); +} + + +CMMAPlayer* CMMASurfaceWindow::UiPlayer() + { + return iPlayer; + } +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src.nga/cmmavideoplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src.nga/cmmavideoplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,525 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing video. +* +*/ + +// INCLUDE FILES +#include +#include + +#include "cmmavideoplayer.h" +#include "mmmadisplay.h" +#include "mmafunctionserver.h" +#include "cmmasurfacewindow.h" + +// CONSTANTS +_LIT(KVideoControlName, "VideoControl"); + +CMMAVideoPlayer* CMMAVideoPlayer::NewLC( + CMMAMMFResolver* aResolver) +{ + CMMAVideoPlayer* self = + new(ELeave) CMMAVideoPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAVideoPlayer::~CMMAVideoPlayer() + { + LOG(EJavaMMAPI,EInfo, "MMA::CMMAVideoPlayer::~CMMAVideoPlayer" ); + + // Window is not able to send any + // callback requests to UI from now. + if (iSurfaceWindow) + { + iSurfaceWindow->SetDisplay(NULL); + } + + if ( iDisplay && iDisplay->HasContainer() ) + { + // Window will delete itself + // after all pending events are processed + // (lazy delete) +// iDisplay->UIGetCallback( + // *iSurfaceWindow, CMMASurfaceWindow::EDestroyWindow ); + iDisplay->GetCallbackInUiThread((TInt)CMMASurfaceWindow::EDestroyWindow ); + } + else + { + delete iSurfaceWindow; + } + + if (iDisplay) + { + TRAPD(err, iDisplay->SetWindowL(NULL)); + if (err != KErrNone) + { + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + } + + delete iEmptySnapshotImage; + delete iActiveSchedulerWait; +} + +CMMAVideoPlayer::CMMAVideoPlayer( + CMMAMMFResolver* aResolver): + CMMAAudioPlayer(aResolver), + iVideoControllerCustomCommands(iController), + iVideoPlayControllerCustomCommands(iController), + iVideoPlaySurfaceSupportCustomCommands(iController) +{ + iMMASurface.iPrevSurfaceAvailable = EFalse; +} + +void CMMAVideoPlayer::ConstructL() +{ + CMMAAudioPlayer::ConstructL(); + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; +} + +EXPORT_C void CMMAVideoPlayer::SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster) +{ + CMMAPlayer::SetPlayerListenerObjectL(aListenerObject, + aJni, + aEventPoster); + + // this method must be called only ones + __ASSERT_DEBUG(!iSurfaceWindow, User::Invariant()); + + // create window for videoplayer + // event poster is always MMAFunctionServer type. + + iSurfaceWindow = CMMASurfaceWindow::NewL( + static_cast< MMAFunctionServer* >(iEventPoster), + this); +} + +EXPORT_C void CMMAVideoPlayer::SetDisplayL(MMMADisplay* aDisplay) +{ + // now it is ready to draw + iDisplay = aDisplay; + iDisplay->SetWindowL( iSurfaceWindow ); + iSurfaceWindow->SetDisplay( aDisplay ); + iDisplay->SetUIPlayer(this); + + +/* + // if state < prefeteched then we dont know actual source size yet + // and it will be set after prefetch + if ( iState >= EPrefetched ) + { + SourceSizeChanged(); + } + */ + } +void CMMAVideoPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::RealizeL" ); + // DataSource must have at least 1 stream or + // we must have file to play + if ((iSourceStreams.Count() == 0) && !iFileName) + { + User::Leave(KErrNotEnoughStreams); + } + + // If file locator is used, then file is prefetched + // in realized state so that FramePositioningControl + // can acquire frame count in REALIZED state + if (iFileName) + { + PrefetchFileL(); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + // If the player has not changed state during wait, + // Then there is an error condition. + if (iState != ERealized) + { + User::Leave(KErrNotSupported); + } + } + else + { + CMMAPlayer::RealizeL(); + } +} + +void CMMAVideoPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrefetchL" ); + if (iFileName) + { + // File has already been prefetched when realizing + + // If initDisplayMode was called before prefetch, + // then the display must notified about source size. + if (iDisplay) + { + SourceSizeChanged(); + } + + PostActionCompletedFile(); + ChangeState( EPrefetched ); + } + else + { + // Using TDes -- load the whole video + iSourceStreams[ 0 ]->ReadAllL(); + } + // CMMASourceStream will notify with ReadCompleted +} + +EXPORT_C void CMMAVideoPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoPlayer::ReadCompletedL: status = %d", aStatus ); + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + TRAPD(err, PrefetchDataL(aData)); + if (err != KErrNone) + { + PostActionCompleted(err); + } + // action completed event will be delivered from handleEvent + } +} + +void CMMAVideoPlayer::HandleEvent(const TMMFEvent& aEvent) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoPlayer::HandleEvent %d", aEvent.iEventType.iUid ); + + // event KMMFEventCategoryPlaybackComplete is handled by both Video + // and Audio players. first it should be handled by Video player + if (aEvent.iEventType == KMMFEventCategoryPlaybackComplete) + { + iSurfaceWindow->RemoveSurface(); + } + + // KNotCompleteVideoError can be notified when video is not complete + // ( missing sound ) but still can be played. Because + // CMMAAudioPlayer::HandleEvent fails with all negative error codes, + // do not call it with KNotCompleteVideoError error when preparing. + if ((aEvent.iErrorCode != KNotCompleteVideoError) || + (aEvent.iEventType != KMMFEventCategoryVideoPrepareComplete)) + { + CMMAAudioPlayer::HandleEvent(aEvent); + } + + if (aEvent.iEventType == KMMFEventCategoryVideoSurfaceCreated) + { + if (aEvent.iErrorCode == KErrNone) + { + TSurfaceId surfaceId; + TRect cropRect; + TVideoAspectRatio pixelAspectRatio; + + iVideoPlaySurfaceSupportCustomCommands.GetSurfaceParameters(surfaceId, + cropRect, + pixelAspectRatio); + + if (iMMASurface.iPrevSurfaceAvailable) + { + // free Surface + TInt error = iVideoPlaySurfaceSupportCustomCommands.SurfaceRemoved(iMMASurface.iPrevSurfaceId); + if (KErrNone != error) + { + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::HandleEvent:SurfaceRemoved error, %d", aEvent.iErrorCode); + } + } + iMMASurface.iPrevSurfaceId = surfaceId; + iMMASurface.iPrevSurfaceAvailable = ETrue; + + iSurfaceWindow->SetSurfaceParameters(surfaceId, + cropRect, + pixelAspectRatio); + + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: KMMFEventCategoryVideoSurfaceCreated, surface parameters set" ); + } + else + { + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::HandleEvent: error getting surface parameters, %d", aEvent.iErrorCode ); + } + } + else if (aEvent.iEventType == KMMFEventCategoryVideoSurfaceParametersChanged) + { + if (aEvent.iErrorCode == KErrNone) + { + TSurfaceId surfaceId; + TRect cropRect; + TVideoAspectRatio pixelAspectRatio; + + iVideoPlaySurfaceSupportCustomCommands.GetSurfaceParameters(surfaceId, + cropRect, + pixelAspectRatio); + + if (iMMASurface.iPrevSurfaceAvailable) + { + // free Surface + TInt error = iVideoPlaySurfaceSupportCustomCommands.SurfaceRemoved(iMMASurface.iPrevSurfaceId); + if (KErrNone != error) + { + LOG1( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent:SurfaceRemoved error, %d", aEvent.iErrorCode); + } + } + iMMASurface.iPrevSurfaceAvailable = ETrue; + iMMASurface.iPrevSurfaceId = surfaceId; + + iSurfaceWindow->SetChangedSurfaceParameters(surfaceId, + cropRect, + pixelAspectRatio); + + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: KMMFEventCategoryVideoSurfaceParametersChanged" ); + } + else + { + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::HandleEvent: surface parameters changed error, %d", aEvent.iErrorCode ); + } + } + else if (aEvent.iEventType == KMMFEventCategoryVideoRemoveSurface) + { + if (aEvent.iErrorCode == KErrNone) + { + if (iMMASurface.iPrevSurfaceAvailable) + { + // free Surface + TInt error = iVideoPlaySurfaceSupportCustomCommands.SurfaceRemoved(iMMASurface.iPrevSurfaceId); + if (KErrNone != error) + { + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::HandleEvent:SurfaceRemoved error, %d", aEvent.iErrorCode); + } + iMMASurface.iPrevSurfaceAvailable = EFalse; + } + } + else + { + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::HandleEvent:KMMFEventCategoryVideoRemoveSurface error, %d", aEvent.iErrorCode); + } + } + // video opened, preparing + else if (aEvent.iEventType == KMMFEventCategoryVideoOpenComplete) + { + if (aEvent.iErrorCode == KErrNone) + { + TInt error = iVideoPlaySurfaceSupportCustomCommands.UseSurfaces(); + ELOG1( EJavaMMAPI, "MMA::CMMAVideoPlayer::HandleEvent::After UseSurfaces(), error = %d", error ); + TInt prepareError(iVideoPlayControllerCustomCommands.Prepare()); + if (prepareError != KErrNone) + { + // opening failed, notifying java + PostActionCompleted(prepareError); + } + } + else + { + // opening failed, notifying java + PostActionCompleted(aEvent.iErrorCode); + } + } + // final state of prefetch ( prepare completed ) + else if (aEvent.iEventType == KMMFEventCategoryVideoPrepareComplete) + { + // This callback must be handled differently depending on whether + // player is created for a file locator or for a stream. When file + // locator is used, this callback is made in realized state. For + // stream it is made in prefetched state. + PrepareDisplay(); + if (iFileName) + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: Using filename, change state to REALIZED" ); + + // If there is an error condition, then the player state is not + // changed, which indicates the error condition to StartL when + // the ActiveSchedulerWait returns. KNotCompleteVideoError is not + // considered as an error condition, instead it indicates that some + // elements of the media cannot be played (e.g. video OR audio) + if (aEvent.iErrorCode == KErrNone || + aEvent.iErrorCode == KNotCompleteVideoError) + { + ChangeState(ERealized); + } + __ASSERT_DEBUG(iActiveSchedulerWait->IsStarted(), User::Invariant()); + iActiveSchedulerWait->AsyncStop(); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::HandleEvent: Not using filename, change state to PREFETCHED" ); + CompletePrefetch(aEvent.iErrorCode); + } + } + else // in case of any other event + { + if (aEvent.iErrorCode != KErrNone) + { + PostActionCompleted(aEvent.iErrorCode); //some other error + } + } +} + +void CMMAVideoPlayer::CompletePrefetch(TInt aError) +{ + ELOG1( EJavaMMAPI, "CMMAVideoPlayer::CompletePrefetch + error = %d",aError); + // Post KNotCompleteVideoError as KErrNone to the Java side, because + // video can be played. + if (aError == KNotCompleteVideoError) + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch KNotCompleteVideoError "); + // release java + PostActionCompleted(KErrNone); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch CompleteVideoError "); + // release java + PostActionCompleted(aError); + } + + if (aError == KErrNone || aError == KNotCompleteVideoError) + { + ChangeState(EPrefetched); + } + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::CompletePrefetch - "); +} + +void CMMAVideoPlayer::PrepareDisplay() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrepareDisplay +" ); + // construction should have leaved if iSurfaceWindow does not exist + __ASSERT_DEBUG(iSurfaceWindow, + User::Panic(_L("CMMVideoPlayer::iSurfaceWindow is null"), + KErrArgument)); + + //First place where we are certain that source size can be fetched + TSize sourceSize; + + TInt err = iVideoControllerCustomCommands.GetVideoFrameSize(sourceSize); + + ELOG1( EJavaMMAPI, "MID::CMMAVideoPlayer::PrepareDisplay: GetVideoFrameSize err = %d", err ); + + // Still we did not get the size of video + if ((err != KErrNone) || + (sourceSize.iWidth <= 0) || + (sourceSize.iHeight <= 0)) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: No sourcesize found, using SurfaceWindow size" ); + // setting size to window size (client rect) + sourceSize = iSurfaceWindow->WindowSize(); + } + + // If 1x1 was got (the default size of form), it must be replaced + // with a valid size as controller will not accept 1x1. + if ((sourceSize.iWidth < KMMAVideoMinDimension) || + (sourceSize.iHeight < KMMAVideoMinDimension)) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: Unacceptable source size, using failsafe" ); + // This is a special case and ought to be used only in + // the rare case that real size is not got from stream. + sourceSize = TSize(KMMAVideoMinDimension, KMMAVideoMinDimension); + } + + iSourceSize = sourceSize; + + // If init has been already done + if (iDisplay) + { + LOG( EJavaMMAPI, EInfo, "MID::CMMAVideoPlayer::PrepareDisplay: display exists, changing source size" ); + SourceSizeChanged(); + } + + // Setting (in)visible if something has changed the DSA state + // (e.g. prepare). If initDisplayMode is not called, this will always + // set visibility to false. + iSurfaceWindow->SetVisible(iSurfaceWindow->IsVisible(), EFalse); + LOG( EJavaMMAPI, EInfo, "CMMAVideoPlayer::PrepareDisplay -" ); +} + +EXPORT_C const TDesC& CMMAVideoPlayer::Type() +{ + return KMMAVideoPlayer; +} + +EXPORT_C TSize CMMAVideoPlayer::SourceSize() +{ + return iSourceSize; +} + +EXPORT_C MMMASnapshot::TEncoding CMMAVideoPlayer::TakeSnapshotL(TRequestStatus* aStatus, + const TSize& /*aSize*/, + const CMMAImageSettings& /*aSettings*/) +{ + if (iEmptySnapshotImage) + { + // Ealier snapshot was not got with SnapshotBitmap method. + User::Leave(KErrInUse); + } + // frame can't be got from video player, but TCK requires that it should + // be available. So returning empty image + iEmptySnapshotImage = new(ELeave) CFbsBitmap(); + User::LeaveIfError(iEmptySnapshotImage->Create(TSize(1, 1), + EColor4K)); + + + User::RequestComplete(aStatus, KErrNone); + + // Return raw bitmap encoding and thus SnapshotEncoded() should not + // get called later on. + return EBitmap; +} + +EXPORT_C CFbsBitmap* CMMAVideoPlayer::SnapshotBitmap() +{ + // snapshot is not supported, returning empty image + CFbsBitmap* image = iEmptySnapshotImage; + + // ownership is transferred to caller + iEmptySnapshotImage = NULL; + return image; +} + +EXPORT_C HBufC8* CMMAVideoPlayer::SnapshotEncoded() +{ + // This method should never be called. + // Asserted in debug build to be sure. + __ASSERT_DEBUG(EFalse, User::Invariant()); + + return NULL; +} + +EXPORT_C void CMMAVideoPlayer::NotifyWithStringEvent( + CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) +{ + PostStringEvent(aEventType, aStringEventData); +} + +EXPORT_C MMMASnapshot* CMMAVideoPlayer::SnapshoterL() +{ + return this; +} + +void CMMAVideoPlayer::SourceSizeChanged() +{ + iDisplay->SourceSizeChanged(iSourceSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/canvasdisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/canvasdisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +#include "logger.h" +#include "com_nokia_microedition_media_control_MMACanvasDisplay.h" +#include "cmmacanvasdisplay.h" +#include "qwidget.h" +#include "cmmasurfacewindow.h" + + +/* + * Class: com_nokia_microedition_media_control_mmacanvasdisplay + * Method: _setVisible + * Signature: (IIZ)I + */ +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setVisible + (JNIEnv *, jobject, jint nativeDisplayHandle, jboolean isVisible) + { + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setVisible +"); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TBool visible = (TBool)isVisible; + display ->SetVisible(visible); + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setVisible -"); + } + +LOCAL_C void LocalSetContainerVisible(CMMADisplay* display,TBool visible) +{ + display ->SetContainerVisibility(visible); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setContainerVisible +(JNIEnv *, jobject,jint aEventSourceHandle, jint nativeDisplayHandle, jboolean isActive) +{ + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setContainerVisible +"); + MMAFunctionServer* eventSource = reinterpret_cast(aEventSourceHandle); + // need to call in Function server thread context because CMMADisplay's JNI pointer + // is valid in that thread context only. + + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TBool visible = (TBool)isActive; + + TInt error = eventSource->ExecuteTrap(&LocalSetContainerVisible, + display, + visible); + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setContainerVisible -"); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setFullScreenMode +(JNIEnv *, jobject, jint nativeDisplayHandle, jboolean isFullScreen) +{ + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setFullScreenMode +"); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TBool mode = (TBool)isFullScreen; + display ->SetFullScreenL(mode); + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setFullScreenMode -"); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setWindowToNative +(JNIEnv *, jobject,jint nativeDisplayHandle, jint qtWidgetHandle) +{ + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setWindowToNative + "); + QWidget *widget = reinterpret_cast(qtWidgetHandle); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + display->SetWindowResources(widget); + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setWindowToNative - "); +} + + +/* +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1nativeDummy +(JNIEnv *, jobject,) +{ +*/ + +LOCAL_C void LocalSourceSizeChanged(CMMADisplay* display,TInt width,TInt height) +{ + display->SourceSizeChanged(width,height); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setNativeWindowSize +(JNIEnv *, jobject,jint nativeDisplayHandle, jint aEventSourceHandle, jint eswtControlwidth,jint eswtControlheight) +{ + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setNativeWindowSize + "); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TInt width = eswtControlwidth; + TInt height = eswtControlheight; + MMAFunctionServer* eventSource = reinterpret_cast(aEventSourceHandle); + // need to call in Function server thread context because CMMADisplay's JNI pointer + // is valid in that thread context only. + TInt error = eventSource->ExecuteTrap(&LocalSourceSizeChanged, + display, + width, + height); + + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : setNativeWindowSize - "); +} + +LOCAL_C void LocalSetDisplayPosition(CMMADisplay* display,TInt uiX,TInt uiY,TInt vcX,TInt vcY) +{ + display->SetDisplayPosition(uiX,uiY,vcX,vcY); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setPosition +(JNIEnv *, jobject,jint nativeDisplayHandle,jint aEventSourceHandle,jint uiX,jint uiY,jint vcX,jint vcY) +{ + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : _setPosition + "); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TInt uiControlLocationX = uiX; + TInt uiControlLocationY = uiY; + TInt videoControlLocationX = vcX; + TInt videoControlLocationY = vcY; + MMAFunctionServer* eventSource = reinterpret_cast(aEventSourceHandle); + // need to call in Function server thread context because CMMADisplay's JNI pointer + // is valid in that thread context only. + TInt error = eventSource->ExecuteTrap(&LocalSetDisplayPosition, + display, + uiControlLocationX, + uiControlLocationY, + videoControlLocationX, + videoControlLocationY); + + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : _setPosition - "); +} + + + + +LOCAL_C void LocalSetDisplaySize(CMMADisplay* display,TInt vcX,TInt vcY) +{ + LOG2(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : LocalSetDisplaySize vcX = %d,vcY=%d ",vcX,vcY); + TSize size(vcX,vcY); + display->SetDisplaySizeL(size); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_MMACanvasDisplay__1setDisplaySize +(JNIEnv *, jobject,jint nativeDisplayHandle,jint aEventSourceHandle,jint width,jint height) +{ + LOG2(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : _setDisplaySize + width = %d,height = %d",width,height); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + TInt vc_width = width; + TInt vc_height = height; + MMAFunctionServer* eventSource = reinterpret_cast(aEventSourceHandle); + // need to call in Function server thread context because CMMADisplay's JNI pointer + // is valid in that thread context only. + LOG2(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : _setDisplaySize + vc_width = %d,vc_height = %d",vc_width,vc_height); + TInt error = eventSource->ExecuteTrap(&LocalSetDisplaySize, + display, + vc_width, + vc_height); + + LOG(EJavaMMAPI,EInfo,"JNI_canvasdisplay.cpp : _setDisplaySize - "); +} \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudiometadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudiometadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAAudioMetaDataControl is a concrete class for getting +* metadata from an audio media. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaaudiometadatacontrol.h" + +CMMAAudioMetaDataControl::CMMAAudioMetaDataControl( + RMMFController& aController) + : iController(aController) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioMetaDataControl constructor called."); +} + +TInt CMMAAudioMetaDataControl::KeyCountL() +{ + TInt entries = 0; + + User::LeaveIfError(iController.GetNumberOfMetaDataEntries(entries)); + return entries; +} + +HBufC* CMMAAudioMetaDataControl::KeyL(TInt aIndex) +{ + CMMFMetaDataEntry* currEntry = NULL; + + currEntry = iController.GetMetaDataEntryL(aIndex); + CleanupStack::PushL(currEntry); + HBufC* key = currEntry->Name().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + + return key; +} + + +/* + * Get the value of given audio metadata key. The ownership of the created value + * (descriptor) is passed to the caller. + */ +HBufC* CMMAAudioMetaDataControl::KeyValueL(const TDesC& aKey) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioMetaDataControl::GetKeyValueL() called."); + + HBufC* retVal = NULL; + CMMFMetaDataEntry* currEntry = NULL; + + TInt nEntries = 0; + User::LeaveIfError(iController.GetNumberOfMetaDataEntries(nEntries)); + + for (TInt i = 0; i < nEntries; ++i) + { + currEntry = iController.GetMetaDataEntryL(i); + + if (0 == aKey.Compare(currEntry->Name())) + { + CleanupStack::PushL(currEntry); + retVal = currEntry->Value().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + break; + } + + delete currEntry; + } + + User::LeaveIfNull(retVal); + return retVal; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudioplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudioplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,326 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +#include +#include +#include +#include +#include "cmmaaudioplayer.h" + +const TInt KPlayerPriority = KAudioPriorityRecording; +const TInt KErrorMessageSize = 32; + +const TUid KSourceUid = { KMmfUidDescriptorSource }; +const TUid KFileSourceUid = { KMmfUidFileSource }; +_LIT(KErrDefaultError, "Symbian OS Error: %d"); + +const TInt KMinIntervalBeforePrime = 0; + +CPlaybackCompletedCallback* CPlaybackCompletedCallback::NewL(MPlaybackCompletedCallback& aObs) +{ + CPlaybackCompletedCallback* self = new(ELeave)CPlaybackCompletedCallback(aObs); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CPlaybackCompletedCallback::~CPlaybackCompletedCallback() +{ + Cancel(); +} + +void CPlaybackCompletedCallback::RunL() +{ + iObs.HandlePlaybackCompleteL(); +} + +TInt CPlaybackCompletedCallback::RunError(TInt aError) +{ + iObs.ErrorPlaybackComplete(aError); + return KErrNone; +} + +CPlaybackCompletedCallback::CPlaybackCompletedCallback(MPlaybackCompletedCallback& aObs) + : CTimer(EPriorityStandard), iObs(aObs) +{ + CActiveScheduler::Add(this); +} + +void CPlaybackCompletedCallback::Callback() +{ + if (!IsActive()) + After(KMinIntervalBeforePrime); +} + +CMMAAudioPlayer* CMMAAudioPlayer::NewLC( + CMMAMMFResolver* aResolver) +{ + CMMAAudioPlayer* self = new(ELeave) CMMAAudioPlayer(aResolver); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + + +CMMAAudioPlayer::~CMMAAudioPlayer() +{ + + delete iPlaybackCompleted; +} + + +CMMAAudioPlayer::CMMAAudioPlayer( + CMMAMMFResolver* aResolver): + CMMAMMFPlayerBase(aResolver) +{ +} + + +void CMMAAudioPlayer::ConstructL() +{ + CMMAMMFPlayerBase::ConstructL(); + + iPlaybackCompleted = CPlaybackCompletedCallback::NewL(*this); +} + + +EXPORT_C void CMMAAudioPlayer::PrefetchDataL(const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAAudioPlayer::PrefetchDataL aData size %d", + aData.Size()); + + // player priority settings + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = KPlayerPriority; + prioritySettings.iPref = EMdaPriorityPreferenceTimeAndQuality; + prioritySettings.iState = EMMFStatePlaying; + + TMMFDescriptorConfig srcConfig; + srcConfig().iDes = (TAny*)&aData; // wants pointer to TPtr8 + srcConfig().iDesThreadId = RThread().Id(); + + User::LeaveIfError(DoOpen(KSourceUid, + srcConfig, + KUidMmfAudioOutput, + KNullDesC8, + prioritySettings)); + + User::LeaveIfError(iController.Prime()); +} + +EXPORT_C void CMMAAudioPlayer::PrefetchFileL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAAudioPlayer::Prefetching from file"); + + // player priority settings + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = KPlayerPriority; + prioritySettings.iPref = EMdaPriorityPreferenceTimeAndQuality; + prioritySettings.iState = EMMFStatePlaying; + + TMMFFileConfig srcConfig; + srcConfig().iPath = iFileName->Des(); + + User::LeaveIfError(DoOpen(KFileSourceUid, + srcConfig, + KUidMmfAudioOutput, + KNullDesC8, + prioritySettings)); + + User::LeaveIfError(iController.Prime()); +} + +EXPORT_C void CMMAAudioPlayer::PlayCompleteL(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioPlayer::PlayCompleteL +"); + TInt64 time; + GetDuration(&time); + iMediaTime = time; + iStartedEventTime = 0; + + ChangeState(EPrefetched); // ready to play again + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, time); + + if (aError == KErrNone) + { + iRepeatCount++; + + // priming again for allowing e.g. mediatime setting + User::LeaveIfError(iController.Prime()); + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + + TTimeIntervalMicroSeconds position(0); + User::LeaveIfError(iController.SetPosition(position)); + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } + LOG( EJavaMMAPI, EInfo, "CMMAAudioPlayer::PlayCompleteL -"); +} + +void CMMAAudioPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioPlayer::RealizeL"); + // DataSource must have at least 1 stream or + // we must have file to play + if ((iSourceStreams.Count() == 0) && !iFileName) + { + User::Leave(KErrNotEnoughStreams); + } + CMMAPlayer::RealizeL(); +} + + +void CMMAAudioPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioPlayer::PrefetchL"); + __ASSERT_DEBUG((iSourceStreams.Count() > 0) || iFileName, User::Invariant()); + + if (iFileName) + { + // prefetching the file + PrefetchFileL(); + // we can go to prefetched state immediately + PostActionCompletedFile(); + ChangeState(EPrefetched); + //PostActionCompleted(KErrNone); + } + else + { + // Using TDes -- load the whole sound + iSourceStreams[ 0 ]->ReadAllL(); + } + // CMMASourceStream will notify with ReadCompleted +} + +const TDesC& CMMAAudioPlayer::Type() +{ + return KMMAAudioPlayer; +} + +// +// CMMASourceStreamReader finished read operation +// This is called when ReadL is completed in Prefetch() +// +void CMMAAudioPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAAudioPlayer::ReadCompletedL: status = %d", aStatus); + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + TRAPD(err, PrefetchDataL(aData)); + if (err == KErrNone) + { + ChangeState(EPrefetched); + } + PostActionCompleted(err); + } +} + + +void CMMAAudioPlayer::HandleEvent(const TMMFEvent& aEvent) +{ + LOG( EJavaMMAPI, EInfo, "MID::CMMAAudioPlayer::HandleEvent"); + TInt err = aEvent.iErrorCode; + if (iState == EStarted) + { + // normal situation; will loop in PlayCompleteL if looping is set + if ((err == KErrEof || err == KErrUnderflow || err == KErrNone) + && aEvent.iEventType == KMMFEventCategoryPlaybackComplete) + { + iPlaybackCompleted->Callback(); + } + } + + if (err == KErrDied && aEvent.iEventType == KMMFEventCategoryPlaybackComplete) + { + + // basically pausing the playback + //1. when the phone call is received/answered , the player will be pushed to pause state and phone call is given high priority. + //2. when the call ends the player will still be in pause state , In this case the user should resume the player. + err = iController.Pause(); + + if (iState == EStarted) + { + TInt64 time; + GetMediaTime(&time); + iStartedEventTime = time; + LOG( EJavaMMAPI, EInfo, "MID::CMMAAudioPlayer::Going to ChangeState( EPrefetched );"); + + PostLongEvent(CMMAPlayerEvent::EStopped, time); + ChangeState(EPrefetched); + } + } + + if (err != KErrNone && err != KErrDied) + { + ErrorPlaybackComplete(err); + } +} + +EXPORT_C void CMMAAudioPlayer::HandlePlaybackCompleteL() +{ + PlayCompleteL(KErrNone); +} + +EXPORT_C void CMMAAudioPlayer::ErrorPlaybackComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MID::CMMAAudioPlayer::ErrorPlaybackComplete: aError = %d", aError); + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, aError); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + + // Preparing controller for next try + TInt err = iController.Prime(); + if (err != KErrNone) + { + // Prime failed + errorMessage.Format(KErrDefaultError, err); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + // we cannot recover, going back to unrealized state + ChangeState(EUnrealized); + return; + } + + // If player was in started state, then error will change state to + // EPrefetched. In other cases the old state is retained. + if (iState == EStarted) + { + ChangeState(EPrefetched); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudioplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudioplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating wav player. +* +*/ + + +// INCLUDE FILES +#include +#include "cmmaaudioplayerfactory.h" +#include "cmmaaudioplayer.h" +#include "cmmaaudiovolumecontrol.h" +#include "cmmastoptimecontrol.h" +#include "cmmaaudiometadatacontrol.h" +#include "cmmammfratecontrol.h" + +_LIT(KMMAMP3ContentType, "audio/mp3"); +_LIT(KMMAMPEGContentType, "audio/mpeg"); + +CMMAAudioPlayerFactory* CMMAAudioPlayerFactory::NewLC() +{ + CMMAAudioPlayerFactory* pFactory = + new(ELeave) CMMAAudioPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAAudioPlayerFactory::CMMAAudioPlayerFactory() +{ +} + + +CMMAAudioPlayerFactory::~CMMAAudioPlayerFactory() +{ +} + +CMMAPlayer* CMMAAudioPlayerFactory::CreatePlayerL(const TDesC& aContentType) +{ + CMMAPlayer* player = NULL; + if (aContentType == KMMAMP3ContentType) + { + // If 'mp3' use 'mpeg' to create player, because audio controller + // does not recognize mp3 + player = CMMAMMFPlayerFactory::CreatePlayerL(KMMAMPEGContentType); + } + else + { + player = CMMAMMFPlayerFactory::CreatePlayerL(aContentType); + } + return player; +} + +CMMAPlayer* CMMAAudioPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + CMMAAudioPlayer* player = CMMAAudioPlayer::NewLC(aResolver); + + CMMAAudioVolumeControl* volumeControl = CMMAAudioVolumeControl::NewL(player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + + CMMAAudioMetaDataControl* metaDataControl = + new(ELeave) CMMAAudioMetaDataControl(player->Controller()); + CleanupStack::PushL(metaDataControl); + player->AddControlL(metaDataControl); + CleanupStack::Pop(metaDataControl); + + CMMAStopTimeControl* stopTimeControl = CMMAStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + CMMAMMFRateControl* rateControl = CMMAMMFRateControl::NewL(player); + CleanupStack::PushL(rateControl); + player->AddControlL(rateControl); + CleanupStack::Pop(rateControl); + + CleanupStack::Pop(player); + + return player; +} + +void CMMAAudioPlayerFactory::GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) +{ + // protocol is empty string all types must be returned. + if (IsSupportedProtocolL(aProtocol) || + (aProtocol == KNullDesC)) + { + // mp3 is not supported in the mmf, but support is + // added in CreatePlayerL( const TDesC& aContentType ) method. + aMimeTypeArray.AppendL(KMMAMP3ContentType); + + // all other types from mmf + CMMAMMFPlayerFactory::GetSupportedContentTypesL(aProtocol, + aMimeTypeArray); + } +} + +void CMMAAudioPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeAudio)); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudiorecordcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudiorecordcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: RecordControl for AudioRecorder +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaaudiorecordcontrol.h" + + +CMMAAudioRecordControl* CMMAAudioRecordControl::NewL( + CMMAAudioRecorder* aRecorder) +{ + CMMAAudioRecordControl* self = new(ELeave) CMMAAudioRecordControl(aRecorder); + CleanupStack::PushL(self); + self->ConstructL(); + aRecorder->InitializeL(&self->iFile, self); + CleanupStack::Pop(self); + return self; +} + +CMMAAudioRecordControl::~CMMAAudioRecordControl() +{ + // close controller to free temp file + if (iRecorder) + { + iRecorder->Deinitialize(); + } +} + + +CMMAAudioRecordControl::CMMAAudioRecordControl(CMMAAudioRecorder* aRecorder): + CMMARecordControl(aRecorder) +{ + iRecorder = aRecorder; + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecordControl()"); +} + +void CMMAAudioRecordControl::DoStartRecordL() +{ + iRecorder->StartRecordL(); +} + +void CMMAAudioRecordControl::DoStopRecordL() +{ + iRecorder->StopRecordL(); +} + +void CMMAAudioRecordControl::DoResetL() +{ + iRecorder->ResetL(); +} + +void CMMAAudioRecordControl::InitializeL() +{ + // already initialized, empty implementation +} + +TInt CMMAAudioRecordControl::SetRecordSizeLimitL(TInt aSize) +{ + return iRecorder->SetRecordSizeLimitL(aSize); +} + +void CMMAAudioRecordControl::HandleEvent(const TMMFEvent& aEvent) +{ + ELOG2( EJavaMMAPI, "MMA:CMMAAudioRecordControl::HandleEvent(type=%x,err=%d)", + aEvent.iEventType.iUid, aEvent.iErrorCode); + if (iState == ERecordRecording) + { + // Event's error code is KErrEof or KErrNone when record size limit + // is reached. When controller is stopped from java error code is + // KErrNone. + if ((aEvent.iEventType == KMMFEventCategoryPlaybackComplete) && + ((aEvent.iErrorCode == KErrNone) || + (aEvent.iErrorCode == KErrEof))) + { + HandleRecordSizeLimit(); + } + else if (aEvent.iErrorCode != KErrNone) + { + Error(aEvent.iErrorCode); + } + } +} + +// END OF FILE + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudiorecorder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudiorecorder.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,391 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for recording Audio +* +*/ + + +#include +#include +#include +#include +#include "cmmaaudiorecorder.h" +#include "cmmaoutputstream.h" + +const TInt KDefaultSize = KMaxTInt32; // Default record size limit + +CMMAAudioRecorder* CMMAAudioRecorder::NewLC( + CMMAMMFResolver* aResolver, + CMMAAudioSettings* aAudioSettings, + TInt aMIDletSuiteID) +{ + // Not using ELeave to avoid leave before owneship change of settings + CMMAAudioRecorder* self = new CMMAAudioRecorder(aResolver, aMIDletSuiteID); + if (!self) + { + delete aAudioSettings; + User::Leave(KErrNoMemory); + } + // Take the ownership of setting before any possible leaves + self->iSettings = aAudioSettings; + CleanupStack::PushL(self); + self->iWait = new(ELeave) CActiveSchedulerWait(); + self->ConstructL(); + return self; +} + + +CMMAAudioRecorder::~CMMAAudioRecorder() +{ + iFile.Close(); + delete iSettings; + delete iWait; +} + + +CMMAAudioRecorder::CMMAAudioRecorder( + CMMAMMFResolver* aResolver, + TInt /*aMIDletSuiteID*/): + CMMAMMFPlayerBase(aResolver), + iAudioRecordControllerCustomCommands(iController), + iAudioControllerRecCustomCommands(iController), + iRecordSizeLimit(KDefaultSize), + iPauseError(KErrNone), + iEOFReached(EFalse) +{ +} + +/** + * start the play + */ +void CMMAAudioRecorder::StartL() +{ + TInt64 time; + GetMediaTime(&time); + + PostLongEvent(CMMAPlayerEvent::EStarted, time); + ChangeState(EStarted); + PostActionCompletedStart(); +} + + +void CMMAAudioRecorder::StopL(TBool aPostEvent) +{ + if (iState == EStarted) + { + ChangeState(EPrefetched); + } + + if (aPostEvent) + { + TInt64 time; + GetMediaTime(&time); + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } +} + +void CMMAAudioRecorder::DoOpenL() +{ + // Make sure any existing controller is closed. + iEventMonitor->Cancel(); + iController.Close(); + + // player priority settings + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = EMdaPriorityMax; + prioritySettings.iPref = EMdaPriorityPreferenceTimeAndQuality; + prioritySettings.iState = EMMFStateRecording; + + // Try opening and configuring each controller in turn + TInt error = KErrNotSupported; + TInt index = 0; + + // Try controllers until found a good controller or out of list + while ((error != KErrNone) && + (index < iControllerInfos->Count())) + { + // Open the controller + error = iController.Open((*iControllerInfos)[ index ]->Uid(), + prioritySettings); + + // If the controller was opened without error, start receiving events from it. + if (!error) + { + iEventMonitor->Start(); + + // Add the data source to the controller. + error = iController.AddDataSource(KUidMmfAudioInput, KNullDesC8); + } + + // Add the data sink + if (!error) + { + TMMFFileHandleParams params(&iFile); + TPckg paramPckg = params; + error = iController.AddDataSink(KUidMmfFileSink, paramPckg, iSinkInfo); + } + + // If an error occurred in any of the above, close the controller. + if (error) + { + iEventMonitor->Cancel(); + iController.Close(); + } + + index++; + } + User::LeaveIfError(error); + + HBufC8* contentType8 = HBufC8::NewLC(iContentType->Length()); + contentType8->Des().Copy(*iContentType); + + TInt cInfoCount = iControllerInfos->Count(); + for (TInt i = 0; i < cInfoCount; i++) + { + CMMFControllerImplementationInformation* contrInfo = (*iControllerInfos)[ i ]; + const RMMFFormatImplInfoArray& recordFormats = contrInfo->RecordFormats(); + + for (TInt formatIndex = 0; formatIndex < recordFormats.Count(); formatIndex++) + { + CMMFFormatImplementationInformation* formatInfo = recordFormats[ formatIndex ]; + + if (formatInfo->SupportsMimeType(*contentType8)) + { + iSupplier.Set(formatInfo->Supplier()); + // Some of the controllers those support only one format can return KErrNotSupported + // error when setting the format, but still they can record that only supported format + // Ignoring this error + TInt err = iAudioControllerRecCustomCommands.SetSinkFormat(formatInfo->Uid()); + if ((err != KErrNotSupported)) + { + User::LeaveIfError(err); + } + break; + } + } + } + CleanupStack::PopAndDestroy(contentType8); + + // Do not set codec if it is default + if (iSettings->iDataType != TFourCC(KFourCCNULL)) + { + User::LeaveIfError( + iAudioControllerRecCustomCommands.SetCodec(KFourCCNULL, iSettings->iDataType)); + } + + // set the audio data settings ie sample rate & channels, if not defaults + if (iSettings->iRate != KDefaultRate) + { + User::LeaveIfError( + iAudioControllerRecCustomCommands.SetSinkSampleRate(iSettings->iRate)); + } + + if (iSettings->iChannels != KDefaultChannels) + { + User::LeaveIfError( + iAudioControllerRecCustomCommands.SetSinkNumChannels(iSettings->iChannels)); + } +} + +void CMMAAudioRecorder::PrefetchL() +{ + if (iResetController) + { + DoOpenL(); + } + User::LeaveIfError(iController.Prime()); + //PostActionCompleted(KErrNone); + PostActionCompletedFile(); + ChangeState(EPrefetched); +} + +void CMMAAudioRecorder::InitializeL(RFile* aFile, + MMMFControllerEventMonitorObserver* aObserver) +{ + iFile.Duplicate(*aFile); + iObserver = aObserver; + DoOpenL(); +} + +void CMMAAudioRecorder::Deinitialize() +{ + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::Deinitialize++"); + if (iEventMonitor) + { + iEventMonitor->Cancel(); + } + iController.Close(); + iFile.Close(); + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::Deinitialize--"); +} + +const TDesC& CMMAAudioRecorder::Type() +{ + return KMMAAudioRecorder; +} + +void CMMAAudioRecorder::StartRecordL() +{ + if (iResetController) + { + iResetController = EFalse; + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StartRecordL reopen controller"); + DoOpenL(); + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StartRecordL reopen done"); + } + + + User::LeaveIfError( + iAudioRecordControllerCustomCommands.SetMaxFileSize(iRecordSizeLimit)); + + LOG1( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StartRecordL Max File size set %d", iRecordSizeLimit); + + User::LeaveIfError(iController.Prime()); + User::LeaveIfError(iController.Play()); +} + + +void CMMAAudioRecorder::StopRecordL() +{ + // ! here is the workaround for pause + // Pause() doesn't work with all formats. + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StopRecordL Stopping"); + + TInt pauseError = iController.Pause(); + // if EOF is already reached return without + // doing any operation because controller is + // already in Stopped state + if (iEOFReached && (KErrNotReady == pauseError)) + { + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StopRecordL, EOF reached already"); + iEOFReached = EFalse; + return; + } + if (pauseError == KErrNotSupported) + { + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StopRecordL Stopped instead pause"); + User::LeaveIfError(iController.Stop()); + } + else + { + User::LeaveIfError(pauseError); +// wait only in HW +#ifndef __WINS__ + LOG( EJavaMMAPI, EInfo, "CMMAAudioRecorder::StopRecordL Stopped waiting"); + // wait for playback complete event + if (!iWait->IsStarted()) + { + iWait->Start(); + } + User::LeaveIfError(iError); +#endif + } + + + // prime controller and set position back to end (autorewind in controller) + User::LeaveIfError(iController.Prime()); + + TTimeIntervalMicroSeconds position(0); + User::LeaveIfError(iController.GetDuration(position)); + User::LeaveIfError(iController.SetPosition(position)); +} + +void CMMAAudioRecorder::GetDuration(TInt64* aDuration) +{ + // Return -1 in realized state in order to pass END_OF_MEDIA + // tests in TCK. MMFPlayerbase would return 0. + if (iState == ERealized) + { + *aDuration = KTimeUnknown; + } + else + { + CMMAMMFPlayerBase::GetDuration(aDuration); + } +} + +void CMMAAudioRecorder::DeallocateL() +{ + // set control to be reopened since + // deallocate closes it + if (iState == EPrefetched) + { + iResetController = ETrue; + } + CMMAMMFPlayerBase::DeallocateL(); +} + +void CMMAAudioRecorder::ResetL() +{ + iResetController = ETrue; +} + +const TInt KMMASymbianControllerLimit = 4096 + 44; // buffer size + header +_LIT(KSymbian, "Symbian"); + +TInt CMMAAudioRecorder::SetRecordSizeLimitL(TInt aSize) +{ + iRecordSizeLimit = aSize; + + // Wav and AU controller (supplied from symbian) is recording in 4kb buffers + // this controller does not record at all if size is smaller than 4kb and + // goes even in wierd state. + LOG1( EJavaMMAPI, EInfo, "CMMAAudioRecorder::SetRecordSizeLimitL Supplier = %S", iSupplier.Ptr()); + if ((iSupplier == KSymbian) && + (aSize < KMMASymbianControllerLimit)) + { + iRecordSizeLimit = KMMASymbianControllerLimit; + } + + // normal case is that recordsize is set just before starting + if (iState == EStarted) + { + LOG1( EJavaMMAPI, EInfo, "CMMAAudioRecorder::SetRecordSizeLimitL Setting while playing limit: %d", iRecordSizeLimit); + // trying to set max file size while recording + User::LeaveIfError( + iAudioRecordControllerCustomCommands.SetMaxFileSize(iRecordSizeLimit)); + } + return iRecordSizeLimit; +} + +void CMMAAudioRecorder::HandleEvent(const TMMFEvent& aEvent) +{ + ELOG1( EJavaMMAPI, "CMMAAudioRecorder::HandleEvent event error: %d", aEvent.iErrorCode); + + if (KErrEof == aEvent.iErrorCode) + { + iEOFReached = ETrue; + } + // if we are waiting event + if (iWait->IsStarted()) + { + iError = aEvent.iErrorCode; + iWait->AsyncStop(); + return; + } + TMMFEvent event = aEvent; + if ((event.iEventType == KMMFEventCategoryPlaybackComplete) && + ((event.iErrorCode == KErrNone) || + (event.iErrorCode == KErrEof))) + { + // Prime controller after playback complete, in order to get position/duration + event.iErrorCode = iController.Prime(); + } + if (iObserver) + { + iObserver->HandleEvent(event); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudiorecorderfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudiorecorderfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,159 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating audio recorder +* +*/ + + +// INCLUDE FILES +#include "cmmaaudiorecorderfactory.h" +#include "cmmaaudiorecordcontrol.h" +#include "cmmammfresolver.h" + +_LIT(KCaptureProtocol, "capture"); +_LIT(KAudioRecord, "audio"); +_LIT(KContentTypeAudioMp4NotIncluded, "audio/mp4"); + +CMMAAudioRecorderFactory* CMMAAudioRecorderFactory::NewLC(TInt aMIDletSuiteID) +{ + CMMAAudioRecorderFactory* pFactory = + new(ELeave) CMMAAudioRecorderFactory(aMIDletSuiteID); + CleanupStack::PushL(pFactory); + return pFactory; +} + + +CMMAAudioRecorderFactory::CMMAAudioRecorderFactory(TInt aMIDletSuiteID) +{ + iMIDletSuiteID = aMIDletSuiteID; +} + + +CMMAAudioRecorderFactory::~CMMAAudioRecorderFactory() +{ + delete iSettings; +} + +CMMAPlayer* CMMAAudioRecorderFactory::CreatePlayerL(const TDesC&) +{ + // record player cannot be created from content-type, since this is used only + // when we have also data + return NULL; +} + + +CMMAPlayer* CMMAAudioRecorderFactory::CreatePlayerL(const TDesC8&) +{ + // record player cannot be created with header data + return NULL; +} + +CMMAPlayer* CMMAAudioRecorderFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + // settings ownership transferred to audiorecorder + CMMAAudioSettings* tmpSettings = iSettings; + iSettings = NULL; + CMMAAudioRecorder* recorder = CMMAAudioRecorder::NewLC(aResolver, + tmpSettings, + iMIDletSuiteID); + + + + CMMAAudioRecordControl* audioRecordControl = CMMAAudioRecordControl::NewL(recorder); + CleanupStack::PushL(audioRecordControl); + recorder->AddControlL(audioRecordControl); + CleanupStack::Pop(audioRecordControl); + + CleanupStack::Pop(recorder); + + return recorder; +} + + +void CMMAAudioRecorderFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeAudio)); +} + +void CMMAAudioRecorderFactory::PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection) +{ + aResolver->SetRequiredRecordFormatSupportL(*aFormatSelection); +} + +CMMAPlayer* CMMAAudioRecorderFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // check that locator is capture:://audio + if ((aProtocol != KCaptureProtocol) || + (aMiddlePart != KAudioRecord)) + { + return NULL; + } + + // validate properties + CMMAAudioSettings* settings = + TMMAParameterValidator::ValidateAudioPropertiesL(aParameters); + delete iSettings; + iSettings = settings; + + // Find controller with content-type + return CMMAMMFPlayerFactory::CreatePlayerL(*iSettings->iContentType); +} + +void CMMAAudioRecorderFactory::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + // Support for MP4 recording disabled: All features cannot + // be supported for MP4 capture at the moment (e.g. pause) + if (IsSupportedContentTypeL(aContentType) && + (aContentType != KContentTypeAudioMp4NotIncluded)) + { + aProtocolArray.AppendL(KMMACaptureProtocol); + } +} + +void CMMAAudioRecorderFactory::GetSupportedContentTypesL( + const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) +{ + // protocol is empty string all types must be returned. + if (IsSupportedProtocolL(aProtocol) || + (aProtocol == KNullDesC)) + { + // get supported types from MMF + CMMAMMFPlayerFactory::GetSupportedContentTypesL(aProtocol, + aMimeTypeArray); + + // "audio/mp4" content type must not be supported + // for capture protocol + if (aProtocol == KCaptureProtocol) + { + TInt position(0); + TInt err = aMimeTypeArray.Find(KContentTypeAudioMp4NotIncluded, position); + if (err == KErrNone) + { + aMimeTypeArray.Delete(position); + aMimeTypeArray.Compress(); + } + } + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaaudiovolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaaudiovolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,65 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#include +#include "cmmaaudiovolumecontrol.h" +#include "cmmaaudioplayer.h" + + +CMMAAudioVolumeControl::CMMAAudioVolumeControl(CMMAAudioPlayer* aPlayer) + : CMMAVolumeControl(aPlayer), + iAudioPlayDeviceCommands(aPlayer->Controller()) +{ +} + +void CMMAAudioVolumeControl::ConstructL() +{ + ConstructBaseL(); +} + +EXPORT_C CMMAAudioVolumeControl* CMMAAudioVolumeControl::NewL(CMMAAudioPlayer* aPlayer) +{ + CMMAAudioVolumeControl* self = new(ELeave)CMMAAudioVolumeControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + + +void CMMAAudioVolumeControl::DoSetLevelL(TInt aLevel) +{ + TInt maxVolume = 0; + User::LeaveIfError(iAudioPlayDeviceCommands.GetMaxVolume(maxVolume)); + // aLevel is the desired volume in range 0..100 + User::LeaveIfError(iAudioPlayDeviceCommands.SetVolume( + aLevel * maxVolume / KMMAVolumeMaxLevel)); +} + +TInt CMMAAudioVolumeControl::DoGetLevelL() +{ + TInt maxVolume = 0; + User::LeaveIfError(iAudioPlayDeviceCommands.GetMaxVolume(maxVolume)); + __ASSERT_DEBUG(maxVolume != 0, User::Invariant()); + TInt volume = 0; + User::LeaveIfError(iAudioPlayDeviceCommands.GetVolume(volume)); + // result is in range 0..100 + return (volume * KMMAVolumeMaxLevel / maxVolume); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmabitmapwindow.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmabitmapwindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,140 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This abstract class implements MMMADisplayWindow functionality +* in CFbsBitmap based displays. +* +*/ + + +// Include Files +#include +#include +#include +#include "cmmabitmapwindow.h" + +// Destructor (virtual by CBase) +CMMABitmapWindow::~CMMABitmapWindow() +{ + delete iBitmap; + delete iBitmapDevice; + delete iBitmapContext; +} + +CMMABitmapWindow* CMMABitmapWindow::NewL() +{ + CMMABitmapWindow* self = new(ELeave)CMMABitmapWindow(); + return self; +} + +CMMABitmapWindow::CMMABitmapWindow(): + iDrawRect(0, 0, 0, 0), + iClientRect(0, 0, 0, 0) +{ +} + +void CMMABitmapWindow::SetDestinationBitmapL(CFbsBitmap* aBitmap) +{ + CFbsBitmap* bitmap = new(ELeave)CFbsBitmap(); + CleanupStack::PushL(bitmap); + User::LeaveIfError(bitmap->Duplicate(aBitmap->Handle())); + + // create context for bitmap + CFbsBitmapDevice* bitmapDevice = CFbsBitmapDevice::NewL(aBitmap); + CleanupStack::PushL(bitmapDevice); + + + CGraphicsContext* bitmapContext = NULL; + User::LeaveIfError(bitmapDevice->CreateContext(bitmapContext)); + + CleanupStack::Pop(bitmapDevice); // bitmapDevice + CleanupStack::Pop(bitmap); // bitmap + + delete iBitmap; + iBitmap = bitmap; + delete iBitmapDevice; + iBitmapDevice = bitmapDevice; + delete iBitmapContext; + iBitmapContext = bitmapContext; + + if (iDrawRect.IsEmpty()) + { + iDrawRect.SetSize(iBitmap->SizeInPixels()); + } +} + +void CMMABitmapWindow::DrawFrameL(const CFbsBitmap* aBitmap) +{ + if (iBitmap) + { + // leave in this function will panic thread + CFbsBitmap* bitmap = new(ELeave)CFbsBitmap(); + CleanupStack::PushL(bitmap); + User::LeaveIfError(bitmap->Duplicate(aBitmap->Handle())); + // set incoming bitmap display mode to 16MA + if (EColor16MU == bitmap->DisplayMode()) + { + bitmap->SetDisplayMode(EColor16MA); + } + AknIconUtils::ScaleBitmapL(iDrawRect, iBitmap, bitmap); + CleanupStack::PopAndDestroy(bitmap); + } +} + +void CMMABitmapWindow::SetDrawRect(const TRect& aRect) +{ + iDrawRect = aRect; +} + +void CMMABitmapWindow::SetDrawRectThread(const TRect& aRect) +{ + // Bitmap window's rect can be set in any thread. + SetDrawRect(aRect); +} + +const TRect& CMMABitmapWindow::DrawRect() +{ + return iDrawRect; +} + +TSize CMMABitmapWindow::WindowSize() +{ + if (!iBitmap) + { + // bitmap not ready returning currently set draw rect + return iDrawRect.Size(); + } + return iBitmap->SizeInPixels(); +} + +void CMMABitmapWindow::SetPosition(const TPoint& /*aPosition*/) +{ + // ignored, this is done by framework +} + +void CMMABitmapWindow::SetVisible(TBool /*aVisible*/, TBool /*aUseEventServer*/) +{ + // ignored, this is done by framework +} + +void CMMABitmapWindow::SetWindowRect(const TRect& aRect ,MMMADisplay::TThreadType /*aThreadType*/) +{ + iClientRect = aRect; +} + +const TRect& CMMABitmapWindow::WindowRect() +{ + return iClientRect; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmacameraplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmacameraplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,669 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing camera. +* +*/ + + +// INCLUDE FILES +#include +#include +#include "cmmacameraplayer.h" +#include "tmmaparametervalidator.h" +#include "mmmadisplay.h" +#include "cmmacamerasound.h" + +#if defined( __WINS__ ) +#include +#endif + +// CONSTANTS +_LIT8(KImageJpegMime, "image/jpeg"); +_LIT8(KJpegMime, "jpeg"); +_LIT(KVideoControlName, "VideoControl"); + +CMMACameraPlayer* CMMACameraPlayer::NewLC(TInt aCameraIndex) +{ + CMMACameraPlayer* self = new(ELeave) CMMACameraPlayer; + CleanupStack::PushL(self); + self->ConstructL(aCameraIndex); + return self; +} + +CMMACameraPlayer::~CMMACameraPlayer() +{ + LOG( EJavaMMAPI, EInfo, "CMMACameraPlayer::~CMMACameraPlayer"); + + // Free (duplicated) UI camera resources first. + // Window is not able to send any + // callback requests to UI from now. + if (iWindow) + { + iWindow->SetDisplay(NULL); + } + + if (iCamera) + { + iCamera->CancelCaptureImage(); + iCamera->Release(); + delete iCamera; + } + + delete iSnapshotEncoded; + delete iSnapshotBitmap; + delete iRealizeWait; + + if (iDisplay && iDisplay->HasContainer()) + { + // Window will delete itself + // after all pending events are processed + // (lazy delete) + // iDisplay->UIGetCallback( + // *iWindow, CMMACameraWindow::EDestroyWindow); + } + else + { + delete iWindow; + } + iWindow = NULL; +} + + +CMMACameraPlayer::CMMACameraPlayer(): + iDisplay(NULL), + iSourceSizeIndex(KErrNotFound), + iStartTime(KErrNotFound) +{ + iStopViewFinder = ETrue; +} + + +void CMMACameraPlayer::ConstructL(TInt aCameraIndex) +{ + CMMAPlayer::ConstructL(); + + if (aCameraIndex >= CCamera::CamerasAvailable()) + { + // image capture is not supported + User::Leave(KErrNotFound); + } + + iCamera = CCamera::NewL(*this, aCameraIndex); + + iWindow = CMMACameraWindow::NewL(iCamera->Handle()); + + TCameraInfo cameraInfo; + iCamera->CameraInfo(cameraInfo); + + if (cameraInfo.iNumImageSizesSupported < 1) + { + // image capture is not supported + User::Leave(KErrNotFound); + } + + // default snapshot size + iSourceSizeIndex = cameraInfo.iNumImageSizesSupported - 1; + + iRealizeWait = new(ELeave)CRealizeWait; +} + +TInt64 CMMACameraPlayer::CurrentTime() +{ + TTime time; + time.HomeTime(); + return time.Int64(); +} + +void CMMACameraPlayer::ResolveViewFinderSizeL(TSize& aSize) +{ + LOG( EJavaMMAPI, EInfo, "CMMACameraPlayer::ResolveViewFinderSizeL"); + + TSize resultSize; + + // The only way to find out the size is to start the view finder + // with a proper size (screen size). + + ResolveScreenSizeL(resultSize); + + // StartViewFinderBitmapsL changes resultSize to + // the used view finder size. + // Used to get the source size only. + iCamera->StartViewFinderBitmapsL(resultSize); + + // Bitmap viewfinder is not used anymore. + iCamera->StopViewFinder(); + + aSize = resultSize; +} + +void CMMACameraPlayer::ResolveScreenSizeL(TSize& aSize) +{ + LOG( EJavaMMAPI, EInfo, "CMMACameraPlayer::ResolveScreenSizeL"); + +#if defined( __WINS__ ) + TSize size(0,0); + RWsSession ws; + + if (ws.Connect() == KErrNone) + { + CleanupClosePushL(ws); + + CWsScreenDevice* wsScreenDevice = new(ELeave)CWsScreenDevice(ws); + CleanupStack::PushL(wsScreenDevice); + + User::LeaveIfError(wsScreenDevice->Construct()); + + size = wsScreenDevice->SizeInPixels(); + + CleanupStack::PopAndDestroy(2); // wsScreenDevice, ws.Close() + } + + aSize = size; + +#else + TScreenInfoV01 info; + TPckgBuf< TScreenInfoV01 > buf(info); + + UserSvr::ScreenInfo(buf); + info = buf(); + + aSize = info.iScreenSize; +#endif +} + +void CMMACameraPlayer::ResolveCaptureSizes(const CCamera::TFormat aFormat, + const TInt aNumImageSizesSupported, + const TSize& aRequestSize, + TSize& aSourceSize, + TInt& aSourceIndex, + TInt& aLargestIndex) +{ + // Largest image size + TSize largestSize; + // Index to largest image size + TInt largestSizeIndex = 0; + // Source size + TSize sourceSize; + // Default source size index not set + TInt sourceSizeIndex = KErrNotFound; + // Temporary size for iterating capture sizes + TSize tmpSize; + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::ResolveCaptureSizes: aFormat = 0x%x", aFormat); + + // go through all supported sizes. + // Notice: Capture sizes are assumed to be in order from smaller to larger sizes + for (TInt i = 0; i < aNumImageSizesSupported; i++) + { + iCamera->EnumerateCaptureSizes(tmpSize, + i, + aFormat); + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::ResolveCaptureSizes: tmpSize.iWidth = %d", tmpSize.iWidth); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::ResolveCaptureSizes: tmpSize.iHeight = %d", tmpSize.iHeight); + + // Check if current is the largest + if ((largestSize.iWidth < tmpSize.iWidth) && + (largestSize.iHeight < tmpSize.iHeight)) + { + largestSize = tmpSize; + largestSizeIndex = i; + } + + // If wanted size is smaller than tmpSize we can use it + if ((aRequestSize.iWidth <= tmpSize.iWidth) && + (aRequestSize.iHeight <= tmpSize.iHeight)) + { + sourceSize = tmpSize; + sourceSizeIndex = i; + } + } + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::ResolveCaptureSizes: sourceSizeIndex = %d", sourceSizeIndex); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::ResolveCaptureSizes: largestSizeIndex = %d", largestSizeIndex); + + aSourceSize = sourceSize; + aSourceIndex = sourceSizeIndex; + aLargestIndex = largestSizeIndex; +} + +void CMMACameraPlayer::StartL() +{ + LOG1( EJavaMMAPI, EInfo, "CMMACameraPlayer:StartL iState %d", iState); + + // start can't be called to not ready player + if (iState == EPrefetched) + { + // camera passes ready images through + // ViewFinderFrameReady method + + // set time when started + iStartTime = CurrentTime(); + + // inform java side + ChangeState(EStarted); + + TInt64 time; + GetMediaTime(&time); + + // Notify the camera window + // about the status change + iWindow->SetStarted(ETrue); + + // inform java side + PostLongEvent(CMMAPlayerEvent::EStarted, time); + } + PostActionCompletedStart(); + PostActionCompleted(KErrNone); // java start return +} + +void CMMACameraPlayer::StopL(TBool aPostEvent) +{ + LOG1( EJavaMMAPI, EInfo, "CMMACameraPlayer::StopL", iState); + if (iState == EStarted) + { + TInt64 time; + GetMediaTime(&time); // add played time to media time + + if (iStopViewFinder && iWindow->ViewFinderActive()) + { + iWindow->SetStarted(EFalse); + } + iStartTime = KErrNotFound; + + if (aPostEvent) + { + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + + // go back to prefetched state + ChangeState(EPrefetched); + } +} + +void CMMACameraPlayer::DeallocateL() +{ + // If player is started when deallocate is called, + // player is stopped from java side -> state is changed to + // prefetched. + // In prefetched state only reserved resource is + // camera reserve( released with iCamera->Release() ) + // In realized state no resources have been reserved. + // CHANGED: not releasing camera anymore, since it is already + // done in realized state + if (iState == EPrefetched) + { + ChangeState(ERealized); + } +} + + +void CMMACameraPlayer::RealizeL() +{ + iCamera->Reserve(); + // this lock will be released when power on is completed (or error) + if (!iRealizeWait->IsStarted()) + { + iRealizeWait->Start(); + } + User::LeaveIfError(iRealizeWait->iError); + CMMAPlayer::RealizeL(); +} + + +void CMMACameraPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::PrefetchL"); + // nothing to do here + ChangeState(EPrefetched); + PostActionCompleted(KErrNone); +} + + +void CMMACameraPlayer::GetDuration(TInt64* aDuration) +{ + // camera viewer has no duration. + *aDuration = KTimeUnknown; +} + + +void CMMACameraPlayer::SetMediaTimeL(TInt64* /*aTime*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::SetMediaTimeL "); + // with camera media time is not supported. +} + + +void CMMACameraPlayer::GetMediaTime(TInt64* aMediaTime) +{ + if (iState == EStarted) + { + // add play time to media time + iMediaTime += CurrentTime() - iStartTime; + // set new start time + iStartTime = CurrentTime(); + } + + // set value to parameter + (*aMediaTime) = iMediaTime; +} + +void CMMACameraPlayer::CloseL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::CloseL()"); + + // cancel all activity + iCamera->CancelCaptureImage(); + + // Stop and release UI Camera instance + iWindow->SetDisplay(NULL); + + // we don't need reserve camera anymore + iCamera->Release(); + + CMMAPlayer::CloseL(); +} + +const TDesC& CMMACameraPlayer::Type() +{ + return KMMACameraPlayer; +} + +// MCameraObserver +void CMMACameraPlayer::ReserveComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMACameraPlayer::ReserveComplete %d", aError); + if (aError == KErrNone) + { + // camera will notify completion with PowerOnComplete method. + iCamera->PowerOn(); + } + else + { + // release lock and store error. State doesn't change. + iRealizeWait->iError = aError; + iRealizeWait->AsyncStop(); + } + +} + +void CMMACameraPlayer::PowerOnComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMACameraPlayer::PowerOnComplete %d", aError); + + TSize viewFinderSize; + TInt error = aError; + + if (error == KErrNone) + { + // The view finder size must be known after prefetching. + TRAP(error, ResolveViewFinderSizeL(viewFinderSize)); + } + + if (error == KErrNone) + { + iSize = viewFinderSize; + + if (iDisplay) + { + iDisplay->SourceSizeChanged(iSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); + } + } + + iRealizeWait->iError = error; + iRealizeWait->AsyncStop(); +} + +void CMMACameraPlayer::ViewFinderFrameReady(CFbsBitmap& /*aFrame*/) +{ + // Empty implementation of an interface method. + // DirectViewFinder is used + // instead of BitmapViewFinder +} + +void CMMACameraPlayer::ImageReady(CFbsBitmap* aBitmap, + HBufC8* aData, + TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMACameraPlayer::ImageReady %d", aError); + + // This method should never be called, + // unless we are taking snapshot + __ASSERT_DEBUG(iSnapshotStatus, User::Invariant()); + + __ASSERT_DEBUG(!iSnapshotBitmap, User::Invariant()); + __ASSERT_DEBUG(!iSnapshotEncoded, User::Invariant()); + + if (aError == KErrNone) + { + // this class has ownership of the bitmap until + // snapshot bitmap is got from this class. + iSnapshotBitmap = aBitmap; + iSnapshotEncoded = aData; + } + + // notify the caller, error code or KErrNone + User::RequestComplete(iSnapshotStatus, aError); + iWindow->SetStarted(ETrue); + // Status is not needed anymore + // and this class don't own the status. + iSnapshotStatus = NULL; +} + +void CMMACameraPlayer::FrameBufferReady(MFrameBuffer* /*aFrameBuffer*/, + TInt /*aError*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::FrameBufferReady"); + // this callback will never be called + // Asserted in debug build to be sure. + __ASSERT_DEBUG(EFalse, User::Invariant()); +} + +void CMMACameraPlayer::SetDisplayL(MMMADisplay* aDisplay) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::SetDisplay"); + + // now it is ready to draw + iDisplay = aDisplay; + + // Passes display into iWindow. + // Allocates all resources needed to use a camera DirectViewFinder. + iWindow->SetDisplay(aDisplay); + + iDisplay->SetWindowL(iWindow); + + // Set view finder size to the display only if the view finder + // size has been resolved. + if (iSize != TSize(0, 0)) + { + iDisplay->SourceSizeChanged(iSize); + NotifyWithStringEvent(CMMAPlayerEvent::ESizeChanged, KVideoControlName); + } +} + +TSize CMMACameraPlayer::SourceSize() +{ + return iSize; +} + +MMMASnapshot::TEncoding CMMACameraPlayer::TakeSnapshotL(TRequestStatus* aStatus, + const TSize& aSize, + const CMMAImageSettings& aSettings) +{ + __ASSERT_DEBUG(!iSnapshotStatus, User::Invariant()); + __ASSERT_DEBUG(!iSnapshotBitmap, User::Invariant()); + __ASSERT_DEBUG(!iSnapshotEncoded, User::Invariant()); + + // snapshots can not be taken if player is not realized + if (iState < ERealized) + { + User::Leave(KErrNotReady); + } + // save status which will be notified + iSnapshotStatus = aStatus; + + // changing status to pending + *iSnapshotStatus = KRequestPending; + + // Source size not set in the beginning + TSize sourceSize; + + // Use default if size is not specified. + TInt sourceSizeIndex = iSourceSizeIndex; + + // Largest image size index + TInt largestSizeIndex = 0; + + // Get camera characteristics + TCameraInfo cameraInfo; + iCamera->CameraInfo(cameraInfo); + + // Set default snapshot encoding type + TEncoding encoding = EBitmap; + + // Set default image capture format + CCamera::TFormat format = CCamera::EFormatFbsBitmapColor16M; + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::TakeSnapshotL: cameraInfo.iImageFormatsSupported = 0x%x", cameraInfo.iImageFormatsSupported); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::TakeSnapshotL: cameraInfo.iNumImageSizesSupported = %d", cameraInfo.iNumImageSizesSupported); + + // Check if size was set in Java + if (aSize.iWidth != KErrNotFound && + aSize.iHeight != KErrNotFound) + { + // Determine if jpeg capture was requested + if ((*aSettings.iMimeType == KJpegMime) || + (*aSettings.iMimeType == KImageJpegMime)) + { + // Shortcut for supported image formats + TUint32 imageFormats = cameraInfo.iImageFormatsSupported; + + // Jpeg subtype constants + _LIT8(KJpegJfif, "jfif"); + _LIT8(KJpegExif, "exif"); + + // Resolve requested jpeg subtype from settings and camerainfo + if ((imageFormats & CCamera::EFormatJpeg) && + (*aSettings.iType == KJpegJfif)) + { + // JFIF JPEG + format = CCamera::EFormatJpeg; + encoding = EEncoded; + } + else if ((imageFormats & CCamera::EFormatExif) && + (*aSettings.iType == KJpegExif)) + { + // EXIF JPEG + format = CCamera::EFormatExif; + encoding = EEncoded; + } + } + + // Try to resolve nearest source size to the one requested, + // except for the JFIF and EXIF jpeg subtypes the match has + // to be exact otherwise non-encode capture format will be + // used + ResolveCaptureSizes(format, + cameraInfo.iNumImageSizesSupported, + aSize, + sourceSize, + sourceSizeIndex, + largestSizeIndex); + + // Format was either of the jpeg formats and requested size + // didn't match the source size + if ((format >= CCamera::EFormatJpeg && + format <= CCamera::EFormatExif) && + (aSize != sourceSize)) + { + // Try again with an non-encoded format + format = CCamera::EFormatFbsBitmapColor16M; + encoding = EBitmap; + ResolveCaptureSizes(format, + cameraInfo.iNumImageSizesSupported, + aSize, + sourceSize, + sourceSizeIndex, + largestSizeIndex); + } + + if (sourceSizeIndex == KErrNotFound) + { + // If correct index was not found use the largest. + sourceSizeIndex = largestSizeIndex; + } + } + // else use default iSourceSizeIndex and default image capture format + + iCamera->PrepareImageCaptureL(format, + sourceSizeIndex); + + // play sound when capturing image + CMMACameraSound::PlayImageCaptureSoundL(); + + // start capture, ImageReady will be called when ready + iWindow->SetStarted(EFalse); + + iCamera->CaptureImage(); + + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::TakeSnapshotL: format = 0x%x", format); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::TakeSnapshotL: sourceSizeIndex = %d", sourceSizeIndex); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayer::TakeSnapshotL: encoding = %d", encoding); + + // Inform caller which snapshot encoding was ultimately used + return encoding; +} + +CFbsBitmap* CMMACameraPlayer::SnapshotBitmap() +{ + CFbsBitmap* bitmap = iSnapshotBitmap; + + // ownership transfers to the caller + iSnapshotBitmap = NULL; + return bitmap; +} + +HBufC8* CMMACameraPlayer::SnapshotEncoded() +{ + HBufC8* encoded = iSnapshotEncoded; + + // ownership transfers to the caller + iSnapshotEncoded = NULL; + return encoded; +} + +void CMMACameraPlayer::NotifyWithStringEvent( + CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) +{ + PostStringEvent(aEventType, aStringEventData); +} + +MMMASnapshot* CMMACameraPlayer::SnapshoterL() +{ + return this; +} + +TInt CMMACameraPlayer::CameraHandle() +{ + return iCamera->Handle(); +} + +void CMMACameraPlayer::SetViewFinderMode(TBool aStopViewFinder) +{ + iStopViewFinder = aStopViewFinder; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmacameraplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmacameraplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,222 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating camera players. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmacameraplayerfactory.h" +#include "cmmacameraplayer.h" +#include "cmmavideocontrol.h" +#include "cmmavideorecordcontrol.h" +#include "cmmastoptimecontrol.h" +#include "cmmaplayerproperties.h" +#include "cmmammfresolver.h" + +_LIT(KDefaultVideo, "video"); +//is the main camera +_LIT(KDevcamZero, "devcam0"); +// the secondary camera +_LIT(KDevcamOne, "devcam1"); + +_LIT(KEncodingProperty, "encoding"); + +_LIT(KVideoMp4MimeType, "video/mp4"); +_LIT(KVideoH264MimeType, "video/H264"); + +CMMACameraPlayerFactory* CMMACameraPlayerFactory::NewLC() +{ + CMMACameraPlayerFactory* pFactory = + new(ELeave) CMMACameraPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + + +CMMACameraPlayerFactory::CMMACameraPlayerFactory() +{ +} + + +CMMACameraPlayerFactory::~CMMACameraPlayerFactory() +{ + delete iAudioSettings; +} + +CMMAPlayer* CMMACameraPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayerFactory::CreatePlayerL( aResolver )+"); + CMMACameraPlayer* player = CMMACameraPlayer::NewLC(iCameraIndex); + + /* Add VideoControl */ + CMMAVideoControl* videoControl = new(ELeave)CMMAVideoControl(player); + + CleanupStack::PushL(videoControl); + player->AddControlL(videoControl); + CleanupStack::Pop(videoControl); + + /* Add RecordControl */ + CMMAVideoRecordControl* videoRecordControl = + CMMAVideoRecordControl::NewL(player, + aResolver, + iVideoSettings, + iAudioSettings, + player->CameraHandle()); + CleanupStack::PushL(videoRecordControl); + player->AddControlL(videoRecordControl); + // ownership transfered to player + CleanupStack::Pop(videoRecordControl); + + // With record control view finder can't be stopped, + // because it can not be restarted. + player->SetViewFinderMode(EFalse); + + CleanupStack::Pop(player); + return player; +} + + +void CMMACameraPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeVideo)); +} + +void CMMACameraPlayerFactory::PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection) +{ + // We are creating record type player + aResolver->SetRequiredRecordFormatSupportL(*aFormatSelection); +} + +CMMAPlayer* CMMACameraPlayerFactory::CreatePlayerL(const TDesC&) +{ + // record player cannot be created from conten-type, since this is used only + // when we have also data + return NULL; +} + + +CMMAPlayer* CMMACameraPlayerFactory::CreatePlayerL(const TDesC8&) +{ + // record player cannot be created with header data + return NULL; +} + +CMMAPlayer* CMMACameraPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraPlayerFactory::CreatePlayerL aParameters = %S", aParameters.Ptr()); + // check that locator is capture:://audio + if (aProtocol != KMMACaptureProtocol) + { + return NULL; + } + + iCameraIndex = KErrNotFound; + + // If the device supports multiple cameras then "capture://devcam0" is the + // main camera pointing outwards from the user. "capture://devcam1" is the + // secondary camera pointing e.g. towards the user. "capture://video" is + // the default camera locator pointing to the same camera as "devcam0" + if ((aMiddlePart == KDefaultVideo) || + (aMiddlePart == KDevcamZero)) + { + // First camera + iCameraIndex = 0; + } + else if (aMiddlePart == KDevcamOne) + { + // Second camera. + iCameraIndex = 1; + } + else + { + // not supported type + return NULL; + } + + CMMAAudioSettings* audioSettings = new(ELeave) CMMAAudioSettings; + audioSettings->iDataType = KMMFFourCCCodeNULL; + delete iAudioSettings; + iAudioSettings = audioSettings; + + if (aParameters.Length() == 0) + { + // getting defaults from validator + iVideoSettings = TMMAParameterValidator::ValidateVideoPropertiesL(aParameters); + } + else + { + // we accept either video or mixed parameters, so properties must contain encoding 2 times for mixed and + // 1 time for video. + // making tmp des without first "encoding" + TInt lengthWithoutEncoding = aParameters.Length() - KEncodingProperty().Length(); + if (lengthWithoutEncoding < 0) + { + User::Leave(KErrArgument); + } + TPtrC tmp = aParameters.Right(lengthWithoutEncoding); + // finding second "encoding" + TInt videoPropertiesStartPos = tmp.Find(KEncodingProperty); + if (videoPropertiesStartPos == KErrNotFound) + { + // there is not another encoding, so assuming that there is only video parameters + iVideoSettings = TMMAParameterValidator::ValidateVideoPropertiesL(aParameters); + } + else + { + // there is mixed parameters + videoPropertiesStartPos += KEncodingProperty().Length(); + + // skipping '&' char + TPtrC audioProperties = aParameters.Left(videoPropertiesStartPos - 1); + TPtrC videoProperties = aParameters.Mid(videoPropertiesStartPos); + iVideoSettings = TMMAParameterValidator::ValidateVideoPropertiesL(videoProperties); + + CMMAAudioSettings* audioSettings = TMMAParameterValidator::ValidateAudioPropertiesL(audioProperties); + delete iAudioSettings; + iAudioSettings = audioSettings; + } + } + + // if wanted video capture encoding is H264, we must create player with video/mp4 + // because mmf doesn't have controller for H264 + if (iVideoSettings.iEncoding.Compare(KVideoH264MimeType) == 0) + { + return CMMAMMFPlayerFactory::CreatePlayerL(KVideoMp4MimeType); + } + + // Find controller with content-type + return CMMAMMFPlayerFactory::CreatePlayerL(iVideoSettings.iEncoding); +} + +void CMMACameraPlayerFactory::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + if (IsSupportedContentTypeL(aContentType)) + { + aProtocolArray.AppendL(KMMACaptureProtocol); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmacamerawindow.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmacamerawindow.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,977 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplayWindow functionality +* for Camera viewfinder usage. +* +*/ + + +// Include Files +#include +#include +#include +#include +#include +#include "cmmacanvasdisplay.h" +#include "logger.h" + +class CMMACanvasDisplay; + +//#include + +// Used for iDisplay member + +#include "cmmacamerawindow.h" + +// Camera viewfinder start delay +const TInt KStarterTimeout = 100000; //100 msecs + +// Margin of icon displayed instead of viewfinder in case of error +const TInt KErrorIconMargin = 5; //5 pixels + + +_LIT(KCameraAppBitmapFile, "z:\\resource\\apps\\cameraapp.mif"); + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::NewL +// Two-phased constructor. +// Use this method to create a CMMACameraWindow instance. +// --------------------------------------------------------------------------- +// +CMMACameraWindow* CMMACameraWindow::NewL(TInt aCameraHandle) +{ + CMMACameraWindow* self = new(ELeave)CMMACameraWindow(aCameraHandle); + return self; +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::~CMMACameraWindow +// Destructor. +// NOTE: iUICamera have to be deleted by ReleaseUiResources() called +// from UI thread +// --------------------------------------------------------------------------- +// +CMMACameraWindow::~CMMACameraWindow() +{ + // It's not allowed to delete any nonsharable object here. + // This must be done in Destroy(). + // If the iDisplay is set, + // instance should be deleted by sending + // event from UI to be received by MUiEventConsumer. +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::ViewFinderActive +// Gets an information if the viewfinder is started. +// --------------------------------------------------------------------------- +// +TBool CMMACameraWindow::ViewFinderActive() +{ + return iUICamera && iViewFinderVisible; +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::SetStarted +// Notifies window about Started state change. +// If started, tries to start viewfinder. +// If not started, stops viewfinder. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetStarted(TBool aStarted) +{ + iStarted = aStarted; + if (iDisplay) + { + if (iStarted) + { + // iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EShowViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetStarted : before GetCallbackInUiThread + EShowViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EShowViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetStarted : before GetCallbackInUiThread - EShowViewFinder"); + } + else + { + // iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EHideViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetStarted : before GetCallbackInUiThread + EHideViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EHideViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetStarted : before GetCallbackInUiThread - EHideViewFinder"); + } + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::SetDisplay +// Sets iDisplay used to invoke callbacks from UI thread. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetDisplay(MMMADisplay *aDisplay) +{ + if (iDisplay != aDisplay) + { + if (iDisplay) + { + // Clear the resources created within the old Display + //iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EDeleteViewFinder); + + + // instead make a call to java, shift to ui thread and call ReleaseUiResources() method in UI thread + + // here jobject and jclass is valid since the flow is first creat CMMACanvasDisplay and then + // call setdeisplay of cameraplayer + /*iJavaDisplayObject = iDisplay->GetJavaDisplayObject(); + iJavaDisplayClass = iDisplay->GetJavaDisplayClass(); + iJni = iDisplay->GetJNIEnv(); + + jmethodID releaseUiResourceID = iJni->GetMethodID( + iJavaDisplayClass, + "releaseUiResource", + "()I"); + + iJni->CallIntMethod(iJavaDisplayObject,releaseUiResourceID);*/ + //MMAPI UI 3.x req. + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetDisplay : before GetCallbackInUiThread +"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EDeleteViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetDisplay : before GetCallbackInUiThread -"); + } + + // Set the new Display + iDisplay = aDisplay; + + if (iDisplay) + { + // Get a DSA resources for the new Display + // iDisplay->UIGetDSAResources(*this, MMMADisplay::EMmaThread); + + } + } +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetDestinationBitmapL +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetDestinationBitmapL(CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetDestinationBitmapL"); +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::DrawFrameL +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::DrawFrameL(const CFbsBitmap* /*aBitmap*/) +{ + // Ignored, this window will not be used for actual drawing +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetDrawRect +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetDrawRect(const TRect& aRect) +{ + // MMAPI thread + LOG2(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::SetDrawRect TL:%d,%d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::SetDrawRect BR:%d,%d", + aRect.iBr.iX, aRect.iBr.iY); + + iDrawRect = aRect; + + if (iDisplay) + { + //iDisplay->UIGetCallback(*this, CMMACameraWindow::EResetViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetDisplay : before GetCallbackInUiThread + EResetViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EResetViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetDisplay : before GetCallbackInUiThread - EResetViewFinder"); + + } +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetDrawRectThread +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetDrawRectThread(const TRect& aRect) +{ + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACameraWindow::SetDrawRectThread TL:%d,%d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACameraWindow::SetDrawRectThread BR:%d,%d", + aRect.iBr.iX, aRect.iBr.iY); + + // Note: Runs in UI thread only + + // Bitmap window's rect can be set in any thread. + if (iDrawRect != aRect) + { + iDrawRect = aRect; + + // Stop and start ViewFinder to update position + ResetViewFinder(); + } + +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::DrawRect +// +// --------------------------------------------------------------------------- +// +const TRect& CMMACameraWindow::DrawRect() +{ + return iDrawRect; +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::WindowSize +// +// --------------------------------------------------------------------------- +// +TSize CMMACameraWindow::WindowSize() +{ + return iDrawRect.Size(); +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetPosition +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetPosition(const TPoint& aPosition) +{ + // Note: Runs in UI thread only + SetDrawRectThread(TRect(aPosition, iDrawRect.Size())); +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetVisible +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetVisible(TBool aVisible, TBool aUseEventServer) +{ + iVisible = aVisible; + + if (aUseEventServer) + { + // We are in UI thread now. + SetViewFinderVisibility(aVisible); + } + else + { + // MMAPI thread + if (iDisplay) + { + if (aVisible) + { + // iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EShowViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetVisible : before GetCallbackInUiThread - EShowViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EShowViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetVisible : before GetCallbackInUiThread - EShowViewFinder"); + } + else + { + // iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EHideViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetVisible : before GetCallbackInUiThread - EHideViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EHideViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetVisible : before GetCallbackInUiThread - EHideViewFinder"); + } + } + } +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetWindowRect +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetWindowRect( + const TRect& aRect, + MMMADisplay::TThreadType aThreadType) +{ + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACameraWindow::SetWindowRect TL:%d,%d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACameraWindow::SetWindowRect BR:%d,%d", + aRect.iBr.iX, aRect.iBr.iY); + + if (iClientRect != aRect) + { + iClientRect = aRect; + + if (aThreadType == MMMADisplay::EUiThread) + { + ResetViewFinder(); + } + else + { + // iDisplay->UIGetCallback( + // *this, CMMACameraWindow::EResetViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetWindowRect : before GetCallbackInUiThread + EResetViewFinder"); + iDisplay->GetCallbackInUiThread((TInt)CMMACameraWindow::EHideViewFinder); + LOG(EJavaMMAPI,EInfo,"CMMACameraWindow::SetWindowRect : before GetCallbackInUiThread - EResetViewFinder"); + } + } + + +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::WindowRect +// +// --------------------------------------------------------------------------- +// +const TRect& CMMACameraWindow::WindowRect() +{ + return iClientRect; +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::GetDisplayWindowType +// +// --------------------------------------------------------------------------- +// +MMMADisplayWindow::TDisplayWindowType +CMMACameraWindow::GetDisplayWindowType() const +{ + return EDisplayWindowTypeIsCamera; +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::IsVisible +// +// --------------------------------------------------------------------------- +// +TBool CMMACameraWindow::IsVisible() const +{ + return iVisible; +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::ContainerSet +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ContainerSet() +{ + // We are in UI thread now + + // Container was probably not set when + // iDisplay was set, + // we can now try get the DSA stuff again + if (!iUICamera && iDisplay) + { + // Get a DSA stuff for the new Display + // iDisplay->UIGetDSAResources(*this, MMMADisplay::EUiThread); + } +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::ContainerDestroyed +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ContainerDestroyed() +{ + // We are in UI thread now + ReleaseUiResources(); +} + + +// --------------------------------------------------------------------------- +// From class MCameraObserver +// CMMACameraWindow::ReserveComplete +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ReserveComplete(TInt aError) +{ + LOG1(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::ReserveComplete %d", aError); + + if (aError == KErrNone) + { + // camera will notify completion with PowerOnComplete method. + iUICamera->PowerOn(); + } +} + + +// --------------------------------------------------------------------------- +// From class MCameraObserver +// CMMACameraWindow::PowerOnComplete +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::PowerOnComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMACameraWindow::PowerOnComplete %d", aError); + + if (aError == KErrNone) + { + iCameraPowerOn = ETrue; + SetViewFinderVisibility(ETrue); + } +} + + +// --------------------------------------------------------------------------- +// From class MCameraObserver +// CMMACameraWindow::ViewFinderFrameReady +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ViewFinderFrameReady(CFbsBitmap& /*aFrame*/) +{ + // Empty implementation of the interface method + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::ViewFinderFrameReady"); +} + + +// --------------------------------------------------------------------------- +// From class MCameraObserver +// CMMACameraWindow::ImageReady +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ImageReady(CFbsBitmap* /*aBitmap*/, + HBufC8* /*aData*/, + TInt /*aError*/) +{ + // Empty implementation of the interface method + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::ImageReady"); +} + + +// --------------------------------------------------------------------------- +// From class MCameraObserver +// CMMACameraWindow::FrameBufferReady +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::FrameBufferReady(MFrameBuffer* /*aFrameBuffer*/, + TInt /*aError*/) +{ + // Empty implementation of the interface method + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::FrameBufferReady"); +} + + +// --------------------------------------------------------------------------- +// From class MDirectScreenAccess. +// CMMACameraWindow::AbortNow +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::AbortNow( + RDirectScreenAccess::TTerminationReasons /*aReasons*/) +{ + SetViewFinderVisibility(EFalse); +} + + +// --------------------------------------------------------------------------- +// From class MDirectScreenAccess. +// CMMACameraWindow::Restart +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::Restart( + RDirectScreenAccess::TTerminationReasons /*aReasons*/) +{ + SetViewFinderVisibility(ETrue); +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::CMMACameraWindow +// C++ constructor. +// --------------------------------------------------------------------------- +// +CMMACameraWindow::CMMACameraWindow(TInt aCameraHandle): + iVisible(EFalse), + iStarted(EFalse), + iViewFinderVisible(EFalse), + iCameraPowerOn(EFalse), + iDrawRect(0, 0, 0, 0), + iClientRect(0, 0, 0, 0), + iCameraHandle(aCameraHandle), + iUICamera(NULL), + iDisplay(NULL), + iStarterTimer(NULL), + iDirectAccess(NULL), + iErrorIconBitmap(NULL), + iErrorIconMaskBitmap(NULL), + iRWindowRect(0, 0, 0, 0) +{ +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::UIStartViewFinder +// Creates UI Camera. +// This CCamera instance is duplicated from handle given to the constructor. +// Have to be called from the thread which UI Camera will be controlled from. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::UIStartViewFinder( + RWsSession &aWs, + CWsScreenDevice &aScreenDevice, + RWindowBase &aWindow) +{ + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::UIStartViewFinder"); + + iWs = &aWs; + iScreenDevice = &aScreenDevice; + iWindow = &aWindow; + + if (!iUICamera) + { + TRAPD(error, iUICamera = + CCamera::NewDuplicateL(*this, iCameraHandle)); + + ELOG1( EJavaMMAPI, + "MMA::CMMACameraWindow::UIStartViewFinder - NewDuplicateL %d", + error); + + if (error == KErrNone) + { + iUICamera->Reserve(); + } + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::SetViewFinderVisibility +// If UI Camera have been created, it starts/hides the DirectViewFinder. +// Have to be called from UI thread in which iUICamera instance was created. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetViewFinderVisibility(TBool aVisible) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMACameraWindow::SetViewFinderVisibility - %d", + aVisible); + + if (!iUICamera || !iCameraPowerOn || iViewFinderVisible == aVisible) + { + return; + } + + if (aVisible) + { + // Viewfinder is going to start + if (!iVisible || !iStarted) + { + return; + } + + iViewFinderVisible = ETrue; + + if (!iStarterTimer) + { + // If starter timer haven't been created yet, create an instance + TRAPD( + timerErr, + iStarterTimer = CPeriodic::NewL(CActive::EPriorityIdle)); + + if (timerErr != KErrNone) + { + ELOG1( EJavaMMAPI, + "MMA::CMMACameraWindow::SetViewFinderVisibility - timer error = %d", + timerErr); + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + } + + if (!iStarterTimer->IsActive()) + { + iStarterTimer->Start( + KStarterTimeout, + 0, + TCallBack(StarterTimerCallback, this)); + } + } + else + { + // Viewfinder is going to be cancelled + LOG(EJavaMMAPI,EInfo, + "MMA::CMMACameraWindow::SetViewFinderVisibility - Stopping VF"); + + if (iStarterTimer && iStarterTimer->IsActive()) + { + // Cancel the running starter timer + iStarterTimer->Cancel(); + } + + if (iUICamera->ViewFinderActive()) + { + iUICamera->StopViewFinder(); + } + if (iDirectAccess->IsActive()) + { + iDirectAccess->Cancel(); + } + + iViewFinderVisible = EFalse; + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::StarterTimerCallback +// Executed at the expiry of the iStartedTimer. +// --------------------------------------------------------------------------- +// +TInt CMMACameraWindow::StarterTimerCallback(TAny* aThis) +{ + CMMACameraWindow* self = static_cast(aThis); + ASSERT(self); + + self->StartViewFinder(); + + // We don't want to run the callback again + return EFalse; +} + + +// --------------------------------------------------------------------------- +// From class MMMADisplayWindow +// CMMACameraWindow::SetRWindowRect +// +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::SetRWindowRect(const TRect& aRect, + MMMADisplay::TThreadType aThreadType) +{ + ELOG2( EJavaMMAPI, + "MID::CMMACameraWindow::SetRWindowRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + ELOG2( EJavaMMAPI, + "MID::CMMACameraWindow::SetRWindowRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + iRWindowRect = aRect; + + if (MMMADisplay::EMmaThread == aThreadType) + { + if (iDisplay) + { + //iDisplay->UIGetCallback(*this, + // CMMACameraWindow::EResetViewFinder); + } + } + else if (MMMADisplay::EUiThread == aThreadType) + { + ResetViewFinder(); + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::StartViewFinder +// Starts viewfinder. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::StartViewFinder() +{ + LOG(EJavaMMAPI,EInfo," < StartViewFinder"); + + ASSERT(iUICamera); + ASSERT(iCameraPowerOn); + ASSERT(iStarted); + + iStarterTimer->Cancel(); + + // align client rect to RWindow, viewfinder + // display co-ordinates is w.r.t to RWindow + TRect relativeClientRect; + relativeClientRect = iClientRect; + relativeClientRect.Move(-iRWindowRect.iTl); + + // Set the drawing area + TRect drawRect(iDrawRect); + drawRect.Move(relativeClientRect.iTl); + + LOG2( EJavaMMAPI, EInfo, + "MMA::CMMACameraWindow::StartViewFinder - Starting VF TL:%d,%d", + drawRect.iTl.iX, + drawRect.iTl.iY); + LOG2( EJavaMMAPI, EInfo, + "MMA::CMMACameraWindow::StartViewFinder - Starting VF BR:%d,%d", + drawRect.iBr.iX, + drawRect.iBr.iY); + + TRAPD(vfError, iUICamera->StartViewFinderDirectL( + *iWs, *iScreenDevice, *iWindow, drawRect)); + + if (vfError == KErrNone) + { + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::StartViewFinder - Start OK"); + } + else + { + LOG1( EJavaMMAPI, EInfo, + "MMA::CMMACameraWindow::StartViewFinder() - \ +StartViewFinderDirectL error=%d", vfError); + + TRAP_IGNORE(DrawViewFinderErrorL(vfError, drawRect)); + } + + LOG(EJavaMMAPI,EInfo," > StartViewFinder"); +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::DrawViewFinderError() +// Draws the error message to specified area. +// Used in cases when viewfinder is unable to start. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::DrawViewFinderErrorL( + const TInt /*aError*/, + const TRect& aDrawRect) +{ + + ASSERT(iDirectAccess); + TInt dcError = KErrNone; + if (!iDirectAccess->IsActive()) + { + TRAP(dcError, iDirectAccess->StartL()); + } + + TRect drawRect(aDrawRect); + + if (dcError == KErrNone) + { + drawRect.Intersection(iClientRect); + drawRect.Move(-iWindow->AbsPosition()); + + CFbsBitGc* directGc = iDirectAccess->Gc(); + directGc->SetClippingRect(drawRect); + directGc->SetBrushColor(TRgb(128,128,128)); + directGc->SetPenColor(TRgb(128,0,0)); + directGc->SetBrushStyle(CGraphicsContext::ESolidBrush); + directGc->SetPenStyle(CGraphicsContext::ESolidPen); + directGc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha); + directGc->DrawRect(drawRect); + + if (!iErrorIconBitmap || !iErrorIconMaskBitmap) + { + if (iErrorIconBitmap) + { + delete iErrorIconBitmap; + iErrorIconBitmap = NULL; + } + + if (iErrorIconMaskBitmap) + { + delete iErrorIconMaskBitmap; + iErrorIconMaskBitmap = NULL; + } +/* + AknsUtils::CreateIconL( + AknsUtils::SkinInstance(), + KAknsIIDQgnIndiCam4Camera, + iErrorIconBitmap, + iErrorIconMaskBitmap, + KCameraAppBitmapFile, + EMbmCameraappQgn_indi_cam4_camera, + EMbmCameraappQgn_indi_cam4_camera_mask + ); + */ + } + + //TRect iconRect + drawRect.iTl.iX += KErrorIconMargin; + drawRect.iTl.iY += KErrorIconMargin; + drawRect.iBr.iX -= KErrorIconMargin; + drawRect.iBr.iY -= KErrorIconMargin; + + if (iErrorIconBitmap->SizeInPixels() != drawRect.Size()) + { + AknIconUtils::SetSize(iErrorIconBitmap, drawRect.Size()); + AknIconUtils::SetSize(iErrorIconMaskBitmap, drawRect.Size()); + } + + directGc->BitBltMasked( + drawRect.iTl, iErrorIconBitmap, + TRect(iErrorIconBitmap->SizeInPixels()), + iErrorIconMaskBitmap, EFalse); + + iDirectAccess->ScreenDevice()->Update(); + } + +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::ReleaseUiResources() +// Stops the DirectViewFinder and deletes UI Camera instance +// Have to be called from UI thread in which UI Camera +// have been created before the CMMACameraWindow instance +// is deleted. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ReleaseUiResources() +{ + if (iUICamera) + { + SetViewFinderVisibility(EFalse); + // iStarterTimer is cancelled by previous call + // it can be deleted now + delete iStarterTimer; + iStarterTimer = NULL; + iUICamera->Release(); + delete iUICamera; + iUICamera = NULL; + iCameraPowerOn = EFalse; + iDirectAccess->Cancel(); + delete iDirectAccess; + iDirectAccess = NULL; + delete iErrorIconBitmap; + iErrorIconBitmap = NULL; + delete iErrorIconMaskBitmap; + iErrorIconMaskBitmap = NULL; + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::ResetViewFinder +// Resets (stops and starts) viewfinder +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::ResetViewFinder() +{ + + if (iStarterTimer && !iStarterTimer->IsActive() && iStarted) + { + SetViewFinderVisibility(EFalse); + SetViewFinderVisibility(ETrue); + } +} + + +// --------------------------------------------------------------------------- +// CMMACameraWindow::Destroy +// Deletes this object. +// --------------------------------------------------------------------------- +// +void CMMACameraWindow::Destroy() +{ + // Delete itself + delete this; +} + + +// --------------------------------------------------------------------------- +// From class MUiEventConsumer. +// CMMACameraWindow::MdcDSAResourcesCallback +// Callback to iDisplay->UIGetDSAResources(). +// Invoked asynchronously from UI Event Server thread. +// --------------------------------------------------------------------------- +// +/*void CMMACameraWindow::MdcDSAResourcesCallback( + RWsSession &aWs, + CWsScreenDevice &aScreenDevice, + RWindowBase &aWindow) +{ + TRAPD(error, iDirectAccess = CDirectScreenAccess::NewL(aWs, + aScreenDevice, + aWindow, + *this)); + LOG1(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::MdcDSAResourcesCallback, error = %d", error); + if (KErrNone != error) + { + return; + } + this->UIStartViewFinder(aWs, aScreenDevice, aWindow); +} +*/ + +// --------------------------------------------------------------------------- +// From class MUiEventConsumer. +// CMMACameraWindow::MdcUICallback +// Callback to iDisplay->UIGetCallback(). +// Invoked asynchronously from UI Event Server thread. +// --------------------------------------------------------------------------- +// + +void CMMACameraWindow::UICallback(TInt aCallbackId) +{ + LOG(EJavaMMAPI,EInfo,"MMA::CMMACameraWindow::MdcUICallback"); + + switch (aCallbackId) + { + case EDeleteViewFinder: + ReleaseUiResources(); + break; + case EHideViewFinder: + SetViewFinderVisibility(EFalse); + break; + case EShowViewFinder: + SetViewFinderVisibility(ETrue); + break; + case EResetViewFinder: + ResetViewFinder(); + break; + case EDestroyWindow: + Destroy(); + break; + } +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmacanvasdisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmacanvasdisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,308 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Draws to Canvas. +* +*/ + + +// Include Files +#include +//#include // MMIDCanvas + +#ifdef EXTENDED_LCDUI_CANVAS +#include +#endif + +#include "cmmacanvasdisplay.h" +#include "cmmabitmapwindow.h" +#include "mmafunctionserver.h" + +// CONSTRUCTION +// Static constructor, leaves pointer to cleanup-stack +CMMACanvasDisplay* CMMACanvasDisplay::NewLC(MMAFunctionServer* aEventSource, jobject obj/*MMIDCanvas* aCanvas*/) +{ + CMMACanvasDisplay* self = + new(ELeave) CMMACanvasDisplay(aEventSource, obj/*aCanvas*/); + + CleanupStack::PushL(self); + self->Construct(aEventSource,obj); + return self; +} + +// Destructor (virtual by CBase) +CMMACanvasDisplay::~CMMACanvasDisplay() +{ +} + +CMMACanvasDisplay::CMMACanvasDisplay(MMAFunctionServer* aEventSource ,jobject aJavaDisplayRef) +{ + /* +iJni = aEventSource->getValidJniEnv(); +javaDisplayObject = iJni->NewGlobalRef(javadisplayref); +javaDisplayClass = iJni->GetObjectClass(javaDisplayObject); +*/ +} + + +/* +void CMMACanvasDisplay::SourceSizeChanged(const TSize& aSourceSize) +{ + LOG(EJavaMMAPI,EInfo,"CMMACanvasDisplay::SourceSizeChanged"); + + #ifdef RD_JAVA_NGA_ENABLED + if ( iWindow ) + { + iWindow->SetVideoCropRegion( TRect( iUserRect.iTl, aSourceSize ) ); + } + #endif + + iSourceSize = aSourceSize; + jmethodID getDisplayWidthID = iJni->GetMethodID( + iJavaDisplayClass, + "getDisplayWidth", + "()I"); + + jmethodID getDisplayHeightID = iJni->GetMethodID( + iJavaDisplayClass, + "getDisplayHeight", + "()I"); + + + TInt x = iJni->CallIntMethod(iJavaDisplayObject,getDisplayWidthID); + TInt y = iJni->CallIntMethod(iJavaDisplayObject,getDisplayHeightID); + + // TSize fullScreenSize(100,100); // TO-Do remove hardcoded with the relevent one + LOG2(EJavaMMAPI,EInfo,"CMMACanvasdisplay.cpp : SourceSizeChanged () fullScreenSize is x = %d ,y = %d ",x,y); + // get the ScreenSize from canvas in java + TSize canvasSize(x, y); + fullScreenSize = canvasSize; + TBool sourceIsBigger = (aSourceSize.iWidth > fullScreenSize.iWidth || + aSourceSize.iHeight > fullScreenSize.iHeight); + + if (sourceIsBigger) + { + // Source is larger than display area. + // Shrink draw are to fit in display. + iWindow->SetDrawRect(ScaleToFullScreen(fullScreenSize, iSourceSize)); + } + else + { + // source is smaller than display area + iWindow->SetDrawRect(TRect(iUserRect.iTl, iSourceSize)); + } + + SetClippingRegion(); + + if (iUserRect.IsEmpty()) + { + // Java side hasn't set size. + iUserRect = iWindow->DrawRect(); + + if (!sourceIsBigger) + { + // Addjusting rect to top left corner. + iUserRect = TRect(iUserRect.Size()); + } + } +} + +*/ + +void CMMACanvasDisplay::SetFullScreenL(TBool aFullScreen) +{ + LOG(EJavaMMAPI,EInfo,"CMMACanvasDisplay::SetFullScreenL +"); + iFullScreen = aFullScreen; + if (iContainerVisible) + { + RemoveClippingRegion(); + + if (aFullScreen) + { + // use new scaled rect + // iWindow->SetDrawRect(ScaleToFullScreen(fullScreenSize, iSourceSize)); + iWindow->SetDrawRectThread(ScaleToFullScreen(fullScreenSize, iSourceSize)); + } + else + { + // use size set from java + //iWindow->SetDrawRect(iUserRect); + iWindow->SetDrawRectThread(iUserRect); + } + + AddClippingRegion(); + } + LOG(EJavaMMAPI,EInfo,"CMMACanvasDisplay::SetFullScreenL +"); +} + +void CMMACanvasDisplay::SetWindowL(MMMADisplayWindow* aWindow) +{ + LOG( EJavaMMAPI, EInfo, "CMMACanvasDisplay::SetWindowL"); + CMMADisplay::SetWindowL(aWindow); + if (!iWindow) + { + LOG( EJavaMMAPI, EInfo, "CMMACanvasDisplay::SetWindowL: NULL window, returning"); + return; + } + /* + CFbsBitmap* bitmap = iCanvas->FrameBuffer(); + + __ASSERT_DEBUG(bitmap, + User::Panic(_L("Canvas has no bitmap"), + KErrNotFound)); + + iWindow->SetDestinationBitmapL(bitmap); + + // Check that container exists + User::LeaveIfNull(iDirectContainer); + + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACanvasDisplay::SetWindowL iDirectContainer->MdcContentBounds() TL %d %d", iDirectContainer->MdcContentBounds().iTl.iX, iDirectContainer->MdcContentBounds().iTl.iY); + LOG2( EJavaMMAPI, EInfo, "MMA::CMMACanvasDisplay::SetWindowL iDirectContainer->MdcContentBounds() BR %d %d", iDirectContainer->MdcContentBounds().iBr.iX, iDirectContainer->MdcContentBounds().iBr.iY); + */ + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::before calling BoundRect"); + TRect boundrect = BoundRect(); + iWindow->SetWindowRect(boundrect/*iDirectContainer->MdcContentBounds()*/, MMMADisplay::EMmaThread); + + #ifdef RD_JAVA_NGA_ENABLED + //iWindow->SetRWindowRect( iDirectContainer->MdcContainerWindowRect(), + // MMMADisplay::EMmaThread ); + iWindow->SetRWindowRect( boundrect, + MMMADisplay::EMmaThread ); + #endif + + SetClippingRegion(); +} + + + +TRect& CMMACanvasDisplay::BoundRect() +{ + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect +"); + jmethodID getBoundRectID = iJni->GetMethodID( + iJavaDisplayClass, + "getBoundRect", + "()V"); + + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect --1"); + // set the value to java,so that we can access those from array + iJni->CallVoidMethod(iJavaDisplayObject,getBoundRectID); + jfieldID field = iJni->GetFieldID(iJavaDisplayClass, "displayboundarr", "[I"); + if(field == NULL) + { + // handle error + } + /* Read the instance field s */ + jintArray javaboundinfoarr = (jintArray)iJni->GetObjectField(iJavaDisplayObject, field); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect --2"); + jint* nativeboundinfoarr = iJni->GetIntArrayElements(javaboundinfoarr, NULL); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect --3"); + if (!nativeboundinfoarr) + { // outputBuffer was already allocated + iJni->ReleaseIntArrayElements(javaboundinfoarr, nativeboundinfoarr, JNI_ABORT); + // return invalid rect. + TRect rect(0,0,0,0); + return rect; + } + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect --4"); +// create TRect + TInt xcoordinate = nativeboundinfoarr[0]; + TInt ycoordinate = nativeboundinfoarr[1]; + TInt width = nativeboundinfoarr[2]; + TInt height = nativeboundinfoarr[3]; + LOG2(EJavaMMAPI,EInfo,"CMMACanvasDisplay: BoundRect() co-ordinate of topleftcorner is x = %d,y =%d",xcoordinate,ycoordinate); + LOG2(EJavaMMAPI,EInfo,"CMMACanvasDisplay: BoundRect() size of bound rect is width = %d,height =%d",width,height); + TPoint topleft(xcoordinate,ycoordinate); + TSize rectsize(width,height); + TRect boundRect(topleft,rectsize); + iJni->ReleaseIntArrayElements(javaboundinfoarr, nativeboundinfoarr, JNI_COMMIT); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::BoundRect -"); + return boundRect; +} + +// ask java side peer about the container rect size +// currently assuming the boundrect and containerrect will be same in case of canvas +TRect& CMMACanvasDisplay::ContainerWindowRect() +{ + + return BoundRect(); + +} + + +void CMMACanvasDisplay::SetDisplayLocationL(const TPoint& aPosition) +{ + // Move iUserRect top left corner to aPosition. + TSize size(iUserRect.Size()); + iUserRect.iTl = aPosition; + iUserRect.SetSize(size); + + if (iContainerVisible && !iFullScreen && iWindow) + { + iWindow->SetDrawRect(iUserRect); + SetClippingRegion(); + } + else + { + iResetDrawRect = ETrue; + } +} + +TPoint CMMACanvasDisplay::DisplayLocation() +{ + if (iWindow && iFullScreen) + { + return iWindow->DrawRect().iTl; + } + else + { + return iUserRect.iTl; + } +} + + + + + +/* +void CMMACanvasDisplay::MdcContentBoundsChanged(const TRect& aRect) +{ + LOG2(EJavaMMAPI,EInfo,"MID::CMMACanvasDisplay::MdcContentBoundsChanged aRect TL %d %d", + aRect.iTl.iX, aRect.iTl.iY); + LOG2(EJavaMMAPI,EInfo,"MID::CMMACanvasDisplay::MdcContentBoundsChanged aRect BR %d %d", + aRect.iBr.iX, aRect.iBr.iY); + + if (iWindow) + { + // Set new rect to window. + iWindow->SetWindowRect(aRect, MMMADisplay::EUiThread); + + if (iFullScreen) + { + TRect fullRect = ScaleToFullScreen(iCanvas->ContentSize(), + iSourceSize); + + // use SetDrawRectThread because this code is executed + // in lcdui thread + iWindow->SetDrawRectThread(fullRect); + } + else + { + // move to user defined position. + iWindow->SetPosition(iUserRect.iTl); + } + } + SetClippingRegion(); +} +*/ + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This is base interface for all controls. +* +*/ + + +// INCLUDE FILES +#include "cmmacontrol.h" + +const TDesC* CMMAControl::ClassNameJni(CMMAControl* aControl) +{ + return &aControl->ClassName(); +} + +void CMMAControl::StaticSetHandle(CMMAControl* aControl, + jobject aControlObject) +{ + aControl->SetHandle(aControlObject); +} + +EXPORT_C const TDesC& CMMAControl::PublicClassName() const +{ + return ClassName(); +} + +inline void CMMAControl::SetHandle(jobject aControlObject) +{ + iControlObject = aControlObject; +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmadeleterefevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmadeleterefevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadeleterefevent.h" + +CMMADeleteRefEvent::CMMADeleteRefEvent(jobject aDeleteRefObject): + CMMAEvent(EDisposableEvent) +{ + iDeleteRefObject = aDeleteRefObject; +} + +// from CJavaEvent +void CMMADeleteRefEvent::Dispatch(JNIEnv& aJni) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADeleteRefEvent::Dispatch"); + aJni.DeleteGlobalRef(iDeleteRefObject); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmadisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmadisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,752 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements MMMADisplay +* +*/ + + +// Include Files +#include "logger.h" + +#include "cmmadisplay.h" +#include "mmmadisplaywindow.h" + +// temporary +#include + +// Destructor (virtual by CBase) +CMMADisplay::~CMMADisplay() +{ +/* + if (iDirectContainer) + { + // Remove clip rect if set + if (!iClipRect.IsEmpty()) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::~CMMADisplay(): Removing clip rect"); + iDirectContainer->MdcRemoveContentBounds(iClipRect); + } + + // Remove this object from MDirectContainer + iDirectContainer->MdcRemoveContent(this); + } + */ +} + + +CMMADisplay::CMMADisplay(): + iVisible(ETrue), + iFullScreen(EFalse), + iContainerVisible(ETrue), + iIsForeground(ETrue), + iResetDrawRect(EFalse) +{ +} + +void CMMADisplay::Construct(MMAFunctionServer* eventSource , jobject javadisplayref) +{ + iEventSource = eventSource; + iJni = iEventSource->getValidJniEnv(); + iJavaDisplayObject = iJni->NewGlobalRef(javadisplayref); + iJavaDisplayClass = iJni->GetObjectClass(iJavaDisplayObject); + // Components must have direct content. + /* __ASSERT_LOG(EJavaMMAPI,EInfo,"aDirectContainer, User::Invariant()); + + // Not owned + iDirectContainer = aDirectContainer; + + // Get component visibility. Later visibility changes will + // be informed through MDirectContent observer. + iContainerVisible = iDirectContainer->MdcContainerVisibility(); + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::Construct iContainerVisible = %d", iContainerVisible); + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::Construct iVisible = %d", iVisible); + + // Add this MDirectContent to the MDirectContainer. Cannot fail. + iDirectContainer->MdcAddContent(this); + */ +} + +TRect CMMADisplay::ScaleToFullScreen(const TSize& aFullScreenSize, + const TSize& aSourceSize) +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::ScaleToFullScreen() +"); + if ((aSourceSize.iWidth == 0) && + (aSourceSize.iHeight == 0)) + { + // Avoid divide by zero. + return TRect(); + } + + // Width or height will be full size. + TRect drawRect(TPoint(0, 0), + aFullScreenSize); + + // Smaller dimension scale ratio will be scaled. + // Changed to area calculation to avoid reals and dimension + // with smaller area will be scaled. + TInt vDif((aFullScreenSize.iWidth - aSourceSize.iWidth) + * aFullScreenSize.iHeight); + TInt hDif((aFullScreenSize.iHeight - aSourceSize.iHeight) + * aFullScreenSize.iWidth); + + TPoint position(0, 0); + + // Check which side to scale to fullscreen size. + if (hDif > vDif) + { + // Width is full screen width. + // Scale height with aspect ratio. + drawRect.iBr.iY = aFullScreenSize.iWidth * aSourceSize.iHeight + / aSourceSize.iWidth; + // move rect middle of the screen + position.iY = (aFullScreenSize.iHeight - drawRect.iBr.iY) / 2; + } + else + { + // Height is full screen height. + // Scale width with aspect ratio. + drawRect.iBr.iX = aFullScreenSize.iHeight * aSourceSize.iWidth + / aSourceSize.iHeight; + // move rect middle of the screen + position.iX = (aFullScreenSize.iWidth - drawRect.iBr.iX) / 2; + } + + drawRect.Move(position); + LOG(EJavaMMAPI,EInfo,"CMMADisplay::ScaleToFullScreen() -"); + return drawRect; +} + +// from MMMADisplay +void CMMADisplay::DrawFrameL(const CFbsBitmap* aBitmap) +{ + // This method is called only if bitmap is used. + // Runs in mmapi thread + if (iVisible && iWindow /*&& iDirectContainer*/) + { + iWindow->DrawFrameL(aBitmap); + //iDirectContainer->MdcFlushContainer(iWindow->WindowRect()); + } +} + +void CMMADisplay::SetClippingRegion() +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion"); + + if (!iWindow || + (iWindow->GetDisplayWindowType() == MMMADisplayWindow::EDisplayWindowTypeIsBitmap) || + iClipRect == iWindow->DrawRect() && iContainerVisible && iVisible) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion before return"); + return; + } + + TBool refreshScreen(EFalse); + // Remove first the current clip rect if set + LOG2(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: iClipRect = %d X %d",iClipRect.Width(),iClipRect.Height()); + if (!iClipRect.IsEmpty()) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: Removing old rect"); + //iDirectContainer->MdcRemoveContentBounds(iClipRect); + iClipRect.SetRect(0, 0, 0, 0); + refreshScreen = ETrue; + } + // If visible then set a new clip rect + if (iVisible && iContainerVisible) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: inside if (iVisible && iContainerVisible)"); + iClipRect = iWindow->DrawRect(); + LOG2(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: inside if (iVisible && iContainerVisible)iClipRect = %d X %d",iClipRect.Width(),iClipRect.Height()); + if (!iClipRect.IsEmpty()) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: Adding new rect"); + // Add new clipping rect + // iDirectContainer->MdcAddContentBounds(iClipRect); + SetContentBoundToJavaControl(iClipRect); + refreshScreen = ETrue; + } + } + if (refreshScreen) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion: inside if(refreshScreen)"); + // refresh screen + // iDirectContainer->MdcFlushContainer(iWindow->WindowRect()); + RefreshJavaControl(iWindow->WindowRect()); + } + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetClippingRegion -"); +} + +void CMMADisplay::RemoveClippingRegion() +{ + // Called in mmapi thread + LOG(EJavaMMAPI,EInfo,"CMMADisplay::RemoveClippingRegion"); + + if (!iWindow || + (iWindow->GetDisplayWindowType() == MMMADisplayWindow::EDisplayWindowTypeIsBitmap)) + { + return; + } + // Remove first the current clip rect if set + if (!iClipRect.IsEmpty()) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::RemoveClippingRegion: Removing old rect"); + //iDirectContainer->MdcRemoveContentBounds(iClipRect); + RemoveContentBoundFromJavaControl(iClipRect); + iClipRect.SetRect(0, 0, 0, 0); + // refresh screen + //iDirectContainer->MdcFlushContainer(iWindow->WindowRect()); + RefreshJavaControl(iWindow->WindowRect()); + } +} + +void CMMADisplay::AddClippingRegion() +{ + // Called in mmapi thread + LOG(EJavaMMAPI,EInfo,"CMMADisplay::AddClippingRegion"); + LOG2(EJavaMMAPI,EInfo,"CMMADisplay::AddClippingRegion iClipRect width = %d height = %d", iClipRect.Width() , iClipRect.Height()); + + if (!iWindow || + (iWindow->GetDisplayWindowType() == + MMMADisplayWindow::EDisplayWindowTypeIsBitmap) || + iClipRect == iWindow->DrawRect()) + { + return; + } + // If visible then set a new clip rect + if (iVisible) + { + iClipRect = iWindow->DrawRect(); + if (!iClipRect.IsEmpty()) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::AddClippingRegion: Adding new rect"); + // Add new clipping rect + // iDirectContainer->MdcAddContentBounds(iClipRect); + SetContentBoundToJavaControl(iClipRect); + // refresh screen + // iDirectContainer->MdcFlushContainer( + // iWindow->WindowRect()); + RefreshJavaControl(iWindow->WindowRect()); + } + } +} + +// from MMMADisplay +TSize CMMADisplay::DisplaySize() +{ + if (iWindow && iFullScreen) + { + return iWindow->DrawRect().Size(); + } + else + { + return iUserRect.Size(); + } +} + +// from MMMADisplay +void CMMADisplay::SetDisplaySizeL(const TSize& aSize) +{ + // user rect contains size set from java. + iUserRect.SetSize(aSize); + LOG2(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetDisplaySizeL iUserRect = %d X %d", iUserRect.Width() ,iUserRect.Height()); + // Size change has no effect if fullscreen mode is on. + // New size could be used when fullscreen is turned off. + if (iContainerVisible && !iFullScreen && iWindow) + { + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetVisible + iContainerVisible = %d", iContainerVisible); + RemoveClippingRegion(); + LOG2(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetDisplaySizeL iUserRect after removingClipRegion = %d X %d", iUserRect.Width() ,iUserRect.Height()); + iWindow->SetDrawRect(iUserRect); + AddClippingRegion(); + LOG2(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetDisplaySizeL iUserRect after AddingClipRegion = %d X %d", iUserRect.Width() ,iUserRect.Height()); + } + else + { + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetVisible + iContainerVisible = %d", iContainerVisible); + iResetDrawRect = ETrue; + } +} + +// from MMMADisplay +void CMMADisplay::SetVisible(TBool aValue) +{ + iVisible = aValue; + // Window may be set visible only if container is on screen, + + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetVisible + iContainerVisible = %d", iContainerVisible); + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetVisible iVisible = %d", iVisible); + if (!iIsForeground) + { + LOG(EJavaMMAPI,EInfo,"MID::CMMADisplay::SetVisible - iIsForeground = 0"); + return; + } + // if not it can not be set visible. + if (iWindow && iContainerVisible) + { + // iWindow->SetVisible(aValue, EFalse); + //MMAPI UI 3.x req. (had to comment above line and add below line which excutes in FS thread) + iWindow->SetVisible(aValue, ETrue); + SetClippingRegion(); + } +} + + +void CMMADisplay::SetContainerVisibility(TBool aValue) +{ + iContainerVisible = aValue; + // TODO : delete the below check once implementation is done as it is used only for testing purpose + if(iContainerVisible) + LOG(EJavaMMAPI,EInfo,"CMMADisplay:SetContainerVisibility(): Container is visible "); + else + LOG(EJavaMMAPI,EInfo,"CMMADisplay:SetContainerVisibility(): Container is not visible "); + + HandleContainerVisibilityChanged(aValue); +} +// from MMMADisplay +void CMMADisplay::SetWindowL(MMMADisplayWindow* aWindow) +{ + // Sets new window. Ownership is not transferred. + iWindow = aWindow; +} + +// from MMMADisplay +MMMADisplayWindow* CMMADisplay::Window() +{ + return iWindow; +} + +TBool CMMADisplay::IsVisible() +{ + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::IsVisible iContainerVisible = %d", iContainerVisible); + LOG1(EJavaMMAPI,EInfo,"MID::CMMADisplay::IsVisible iVisible = %d", iVisible); + // display is visible if container is on screen and + // java side has set it visible + return iVisible && iContainerVisible; +} + +TBool CMMADisplay::IsFullScreen() +{ + return iFullScreen; +} + +TBool CMMADisplay::HasContainer() +{ + // return iDirectContainer != NULL; + return EFalse; // temporary +} + + +void CMMADisplay::HandleContainerVisibilityChanged( TBool aVisible ) + { + LOG1(EJavaMMAPI,EInfo, "CMMADisplay::HandleContainerVisibilityChanged aVisible = %d", + aVisible ); + if(!iIsForeground && aVisible) + { + LOG(EJavaMMAPI,EInfo," CMMADisplay::HandleContainerVisibilityChanged Condition 1 "); + return; + } + + LOG(EJavaMMAPI,EInfo," CMMADisplay::HandleContainerVisibilityChanged After condition1"); + + if (iWindow) + { + // midlet comes to foreground (0 to 1 transition), + // Allow turn on or turn off based on aVisible + if (aVisible != iWindow->IsVisible()) + { + // Allow + LOG(EJavaMMAPI,EInfo,"MID::CMMADisplay::MdcContainerVisibilityChanged Allow "); + } + else if( iContainerVisible == aVisible ) + { + LOG(EJavaMMAPI,EInfo,"MID::CMMADisplay::MdcContainerVisibilityChanged iContainerVisible == aVisible "); + // if state is not changed, we do not need to do it again + return; + } + } + + LOG(EJavaMMAPI,EInfo,"MID::CMMADisplay::MdcContainerVisibilityChanged After condition2"); + + if (iWindow) + { + LOG(EJavaMMAPI,EInfo,"MID::CMMADisplay::MdcContainerVisibilityChanged iWindow is valid "); + // change is only needed if java side has set display visible or + // if container loses focus + if (!iContainerVisible || iVisible) + { + if (iResetDrawRect && aVisible && !iFullScreen) + { + iWindow->SetDrawRectThread(iUserRect); + iResetDrawRect = EFalse; + } + if (iIsForeground) + { + iWindow->SetVisible(aVisible); + } + SetClippingRegion(); + } + } +} + +/* + +void CMMADisplay::MdcItemContentRectChanged(const TRect& aContentRect, + const TRect& aScreenRect) +{ + // To be overwritten if used + __ASSERT_LOG(EJavaMMAPI,EInfo,"EFalse, User::Invariant()); +} + +void CMMADisplay::MdcContainerWindowRectChanged(const TRect& + #ifdef RD_JAVA_NGA_ENABLED + aRect + #endif + ) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::MdcContainerWindowRectChanged +"); + + #ifdef RD_JAVA_NGA_ENABLED + if( iWindow ) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::MdcContainerWindowRectChanged, SetRWindowRect"); + iWindow->SetRWindowRect(aRect, MMMADisplay::EUiThread); + } + #endif + } +void CMMADisplay::MdcContainerDestroyed() +{ + LOG(EJavaMMAPI,EInfo,"MMA::CMMADisplay::MdcContainerDestroyed"); + + if (iWindow) + { + iWindow->ContainerDestroyed(); + } + + iDirectContainer = NULL; +} + + +void CMMADisplay::MdcAbortDSA() +{ + if (iWindow) + { + iWindow->AbortDSA(); + } +} + + +void CMMADisplay::MdcResumeDSA() +{ + if (iWindow) + { + iWindow->ResumeDSA(); + } +} + +void CMMADisplay::UIGetCallback( + MUiEventConsumer& aConsumer, + TInt aCallbackId) +{ + if (iDirectContainer) + { + iDirectContainer->MdcGetUICallback(aConsumer, aCallbackId); + } +} +*/ + + +void CMMADisplay::GetCallbackInUiThread(TInt placeholder) +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::GetCallbackInUiThread +"); + + + + + + + + + jmethodID getCallBackMethodID = iJni->GetMethodID( + iJavaDisplayClass, + "GetCallbackInUiThread", + "(I)V"); + // LOG1(EJavaMMAPI,EInfo,"CMMADisplay::GetCallbackInUiThread getCallBackMethodID = %d",getCallBackMethodID); + iJni->CallVoidMethod(iJavaDisplayObject,getCallBackMethodID,placeholder); + LOG(EJavaMMAPI,EInfo,"CMMADisplay::GetCallbackInUiThread -"); +} + +void CMMADisplay::CalledBackInUiThread(TInt placeholder) +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::CalledBackInUiThread +"); + iWindow->UICallback(placeholder); + LOG(EJavaMMAPI,EInfo,"CMMADisplay::CalledBackInUiThread -"); + +} + +void CMMADisplay::SourceSizeChanged(TInt aJavaControlWidth, TInt aJavaControlHeight) + { + LOG2(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged(aSourceSize,aJavaControlWidth,aJavaControlHeight) + aJavaControlWidth = %d ,aJavaControlHeight = %d",aJavaControlWidth,aJavaControlHeight); + iSourceSize = SourceSize(); + LOG2(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged(aSourceSize,aJavaControlWidth,aJavaControlHeight) + sourcesize = %d X %d",iSourceSize.iWidth , iSourceSize.iHeight); + #ifdef RD_JAVA_NGA_ENABLED + if ( iWindow ) + { + iWindow->SetVideoCropRegion( TRect( iUserRect.iTl, iSourceSize ) ); + } + #endif + + // size of canvas in java + TSize canvasSize(aJavaControlWidth, aJavaControlHeight); + fullScreenSize = canvasSize; + TBool sourceIsBigger = (iSourceSize.iWidth > fullScreenSize.iWidth || + iSourceSize.iHeight > fullScreenSize.iHeight); + + if (sourceIsBigger) + { + // Source is larger than display area. + // Shrink draw are to fit in display. + iWindow->SetDrawRect(ScaleToFullScreen(fullScreenSize, iSourceSize)); + } + else + { + // source is smaller than display area + iWindow->SetDrawRect(TRect(iUserRect.iTl, iSourceSize)); + } + + SetClippingRegion(); + + if (iUserRect.IsEmpty()) + { + // Java side hasn't set size. + iUserRect = iWindow->DrawRect(); + + if (!sourceIsBigger) + { + // Addjusting rect to top left corner. + iUserRect = TRect(iUserRect.Size()); + } + } + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged(aSourceSize,aJavaControlWidth,aJavaControlHeight) -"); + } + +void CMMADisplay::SetWindowResources(QWidget* qtWidget) + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetWindowResources +"); + CCoeControl* control = 0; + if(qtWidget && qtWidget ->winId()) + { + control = reinterpret_cast(qtWidget->winId()); + } + + CCoeEnv *coeEnv = control->ControlEnv(); + RWsSession * iWs = &(coeEnv->WsSession()); + CWsScreenDevice* iScreenDevice = coeEnv->ScreenDevice(); + RWindowBase* window = static_cast(control->DrawableWindow()); + if (!iWindow) + { + return; + } + iWindow->ProcureWindowResourcesFromQWidget(iWs,iScreenDevice,window); + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetWindowResources -"); + } + + +void CMMADisplay::SetForeground(TBool aForeground, TBool aUseEventServer) +{ + LOG1(EJavaMMAPI,EInfo,"MMA::CMMADisplay::SetForeground %d", aForeground); + iIsForeground = aForeground; + + if (aForeground) + { + if (iContainerVisible && !iWindow->IsVisible()) + { + iWindow->SetVisible(ETrue, aUseEventServer); + } + } + else + { + if (iWindow->IsVisible()) + { + iWindow->SetVisible(EFalse, aUseEventServer); + } + } +} + +TSize CMMADisplay::SourceSize() + { + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SetSourceSizeToDisplay "); + return iUiPlayer->SourceSize(); + } + +void CMMADisplay::SetUIPlayer(MMMAGuiPlayer* player) + { + iUiPlayer = player; + } + + +void CMMADisplay::SourceSizeChanged(const TSize& aSourceSize) +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged"); + + #ifdef RD_JAVA_NGA_ENABLED + if ( iWindow ) + { + iWindow->SetVideoCropRegion( TRect( iUserRect.iTl, aSourceSize ) ); + } + #endif + + iSourceSize = aSourceSize; + jmethodID getDisplayWidthID = iJni->GetMethodID( + iJavaDisplayClass, + "getDisplayWidth", + "()I"); + + jmethodID getDisplayHeightID = iJni->GetMethodID( + iJavaDisplayClass, + "getDisplayHeight", + "()I"); + + + TInt x = iJni->CallIntMethod(iJavaDisplayObject,getDisplayWidthID); + TInt y = iJni->CallIntMethod(iJavaDisplayObject,getDisplayHeightID); + LOG2(EJavaMMAPI,EInfo,"CMMADisplay.cpp : SourceSizeChanged () fullScreenSize is x = %d ,y = %d ",x,y); + // get the ScreenSize from canvas in java + TSize canvasSize(x, y); + fullScreenSize = canvasSize; + TBool sourceIsBigger = (aSourceSize.iWidth > fullScreenSize.iWidth || + aSourceSize.iHeight > fullScreenSize.iHeight); + + if (sourceIsBigger) + { + // Source is larger than display area. + // Shrink draw are to fit in display. + iWindow->SetDrawRect(ScaleToFullScreen(fullScreenSize, iSourceSize)); + } + else + { + // source is smaller than display area + iWindow->SetDrawRect(TRect(iUserRect.iTl, iSourceSize)); + } + + SetClippingRegion(); + + if (iUserRect.IsEmpty()) + { + // Java side hasn't set size. + iUserRect = iWindow->DrawRect(); + + if (!sourceIsBigger) + { + // Addjusting rect to top left corner. + iUserRect = TRect(iUserRect.Size()); + } + } +} + + + +void CMMADisplay::SetDisplayPosition(TInt uiControlLocationX,TInt uiControlLocationY,TInt videoControlLocationX,TInt videoControlLocationY) +{ + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged + "); + TPoint point(videoControlLocationX ,videoControlLocationY); + //calling derived class fuction + SetDisplayLocationL(point); + LOG(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged - "); +} + + +void CMMADisplay::ResetJavaRectObject(const TRect& aRect) + { + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject +"); + JNIEnv* validJni = iEventSource->getValidJniEnv(); + jmethodID setRectID = validJni->GetMethodID( + iJavaDisplayClass, + "setRect", + "()V"); + + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject --1"); + // set the value to java,so that we can access those from array + jfieldID field = validJni->GetFieldID(iJavaDisplayClass, "rectDimension", "[I"); + if(field == NULL) + { + // handle error + } + /* Write to the instance fields */ + jintArray javaDimensionarr = (jintArray)validJni->GetObjectField(iJavaDisplayObject, field); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject --2"); + jint* nativeRectDimensionArr = validJni->GetIntArrayElements(javaDimensionarr, NULL); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject --3"); + if (!nativeRectDimensionArr) + { // inputBuffer was already allocated + validJni->ReleaseIntArrayElements(javaDimensionarr, nativeRectDimensionArr, JNI_ABORT); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject Error in resetting rect dimension to java"); + return; + } + nativeRectDimensionArr[0] = aRect.iTl.iX; + nativeRectDimensionArr[1] = aRect.iTl.iY;; + nativeRectDimensionArr[2] = aRect.Width(); + nativeRectDimensionArr[3] = aRect.Height(); + // Now the dimension array in java is updated hence reset the java rect + validJni->CallVoidMethod(iJavaDisplayObject,setRectID); + + validJni->ReleaseIntArrayElements(javaDimensionarr, nativeRectDimensionArr, JNI_COMMIT); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::ResetJavaRectObject -"); +} + + +void CMMADisplay::SetContentBoundToJavaControl(const TRect& aRect) + { + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::SetContentBoundToJavaControl +"); + JNIEnv* validJni = iEventSource->getValidJniEnv(); + // Reset the java rect + ResetJavaRectObject(aRect); + jmethodID setContentBoundID = validJni->GetMethodID( + iJavaDisplayClass, + "setContentBound", + "()V"); + // call java function + validJni->CallVoidMethod(iJavaDisplayObject,setContentBoundID); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::SetContentBoundToJavaControl -"); + } + +void CMMADisplay::RemoveContentBoundFromJavaControl(const TRect& aRect) + { + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::RemoveContentBoundFromJavaControl +"); + JNIEnv* validJni = iEventSource->getValidJniEnv(); + // Reset the java rect + ResetJavaRectObject(aRect); + jmethodID removeContentBoundID = validJni->GetMethodID( + iJavaDisplayClass, + "removeContentBound", + "()V"); + // call java function + validJni->CallVoidMethod(iJavaDisplayObject,removeContentBoundID); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::RemoveContentBoundFromJavaControl -"); + } + +void CMMADisplay::RefreshJavaControl(const TRect& aRect) + { + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::RefreshJavaControl +"); + JNIEnv* validJni = iEventSource->getValidJniEnv(); + // Reset the java rect + //ResetJavaRectObject(aRect); + jmethodID redrawControlID = validJni->GetMethodID( + iJavaDisplayClass, + "redrawControl", + "()V"); + // call java function + validJni->CallVoidMethod(iJavaDisplayObject,redrawControlID); + LOG(EJavaMMAPI,EInfo,"MMA::CMMACanvasDisplay::RefreshJavaControl -"); + } + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmadurationupdater.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmadurationupdater.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Send update duration event if needed when player state changes +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadurationupdater.h" + +CMMADurationUpdater* CMMADurationUpdater::NewL(CMMAPlayer& aPlayer) +{ + CMMADurationUpdater* self = new(ELeave) CMMADurationUpdater(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; +} + +CMMADurationUpdater::CMMADurationUpdater(CMMAPlayer& aPlayer) + : iPlayer(aPlayer), iDuration(KErrNotFound), iSecondStart(EFalse) +{ +} + +void CMMADurationUpdater::ConstructL() +{ + iPlayer.AddStateListenerL(this); +} + +CMMADurationUpdater::~CMMADurationUpdater() +{ + iPlayer.RemoveStateListener(this); +} + +void CMMADurationUpdater::StateChanged(TInt aState) +{ + TInt64 duration = 0; + iPlayer.GetDuration(&duration); + + if ((duration >= KErrNotFound) && (duration != iDuration)) + { + // Send DURATION_UPDATED + iDuration = duration; + iPlayer.PostLongEvent(CMMAPlayerEvent::EDurationUpdated, iDuration); + } + else if (duration == KErrNotFound && aState == CMMAPlayer::EStarted && !iSecondStart) + { + // for medias whose duration is unknown (e.g. streaming audio amr) + // must post EDurationUpdated event with duration -1 in first start + iPlayer.PostLongEvent(CMMAPlayerEvent::EDurationUpdated, iDuration); + iSecondStart = ETrue; + } + + if (aState == CMMAPlayer::ERealized) + { + iSecondStart = EFalse; + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaevent.h" + +CMMAEvent::CMMAEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable): + iListenerObject(aNotifyObject), + iHandleEventMethod(aHandleEventMethod) +{ +} + + +CMMAEvent::CMMAEvent(TDisposability /*aDisposable*/) +{ +} + + +void CMMAEvent::SetEventData(TInt aEventData) +{ + iEventData = aEventData; +} + + +// from CJavaEvent +void CMMAEvent::Dispatch(JNIEnv& aJni) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAEvent::Dispatch iEventData=%d", iEventData); + + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventData); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaframepositioningcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaframepositioningcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Abstract base class for FramePositioningControl +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaplayer.h" +#include "cmmaframepositioningcontrol.h" + +CMMAFramePositioningControl::CMMAFramePositioningControl(CMMAPlayer* aPlayer) + : iPlayer(aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAFramePositioningControl::CMMAFramePositioningControl"); +} + +CMMAFramePositioningControl::~CMMAFramePositioningControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAFramePositioningControl::~CMMAFramePositioningControl"); +} + +const TDesC& CMMAFramePositioningControl::ClassName() const +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAFramePositioningControl::ClassName"); + return KMMAFramePositioningControlName; +} + +TInt CMMAFramePositioningControl::ClampMediaTime(TInt64& aMediaTime) +{ + TInt64 duration = 0; + iPlayer->GetDuration(&duration); + if (duration < 0) + { + return KErrNotFound; + } + + if (aMediaTime > duration) + { + aMediaTime = duration; + } + else if (aMediaTime < 0) + { + aMediaTime = 0; + } + return KErrNone; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaitemdisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaitemdisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,177 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Bitmap display that draws to the Java CustomItem's bitmap. +* +*/ + + +// Include Files +#include +//#include + +#include "cmmaitemdisplay.h" +#include "cmmabitmapwindow.h" + +// CONSTRUCTION +// Static constructor, leaves pointer to cleanup-stack +CMMAItemDisplay* CMMAItemDisplay::NewLC(/*MMIDCustomItem* aCustomItem*/) +{ + CMMAItemDisplay* self = new(ELeave) CMMAItemDisplay(/*aCustomItem*/); + CleanupStack::PushL(self); + // self->Construct(/*&(aCustomItem->DirectContainer())*/); + return self; +} + + +// Destructor (virtual by CBase) +CMMAItemDisplay::~CMMAItemDisplay() +{ +} + + +CMMAItemDisplay::CMMAItemDisplay(/*MMIDCustomItem* aCustomItem*/) + //: iItem(aCustomItem) +{ + iVisible = ETrue; // Item is visible at startup +} + +void CMMAItemDisplay::SizeChangedL(CMMAItemDisplay* aDisplay, + TInt /*aWidth*/, + TInt /*aHeight*/) +// currently width and height is ignored +// may be used later to layout the image. +{ + /* + if (aDisplay->iWindow) + { + CFbsBitmap* bitmap = aDisplay->iItem->FrameBuffer(); + aDisplay->iWindow->SetDestinationBitmapL(bitmap); + } + */ +} + +void CMMAItemDisplay::SetFullScreenL(TBool aFullScreen) +{ + iFullScreen = aFullScreen; + if (!iWindow) + { + return; + } + if (aFullScreen) + { + // switch to fullscreen + iWindow->SetDrawRect(ScaleToFullScreen( + iWindow->WindowSize(), iSourceSize)); + } + else + { + // switch to normal screen + iWindow->SetDrawRect(iUserRect); + } +} + +void CMMAItemDisplay::SetWindowL(MMMADisplayWindow* aWindow) +{ + CMMADisplay::SetWindowL(aWindow); + if (!iWindow) + { + LOG( EJavaMMAPI, EInfo, "CMMAItemDisplay::SetWindowL: NULL window, returning"); + return; + } + iSourceSize = iWindow->WindowSize(); + /* CFbsBitmap* bitmap = iItem->FrameBuffer(); + + if (bitmap) + { + iWindow->SetDestinationBitmapL(bitmap); + } + */ +} + +void CMMAItemDisplay::SetDisplayLocationL(const TPoint& /*aPosition*/) +{ + // In item( USE_GUI_PRIMITIVE ) mode, this call will be ignored. +} + + +TPoint CMMAItemDisplay::DisplayLocation() +{ + // Java Item's location is always 0, 0 + return TPoint(0, 0); +} + +void CMMAItemDisplay::SourceSizeChanged(const TSize& aSourceSize) +{ + LOG1(EJavaMMAPI,EInfo,"MMA::CMMAItemDisplay::SourceSizeChanged %d", + aSourceSize.iWidth); + LOG1(EJavaMMAPI,EInfo,"MMA::CMMAItemDisplay::SourceSizeChanged %d", + aSourceSize.iHeight); + + #ifdef RD_JAVA_NGA_ENABLED + if ( iWindow ) + { + iWindow->SetVideoCropRegion( TRect( iUserRect.iTl, aSourceSize ) ); + } + #endif + + iSourceSize = aSourceSize; + + if (iWindow) + { + TRect clientRect(iUserRect.iTl, aSourceSize); + + iWindow->SetDrawRect(clientRect); + // Setting initial window size if not already set, actual size will + // be set in MdcItemContentRectChanged() + if (iWindow->WindowSize() == TSize()) + { + iWindow->SetWindowRect(clientRect, MMMADisplay::EMmaThread); + } + } + + SetClippingRegion(); + + if (iUserRect.IsEmpty()) + { + // Java side hasn't set size. + iUserRect.SetSize(iSourceSize); + } +} + +void CMMAItemDisplay::StaticSourceSize(CMMAItemDisplay* aDisplay, + TSize* aSize) +{ + *aSize = aDisplay->iUserRect.Size(); +} + +/*void CMMAItemDisplay::MdcItemContentRectChanged(const TRect& aContentRect, + const TRect& aScreenRect) +{ + if (iWindow) + { + // Change windows rect. + iWindow->SetWindowRect(aScreenRect, MMMADisplay::EUiThread); + TRect drawRect = aContentRect; + drawRect.Move(- aScreenRect.iTl); + iWindow->SetDrawRectThread(drawRect); + } + SetClippingRegion(); +} +*/ +/*void CMMAItemDisplay::MdcContentBoundsChanged(const TRect& aRect) +{ + // Do nothing in Item display +} +*/ +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmametadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmametadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This interface is for getting metadata from a media. +* +*/ + + +// INCLUDE FILES +#include "cmmametadatacontrol.h" + + +_LIT(KControlName, "MetaDataControl"); + + +CMMAMetaDataControl::CMMAMetaDataControl() +{ + // Nothing, OK. +} + +void CMMAMetaDataControl::StaticKeysCountL(CMMAMetaDataControl* aMetaDataControl, TInt *aCount) +{ + *aCount = aMetaDataControl->KeyCountL(); +} + +void CMMAMetaDataControl::StaticKeyL(CMMAMetaDataControl* aMetaDataControl, HBufC** aKey, TInt aIndex) +{ + *aKey = aMetaDataControl->KeyL(aIndex); +} + +void CMMAMetaDataControl::StaticKeyValueL( + CMMAMetaDataControl* aMetaDataControl, + HBufC** aValue, + TDesC* aKey) +{ + /* Just pass the call through to the real implementation. The ownership of the returned data + * is received from the implementation and passed to the caller as well. + * + */ + *aValue = aMetaDataControl->KeyValueL(*aKey); +} + +const TDesC& CMMAMetaDataControl::ClassName() const +{ + return KControlName; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidicontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidicontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,328 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a MIDIControl. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmamidicontrol.h" +#include "cmmamidiplayer.h" + +namespace +{ +const TReal KMMAMIDIVolumeConversionConstant = 40; +const TReal KMMADecibelToMidiVolumeConversionPowerBase = 10; +//const TTimeIntervalMicroSeconds32 KMMAMIDIVolumeChangeTimeout = 2000000; +const TInt KMMAMIDIVolumeChangeTimeout = 2000000; +const TReal KMMAMIDIMinimumVolumeDecibels = -130; +// For channel volume change message: +const TUint8 KMIDIControlChangeEvent = 0xB0; +const TUint8 KMIDIControlMainVolume = 0x07; +} + +CMMAMIDIControl* CMMAMIDIControl::NewL(CMMAMIDIPlayer* aPlayer) +{ + CMMAMIDIControl* self = new(ELeave)CMMAMIDIControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CMMAMIDIControl::CMMAMIDIControl(CMMAMIDIPlayer* aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::CMMAMIDIControl"); + iPlayer = aPlayer; +} + +CMMAMIDIControl::~CMMAMIDIControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::~CMMAMIDIControl +"); + delete iVolumeEventWait; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::~CMMAMIDIControl -"); +} + +void CMMAMIDIControl::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::ConstructL +"); + iVolumeEventWait = CChannelVolumeEventWait::NewL(); + iPlayer->addObserverL(this); + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::ConstructL -"); +} + +const TDesC& CMMAMIDIControl::ClassName() const +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIControl::ClassName"); + return KMIDIControlName; +} + +TInt CMMAMIDIControl::ChannelVolumeL(TInt aChannel) +{ + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: ChannelVolumeL + aChannel=%d", aChannel); + + CMidiClientUtility* midi = iPlayer->MidiClient(); + + // If engine is not processing events, current + // volume cannot be known for sure. + TMidiState engineState = midi->State(); +#ifdef RD_JAVA_TMIDISTATECHANGE + if ((engineState == EMidiStateClosedDisengaged) || + (engineState == EMidiStateOpenDisengaged)) +#else + if ((engineState == EClosedDisengaged) || + (engineState == EOpenDisengaged)) +#endif + { + return KErrNotFound; + } + + // This calculation might be slow on hardware, since + // following equation must be calculated using TReals: + // + // p1 = 10^(dB/40) * p0, where: + // p1 is target midi volume, + // p0 is reference value (maximum midi volume, 127) + // dB is volume value in Decibels from MidiClientUtility + + TReal32 volume = midi->ChannelVolumeL(aChannel); + if (volume < KMMAMIDIMinimumVolumeDecibels) + { + volume = KMMAMIDIMinimumVolumeDecibels; + } + TReal exponent = volume / KMMAMIDIVolumeConversionConstant; + TReal targetVal = 0; + + // calculate midi volume value + User::LeaveIfError( + Math::Pow( + targetVal, + KMMADecibelToMidiVolumeConversionPowerBase, + exponent)); + + // multiply by reference value + targetVal *= KMAXVolume; + + // round value to zero decimals + User::LeaveIfError(Math::Round(targetVal, targetVal, 0)); + + // clamp to bounds + TInt retVal = (int) targetVal; + if (retVal < 0) + { + retVal = 0; + } + else if (retVal > KMAXVolume) + { + retVal = KMAXVolume; + } + + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: ChannelVolumeL - retVal=%d", retVal); + return retVal; +} + +void CMMAMIDIControl::SetChannelVolumeL(TInt aChannel, TInt aVolume) +{ + LOG2( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SetChannelVolumeL + aChannel=%d aVolume=%d", aChannel, aVolume); + + CMidiClientUtility* midi = iPlayer->MidiClient(); + + // Change is done with shortMidiEvent so midi volume -> decibel + // calculation is avoided (would be needed for midi client api + // SetChannelVolumeL method) + + TBuf8<3> volumeChangeMessage; + // range is checked before + TUint8 channel = (KMIDIControlChangeEvent | (TUint8)aChannel); + volumeChangeMessage.Append(channel); + volumeChangeMessage.Append(KMIDIControlMainVolume); + volumeChangeMessage.Append((TUint8)aVolume); + SendMIDIEventL(&volumeChangeMessage); + + TMidiState engineState = midi->State(); + + // If engine is not processing, we do not have to + // wait until change is done. +#ifdef RD_JAVA_TMIDISTATECHANGE + if (!((engineState == EMidiStateClosedDisengaged) || + (engineState == EMidiStateOpenDisengaged))) +#else + if (!((engineState == EClosedDisengaged) || + (engineState == EOpenDisengaged))) +#endif + { + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SetChannelVolumeL: ExecuteL ->"); + iVolumeEventWait->StartWait(aChannel); + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SetChannelVolumeL: ExecuteL <-"); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SetChannelVolumeL -"); +} + +void CMMAMIDIControl::SetProgramL(TInt aChannel, + TInt aBank, + TInt aProgram) +{ + CMidiClientUtility* midi = iPlayer->MidiClient(); + + // Program means instrument. + midi->SetInstrumentL(aChannel, aBank, aProgram); +} + +TInt CMMAMIDIControl::SendMIDIEventL(const TDesC8* aData) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SendMIDIEventL +"); + CMidiClientUtility* midi = iPlayer->MidiClient(); + + // SendMessageL only processes first message in the descriptor, + // so we need to send blocks of data as many times as needed. + + TInt dataLength = aData->Length(); + TInt dataSent = 0; + while (dataSent < dataLength) + { + // Delegate event directly to the native implementation + // which checks the validity. + TPtrC8 nextBlock = aData->Right(dataLength - dataSent); + dataSent += midi->SendMessageL(nextBlock); + } + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SendMIDIEventL: sent %d bytes", dataSent); + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: SendMIDIEventL -"); + return dataSent; +} + +TInt CMMAMIDIControl::ReInitializeMidiL(const TDesC8* aData) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: ReInitializeMidiL + "); + iPlayer->ReInitializeMidiEngineL(aData); + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIControl: ReInitializeMidiL - "); + return KErrNone; +} + +void CMMAMIDIControl::MmcuoStateChanged(TMidiState /*aOldState*/, + TMidiState /*aNewState*/, + const TTimeIntervalMicroSeconds& /*aTime*/, + TInt /*aError*/) +{ +} + +void CMMAMIDIControl::MmcuoTempoChanged(TInt /*aMicroBeatsPerMinute*/) +{ +} + +void CMMAMIDIControl::MmcuoVolumeChanged(TInt aChannel, TReal32 /*aVolumeInDecibels*/) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAMIDIControl:: MmcuoVolumeChanged + aChannel=%d", aChannel); + if (iVolumeEventWait) + { + iVolumeEventWait->HandleVolumeChangedEvent(aChannel); + } + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl:: MmcuoVolumeChanged -"); +} + +void CMMAMIDIControl::MmcuoMuteChanged(TInt /*aChannel*/,TBool /*aMuted*/) +{ +} + +void CMMAMIDIControl::MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& /*aMicroSeconds*/,TInt64 /*aMicroBeats*/) +{ +} + +void CMMAMIDIControl::MmcuoMetaDataEntryFound(const TInt /*aMetaDataEntryId*/,const TTimeIntervalMicroSeconds& /*aPosition*/) +{ +} + +void CMMAMIDIControl::MmcuoMipMessageReceived(const RArray& /*aMessage*/) +{ +} + +void CMMAMIDIControl::MmcuoPolyphonyChanged(TInt /*aNewPolyphony*/) +{ +} + +void CMMAMIDIControl::MmcuoInstrumentChanged(TInt /*aChannel*/,TInt /*aBankId*/,TInt /*aInstrumentId*/) +{ +} + +CMMAMIDIControl::CChannelVolumeEventWait* CMMAMIDIControl::CChannelVolumeEventWait::NewL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::NewL"); + CChannelVolumeEventWait* self = new(ELeave) CChannelVolumeEventWait(); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +void CMMAMIDIControl::CChannelVolumeEventWait::ConstructL() +{ + iWait = new(ELeave) CActiveSchedulerWait(); + iTimer = CTimeOutTimer::NewL(CActive::EPriorityStandard, *this); +} + +CMMAMIDIControl::CChannelVolumeEventWait::CChannelVolumeEventWait() +{ +} + +CMMAMIDIControl::CChannelVolumeEventWait::~CChannelVolumeEventWait() +{ + delete iTimer; + delete iWait; +} + +void CMMAMIDIControl::CChannelVolumeEventWait::TimerExpired() +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::TimerExpired +"); + if (iWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::TimerExpired - cancelling wait"); + iWait->AsyncStop(); + } + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::TimerExpired -"); +} + +void CMMAMIDIControl::CChannelVolumeEventWait::StartWait(TInt aChannel) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::StartWait aChannel=%d", aChannel); + iChannel = aChannel; + + if (!iWait->IsStarted()) + { + iTimer->After(KMMAMIDIVolumeChangeTimeout); + iWait->Start(); + } +} + +void CMMAMIDIControl::CChannelVolumeEventWait::StopWait() +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::StopWait"); + if (iWait->IsStarted()) + { + iTimer->Cancel(); + iWait->AsyncStop(); + } +} + +void CMMAMIDIControl::CChannelVolumeEventWait::HandleVolumeChangedEvent(TInt aChannel) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAMIDIControl::CChannelVolumeEventWait::HandleVolumeChangedEvent aChannel=%d", aChannel); + if (iChannel == aChannel) + { + StopWait(); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidimetadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidimetadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMAMIDIMetaDataControl is a concrete class for getting +* metadata from midi engine. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmamidimetadatacontrol.h" + +CMMAMIDIMetaDataControl::CMMAMIDIMetaDataControl( + CMMAMIDIPlayer* aPlayer) + : iPlayer(aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMIDIMetaDataControl constructor called."); +} + +TInt CMMAMIDIMetaDataControl::KeyCountL() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIMetaDataControl::KeyCountL"); + TInt entries = iPlayer->MidiClient()->NumberOfMetaDataEntriesL(); + return entries; +} + +HBufC* CMMAMIDIMetaDataControl::KeyL(TInt aIndex) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIMetaDataControl::KeyL"); + CMMFMetaDataEntry* currEntry = + iPlayer->MidiClient()->GetMetaDataEntryL(aIndex); + CleanupStack::PushL(currEntry); + HBufC* key = currEntry->Name().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + return key; +} + + +/* + * Get the value of given midi metadata key. The ownership of the created value + * (descriptor) is passed to the caller. + */ +HBufC* CMMAMIDIMetaDataControl::KeyValueL(const TDesC& aKey) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIMetaDataControl::KeyValueL"); + + HBufC* retVal = NULL; + CMMFMetaDataEntry* currEntry = NULL; + + TInt nEntries = iPlayer->MidiClient()->NumberOfMetaDataEntriesL(); + + for (TInt i = 0; i < nEntries; ++i) + { + currEntry = iPlayer->MidiClient()->GetMetaDataEntryL(i); + + if (0 == aKey.Compare(currEntry->Name())) + { + CleanupStack::PushL(currEntry); + retVal = currEntry->Value().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + break; + } + + delete currEntry; + } + + User::LeaveIfNull(retVal); + return retVal; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidipitchcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidipitchcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a PitchControl. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmamidipitchcontrol.h" +#include "cmmamidiplayer.h" + +CMMAMIDIPitchControl* CMMAMIDIPitchControl::NewL(CMMAMIDIPlayer* aPlayer) +{ + CMMAMIDIPitchControl* self = new(ELeave) CMMAMIDIPitchControl(aPlayer); + return self; +} + +CMMAMIDIPitchControl::CMMAMIDIPitchControl(CMMAMIDIPlayer* aPlayer) +{ + iPlayer = aPlayer; + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIPitchControl::CMMAMIDIPitchControl"); +} + +CMMAMIDIPitchControl::~CMMAMIDIPitchControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIPitchControl::~CMMAMIDIPitchControl"); +} + +const TDesC& CMMAMIDIPitchControl::ClassName() const +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIPitchControl::ClassName"); + return KMIDIPitchControlName; +} + + +TInt CMMAMIDIPitchControl::PitchL() +{ + return iPlayer->MidiClient()->PitchTranspositionCentsL(); +} + +TInt CMMAMIDIPitchControl::SetPitchL(TInt aPitch) +{ + TInt pitch = aPitch; + if (aPitch > KMIDIPitchControlMaxPitch) + { + pitch = KMIDIPitchControlMaxPitch; + } + else if (aPitch < KMIDIPitchControlMinPitch) + { + pitch = KMIDIPitchControlMinPitch; + } + iPlayer->MidiClient()->SetPitchTranspositionL(pitch); + + return PitchL(); // return the actual Pitch +} + +// this method is intentionally left leaving to allow leaving implementation in the future +TInt CMMAMIDIPitchControl::MaxPitchL() +{ + return KMIDIPitchControlMaxPitch; +} + +// this method is intentionally left leaving to allow leaving implementation in the future +TInt CMMAMIDIPitchControl::MinPitchL() +{ + return KMIDIPitchControlMinPitch; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidiplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidiplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,590 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for MIDI. +* +*/ + + +// INCLUDE FILES +#include +#include +#include +#include + +#include "cmmamidiplayer.h" +#include "mmmadisplay.h" + +const TInt KErrorMessageSize = 32; +_LIT(KErrDefaultError, "Symbian OS Error: %d"); +const TInt KMidiDefaultBank = 0x3c80; +const TInt KMidiDrumBank = 0x3c7c; +const TInt KMidiDrumChannel = 9; +const TInt KMidiChannels = 16; +const TInt KMidiDefaultInstrument = 1; + +CMMAMIDIPlayer* CMMAMIDIPlayer::NewLC(const TDesC& aContentType, + TFileName aFileName) +{ + CMMAMIDIPlayer* self = new(ELeave) CMMAMIDIPlayer(aFileName); + CleanupStack::PushL(self); + self->ConstructL(aContentType); + return self; +} + +CMMAMIDIPlayer::~CMMAMIDIPlayer() +{ + CloseClientUtility(); + // new function added to CMMAPlayer delete the controls before the destruction of iMidi. + DeleteControls(); + delete iMidi; + delete iActiveSchedulerWait; + iObservers.Close(); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMIDIPlayer::~CMMAMIDIPlayer"); +} + +void CMMAMIDIPlayer::ConstructL(const TDesC& aContentType) +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDIPlayer::ConstructL"); + iContentType = aContentType.AllocL(); + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; + iMidi = CMidiClientUtility::NewL(*this, KAudioPriorityRecording, + KMMAMIDIPriorityPreference, ETrue); + + CMMAPlayer::ConstructL(); +} + +CMMAMIDIPlayer::CMMAMIDIPlayer(TFileName aFileName): + iFileName(aFileName), + iMediaTime(KTimeUnknown), iStartedEventTime(0) +{ +} + +EXPORT_C CMidiClientUtility* CMMAMIDIPlayer::MidiClient() const +{ + return iMidi; +} + + +void CMMAMIDIPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDIPlayer::RealizeL"); + CMMAPlayer::RealizeL(); +} + +void CMMAMIDIPlayer::PrefetchL() +{ + LOG1( EJavaMMAPI, EInfo, "CMMAMIDIPlayer::PrefetchL stream count %d", iSourceStreams.Count()); + if (iFileName != KNullDesC) + { + iMidi->OpenFile(iFileName); + } + else if (iSourceStreams.Count() == 0) + { + // We have no data, but need to initialize the player + // Preparing all channels + for (TInt i = 0; i < KMidiChannels; i++) + { + iMidi->SetInstrumentL(i, KMidiDefaultBank, + KMidiDefaultInstrument); + } + + // Setting drums to channel 10 + iMidi->SetInstrumentL(KMidiDrumChannel, KMidiDrumBank, + KMidiDefaultInstrument); + + // Start it immediately in order to get MIDIControl work without + // calling the start. This is how reference implementation works. + iMidi->Play(); + } + else + { + // Created with content, audio player will initialize controller + // and data source. + iSourceStreams[ 0 ]->ReadAllL(); + } +} + +// +// This method is called when CMMASourceStreamReader finished reading +// initiated in PrefetchL +// +void CMMAMIDIPlayer::ReadCompletedL(TInt aStatus, const TDesC8& aData) +{ + if (aStatus < KErrNone) + { + PostActionCompleted(aStatus); + } + else + { + // we're not finished yet + iMidi->OpenDes(aData); //wait for MMidiClientUtilityObserver::MmcuoStateChanged + } +} + +void CMMAMIDIPlayer::DeallocateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: DeallocateL +"); + if (iState == EPrefetched) + { + CloseClientUtility(); + ResetSourceStreams(); + ChangeState(ERealized); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: DeallocateL -"); +} + +void CMMAMIDIPlayer::StartL() +{ + iMediaTime = KTimeUnknown; + + // Player is already started if this player is constructed with + // device://midi locator. + TBool isDeviceMidi = (iSourceStreams.Count() == 0 && + iFileName == KNullDesC); + if (!isDeviceMidi) + { + iMidi->Play(); + } + + // inform java side + PostLongEvent(CMMAPlayerEvent::EStarted, iStartedEventTime); + ChangeState(EStarted); + + // To achieve similar functionality as reference implementation, + // END_OF_MEDIA must be sent right after Start on device://midi. + if (isDeviceMidi) + { + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, iStartedEventTime); + ChangeState(EPrefetched); + } + PostActionCompletedStart(); + //PostActionCompleted(KErrNone); // java start return +} + +void CMMAMIDIPlayer::StopL(TBool aPostEvent) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer::StopL"); + if (iState == EStarted) + { + TInt64 time; + GetMediaTime(&time); + iStartedEventTime = time; + + // do the stop only if we are playing some content + if ((iSourceStreams.Count() > 0) || + (iFileName != KNullDesC)) + { + // should actually pause!!! + iMidi->Stop(TTimeIntervalMicroSeconds(0)); + } + + if (aPostEvent) + { + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + // go back to prefetched state + ChangeState(EPrefetched); + } +} + +void CMMAMIDIPlayer::GetDuration(TInt64* aDuration) +{ + // Special case for device://midi + if ((iSourceStreams.Count() == 0) && + (iFileName == KNullDesC)) + { + iDuration = KErrNone; + } + else if (iDuration == KTimeUnknown) + { + TRAPD(err, iDuration = iMidi->DurationMicroSecondsL().Int64()); + if (err != KErrNone) + { + // Duration was not available. + iDuration = KTimeUnknown; + } + } + + *aDuration = iDuration; +} + +void CMMAMIDIPlayer::SetMediaTimeL(TInt64* aTime) +{ + TTimeIntervalMicroSeconds position(*aTime); + iMidi->SetPositionMicroSecondsL(position); + + // Reset cached media time, because actual set position may be + // something else than aTime. + iMediaTime = KTimeUnknown; + + // Inform about the position change to the StateListeners + ChangeState(iState); + + // Get the actual media time + GetMediaTime(aTime); + + iStartedEventTime = iMediaTime; +} + +void CMMAMIDIPlayer::GetMediaTime(TInt64* aMediaTime) +{ + // Special case for device://midi + if ((iSourceStreams.Count() == 0) && + (iFileName == KNullDesC)) + { + iMediaTime = KErrNone; + } + else if (iMediaTime == KTimeUnknown || iState == EStarted) + { + TTimeIntervalMicroSeconds position(0); + TRAPD(error, position = iMidi->PositionMicroSecondsL()); + + if (error == KErrNone) + { + TInt64 newTime = position.Int64(); + + // Sanity check for media time going backwards or beyond the + // duration. + // Some native controls may return zero media time for + // a few moments just before playback will complete. + if (newTime < iMediaTime || + (iDuration > 0 && newTime > iDuration)) + { + GetDuration(&iMediaTime); + } + else + { + // set return value + iMediaTime = newTime; + } + } + else + { + // media time cannot be get + iMediaTime = KTimeUnknown; + } + } + *aMediaTime = iMediaTime; +} + +void CMMAMIDIPlayer::ReInitializeMidiEngineL(const TDesC8* aMidiSequence) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIPlayer: ReInitializeMidiEngineL: + "); + + CloseClientUtility(); + + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: ReInitializeMidiEngineL: Opening descriptor"); + + iMidi->OpenDes(*aMidiSequence); + // Wait until asynchronous OpenDes call has completed + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + ChangeState(EPrefetched); + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDIPlayer: ReInitializeMidiEngineL: - "); +} + +void CMMAMIDIPlayer::addObserverL(MMidiClientUtilityObserver* aObserver) +{ + iObservers.AppendL(aObserver); +} + +void CMMAMIDIPlayer::CloseL() +{ + CMMAPlayer::CloseL(); + CloseClientUtility(); +} + +const TDesC& CMMAMIDIPlayer::Type() +{ + return KMMAMIDIPlayer; +} + +void CMMAMIDIPlayer::PlayCompleteL(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: PlayCompleteL +"); + ELOG1( EJavaMMAPI, "MMA: CMMAMidiPlayer: PlayCompleteL: Error=%d", aError); + TInt64 duration; + GetDuration(&duration); + iMediaTime = duration; + iStartedEventTime = 0; + + iMidi->Stop(TTimeIntervalMicroSeconds(0)); + + // go back to prefetched state + ChangeState(EPrefetched); // ready to play again + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, duration); + + if (aError == KErrNone) + { + iRepeatCount++; + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: PlayCompleteL -"); +} + +void CMMAMIDIPlayer::MmcuoStateChanged(TMidiState aOldState, + TMidiState aNewState, + const TTimeIntervalMicroSeconds& aTime, + TInt aError) +{ + TInt err = aError; + + ELOG3( EJavaMMAPI, "MMA: CMMAMIDIPlayer: MmcuoStateChanged: Old=%d, New=%d, Error=%d", + aOldState, + aNewState, + err); + // Closing the utility or reinitialising +#ifdef RD_JAVA_TMIDISTATECHANGE + if (iActiveSchedulerWait->IsStarted() && + ((aNewState == EMidiStateClosedDisengaged) || + (aNewState == EMidiStateOpenDisengaged) || + (aNewState == EMidiStateClosedEngaged))) +#else + if (iActiveSchedulerWait->IsStarted() && + ((aNewState == EClosedDisengaged) || + (aNewState == EOpenDisengaged) || + (aNewState == EClosedEngaged))) +#endif + { + iActiveSchedulerWait->AsyncStop(); + } + // changing from realized to prefetched state +#ifdef RD_JAVA_TMIDISTATECHANGE + else if ((iState == ERealized) && + (aOldState == EMidiStateClosedDisengaged) && + ((aNewState == EMidiStateOpenDisengaged) || + (aNewState == EMidiStateClosedEngaged) || + (aNewState == EMidiStateClosedDisengaged))) +#else + else if ((iState == ERealized) && + (aOldState == EClosed) && + ((aNewState == EOpen) || (aNewState == EClosedEngaged) || + (aNewState == EClosed))) // EClosed is EClosedDisengaged +#endif + { + if (aError == KErrNone) + { + // prefetch succeed + ChangeState(EPrefetched); + } + // else state remains realized + + // inform java + PostActionCompleted(aError); + err = KErrNone; // don't report the error again + } +#ifdef RD_JAVA_TMIDISTATECHANGE + else if ((aOldState == EMidiStateOpenPlaying) && + (aNewState == EMidiStateOpenEngaged) && + (iState == EStarted)) +#else + else if ((aOldState == EPlaying) && + (aNewState == EOpenEngaged) && + (iState == EStarted)) +#endif + { + // If iState is not EStarted PlayCompleteL may not be called because + // player may be already stopped. + + // playing completed + TRAPD(playErr, PlayCompleteL(aError)); + if (playErr != KErrNone) + { + err = playErr; + } + } + + if (err != KErrNone) + { + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, err); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } + } + + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoStateChanged(aOldState, aNewState, aTime, aError); + } + + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDIPlayer: MmcuoStateChanged: midi state %d", + iMidi->State()); +} + +void CMMAMIDIPlayer::MmcuoTempoChanged(TInt aMicroBeatsPerMinute) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoTempoChanged(aMicroBeatsPerMinute); + } +} + +void CMMAMIDIPlayer::MmcuoVolumeChanged(TInt aChannel,TReal32 aVolumeInDecibels) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoVolumeChanged(aChannel, aVolumeInDecibels); + } +} + +void CMMAMIDIPlayer::MmcuoMuteChanged(TInt aChannel,TBool aMuted) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoMuteChanged(aChannel, aMuted); + } +} + +void CMMAMIDIPlayer::MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& aMicroSeconds,TInt64 aMicroBeats) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoSyncUpdate(aMicroSeconds, aMicroBeats); + } +} + +void CMMAMIDIPlayer::MmcuoMetaDataEntryFound(const TInt aMetaDataEntryId,const TTimeIntervalMicroSeconds& aPosition) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoMetaDataEntryFound(aMetaDataEntryId, aPosition); + } +} + +void CMMAMIDIPlayer::MmcuoMipMessageReceived(const RArray& aMessage) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoMipMessageReceived(aMessage); + } +} + +void CMMAMIDIPlayer::MmcuoPolyphonyChanged(TInt aNewPolyphony) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoPolyphonyChanged(aNewPolyphony); + } +} + +void CMMAMIDIPlayer::MmcuoInstrumentChanged(TInt aChannel,TInt aBankId,TInt aInstrumentId) +{ + // notify observers + TInt count = iObservers.Count(); + for (TInt i = 0; i < count; i++) + { + iObservers[ i ]->MmcuoInstrumentChanged(aChannel, aBankId, aInstrumentId); + } +} + +void CMMAMIDIPlayer::CloseClientUtility() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: CloseClientUtility +"); + if (iMidi && + iActiveSchedulerWait && +#ifdef RD_JAVA_TMIDISTATECHANGE + (iMidi->State() != EMidiStateClosedDisengaged)) +#else + (iMidi->State() != EClosed)) +#endif + { + // Have to stop midi before closing, + // this case is for device://midi +#ifdef RD_JAVA_TMIDISTATECHANGE + if (iMidi->State() == EMidiStateClosedEngaged) +#else + if (iMidi->State() == EClosedEngaged) +#endif + { + iMidi->Stop(TTimeIntervalMicroSeconds(0)); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + } + else + { + // Calling Close and Stop or Stop and Close should + // always lead to EClosed state. + + // From EOpenEngaged or EOpenPlaying to EClosedEngaged + // or from EOpenDisengaged to EClosedDisengaged + iMidi->Close(); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + + LOG1( EJavaMMAPI, EInfo, "State after Close: %d", iMidi->State()); + + // If not in EClosedDisengaged yet +#ifdef RD_JAVA_TMIDISTATECHANGE + if (iMidi->State() != EMidiStateClosedDisengaged) +#else + if (iMidi->State() != EClosed) +#endif + { + // From EClosedEngaged to EClosedDisengaged + iMidi->Stop(TTimeIntervalMicroSeconds(0)); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + LOG1( EJavaMMAPI, EInfo, "State after Stop: %d", iMidi->State()); + } + } + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: CloseClientUtility: State after close: %d", iMidi->State()); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: CloseClientUtility -"); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidiplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidiplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,178 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating MIDI player. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmamidiplayerfactory.h" +#include "cmmamidiplayer.h" +#include "cmmamidivolumecontrol.h" +#include "cmmamidistoptimecontrol.h" +#include "cmmamidicontrol.h" +#include "cmmamiditempocontrol.h" +#include "cmmamidipitchcontrol.h" +#include "cmmammfresolver.h" +#include "cmmamidimetadatacontrol.h" + + +_LIT(KMMAMidi, "midi"); +_LIT(KDeviceMidiContentType, "audio/midi"); + +CMMAMIDIPlayerFactory* CMMAMIDIPlayerFactory::NewLC() +{ + CMMAMIDIPlayerFactory* pFactory = + new(ELeave) CMMAMIDIPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAMIDIPlayerFactory::CMMAMIDIPlayerFactory() +{ +} + + +CMMAMIDIPlayerFactory::~CMMAMIDIPlayerFactory() +{ +} + +CMMAPlayer* CMMAMIDIPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + // if we get this far then MIDI is supported + HBufC* contentType = aResolver->ContentType(); + HBufC* tmpFileName = aResolver->FileNameOwnership(); + TFileName fileName; + if (tmpFileName) + { + fileName.Copy(tmpFileName->Des()); + } + else + { + fileName = KNullDesC; + } + delete tmpFileName; + CMMAPlayer* player = CreateMidiFilePlayerL(*contentType, fileName); + return player; +} + + +void CMMAMIDIPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeMidi)); +} + +CMMAPlayer* CMMAMIDIPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aProperties) +{ + CMMAPlayer* player = NULL; + if ((aProtocol == KMMADeviceProtocol) && + (aMiddlePart == KMMAMidi)) + { + // locator was device://midi + player = CreateMidiSynthPlayerL(KDeviceMidiContentType); + } + else + { + // other locator, if it is midi file CMMAMMFPlayerFactory + // calls CreatePlayerL( CMMAMMFResolver* aResolver ) method. + player = CMMAMMFPlayerFactory::CreatePlayerL(aProtocol, + aMiddlePart, + aProperties); + } + return player; +} + +void CMMAMIDIPlayerFactory::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + if (IsSupportedContentTypeL(aContentType)) + { + aProtocolArray.AppendL(KMMADeviceProtocol); + } +} + +CMMAPlayer* CMMAMIDIPlayerFactory::CreateMidiFilePlayerL(const TDesC& aContentType, + TFileName aFileName) +{ + CMMAMIDIPlayer* player = CMMAMIDIPlayer::NewLC(aContentType, aFileName); + + CMMAMIDIVolumeControl* volumeControl = CMMAMIDIVolumeControl::NewL(player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + + CMMAMIDIStopTimeControl* stopTimeControl = CMMAMIDIStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + CMMAMIDIControl* midiControl = CMMAMIDIControl::NewL(player); + CleanupStack::PushL(midiControl); + player->AddControlL(midiControl); + CleanupStack::Pop(midiControl); + + CMMAMIDITempoControl* tempoControl = CMMAMIDITempoControl::NewL(player); + CleanupStack::PushL(tempoControl); + player->AddControlL(tempoControl); + CleanupStack::Pop(tempoControl); + + CMMAMIDIPitchControl* pitchControl = CMMAMIDIPitchControl::NewL(player); + CleanupStack::PushL(pitchControl); + player->AddControlL(pitchControl); + CleanupStack::Pop(pitchControl); + +#ifdef __MMA_METADATA_CONTROL__ + CMMAMIDIMetaDataControl* metaDataControl = + new(ELeave) CMMAMIDIMetaDataControl(player); + CleanupStack::PushL(metaDataControl); + player->AddControlL(metaDataControl); + CleanupStack::Pop(metaDataControl); +#endif // __MMA_METADATA_CONTROL__ + + CleanupStack::Pop(player); + return player; +} + +CMMAPlayer* CMMAMIDIPlayerFactory::CreateMidiSynthPlayerL(const TDesC& aContentType) +{ + CMMAMIDIPlayer* player = CMMAMIDIPlayer::NewLC(aContentType, KNullDesC()); + + CMMAMIDIVolumeControl* volumeControl = CMMAMIDIVolumeControl::NewL(player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + + CMMAMIDIControl* midiControl = CMMAMIDIControl::NewL(player); + CleanupStack::PushL(midiControl); + player->AddControlL(midiControl); + CleanupStack::Pop(midiControl); + + CMMAMIDIPitchControl* pitchControl = CMMAMIDIPitchControl::NewL(player); + CleanupStack::PushL(pitchControl); + player->AddControlL(pitchControl); + CleanupStack::Pop(pitchControl); + + CleanupStack::Pop(player); + return player; +} + +// END OF FILE + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidistoptimecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidistoptimecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmamidistoptimecontrol.h" +#include "cmmaplayer.h" + +CMMAMIDIStopTimeControl* CMMAMIDIStopTimeControl::NewL(CMMAPlayer* aPlayer) +{ + CMMAMIDIStopTimeControl* control = + new(ELeave) CMMAMIDIStopTimeControl(aPlayer); + CleanupStack::PushL(control); + // calls base class ConstructL + control->ConstructL(); + CleanupStack::Pop(); // control + return control; +} + + +CMMAMIDIStopTimeControl::~CMMAMIDIStopTimeControl() +{ +} + +CMMAMIDIStopTimeControl::CMMAMIDIStopTimeControl(CMMAPlayer* aPlayer) + : CMMAStopTimeControl(aPlayer) +{ +} + + +void CMMAMIDIStopTimeControl::StopAtTimeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDIStopTimeControl::StopAtTime"); + + // Stop the player only when it's playing + if (iPlayer->State() == CMMAPlayer::EStarted) + { + TInt64 time; + iPlayer->GetMediaTime(&time); + if (time >= 0 && time < iStopTime) + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAMIDIStopTimeControl::StopAtTime - Called %dms too early", + I64INT((time - iStopTime)/1000)); + StartTimer(time); + return; + } + + TInt64 stopTime; + + iPlayer->StopL(EFalse); + iPlayer->SetMediaTimeL(&iStopTime); + iPlayer->GetMediaTime(&stopTime); + + // Inform the player that it's "stopped at time" + iPlayer->PostLongEvent(CMMAPlayerEvent::EStoppedAtTime, stopTime); + + iStopTime = iNoTimer; // Timer is reseted + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamiditempocontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamiditempocontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,213 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a TempoControl. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmamiditempocontrol.h" +#include "cmmamidiplayer.h" + +static const TInt KMicroBeatsInMiliBeat = 1000; +static const TInt KMMAMIDIMinimumTempo = 10000; +static const TInt KMMAMIDIMaximumTempo = 300000; +static const TInt KMMAMIDIDefaultTempoInMicroBeats = 120000000; +_LIT(KMMAMidiTempoStateChangedError, "Tempo error in state change"); + +CMMAMIDITempoControl* CMMAMIDITempoControl::NewL(CMMAMIDIPlayer* aPlayer) +{ + CMMAMIDITempoControl* self = new(ELeave) CMMAMIDITempoControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CMMAMIDITempoControl::CMMAMIDITempoControl(CMMAMIDIPlayer* aPlayer) +{ + iPlayer = aPlayer; + iTempo = KMMAMIDIDefaultTempoInMicroBeats; + + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDITempoControl::CMMAMIDITempoControl"); +} + +CMMAMIDITempoControl::~CMMAMIDITempoControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDITempoControl::~CMMAMIDITempoControl"); +} + +inline void CMMAMIDITempoControl::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDITempoControl::ConstructL"); + + iPlayer->addObserverL(this); + iPlayer->AddStateListenerL(this); +} + +const TDesC& CMMAMIDITempoControl::ClassName() const +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMIDITempoControl::ClassName"); + return KMIDITempoControlName; +} + + +TInt CMMAMIDITempoControl::TempoL() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDITempoControl: TempoL"); + + return iTempo / KMicroBeatsInMiliBeat; +} + +TInt CMMAMIDITempoControl::SetTempoL(TInt aTempo) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMIDITempoControl: SetTempoL"); + TInt tempo = aTempo; + if (tempo < KMMAMIDIMinimumTempo) + { + tempo = KMMAMIDIMinimumTempo; + } + if (tempo > KMMAMIDIMaximumTempo) + { + tempo = KMMAMIDIMaximumTempo; + } + + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDITempoControl: SetTempoL: setting tempo %d", + tempo); + + // Convert tempo to micro-beats. + tempo *= KMicroBeatsInMiliBeat; + + // Set the tempo to the midi client if the player state is not REALIZED. + // (Tempo cannot be set to the midi client if the player + // has not been prefetched). + if (iPlayer->State() != CMMAPlayer::ERealized) + { + CMidiClientUtility* midi = iPlayer->MidiClient(); + midi->SetTempoL(tempo); + tempo = iPlayer->MidiClient()->TempoMicroBeatsPerMinuteL(); + } + + iTempo = tempo; + + LOG1( EJavaMMAPI, EInfo, "MMA: CMMAMIDITempoControl: SetTempoL: Tempo set: %d", + tempo / KMicroBeatsInMiliBeat); + + return tempo / KMicroBeatsInMiliBeat; +} + +TInt CMMAMIDITempoControl::SetRateL(TInt aRate) +{ + TInt rate = aRate; + TInt maxRate = MaxRateL(); + TInt minRate = MinRateL(); + + if (rate > maxRate) + { + rate = maxRate; + } + else if (rate < minRate) + { + rate = minRate; + } + iPlayer->MidiClient()->SetPlaybackRateL(rate); + return RateL(); // return the actual tempo +} + +TInt CMMAMIDITempoControl::RateL() +{ + return iPlayer->MidiClient()->PlaybackRateL(); +} + +TInt CMMAMIDITempoControl::MaxRateL() +{ + return iPlayer->MidiClient()->MaxPlaybackRateL(); +} + +TInt CMMAMIDITempoControl::MinRateL() +{ + return iPlayer->MidiClient()->MinPlaybackRateL(); +} + +void CMMAMIDITempoControl::StateChanged(TInt aState) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAMIDITempoControl:: StateChanged, state = %d", aState); + + // If tempo was set when the player was in REALIZED state, set the tempo + // now when the player has been prefetched. + if ((aState == CMMAPlayer::EPrefetched) && + (iTempo != KMMAMIDIDefaultTempoInMicroBeats)) + { + CMidiClientUtility* midi = iPlayer->MidiClient(); + TRAPD(err, midi->SetTempoL(iTempo)); + + ELOG1( EJavaMMAPI, "CMMAMIDITempoControl:: StateChanged, err = %d", err); + + if (err != KErrNone) + { + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, + KMMAMidiTempoStateChangedError); + } + } + else if (aState == CMMAPlayer::ERealized) + { + // If the player was deallocated, set the tempo to the default value. + iTempo = KMMAMIDIDefaultTempoInMicroBeats; + } +} +void CMMAMIDITempoControl::MmcuoStateChanged(TMidiState /*aOldState*/, + TMidiState /*aNewState*/, + const TTimeIntervalMicroSeconds& /*aTime*/, + TInt /*aError*/) +{ +} + +void CMMAMIDITempoControl::MmcuoTempoChanged(TInt aMicroBeatsPerMinute) +{ + LOG( EJavaMMAPI, EInfo, "CMMAMIDITempoControl:: MmcuoTempoChanged"); + + iTempo = aMicroBeatsPerMinute; +} + +void CMMAMIDITempoControl::MmcuoVolumeChanged(TInt /*aChannel*/,TReal32 /*aVolumeInDecibels*/) +{ +} + +void CMMAMIDITempoControl::MmcuoMuteChanged(TInt /*aChannel*/,TBool /*aMuted*/) +{ +} + +void CMMAMIDITempoControl::MmcuoSyncUpdate(const TTimeIntervalMicroSeconds& /*aMicroSeconds*/,TInt64 /*aMicroBeats*/) +{ +} + +void CMMAMIDITempoControl::MmcuoMetaDataEntryFound(const TInt /*aMetaDataEntryId*/,const TTimeIntervalMicroSeconds& /*aPosition*/) +{ +} + +void CMMAMIDITempoControl::MmcuoMipMessageReceived(const RArray& /*aMessage*/) +{ +} + +void CMMAMIDITempoControl::MmcuoPolyphonyChanged(TInt /*aNewPolyphony*/) +{ +} + +void CMMAMIDITempoControl::MmcuoInstrumentChanged(TInt /*aChannel*/,TInt /*aBankId*/,TInt /*aInstrumentId*/) +{ +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmamidivolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmamidivolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#include +#include "cmmamidivolumecontrol.h" +#include "cmmamidiplayer.h" + +CMMAMIDIVolumeControl::CMMAMIDIVolumeControl(CMMAMIDIPlayer* aPlayer) + : CMMAVolumeControl(aPlayer) +{ + iPlayer = aPlayer; +} + +void CMMAMIDIVolumeControl::ConstructL() +{ + ConstructBaseL(); +} + +CMMAMIDIVolumeControl* CMMAMIDIVolumeControl::NewL(CMMAMIDIPlayer* aPlayer) +{ + CMMAMIDIVolumeControl* self = new(ELeave)CMMAMIDIVolumeControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +void CMMAMIDIVolumeControl::DoSetLevelL(TInt aLevel) +{ + CMidiClientUtility* midi = iPlayer->MidiClient(); + TInt maxVolume = midi->MaxVolumeL(); + midi->SetVolumeL(aLevel * maxVolume / KMMAVolumeMaxLevel); +} + +TInt CMMAMIDIVolumeControl::DoGetLevelL() +{ + CMidiClientUtility* midi = iPlayer->MidiClient(); + // result is in range 0..100 + return (midi->VolumeL() * KMMAVolumeMaxLevel / midi->MaxVolumeL()); +} + + +// END OF FILE + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmammfplayerbase.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmammfplayerbase.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,377 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +#include +#include +#include +#include "cmmammfplayerbase.h" +#include "cmmammfresolver.h" + + +CMMAMMFPlayerBase::~CMMAMMFPlayerBase() +{ + // First delete the control and then close the controller + // Added after AudioOutputControl + DeleteControls(); + if (iControllerInfos) + { + iControllerInfos->ResetAndDestroy(); + } + delete iControllerInfos; + + if (iEventMonitor) + { + iEventMonitor->Cancel(); + } + + iController.Close(); + + delete iEventMonitor; + + delete iFileName; +} + + +CMMAMMFPlayerBase::CMMAMMFPlayerBase( + CMMAMMFResolver* aResolver) : + iMediaTime(KTimeUnknown), iStartedEventTime(0) +{ + // implementation array ownership is transferred + iControllerInfos = aResolver->ImplementationsOwnership(); + + // content type ownership is transferred + iContentType = aResolver->ContentTypeOwnership(); + + // file name ownership is transferred + iFileName = aResolver->FileNameOwnership(); +} + + +void CMMAMMFPlayerBase::ConstructL() +{ + CMMAPlayer::ConstructL(); + + // Create an event monitor + iEventMonitor = + CMMFControllerEventMonitor::NewL(*this, iController); +} + + +EXPORT_C RMMFController& CMMAMMFPlayerBase::Controller() +{ + return iController; +} + +EXPORT_C TInt CMMAMMFPlayerBase::DoOpen(TUid aSourceUid, + const TDesC8& aSourceData, + TUid aSinkUid, + const TDesC8& aSinkData, + TMMFPrioritySettings aPrioritySettings) +{ + // Make sure any existing controller is closed. + iEventMonitor->Cancel(); + iController.Close(); + + // Try opening and configuring each controller in turn + TInt error = KErrNotSupported; + TInt index = 0; + + // Try controllers until found a good controller or out of list + while ((error != KErrNone) && + (index < iControllerInfos->Count())) + { + // Open the controller + error = iController.Open((*iControllerInfos)[ index ]->Uid(), + aPrioritySettings, ETrue); + + // If the controller was opened without error, start receiving events from it. + if (!error) + { + iEventMonitor->Start(); + + // Add the data source to the controller. + error = iController.AddDataSource(aSourceUid, aSourceData); + } + + // Add the data sink + if (!error) + { + error = iController.AddDataSink(aSinkUid, aSinkData); + } + + // If an error occurred in any of the above, close the controller. + if (error) + { + iEventMonitor->Cancel(); + iController.Close(); + } + + index++; + } + + return error; +} + +TBool CMMAMMFPlayerBase::IsFilePlayer() +{ + if (iFileName != NULL) + { + return ETrue; + } + return EFalse; +} + +void CMMAMMFPlayerBase::StartL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StartL +"); + iMediaTime = KTimeUnknown; + User::LeaveIfError(iController.Play()); + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StartL after iController.Play() "); + // inform java side + ChangeState(EStarted); + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StartL after ChangeState "); + PostLongEvent(CMMAPlayerEvent::EStarted, iStartedEventTime); + PostActionCompletedStart(); + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StartL after PostLongEvent "); + +// PostActionCompleted(KErrNone); // java start return + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StartL after PostActionCompleted "); +} + +void CMMAMMFPlayerBase::StopL(TBool aPostEvent) +{ + if (iState == EStarted) + { + TInt64 time; + GetMediaTime(&time); + iStartedEventTime = time; + + TInt err = KErrNone; + // AAC controller does not support multiple + // calls to pause but leave with KErrNotReady. + // That error is dismissed as player should + // be paused already in that case. + if (time == 0) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StopL: Position is zero, stopping"); + // Normally pause would be called, but if + // current time is zero, Stop is called instead. + // This is done because video playback breaks + // if pause is called between events + // KMMFEventCategoryVideoLoadingStarted and + // KMMFEventCategoryVideoLoadingCompleted + // (no wurther events are delivered altough + // playback continues fine). + // However calling Stop is tolerated in that + // situation. + err = iController.Stop(); + if (err == KErrNone) + { + err = iController.Prime(); + } + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::StopL: Position not zero, pausing"); + err = iController.Pause(); + } + + if ((err != KErrNone) && (err != KErrNotReady)) + { + ELOG1( EJavaMMAPI, "CMMAMMFPlayerBase::StopL: pause/stop failed %d, leaving", err); + User::Leave(err); + } + + if (aPostEvent) + { + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + // go back to prefetched state + ChangeState(EPrefetched); + } +} + + +void CMMAMMFPlayerBase::DeallocateL() +{ + if (iState == EPrefetched) + { + // release all resources + if (iEventMonitor) + { + iEventMonitor->Cancel(); + } + + // Change state first to enable AMMS to delete Effect API classes + ChangeState(ERealized); + iController.Stop(); + ResetSourceStreams(); + } +} + + +EXPORT_C void CMMAMMFPlayerBase::GetDuration(TInt64* aDuration) +{ + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetDuration "); + if (iDuration == KTimeUnknown) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetDuration Time unknown "); + TTimeIntervalMicroSeconds duration; + TInt err = iController.GetDuration(duration); + if (!err) + { + iDuration = duration.Int64(); + } + } + *aDuration = iDuration; + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetDuration - "); +} + +void CMMAMMFPlayerBase::SetMediaTimeL(TInt64* aTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::SetMediaTimeL"); + + // Negative values are not checked here + // because it's done already in Java side. + + // Get clip duration + TTimeIntervalMicroSeconds duration; + User::LeaveIfError(iController.GetDuration(duration)); + LOG1( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::SetMediaTimeL iController.GetDuration=%d", duration.Int64()); + + TTimeIntervalMicroSeconds position; + + // If the desired media time is beyond the duration, + // the time is set to the end of the media. + if (*aTime > duration.Int64()) + { + position = duration; + } + else + { + position = *aTime; + } + + TBool paused = EFalse; + TInt err = KErrNone; + + if (iState == EStarted) + { + paused = ETrue; + User::LeaveIfError(err = iController.Pause()); + ELOG1( EJavaMMAPI, "CMMAMMFPlayerBase::SetMediaTimeL after iController.Pause = %d", err); + } + + if (err == KErrNone) + { + // The controller must be in the PRIMED or PLAYING state + User::LeaveIfError(err = iController.SetPosition(position)); + ELOG1( EJavaMMAPI, "CMMAMMFPlayerBase::SetMediaTimeL iController.SetPosition() = %d", err); + } + + // Reset cached media time, because actual set position may be + // something else than aTime. + iMediaTime = KTimeUnknown; + + // Inform about the position change to the StateListeners + ChangeState(iState); + + // Get the actual media time + GetMediaTime(aTime); + + iStartedEventTime = iMediaTime; + + if (err == KErrNone) + { + if (paused == (TBool)ETrue) + { + User::LeaveIfError(err = iController.Play()); + ELOG1( EJavaMMAPI, "CMMAMMFPlayerBase::SetMediaTimeL iController.Play() = %d", err); + } + } + + if (err != KErrNone) + { + User::Leave(err); + } +} + +void CMMAMMFPlayerBase::GetMediaTime(TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime +"); + TTimeIntervalMicroSeconds position(0); + + if (iMediaTime == KTimeUnknown || iState == EStarted) + { + // The controller must be in the PRIMED or PLAYING state + TInt error(iController.GetPosition(position)); + + if (error == KErrNone) + { + TInt64 newTime = position.Int64(); + LOG1( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime iController.GetPosition : %d", newTime); + + // Sanity check for media time going backwards or beyond the + // duration. + // Some native controls may return zero media time for + // a few moments just before playback will complete. + if (newTime < iMediaTime || + (iDuration > 0 && newTime > iDuration)) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime.GetDuration "); + GetDuration(&iMediaTime); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime.else "); + // set return value + iMediaTime = newTime; + } + } + else + { + LOG1( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime: error=%d, returning TIME_UNKNOWN", error); + // cannot get media time + iMediaTime = KTimeUnknown; + } + } + *aMediaTime = iMediaTime; + LOG1( EJavaMMAPI, EInfo, "CMMAMMFPlayerBase::GetMediaTime - %d", *aMediaTime); +} + +void CMMAMMFPlayerBase::CloseL() +{ + CMMAPlayer::CloseL(); + if (iEventMonitor) + { + iEventMonitor->Cancel(); + } + // First delete the control and then close the controller + // Added after AudioOutputControl + iController.Stop(); + delete iEventMonitor; + iEventMonitor = NULL; +} + +void CMMAMMFPlayerBase::HandleEvent(const TMMFEvent& /*aEvent*/) +{ + // empty implementation +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmammfplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmammfplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,292 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating MMF-based players. +* +*/ + + +// INCLUDE FILES +#include +#include + +#ifndef RD_JAVA_OMA_DRM_V2 +#include +#endif // RD_JAVA_OMA_DRM_V2 + +#include "cmmammfplayerfactory.h" +#include "cmmammfresolver.h" + +// CONSTANTS +// Granularity used to create initial arrays. +const TInt KGranularity = 8; +_LIT(KContentTypePacketSrcNotIncluded, "application/x-ext-packetsrc"); + +EXPORT_C CMMAMMFPlayerFactory::CMMAMMFPlayerFactory() +{ +} + +EXPORT_C CMMAMMFPlayerFactory::~CMMAMMFPlayerFactory() +{ +} + +CMMAPlayer* CMMAMMFPlayerFactory::CreatePlayerL(const TDesC& aContentType) +{ + return CreatePlayerL(aContentType, NULL); +} + +CMMAPlayer* CMMAMMFPlayerFactory::CreatePlayerL(const TDesC& aContentType, + const TDesC* aFileName) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL content type = %S", + aContentType.Ptr()); + CMMFFormatSelectionParameters* fSelect = + CMMFFormatSelectionParameters::NewLC(); + + // MMF needs 8bit data + HBufC8* contentType = HBufC8::NewLC(aContentType.Length()); + contentType->Des().Copy(aContentType); + + // Match to mime/content type + fSelect->SetMatchToMimeTypeL(*contentType); + + CMMAPlayer* player = CreatePlayerL(fSelect, aFileName); + + CleanupStack::PopAndDestroy(contentType); + CleanupStack::PopAndDestroy(fSelect); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL content type ok"); + return player; +} + +CMMAPlayer* CMMAMMFPlayerFactory::CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC&) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL aMiddlePart = %S", + aMiddlePart.Ptr()); + CMMFFormatSelectionParameters* fSelect = + CMMFFormatSelectionParameters::NewLC(); + + // Match to file name, using only middle part of the locator + fSelect->SetMatchToFileNameL(aMiddlePart); + + CMMAPlayer* player = NULL; + if (aProtocol == KMMAFileProtocol) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMMFPlayerFactory::CreatePlayerL creating file player"); + player = CreatePlayerL(fSelect, &aMiddlePart); + +#ifndef RD_JAVA_OMA_DRM_V2 + // if opening is failed, it might be DRM file, trying it + if (!player) + { + player = TryOpenDRMFileL(aMiddlePart); + } +#endif // RD_JAVA_OMA_DRM_V2 + + } + else + { + player = CreatePlayerL(fSelect, NULL); + } + + CleanupStack::PopAndDestroy(fSelect); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL aMiddlePart ok"); + return player; +} + +#ifndef RD_JAVA_OMA_DRM_V2 +CMMAPlayer* CMMAMMFPlayerFactory::TryOpenDRMFileL(const TDesC& aFileName) +{ + // we are most likely going to play this file + ContentAccess::TIntent intent = ContentAccess::EPlay; + + CContent* contentObj = CContent::NewL(aFileName); + CleanupStack::PushL(contentObj); + CData* dataObj = contentObj->OpenContentL(intent); + CleanupStack::PushL(dataObj); + User::LeaveIfError(dataObj->EvaluateIntent(intent)); + TBuf8 mimeType; + CMMAPlayer* player = NULL; + if (dataObj->GetMimeTypeL(mimeType)) + { + // we use 16bit mimeType + HBufC* mimeTypeBuf = HBufC::NewLC(mimeType.Length()); + mimeTypeBuf->Des().Copy(mimeType); + player = CreatePlayerL(*mimeTypeBuf, &aFileName); + CleanupStack::PopAndDestroy(mimeTypeBuf); + } + CleanupStack::PopAndDestroy(2); //dataObj, contentObj + return player; +} +#endif // RD_JAVA_OMA_DRM_V2 + +CMMAPlayer* CMMAMMFPlayerFactory::CreatePlayerL(const TDesC8& aHeaderData) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL header data +"); + CMMFFormatSelectionParameters* fSelect = + CMMFFormatSelectionParameters::NewLC(); + + // Match to header data + fSelect->SetMatchToHeaderDataL(aHeaderData); + + CMMAPlayer* player = CreatePlayerL(fSelect); + + CleanupStack::PopAndDestroy(fSelect); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAMMFPlayerFactory::CreatePlayerL header data -"); + return player; +} + +void CMMAMMFPlayerFactory::GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray) +{ + // check that this is supported protocol + if (!IsSupportedProtocolL(aProtocol)) + { + return; + } + + CMMFFormatSelectionParameters* fSelect = + CMMFFormatSelectionParameters::NewLC(); + + CMMAMMFResolver* cSelect = + CMMAMMFResolver::NewLC(); + + PreparePluginSelectionParametersL(cSelect, fSelect); + + // Set the media ids + RArray mediaIds; + CleanupClosePushL(mediaIds); + MediaIdsL(mediaIds); + cSelect->SelectionParameters()->SetMediaIdsL(mediaIds, MediaIdMatchType()); + + cSelect->GetSupportedContentTypesL(aMimeTypeArray); + + // Content type application/x-ext-packetsrc must not be supported, + // thus it is removed from the list of supported content types + TInt position(0); + TInt err = aMimeTypeArray.Find(KContentTypePacketSrcNotIncluded, position); + if (err == KErrNone) + { + aMimeTypeArray.Delete(position); + aMimeTypeArray.Compress(); + } + + CleanupStack::PopAndDestroy(); // mediaIds + CleanupStack::PopAndDestroy(cSelect); + CleanupStack::PopAndDestroy(fSelect); +} + +EXPORT_C CMMAPlayer* CMMAMMFPlayerFactory::CreatePlayerL(CMMFFormatSelectionParameters* aFormatSelect, + const TDesC* aFileName) +{ + CMMAMMFResolver* cSelect = + CMMAMMFResolver::NewLC(); + cSelect->SetFileNameL(aFileName); + + PreparePluginSelectionParametersL(cSelect, + aFormatSelect); + + // Set the media ids + RArray mediaIds; + CleanupClosePushL(mediaIds); + MediaIdsL(mediaIds); + cSelect->SelectionParameters()->SetMediaIdsL( + mediaIds, MediaIdMatchType()); + + cSelect->ListImplementationsL(); + CMMAPlayer* player = NULL; + + // check that did we get any hits + if (cSelect->Implementations()->Count() > 0) + { + // Call actual factory to create player + player = CreatePlayerL(cSelect); + } + + CleanupStack::PopAndDestroy(); // mediaIds + CleanupStack::PopAndDestroy(cSelect); + return player; +} + +void CMMAMMFPlayerFactory::GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + // Check that this is supported content type + if (!IsSupportedContentTypeL(aContentType)) + { + return; + } + aProtocolArray.AppendL(KMMAHttpProtocol); + aProtocolArray.AppendL(KMMAHttpsProtocol); + aProtocolArray.AppendL(KMMAFileProtocol); +} + +TBool CMMAMMFPlayerFactory::IsSupportedProtocolL(const TDesC& aProtocol) +{ + // With null desc we are getting all + if (aProtocol == KNullDesC) + { + return ETrue; + } + CDesC16ArraySeg* protocols = new(ELeave) CDesC16ArraySeg(KGranularity); + CleanupStack::PushL(protocols); + GetSupportedProtocolsL(KNullDesC, *protocols); + TInt pos = KErrNotFound; + // Find returns 0 if there contentType is found + TBool retValue = (protocols->Find(aProtocol, pos) == 0); + CleanupStack::PopAndDestroy(protocols); + return retValue; +} + +TBool CMMAMMFPlayerFactory::IsSupportedContentTypeL(const TDesC& aContentType) +{ + // With null desc we are getting all + if (aContentType == KNullDesC) + { + return ETrue; + } + + // Content type application/x-ext-packetsrc + // must not be supported at the moment. + if (aContentType == KContentTypePacketSrcNotIncluded) + { + return EFalse; + } + + CDesC16ArraySeg* contentTypes = new(ELeave) CDesC16ArraySeg(KGranularity); + CleanupStack::PushL(contentTypes); + GetSupportedContentTypesL(KNullDesC, *contentTypes); + TInt pos = KErrNotFound; + // Find returns 0 if there contentType is found + TBool retValue = (contentTypes->Find(aContentType, pos) == 0); + CleanupStack::PopAndDestroy(contentTypes); + return retValue; +} + +EXPORT_C void CMMAMMFPlayerFactory::PreparePluginSelectionParametersL( + CMMAMMFResolver* aResolver, + CMMFFormatSelectionParameters* aFormatSelection) +{ + // Play type is default + aResolver->SetRequiredPlayFormatSupportL(*aFormatSelection); +} + + +CMMFPluginSelectionParameters::TMediaIdMatchType +CMMAMMFPlayerFactory::MediaIdMatchType() +{ + // We are now getting only Audio Controllers + return CMMFPluginSelectionParameters::EAllowOnlySuppliedMediaIds; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmammfratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmammfratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements generic RateControl functionality. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmammfratecontrol.h" + +namespace +{ +const TInt KErrorMessageSize = 32; +_LIT(KErrDefaultError, "Symbian OS Error: %d"); +} + +CMMAMMFRateControl* CMMAMMFRateControl::NewL(CMMAMMFPlayerBase* aPlayer) +{ + CMMAMMFRateControl* self = new(ELeave) CMMAMMFRateControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CMMAMMFRateControl::~CMMAMMFRateControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMMFRateControl::~CMMAMMFRateControl"); +} + +CMMAMMFRateControl::CMMAMMFRateControl(CMMAMMFPlayerBase* aPlayer) : + iPlayer(aPlayer), iCurrentRate(KMMADefaultRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMMFRateControl::CMMAMMFRateControl"); +} + +void CMMAMMFRateControl::ConstructL() +{ + iPlayer->AddStateListenerL(this); +} + +void CMMAMMFRateControl::StateChanged(TInt aState) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMMFRateControl::StateChanged"); + if (aState == CMMAPlayer::EStarted && iCurrentRate == KMMAMinRate) + { + RMMFController& controller = iPlayer->Controller(); + TInt err = controller.Pause(); + if ((err != KErrNone) && (err != KErrNotReady)) + { + ELOG1( EJavaMMAPI, "CMMAMMFRateControl::StateChanged: Pause error %d", err); + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + } + } +} + +TInt CMMAMMFRateControl::SetRateL(TInt aRate) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAMMFRateControl::SetRateL"); + RMMFController& controller = iPlayer->Controller(); + + TInt newRate; + if (aRate <= KMMAMinRate) + { + newRate = KMMAMinRate; + } + else + { + newRate = KMMADefaultRate; + } + + if ((iPlayer->State() == CMMAPlayer::EStarted) && + (newRate != iCurrentRate)) + { + if (newRate == KMMAMinRate) + { + TInt err = controller.Pause(); + if ((err != KErrNone) && (err != KErrNotReady)) + { + User::Leave(err); + } + } + else + { + User::LeaveIfError(controller.Play()); + } + } + iCurrentRate = newRate; + return iCurrentRate; +} + +TInt CMMAMMFRateControl::RateL() +{ + return iCurrentRate; +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmammfresolver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmammfresolver.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,395 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing sounds +* +*/ + + +// INCLUDE FILES +#include + + +#include "cmmammfresolver.h" +#include "apgcli.h" +#include "apmrec.h" + + +#include "hxmetadatautil.h" +_LIT8(KMimetypeRM, "audio/x-pn-realaudio"); +_LIT(KRVMimeType1, "video/x-pn-realvideo"); +_LIT(KRVMimeType2, "video/x-realvideo"); +_LIT(KRVMimeType3, "video/vnd.rn-realvideo"); + + +// CONSTANTS + +CMMAMMFResolver* CMMAMMFResolver::NewLC() +{ + CMMAMMFResolver* self = new(ELeave)CMMAMMFResolver(); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +void CMMAMMFResolver::ListImplementationsL() +{ + iControllerSelection->ListImplementationsL(*iImplementations); + if (iImplementations->Count() > 0) + { + ResolveContentTypeL(); + } +} + +RMMFControllerImplInfoArray* CMMAMMFResolver::Implementations() +{ + // ImplementationsOwnership method must not be called before this + __ASSERT_DEBUG(iImplementations, User::Invariant()); + return iImplementations; +} + +RMMFControllerImplInfoArray* CMMAMMFResolver::ImplementationsOwnership() +{ + // ImplementationsOwnership method must not be called many times + __ASSERT_DEBUG(iImplementations, User::Invariant()); + + RMMFControllerImplInfoArray* implementations = iImplementations; + iImplementations = NULL; // ownership is transferred + return implementations; +} + +HBufC* CMMAMMFResolver::ContentTypeOwnership() +{ + HBufC* ct = iContentType; + iContentType = NULL; + return ct; +} + +HBufC* CMMAMMFResolver::ContentType() +{ + return iContentType; +} + +void CMMAMMFResolver::SetFileNameL(const TDesC* aFileName) +{ + HBufC* fn = NULL; + if (aFileName) + { + fn = aFileName->AllocL(); + } + delete iFileName; + iFileName = fn; +} + +HBufC* CMMAMMFResolver::FileNameOwnership() +{ + HBufC* fn = iFileName; + iFileName = NULL; + return fn; +} + +void CMMAMMFResolver::ResolveContentTypeL() +{ + LOG( EJavaMMAPI, EInfo, "+ CMMAMMFResolver::ResolveContentTypeL()"); + CMMFFormatSelectionParameters* fSelect = iRequiredPlayFormatSupport; + if (!fSelect) + { + fSelect = iRequiredRecordFormatSupport; + } + // if there is no play or record formats this object is not + // initialized correctly. + __ASSERT_DEBUG(fSelect, User::Invariant()); + + CMMFFormatSelectionParameters::TMatchDataType type = + fSelect->MatchDataType(); + + // if there is no implementation this method must not be called. + __ASSERT_DEBUG(iImplementations->Count() > 0, User::Invariant()); + const RMMFFormatImplInfoArray* formats = + Formats((*iImplementations)[ 0 ]); + + HBufC8* contentType = NULL; + TInt formatsCount = formats->Count(); + + if (type == CMMFFormatSelectionParameters::EMatchMimeType) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - EMatchMimeType"); + // The match was based on a mime type. + contentType = fSelect->MatchData().AllocLC(); + } + else if (type == CMMFFormatSelectionParameters::EMatchFileExtension) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - EMatchFileExtension"); + // The match was based on a file extension. + RApaLsSession ls; + TInt error; + error = ls.Connect(); + TDataRecognitionResult result; + error = ls.RecognizeData(*iFileName, KNullDesC8, result); + ls.Close(); + + if (iFileName && (iFileName->Right(3).Compare(KRaFileExtension()) == 0)) + { + contentType = KMimetypeRM().AllocLC(); + } + else if (iFileName && (iFileName->Right(3).Compare(KRmFileExtension()) == 0) && + !(IsRealVideoTypeL(*iFileName))) + { + contentType = KMimetypeRM().AllocLC(); + } + else if (!error && (result.iConfidence >= CApaDataRecognizerType::EProbable)) + { + LOG1( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - Confidence : %d", result.iConfidence); + contentType = result.iDataType.Des8().AllocLC(); + } + + + else + { + // The probability is less, hence matching is done based on legacy style + for (TInt format = 0; (format < formatsCount) && + !contentType; format++) + { + const CMMFFormatImplementationInformation* info = (*formats)[ format ]; + if (info->SupportsFileExtension(fSelect->MatchData())) + { + if (info->SupportedMimeTypes().Count() > 0) + { + contentType = info->SupportedMimeTypes()[ 0 ].AllocLC(); + } + } + } + } + } + else if (type == CMMFFormatSelectionParameters::EMatchHeaderData) + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - EMatchHeaderData"); + // The match was on a header data. + RApaLsSession ls; + TInt error; + error = ls.Connect(); + TDataRecognitionResult result; + error = ls.RecognizeData(KNullDesC, fSelect->MatchData() , result); + ls.Close(); + if (!error && (result.iConfidence >= CApaDataRecognizerType::EProbable)) + { + contentType = result.iDataType.Des8().AllocLC(); + } + else + { + // The probability is less, hence matching is done based on legacy style + for (TInt format = 0; (format < formatsCount) && + !contentType; format++) + { + CMMFFormatImplementationInformation* info = (*formats)[ format ]; + if (info->SupportsHeaderDataL(fSelect->MatchData())) + { + if (info->SupportedMimeTypes().Count() > 0) + { + contentType = info->SupportedMimeTypes()[ 0 ].AllocLC(); + } + } + } + } + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - KErrNotSupported"); + // EMatchAny is not supported + User::Leave(KErrNotSupported); + } + + // iContentType remains NULL if content type was not found. + if (contentType) + { + LOG1( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - contentType : %s", contentType->Des().PtrZ()); + + HBufC* ct = HBufC::NewL(contentType->Length()); + (ct->Des()).Copy(*contentType); + CleanupStack::PopAndDestroy(contentType); + delete iContentType; + iContentType = ct; + } + else + { + //This situation should never occur + LOG( EJavaMMAPI, EInfo, "CMMAMMFResolver::ResolveContentTypeL - contentType = NULL"); + User::Leave(KErrUnknown); + } + LOG( EJavaMMAPI, EInfo, "- CMMAMMFResolver::ResolveContentTypeL()"); +} + + +TBool CMMAMMFResolver::IsRealVideoTypeL(const TDesC& aFileName) +{ + TBool result = EFalse; + + CHXMetaDataUtility *putil; + putil = CHXMetaDataUtility::NewL(); + CleanupStack::PushL(putil); + TRAPD(err, putil->OpenFileL(aFileName)); + ELOG1( EJavaMMAPI, "MMA:CMMAMMFResolver::IsRealVideoTypeL, err = %d", err); + + if (err != KErrNone) + { + CleanupStack::Pop(putil); + putil->ResetL(); + delete putil; + return EFalse; + } + + TUint count = 0; + putil->GetMetaDataCount(count); + + TUint i; + HXMetaDataKeys::EHXMetaDataId id; + + for (i = 0; i < count; i++) + { + HBufC* pDes = NULL; + + putil->GetMetaDataAt(i, id, pDes); + + if (id == HXMetaDataKeys::EHXMimeType) + { + if (IsRealMimeTypeSupported(*pDes)) + { + result = ETrue; + } + } + } + + CleanupStack::Pop(putil); + + putil->ResetL(); + delete putil; + + return result; +} + + +TBool CMMAMMFResolver::IsRealMimeTypeSupported(const TDesC& aMimeType) +{ + TBool match = EFalse; + + if (!aMimeType.Compare(KRVMimeType1())) + { + match = ETrue; + return match; + } + if (!aMimeType.Compare(KRVMimeType2())) + { + match = ETrue; + return match; + } + if (!aMimeType.Compare(KRVMimeType3())) + { + match = ETrue; + return match; + } + + return match; +} + + +void CMMAMMFResolver::GetSupportedContentTypesL(CDesC16Array& aMimeTypeArray) +{ + iControllerSelection->ListImplementationsL(*iImplementations); + + TInt impCount = iImplementations->Count(); + for (TInt i = 0; i < impCount; i++) + { + const RMMFFormatImplInfoArray* formats = Formats((*iImplementations)[ i ]); + TInt formatsCount(formats->Count()); + for (TInt format = 0; format < formatsCount; format++) + { + const CMMFFormatImplementationInformation* info = (*formats)[ format ]; + const CDesC8Array& supportedMimes = info->SupportedMimeTypes(); + TInt mimeCount = supportedMimes.Count(); + for (TInt mime = 0; mime < mimeCount; mime++) + { + // must convert from 8 bits to 16 bits + HBufC* tmpBuf = HBufC::NewLC(supportedMimes[ mime ].Length()); + tmpBuf->Des().Copy(supportedMimes[ mime ]); + aMimeTypeArray.AppendL(*tmpBuf); + CleanupStack::PopAndDestroy(tmpBuf); + } + } + } +} + + +void CMMAMMFResolver::SetRequiredPlayFormatSupportL( + CMMFFormatSelectionParameters& aRequiredSupport) +{ + iControllerSelection->SetRequiredPlayFormatSupportL(aRequiredSupport); + iRequiredPlayFormatSupport = &aRequiredSupport; +} + +void CMMAMMFResolver::SetRequiredRecordFormatSupportL( + CMMFFormatSelectionParameters& aRequiredSupport) +{ + iControllerSelection->SetRequiredRecordFormatSupportL(aRequiredSupport); + iRequiredRecordFormatSupport = &aRequiredSupport; +} + +const RMMFFormatImplInfoArray* CMMAMMFResolver::Formats(CMMFControllerImplementationInformation* aImplementation) +{ + const RMMFFormatImplInfoArray* formats = NULL; + if (iRequiredPlayFormatSupport) + { + formats = &(aImplementation->PlayFormats()); + } + else + { + // if there is no play or record formats this object is not + // initialized correctly. + __ASSERT_DEBUG(iRequiredRecordFormatSupport, User::Invariant()); + + formats = &(aImplementation->RecordFormats()); + } + return formats; +} + +CMMFControllerPluginSelectionParameters* +CMMAMMFResolver::SelectionParameters() +{ + return iControllerSelection; +} + +CMMAMMFResolver::~CMMAMMFResolver() +{ + if (iImplementations) + { + iImplementations->ResetAndDestroy(); + } + delete iImplementations; + delete iContentType; + delete iControllerSelection; + delete iFileName; +} + + +CMMAMMFResolver::CMMAMMFResolver() +{ +} + + +void CMMAMMFResolver::ConstructL() +{ + iImplementations = new(ELeave)RMMFControllerImplInfoArray(); + iControllerSelection = CMMFControllerPluginSelectionParameters::NewL(); +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaoutputstream.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaoutputstream.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,221 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class to handle OutputStream operations. +* +*/ + +#include + +#include +#include "cmmaoutputstream.h" +#include "mmmaeventposter.h" +#include "cmmaoutputstreamevent.h" + +// CONSTANTS +const TInt KMMACommit = -10000; // indicates native started commit + +CMMAOutputStream* CMMAOutputStream::NewL(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter + ) +{ + CMMAOutputStream* self = CMMAOutputStream::NewLC(aJNIEnv, + aEventPoster, + aJavaOutputStreamWriter + ); + CleanupStack::Pop(); + return self; +} + + +CMMAOutputStream* CMMAOutputStream::NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter + ) +{ + CMMAOutputStream* self = new(ELeave) CMMAOutputStream(aEventPoster); + CleanupStack::PushL(self); + self->ConstructL(aJNIEnv, aJavaOutputStreamWriter); + return self; +} + + +void CMMAOutputStream::CreateL(CMMAOutputStream** aOutputStream, + MMAFunctionServer* aEventServer, + JNIEnv* aJniEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaOutputStreamWriter) +{ + + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJniEnv = aEventServer->getValidJniEnv(); + + *aOutputStream = NewL(aJniEnv, aEventPoster, aJavaOutputStreamWriter); +} + + +CMMAOutputStream::~CMMAOutputStream() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAOutputStream::~"); + + // If write event is in the event server, it cannot be deleted. + // Thus set the event to be deleted when event dispatch is called. + if (iWriteEvent && + iWriteEvent->State() == CMMAOutputStreamEvent::EMMAEventActive) + { + iWriteEvent->SetState(CMMAOutputStreamEvent::EMMADeleteEvent); + } + else + { + delete iWriteEvent; + } + + delete iData; + LOG( EJavaMMAPI, EInfo, "MMA::CMMAOutputStream::~ OK"); +} + + +// Default constructor +CMMAOutputStream::CMMAOutputStream(MMMAEventPoster* aEventPoster) + : iEventSource(aEventPoster), + iPtr(NULL, 0) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAOutputStream constructed"); +} + + +void CMMAOutputStream::ConstructL(JNIEnv* aJNIEnv, + jobject aJavaOutputStreamWriter) +{ + LOG( EJavaMMAPI, EInfo, "CMMAOutputStream::ConstructL()"); + + // void write( int aLength, int aStatus ) method in OutputStreamWriter + jmethodID classMethodID = + aJNIEnv->GetMethodID( + aJNIEnv->GetObjectClass(aJavaOutputStreamWriter), + "write", + "(II)V"); + if (!classMethodID) + { + LOG( EJavaMMAPI, EInfo, "CMMAOutputStream::ConstructL: Cannot find java method"); + User::Panic(_L("Java method write(II)V not found"), KErrGeneral); + } + + iWriteEvent = new(ELeave) CMMAOutputStreamEvent(classMethodID, + aJavaOutputStreamWriter); +} + +void CMMAOutputStream::ReadDataL(TUint8* aOutputData, + TInt* aBufferSize, + TInt* aReadStatus) +{ + if (!iData) + { + User::Leave(KErrNotReady); + } + + // Status code to be returned + TInt status = KErrNone; + + TPtr8 buffer(aOutputData, *aBufferSize); + LOG1( EJavaMMAPI, EInfo, " MMA::CMMAOutputStream::ReadDataL SIZE BEFORE READL %d", buffer.Length()); + LOG1( EJavaMMAPI, EInfo, " MMA::CMMAOutputStream::ReadDataL BYTES AVAILABLE %d", iPtr.Length()); + + // Bytes available in native buffer + TInt bytesAvailable = iPtr.Length(); + + // Maximum size that can be written to Java buffer + TInt outputMaxLength = buffer.MaxLength(); + + // Length that can be written + TInt writeLength = 0; + + if (outputMaxLength < bytesAvailable) + { + // Not all bytes can be written Java buffer + writeLength = outputMaxLength; + + // Java need to read more data + status = EMoreData; + } + else + { + // All bytes can be written to Java buffer + writeLength = bytesAvailable; + + // All data is copied + status = ECompleted; + } + + // Copy maximum number of bytes to Java buffer + buffer.Copy(iPtr.Left(writeLength)); + *aBufferSize = buffer.Length(); + + // Move pointer to next read position. + iPtr = iPtr.Mid(writeLength); + + LOG1( EJavaMMAPI, EInfo, " MMA::CMMAOutputStream::ReadDataL SIZE AFTER READL %d", buffer.Length()); + LOG1( EJavaMMAPI, EInfo, " MMA::CMMAOutputStream::ReadDataL RETURN %d", status); + LOG1( EJavaMMAPI, EInfo, " MMA::CMMAOutputStream::ReadDataL dataLeft %d", iPtr.Length()); + + if (iPtr.Length() == 0) + { + // All data is read and buffer is not needed anymore. + delete iData; + iData = NULL; + } + *aReadStatus = status; +} + +void CMMAOutputStream::WriteL(const TDesC8& aData) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAOutputStream::WriteL data size = %d", aData.Size()); + if (iData) + { + // Previous data was not readed from the stream. + User::Leave(KErrNotReady); + } + + if (aData.Length() > 0) + { + // Take a copy of new data. + HBufC8* data = aData.AllocL(); + delete iData; + iData = data; + iPtr.Set(iData->Des()); + + // Set java event + LOG1( EJavaMMAPI, EInfo, "CMMAOutputStream::WriteL: available data: %d", iData->Length()); + iWriteEvent->SetLength(iData->Length()); + iWriteEvent->SetStatus(EMoreData); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMAOutputStream::WriteL Zero length data"); + iWriteEvent->SetLength(0); + iWriteEvent->SetStatus(ECompleted); + } + iEventSource->PostEvent(iWriteEvent, CMMAEvent::ENotifyPriority); +} + +void CMMAOutputStream::Commit() +{ + iWriteEvent->SetLength(0); + iWriteEvent->SetStatus(KMMACommit); + iEventSource->PostEvent(iWriteEvent, CMMAEvent::ENotifyPriority); +} + +// END OF FILE + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaoutputstreamevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaoutputstreamevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#include + +#include "cmmaoutputstreamevent.h" + + +CMMAOutputStreamEvent::CMMAOutputStreamEvent(jmethodID aHandleEventMethod, + jobject aNotifyObject) + : CMMAEvent(EReusableEvent), + iHandleEventMethod(aHandleEventMethod), + iListenerObject(aNotifyObject) +{ + iState = EMMAEventNotActive; +} + +void CMMAOutputStreamEvent::SetLength(TInt aLength) +{ + iLength = aLength; + iState = EMMAEventActive; +} + + +void CMMAOutputStreamEvent::SetStatus(TInt aStatus) +{ + iStatus = aStatus; + iState = EMMAEventActive; +} + +void CMMAOutputStreamEvent::SetState(CMMAOutputStreamEvent::TMMAOutputStreamState aState) +{ + iState = aState; +} + +CMMAOutputStreamEvent::TMMAOutputStreamState CMMAOutputStreamEvent::State() +{ + return iState; +} + +void CMMAOutputStreamEvent::Dispatch(JNIEnv& aJni) +{ + LOG2( EJavaMMAPI, EInfo, "CMMAOutputStreamEvent::Dispatch, len=%d status=%d-", + iLength, iStatus); + + if (iState == EMMAEventActive) + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iLength, + iStatus); + iState = EMMAEventNotActive; + } + else if (iState == EMMADeleteEvent) + { + // This is done because some + // event may still exist in the event server when + // the sender has been deleted. + + delete this; + } + // else event is not active +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,496 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is base class for all players. +* +*/ + +// INCLUDE FILES +#include + +#include + +#include "cmmaplayer.h" +#include "mmafunctionserver.h" +#include "cmmadurationupdater.h" +#include "cmmavolumecontrol.h" + +// CONSTANTS +_LIT(KPanicOutOfMem, "out of memory"); + +#ifdef _DEBUG // Needed only in ASSER_DEBUG statements. +_LIT(KPanicMethod, "method not found"); +#endif + +CMMAPlayer::~CMMAPlayer() +{ + LOG( EJavaMMAPI, EInfo, "CMMAPlayer::~CMMAPlayer()"); + + iSourceStreams.ResetAndDestroy(); + if (iControls.Count() > 0) + iControls.ResetAndDestroy(); + iStateListeners.Reset(); + delete iActionCompletedEvent; + delete iOOMErrorEvent; + delete iDurationUpdater; + delete iContentType; +} + + +CMMAPlayer::CMMAPlayer(): + iRepeatNumberOfTimes(0), + iRepeatForever(EFalse), + iRepeatCount(0), + iDuration(KTimeUnknown), + iState(EUnrealized) +{ +} + + +void CMMAPlayer::ConstructL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ConstructL + "); + iDurationUpdater = CMMADurationUpdater::NewL(*this); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ConstructL - "); +} + + +void CMMAPlayer::StaticAddSourceStreamL(JNIEnv* aJniEnv, + CMMAPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aReader, + CMMASourceStream** aSourceStream) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticAddSourceStreamL +"); + + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJniEnv = aEventSource-> getValidJniEnv(); + + *aSourceStream = aPlayer->AddSourceStreamL(aJniEnv, + aEventSource, + aReader); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticAddSourceStreamL -"); +} + + + +void CMMAPlayer::StaticSetPlayerListenerObjectL(CMMAPlayer* aPlayer, + MMAFunctionServer* aEventsource, + jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aPoster) +{ + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticSetPlayerListenerObjectL +"); + + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJni = aEventsource-> getValidJniEnv(); + + aPlayer->SetPlayerListenerObjectL(aListenerObject, aJni, aPoster); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticSetPlayerListenerObjectL -"); +} + + +void CMMAPlayer::StaticInitPlayerL(CMMAPlayer* aPlayer, + MMAFunctionServer* aEventsource, + jobject aPlayerObject, + JNIEnv* aJni) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticInitPlayerL +"); + + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJni = aEventsource-> getValidJniEnv(); + + jmethodID actionCompletedMethod = aJni->GetMethodID( + aJni->GetObjectClass(aPlayerObject), + "actionCompleted", + "(I)V"); + + jmethodID actionCompletedFileMethod = aJni->GetMethodID( + aJni->GetObjectClass(aPlayerObject), + "actionCompletedFile", + "()V"); + + jmethodID actionCompletedStartMethod = aJni->GetMethodID( + aJni->GetObjectClass(aPlayerObject), + "actionCompletedStart", + "()V"); + + // Sanity Check, something is really wrong if methods cannot be found + __ASSERT_DEBUG(actionCompletedMethod, + User::Panic(KPanicMethod, KErrGeneral)); + + aPlayer->iActionCompletedEvent = new(ELeave) CMMAEvent( + aPlayerObject, + actionCompletedMethod, + CMMAEvent::EReusableEvent); + + aPlayer->iActionCompletedFileEvent = new(ELeave) CMMAEvent( + aPlayerObject, + actionCompletedFileMethod, + CMMAEvent::EReusableEvent); + + aPlayer->iActionCompletedStartEvent = new(ELeave) CMMAEvent( + aPlayerObject, + actionCompletedStartMethod, + CMMAEvent::EReusableEvent); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticInitPlayerL -"); +} + +CMMAControl* CMMAPlayer::StaticControl(CMMAPlayer* aPlayer, TInt aIndex) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::StaticControl +"); + return aPlayer->Control(aIndex); + +} + + +void CMMAPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::RealizeL +"); + ChangeState(ERealized); + +} + + +void CMMAPlayer::CloseL() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::CloseL "); + ChangeState(EClosed); + PostObjectEvent(CMMAPlayerEvent::EClosed, NULL); +} + + +void CMMAPlayer::GetDuration(TInt64* aDuration) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::GetDuration "); + *aDuration = iDuration; +} + + +void CMMAPlayer::SetMediaTimeL(TInt64* aTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::SetMediaTimeL "); + *aTime = KErrNotSupported; +} + +void CMMAPlayer::GetMediaTime(TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::GetMediaTime "); + *aMediaTime = KErrNotSupported; +} + + +EXPORT_C void CMMAPlayer::SetLoopCount(TInt aCount) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::SetLoopCount "); + iRepeatForever = (aCount == KJavaRepeatForever); + iRepeatNumberOfTimes = aCount; + iRepeatCount = 0; +} + +HBufC* CMMAPlayer::ContentType() const +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ContentType "); + return iContentType; +} + +void CMMAPlayer::SetPlayerListenerObjectL(jobject aListenerObject, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::SetPlayerListenerObjectL +"); + iListenerObject = aListenerObject; + iEventPoster = aEventPoster; + + jclass listenerClass = aJni->GetObjectClass(aListenerObject); + + iPostEvent = aJni->GetMethodID( + listenerClass, + "postEvent", + "(Ljava/lang/String;Ljava/lang/Object;)V"); + + iPostObjectEvent = aJni->GetMethodID(listenerClass, + "postObjectEvent", + "(ILjava/lang/Object;)V"); + + iPostLongEvent = aJni->GetMethodID(listenerClass, + "postLongEvent", + "(IJ)V"); + + iPostStringEvent = aJni->GetMethodID(listenerClass, + "postStringEvent", + "(ILjava/lang/String;)V"); + + iPostControlEvent = aJni->GetMethodID(listenerClass, + "postControlEvent", + "(ILjava/lang/String;)V"); + + + // Sanity Check, something is really wrong if methods cannot be found + __ASSERT_DEBUG(iPostEvent && + iPostObjectEvent && + iPostLongEvent && + iPostStringEvent && + iPostControlEvent, + User::Panic(KPanicMethod, KErrGeneral)); + + iOOMErrorEvent = new(ELeave) CMMAPlayerEvent(iListenerObject, + iPostStringEvent, + CMMAEvent::EReusableEvent); + iOOMErrorEvent->SetStringEventL(CMMAPlayerEvent::EError, + KPanicOutOfMem); + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::SetPlayerListenerObjectL -"); +} + + +EXPORT_C TInt CMMAPlayer::ControlCount() +{ + return iControls.Count(); +} + + +EXPORT_C CMMAControl* CMMAPlayer::Control(TInt aIndex) +{ + return iControls[ aIndex ]; +} + +void CMMAPlayer::RefreshControls() +{ + + for (TInt index = 0; index < iControls.Count(); index++) + { + CMMAControl* control = iControls[ index ]; + control->RefreshControl(); + } + +} + +EXPORT_C void CMMAPlayer::AddStateListenerL(MMMAPlayerStateListener* aListener) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::AddStateListenerL +"); + TInt err = iStateListeners.Append(aListener); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::AddStateListenerL - err = %d ",err); + User::LeaveIfError(err); + //User::LeaveIfError(iStateListeners.Append(aListener)); + +} + +EXPORT_C void CMMAPlayer::RemoveStateListener(MMMAPlayerStateListener* aListener) +{ + + TInt index = iStateListeners.Find(aListener); + + if (index != KErrNotFound) + { + iStateListeners.Remove(index); + } + +} + +const TDesC& CMMAPlayer::Type() +{ + // by default player has not the type + return KNullDesC; +} + +void CMMAPlayer::SetContentType(HBufC* aContentType) +{ + + delete iContentType; + iContentType = aContentType; + +} + +void CMMAPlayer::ResetSourceStreams() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ResetSourceStreams +"); + int sourceStreamsCount = iSourceStreams.Count(); + for (int i = 0; i < sourceStreamsCount; i++) + { + iSourceStreams[ i ]->ResetData(); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ResetSourceStreams -"); +} + +EXPORT_C void CMMAPlayer::AddControlL(CMMAControl* aControl) +{ + + User::LeaveIfError(iControls.Append(aControl)); + +} + +void CMMAPlayer::PostLongEvent(CMMAPlayerEvent::TEventType aEventType, + const TInt64& aLongEventData) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostLongEvent "); + if (!iListenerObject || !iEventPoster) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostLongEvent No listener"); + // return since player is not ready for posting any events and is not initialized + return; + } + + CMMAPlayerEvent* playerEvent = new CMMAPlayerEvent(iListenerObject, + iPostLongEvent); + if (!playerEvent) + { + // creation of player event failed, informing Java + iEventPoster->PostEvent(iOOMErrorEvent); + return; + } + playerEvent->SetLongEvent(aEventType, aLongEventData); + + // event poster takes ownership of event + iEventPoster->PostEvent(playerEvent); +} + + +EXPORT_C void CMMAPlayer::PostStringEvent(CMMAPlayerEvent::TEventType aEventType, + const TDesC& aStringEventData) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostStringEvent "); + if (!iListenerObject || !iEventPoster) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostStringEvent No listener"); + // return since player is not ready for posting any events and is not initialized + return; + } + + CMMAPlayerEvent* playerEvent = new CMMAPlayerEvent(iListenerObject, + iPostStringEvent); + if (!playerEvent) + { + // creation of player event failed, informing Java + iEventPoster->PostEvent(iOOMErrorEvent); + return; + } + + TRAPD(err, playerEvent->SetStringEventL(aEventType, aStringEventData)); + if (err != KErrNone) + { + // string setting failed, informing Java + iEventPoster->PostEvent(iOOMErrorEvent); + return; + } + + // event poster takes ownership of event + iEventPoster->PostEvent(playerEvent); +} + + +EXPORT_C void CMMAPlayer::PostObjectEvent(CMMAPlayerEvent::TEventType aEventType, + const jobject aEventData) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostObjectEvent "); + + if (!iListenerObject || !iEventPoster) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostObjectEvent No listener"); + // return since player is not ready for posting any events and is not initialized + return; + } + + CMMAPlayerEvent* playerEvent = new CMMAPlayerEvent(iListenerObject, + iPostObjectEvent); + + if (!playerEvent) + { + // creation of player event failed, informing Java + iEventPoster->PostEvent(iOOMErrorEvent); + return; + } + + TRAPD(err, playerEvent->SetObjectEventL(aEventType, aEventData)); + if (err != KErrNone) + { + // creation of player event failed, informing Java + iEventPoster->PostEvent(iOOMErrorEvent); + return; + } + + // event poster takes ownership of event + iEventPoster->PostEvent(playerEvent); +} + +EXPORT_C CMMASourceStream* CMMAPlayer::AddSourceStreamL(JNIEnv* aJNIEnv, + MMAFunctionServer* aEventSource, + jobject aReader) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::AddSourceStreamL "); + CMMASourceStream* sourceStream = CMMASourceStream::NewL(aJNIEnv, + aEventSource, + aReader, + this); + + CleanupStack::PushL(sourceStream); + User::LeaveIfError(iSourceStreams.Append(sourceStream)); + CleanupStack::Pop(); // sourceStream + return sourceStream; +} + + +void CMMAPlayer::PostActionCompleted(TInt aError) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostActionCompleted "); + iActionCompletedEvent->SetEventData(aError); + iEventPoster->PostEvent(iActionCompletedEvent, + CMMAEvent::ENotifyPriority); +} + +void CMMAPlayer::PostActionCompletedFile() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostActionCompleted "); + // iActionCompletedFileEvent->SetEventData(aError); + iEventPoster->PostEvent(iActionCompletedFileEvent, + CMMAEvent::ENotifyPriority); +} + + +void CMMAPlayer::PostActionCompletedStart() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::PostActionCompleted "); + iEventPoster->PostEvent(iActionCompletedStartEvent, + CMMAEvent::ENotifyPriority); +} + +void CMMAPlayer::ChangeState(TPlayerState aState) +{ + iState = aState; + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ChangeState - iStateListeners count is %d", iStateListeners.Count()); + for (TInt i(0); iStateChanged(aState); + } + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ChangeState - State changed to %d", iState); +} + +void CMMAPlayer::ReadCompletedL(TInt /*aStatus*/, const TDesC8& /*aData*/) +{ + // empty implementation + LOG( EJavaMMAPI, EInfo, "MMA::CMMAPlayer::ReadCompletedL "); +} +void CMMAPlayer:: DeleteControls() +{ + if (iControls.Count() > 0) + { + iControls.ResetAndDestroy(); + } +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaplayerevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaplayerevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaplayerevent.h" +#include "mmapiutils.h" +#include "s60commonutils.h" +using namespace java::util; + + +CMMAPlayerEvent::CMMAPlayerEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable): + CMMAEvent(aNotifyObject, aHandleEventMethod, aDisposable) +{ +} + +CMMAPlayerEvent::~CMMAPlayerEvent() +{ + //delete iStringEventType; + delete iStringEventData; +} + +void CMMAPlayerEvent::SetObjectEventL(TEventType aEventType, + const jobject aEventData) +{ + iEventType = aEventType; + iObjectEventData = aEventData; + iEventParams = EObject; +} + +void CMMAPlayerEvent::SetLongEvent(TEventType aEventType, + const TInt64& aEventData) +{ + iEventType = aEventType; + iLongEventData = aEventData; + iEventParams = ELong; +} + +void CMMAPlayerEvent::SetStringEventL(TEventType aEventType, + const TDesC& aEventData) +{ + // __ASSERT_DEBUG(iStringEventData == NULL, User::Invariant()); + iEventType = aEventType; + iStringEventData = aEventData.AllocL(); + iEventParams = EString; +} + +void CMMAPlayerEvent::Dispatch(JNIEnv& aJni) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAPlayerEvent::Dispatch type=%d", iEventType); + if (aJni.IsSameObject(iListenerObject, 0)) + { + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAPlayerEvent::Dispatch EVENT_NOT_VALID type=%d", iEventType); + return; + } + switch (iEventParams) + { + case ENormal: + { + jstring javaString = S60CommonUtils::NativeToJavaString(aJni, *iStringEventType); + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + javaString, + iObjectEventData); + break; + } + case ELong: + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventType, + iLongEventData); + break; + } + case EString: + { + jstring javaString = S60CommonUtils::NativeToJavaString(aJni, *iStringEventData); + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventType, + javaString); + break; + } + case EObject: + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventType, + iObjectEventData); + break; + } + default: + { + // cannot occur + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + } + +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaplayerproperties.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaplayerproperties.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,381 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for storing and parsing properties +* +*/ + + +// INCLUDE FILES +#include +#include "cmmaplayerproperties.h" + +const TInt KPropertyNameEndChar = '='; +const TInt KPropertyEndChar = '&'; +const TInt KDefaultGranularity = 8; + +CMMAPlayerProperties* CMMAPlayerProperties::NewL(const TDesC& aProperties, + MMMAParameterRule& aRule) +{ + CMMAPlayerProperties* props = new(ELeave) CMMAPlayerProperties(aProperties, aRule); + return props; +} + +CMMAPlayerProperties::~CMMAPlayerProperties() +{ +} + + +CMMAPlayerProperties::CMMAPlayerProperties(const TDesC& aProperties, MMMAParameterRule& aRule) : + iProperties(aProperties), + iRule(aRule) +{ +} + +TBool CMMAPlayerProperties::GetProperty(const TDesC& aKey, + TInt& aValue) const +{ + return iRule.FindProperty(aKey, aValue); +} + +TBool CMMAPlayerProperties::GetProperty(const TDesC& aKey, TPtrC& aValue) const +{ + return iRule.FindProperty(aKey, aValue); +} + +TBool CMMAPlayerProperties::Compare(const TDesC& aKey, const TDesC& aValue) const +{ + return iRule.Compare(aKey, aValue); +} + +TBool CMMAPlayerProperties::Compare(const TDesC& aKey, const TInt& aValue) const +{ + return iRule.Compare(aKey, aValue); +} + +// Parse property values: "key=value&key2=value2&..." +void CMMAPlayerProperties::ValidateL() const +{ + // Empty properties are valid + if (iProperties.Length() == 0) + { + return; + } + TInt pos = 0; + while (pos != KErrNotFound) + { + // Getting everything from 'pos' to end and finding '&' + TPtrC property = iProperties.Mid(pos); + TInt valueEndPos = property.Locate(KPropertyEndChar); + + if (valueEndPos != KErrNotFound) + { + // This is not last property, clipping remaining chars + property.Set(iProperties.Mid(pos, valueEndPos)); + } + + TInt keyEndPos = property.Locate(KPropertyNameEndChar); + // if we are getting KErrNotFound then properties is not valid + if (keyEndPos == KErrNotFound) + { + User::Leave(KErrArgument); + } + + // "key=value" + TPtrC propertyKey(property.Left(keyEndPos)); + TPtrC propertyValue(property.Mid(keyEndPos + 1)); + + // check is the pair valid, leave if not + // check also that this key was expected, leave if not + TPtrC tmp; + TInt tmpInt; + if (!iRule.ValidateAndStoreL(propertyKey, propertyValue) || + !(iRule.FindProperty(propertyKey, tmp) || + iRule.FindProperty(propertyKey, tmpInt))) + { + User::Leave(KErrArgument); + } + + // prepare for next token or mark end + if (valueEndPos != KErrNotFound) + { + pos += valueEndPos + 1; + } + else + { + pos = valueEndPos; + } + } +} + + +CMMAParameterRuleSet* CMMAParameterRuleSet::NewLC() +{ + CMMAParameterRuleSet* self = new(ELeave)CMMAParameterRuleSet(); + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + +CMMAParameterRuleSet::~CMMAParameterRuleSet() +{ + if (iRules) + { + iRules->Reset(); + delete iRules; + } +} + +CMMAParameterRuleSet::CMMAParameterRuleSet() +{ +} + +void CMMAParameterRuleSet::ConstructL() +{ + iRules = new(ELeave)CArrayPtrSeg< MMMAParameterRule >(KDefaultGranularity); +} + +#define LOOPUNTILRULE( endRule ) \ + TInt rules = iRules->Count(); \ + TInt i( 0 ); \ + while( ( i < rules ) && \ + endRule ) \ + { \ + i++; \ + } + +TBool CMMAParameterRuleSet::ValidateAndStoreL(const TDesC& aKey, const TDesC& aValue) +{ + LOOPUNTILRULE(iRules->At(i)->ValidateAndStoreL(aKey, aValue)); + // if loop has ended before end then some validation has failed. + return (i == rules); +} + +TBool CMMAParameterRuleSet::Compare(const TDesC& aKey, const TDesC& aValue) +{ + LOOPUNTILRULE(!iRules->At(i)->Compare(aKey, aValue)); + // if loop has ended before end then key-value pair has been found + return (i != rules); +} + +TBool CMMAParameterRuleSet::Compare(const TDesC& aKey, const TInt aValue) +{ + LOOPUNTILRULE(!iRules->At(i)->Compare(aKey, aValue)); + // if loop has ended before end then key-value pair has been found + return (i != rules); +} + +TBool CMMAParameterRuleSet::FindProperty(const TDesC& aKey, TPtrC& aValue) +{ + LOOPUNTILRULE(!iRules->At(i)->FindProperty(aKey, aValue)); + // if loop has ended before end then key has been found + return (i != rules); +} + +TBool CMMAParameterRuleSet::FindProperty(const TDesC& aKey, TInt& aValue) +{ + LOOPUNTILRULE(!iRules->At(i)->FindProperty(aKey, aValue)); + // if loop has ended before end then key has been found + return (i != rules); +} + +void CMMAParameterRuleSet::AppendRuleL(MMMAParameterRule* aRule) +{ + iRules->AppendL(aRule); +} + +TMMAParameterRuleBase::TMMAParameterRuleBase(const TDesC& aKey) : + iKey(aKey), + iAssigned(EFalse) +{} + +TBool TMMAParameterRuleBase::ValidateAndStoreL(const TDesC& aKey, const TDesC& aValue) +{ + if ((aKey.Length() == 0) || + (aValue.Length() == 0)) + { + // key or value length is zero, fail + User::Leave(KErrArgument); + } + + TBool isValid = ETrue; + // this is same key as in rule + if (iKey.Compare(aKey) == 0) + { + //if this key is already assigned then there is same key more than once + if (iAssigned) + { + User::Leave(KErrArgument); + } + isValid = ValidateValueL(aValue); + + // if it was valid we mark this key as assigned + if (isValid) + { + iAssigned = ETrue; + } + } + return isValid; +} + +TBool TMMAParameterRuleBase::Compare(const TDesC& /*aKey*/, const TDesC& /*aValue*/) +{ + // by default we do not found this key + return EFalse; +} + +TBool TMMAParameterRuleBase::Compare(const TDesC& /*aKey*/, const TInt /*aValue*/) +{ + // by default we do not found this key + return EFalse; +} + +TBool TMMAParameterRuleBase::FindProperty(const TDesC& /*aKey*/, TPtrC& /*aValue*/) +{ + // by default we do not found this key + return EFalse; +} + +TBool TMMAParameterRuleBase::FindProperty(const TDesC& /*aKey*/, TInt& /*aValue*/) +{ + // by default we do not found this key + return EFalse; +} + +TMMAParameterRuleInt::TMMAParameterRuleInt(const TDesC& aKey) : + TMMAParameterRuleBase(aKey), + iUpperLimit(KMaxTInt), + iLowerLimit(KMinTInt) +{} + +TMMAParameterRuleInt::TMMAParameterRuleInt(const TDesC& aKey, + const TInt aLowerLimit) : + TMMAParameterRuleBase(aKey), + iUpperLimit(KMaxTInt), + iLowerLimit(aLowerLimit) +{} + +TMMAParameterRuleInt::TMMAParameterRuleInt(const TDesC& aKey, + const TInt aLowerLimit, + const TInt aUpperLimit) : + TMMAParameterRuleBase(aKey), + iUpperLimit(aUpperLimit), + iLowerLimit(aLowerLimit) +{} + +TBool TMMAParameterRuleInt::ValidateValueL(const TDesC& aValue) +{ + TLex lex(aValue); + TInt valueInt = 0; + if ((lex.Val(valueInt) != KErrNone) || + !lex.Eos()) + { + User::Leave(KErrArgument); + } + if ((valueInt < iLowerLimit) || + (valueInt > iUpperLimit)) + { + // value is not valid + return EFalse; + } + else + { + // value is valid, store it + iValue = valueInt; + return ETrue; + } +} + +TBool TMMAParameterRuleInt::Compare(const TDesC& aKey, const TInt aValue) +{ + TBool match = EFalse; + if (iAssigned && + (iKey.Compare(aKey) == 0) && + (aValue == iValue)) + { + match = ETrue; + } + return match; +} + +TBool TMMAParameterRuleInt::FindProperty(const TDesC& aKey, TInt& aValue) +{ + TBool match = EFalse; + if (iAssigned && + iKey.Compare(aKey) == 0) + { + aValue = iValue; + match = ETrue; + } + return match; +} + +TMMAParameterRuleDes::TMMAParameterRuleDes(const TDesC& aKey) : + TMMAParameterRuleBase(aKey), + iValidValues(NULL), + iArraySize(0) +{} + +TMMAParameterRuleDes::TMMAParameterRuleDes(const TDesC& aKey, + const TMMAStaticStrArray* aValidValues, + const TInt aArraySize) : + TMMAParameterRuleBase(aKey), + iValidValues(aValidValues), + iArraySize(aArraySize) +{} + +TBool TMMAParameterRuleDes::ValidateValueL(const TDesC& aValue) +{ + TInt i = 0; + while ((i < iArraySize) && + aValue.Compare(iValidValues[i]()) != 0) + { + i++; + } + // if there is not valid values then we treat every value as valid + if (iValidValues && + (i == iArraySize)) + { + // there was no hit + return EFalse; + } + + // find match or every value is valid, storing + iValue.Set(aValue); + return ETrue; +} + +TBool TMMAParameterRuleDes::Compare(const TDesC& aKey, const TDesC& aValue) +{ + TBool match = EFalse; + if (iAssigned && + (iKey.Compare(aKey) == 0) && + (iValue.Compare(aValue) == 0)) + { + match = ETrue; + } + return match; +} + +TBool TMMAParameterRuleDes::FindProperty(const TDesC& aKey, TPtrC& aValue) +{ + TBool match = EFalse; + if (iAssigned && + iKey.Compare(aKey) == 0) + { + aValue.Set(iValue); + match = ETrue; + } + return match; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmaratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmaratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements generic RateControl functionality. +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmaratecontrol.h" + +CMMARateControl::CMMARateControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARateControl::CMMARateControl"); +} + +CMMARateControl::~CMMARateControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARateControl::~CMMARateControl"); +} + +const TDesC& CMMARateControl::ClassName() const +{ + return KMMARateControlName; +} + +TInt CMMARateControl::MaxRateL() +{ + return KMMADefaultRate; +} + +TInt CMMARateControl::MinRateL() +{ + return KMMAMinRate; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmarecordcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmarecordcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,298 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a RecordControl. +* +*/ + + +// INCLUDE FILES +#include +#include "cmmarecordcontrol.h" +#include "cmmaplayer.h" + + +_LIT(KControlName, "RecordControl"); + +CMMARecordControl::CMMARecordControl(CMMAPlayer* aPlayer): + iState(ERecordUninitialized), + iPlayer(aPlayer), + iStartTime(0) +{ +} + + +CMMARecordControl::~CMMARecordControl() +{ + iRecordPauseTimer.Cancel(); + iRecordPauseTimer.Close(); + + if (iPlayer) + { + iPlayer->RemoveStateListener(this); + } + + delete iOutputStream; + + iFile.Close(); + iFs.Delete(iFilename); + iFs.Close(); +} + +void CMMARecordControl::WaitForPauseL(const TInt64& aMediaTime) +{ + // reusing time variable + TInt64 time = iStartTime - aMediaTime + KMinRecordPauseInterval; + iStartTime = 0; + LOG1( EJavaMMAPI, EInfo, "CMMARecordControl::WaitForPauseL wait time = %d", (TInt)time); + // if time > 0, time between record and pause is smaller than + // KMinRecordPauseInterval and we have to wait. + if (time > 0) + { + TRequestStatus status; + iRecordPauseTimer.Cancel(); + iRecordPauseTimer.After(status, I64INT(time)); + User::WaitForRequest(status); + // Status ignored because recording must be stopped. + } +} + +void CMMARecordControl::ConstructL() +{ + User::LeaveIfError(iRecordPauseTimer.CreateLocal()); + + User::LeaveIfError(iFs.Connect()); + + // create temporary file for recording + User::LeaveIfError(iFile.Temp(iFs, + KMMARecordTempDirectory, + iFilename, + EFileRead | EFileWrite | EFileShareAny)); + + iPlayer->AddStateListenerL(this); +} + +void CMMARecordControl::StartRecordL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::StartRecordL+"); + + // Initialize needs to be done only once after setRecordLocation or + // setRecordStream and before commit or reset. Although startRecord can be + // called several times in the process, the initialization must happen + // only in the first call to startRecord + if (iState == ERecordUninitialized) + { + InitializeL(); + } + + iState = ERecordStandBy; + // calling next state if player is already started + NextStateL(iPlayer->State()); + + iPlayer->GetMediaTime(&iStartTime); + iPlayer->PostLongEvent(CMMAPlayerEvent::ERecordStarted, iStartTime); + + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::StartRecordL-"); +} + + +void CMMARecordControl::StopRecordL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::StopRecordL+"); + if (iState == ERecordRecording) + { + NextStateL(iPlayer->State()); + } + + iState = ERecordInitialized; + + // ask mediatime again for more accurate value + TInt64 time; + iPlayer->GetMediaTime(&time); + iPlayer->PostLongEvent(CMMAPlayerEvent::ERecordStopped, time); + + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::StopRecordL-"); +} + + +void CMMARecordControl::CommitL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::CommitL+"); + // reset the recorder if already initialized + if (iState > ERecordUninitialized) + { + DoResetL(); + } + else + { + // not even initialized yet, just inform java + iOutputStream->WriteL(KNullDesC8); + return; + } + iState = ERecordUninitialized; + + // Create buffer for file context + TInt fileSize; + User::LeaveIfError(iFile.Size(fileSize)); + LOG1( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::CommitL size in bytes = %d", fileSize); + + HBufC8* data = HBufC8::NewLC(fileSize); + + // Read file context + TPtr8 dataPtr = data->Des(); + TInt pos(0); + User::LeaveIfError(iFile.Seek(ESeekStart, pos)); + User::LeaveIfError(iFile.Read(dataPtr)); + User::LeaveIfError(iFile.SetSize(0)); + User::LeaveIfError(iFile.Flush()); + + // Write whole video data to stream + iOutputStream->WriteL(dataPtr); + CleanupStack::PopAndDestroy(data); + + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::CommitL-"); +} + + +void CMMARecordControl::ResetL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::ResetL+"); + // reset the recorder if already initialized + if (iState > ERecordUninitialized) + { + DoResetL(); + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::DoResetL done"); + iState = ERecordUninitialized; + + // Empty file that it can be reused + User::LeaveIfError(iFile.SetSize(0)); + User::LeaveIfError(iFile.Flush()); + } + + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::ResetL-"); +} + +void CMMARecordControl::SetRecordStream(CMMAOutputStream* aStream) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::SetRecordStream"); + __ASSERT_DEBUG(aStream, User::Panic( + _L("CMMAVideoRecordControl:: Stream is NULL."), + KErrArgument)); + delete iOutputStream; + iOutputStream = aStream; +} + + +HBufC* CMMARecordControl::GetContentTypeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::GetContentTypeL"); + return iPlayer->ContentType(); +} + +const TDesC& CMMARecordControl::ClassName() const +{ + return KControlName; +} + +void CMMARecordControl::StateChanged(TInt aState) +{ + TRAPD(err, NextStateL(aState)); + if (err) + { + Error(err); + } +} + +void CMMARecordControl::Error(TInt aErrorCode) +{ + ELOG1( EJavaMMAPI, "MMA:CMMARecordControl::Error %d", aErrorCode); + TBuf errorMessage; + errorMessage.Format(KMMARecordErrorMsg, aErrorCode); + iPlayer->PostStringEvent(CMMAPlayerEvent::ERecordError, + errorMessage); +} + +void CMMARecordControl::HandleRecordSizeLimit() +{ + // commit the stream + iOutputStream->Commit(); + TInt64 time; + iPlayer->GetMediaTime(&time); + iPlayer->PostLongEvent(CMMAPlayerEvent::ERecordStopped, time); +} + +void CMMARecordControl::NextStateL(TInt aPlayerState) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL Player state = %d", aPlayerState); + LOG1( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL internal state = %d", iState); + switch (iState) + { + case ERecordUninitialized: + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: case ERecordUninitialized"); + // This is the initial state. + // To getinto this state, commit or reset must be called + // To get out of this state startRecord must be called + + break; + } + case ERecordInitialized: + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: case ERecordInitialized"); + // To get into this state stopRecord must be called. + // To get out of this state startRecord, commit or reset must be + // called + break; + } + case ERecordStandBy: + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: case ERecordStandBy"); + // To get into this state startRecord must be called. + // To get out of this state stopRecord, commit or reset must be + // called, or state of the Player must change to STARTED + + + // start the actual recording if player is started + if (aPlayerState == CMMAPlayer::EStarted) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: ERecordStandBy -> ERecordRecording"); + DoStartRecordL(); + iState = ERecordRecording; + } + break; + } + case ERecordRecording: + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: case ERecordRecording"); + + // To get into this state startRecord must have been called and + // the Player must be in STARTED state. + // To get out of this state, stopRecord, commit or reset must be + // called or the Player must change to a state other than STARTED + TInt64 time; + iPlayer->GetMediaTime(&time); + WaitForPauseL(time); + DoStopRecordL(); + iState = ERecordStandBy; + break; + } + default: + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMARecordControl::NextStateL: case default - code should not reach here!!"); + __ASSERT_DEBUG(KErrGeneral, User::Invariant()); // This will newer occur + break; + } + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmasnapshot.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmasnapshot.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,248 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class takes snapshot and resizes bitmap if needed. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmasnapshot.h" +#include "mmmaguiplayer.h" +#include "mmmasnapshotreadycallback.h" +#include "mmmasnapshot.h" + +// CONSTANTS +const TInt KIgnoreSize = -1; + + +// CONSTRUCTION +CMMASnapshot* CMMASnapshot::NewL(MMMAGuiPlayer* aGuiPlayer, + MMMASnapshotReadyCallback& aCallBack) +{ + CMMASnapshot* self = new(ELeave) CMMASnapshot(aGuiPlayer, + aCallBack); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); // self + return self; +} + +CMMASnapshot::~CMMASnapshot() +{ + if (iScaler) + { + iScaler->Cancel(); + delete iScaler; + } + if (iEncoder) + { + iEncoder->Cancel(); + delete iEncoder; + } + delete iBitmap; + delete iBuffer; + delete iSettings; +} + +void CMMASnapshot::ConstructL() +{ + CActiveScheduler::Add(this); + iScaler = CBitmapScaler::NewL(); +} + +CMMASnapshot::CMMASnapshot(MMMAGuiPlayer* aGuiPlayer, + MMMASnapshotReadyCallback& aCallBack): + CActive(EPriorityStandard), + iEncoding(MMMASnapshot::EBitmap), + iCallBack(aCallBack), + iState(EIdle) +{ + iGUIPlayer = aGuiPlayer; +} + +void CMMASnapshot::TakeSnapShotL(const TDesC& aProperties) +{ + // snapshot sequence is not finished + __ASSERT_DEBUG(iState == EIdle, User::Invariant()); + // image buffer must be taken with ImageBuffer before taking new snapshot + __ASSERT_DEBUG(iBuffer == NULL, User::Invariant()); + + CMMAImageSettings* settings + = TMMAParameterValidator::ValidateImagePropertiesL(aProperties); + CleanupStack::PushL(settings); + + delete iSettings; + CleanupStack::Pop(settings); + iSettings = settings; + + // take snapshot from player. RunL is called when image is ready + // or error occures + iState = ETakingSnapshot; + TSize snapshotSize(iSettings->iWidth, iSettings->iHeight); + iEncoding = iGUIPlayer->SnapshoterL()->TakeSnapshotL(&iStatus, + snapshotSize, + *iSettings); + SetActive(); +} + +HBufC8* CMMASnapshot::ImageBuffer() +{ + // this must not be called when snapshot sequence is running + __ASSERT_DEBUG(iState == EIdle, User::Invariant()); + HBufC8* buffer = iBuffer; + // caller takes ownership of the buffer + iBuffer = NULL; + return buffer; +} + +void CMMASnapshot::ResizeL() +{ + iState = EResizing; + TSize imageSize(iBitmap->SizeInPixels()); + if (iSettings->iWidth != KIgnoreSize) + { + imageSize.iWidth = iSettings->iWidth; + } + if (iSettings->iHeight != KIgnoreSize) + { + imageSize.iHeight = iSettings->iHeight; + } + if (imageSize == iBitmap->SizeInPixels()) + { + // no user resizing needed, continue sequence + EncodeL(); + } + else + { + iScaler->Scale(&iStatus, *iBitmap, imageSize, EFalse); + SetActive(); + } +} + +void CMMASnapshot::EncodeL() +{ + // CImageEncoder cannot be reused, so have to make it every time + CImageEncoder* encoder = CImageEncoder::DataNewL(iBuffer, *iSettings->iMimeType); + delete iEncoder; + iEncoder = encoder; + + iState = EEncoding; + iEncoder->Convert(&iStatus, *iBitmap, iSettings->iImageData); + SetActive(); +} + +void CMMASnapshot::Completed(TInt aError) +{ + iStatus = aError; + iCallBack.SnapshotReady(); +} + +void CMMASnapshot::RunL() +{ + if (iStatus != KErrNone) + { + // Error has occured, inform java side and change state + iState = EIdle; + Completed(iStatus.Int()); + return; + } + + switch (iState) + { + case ETakingSnapshot: + { + LOG1( EJavaMMAPI, EInfo, "MMA::CMMASnapshot::RunL: iEncoding = %d", iEncoding); + if (iEncoding == MMMASnapshot::EEncoded) + { + // take encoded image from player. + // Ownership transfers to this class. + iBuffer = iGUIPlayer->SnapshoterL()->SnapshotEncoded(); + if (!iBuffer) + { + // error has occured with taking image + Completed(KErrNotFound); + } + // Image is ready, update internal state and inform listener + // Encoded images are not resized + iState = EIdle; + Completed(KErrNone); + } + else + { + // take bitmap from player. + // Ownership transfers to this class. + iBitmap = iGUIPlayer->SnapshoterL()->SnapshotBitmap(); + if (!iBitmap) + { + // error has occured with taking image + Completed(KErrNotFound); + } + // Continue to next state + ResizeL(); + } + break; + } + case EResizing: + { + // Continue to next state + EncodeL(); + break; + } + case EEncoding: + { + delete iEncoder; + iEncoder = NULL; + + delete iBitmap; + iBitmap = NULL; + iState = EIdle; + // encoding is ready, inform listener + Completed(KErrNone); + break; + } + default: + { + // unknown state + __ASSERT_DEBUG(EFalse, User::Invariant()); + } + } +} + +TInt CMMASnapshot::RunError(TInt aError) +{ + // Reset state + iState = EIdle; + // Pass error code to observer + Completed(aError); + + return KErrNone; +} + +void CMMASnapshot::DoCancel() +{ + // snapshot taking cannot be cancelled + if (iScaler) + { + iScaler->Cancel(); + } + if (iEncoder) + { + iEncoder->Cancel(); + } + iState = EIdle; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmasnapshotevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmasnapshotevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,88 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmasnapshotevent.h" +#include "mmapiutils.h" + +CMMASnapshotEvent::CMMASnapshotEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TInt aError, + HBufC8* aImageBuffer, + TDisposability aDisposable): + CMMAEvent(aNotifyObject, + aHandleEventMethod, + aDisposable) +{ + iEventData = aError; + iImageBuffer = aImageBuffer; +} + +CMMASnapshotEvent::~CMMASnapshotEvent() +{ + // image buffer need to be deleted if + // event server hasn't sent this event before + // middlet is destroyed + delete iImageBuffer; +} + +void CMMASnapshotEvent::Dispatch(JNIEnv& aJni) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMASnapshotEvent::Dispatch"); + + // create java byte array + jbyteArray byteArray; + if (iImageBuffer) + { + byteArray = aJni.NewByteArray(iImageBuffer->Size()); + if (byteArray) + { + MMAPIUtils::CopyToJava(aJni, + *iImageBuffer, + byteArray, + 0, + iImageBuffer->Size()); + } + } + else + { + byteArray = aJni.NewByteArray(0); + } + + if (!byteArray) + { + delete iImageBuffer; + iImageBuffer = NULL; // otherwise double delete in destructor + + LOG( EJavaMMAPI, EInfo, "MMA::CMMASnapshotEvent::Dispatch - Failed to create ByteArray"); + return; + } + + + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventData, + byteArray); + + delete iImageBuffer; + iImageBuffer = NULL; // otherwise double delete in destructor +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmasourcestream.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmasourcestream.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,215 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class for reading data from Java SourceStream to native side +* +*/ + +#include + +#include + +#include "mmafunctionserver.h" +#include "cmmasourcestream.h" +#include "cmmasourcestreamevent.h" +#include "mmmasourcestreamlistener.h" + +const TInt KBufferSize = 4096; // data is read from java in 4k pieces + +// CONSTRUCTION +CMMASourceStream* CMMASourceStream::NewL(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener + ) +{ + CMMASourceStream* self = CMMASourceStream::NewLC(aJNIEnv, + aEventPoster, + aJavaSourceStream, + aListener); + CleanupStack::Pop(); + return self; +} + + +CMMASourceStream* CMMASourceStream::NewLC(JNIEnv* aJNIEnv, + MMMAEventPoster* aEventPoster, + jobject aJavaSourceStream, + MMMASourceStreamListener* aListener + ) +{ + CMMASourceStream* self = new(ELeave) CMMASourceStream(aEventPoster, + aListener); + CleanupStack::PushL(self); + self->ConstructL(aJNIEnv, aJavaSourceStream); + return self; +} + + +CMMASourceStream::~CMMASourceStream() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMASourceStream::~"); + delete iData; + delete iReadEvent; +} + + +// Default constructor +CMMASourceStream::CMMASourceStream(MMMAEventPoster* aEventPoster, + MMMASourceStreamListener* aListener) + : iEventPoster(aEventPoster), iListener(aListener) +{ +} + + +void CMMASourceStream::ConstructL(JNIEnv* aJNIEnv, + jobject aJavaSourceStream) +{ + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJNIEnv = iEventPoster->getValidJniEnv(); + jmethodID classMethodID = + aJNIEnv->GetMethodID(aJNIEnv->GetObjectClass(aJavaSourceStream), + "read", + "(II)V"); + if (!classMethodID) + { + User::Leave(KErrNoMemory); + } + LOG( EJavaMMAPI, EInfo, "CMMASourceStream::ConstructL , jmethodId found"); + jobject apeer = aJNIEnv->NewGlobalRef(aJavaSourceStream); + iReadEvent = new(ELeave) CMMASourceStreamEvent(classMethodID, + apeer); +} + + +void CMMASourceStream::WriteL(const TUint8* aData, + TInt aLength, + TInt aState) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMASourceStream::WriteL() %d",aState); + if (aState < KErrNone) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMASourceStream::WriteL : 1"); + // Inform listener on error case + iListener->ReadCompletedL(aState, KNullDesC8()); + return; + } + + + if ((iData->Size() + aLength) > iData->Des().MaxSize()) + { + // if data doesn't fit, reallocate more + HBufC8* reallocated = iData->ReAlloc(iData->Des().MaxSize() + KBufferSize); + if (!reallocated) // realloc failed + { + // probably too much data read, so freeing used memory + delete iData; + iData = NULL; + iListener->ReadCompletedL(KErrNoMemory, KNullDesC8()); + return; + } + iData = reallocated; + } + + // java returns length -1 when completed + if (aLength > 0) + { + iData->Des().Append(aData, aLength); + } + + TInt currentRead = iData->Size() - iBufferPosition; + + if ((aState == ECompleted) || + (currentRead == iReadLength)) + { + if (iReadLength == KMMAReadAllData) + { + iListener->ReadCompletedL(aState, *iData); + } + else + { + TPtrC8 data = iData->Mid(iBufferPosition, currentRead); + iListener->ReadCompletedL(aState, data); + } + } + else + { + // phase ready, inform the Player + if (iReadLength == KMMAReadAllData) + { + iReadEvent->SetLength(KBufferSize); + } + else + { + iReadEvent->SetLength(iReadLength - currentRead); + } + + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMASourceStream::WriteL completed"); +} + +void CMMASourceStream::ReadL(TInt aLength) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMASourceStream::ReadL(%d)", aLength); + + __ASSERT_DEBUG(iData != NULL, User::Invariant()); + + PrepareReadL(); + + iBufferPosition = iData->Size(); + iReadLength = aLength; + + iReadEvent->SetLength(aLength); + + // data has been requested, note will be sent + iEventPoster->PostEvent(iReadEvent, CMMAEvent::ENotifyPriority); +} + + +void CMMASourceStream::ReadAllL() +{ + // not reading again if iData already has data + if (iData == NULL) + { + LOG( EJavaMMAPI, EInfo, "CMMASourceStream::ReadAllL: Buffer empty, reading from java"); + CreateDataBufferL(KBufferSize); + ReadL(KMMAReadAllData); + } + else + { + LOG( EJavaMMAPI, EInfo, "CMMASourceStream::ReadAllL: Buffer not empty, ->ReadCompleteL"); + iListener->ReadCompletedL(ECompleted, *iData); + } +} + +void CMMASourceStream::PrepareReadL() +{ +} + +void CMMASourceStream::ResetData() +{ + delete iData; + iData = NULL; +} + +void CMMASourceStream::CreateDataBufferL(TInt aBufferSize) +{ + LOG( EJavaMMAPI, EInfo, "CMMASourceStream::CreateDataBufferL +"); + __ASSERT_DEBUG(iData == NULL, User::Invariant()); + + iData = HBufC8::NewL(aBufferSize); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmasourcestreamevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmasourcestreamevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + +#include + +#include "cmmasourcestreamevent.h" + + +CMMASourceStreamEvent::CMMASourceStreamEvent( + jmethodID aHandleEventMethod, + jobject aNotifyObject): + CMMAEvent(EReusableEvent), + iHandleEventMethod(aHandleEventMethod), + iListenerObject(aNotifyObject) +{ +} + + +void CMMASourceStreamEvent::SetLength(TInt aLength) +{ + iLength = aLength; +} + + + +void CMMASourceStreamEvent::Dispatch(JNIEnv& aJni) +{ + LOG1( EJavaMMAPI, EInfo, "CMMASourceStreamEvent:Dispatch len=%d", iLength); + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iLength); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmastoptimecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmastoptimecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,263 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for stoptime controlling +* +*/ + + +// INCLUDE FILES +#include +#include + +#include "cmmastoptimecontrol.h" +#include "cmmaplayer.h" + + +_LIT(KControlName, "StopTimeControl"); + +_LIT(KMMAStopTimeControlError, "StopTimeControl Symbian OS error: %d"); +const TInt KMMAStopTimeControlErrorLength = 50; + +CMMAStopTimeControl::CStopTimer* CMMAStopTimeControl::CStopTimer::NewL( + CMMAStopTimeControl* aControl) +{ + CStopTimer* self = new(ELeave) CStopTimer(aControl); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; +} + + +CMMAStopTimeControl::CStopTimer::CStopTimer(CMMAStopTimeControl* aControl) + : CTimer(CActive::EPriorityStandard) +{ + iControl = aControl; +} + + +void CMMAStopTimeControl::CStopTimer::ConstructL() +{ + CTimer::ConstructL(); + CActiveScheduler::Add(this); +} + + +void CMMAStopTimeControl::CStopTimer::RunL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl:CStopTimer:RunL timer triggered"); + iControl->StopAtTimeL(); +} + +const TDesC& CMMAStopTimeControl::ClassName() const +{ + return KControlName; +} + + +CMMAStopTimeControl* CMMAStopTimeControl::NewL(CMMAPlayer* aPlayer) +{ + CMMAStopTimeControl* control = + new(ELeave) CMMAStopTimeControl(aPlayer); + CleanupStack::PushL(control); + control->ConstructL(); + CleanupStack::Pop(); // control + return control; +} + + +CMMAStopTimeControl::~CMMAStopTimeControl() +{ + delete iTimer; +} + + +CMMAStopTimeControl::CMMAStopTimeControl(CMMAPlayer* aPlayer) + : iPlayer(aPlayer), iNoTimer((MAKE_TINT64(KMaxTInt, KMaxTUint))) +{ + iStopTime = iNoTimer; +} + + +void CMMAStopTimeControl::ConstructL() +{ + iTimer = CStopTimer::NewL(this); + iPlayer->AddStateListenerL(this); +} + + +void CMMAStopTimeControl::StaticGetStopTime(CMMAStopTimeControl* aControl, + TInt64* aTime) +{ + aControl->GetStopTime(*aTime); +} + + +void CMMAStopTimeControl::StaticSetStopTimeL(CMMAStopTimeControl* aControl, + TInt64* aTime) +{ + aControl->SetStopTimeL(*aTime); +} + + +void CMMAStopTimeControl::StopAtTimeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl::StopAtTime"); + + // Stop the player only when it's playing + if (iPlayer->State() == CMMAPlayer::EStarted) + { + TInt64 time; + iPlayer->GetMediaTime(&time); + if (time >= 0 && time < iStopTime) + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl::StopAtTime - Called %dms too early", + I64INT((time - iStopTime)/1000)); + StartTimer(time); + return; + } + + TInt64 stopTime; + + // MediaTime is known + if (time >= 0) + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl::StopAtTime - called %dms late", I64INT((time - iStopTime)/1000)); + stopTime = time; + } + else + { + // Use the requested time + stopTime = iStopTime; + } + + iPlayer->StopL(EFalse); + + // Inform the player that it's "stopped at time" + iPlayer->PostLongEvent(CMMAPlayerEvent::EStoppedAtTime, stopTime); + + iStopTime = iNoTimer; // Timer is reseted + } +} + + +/** + * Get stop time, in microseconds + */ +void CMMAStopTimeControl::GetStopTime(TInt64& aTime) +{ + aTime = iStopTime; +} + + +/** + * Set stop time, in microseconds + * @param aTime is iNoTimer if the timer should be reseted + */ +void CMMAStopTimeControl::SetStopTimeL(const TInt64& aTime) +{ + iStopTime = aTime; + + if (aTime != iNoTimer) + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl:SetStopTime(%dms)", + I64INT(aTime / 1000)); + + if (iPlayer->State() == CMMAPlayer::EStarted) + { + TInt64 currentTime(0); + iPlayer->GetMediaTime(¤tTime); + + StartTimer(currentTime); + } + } + else + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl:SetStopTime(RESET)"); + + iTimer->Cancel(); + } +} + + +/* + * Start timer + * @param aCurrentTime current position of the player + */ +void CMMAStopTimeControl::StartTimer(const TInt64& aCurrentTime) +{ + // StopTime is defined + TInt64 time = iStopTime - aCurrentTime; + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAStopTimeControl:StartTimer timer started; time=%dms", + I64INT(time / 1000)); + iTimer->Cancel(); + + if (time >= 0) + { + // Value is too large to represent with TInt + // use the biggest possible value instead + if (I64HIGH(time) != 0 || I64INT(time) < 0) + { + time = KMaxTInt; + } + + iTimer->After(TTimeIntervalMicroSeconds32(I64INT(time))); + } + else + { + // Stop the player immediatelly + TRAPD(err, StopAtTimeL()); + if (err != KErrNone) + { + TBuf< KMMAStopTimeControlErrorLength > errorMsg; + errorMsg.Format(KMMAStopTimeControlError, err); + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, + errorMsg); + } + } +} + + +void CMMAStopTimeControl::StateChanged(TInt aState) +{ + switch ((CMMAPlayer::TPlayerState) aState) + { + case CMMAPlayer::EStarted: + { + if (iStopTime != iNoTimer) + { + // (Re)start the timer + TInt64 time; + iPlayer->GetMediaTime(&time); + + StartTimer(time); + } + break; + } + case CMMAPlayer::ERealized: + case CMMAPlayer::EPrefetched: + case CMMAPlayer::EClosed: + { + // Player is not running anymore + iTimer->Cancel(); + break; + } + default: + { + // other states are ignored + } + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideocontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideocontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,486 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a VideoControl. +* +*/ + + +// INCLUDE FILES +#include +//#include + +#include + +#include "com_nokia_microedition_media_control_VideoControl.h" + +#include "cmmavideocontrol.h" +#include "cmmacameraplayer.h" +#include "mmmaeventposter.h" +#include "cmmacanvasdisplay.h" +#include "cmmaitemdisplay.h" +#include "cmmasnapshotevent.h" +#include "mmmaguiplayer.h" +#include "cmmasnapshot.h" +#include "mmmadisplaywindow.h" +#include "cmmaplayerproperties.h" +#include "cmmadcdisplay.h" +#include "cmmavideocontrol.h" + +_LIT(KControlName, "VideoControl"); + +EXPORT_C CMMAVideoControl::CMMAVideoControl(MMMAGuiPlayer* aGuiPlayer): + CMMAControl() +{ + iGuiPlayer = aGuiPlayer; + iIsForeground = 1; + + iDisplay = 0; +} + +EXPORT_C CMMAVideoControl::~CMMAVideoControl() +{ + delete iDisplay; + + // Event server takes event ownership + if (iEventPoster) + { + if(iDeleteRefEvent) + { + iEventPoster->PostEvent(iDeleteRefEvent); + } + } + if (iSnapshot) + { + iSnapshot->Cancel(); + delete iSnapshot; + } +} + + +void CMMAVideoControl::ConstructL(CMMAVideoControl* aControl, + jobject aControlObject, + MMAFunctionServer* aEventSource, + JNIEnv* aJni, + MMMAEventPoster* aEventPoster/*, + CMIDToolkit* aToolkit*/) // mobitv fix // 3.x QT based UI +{ + + + + + + aControl->iListenerObject = aControlObject; + aControl->iJni = aEventSource->getValidJniEnv(); + aControl->iEventPoster = aEventPoster; + + // snapshot ready method. Created here because jni cannot be used later. + aControl->iSnapshotReadyMethod = aJni->GetMethodID( + aJni->GetObjectClass(aControlObject), + "snapshotReady", + "(I[B)V"); + + aControl->iSnapshot = CMMASnapshot::NewL(aControl->iGuiPlayer, + *aControl); + // aControl->RegisterForegroundListenerL(aToolkit); // 3.x QT based UI +} +/* // 3.x QT based UI +// mobitv fix` +void CMMAVideoControl::RegisterForegroundListenerL(CMIDToolkit* aToolkit) +{ + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListener + "); + + // Initialize IsForeground to true, we might have already missed the event (HandleForegroundL), events before observer registration + iIsForeground = ETrue; + + + iToolkit = aToolkit; + + if (iToolkit) + { + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListenerL : iToolkit->Env(); +"); + iMidEnv = iToolkit->Env(); + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListenerL : iToolkit->Env(); -"); + } + + if (iMidEnv) + { + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListenerL : iMidEnv->AddObserverL + "); + // register for getting the foreground change event + iMidEnv->AddObserverL(*this); + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListenerL : iMidEnv->AddObserverL - "); + } + + LOG(EJavaMMAPI,EInfo,"CMMAVideoControl::RegisterForegroundListenerL - "); +} +*/ +void CMMAVideoControl::StaticInitL(CMMAVideoControl* aControl, + jobject javaDisplayRef, + MMAFunctionServer* aEventSource, + TInt* aDisplayHandle, + CMMAEvent* aDeleteRefEvent) +{ + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticInitL +"); + + aControl->iDeleteRefEvent = aDeleteRefEvent; + + CMMACanvasDisplay* canvasDisplay = + CMMACanvasDisplay::NewLC(aEventSource,javaDisplayRef); + aControl->iDisplay = canvasDisplay; + CleanupStack::Pop(canvasDisplay); + *aDisplayHandle = reinterpret_cast(canvasDisplay); + + +/* MMIDComponent::TType componentType = aComponent->Type(); + switch (componentType) + { + case MMIDComponent::ECustomItem: + { + //MMIDCustomItem // end of // 3.x QT based UI + // MMIDCustomItem* customItem = + // reinterpret_cast< MMIDCustomItem* >(aComponent); + + CMMAItemDisplay* itemDisplay = + CMMAItemDisplay::NewLC(customItem); + + aControl->iDisplay = itemDisplay; + CleanupStack::Pop(itemDisplay); + *aDisplayHandle = JavaMakeHandle(itemDisplay); + break; + } + case MMIDComponent::ECanvas: + { + //MMIDCanvas + MMIDCanvas* canvas = reinterpret_cast< MMIDCanvas* >(aComponent); + + CMMACanvasDisplay* canvasDisplay = + CMMACanvasDisplay::NewLC(canvas); + + aControl->iDisplay = canvasDisplay; + CleanupStack::Pop(canvasDisplay); + *aDisplayHandle = JavaMakeHandle(canvasDisplay); + break; + } + default: + { + // other component types are not supported + User::Leave(KErrNotSupported); + } + + }*/ + + aControl->iGuiPlayer->SetDisplayL(aControl->iDisplay); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticInitL - "); +} + + +void CMMAVideoControl::SetDisplayHandleToJavaPeer(MMAFunctionServer* eventSource ,jobject aJavaVideoControlPeer) +{ + JNIEnv* validJNI = eventSource->getValidJniEnv(); + + jmethodID jmid = validJNI->GetMethodID( validJNI->GetObjectClass(aJavaVideoControlPeer), + "setNativeDisplayHandleToJavaPeer", + "(I)V"); + // DEBUG_INT("CMMADisplay::GetCallbackInUiThread getCallBackMethodID = %d",getCallBackMethodID); + TInt handle = reinterpret_cast(iDisplay); + validJNI->CallVoidMethod(aJavaVideoControlPeer,jmid,handle); + iGuiPlayer->SetDisplayL(iDisplay); +} + +void CMMAVideoControl::StaticInitDynamicModeL( + CMMAVideoControl* aVideoControl, + TInt* aContentHandle, + MMAFunctionServer* aEventSource, + jobject aGUIObject, + CMMAEvent* aDeleteRefEvent) +{ + LOG(EJavaMMAPI,EInfo,"MMA::CMMAVideoControl::StaticInitDynamicModeL+"); + aVideoControl->iDeleteRefEvent = aDeleteRefEvent; + + CMMADCDisplay* dcDisplay = CMMADCDisplay::NewLC(aVideoControl->iGuiPlayer, + aEventSource, + aGUIObject); + + MMMADirectContent* content = dcDisplay; + *aContentHandle = reinterpret_cast< TInt >(content); + aVideoControl->iDisplay = dcDisplay; + aVideoControl->iGuiPlayer->SetDisplayL(aVideoControl->iDisplay); + CleanupStack::Pop(dcDisplay); + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticInitDynamicModeL-"); +} + +void CMMAVideoControl::StaticGetPropertyL(CMMAVideoControl* aControl, + TInt aPropertyType, + TInt* aReturnValue) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticGetPropertyL property %d", + aPropertyType); + +// MMAPI UI 3.x req. +// remove the below return; once display is implemented in java + return; + + + MMMADisplay* display = aControl->iDisplay; + + if (aPropertyType != com_nokia_microedition_media_control_VideoControl_PROPERTY_SOURCE_WIDTH && + aPropertyType != com_nokia_microedition_media_control_VideoControl_PROPERTY_SOURCE_HEIGHT && + !display) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticGetPropertyL not initialized yet"); + // init is not done yet, returning 0 + *aReturnValue = 0; + return; + } + + switch (aPropertyType) + { + case com_nokia_microedition_media_control_VideoControl_PROPERTY_DISPLAY_WIDTH: + { + *aReturnValue = display->DisplaySize().iWidth; + break; + } + case com_nokia_microedition_media_control_VideoControl_PROPERTY_DISPLAY_HEIGHT: + { + *aReturnValue = display->DisplaySize().iHeight; + break; + } + case com_nokia_microedition_media_control_VideoControl_PROPERTY_DISPLAY_X: + { + *aReturnValue = display->DisplayLocation().iX; + break; + } + case com_nokia_microedition_media_control_VideoControl_PROPERTY_DISPLAY_Y: + { + *aReturnValue = display->DisplayLocation().iY; + break; + } + case com_nokia_microedition_media_control_VideoControl_PROPERTY_SOURCE_WIDTH: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticGetPropertyL get source width"); + *aReturnValue = aControl->iGuiPlayer->SourceSize().iWidth; + break; + } + case com_nokia_microedition_media_control_VideoControl_PROPERTY_SOURCE_HEIGHT: + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticGetPropertyL get source height"); + *aReturnValue = aControl->iGuiPlayer->SourceSize().iHeight; + break; + } + default: + { + *aReturnValue = KErrNotFound; + User::Leave(KErrNotFound); + break; + } + } +} + + +void CMMAVideoControl::StaticSetPropertyL(CMMAVideoControl* aControl, + TInt aPropertyType, + TInt aPropertyA, + TInt aPropertyB) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticSetPropertyL property type %d", + aPropertyType); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticSetPropertyL a property %d", + aPropertyA); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticSetPropertyL b property %d", + aPropertyB); +// MMAPI UI 3.x req. +// remove the below return; once display is implemented in java + return; + + MMMADisplay* display = aControl->iDisplay; + + __ASSERT_DEBUG(display != NULL, + User::Panic(_L("display not initialized"), KErrNotReady)); + + switch (aPropertyType) + { + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_SIZE: + { + TSize displaySize(aPropertyA, aPropertyB); + display->SetDisplaySizeL(displaySize); + + // inform java side + if (!display->IsFullScreen()) + { + aControl->iGuiPlayer->NotifyWithStringEvent( + CMMAPlayerEvent::ESizeChanged, KControlName); + } + break; + } + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_LOCATION: + { + TPoint displayLocation(aPropertyA, aPropertyB); + display->SetDisplayLocationL(displayLocation); + break; + } + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_VISIBLE_TRUE: + { + display->SetVisible(ETrue); + break; + } + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_VISIBLE_FALSE: + { + display->SetVisible(EFalse); + break; + } + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_FULLSCREEN_TRUE: + { + // store old user rect to determine if SIZE_CHANGED event + // has to be delivered when full screen mode is turned off. + aControl->iOldDisplaySize = display->DisplaySize(); + + display->SetFullScreenL(ETrue); + break; + } + case com_nokia_microedition_media_control_VideoControl_SET_DISPLAY_FULLSCREEN_FALSE: + { + display->SetFullScreenL(EFalse); + + // Send SIZE_CHANGED event when fullscreen is turned off if + // size of the video display has changed. Possible position + // change is however disregarded + if (aControl->iOldDisplaySize != display->DisplaySize()) + { + aControl->iGuiPlayer->NotifyWithStringEvent( + CMMAPlayerEvent::ESizeChanged, KControlName); + } + + break; + } + default: + { + User::Leave(KErrNotFound); + break; + } + } +} + + +void CMMAVideoControl::TakeSnapShotL(CMMAVideoControl* aControl, + const TDesC* aProperties) +{ + __ASSERT_DEBUG( + aControl, + User::Panic(_L("CMMAVideoControl::TakeSnapShotL CMMAVideoControl is NULL"), + KErrArgument) + ); + + ASSERT(aProperties); + aControl->iSnapshot->TakeSnapShotL(*aProperties); +} + +EXPORT_C void CMMAVideoControl::SnapshotReady() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::SnapshotReady()"); + + // now this class owns the buffer + HBufC8* imageBuffer = iSnapshot->ImageBuffer(); + // Use standard new to avoid useless trap. + CMMASnapshotEvent* event = + new CMMASnapshotEvent(iListenerObject, + iSnapshotReadyMethod, + iSnapshot->iStatus.Int(), + imageBuffer, + CMMAEvent::EDisposableEvent); + if (event) + { + // ok, ownership of buffer transfered to event + + // event poster takes the ownership of the event + iEventPoster->PostEvent(event, CMMAEvent::ENotifyPriority); + } + else + { + // we own the buffer + delete imageBuffer; + } +} + +EXPORT_C const TDesC& CMMAVideoControl::ClassName() const +{ + return KControlName; +} +TBool CMMAVideoControl::IsForeground() +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoControl::IsForeground() %d",iIsForeground); + + return iIsForeground; +} + +void CMMAVideoControl::StaticSetForegroundL(CMMAVideoControl* aControl, + TInt aForeground) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticSetForegroundL + aForeground %d", + aForeground); + + __ASSERT_DEBUG( + aControl, + User::Panic(_L("MMA::CMMAVideoControl::StaticSetForegroundL : CMMAVideoControl is NULL"), + KErrArgument) + ); + + if (aControl) + { + aControl->SetForeground(aForeground, EFalse); + } + + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoControl::StaticSetForegroundL - "); +} + +/* // 3.x QT based UI +// Implement MMIDEnvObserver + +void CMMAVideoControl::HandleSwitchOnL(TBool aSwitchOn) +{ + // Dummy implementation, no intent to do anything +} +*/ +/** + * Handles the case when the MIDlet is brought to the foreground. + */ + +/* +void CMMAVideoControl::HandleForegroundL(TBool aForeground) +{ + + SetForeground(aForeground, ETrue); + +} + +*/ +void CMMAVideoControl::SetForeground(TBool aForeground, TBool aUseEventServer) +{ + iIsForeground = aForeground; + if (iDisplay) + { + iDisplay->SetForeground(iIsForeground, aUseEventServer); + } +} + + +/** + * Handles a change to resources which are shared accross the environment. + */ +/* +void CMMAVideoControl::HandleResourceChangeL(TInt aType) +{ + // Dummy implementation, no intent to do anything +} +*/ // end of // 3.x QT based UI +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideoframepositioningcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideoframepositioningcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,284 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements FramePositioningControl for video player +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "cmmavideoframepositioningcontrol.h" + +namespace +{ +const TInt32 KMMAFramePosMicroSecMultiplier = 1000000; +} + +CMMAVideoFramePositioningControl* +CMMAVideoFramePositioningControl::NewL(CMMAVideoPlayer* aPlayer) +{ + CMMAVideoFramePositioningControl* self = + new(ELeave) CMMAVideoFramePositioningControl(aPlayer); + return self; + +} +CMMAVideoFramePositioningControl:: +CMMAVideoFramePositioningControl(CMMAVideoPlayer* aPlayer) + : CMMAFramePositioningControl(aPlayer), iPlayer(aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoFramePositioningControl::CMMAVideoFramePositioningControl"); +} + +CMMAVideoFramePositioningControl::~CMMAVideoFramePositioningControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoFramePositioningControl::~CMMAVideoFramePositioningControl"); +} + +TInt CMMAVideoFramePositioningControl::SeekL(TInt aFrameNumber) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::SeekL, aFrameNumber: %d", aFrameNumber); + + RMMFController& controller = iPlayer->Controller(); + + // Controller is paused before changing position to increase + // accuracy + TBool playerStarted = EFalse; + if (iPlayer->State() == CMMAPlayer::EStarted) + { + playerStarted = ETrue; + } + + if (playerStarted) + { + User::LeaveIfError(controller.Pause()); + } + + // Frame number must be positive + TInt frameNumber = aFrameNumber; + if (frameNumber < 0) + { + frameNumber = 0; + } + + // Find out framerate of video + TReal32 frameRate = 0; + GetAndCheckFrameRateL(frameRate); + + // Calculate new media time + TReal tempReal = ((TReal32)frameNumber * + KMMAFramePosMicroSecMultiplier) / frameRate; + User::LeaveIfError(Math::Round(tempReal, tempReal, 0)); + TInt64 newMediaTime = tempReal; + + // New media time is clamped to duration + TInt err = ClampMediaTime(newMediaTime); + // Clamp fails if duration of content is not known. + // Two additional resorts are (in preferred order): + // 1) Return current frame position if it can be calculated. + // 2) Or seek to 0. + + // First resort + if (err != KErrNone) + { + iPlayer->GetMediaTime(&newMediaTime); + // Second resort + if (newMediaTime < 0) + { + newMediaTime = 0; + } + } + iPlayer->SetMediaTimeL(&newMediaTime); + // Error condition + if (newMediaTime < KErrNotFound) + { + User::Leave(KErrNotFound); + } + + // Calculate actually set frame number + tempReal = (((TReal32)newMediaTime / KMMAFramePosMicroSecMultiplier) * + (TReal32) frameRate); + User::LeaveIfError(Math::Round(tempReal, tempReal, 0)); + + // Restart controller + if (playerStarted) + { + User::LeaveIfError(controller.Play()); + } + + return tempReal; +} + +TInt CMMAVideoFramePositioningControl::SkipL(TInt aFramesToSkip) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::SkipL, aFramesToSkip: %d", aFramesToSkip); + + RMMFController& controller = iPlayer->Controller(); + + // Controller is paused before changing position to increase + // accuracy + TBool playerStarted = EFalse; + if (iPlayer->State() == CMMAPlayer::EStarted) + { + playerStarted = ETrue; + } + + if (playerStarted) + { + User::LeaveIfError(controller.Pause()); + } + + // Find out framerate of video + TReal32 frameRate = 0; + GetAndCheckFrameRateL(frameRate); + + // Find out current media time + TInt64 currentMediaTime = 0; + iPlayer->GetMediaTime(¤tMediaTime); + + // Error condition + if (currentMediaTime < KErrNone) + { + User::Leave(KErrNotFound); + } + + // Find out current frame number + TReal tempReal = + ((TReal32) currentMediaTime / KMMAFramePosMicroSecMultiplier) * + frameRate; + User::LeaveIfError(Math::Round(tempReal, tempReal, 0)); + TInt currentFrameNumber = tempReal; + + // Calculate new media time + TInt64 newMediaTime = currentMediaTime + + (((TReal32) aFramesToSkip / frameRate) * KMMAFramePosMicroSecMultiplier); + + // New media time is clamped to duration + TInt err = ClampMediaTime(newMediaTime); + + // If clamping fails, no frames are skipped + TInt framesSkipped = 0; + if (err == KErrNone) + { + iPlayer->SetMediaTimeL(&newMediaTime); + // Error condition + if (newMediaTime < KErrNone) + { + User::Leave(KErrNotFound); + } + + // Calculate actual amount of frames skipped + tempReal = ((((TReal32) newMediaTime / KMMAFramePosMicroSecMultiplier) * + (TReal32) frameRate) - currentFrameNumber); + + User::LeaveIfError(Math::Round(tempReal, tempReal, 0)); + framesSkipped = tempReal; + } + + // Restart controller + if (playerStarted) + { + User::LeaveIfError(controller.Play()); + } + + return framesSkipped; +} + +void CMMAVideoFramePositioningControl::MapFrameToTimeL(TInt aFrameNumber, TInt64* aMediaTime) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::MapFrameToTimeL, aFrameNumber: %d", aFrameNumber); + // Find out framerate of video + TReal32 frameRate = 0; + GetAndCheckFrameRateL(frameRate); + + // Find out frame mediatime + TInt64 frameMediaTime = + ((TReal32)aFrameNumber / (TReal32)frameRate) * + KMMAFramePosMicroSecMultiplier; + + TInt64 duration; + iPlayer->GetDuration(&duration); + + if (frameMediaTime < 0) + { + frameMediaTime = KErrNotFound; + } + else if (frameMediaTime > duration) + { + frameMediaTime = KErrNotFound; + // With some medias last frame media time is few hundred microsec's + // over duration. This is because framerate is not accurate. + // If given frame number is last frame and frameMediaTime > duration, + // return duration + // Find out last frame + TReal lastFrame = (frameRate * (TReal32)duration) / + KMMAFramePosMicroSecMultiplier; + User::LeaveIfError(Math::Round(lastFrame, lastFrame, 0)); + if (aFrameNumber == lastFrame) + { + frameMediaTime = duration; + } + } + *aMediaTime = frameMediaTime; +} + +TInt CMMAVideoFramePositioningControl::MapTimeToFrameL(TInt64* aMediaTime) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::MapTimeToFrameL, aMediaTime: %d", *aMediaTime); + TInt64 mediaTime = *aMediaTime; + + // If given media time is < 0 or > duration, cannot map time to frame + // conversion fails, -1 is returned + TInt64 duration; + iPlayer->GetDuration(&duration); + if (mediaTime > duration || mediaTime < 0) + { + return KErrNotFound; + } + + // Find out framerate of video + TReal32 frameRate = 0; + GetAndCheckFrameRateL(frameRate); + + // Calculate frame number from media time + TReal tempReal = (TInt)((TReal64)(mediaTime * frameRate) / + KMMAFramePosMicroSecMultiplier); + User::LeaveIfError(Math::Round(tempReal, tempReal, 0)); + + return tempReal; +} + + +void CMMAVideoFramePositioningControl::GetAndCheckFrameRateL( + TReal32& aFrameRate) +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::GetAndCheckFrameRateL"); + RMMFVideoControllerCustomCommands customCommands = + RMMFVideoControllerCustomCommands(iPlayer->Controller()); + + User::LeaveIfError(customCommands.GetFrameRate(aFrameRate)); + LOG1( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::GetAndCheckFrameRateL, aFrameRate: %d", aFrameRate); + if (aFrameRate <= 0) + { + // zero framerate is not accepted because cannot + // divide by zero. Negative framerate is not + // acceptable aswell. + LOG( EJavaMMAPI, EInfo, "CMMAVideoFramePositioningControl::GetAndCheckFrameRateL: invalid framerate"); + User::Leave(KErrNotFound); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideoplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideoplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,127 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating video player. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideoplayerfactory.h" +#include "cmmastoptimecontrol.h" +#include "cmmavideoplayer.h" +#include "cmmavideocontrol.h" +#include "cmmaaudiovolumecontrol.h" +#include "cmmammfresolver.h" +#include "cmmavideoframepositioningcontrol.h" +#include "cmmammfratecontrol.h" + + +// audio content type +_LIT(KMMAAudio, "audio"); +// Length of KMMAAudio descriptor +const TInt KMMAAudioLength = 5; + +CMMAVideoPlayerFactory* CMMAVideoPlayerFactory::NewLC() +{ + CMMAVideoPlayerFactory* pFactory = + new(ELeave) CMMAVideoPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + +CMMAVideoPlayerFactory::CMMAVideoPlayerFactory() +{ +} + + +CMMAVideoPlayerFactory::~CMMAVideoPlayerFactory() +{ +} + +#ifdef RD_JAVA_OMA_DRM_V2 +CMMAPlayer* CMMAVideoPlayerFactory::CreatePlayerWithFileL(const TDesC& aContentType, + const TDesC* aFileName) +{ + iFileName = aFileName; + return CMMAMMFPlayerFactory::CreatePlayerL(aContentType); +} +#endif // RD_JAVA_OMA_DRM_V2 + +CMMAPlayer* CMMAVideoPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + HBufC* cType = aResolver->ContentType(); + + // Video player may not accept audio content types. + if (cType && + cType->Length() >= KMMAAudioLength && + (aResolver->ContentType()->Mid(0, KMMAAudioLength) == KMMAAudio)) + { + return NULL; + } + +#ifdef RD_JAVA_OMA_DRM_V2 + if (iFileName) + { + aResolver->SetFileNameL(iFileName); + iFileName = NULL; + } +#endif // RD_JAVA_OMA_DRM_V2 + + CMMAVideoPlayer* player = CMMAVideoPlayer::NewLC(aResolver); + + CMMAVideoControl* videoControl = new(ELeave) CMMAVideoControl(player); + CleanupStack::PushL(videoControl); + player->AddControlL(videoControl); + CleanupStack::Pop(videoControl); + + CMMAAudioVolumeControl* audioVolumeControl = CMMAAudioVolumeControl::NewL(player); + CleanupStack::PushL(audioVolumeControl); + player->AddControlL(audioVolumeControl); + CleanupStack::Pop(audioVolumeControl); + + CMMAStopTimeControl* stopTimeControl = CMMAStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + // FramePositioningControl is only supported for file locator + if (player->IsFilePlayer()) + { + CMMAVideoFramePositioningControl* framePositioningControl = + CMMAVideoFramePositioningControl::NewL(player); + CleanupStack::PushL(framePositioningControl); + player->AddControlL(framePositioningControl); + CleanupStack::Pop(framePositioningControl); + } + + CMMAMMFRateControl* rateControl = CMMAMMFRateControl::NewL(player); + CleanupStack::PushL(rateControl); + player->AddControlL(rateControl); + CleanupStack::Pop(rateControl); + + + CleanupStack::Pop(); // player + return player; +} + + +void CMMAVideoPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeVideo)); + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeAudio)); +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideorecordcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideorecordcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,374 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is a RecordControl. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideorecordcontrol.h" +#include "cmmaplayer.h" +#include "cmmammfresolver.h" +#include "cmmacamerasound.h" + +const TInt KUnlimitedSize = KMaxTInt32; + +const TReal32 KNoUserDefinedFps = -1; +const TInt KNoUserDefinedSize = -1; +const TInt KNoUserDefinedRecordSize = -1; + +_LIT(KVideoMp4MimeType, "video/mp4"); +_LIT(KVideoH264MimeType, "video/H264"); + +_LIT8(KMimeTypeMPEG4VSPL3, "video/mp4v-es; profile-level-id=3"); +_LIT8(KMimeTypeH264AVCBPL12, "video/H264; profile-level-id=42800C"); // Level 1.2 + +CMMAVideoRecordControl* CMMAVideoRecordControl::NewL(CMMAPlayer* aPlayer, + CMMAMMFResolver* aResolver, + const TMMAVideoSettings& aVideoSettings, + CMMAAudioSettings* aAudioSettings, + TInt aCameraHandle) +{ + CMMAVideoRecordControl* self = + new(ELeave)CMMAVideoRecordControl(aPlayer, + aCameraHandle); + CleanupStack::PushL(self); + + // SetContentType takes ownership + aPlayer->SetContentType(aResolver->ContentTypeOwnership()); + self->ConstructL(*aResolver->Implementations(), + aVideoSettings, + aAudioSettings); + + CleanupStack::Pop(); + return self; +} + +CMMAVideoRecordControl::CMMAVideoRecordControl(CMMAPlayer* aPlayer, + TInt aCameraHandle): + CMMARecordControl(aPlayer), + iRecordSizeLimit(KNoUserDefinedRecordSize) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::CMMAVideoRecordControl"); + + __ASSERT_DEBUG(aCameraHandle > 0, User::Panic( + _L("CMMAVideoRecordControl::Invalid camera"), + KErrArgument)); + __ASSERT_DEBUG(aPlayer, User::Panic( + _L("CMMAVideoRecordControl::Invalid player"), + KErrArgument)); + iCameraHandle = aCameraHandle; +} + +CMMAVideoRecordControl::~CMMAVideoRecordControl() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::~CMMAVideoRecordControl"); + + delete iActiveSchedulerWait; + + if (iRecorder) + { + iRecorder->Close(); + delete iRecorder; + } +} + +void CMMAVideoRecordControl::ConstructL( + RMMFControllerImplInfoArray& aControllerInfos, + const TMMAVideoSettings& aVideoSettings, + CMMAAudioSettings* aAudioSettings) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::ConstructL +"); + CMMARecordControl::ConstructL(); + + iVideoSettings = aVideoSettings; + + iActiveSchedulerWait = new(ELeave) CActiveSchedulerWait(); + + iRecorder = CVideoRecorderUtility::NewL(*this, EMdaPriorityMin, EMdaPriorityPreferenceNone); + + TUid videoControllerUid = KNullUid; + TUid videoFormatUid = KNullUid; + + HBufC8* encoding; + // if wanted video encoding is H264, we must find format uid for video/mp4 + // and set encoding later because mmf doesn't have controller for video/H264 + if (!(iVideoSettings.iEncoding.Compare(KVideoH264MimeType) == 0)) + { + encoding = HBufC8::NewLC(iVideoSettings.iEncoding.Length()); + encoding->Des().Copy(iVideoSettings.iEncoding); + } + else + { + encoding = HBufC8::NewLC(KVideoMp4MimeType().Length()); + encoding->Des().Copy(KVideoMp4MimeType()); + } + + // Go through controller infos to find format UID + TInt controllerCount = aControllerInfos.Count(); + for (TInt cIndex = 0; cIndex < controllerCount; cIndex++) + { + const RMMFFormatImplInfoArray infoArray = + aControllerInfos[ cIndex ]->RecordFormats(); + + // Find correct format uid + TInt formatCount = infoArray.Count(); + for (TInt formatIndex = 0; formatIndex < formatCount; formatIndex++) + { + if (infoArray[ formatIndex ]->SupportsMimeType(*encoding)) + { + // Uids will be used to open controller + videoFormatUid = infoArray[ formatIndex ]->Uid(); + videoControllerUid = aControllerInfos[ cIndex ]->Uid(); + } + } + } + CleanupStack::PopAndDestroy(encoding); + + if (videoFormatUid == KNullUid || + videoControllerUid == KNullUid) + { + // Controller and / or format for mime was not found. + User::Leave(KErrNotSupported); + } + + iFile.Close(); + iRecorder->OpenFileL(iFilename, + iCameraHandle, + videoControllerUid, + videoFormatUid, + KNullDesC8, + aAudioSettings->iDataType); + + // wait until MvruoOpenComplete is called + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + User::LeaveIfError(iError); + + // if wanted video encoding is mp4, set it + if (iVideoSettings.iEncoding.Compare(KVideoMp4MimeType) == 0) + { + iRecorder->SetVideoTypeL(KMimeTypeMPEG4VSPL3); + // audio encoding with mp4 is AAC by default + iRecorder->SetAudioTypeL(KMMFFourCCCodeAAC); + } + + // if wanted video encoding is H264, set it + if (iVideoSettings.iEncoding.Compare(KVideoH264MimeType) == 0) + { + iRecorder->SetVideoTypeL(KMimeTypeH264AVCBPL12); + // audio encoding with mp4 is AAC by default + iRecorder->SetAudioTypeL(KMMFFourCCCodeAAC); + } + + // setting size if it is set by user + TSize videoSize; + iRecorder->GetVideoFrameSizeL(videoSize); + if (iVideoSettings.iHeight != KNoUserDefinedSize) + { + videoSize.iHeight = iVideoSettings.iHeight; + } + + if (iVideoSettings.iWidth != KNoUserDefinedSize) + { + videoSize.iWidth = iVideoSettings.iWidth; + } + iRecorder->SetVideoFrameSizeL(videoSize); + + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::ConstructL()-"); +} + +void CMMAVideoRecordControl::InitializeL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::InitializeL()"); + iRecorder->Prepare(); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + User::LeaveIfError(iError); + + // setting frame rate if it is set by user + // record utility must be prepared to do this + if (iVideoSettings.iFps != KNoUserDefinedFps) + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::InitializeL() SetVideoFrameRateL = %d", iVideoSettings.iFps); + iRecorder->SetVideoFrameRateL(iVideoSettings.iFps); + } + + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::InitializeL()-"); +} + +void CMMAVideoRecordControl::DoStartRecordL() +{ + // if reset is called then file is reopened, closing it in order to prevent + // KErrInUse + iFile.Close(); + ELOG1( EJavaMMAPI, "MMA:CMMAVideoRecordControl::DoStartRecordL() err=%d", iError); + User::LeaveIfError(iError); + + // play sound when recording starts + CMMACameraSound::PlayVideoRecordSoundL(); + + // Set recordsize limit if needed + if (iRecordSizeLimit != KNoUserDefinedRecordSize) + { + DoSetRecordSizeLimitL(iRecordSizeLimit); + } + + iRecorder->Record(); +} + +void CMMAVideoRecordControl::DoStopRecordL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::DoStopRecordL"); + // Just paused that recording can continue + iRecorder->PauseL(); +} + +void CMMAVideoRecordControl::DoResetL() +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::ResetL"); + TInt err = iRecorder->Stop(); + // returns KErrCompletion when recording is finished when size limit is reached + // and KErrAlreadyExists if we have created file (ignoring both) + if ((err != KErrCompletion) && + (err != KErrAlreadyExists)) + { + User::LeaveIfError(err); + } + TBool isOpen(EFalse); + err = iFs.IsFileOpen(iFilename, isOpen); + if (!isOpen && (err != KErrNotFound)) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::ResetL - Opening file"); + // opening file for resetting (or commit) + User::LeaveIfError(iFile.Open(iFs, iFilename, EFileRead | + EFileWrite | + EFileShareAny)); + } + else if (err == KErrNotFound) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::ResetL - Recreating file"); + // record utility deletes file if nothing is recorded, creating it again + User::LeaveIfError(iFile.Create(iFs, + iFilename, + EFileRead | + EFileWrite | + EFileShareAny)); + } + else + { + User::LeaveIfError(err); + } +} + +void CMMAVideoRecordControl::DoSetRecordSizeLimitL(TInt aSize) +{ + if (aSize == KUnlimitedSize) + { + iRecorder->SetMaxClipSizeL(KMMFNoMaxClipSize); + } + else + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::DoSetRecordSizeLimitL %d", aSize); + iRecorder->SetMaxClipSizeL(aSize); + } + // reset local value + iRecordSizeLimit = KNoUserDefinedRecordSize; + // have to reprepare after setting clipsize + iRecorder->Prepare(); + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + User::LeaveIfError(iError); +} + +TInt CMMAVideoRecordControl::SetRecordSizeLimitL(TInt aSize) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoRecordControl::SetRecordSizeLimitL %d", aSize); + + // if already recording, try to set immediately + if (iState == ERecordRecording) + { + DoSetRecordSizeLimitL(aSize); + } + else + { + // set record size limit when recording is started + iRecordSizeLimit = aSize; + } + return aSize; +} + +void CMMAVideoRecordControl::MvruoOpenComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA:CMMAVideoRecordControl::MvruoOpenComplete aError = %d", aError); + + // Error situation is handled in ConstructL, + iError = aError; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } +} + +void CMMAVideoRecordControl::MvruoPrepareComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA:CMMAVideoRecordControl::MvruoPrepareComplete aError = %d", aError); + // Error situation is handled in InitializeL + iError = aError; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } +} + +void CMMAVideoRecordControl::MvruoRecordComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA:CMMAVideoRecordControl::MvruoRecordComplete aError = %d", aError); + + // iState = ERecordComplete + + if ((aError == KErrNone) || + (aError == KErrCompletion)) // Size limit reached + { + if (aError == KErrCompletion) + { + HandleRecordSizeLimit(); + } + } + else + { + Error(aError); + } +} + + +void CMMAVideoRecordControl::MvruoEvent(const TMMFEvent& aEvent) +{ + ELOG1( EJavaMMAPI, "MMA:CMMAVideoRecordControl::MvruoEvent event error code = %d", aEvent.iErrorCode); + // Only error situations needs to be considered. + if (aEvent.iErrorCode != KErrNone) + { + Error(aEvent.iErrorCode); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideourlplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideourlplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,317 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing video. +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "cmmavideourlplayer.h" +#include "mmmadisplay.h" +#include "cmmasourcestream.h" + +const TUid KUrlSourceUid = { KMmfUidUrlSource }; +_LIT(KMMALiveStreamMetaDataKeyword, "LiveStream"); +_LIT(KMMALiveStreamMetaDataValue, "1"); + +CMMAVideoUrlPlayer* CMMAVideoUrlPlayer::NewLC( + CMMAMMFResolver* aResolver, + const TDesC& aUrl) +{ + CMMAVideoUrlPlayer* self = new(ELeave) CMMAVideoUrlPlayer( + aResolver); + CleanupStack::PushL(self); + self->ConstructL(aUrl); + return self; +} + +EXPORT_C CMMAVideoUrlPlayer::~CMMAVideoUrlPlayer() +{ + iConnection.Close(); + iSocketServ.Close(); + delete iUrl; + delete iPlayerDelegate; +} + +EXPORT_C void CMMAVideoUrlPlayer::ConstructL(const TDesC& aUrl) +{ + CMMAVideoPlayer::ConstructL(); + iUrl = aUrl.AllocL(); + + User::LeaveIfError(iSocketServ.Connect()); + User::LeaveIfError(iConnection.Open(iSocketServ)); +} + +EXPORT_C CMMAVideoUrlPlayer::CMMAVideoUrlPlayer( + CMMAMMFResolver* aResolver): + CMMAVideoPlayer(aResolver) +{ +} + +EXPORT_C void CMMAVideoUrlPlayer::DeallocateL() +{ + __ASSERT_DEBUG(iPlayerDelegate != NULL, User::Invariant()); + delete iPlayerDelegate; + iPlayerDelegate = NULL; + CMMAMMFPlayerBase::DeallocateL(); +} + +EXPORT_C void CMMAVideoUrlPlayer::CloseL() +{ + // Do not call the CMMAVideoPlayer CloseL because it deletes + // file source stream. + CMMAAudioPlayer::CloseL(); +} + +EXPORT_C void CMMAVideoUrlPlayer::StartL() +{ + __ASSERT_DEBUG(iPlayerDelegate != NULL, User::Invariant()); + LOG( EJavaMMAPI, EInfo, "CMMAVideoUrlPlayer::StartL() +"); + iPlayerDelegate->StartL(); + LOG( EJavaMMAPI, EInfo, "CMMAVideoUrlPlayer::StartL() -"); +} + +EXPORT_C void CMMAVideoUrlPlayer::StopL(TBool aPostEvent) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::StopL "); + __ASSERT_DEBUG(iPlayerDelegate != NULL, User::Invariant()); + iPlayerDelegate->StopL(aPostEvent); +} + +EXPORT_C void CMMAVideoUrlPlayer::GetMediaTime(TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::GetMediaTime +"); + if (iPlayerDelegate) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::GetMediaTime .iPlayerDelegate->GetMediaTime "); + iPlayerDelegate->GetMediaTime(aMediaTime); + } + else + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::GetMediaTime Not found "); + *aMediaTime = KErrNotFound; + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::GetMediaTime -"); +} + +EXPORT_C void CMMAVideoUrlPlayer::RealizeL() +{ + CMMAPlayer::RealizeL(); // Changes state to ERealized +} + + +EXPORT_C void CMMAVideoUrlPlayer::PrefetchL() +{ + const TUint KConnectionTreshold(1); + TUint connectIap((TUint)KUseDefaultIap); + TUint connectionCount(0); + User::LeaveIfError(iConnection.EnumerateConnections(connectionCount)); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::PrefetchL: connectionCount = %d", connectionCount); + if (connectionCount == KConnectionTreshold) + { + // One active connection - find it and try using it + FindActiveIap(connectionCount, connectIap); + } + // else No active connections try using the default one + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::PrefetchL: connectIap = %d", connectIap); + + CMMFUrlParams* urlCfg = CMMFUrlParams::NewLC(*iUrl, (TInt)connectIap); + CBufFlat* urlCfgBuffer = urlCfg->ExternalizeToCBufFlatLC(); + + // Store current thread priority to give + // more CPU time to Java threads i.e. this + // is work around for not locking the Java + // thread while RTSP connection is being + // opened + iOrigPriority = RThread().Priority(); + + // player priority settings + TMMFPrioritySettings prioritySettings; + prioritySettings.iPriority = EMdaPriorityMax; + prioritySettings.iPref = EMdaPriorityPreferenceTimeAndQuality; + prioritySettings.iState = EMMFStatePlaying; + + User::LeaveIfError(DoOpen(KUrlSourceUid, + urlCfgBuffer->Ptr(0), + KUidMmfAudioOutput, + KNullDesC8, + prioritySettings)); + + User::LeaveIfError(iController.Prime()); + + CleanupStack::PopAndDestroy(urlCfgBuffer); + CleanupStack::PopAndDestroy(urlCfg); + + // Prefetch will be completed in HandleEvent method. + // Next event KMMFEventCategoryVideoOpenComplete will be handled in + // CMMAVideoPlayer. +} + +void CMMAVideoUrlPlayer::FindActiveIap(const TUint aConnectionCount, TUint& aActiveIap) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::FindActiveIap: aConnectionCount = %d +", aConnectionCount); + + TPckgBuf connectionInfo; + for (TUint i = 1; i <= aConnectionCount; ++i) + { + if (iConnection.GetConnectionInfo(i, connectionInfo) == KErrNone) + { + aActiveIap = connectionInfo().iIapId; + break; + } + } + + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::FindActiveIap: aActiveIap = %d -", aActiveIap); +} + +TBool CMMAVideoUrlPlayer::IsLiveStreamL() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVideoUrlPlayer::IsLiveStream: Checking if this is a live stream.."); + + CMMFMetaDataEntry* currEntry = NULL; + + TInt nEntries = 0; + User::LeaveIfError(iController.GetNumberOfMetaDataEntries(nEntries)); + + for (TInt i = 0; i < nEntries; ++i) + { + currEntry = iController.GetMetaDataEntryL(i); + + if ((0 == currEntry->Name().Compare(KMMALiveStreamMetaDataKeyword)) && + (0 == currEntry->Value().Compare(KMMALiveStreamMetaDataValue))) + { + LOG( EJavaMMAPI, EInfo, "CMMAVideoUrlPlayer::IsLiveStream: Stream is a live stream"); + delete currEntry; + return ETrue; + } + + delete currEntry; + } + + LOG( EJavaMMAPI, EInfo, "CMMAVideoUrlPlayer::IsLiveStream: Not a live stream"); + return EFalse; +} + +EXPORT_C void CMMAVideoUrlPlayer::HandleEvent(const TMMFEvent& aEvent) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::HandleEvent 0x%X", aEvent.iEventType.iUid); + ELOG1( EJavaMMAPI, "MMA:CMMAVideoUrlPlayer::HandleEvent error code: %d", aEvent.iErrorCode); + RThread currentThread; + + if (iPlayerDelegate != NULL) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::HandleEvent: iPlayerDelegate != NULL"); + iPlayerDelegate->HandleEvent(aEvent); + } + else + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::HandleEvent: else"); + + __ASSERT_DEBUG(iPlayerDelegate == NULL, User::Invariant()); + TInt err = aEvent.iErrorCode; + + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::HandleEvent: currentThread.Priority() I = %d", currentThread.Priority()); + + // Lower thread priority to give more CPU time to Java-threads + // i.e. current thread has one increment higher priority than + // EPriorityNormal + if (aEvent.iEventType == KMMFEventCategoryVideoOpenComplete && + err == KErrNone) + { + currentThread.SetPriority(EPriorityNormal); + } + + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::HandleEvent: currentThread.Priority() II = %d", currentThread.Priority()); + + if (aEvent.iEventType == KMMFEventCategoryVideoPrepareComplete) + { + // Restore original thread priority + currentThread.SetPriority(iOrigPriority); + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::HandleEvent: currentThread.Priority() III = %d", currentThread.Priority()); + + // NotCompleteVideoError is not considered as an error condition, instead it indicates + // that some elements of the media cannot be played (e.g. video OR audio) + if (err != KErrNone && err != KNotCompleteVideoError) + { + CompletePrefetch(err); + return; + } + + // Find out of this is a live stream + TBool liveStream = EFalse; + TRAP(err, liveStream = IsLiveStreamL()); + + if (err != KErrNone) + { + CompletePrefetch(err); + return; + } + + if (liveStream) + { + TRAP(err, iPlayerDelegate = + CMMAVideoUrlPlayerLiveStreamDelegate::NewL(*this)); + } + else + { + iPlayerDelegate = new CMMAVideoUrlPlayerClipStreamDelegate(*this); + err = iPlayerDelegate ? KErrNone : KErrNoMemory; + } + + if (err != KErrNone) + { + // could not create delegate + CompletePrefetch(err); + return; + } + + iPlayerDelegate->HandleEvent(aEvent); + } + else + { + // All other events. + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVideoUrlPlayer::HandleEvent: Calling CMMAVideoPlayer::HandleEvent()"); + CMMAVideoPlayer::HandleEvent(aEvent); + } + } +} + +void CMMAVideoUrlPlayer::HandleEventToParent(const TMMFEvent& aEvent) +{ + CMMAVideoPlayer::HandleEvent(aEvent); +} + +// ---------------------------------------------------------------------------- +// +// CMMAVideoUrlPlayerClipStreamDelegate +// +// ---------------------------------------------------------------------------- + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerDelegate:: +CMMAVideoUrlPlayerDelegate(CMMAVideoUrlPlayer& aPlayer) : + iPlayer(aPlayer) +{ + // Nothing to be done. +} + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerDelegate::~CMMAVideoUrlPlayerDelegate() +{ + // Nothing to be done. +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideourlplayerclipstreamdelegate.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideourlplayerclipstreamdelegate.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,112 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Player delegate to handle RTSP live streaming +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideourlplayer.h" + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate:: +CMMAVideoUrlPlayerClipStreamDelegate(CMMAVideoUrlPlayer& aPlayer) : + CMMAVideoUrlPlayerDelegate(aPlayer) +{ + // Nothing to be done. +} + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate::~CMMAVideoUrlPlayerClipStreamDelegate() +{ + // Nothing to be done. +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate::StartL() +{ + iPlayer.CMMAMMFPlayerBase::StartL(); +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate::StopL(TBool aPostEvent) +{ + if (iPlayer.iState == EStarted) + { + User::LeaveIfError(iPlayer.iController.Pause()); + + if (aPostEvent) + { + TInt64 time; + iPlayer.GetMediaTime(&time); + iPlayer.PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + // go back to prefetched state + iPlayer.ChangeState(EPrefetched); + } +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate::GetMediaTime(TInt64* aMediaTime) +{ + iPlayer.CMMAMMFPlayerBase::GetMediaTime(aMediaTime); +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerClipStreamDelegate::HandleEvent(const TMMFEvent& aEvent) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Clip stream: HandleEvent %d", aEvent.iEventType.iUid); + ELOG1( EJavaMMAPI, "MMA:CMMAVideoUrlPlayer: Clip stream: HandleEvent error code: %d", aEvent.iErrorCode); + + TInt err = aEvent.iErrorCode; + + if ((aEvent.iEventType == KMMFEventCategoryVideoLoadingComplete) && + (iPlayer.iState == ERealized)) + { + // Call pause only when doing prefetch. + // Loading complete will come also when looping. + if (err == KErrNone) + { + err = iPlayer.iController.Pause(); + } + + // VideoLoadingComplete-event only completes prefetch sequence + // for non-live streams. + iPlayer.CompletePrefetch(err); + } + else if (aEvent.iEventType == KMMFEventCategoryVideoPrepareComplete) + { + // going to prefetch state, after Play + // KMMFEventCategoryVideoLoadingComplete event will be received + + if (err == KErrNone) + { + iPlayer.PrepareDisplay(); + + // Buffering is done only for non-live streams. + err = iPlayer.iController.Play(); + } + + // For non-live streams: if error is other than + // KErrNone, then complete prefetch. + if (err != KErrNone) + { + // prefetch didn't succeed + iPlayer.CompletePrefetch(err); + } + } + else + { + // All other events. + iPlayer.HandleEventToParent(aEvent); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideourlplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideourlplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,223 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating video player. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideourlplayerfactory.h" +#include "cmmavideourlplayer.h" +#include "cmmavideocontrol.h" +#include "cmmaaudiovolumecontrol.h" +#include "cmmammfratecontrol.h" + +// CONSTANTS +const TInt KDefaultGranularity = 8; +_LIT(KProtocolRtsp, "rtsp"); +_LIT(KRtspMimeType, "application/sdp"); + +_LIT(KAudioXPnRmMimeType, "application/x-pn-realmedia"); +_LIT(KAudioRmMimeType, "application/vnd.rn-realmedia"); +_LIT(KAudio3gppMimeType, "audio/3gpp"); +_LIT(KAudio3gpp2MimeType, "audio/3gpp2"); +_LIT(KAudioAmrMimeType, "audio/amr"); +_LIT(KAudioMp4MimeType, "audio/mp4"); +_LIT(KAudioMp4LatmMimeType, "audio/mp4-latm"); +_LIT(KAudioQcelpMimeType, "audio/qcelp"); +_LIT(KAudioVndQcelpMimeType, "audio/vnd.qcelp"); +_LIT(KVideo3GppMimeType, "video/3gpp"); +_LIT(KVideo3Gpp2MimeType, "video/3gpp2"); +_LIT(KVideoMp4MimeType, "video/mp4"); + +_LIT(KProtocolSeparator, "://"); +_LIT(KParameterSeparator, "?"); + +CMMAVideoUrlPlayerFactory::CMMAVideoUrlPlayerFactory() +{ +} + + +CMMAVideoUrlPlayerFactory* CMMAVideoUrlPlayerFactory::NewLC() +{ + CMMAVideoUrlPlayerFactory* pFactory = + new(ELeave) CMMAVideoUrlPlayerFactory(); + CleanupStack::PushL(pFactory); + return pFactory; +} + + +CMMAVideoUrlPlayerFactory::~CMMAVideoUrlPlayerFactory() +{ + delete iUrl; +} + + +CMMAPlayer* CMMAVideoUrlPlayerFactory::CreatePlayerL(const TDesC& /*aContentType*/) +{ + // Only creating with locator is supported + return NULL; +} +CMMAPlayer* CMMAVideoUrlPlayerFactory::CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters) +{ + // Is it rtsp:// protocol + if (aProtocol != KProtocolRtsp) + { + return NULL; + } + CMMFFormatSelectionParameters* fSelect = + CMMFFormatSelectionParameters::NewLC(); + + // combining the locator + HBufC* remadeLocator = HBufC::NewLC(aProtocol.Length() + + KProtocolSeparator().Length() + + aMiddlePart.Length() + + KParameterSeparator().Length() + + aParameters.Length()); + TPtr loc = remadeLocator->Des(); + loc.Append(aProtocol); + loc.Append(KProtocolSeparator); + loc.Append(aMiddlePart); + if (aParameters != KNullDesC) + { + loc.Append(KParameterSeparator); + loc.Append(aParameters); + } + delete iUrl; + iUrl = remadeLocator; + CleanupStack::Pop(remadeLocator); + + // RTSP URLs without file extension: + // In case of file extensionless RTSP URL a predefined mime type + // is used to select controller. It is assumed that this mime + // type selects the controller that is capable to play any file + // extensionless RTSP URLs. + // To determine whether there is a file extension, it is checked whether + // there is a dot at all or if there is a slash after last dot in the + // URL. If there is a slash after last dot or if there is no dot at all, + // then there is no file extension. + TInt dotPos = aMiddlePart.LocateReverse('.'); + TInt slashPos = aMiddlePart.LocateReverse('/'); + if ((dotPos == KErrNotFound) || (slashPos > dotPos)) + { + HBufC8* mimeBuf = HBufC8::NewLC(KRtspMimeType().Length()); + TPtr8 mimePtr = mimeBuf->Des(); + mimePtr.Copy(KRtspMimeType()); + fSelect->SetMatchToMimeTypeL(mimePtr); + CleanupStack::PopAndDestroy(mimeBuf); + } + else + { + // Match to file name, using only middle part of the locator + fSelect->SetMatchToUriL(loc); + } + + CMMAPlayer* player = CMMAMMFPlayerFactory::CreatePlayerL(fSelect); + + CleanupStack::PopAndDestroy(fSelect); + return player; +} + +CMMAPlayer* CMMAVideoUrlPlayerFactory::CreatePlayerL( + const TDesC8& /*aHeaderData*/) +{ + // We do not try to match headerdata + return NULL; +} + + +void CMMAVideoUrlPlayerFactory::GetSupportedContentTypesL( + const TDesC& aProtocol, + CDesC16Array& aMimeTypes) +{ + if ((aProtocol == KNullDesC) || + (aProtocol == KProtocolRtsp)) + { + aMimeTypes.AppendL(KAudio3gppMimeType); + aMimeTypes.AppendL(KAudio3gpp2MimeType); + aMimeTypes.AppendL(KAudioAmrMimeType); + aMimeTypes.AppendL(KAudioMp4MimeType); + aMimeTypes.AppendL(KAudioMp4LatmMimeType); + aMimeTypes.AppendL(KAudioQcelpMimeType); + aMimeTypes.AppendL(KAudioVndQcelpMimeType); + aMimeTypes.AppendL(KVideo3GppMimeType); + aMimeTypes.AppendL(KVideo3Gpp2MimeType); + aMimeTypes.AppendL(KVideoMp4MimeType); + aMimeTypes.AppendL(KAudioRmMimeType); + aMimeTypes.AppendL(KAudioXPnRmMimeType); + // plus RTSP content types + aMimeTypes.AppendL(KRtspMimeType); + } +} + + +void CMMAVideoUrlPlayerFactory::GetSupportedProtocolsL( + const TDesC& aContentType, + CDesC16Array& aProtocolArray) +{ + CDesC16ArraySeg* supportedCTs + = new(ELeave) CDesC16ArraySeg(KDefaultGranularity); + CleanupStack::PushL(supportedCTs); + GetSupportedContentTypesL(KNullDesC, *supportedCTs); + TInt ignore(0); + if ((supportedCTs->Find(aContentType, ignore) == 0) || + (aContentType == KNullDesC)) + { + aProtocolArray.AppendL(KProtocolRtsp); + } + CleanupStack::PopAndDestroy(supportedCTs); +} + +CMMAPlayer* CMMAVideoUrlPlayerFactory::CreatePlayerL( + CMMAMMFResolver* aResolver) +{ + CMMAVideoUrlPlayer* player = CMMAVideoUrlPlayer::NewLC(aResolver, + *iUrl); + + CMMAVideoControl* videoControl = new(ELeave) CMMAVideoControl(player); + CleanupStack::PushL(videoControl); + player->AddControlL(videoControl); + CleanupStack::Pop(videoControl); + + CMMAAudioVolumeControl* audioVolumeControl = CMMAAudioVolumeControl::NewL(player); + CleanupStack::PushL(audioVolumeControl); + player->AddControlL(audioVolumeControl); + CleanupStack::Pop(audioVolumeControl); + + CMMAMMFRateControl* rateControl = CMMAMMFRateControl::NewL(player); + CleanupStack::PushL(rateControl); + player->AddControlL(rateControl); + CleanupStack::Pop(rateControl); + + CleanupStack::Pop(); // player + return player; +} + +void CMMAVideoUrlPlayerFactory::MediaIdsL(RArray& aMediaIds) +{ + User::LeaveIfError(aMediaIds.Append(KUidMediaTypeVideo)); +} + +CMMFPluginSelectionParameters::TMediaIdMatchType +CMMAVideoUrlPlayerFactory::MediaIdMatchType() +{ + // We are now getting only Audio Controllers + return CMMFPluginSelectionParameters::EAllowOtherMediaIds; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavideourlplayerlivestreamdelegate.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavideourlplayerlivestreamdelegate.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,227 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Player delegate to handle RTSP live streaming +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmavideourlplayer.h" + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate* +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::NewL(CMMAVideoUrlPlayer& aPlayer) +{ + CMMAVideoUrlPlayerLiveStreamDelegate* self = + new(ELeave) CMMAVideoUrlPlayerLiveStreamDelegate(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate:: +CMMAVideoUrlPlayerLiveStreamDelegate(CMMAVideoUrlPlayer& aPlayer) : + CMMAVideoUrlPlayerDelegate(aPlayer), iMediaStartTime(0), + iStoppedAtTime(0) +{ +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::ConstructL() +{ + iActiveSchedulerWait = new(ELeave)CActiveSchedulerWait; +} + +CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::~CMMAVideoUrlPlayerLiveStreamDelegate() +{ + delete iActiveSchedulerWait; +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::StartL() +{ + // start can't be called to not ready player + ASSERT(iPlayer.iState == EPrefetched); + + + iPlayer.PrefetchL(); + + // Refresh all controls again after second prefetch + iPlayer.RefreshControls(); + + // Completed in VideoPrepareComplete-event + if (!iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StartL() ASW Start1"); + iActiveSchedulerWait->Start(); + } + + // Prime() is called sometimes twice since it's needed also when + // restarting the playing + User::LeaveIfError(iPlayer.iController.Prime()); + User::LeaveIfError(iPlayer.iController.Play()); + + // Completed in VideoLoadingComplete-event + if (!iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StartL() ASW Start2"); + iActiveSchedulerWait->Start(); + } + iPlayer.PostActionCompleted(KErrNone); // java start return +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::StopL(TBool aPostEvent) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StopL"); + if (iPlayer.iState == EStarted) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StopL : Started "); + GetMediaTime(&iStoppedAtTime); + if (aPostEvent) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StopL : Postevent "); + iPlayer.PostLongEvent(CMMAPlayerEvent::EStopped, iStoppedAtTime); + } + // go back to prefetched state + iPlayer.ChangeState(EPrefetched); + + // Call stop instead of Pause as per the suggestions from helix + // Pause has no meaning for live streaming + iPlayer.iController.Stop(); + } + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: StopL - "); +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::GetMediaTime(TInt64* aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::GetMediaTime +"); + if (iPlayer.iState == EStarted) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::GetMediaTime Started Playerbase call"); + iPlayer.CMMAMMFPlayerBase::GetMediaTime(aMediaTime); + *aMediaTime -= iMediaStartTime; + } + else + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::GetMediaTime Stopped"); + *aMediaTime = iStoppedAtTime; + } + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::GetMediaTime -"); +} + +void CMMAVideoUrlPlayer::CMMAVideoUrlPlayerLiveStreamDelegate::HandleEvent(const TMMFEvent& aEvent) +{ + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: HandleEvent %d", aEvent.iEventType.iUid); + ELOG1( EJavaMMAPI, "MMA:CMMAVideoUrlPlayer: Live stream: HandleEvent error code: %d", aEvent.iErrorCode); + + TInt err = aEvent.iErrorCode; + + if ((aEvent.iEventType == KMMFEventCategoryVideoLoadingComplete) && + (iPlayer.iState == EPrefetched)) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoLoadingComplete +"); + if (err == KErrNone) + { + TTimeIntervalMicroSeconds position(0); + TInt error(iPlayer.iController.GetPosition(position)); + if (error == KErrNone) + { + iMediaStartTime = position.Int64(); + } + + // inform java side. Always start playback from zero for + // live stream. + iPlayer.PostLongEvent(CMMAPlayerEvent::EStarted, 0); + + // Buffering takes a long time, so player state is not changed + // until playback really starts. + iPlayer.ChangeState(EStarted); + } + if (iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoLoadingComplete ASW Stop"); + iActiveSchedulerWait->AsyncStop(); + } + if (err != KErrNone) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoLoadingComplete Error Inform Parent"); + iPlayer.HandleEventToParent(aEvent); + } + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoLoadingComplete -"); + } + else if (aEvent.iEventType == KMMFEventCategoryVideoPrepareComplete) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPrepareComplete +"); + // going to prefetch state, after Play + // KMMFEventCategoryVideoLoadingComplete event will be received + + if (err == KErrNone) + { + iPlayer.PrepareDisplay(); + } + + // For live streams: complete prefetch. + // if activeschedulerwait is started, then + // do not complete prefetch as we are here + // as a result of calling StartL and not for + // PrefetchL. + if (!(iActiveSchedulerWait->IsStarted())) + { + iPlayer.CompletePrefetch(err); + } + + if (iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPrepareComplete ASW Stop"); + iActiveSchedulerWait->AsyncStop(); + } + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPrepareComplete -"); + } + else if (aEvent.iEventType == KMMFEventCategoryVideoPlayerGeneralError) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPlayerGeneralError +"); + // For live streams: KMMFEventCategoryVideoPlayerGeneralError means helix is closed + // side if player is in prefetched state. + if (iActiveSchedulerWait->IsStarted()) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPlayerGeneralError ASW Stop"); + iActiveSchedulerWait->AsyncStop(); + } + + // usually error condition -45 (KErrSessionClosed) or -33 (KErrTimedOut) + if (err != KErrNone) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPlayerGeneralError Inform Parent"); + iPlayer.HandleEventToParent(aEvent); + } + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: KMMFEventCategoryVideoPlayerGeneralError -"); + } + else + { + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: + 0x%X", aEvent.iEventType.iUid); + // For live streams: KErrSessionClosed is not posted to Java + // side if player is in prefetched state. + if ((iPlayer.iState != EPrefetched) || + (aEvent.iErrorCode != KErrSessionClosed)) + { + LOG( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: Error Inform Parent"); + // All other events. + iPlayer.HandleEventToParent(aEvent); + } + LOG1( EJavaMMAPI, EInfo, "MMA:CMMAVideoUrlPlayer: Live stream: - 0x%X", aEvent.iEventType.iUid); + } + +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/cmmavolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/cmmavolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,239 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for volume setting +* +*/ + + +// INCLUDE FILES + +#include "cmmavolumecontrol.h" +#include "cmmaplayer.h" +#include + +_LIT(KMMAVolumeErrorMsg, "Can't set volume level"); + +const TInt KMMAJavaSoundIndex = 0; +const TInt KMMAGlobalVolumeSoundIndex = 2; + +void CMMAVolumeControl::StaticSetLevelL(CMMAVolumeControl* aVolumeControl, + TInt aLevel) +{ + // Java level is the first + aVolumeControl->SetVolumeLevelL(KMMAJavaSoundIndex, aLevel); +} + +void CMMAVolumeControl::StaticGetLevelL(CMMAVolumeControl* aVolumeControl, + TInt* aLevel) +{ + // Java level is the first + aVolumeControl->GetVolumeLevelL(KMMAJavaSoundIndex, aLevel); +} + + +CMMAVolumeControl::CMMAVolumeControl(CMMAPlayer* aPlayer) + : iPlayer(aPlayer), iLevel(KMMAVolumeMaxLevel) +{ +} + + +CMMAVolumeControl::~CMMAVolumeControl() +{ + iLevels.Close(); +} + + +void CMMAVolumeControl::ConstructBaseL() +{ + iPlayer->AddStateListenerL(this); + + // Add level for java, will set in StaticSetLevelL method. + // In constructor iLevels array is empty and Java level will be the first, + // KMMAJavaSoundIndex. + AddLevelL(); + + iLevel = CalculateLevel(); + + // The default value is not yet known. Volume control may change the + // volume of the controller before it has been retrieved so when the + // state of the player is changed the Java volume is retrieved from + // the controller. + iLevels[ KMMAJavaSoundIndex ] = KErrNotFound; +} + +const TDesC& CMMAVolumeControl::ClassName() const +{ + return KMMAVolumeControlName; +} + +void CMMAVolumeControl::SetLevelL(TInt aLevel) +{ + // Level cannot be set to derived control if player is not prefetched. + if (iPlayer->State() > CMMAPlayer::ERealized) + { + DoSetLevelL(aLevel); + } + iLevel = aLevel; +} + +void CMMAVolumeControl::StateChanged(TInt aState) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVolumeControl::StateChanged - state %d", aState); + // Set the volume if the player is prefetched + if (aState == CMMAPlayer::EPrefetched) + { + TRAPD(error, + { + // Get the default value for the Java sound level + if (iLevels[ KMMAJavaSoundIndex ] == KErrNotFound) + { + iLevels[ KMMAJavaSoundIndex ] = DoGetLevelL(); + iLevel = CalculateLevel(); + } + SetLevelL(iLevel); + + }); + if (error != KErrNone) + { + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, + KMMAVolumeErrorMsg); + } + } + + // Level is already set for Global Volume so no need to set it again + // Notify the initial global volume value to java + // Notify only if STATE == CMMAPlayer::ERealized + // Error ID AKUR-7G69Q5 GLOBAL VOLUME EVENT CR + if (aState == CMMAPlayer::ERealized) + { + if ((iLevels.Count() - 1) == KMMAGlobalVolumeSoundIndex) + { + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVolumeControl::StateChanged : Post GLOBAL VOL EVENT "); + if (iLevels[ KMMAGlobalVolumeSoundIndex ] != KErrNotFound) + { + LOG1( EJavaMMAPI, EInfo, "MMA::CMMAVolumeControl::StateChanged : Post complete Val = %d ",iLevels[ KMMAGlobalVolumeSoundIndex ]); + iPlayer->PostLongEvent(CMMAPlayerEvent::ENOKIA_EXTERNAL_VOLUME_EVENT, + iLevels[ KMMAGlobalVolumeSoundIndex ]); + } + } + } +} + +void CMMAVolumeControl::RefreshVolume() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVolumeControl::RefreshVolume ++ "); + TRAPD(error, + { + // Get the default value for the Java sound level + if (iLevels[ KMMAJavaSoundIndex ] == KErrNotFound) + { + iLevels[ KMMAJavaSoundIndex ] = DoGetLevelL(); + iLevel = CalculateLevel(); + } + SetLevelL(iLevel); + + }); + + if (error != KErrNone) + { + iPlayer->PostStringEvent(CMMAPlayerEvent::EError, + KMMAVolumeErrorMsg); + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMAVolumeControl::RefreshVolume -- "); +} + +void CMMAVolumeControl::RefreshControl() +{ + RefreshVolume(); +} + +EXPORT_C TInt CMMAVolumeControl::AddLevelL() +{ + User::LeaveIfError(iLevels.Append(KMMAVolumeMaxLevel)); + + // New level is the last element + return iLevels.Count() - 1; +} + +EXPORT_C void CMMAVolumeControl::SetVolumeLevelL(TInt aLevelIndex, + TInt aVolumeLevel) +{ + LOG2( EJavaMMAPI, EInfo, "CMMAVolumeControl::SetVolumeLevelL - setting index %d, level %d", + aLevelIndex, aVolumeLevel); + if (0 >= iLevels.Count() || iLevels.Count() > 3) + { + return ; + } + TInt oldVolumeLevel = iLevels[ aLevelIndex ]; + iLevels[ aLevelIndex ] = aVolumeLevel; + SetLevelL(CalculateLevel()); + + // send event if level is really changed + if ((aLevelIndex == KMMAJavaSoundIndex) && + (aVolumeLevel != oldVolumeLevel)) + { + iPlayer->PostObjectEvent(CMMAPlayerEvent::EVolumeChanged, + iControlObject); + } + + // send event if global volume level is really changed + // Error ID AKUR-7G69Q5 GLOBAL VOLUME EVENT CR + if ((aLevelIndex == KMMAGlobalVolumeSoundIndex) && + (aVolumeLevel != oldVolumeLevel)) + { + + iPlayer->PostLongEvent(CMMAPlayerEvent::ENOKIA_EXTERNAL_VOLUME_EVENT, + iLevels[ aLevelIndex ]); + } +} + +void CMMAVolumeControl::GetVolumeLevelL(TInt aLevelIndex, + TInt* aVolumeLevel) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAVolumeControl::GetVolumeLevelL - level index %d", aLevelIndex); + + // Return max volume if the default Java volume level is not yet known + if (aLevelIndex == KMMAJavaSoundIndex && + iLevels[ KMMAJavaSoundIndex ] == KErrNotFound) + { + *aVolumeLevel = KMMAVolumeMaxLevel; + return; + } + + *aVolumeLevel = iLevels[ aLevelIndex ]; + + LOG1( EJavaMMAPI, EInfo, "CMMAVolumeControl::GetVolumeLevelL - level %d", *aVolumeLevel); +} + +TInt CMMAVolumeControl::CalculateLevel() +{ + TInt levelCount = iLevels.Count(); + + // 64 bit integer must be used to have more than 4 levels. + TInt64 level = KMMAVolumeMaxLevel; + TInt64 sum = 1; + + // All levels in the array are percentage of the max volume (0..100). + // Actual sound level will be multiplying all levels. + for (TInt i = 0; i < levelCount; i++) + { + // If the level is not known it is expected to be max volume + level = (iLevels[ i ] == KErrNotFound ? + level * KMMAVolumeMaxLevel : + level * iLevels[ i ]); + sum *= KMMAVolumeMaxLevel; + } + return level / sum; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/controlcontainer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/controlcontainer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,97 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This file contains ControlContainer JNI functions +* +*/ + +#include +#include "com_nokia_microedition_media_ControlContainer.h" + +#include "cmmaplayer.h" +#include "cmmacontrol.h" +#include "s60commonutils.h" + +using namespace java::util; + +//#include "mmapiutils.h" +//#include "jutils.h" + + +/** + * JNI function + */ +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_ControlContainer__1getControlClassName +(JNIEnv* aJni, jclass, + jint aControlHandle) +{ + CMMAControl* control = + reinterpret_cast< CMMAControl* >(aControlHandle); + + const TDesC& className = control->ClassName(); + + LOG1( EJavaMMAPI, EInfo, "MMA::ControlContainer.cpp::getControlClassName name = %S", + className.Ptr()); + + // Create Java String from class name and return it + return (className == KNullDesC) ? NULL : S60CommonUtils::NativeToJavaString(*aJni, className); +} + +/** + * JNI function + */ +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_ControlContainer__1getPublicControlClassName +(JNIEnv* aJni, jclass, + jint aControlHandle) +{ + CMMAControl* control = + reinterpret_cast< CMMAControl* >(aControlHandle); + + const TDesC& className = control->PublicClassName(); + + LOG1( EJavaMMAPI, EInfo, "MMA::ControlContainer.cpp::getPublicControlClassName name = %S", + className.Ptr()); + + // Create Java String from class name and return it + return (className == KNullDesC) ? NULL : S60CommonUtils::NativeToJavaString(*aJni, className); +} + +/** + * JNI function + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_ControlContainer__1getControlsCount +(JNIEnv*, jclass, + jint aPlayerHandle) +{ + CMMAPlayer* player = + reinterpret_cast< CMMAPlayer *>(aPlayerHandle); + LOG1( EJavaMMAPI, EInfo, "MMA::ControlContainer.cpp::getControlsCount count = %d", + player->ControlCount()); + return player->ControlCount(); +} + +/** + * JNI function + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_ControlContainer__1getControlHandle +(JNIEnv*, jclass, + jint aPlayerHandle, jint aControlIndex) +{ + CMMAPlayer* player = + reinterpret_cast< CMMAPlayer *>(aPlayerHandle); + + // Get control and make Java handle + return reinterpret_cast(player->Control(aControlIndex)); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/controlimpl.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/controlimpl.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAControl +* +*/ + + +//#include +//#include "mmapiutils.h" + + +#include "com_nokia_microedition_media_control_ControlImpl.h" +#include "mmafunctionserver.h" +#include "cmmacontrol.h" + +/* + * Class: com_nokia_microedition_media_control_ControlImpl + * Method: _setHandle + */ + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_ControlImpl__1setHandle +(JNIEnv* aJni, jclass , jint aEventSource, jint aControlHandle, jobject aControlObject) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAControl* control = + reinterpret_cast< CMMAControl* >(aControlHandle); + jobject controlObject = aJni->NewWeakGlobalRef(aControlObject); + + eventSource->ExecuteV(&CMMAControl::StaticSetHandle, + control, controlObject); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/display.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/display.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +#include "logger.h" +#include "com_nokia_microedition_media_control_BaseDisplay.h" +#include "cmmadisplay.h" + +/* + * Class: com_nokia_microedition_media_control_BaseDisplay + * Method: _setVisible + * Signature: (IIZ)I + */ +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_control_BaseDisplay__1nativeMethodCallInUiThread + (JNIEnv *, jobject, jint nativeDisplayHandle, jint nativeFunctionID) + { + LOG(EJavaMMAPI,EInfo,"JNI_Display.cpp : nativeMethodCallInUiThread +"); + CMMADisplay* display = reinterpret_cast(nativeDisplayHandle); + display ->CalledBackInUiThread(nativeFunctionID); + LOG(EJavaMMAPI,EInfo,"JNI_Display.cpp : nativeMethodCallInUiThread -"); + } + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/framepositioningcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/framepositioningcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,224 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAFramePositioningControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_FramePositioningControl.h" +#include "mmafunctionserver.h" +#include "cmmaframepositioningcontrol.h" +#include + +/** + * Local function which can be used to call CMMAFramePositioningControl class methods. + * Type of of the function pointer must be + * TInt CMMAFramePositioningControl::aFunc( TInt ) + * + * @param aFramePositioningControl CMMAFramePositioningControl pointer. + * @param aFuncL Pointer to the CMMAFramePositioningControl method. + * @param aParam Parameter value for aFuncL method. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntFuncIntL(CMMAFramePositioningControl* aFramePositioningControl, + TInt(CMMAFramePositioningControl::*aFuncL)(TInt aParam), + TInt aParam, + TInt* aReturnValue) +{ + // call TInt CMMAFramePositioningControl::aFunc( TInt ) method. + *aReturnValue = (aFramePositioningControl->*aFuncL)(aParam); +} + +// +// JNI functions. Prototypes are generated and commented in Java class +// com_nokia_microedition_media_control_FramePositioningControl +// + +/** + * JNI function from com.nokia.microedition.media.control.FramePositioningControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_FramePositioningControl__1seek +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aFrameNumber) +{ + LOG( EJavaMMAPI, EInfo, "FramePositioningControl__1seek"); + + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAFramePositioningControl* FramePositioningControl = + reinterpret_cast< CMMAFramePositioningControl* >(aControlHandle); + + // Will leave on error. Otherwise returnValue contains frame number + // to which the implementation has seeked. + TInt returnValue = 0; + TInt error = eventSource->ExecuteTrap(&ReturnIntFuncIntL, + FramePositioningControl, + &CMMAFramePositioningControl::SeekL, + aFrameNumber, + &returnValue); + LOG1( EJavaMMAPI, EInfo, "FramePositioningControl__1seek error= %d",error); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.FramePositioningControl + */ +JNIEXPORT jintArray JNICALL +Java_com_nokia_microedition_media_control_FramePositioningControl__1skip +(JNIEnv* aJniEnv, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jintArray aValues) +{ + LOG( EJavaMMAPI, EInfo, "FramePositioningControl__1skip"); + + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAFramePositioningControl* FramePositioningControl = + reinterpret_cast< CMMAFramePositioningControl* >(aControlHandle); + + TInt value[ 2 ]; + aJniEnv->GetIntArrayRegion(aValues, 0, 2, &value[ 0 ]); + + // Will leave on error. Otherwise returnValue contains number of frames + // skipped. + value[ 1 ] = eventSource->ExecuteTrap(&ReturnIntFuncIntL, + FramePositioningControl, + &CMMAFramePositioningControl::SkipL, + value[ 0 ], + &value[ 0 ]); + + if (aValues) + { + aJniEnv->SetIntArrayRegion(aValues, 0, 2, &value[ 0 ]); + } + + return aValues; +} + +/** + * Local function which can be used to call CMMAFramePositioningControl class methods. + * Type of of the function pointer must be + * void CMMAFramePositioningControl::aFunc( TInt, TInt64* ) + * + * @param aFramePositioningControl CMMAFramePositioningControl pointer. + * @param aFuncL Pointer to the CMMAFramePositioningControl method. + * @param aParam Parameter value for aFuncL + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void VoidFuncInt64L(CMMAFramePositioningControl* aFramePositioningControl, + void (CMMAFramePositioningControl::*aFuncL)( + TInt aParam, + TInt64* aReturnValue), + TInt aParam, + TInt64* aReturnValue) +{ + // call void CMMAFramePositioningControl::aFunc( TInt, TInt64 ) method. + (aFramePositioningControl->*aFuncL)(aParam, aReturnValue); +} + +/** + * JNI function from com.nokia.microedition.media.control.FramePositioningControl + */ +JNIEXPORT jlong JNICALL +Java_com_nokia_microedition_media_control_FramePositioningControl__1mapFrameToTime +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aFrameNumber) +{ + LOG( EJavaMMAPI, EInfo, "FramePositioningControl__1mapFrameToTime"); + + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAFramePositioningControl* FramePositioningControl = + reinterpret_cast< CMMAFramePositioningControl* >(aControlHandle); + + // Will leave on error. Media time of frame in question. + TInt64 returnValue(0); + TInt error = eventSource->ExecuteTrap(&VoidFuncInt64L, + FramePositioningControl, + &CMMAFramePositioningControl::MapFrameToTimeL, + aFrameNumber, + &returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * Local function which can be used to call CMMAFramePositioningControl class methods. + * Type of of the function pointer must be + * TInt CMMAFramePositioningControl::aFunc( TInt64* ) + * + * @param aFramePositioningControl CMMAFramePositioningControl pointer. + * @param aFuncL Pointer to the CMMAFramePositioningControl method. + * @param aParam Parameter value for aFuncL method. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntFuncInt64L(CMMAFramePositioningControl* aFramePositioningControl, + TInt(CMMAFramePositioningControl::*aFuncL)(TInt64* aParam), + TInt64* aParam, + TInt* aReturnValue) +{ + // call TInt CMMAFramePositioningControl::aFunc() method. + *aReturnValue = (aFramePositioningControl->*aFuncL)(aParam); +} + +/** + * JNI function from com.nokia.microedition.media.control.FramePositioningControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_FramePositioningControl__1mapTimeToFrame +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jlong aMediaTime) +{ + LOG( EJavaMMAPI, EInfo, "FramePositioningControl__1mapFrameToTime"); + + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAFramePositioningControl* FramePositioningControl = + reinterpret_cast< CMMAFramePositioningControl* >(aControlHandle); + + // Will leave on error. Media time of frame in question. + TInt returnValue = 0; + TInt error = eventSource->ExecuteTrap(&ReturnIntFuncInt64L, + FramePositioningControl, + &CMMAFramePositioningControl::MapTimeToFrameL, + &aMediaTime, + &returnValue); + + return (error == KErrNone) ? returnValue : error; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/itemdisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/itemdisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAItemDisplay +* +*/ + + +//#include +//#include "mmapiutils.h" +#include "com_nokia_microedition_media_control_VideoItem.h" +#include "mmafunctionserver.h" +#include "cmmaitemdisplay.h" + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoItem__1sizeChanged +(JNIEnv*, jobject, + jint aEventSourceHandle, + jint aDisplayHandle, + jint aWidth, + jint aHeight) +{ + CMMAItemDisplay* itemDisplay = reinterpret_cast< CMMAItemDisplay* >(aDisplayHandle); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + __ASSERT_DEBUG(itemDisplay != NULL, + User::Panic(_L("itemdisplay::control is null"), + KErrArgument)); + __ASSERT_DEBUG(eventSource != NULL, + User::Panic(_L("itemdisplay::eventsource is null"), + KErrArgument)); + + TInt err = eventSource->ExecuteTrap(&CMMAItemDisplay::SizeChangedL, + itemDisplay, + aWidth, + aHeight); + + return err; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoItem__1getMinContentWidth +(JNIEnv*, jobject, + jint aEventSourceHandle, + jint aDisplayHandle) +{ + CMMAItemDisplay* itemDisplay = reinterpret_cast< CMMAItemDisplay* >(aDisplayHandle); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + TSize size; + eventSource->ExecuteV(CMMAItemDisplay::StaticSourceSize, + itemDisplay, + (TSize*)&size); + return size.iWidth; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoItem__1getMinContentHeight +(JNIEnv*, jobject, + jint aEventSourceHandle, + jint aDisplayHandle) +{ + CMMAItemDisplay* itemDisplay = reinterpret_cast< CMMAItemDisplay *>(aDisplayHandle); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + TSize size; + eventSource->ExecuteV(CMMAItemDisplay::StaticSourceSize, + itemDisplay, + (TSize*)&size); + return size.iHeight; +} + + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoItem__1getPrefContentHeight +(JNIEnv*, jobject, + jint aEventSourceHandle, + jint aDisplayHandle, + jint /*aTentative*/) // tentative value is ignored because current +// implementation returns always -1 +{ + CMMAItemDisplay* itemDisplay = reinterpret_cast< CMMAItemDisplay* >(aDisplayHandle); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + TSize size; + eventSource->ExecuteV(CMMAItemDisplay::StaticSourceSize, + itemDisplay, + (TSize*)&size); + return size.iHeight; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoItem__1getPrefContentWidth +(JNIEnv*, jobject, + jint aEventSourceHandle, + jint aDisplayHandle, + jint /*aTentative*/) // tentative value is ignored because current +// implementation returns always -1 +{ + CMMAItemDisplay* itemDisplay = reinterpret_cast< CMMAItemDisplay *>(aDisplayHandle); + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + TSize size; + eventSource->ExecuteV(CMMAItemDisplay::StaticSourceSize, + itemDisplay, + (TSize*)&size); + return size.iWidth; +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/managerimpl.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/managerimpl.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,261 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has ManagerImpl JNI functions +* +*/ + +#include + +#include + +#include "com_nokia_microedition_media_ManagerImpl.h" +#include "cmmamanager.h" +#include "cmmaplayer.h" +#include "jstringutils.h" +#include "s60commonutils.h" +using namespace java::util; + +const TInt KMMADefaultArrayGranularity = 8; + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_ManagerImpl__1dispose +(JNIEnv* aJni, jobject, jint aEventSourceHandle) +{ + LOG(EJavaMMAPI,EInfo,"MMA::ManagerImpl dispose"); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + delete eventSource; +} + +LOCAL_C void ReleaseEventSource(MMAFunctionServer* aEventSource) +{ + aEventSource->Release(); +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_ManagerImpl__1release +(JNIEnv*, jobject, jint aEventSourceHandle) +{ + LOG( EJavaMMAPI, EInfo, "MMA::ManagerImpl release"); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + eventSource->ExecuteV(&ReleaseEventSource, + eventSource); +} + +/* + * Class: javax_microedition_media_Manager + * Method: _createManager + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_ManagerImpl__1createManager +(JNIEnv*, jobject, jint aEventSourceHandle, jint aMIDletSuiteID) +{ + MMAFunctionServer* eventSource = reinterpret_cast(aEventSourceHandle); + + CMMAManager* manager = NULL; + TInt error = eventSource->ExecuteTrap(&CMMAManager::StaticCreateManagerL, + &manager, + aMIDletSuiteID); + ELOG1( EJavaMMAPI, "MMA::ManagerImpl createManager StaticCreateManagerL %d", + error); + if (error != KErrNone) + { + return error; + } + + TInt managerHandle( reinterpret_cast(manager)); + + error = eventSource->ExecuteTrap(MMAFunctionServer::StaticAddObjectFromHandleL, + eventSource, + managerHandle); + + ELOG1( EJavaMMAPI, "MMA::ManagerImpl createManager StaticAddObjectFromHandleL %d", + error); + + if (error != KErrNone) + { + // Adding manager to event source failed. + delete manager; + + // Error code will be returned to java + managerHandle = error; + } + LOG1( EJavaMMAPI, EInfo, "MMA::ManagerImpl createManager %d", + managerHandle); + return managerHandle; +} + + +LOCAL_C void InvokeConstructSvrL(MMAFunctionServer* aEventSource) +{ + aEventSource->ConstructSvrL(); +} + +/* + * Class: javax_microedition_media_Manager + * Method: _getEventSource + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_ManagerImpl__1createEventSource +(JNIEnv* aJni, jobject aPeer) +{ + TInt eventSourceHandle = MMAFunctionServer::NewL(*aJni, aPeer); + if (eventSourceHandle > KErrNone) + { + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(eventSourceHandle); + + // third phase construction + TInt error = eventSource->ExecuteTrap(&InvokeConstructSvrL, + eventSource); + if (error != KErrNone) + { + eventSourceHandle = error; + } + } + LOG1( EJavaMMAPI, EInfo, "MMA::ManagerImpl createEventSource %d", + eventSourceHandle); + return eventSourceHandle; +} + +/** + * Local function which can be used to call CMMAManager class methods. + * Type of of the function pointer must be + * void CMMAManager::aFuncL( RPointerArray< HBufC >&, const TDesC& ) + * Java String array will be created and set to aArray variable. + * + * @param aManager CMMAManager instance. + * @param aFuncL Pointer to the CMMAManager method. + * @param aJni Used to create an array. + * @param aArray Values got from aFuncL will be copied to this array. + * @param aParam Parameter that will be passed to aFuncL method. + */ +LOCAL_C void GetObjectArrayL(MMAFunctionServer* aEventSource, + CMMAManager* aManager, + void (CMMAManager::*aFuncL)(const TDesC&, + CDesC16Array&), + JNIEnv* aJni, + jobjectArray* aArray, + const TDesC* aParam) +{ + // Temporary descriptor array to be copied to Java array. + CDesC16ArrayFlat* values = new(ELeave) CDesC16ArrayFlat( + KMMADefaultArrayGranularity); + CleanupStack::PushL(values); + + // Call void CMMAManager::aFuncL( const TDesC&, RPointerArray< HBufC >& ) + // method. Method can leave. + // Elements of the array will be owned by this method. + (aManager->*aFuncL)(*aParam, *values); + + // JNI interface pointer can't be passed to different thread, so + // it is needed to get valid JNI interface pointer for Event Server thread + aJni =aEventSource->getValidJniEnv(); + + // Create new java String array and copy values from the values array + *aArray = MMAPIUtils::CopyToNewJavaStringArrayL(*aJni, *values); + CleanupStack::PopAndDestroy(values); +} + + +/* + * Class: javax_microedition_media_Manager + * Method: _getSupportedContentTypes + * Signature: (II)[[B + */ +JNIEXPORT jobjectArray JNICALL Java_com_nokia_microedition_media_ManagerImpl__1getSupportedContentTypes +(JNIEnv* aJni, + jclass, + jint aEventSourceHandle, + jint aManagerHandle, + jstring aProtocol) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer * >(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager *>(aManagerHandle); + + jobjectArray contentTypes = NULL; + + // Create descritor from Java String. + // JStringUtils is derived from TPtrC16 and is save to cast to TDesC + JStringUtils tmp(*aJni, aProtocol); + const TDesC* protocol = &tmp; + if (aProtocol == NULL) + { + protocol = &KNullDesC; + } + + // Call manager->GetSupportedContentTypesL and create Java array. + TInt err = eventSource->ExecuteTrap(&GetObjectArrayL, + eventSource, + manager, + &CMMAManager::GetSupportedContentTypesL, + aJni, + &contentTypes, + protocol); + + if (err != KErrNone) + { + // Something failed. Returning NULL, because contentTypes array may not + // be complete. contentTypes array is left for carbage collertor, + // because it can't be released. + return NULL; + } + return contentTypes; +} + +/* + * Class: javax_microedition_media_Manager + * Method: _getSupportedProtocols + * Signature: (II)[[B + */ +JNIEXPORT jobjectArray JNICALL Java_com_nokia_microedition_media_ManagerImpl__1getSupportedProtocols +(JNIEnv* aJni, + jclass, + jint aEventSourceHandle, + jint aManagerHandle, + jstring aContentType) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager *>(aManagerHandle); + + jobjectArray protocols = NULL; + + // Create descritor from Java String. + // JStringUtils is derived from TPtrC16 and is save to cast to TDesC + JStringUtils tmp(*aJni, aContentType); + const TDesC* contentType = &tmp; + if (aContentType == NULL) + { + contentType = &KNullDesC; + } + + // Call manager->GetSupportedProtocolsL and create Java array. + TInt err = eventSource->ExecuteTrap(&GetObjectArrayL, + eventSource, + manager, + &CMMAManager::GetSupportedProtocolsL, + aJni, + &protocols, + contentType); + if (err != KErrNone) + { + // Something failed. Returning NULL, because contentTypes array may not + // be complete. contentTypes array is left for carbage collertor, + // because it can't be released. + return NULL; + } + return protocols; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/metadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/metadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAMetaDataControl +* +*/ + + +#include +#include "com_nokia_microedition_media_control_MetaDataControl.h" + +#include "mmafunctionserver.h" +#include "cmmametadatacontrol.h" +#include "s60commonutils.h" +#include "jstringutils.h" +using namespace java::util; + +//#include "mmapiutils.h" + + +/* ...getKeyCount + * + * Returns the number of metadata keys or symbian error code + */ + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_MetaDataControl__1getKeysCount +(JNIEnv* /*aJniEnv*/, jobject, jint aEventSourceHandle, jint aMetaDataControlHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAMetaDataControl* metaDataControl = + reinterpret_cast< CMMAMetaDataControl* >(aMetaDataControlHandle); + + TInt keys; + TInt err = eventSource->ExecuteTrap(&CMMAMetaDataControl::StaticKeysCountL, metaDataControl, &keys); + + return err == KErrNone ? keys : err; +} + + +/* ... getKey + * + * Get the key name at the given index from the actual native implementation. If no key is available, + * return null. + * + * The ownership of the native data is received from the actual native implementation. + * The data is duplicated to the Java side and the native data is destroyed here. + */ + +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_control_MetaDataControl__1getKey +(JNIEnv* aJniEnv, jobject, jint aEventSourceHandle, jint aMetaDataControlHandle, jint aIndex) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAMetaDataControl* metaDataControl = + reinterpret_cast< CMMAMetaDataControl* >(aMetaDataControlHandle); + + HBufC* key = NULL; + jstring javaStr = NULL; + + TInt err = eventSource->ExecuteTrap(&CMMAMetaDataControl::StaticKeyL, metaDataControl, &key, aIndex); + + if (err == KErrNone) + { + javaStr = S60CommonUtils::NativeToJavaString(*aJniEnv, key->Des()); + } + delete key; + + return javaStr; +} + +/* ...getKeyValue + * + * Get the value of the given key from the actual native implementation. If no key is available, + * return null (as specified in the MetaDataControl interface). + * + * The ownership of the native data is received from the actual native implementation. + * The data is duplicated to the Java side and the native data is destroyed here. + */ + +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_control_MetaDataControl__1getKeyValue +(JNIEnv* aJniEnv, jobject, jint aEventSourceHandle, jint aMetaDataControlHandle, jstring aKey) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMetaDataControl* metaDataControl = + reinterpret_cast< CMMAMetaDataControl* >(aMetaDataControlHandle); + + HBufC* value = NULL; + JStringUtils key(*aJniEnv, aKey); + + TInt retVal = eventSource->ExecuteTrap( + &CMMAMetaDataControl::StaticKeyValueL, + metaDataControl, + &value, + (TDesC*) &key); + + jstring retString = NULL; + + if (KErrNone == retVal) + { + retString = S60CommonUtils::NativeToJavaString(*aJniEnv, *value); + } + + delete value; + + return retString; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/midicontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/midicontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,301 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAMIDIControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_MIDIControl.h" +#include "mmafunctionserver.h" +#include "cmmamidicontrol.h" +#include + +/** + * Local function which is used to call CMMAMIDIControl class method. + * Type of of the function pointer must be + * void CMMAMIDIControl::aFunc( TInt, TInt, TInt ) + * + * @param aMIDIControl CMMAMIDIControl pointer. + * @param aFunc Pointer to the CMMAMIDIControl method. + * @param aParam1 Parameter passed to the aFunc. + * @param aParam2 Parameter passed to the aFunc. + * @param aParam3 Parameter passed to the aFunc. + */ +LOCAL_C void ReturnVoidParam3IntFuncL( + CMMAMIDIControl* aMIDIControl, + void (CMMAMIDIControl::*aFuncL)(TInt, TInt, TInt), + TInt aParam1, + TInt aParam2, + TInt aParam3) +{ + // call TInt CMMAMIDIControl::aFunc( TInt, TInt, TInt ) method. + (aMIDIControl->*aFuncL)(aParam1, aParam2, aParam3); +} + +/** + * Implements generated JNI function prototype. + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_MIDIControl__1setProgram +( + JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aChannel, + jint aBank, + jint aProgram) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDIControl* midiControl = + reinterpret_cast< CMMAMIDIControl *>(aControlHandle); + + TInt error; + error = eventSource->ExecuteTrap(&ReturnVoidParam3IntFuncL, + midiControl, + &CMMAMIDIControl::SetProgramL, + aChannel, + aBank, + aProgram); + + return error; +} + +/** + * Local function which is used to call CMMAMIDIControl class method. + * Type of of the function pointer must be + * TInt CMMAMIDIControl::aFunc( TInt ) + * + * @param aMIDIControl CMMAMIDIControl pointer. + * @param aFunc Pointer to the CMMAMIDIControl method. + * @param aData Parameter passed to the aFunc. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntParamIntFuncL( + CMMAMIDIControl* aMIDIControl, + TInt(CMMAMIDIControl::*aFuncL)(TInt aData), + TInt aData, + TInt* aReturnValue) +{ + // call TInt CMMAMIDIControl::aFunc( TDesC* aData ) method. + *aReturnValue = (aMIDIControl->*aFuncL)(aData); +} + +/** + * Implements generated JNI function prototype. + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_MIDIControl__1getChannelVolume +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aChannel) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + CMMAMIDIControl* midiControl = + reinterpret_cast< CMMAMIDIControl *>(aControlHandle); + + + TInt returnValue = 0; + TInt error; + + error = eventSource->ExecuteTrap(&ReturnIntParamIntFuncL, + midiControl, + &CMMAMIDIControl::ChannelVolumeL, + aChannel, + &returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * Local function which is used to call CMMAMIDIControl class method. + * Type of of the function pointer must be + * void CMMAMIDIControl::aFunc( TInt, TInt ) + * + * @param aMIDIControl CMMAMIDIControl pointer. + * @param aFunc Pointer to the CMMAMIDIControl method. + * @param aParam1 Parameter passed to the aFunc. + * @param aParam2 Parameter passed to the aFunc. + */ +LOCAL_C void ReturnVoidParamIntIntFuncL( + CMMAMIDIControl* aMIDIControl, + void (CMMAMIDIControl::*aFuncL)(TInt, TInt), + TInt aParam1, + TInt aParam2) +{ + // call TInt CMMAMIDIControl::aFunc( TInt, TInt ) method. + (aMIDIControl->*aFuncL)(aParam1, aParam2); +} + +/** + * Implements generated JNI function prototype. + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_MIDIControl__1setChannelVolume +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aChannel, + jint aVolume) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDIControl* midiControl = + reinterpret_cast< CMMAMIDIControl *>(aControlHandle); + + TInt error = eventSource->ExecuteTrap(&ReturnVoidParamIntIntFuncL, + midiControl, + &CMMAMIDIControl::SetChannelVolumeL, + aChannel, + aVolume); + + return error; +} + +/** + * Local function which can be used to call CMMAMIDIControl class methods. + * Type of of the function pointer must be + * TInt CMMAMIDIControl::aFunc( TDesC* aData ) + * + * @param aMIDIControl CMMAMIDIControl pointer. + * @param aFunc Pointer to the CMMAMIDIControl method. + * @param aData Parameter passed to the aFunc. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void SendMIDIEventFuncL( + CMMAMIDIControl* aMIDIControl, + TInt(CMMAMIDIControl::*aFuncL)(const TDesC8* aData), + const TDesC8* aData, + TInt* aReturnValue) +{ + // call TInt CMMAMIDIControl::aFunc( TDesC* aData ) method. + *aReturnValue = (aMIDIControl->*aFuncL)(aData); +} + +/** + * Implements generated JNI function prototype. + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_MIDIControl__1sendMidiEvent +(JNIEnv* aJni, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jbyteArray aData, + jint aOffset, + jint aLength) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAMIDIControl* midiControl = + reinterpret_cast< CMMAMIDIControl* >(aControlHandle); + + // Get pointer to Java data + jbyte* data = aJni->GetByteArrayElements(aData, NULL); + + // Assert only in debug builds, array size must be checked in Java. + __ASSERT_DEBUG(aJni->GetArrayLength(aData) >= aOffset + aLength && + aOffset >= 0 && + aLength > 0, + User::Invariant()); + + // Create descriptor from Java data starting from offset + jbyte* tempJbyte = &data[ aOffset ]; + TUint8* tempPtr = (TUint8*) tempJbyte; + TPtrC8 dataPtr(tempPtr, aLength); + + TInt returnValue = 0; + + TInt err = eventSource->ExecuteTrap(&SendMIDIEventFuncL, + midiControl, + &CMMAMIDIControl::SendMIDIEventL, + (const TDesC8*)(&dataPtr), + &returnValue); + + // Java bytes are not needed anymore + aJni->ReleaseByteArrayElements(aData, data, 0); + + if (err != KErrNone) + { + // return error code to Java + returnValue = err; + } + + return returnValue; +} + +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_MIDIControl__1reInitializeMidi +(JNIEnv* aJni, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jbyteArray aMidiSequence, + jint aOffset, + jint aLength) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAMIDIControl* midiControl = + reinterpret_cast< CMMAMIDIControl* >(aControlHandle); + + // Assert only in debug builds, array size must be checked in Java. + __ASSERT_DEBUG(aJni->GetArrayLength(aMidiSequence) >= aOffset + aLength && + aOffset >= 0 && + aLength > 0, + User::Invariant()); + + // Get pointer to Java data + jbyte* data = aJni->GetByteArrayElements(aMidiSequence, NULL); + + // Create descriptor from Java data starting from offset + jbyte* tempJbyte = &data[ aOffset ]; + TUint8* tempPtr = (TUint8*) tempJbyte; + TPtrC8 dataPtr(tempPtr, aLength); + + // SendMIDIEventFuncL has suitable enough footprint for this call too. + // Return value is not used but needs to be there for method footprint. + + TInt returnValue = 0; + TInt err = eventSource->ExecuteTrap(&SendMIDIEventFuncL, + midiControl, + &CMMAMIDIControl::ReInitializeMidiL, + (const TDesC8*)(&dataPtr), + &returnValue); + + // Release Java bytes + aJni->ReleaseByteArrayElements(aMidiSequence, data, 0); + return err; +} + + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/mmafunctionserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/mmafunctionserver.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,245 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class provides CJavaEventSource services +* +*/ + + +// INCLUDE FILES +#include // DEBUG +#include +#include + +#include "mmafunctionserver.h" +#include "cmmaevent.h" +#include "cmmaplayer.h" +#include "mmmaplayerinstanceobserver.h" +#ifdef RD_JAVA_VOLUME_CONTROL +#include "cmmaglobalvolume.h" +#endif // RD_JAVA_VOLUME_CONTROL + +MMAFunctionServer::MMAFunctionServer(JNIEnv& aJni, jobject aPeer): java::util::FunctionServer("JavaMMAPIFunctionServer") +{ + LOG( EJavaMMAPI, EInfo, "++MMAFunctionServer::MMAFunctionServer"); + createServerToNewThread(); + attachToVm(aJni, aPeer); + mVmAttached = true; + iServer = reinterpret_cast(this); +} + +MMAFunctionServer::~MMAFunctionServer() +{ + LOG( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::~MMAFunctionServer()"); + if (mVmAttached) + { + detachFromVm(); + } + stopServer(); +#ifdef RD_JAVA_VOLUME_CONTROL + delete iGlobalVolume; +#endif // RD_JAVA_VOLUME_CONTROL +} + +TInt MMAFunctionServer::NewL(JNIEnv& aJni, jobject aPeer) +{ + + MMAFunctionServer* self = new(ELeave) MMAFunctionServer(aJni,aPeer); + self->ConstructL(aJni,aPeer); + return reinterpret_cast(self); +} +void MMAFunctionServer::ConstructL(JNIEnv& aJni, + jobject aPeer + ) +{ + LOG( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::ConstructL +"); + aJni.GetJavaVM(&iJavaVM); // Get pointer to VM + LOG( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::ConstructL -"); +} + +java::util::FunctionServer* MMAFunctionServer::getFunctionServer() const +{ + LOG( EJavaMMAPI, EInfo, "++getFunctionServer1"); + JELOG2(EJavaMMAPI); + return iServer; +} +JNIEnv* MMAFunctionServer::getValidJniEnv() + { + JELOG2(EJavaLocation); + return mJniEnv; + } +jobject MMAFunctionServer::getPeer() + { + return mJavaPeerObject; + } + +void MMAFunctionServer::ConstructSvrL() +{ + // creating fbs session + User::LeaveIfError(RFbsSession::Connect()); + iFbsSessionConnected = ETrue; + LOG( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::ConstructSvrL ok"); +} + +EXPORT_C void MMAFunctionServer::StaticAddObjectFromHandleL( + MMAFunctionServer* aEventSource, + TInt aHandle) +{ + aEventSource->AddObjectFromHandleL(aHandle); +} + +void MMAFunctionServer::AddPlayerL(CMMAPlayer* aPlayer) +{ + if (iInstanceObserver) + { + iInstanceObserver->AddPlayerNotifyL(aPlayer); + } +#ifdef RD_JAVA_VOLUME_CONTROL + if (iGlobalVolume) + { + iGlobalVolume->AddPlayerL(aPlayer); + } +#endif // RD_JAVA_VOLUME_CONTROL + TInt err = iPlayers.Append(aPlayer); + + if (err != KErrNone) + { + // There was no memory to add new player to array, + // player must be removed from instance observer. + if (iInstanceObserver) + { + iInstanceObserver->RemovePlayerNotify(aPlayer); + } +#ifdef RD_JAVA_VOLUME_CONTROL + if (iGlobalVolume) + { + iGlobalVolume->RemovePlayer(aPlayer); + } +#endif // RD_JAVA_VOLUME_CONTROL + User::Leave(err); + } +} + +void MMAFunctionServer::DisposePlayer(CMMAPlayer* aPlayer) +{ + TInt index = iPlayers.Find(aPlayer); + if (index != KErrNotFound) + { + if (iInstanceObserver) + { + iInstanceObserver->RemovePlayerNotify(aPlayer); + } +#ifdef RD_JAVA_VOLUME_CONTROL + if (iGlobalVolume) + { + iGlobalVolume->RemovePlayer(aPlayer); + } +#endif // RD_JAVA_VOLUME_CONTROL + delete iPlayers[ index ]; + + // remove object from list + iPlayers.Remove(index); + } +} + +EXPORT_C void MMAFunctionServer::SetPlayerInstanceObserver( + MMMAPlayerInstanceObserver* aObserver) +{ + iInstanceObserver = aObserver; +} + +EXPORT_C RPointerArray< CMMAPlayer >& MMAFunctionServer::Players() +{ + return iPlayers; +} + +void MMAFunctionServer::Release() +{ + // If player instance observer is added to event source, remove all + // players from observer before deleting those. + if (iInstanceObserver) + { + for (TInt i = 0; i < iPlayers.Count(); i++) + { + iInstanceObserver->RemovePlayerNotify(iPlayers[ i ]); +#ifdef RD_JAVA_VOLUME_CONTROL + if (iGlobalVolume) + { + iGlobalVolume->RemovePlayer(iPlayers[ i ]); + } +#endif // RD_JAVA_VOLUME_CONTROL + } + } + + iPlayers.ResetAndDestroy(); +} + +void MMAFunctionServer::AddObjectFromHandleL(TInt aHandle) +{ + User::LeaveIfError(iObjects.Append(reinterpret_cast< CBase* >(aHandle))); +} + + +void MMAFunctionServer::FinalizeSvr() +{ + LOG1( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::FinalizeSvr() object count = %d", + iObjects.Count()); + LOG1( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::FinalizeSvr() player count = %d", + iPlayers.Count()); + + // After object array alements are deleted all external references to + // player objects are removed and player array can be deleted. + iObjects.ResetAndDestroy(); + iPlayers.ResetAndDestroy(); + + if (iFbsSessionConnected) + { + RFbsSession::Disconnect(); + iFbsSessionConnected = EFalse; + } + LOG( EJavaMMAPI, EInfo, "MMA::MMAFunctionServer::FinalizeSvr() ok"); +} + + +void MMAFunctionServer::PostEvent(CMMAEvent* aEvent, TInt /*aPriority*/) +{ + LOG( EJavaMMAPI, EInfo, "MMAFunctionServer::PostEvent"); + aEvent->Dispatch(*mJniEnv); +} + +CMMAPlayer* MMAFunctionServer::FindPlayer(TInt aPlayerHandle) +{ + LOG( EJavaMMAPI, EInfo, "MMAFunctionServer::FindPlayer"); + CMMAPlayer* player = reinterpret_cast< CMMAPlayer* >(aPlayerHandle); + TInt index = iPlayers.Find(player); + if (index != KErrNotFound) + { + player = iPlayers[ index ]; + LOG( EJavaMMAPI, EInfo, "MMAFunctionServer::FindPlayer: player found"); + } + else + { + LOG( EJavaMMAPI, EInfo, "MMAFunctionServer::FindPlayer: player not found"); + player = NULL; + } + return player; +} +#ifdef RD_JAVA_VOLUME_CONTROL +void MMAFunctionServer::SetGlobalVolume(CMMAGlobalVolume* aGlobalVolume) +{ + delete iGlobalVolume; + iGlobalVolume = aGlobalVolume; +} +#endif // RD_JAVA_VOLUME_CONTROL + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/nativeplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/nativeplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,234 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has NativePlayerFactory JNI functions +* +*/ + +#include + +#include "com_nokia_microedition_media_NativePlayerFactory.h" +#include "cmmamanager.h" +#include "cmmaplayer.h" + +#include "s60commonutils.h" +#include "jstringutils.h" +using namespace java::util; + +/** + * Adds player to event source. If player could not be created + * handle KErrNone indicates in Java side that there wasn't suitable factory. + */ +LOCAL_C void HandleCreatePlayerL(CMMAPlayer* aPlayer, + MMAFunctionServer* aEventSource, + TInt* aHandle) +{ + if (aPlayer) + { + // Player was created, add it to event source + CleanupStack::PushL(aPlayer); + aEventSource->AddPlayerL(aPlayer); + *aHandle = reinterpret_cast(aPlayer); + CleanupStack::Pop(aPlayer); + } + else + { + // Data was not supported and there is no error. + // Return KErrNone to java side + *aHandle = KErrNone; + } +} + +/** + * Local function that calls CMMAManager's CreatePlayerL method. + */ +LOCAL_C void CreatePlayerHeaderDataL(CMMAManager* aManager, + MMAFunctionServer* aEventSource, + const TDesC8* aHeaderData, + TInt* aHandle) +{ + HandleCreatePlayerL(aManager->CreatePlayerL(*aHeaderData), + aEventSource, + aHandle); +} + +/** + * JNI function from NativePlayerFactory class. + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_NativePlayerFactory__1createPlayerHeaderData +(JNIEnv* aJni, jclass, + jint aEventSourceHandle, jint aManagerHandle, + jbyteArray aHeaderData) +{ + // Development time check. + __ASSERT_DEBUG((aEventSourceHandle > 0) && (aManagerHandle > 0), User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager *>(aManagerHandle); + + // Returning just KErrNone if there is no header data + TInt playerHandle = KErrNone; + if (aHeaderData) + { + // Get pointer to Java header data + jbyte* data = aJni->GetByteArrayElements(aHeaderData, NULL); + // if data is null Java data could not be obtained to native and + // KErrNoMemory is returned to Java + if (!data) + { + return KErrNoMemory; + } + + TInt headerDataLength = aJni->GetArrayLength(aHeaderData); + TPtrC8 headerData((TUint8*)data, headerDataLength); + TInt err = eventSource->ExecuteTrap(&CreatePlayerHeaderDataL, + manager, + eventSource, + (const TDesC8*)&headerData, + &playerHandle); + + // release bytes got with GetByteArrayElements + aJni->ReleaseByteArrayElements(aHeaderData, + data, + 0); + if (err != KErrNone) + { + // Leave occured return error code to Java + playerHandle = err; + ELOG1( EJavaMMAPI, "MMA::NativePlayerFactory createPlayerHeaderData err %d", + playerHandle); + } + } + return playerHandle; +} + +/** + * Local function that calls CMMAManager's CreatePlayerL method. + */ +LOCAL_C void CreatePlayerLocatorL(CMMAManager* aManager, + MMAFunctionServer* aEventSource, + const TDesC* aProtocol, + const TDesC* aMiddlePart, + const TDesC* aParameters, + TInt* aHandle) +{ + HandleCreatePlayerL(aManager->CreatePlayerL(*aProtocol, + *aMiddlePart, + *aParameters), + aEventSource, + aHandle); +} + +/** + * JNI function from NativePlayerFactory class. + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_NativePlayerFactory__1createPlayerLocator +(JNIEnv* aJni, jclass, + jint aEventSourceHandle, jint aManagerHandle, + jstring aProtocol, jstring aMiddlePart, jstring aParameters) +{ + // Development time check. + __ASSERT_DEBUG((aEventSourceHandle > 0) && (aManagerHandle > 0), User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager *>(aManagerHandle); + + // Get Java strings to native + JStringUtils protocol(*aJni, aProtocol); + JStringUtils middlePart(*aJni, aMiddlePart); + + // If Java parameters is null, empty descriptor will be given to + // CreatePlayerL method. + TPtrC parameters(KNullDesC); + JStringUtils* tmp = NULL; + if (aParameters != NULL) + { + tmp = new JStringUtils(*aJni, aParameters); + if (tmp) + { + parameters.Set(*tmp); + } + else + { + // failed to create string + return KErrNoMemory; + } + } + + TInt playerHandle = KErrNoMemory; + TInt err = eventSource->ExecuteTrap(&CreatePlayerLocatorL, + manager, + eventSource, + (const TDesC*)&protocol, + (const TDesC*)&middlePart, + (const TDesC*)¶meters, + &playerHandle); + delete tmp; + if (err != KErrNone) + { + // Leave occured return error code to Java + playerHandle = err; + ELOG1( EJavaMMAPI, "MMA::NativePlayerFactory createPlayerLocator err %d", + playerHandle); + } + return playerHandle; +} + +/** + * Local function that calls CMMAManager's CreatePlayerL method. + */ +LOCAL_C void CreatePlayerContentTypeL(CMMAManager* aManager, + MMAFunctionServer* aEventSource, + const TDesC* aContentType, + TInt* aHandle) +{ + HandleCreatePlayerL(aManager->CreatePlayerL(*aContentType), + aEventSource, + aHandle); +} + +/** + * JNI function from NativePlayerFactory class. + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_NativePlayerFactory__1createPlayerContentType +(JNIEnv* aJni, jclass, + jint aEventSourceHandle, jint aManagerHandle, + jstring aContentType) +{ + // Development time check. + __ASSERT_DEBUG((aEventSourceHandle > 0) && (aManagerHandle > 0), User::Invariant()); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + CMMAManager* manager = reinterpret_cast< CMMAManager* >(aManagerHandle); + + JStringUtils contentType(*aJni, aContentType); + TInt playerHandle = KErrNoMemory; + TInt err = eventSource->ExecuteTrap(&CreatePlayerContentTypeL, + manager, + eventSource, + (const TDesC*)&contentType, + &playerHandle); + if (err != KErrNone) + { + // Leave occured return error code to Java + playerHandle = err; + ELOG1( EJavaMMAPI, "MMA::NativePlayerFactory createPlayerContentType err %d", + playerHandle); + } + return playerHandle; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/outputstreamwriter.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/outputstreamwriter.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAOutputStream +* +*/ + + +//#include "jutils.h" +//#include "mmapiutils.h" +#include "com_nokia_microedition_media_protocol_OutputStreamWriter.h" +#include "cmmaoutputstream.h" +#include "mmafunctionserver.h" + +// If eventsource is already disposed, then do nothing +#define CHECK_HANDLE(x, j) { if ( !( x ) || ( ( x )->Players().Count() == 0 ) ) { return ( j ); } } + +LOCAL_C void ReadDataL(MMAFunctionServer* aEventSource, + TInt aPlayer, + CMMAOutputStream* aOutputStream, + TUint8* aOutputBuffer, + TInt* aOutputBufferSize, + TInt* aReadStatus) +{ + if (!aEventSource->FindPlayer(aPlayer)) + { + // Native object was already deleted + User::Leave(KErrBadHandle); + } + + aOutputStream->ReadDataL(aOutputBuffer, aOutputBufferSize, aReadStatus); +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_protocol_OutputStreamWriter__1readData +(JNIEnv* aJni, jclass, jint aOutputStream, jint aEventSource, + jbyteArray aOutputBuffer, jintArray aOutputBufferSize, jint aLength, jint aPlayerHandle) +{ + MMAFunctionServer* eventSource = reinterpret_cast< MMAFunctionServer* >(aEventSource); + CHECK_HANDLE(eventSource, KErrNone); + + CMMAOutputStream* outputStream = reinterpret_cast< CMMAOutputStream* >(aOutputStream); + + TInt readStatus; + jbyte* outputBuffer = aJni->GetByteArrayElements(aOutputBuffer, NULL); + + // NULL is returned if there is not enough memory + if (!outputBuffer) + { + return KErrNoMemory; + } + + jint* outputBufferSize = aJni->GetIntArrayElements(aOutputBufferSize, NULL); + if (!outputBufferSize) + { + // outputBuffer was already allocated + aJni->ReleaseByteArrayElements(aOutputBuffer, outputBuffer, JNI_ABORT); + return KErrNoMemory; + } + + *outputBufferSize = aLength; // size of the buffer + + TInt err = eventSource->ExecuteTrap(ReadDataL, + eventSource, + aPlayerHandle, + outputStream, + (TUint8*) outputBuffer, + outputBufferSize, // returns readed size + &readStatus); + + aJni->ReleaseByteArrayElements(aOutputBuffer, outputBuffer, JNI_COMMIT); + aJni->ReleaseIntArrayElements(aOutputBufferSize, outputBufferSize, JNI_COMMIT); + + if (err != KErrNone) + { + return err; + } + + // Tells if there's more data available or not + return readStatus; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/pitchcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/pitchcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,196 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAPitchControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_PitchControl.h" +#include "mmafunctionserver.h" +#include "cmmamidipitchcontrol.h" +#include + +static const int KPitchOffset = 1000000; + +/** + * Local function which can be used to call CMMAPitchControl class methods. + * Type of of the function pointer must be + * TInt CMMAPitchControl::aFunc( TInt aData ) + * + * @param aPitchControl CMMAPitchControl pointer. + * @param aFunc Pointer to the CMMAPitchControl method. + * @param aData Parameter to passed to the aFunc method + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntParamIntFuncL(CMMAMIDIPitchControl* aPitchControl, + TInt(CMMAMIDIPitchControl::*aFuncL)(TInt), + TInt aData, + TInt* aReturnValue) +{ + // call TInt CMMAPitchControl::aFunc( TInt aData ) method. + *aReturnValue = (aPitchControl->*aFuncL)(aData); +} + +/** + * Local function which can be used to call CMMAPitchControl class methods. + * Type of of the function pointer must be + * TInt CMMAPitchControl::aFunc() + * + * @param aPitchControl CMMAPitchControl pointer. + * @param aFunc Pointer to the CMMAPitchControl method. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntFuncL(CMMAMIDIPitchControl* aPitchControl, + TInt(CMMAMIDIPitchControl::*aFuncL)(), + TInt* aReturnValue) +{ + // call TInt CMMAPitchControl::aFunc() method. + *aReturnValue = (aPitchControl->*aFuncL)(); +} + +// +// JNI functions. Prototypes are generated and commented in Java class +// com_nokia_microedition_media_control_PitchControl +// + +/** + * JNI function from com.nokia.microedition.media.control.PitchControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_PitchControl__1setPitch +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aPitch) // parameter boundary is checked in Java side. +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDIPitchControl* PitchControl = + reinterpret_cast< CMMAMIDIPitchControl *>(aControlHandle); + + // Value returned from SetPitch method will be assigned to returnValue. + TInt returnValue = 0; + + // Setting Pitch will not leave, it just assigns default + // value to the returnValue variable. + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntParamIntFuncL, + PitchControl, + &CMMAMIDIPitchControl::SetPitchL, + aPitch, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "PitchControl__1setPitch return value %d", returnValue); + + return (error == KErrNone) ? (returnValue+KPitchOffset) : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.PitchControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_PitchControl__1getMinPitch +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAMIDIPitchControl* PitchControl = + reinterpret_cast< CMMAMIDIPitchControl* >(aControlHandle); + + TInt returnValue = 0; + + // Get value or the default. + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + PitchControl, + &CMMAMIDIPitchControl::MinPitchL, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "PitchControl__1setPitch return value %d", returnValue); + + return (error == KErrNone) ? (returnValue+KPitchOffset) : error; +} + + +/** + * JNI function from com.nokia.microedition.media.control.PitchControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_PitchControl__1getMaxPitch +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDIPitchControl* PitchControl = + reinterpret_cast< CMMAMIDIPitchControl* >(aControlHandle); + + TInt returnValue = 0; + TInt error; + + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + PitchControl, + &CMMAMIDIPitchControl::MaxPitchL, + &returnValue); + LOG1( EJavaMMAPI, EInfo, "PitchControl__1getMaxRate return value %d", returnValue); + + return (error == KErrNone) ? (returnValue+KPitchOffset) : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.PitchControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_PitchControl__1getPitch +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDIPitchControl* PitchControl = + reinterpret_cast< CMMAMIDIPitchControl* >(aControlHandle); + + TInt returnValue = 0; + TInt error; + + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + PitchControl, + &CMMAMIDIPitchControl::PitchL, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "PitchControl__1getPitch return value %d", returnValue); + + return (error == KErrNone) ? (returnValue+KPitchOffset) : error; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/player.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/player.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,547 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAPlayer +* +*/ + + +//#include +#include "com_nokia_microedition_media_PlayerImpl.h" + +#include "mmafunctionserver.h" +#include "cmmaplayer.h" +#include "s60commonutils.h" +#include + +using namespace java::util; + +// If eventsource is already disposed, then do nothing +#define CHECK_HANDLE(x, j) { if ( !( x ) || ( ( x )->Players().Count() == 0 ) ) { return ( j ); } } +/* + * Wrappers for calling non static methods + */ + +TInt VoidFunc(TInt aPlayer, MMAFunctionServer* aEventSource, + TInt(CMMAPlayer::*aFunc)()) +{ + CMMAPlayer* p = aEventSource->FindPlayer(aPlayer); + if (p) + { + return (p->*aFunc)(); + } + else + { + return KErrBadHandle; + } +} + +void BoolFuncL(TInt aPlayer, MMAFunctionServer* aEventSource, + void(CMMAPlayer::*aFunc)(TBool), + TBool aValue) +{ + CMMAPlayer* p = aEventSource->FindPlayer(aPlayer); + if (p) + { + (p->*aFunc)(aValue); + } + // ignore call if player is not found +} + +void VVoidFuncL(TInt aPlayer, MMAFunctionServer* aEventSource, void(CMMAPlayer::*aFunc)()) +{ + CMMAPlayer* p = aEventSource->FindPlayer(aPlayer); + if (p) + { + (p->*aFunc)(); + } + // ignore call if player is not found +} + +void IntFunc(TInt aPlayer, + MMAFunctionServer* aEventSource, + void(CMMAPlayer::*aFunc)(TInt), + TInt aData) +{ + CMMAPlayer* p = aEventSource->FindPlayer(aPlayer); + if (p) + { + (p->*aFunc)(aData); + } + // ignore call if player is not found +} + +void TInt64Func(TInt aPlayer, MMAFunctionServer* aEventSource, + void(CMMAPlayer::*aFunc)(TInt64* aData), + TInt64* aData) +{ + CMMAPlayer* p = aEventSource->FindPlayer(aPlayer); + if (p) + { + (p->*aFunc)(aData); + } + else + { + *aData = KErrBadHandle; + } +} + + + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _createPlayer + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1initPlayer +(JNIEnv* aJni, + jobject aObject, + jobject aListenerObject, + jint aEventSourceHandle, + jint aPlayerHandle) +{ + LOG(EJavaMMAPI,EInfo,"jni_PlayerImpl__1initPlayer Enter... 1"); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CHECK_HANDLE(eventSource, KErrNone); + + CMMAPlayer* player = reinterpret_cast< CMMAPlayer* >(aPlayerHandle); + + // init player + jobject playerObject = aJni->NewWeakGlobalRef(aObject); +LOG(EJavaMMAPI,EInfo,"jni_PlayerImpl__1initPlayer Enter... 5"); + TInt err = eventSource->ExecuteTrap(&CMMAPlayer::StaticInitPlayerL, + player, + eventSource, + playerObject, + eventSource->getValidJniEnv()); + if (err != KErrNone) + { + aJni->DeleteWeakGlobalRef((jweak)playerObject); + return err; + } + + // set player listener + jobject playerListener = aJni->NewWeakGlobalRef(aListenerObject); + err = eventSource->ExecuteTrap(&CMMAPlayer::StaticSetPlayerListenerObjectL, + player, + eventSource, + playerListener, + eventSource->getValidJniEnv(), + (MMMAEventPoster*)eventSource); + if (err != KErrNone) + { + aJni->DeleteWeakGlobalRef((jweak)playerListener); + } + return err; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _start + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1start +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "jni_PlayerImpl__1start..."); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + CHECK_HANDLE(eventSource, KErrNone); + TInt err = eventSource->ExecuteTrap(&VVoidFuncL, + aPlayer, + eventSource, + &CMMAPlayer::StartL); + LOG1(EJavaMMAPI,EInfo,"jni_PlayerImpl__1start Enter... 3, err = %d",err); + // complete java side request in case of leave. + if (err != KErrNone) + { + CMMAPlayer* p = eventSource->FindPlayer(aPlayer); + p->PostActionCompleted(err); // java start return + } + + return err; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _stop + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1stop +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt err = eventSource->ExecuteTrap(&BoolFuncL, + aPlayer, + eventSource, + &CMMAPlayer::StopL, + (TBool)ETrue); + return err; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _close + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1close +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + // if eventsource is already disposed, then do nothing + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + LOG( EJavaMMAPI, EInfo, "jni_Player.cpp__1close before &CMMAPlayer::CloseL"); + TInt err = eventSource->ExecuteTrap(&VVoidFuncL, + aPlayer, + eventSource, + &CMMAPlayer::CloseL); + ELOG1( EJavaMMAPI, "jni_Player.cpp__1close %d", err); + return err; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _prefetch + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1prefetch +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + ELOG( EJavaMMAPI, "jni_Player.cpp__1prefetch "); + MMAFunctionServer* eventSource = + //JavaUnhand< MMAFunctionServer >(aEventSource); + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt err = eventSource->ExecuteTrap(&VVoidFuncL, aPlayer, + eventSource, + &CMMAPlayer::PrefetchL); + + ELOG1( EJavaMMAPI, "jni_Player.cpp__1prefetch %d", err); + + return err; +} + + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _realize + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1realize +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt err = eventSource->ExecuteTrap(&VVoidFuncL, + aPlayer, eventSource, + &CMMAPlayer::RealizeL); + return err; +} + + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _setLoopCount + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1setLoopCount +(JNIEnv *, jclass, jint aEventSource, jint aPlayer, jint aLoopCount) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + eventSource->ExecuteV(&IntFunc, + aPlayer, eventSource, + &CMMAPlayer::SetLoopCount, + aLoopCount); + return KErrNone; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _duration + * Signature: (II)J + */ +JNIEXPORT jlong JNICALL Java_com_nokia_microedition_media_PlayerImpl__1duration +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt64 duration(0); + + TInt err = eventSource->ExecuteTrap(&TInt64Func, + aPlayer, eventSource, + &CMMAPlayer::GetDuration, + &duration); + if (err != KErrNone) + { + return err; + } + return *reinterpret_cast< jlong* >(&duration); +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _setMediaTime + * Signature: (IIJ)J + */ +JNIEXPORT jlong JNICALL Java_com_nokia_microedition_media_PlayerImpl__1setMediaTime +(JNIEnv *, jclass, jint aEventSource, jint aPlayer, jlong aNow) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + + TInt64 time = *reinterpret_cast< TInt64* >(&aNow); + + TInt err = eventSource->ExecuteTrap(&TInt64Func, + aPlayer, eventSource, + &CMMAPlayer::SetMediaTimeL, + &time); + + if (err != KErrNone) + { + ELOG1( EJavaMMAPI, "MMA::Java_com_nokia_microedition_media_PlayerImpl__1setMediaTime error %d ", + err); + return err; + } + return *reinterpret_cast< jlong* >(&time); +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _deallocate + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1deallocate +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt err = eventSource->ExecuteTrap(&VVoidFuncL, + aPlayer, eventSource, + &CMMAPlayer::DeallocateL); + return err; +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _getMediaTime + * Signature: (II)J + */ +JNIEXPORT jlong JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getMediaTime +(JNIEnv*, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + TInt64 mediaTime(0); + + TInt err = eventSource->ExecuteTrap(&TInt64Func, aPlayer, + eventSource, + &CMMAPlayer::GetMediaTime, + &mediaTime); + if (err != KErrNone) + { + return err; + } + return *reinterpret_cast< jlong* >(&mediaTime); +} + +/* + * Class: com_nokia_microedition_media_PlayerImpl + * Method: _getState + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getState +(JNIEnv *, jclass, jint aEventSource, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + +LOG(EJavaMMAPI,EInfo,"MMA::Java_com_nokia_microedition_media_PlayerImpl__1getState before finding player "); + CMMAPlayer* player = eventSource->FindPlayer(aPlayer); +LOG(EJavaMMAPI,EInfo,"MMA::Java_com_nokia_microedition_media_PlayerImpl__1getState after finding player "); + TInt state = CMMAPlayer::EClosed; + if (player != NULL) + { + state = player->State(); + } + +LOG1(EJavaMMAPI,EInfo,"MMA::Java_com_nokia_microedition_media_PlayerImpl__1getState state %d ", + state); + return state; +} + +/* + * + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1addSourceStream +(JNIEnv* aJni, jclass, jint aEventSource, jint aPlayer, jobject aReader) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + CMMAPlayer* player = eventSource->FindPlayer(aPlayer); + CMMASourceStream* sourceStream; + + jobject readerRef = aJni->NewWeakGlobalRef(aReader); + + TInt err = KErrNotFound; + if (player != NULL) + { + err = eventSource->ExecuteTrap(&CMMAPlayer::StaticAddSourceStreamL, + eventSource->getValidJniEnv(), + player, + eventSource, + readerRef, + &sourceStream); + } + if (err != KErrNone) + { + aJni->DeleteWeakGlobalRef((jweak)readerRef); + return err; + } + return reinterpret_cast(sourceStream); +} + + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getControlsCount +(JNIEnv*, jclass, jint aEventSourceHandle, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CHECK_HANDLE(eventSource, KErrNone); + + + TInt count = eventSource->Execute(&VoidFunc, + aPlayer, eventSource, + &CMMAPlayer::ControlCount); + return count; +} + + +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getControlClassName +(JNIEnv* aJniEnv, jclass, jint aEventSourceHandle, jint aControlHandle) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAControl* control = reinterpret_cast< CMMAControl* >(aControlHandle); + + const TDesC* name = eventSource->Execute(CMMAControl::ClassNameJni, + control); + return S60CommonUtils::NativeToJavaString(*aJniEnv, *name); +} + + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getControlHandle +(JNIEnv*, jclass, jint aEventSourceHandle, jint aPlayer, jint aIndex) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CHECK_HANDLE(eventSource, KErrNone); + + CMMAPlayer* player = eventSource->FindPlayer(aPlayer); + CMMAControl* control = NULL; + if (player) + { + control = eventSource->Execute(CMMAPlayer::StaticControl, + player, + aIndex); + } + else + { + return KErrBadHandle; + } + + return reinterpret_cast(control); +} + +LOCAL_C void DisposePlayer(MMAFunctionServer* aEventSource, + TInt aPlayer) +{ + CMMAPlayer* player = aEventSource->FindPlayer(aPlayer); + if (player) + { + aEventSource->DisposePlayer(player); + } + // else already disposed +} + +JNIEXPORT void JNICALL Java_com_nokia_microedition_media_PlayerImpl__1dispose +(JNIEnv*, jclass, jint aEventSourceHandle, jint aPlayer) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + // if eventsource is already disposed, then do nothing + if (!eventSource || eventSource->IsDisposed()) + { + return; + } + + eventSource->ExecuteV(&DisposePlayer, + eventSource, + aPlayer); +} + +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_PlayerImpl__1getContentType +(JNIEnv* aJni, jclass, + jint aPlayerHandle) +{ + CMMAPlayer* player = reinterpret_cast< CMMAPlayer* >(aPlayerHandle); + jstring contentType = NULL; + + // if content type is null, we just return NULL to Java + if (player->ContentType()) + { + // need to create Java String object + contentType = S60CommonUtils::NativeToJavaString(*aJni, *player->ContentType()); + } + return contentType; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/ratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/ratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,202 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMARateControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_RateControl.h" +#include "mmafunctionserver.h" +#include "cmmaratecontrol.h" +#include + +// +// Wrapper functions which are needed in event source execution. +// If method to be called can leave ExecuteTrap must be used, +// otherwise Execute and ExecuteV can be used. +// +// + +/** + * Local function which can be used to call CMMARateControl class methods. + * Type of of the function pointer must be + * TInt CMMARateControl::aFunc( TInt aData ) + * + * @param aRateControl CMMARateControl pointer. + * @param aFunc Pointer to the CMMARateControl method. + * @param aData Parameter to passed to the aFunc method + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntParamIntFuncL(CMMARateControl* aRateControl, + TInt(CMMARateControl::*aFuncL)(TInt), + TInt aData, + TInt* aReturnValue) +{ + // call TInt CMMARateControl::aFunc( TInt aData ) method. + *aReturnValue = (aRateControl->*aFuncL)(aData); +} + +/** + * Local function which can be used to call CMMARateControl class methods. + * Type of of the function pointer must be + * TInt CMMARateControl::aFunc() + * + * @param aRateControl CMMARateControl pointer. + * @param aFunc Pointer to the CMMARateControl method. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntFuncL(CMMARateControl* aRateControl, + TInt(CMMARateControl::*aFuncL)(), + TInt* aReturnValue) +{ + // call TInt CMMARateControl::aFunc() method. + *aReturnValue = (aRateControl->*aFuncL)(); +} + +// +// JNI functions. Prototypes are generated and commented in Java class +// com_nokia_microedition_media_control_RateControl +// + +/** + * JNI function from com.nokia.microedition.media.control.RateControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_RateControl__1getMinRate +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARateControl* RateControl = + reinterpret_cast< CMMARateControl *>(aControlHandle); + + TInt returnValue = 0; + + // Get value or the default. + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + RateControl, + &CMMARateControl::MinRateL, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "RateControl__1getMinRate return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.RateControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_RateControl__1getRate +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARateControl* RateControl = + reinterpret_cast< CMMARateControl *>(aControlHandle); + + + TInt returnValue = 0; + + // Get actual rate or the default value to the returnValue. + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + RateControl, + &CMMARateControl::RateL, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "RateControl__1getRate return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.RateControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_RateControl__1setRate +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aRate) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARateControl* RateControl = + reinterpret_cast< CMMARateControl *>(aControlHandle); + + // Return value will be actual rate set or default value if rate is not + // available. + TInt returnValue = 0; + + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntParamIntFuncL, + RateControl, + &CMMARateControl::SetRateL, + aRate, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "RateControl__1setRate return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.RateControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_RateControl__1getMaxRate +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARateControl* RateControl = + reinterpret_cast< CMMARateControl *>(aControlHandle); + + TInt returnValue = 0; + TInt error; + + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + RateControl, + &CMMARateControl::MaxRateL, + &returnValue); + LOG1( EJavaMMAPI, EInfo, "RateControl__1getMaxRate return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/recordcontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/recordcontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,235 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMARecordControl +* +*/ + + +#include + +#include + +#include "com_nokia_microedition_media_control_RecordControl.h" +#include "mmafunctionserver.h" +#include "cmmarecordcontrol.h" +#include "s60commonutils.h" +#include "jstringutils.h" +using namespace java::util; + + +void VVoidFuncL(CMMARecordControl* aControl, void(CMMARecordControl::*aFunc)()) +{ + (aControl->*aFunc)(); +} + +void TIntFuncL(CMMARecordControl* aControl, TInt(CMMARecordControl::*aFunc)(TInt), + TInt* aReturnValue) +{ + *aReturnValue = (aControl->*aFunc)(*aReturnValue); +} +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: int _startRecord( int aEventSourceHandle, int aRecordControlHandle ); + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1startRecord +(JNIEnv *, jclass, jint aEventSourceHandle, jint aRecordControlHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1startRecord"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl* >(aRecordControlHandle); + + return eventSource->ExecuteTrap(&VVoidFuncL, + recordControl, + &CMMARecordControl::StartRecordL); +} + +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: int _stopRecord( int aEventSourceHandle, int aRecordControlHandle ); + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1stopRecord +(JNIEnv *, jclass, jint aEventSourceHandle, jint aRecordControlHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1stopRecord"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl* >(aRecordControlHandle); + + return eventSource->ExecuteTrap(&VVoidFuncL, + recordControl, + &CMMARecordControl::StopRecordL); +} + +void CMMAOutputStreamFunc(void(CMMARecordControl::*aFunc)(CMMAOutputStream*),CMMARecordControl* aControl, + CMMAOutputStream* aOutputStream) +{ + (aControl->*aFunc)(aOutputStream); +} +/* + * Class: com_nokia_microedition_media_RecordControl + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1setRecordStream +(JNIEnv *aJni, jclass, jint aEventSourceHandle, jint aRecordControlHandle, jobject aOutputWriter) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1setRecordStream"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl* >(aRecordControlHandle); + + jobject writerRef = aJni->NewWeakGlobalRef(aOutputWriter); + CMMAOutputStream* outputStream; + + TInt err = eventSource->ExecuteTrap(CMMAOutputStream::CreateL, + &outputStream, + eventSource, + aJni, + (MMMAEventPoster*)eventSource, + writerRef); + + if (err == KErrNone) + { + eventSource->ExecuteV(&CMMAOutputStreamFunc, + &CMMARecordControl::SetRecordStream, + recordControl, + outputStream); + + return reinterpret_cast(outputStream); + } + else + { + aJni->DeleteWeakGlobalRef((jweak)writerRef); + return err; + } +} + +void HBufCFunc(CMMARecordControl* aControl, HBufC*(CMMARecordControl::*aFunc)(), + HBufC** aBuf) +{ + *aBuf = (aControl->*aFunc)(); +} + +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: String _getContentType( int aEventSourceHandle, int aRecordControlHandle ); + * Signature: (II)I + */ +JNIEXPORT jstring JNICALL Java_com_nokia_microedition_media_control_RecordControl__1getContentType +(JNIEnv *aJniEnv, jclass, jint aEventSourceHandle, jint aRecordControlHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1getContentType"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl* >(aRecordControlHandle); + + const HBufC* contentType = NULL; + eventSource->ExecuteTrap(&HBufCFunc, + recordControl, + &CMMARecordControl::GetContentTypeL, + (HBufC**)&contentType); + + if (contentType != NULL) + { + return S60CommonUtils::NativeToJavaString(*aJniEnv, *contentType); + } + // ContentType is not known (Player not started?) + return S60CommonUtils::NativeToJavaString(*aJniEnv, KNullDesC); +} + +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: int _commit( int aEventSourceHandle, int aRecordControlHandle ); + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1commit +(JNIEnv *, jclass, jint aEventSourceHandle, jint aRecordControlHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1commit"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl* >(aRecordControlHandle); + + return eventSource->ExecuteTrap(&VVoidFuncL, + recordControl, + &CMMARecordControl::CommitL); +} + +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: int _setRecordSizeLimit( int aEventSourceHandle, int aRecordControlHandle, int aSize ); + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1setRecordSizeLimit +(JNIEnv *, jclass, jint aEventSourceHandle, jint aRecordControlHandle, jint aSize) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1setRecordSizeLimit"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl *>(aRecordControlHandle); + + TInt err = eventSource->ExecuteTrap(&TIntFuncL, + recordControl, + &CMMARecordControl::SetRecordSizeLimitL, + &aSize); + if (err != KErrNone) + { + return err; + } + + // return size of the set record size + return aSize; +} + +/* + * Class: com_nokia_microedition_media_RecordControl + * Method: int _reset( int aEventSourceHandle, int aRecordControlHandle ); + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_RecordControl__1reset +(JNIEnv *, jclass, jint aEventSourceHandle, jint aRecordControlHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_RecordControl__1reset"); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMARecordControl* recordControl = + reinterpret_cast< CMMARecordControl *>(aRecordControlHandle); + + return eventSource->ExecuteTrap(&VVoidFuncL, + recordControl, + &CMMARecordControl::ResetL); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/rmmatempfile.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/rmmatempfile.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +// INCLUDE FILES + +#include "rmmatempfile.h" + +RMMATempFile::RMMATempFile() +{ + iFileHandle = KErrNone; + iMidletSuiteID = KErrNotFound; +} + +void RMMATempFile::ConnectL() +{ + User::Leave(KErrNotSupported); +} + +void RMMATempFile::CreateL() +{ + User::Leave(KErrNotSupported); +} + +RFile& RMMATempFile::File() +{ + return iFile; +} + +void RMMATempFile::SetMIDletSuiteID(TInt aMidletSuiteID) +{ + iMidletSuiteID = aMidletSuiteID; +} + +void RMMATempFile::Close() +{ +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/sourcestreamreader.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/sourcestreamreader.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMASourceStream +* +*/ + + +//#include "jutils.h" +//#include "mmapiutils.h" +#include "com_nokia_microedition_media_protocol_SourceStreamReader.h" +#include "cmmasourcestream.h" +#include "mmafunctionserver.h" + +// If eventsource is already disposed, then do nothing +#define CHECK_HANDLE(x, j) { if ( !( x ) || ( ( x )->Players().Count() == 0 ) ) { return ( j ); } } +LOCAL_C void WriteDataL(TInt aSourceStream, + TInt aPlayer, + MMAFunctionServer* aEventSource, + const TUint8* aData, + TInt aLength, + TInt aState) +{ + if (!aEventSource->FindPlayer(aPlayer)) + { + // Native object was already deleted + User::Leave(KErrBadHandle); + } + CMMASourceStream* sourceStream = + reinterpret_cast< CMMASourceStream *>(aSourceStream); + + sourceStream->WriteL(aData, aLength, aState); + LOG( EJavaMMAPI, EInfo, "jni SourceStreamReader.cpp: WriteDataL() -"); +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_protocol_SourceStreamReader__1write +(JNIEnv* aJni, jclass, jint aSourceStream, jint aEventSource, + jbyteArray aData, jint aLength, jint aState, jint aPlayerHandle) +{ + LOG( EJavaMMAPI, EInfo, "SourceStreamReaderjni_write"); + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CHECK_HANDLE(eventSource, KErrNone); + + jbyte* data = aJni->GetByteArrayElements(aData, NULL); + LOG2( EJavaMMAPI, EInfo, "SourceStreamReaderjni_write , length = %d,state = %d",(TInt)aLength,(TInt)aState); + TInt err = eventSource->ExecuteTrap(&WriteDataL, + aSourceStream, + aPlayerHandle, + eventSource, + (const TUint8*)data, + aLength, + aState); + ELOG1( EJavaMMAPI, "SourceStreamReaderjni_write , err = %d",err); + aJni->ReleaseByteArrayElements(aData, data, JNI_ABORT); + return err; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/stoptimecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/stoptimecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAStopTimeControl +* +*/ + +//#include +//#include "mmapiutils.h" +#include "com_nokia_microedition_media_control_StopTimeControl.h" +#include "mmafunctionserver.h" +#include "cmmastoptimecontrol.h" + + +JNIEXPORT jlong JNICALL Java_com_nokia_microedition_media_control_StopTimeControl__1getStopTime +(JNIEnv *, jclass , jint aEventSource, jint aControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAStopTimeControl* control = + reinterpret_cast< CMMAStopTimeControl* >(aControl); + + TInt64 time(0); + eventSource->ExecuteV(CMMAStopTimeControl::StaticGetStopTime, + control, + &time); + + return *reinterpret_cast< jlong* >(&time); +} + + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_StopTimeControl__1setStopTime +(JNIEnv *, jclass , jint aEventSource, jint aControl, jlong aTime) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAStopTimeControl* control = + reinterpret_cast< CMMAStopTimeControl* >(aControl); + + TInt64 time; + time = *((TInt64*)&aTime); // convert 'long long' to TInt64 + + TInt err = eventSource->ExecuteTrap(CMMAStopTimeControl::StaticSetStopTimeL, + control, + &time); + + return err; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/tempocontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/tempocontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,140 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMATempoControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_TempoControl.h" +#include "mmafunctionserver.h" +#include "cmmamiditempocontrol.h" +#include + +// +// Wrapper functions which are needed in event source execution. +// If method to be called can leave ExecuteTrap must be used, +// otherwise Execute and ExecuteV can be used. +// +// + +/** + * Local function which can be used to call CMMATempoControl class methods. + * Type of of the function pointer must be + * TInt CMMATempoControl::aFunc( TInt aData ) + * + * @param aTempoControl CMMATempoControl pointer. + * @param aFunc Pointer to the CMMATempoControl method. + * @param aData Parameter to passed to the aFunc method + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntParamIntFuncL(CMMAMIDITempoControl* aTempoControl, + TInt(CMMAMIDITempoControl::*aFuncL)(TInt), + TInt aData, + TInt* aReturnValue) +{ + // call TInt CMMATempoControl::aFunc( TInt aData ) method. + *aReturnValue = (aTempoControl->*aFuncL)(aData); +} + +/** + * Local function which can be used to call CMMATempoControl class methods. + * Type of of the function pointer must be + * TInt CMMATempoControl::aFunc() + * + * @param aTempoControl CMMATempoControl pointer. + * @param aFunc Pointer to the CMMATempoControl method. + * @param aReturnValue The return value of the aFunc will + * be assigned to this parameter. + */ +LOCAL_C void ReturnIntFuncL(CMMAMIDITempoControl* aTempoControl, + TInt(CMMAMIDITempoControl::*aFuncL)(), + TInt* aReturnValue) +{ + // call TInt CMMATempoControl::aFunc() method. + *aReturnValue = (aTempoControl->*aFuncL)(); +} + +// +// JNI functions. Prototypes are generated and commented in Java class +// com_nokia_microedition_media_control_TempoControl +// + +/** + * JNI function from com.nokia.microedition.media.control.TempoControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_TempoControl__1setTempo +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle, + jint aTempo) // parameter boundary is checked in Java side. +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + CMMAMIDITempoControl* tempoControl = + reinterpret_cast< CMMAMIDITempoControl* >(aControlHandle); + + // Value returned from SetTempo method will be assigned to returnValue. + TInt returnValue = 0; + + // Setting tempo will not leave, it just assigns default + // value to the returnValue variable. + TInt error; + error = eventSource->ExecuteTrap(&ReturnIntParamIntFuncL, + tempoControl, + &CMMAMIDITempoControl::SetTempoL, + aTempo, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "TempoControl__1setTempo return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} + +/** + * JNI function from com.nokia.microedition.media.control.TempoControl + */ +JNIEXPORT jint JNICALL +Java_com_nokia_microedition_media_control_TempoControl__1getTempo +(JNIEnv*, + jobject, + jint aControlHandle, + jint aEventSourceHandle) +{ + // Get pointer to native event source. + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + CMMAMIDITempoControl* tempoControl = + reinterpret_cast< CMMAMIDITempoControl* >(aControlHandle); + + TInt returnValue = 0; + TInt error; + + error = eventSource->ExecuteTrap(&ReturnIntFuncL, + tempoControl, + &CMMAMIDITempoControl::TempoL, + &returnValue); + + LOG1( EJavaMMAPI, EInfo, "TempoControl__1getTempo return value %d", returnValue); + + return (error == KErrNone) ? returnValue : error; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/tmmaparametervalidator.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/tmmaparametervalidator.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,628 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for storing and parsing properties +* +*/ + + +// INCLUDE FILES +#include +#include +#include +#include "cmmaplayerproperties.h" +#include + + +#include "tmmaparametervalidator.h" + +// CONSTANTS + +// AUDIO PARAMETERS +_LIT(KPropertyEncoding, "encoding"); +_LIT(KPropertyEncodingPcm, "pcm"); // Wav +_LIT(KPropertyEncodingAmr, "amr"); // Amr +_LIT(KPropertyEncodingGsm, "gsm"); +_LIT(KPropertyEncodingUlaw, "ulaw"); // Au +_LIT(KPropertyEncodingAlaw, "alaw"); +_LIT(KPropertyEncodingRaw, "raw"); // Raw pcm +_LIT(KPropertyEncodingNone, ""); // empty string + +_LIT(KContentTypeWav, "audio/wav"); +_LIT(KContentTypeAu, "audio/au"); +_LIT(KContentTypeAmr, "audio/amr"); +_LIT(KContentTypeRaw, "audio/raw"); + +// Format used if not specified in locator +_LIT(KDefaultAudioRecordContentType, "audio/wav"); + +_LIT(KPropertyRate, "rate"); +_LIT(KPropertyBits, "bits"); +_LIT(KPropertyChannels, "channels"); + +_LIT(KPropertyEndian, "endian"); +MMA_PARAMETER_STR(KPropertyEndianLittle, "little"); +MMA_PARAMETER_STR(KPropertyEndianBig, "big"); +MMA_PARAMETER_ARRAY(KValidEndianValues) +{ + { + &KPropertyEndianLittle + }, {&KPropertyEndianBig} +}; + +_LIT(KPropertySigned, "signed"); +MMA_PARAMETER_STR(KPropertySignedSigned, "signed"); +MMA_PARAMETER_STR(KPropertySignedUnsigned, "unsigned"); +MMA_PARAMETER_ARRAY(KValidSignedValues) +{ + { + &KPropertySignedSigned + }, {&KPropertySignedUnsigned} +}; + +// VIDEO PARAMETERS +_LIT(KPropertyFps, "fps"); +_LIT(KPropertyWidth, "width"); +_LIT(KPropertyHeight, "height"); + +const TInt KSizeNotSet = -1; + +// Format used if not specified in locator +_LIT(KDefaultVideoRecordContentType, "video/3gpp"); + +//IMAGE PARAMETERS +_LIT(KPropertyType, "type"); +MMA_PARAMETER_STR(KPropertyJfif, "jfif"); +MMA_PARAMETER_STR(KPropertyExif, "exif"); +MMA_PARAMETER_ARRAY(KValidTypes) +{ + { + &KPropertyJfif + }, {&KPropertyExif} +}; + +_LIT(KFormatPng, "png"); +_LIT(KFormatJpg, "jpeg"); // not "jpg" +_LIT(KFormatGif, "gif"); +_LIT(KFormatBmp, "bmp"); +_LIT(KContentTypePng, "image/png"); +_LIT(KContentTypeJpg, "image/jpeg"); +_LIT(KContentTypeJpg2,"image/jpg"); +_LIT(KContentTypeGif, "image/gif"); +_LIT(KContentTypeBmp, "image/bmp"); + +_LIT(KPropertyColor, "colors"); +MMA_PARAMETER_STR(KPropertyRGB888, "rgb888"); +MMA_PARAMETER_STR(KPropertyRGB444, "rgb444"); +MMA_PARAMETER_STR(KPropertyGray16, "gray16"); +MMA_PARAMETER_STR(KPropertyGray8, "gray8"); + +_LIT(KPropertyQuality, "quality"); +const TInt KDefaultQuality = 75; // digged out from ICL source +const TInt KDefaultBpp = 24; +const TInt KDefaultBpp444 = 12; +const TInt KDefaultBppGray16 = 16; +const TInt KDefaultBppGray8 = 8; +const TInt KNoUserDefinedQuality = -1; +const TReal32 KNoUserDefinedFps = -1; + +// CMMAImageSettings container destructor +CMMAImageSettings::~CMMAImageSettings() +{ + delete iMimeType; + delete iType; + delete iImageData; +} + +CMMAAudioSettings::~CMMAAudioSettings() +{ + delete iContentType; +} + +CMMAAudioSettings *TMMAParameterValidator::ValidateAudioPropertiesL(const TDesC& aProperties) +{ + CMMAAudioSettings* settings = new(ELeave) CMMAAudioSettings; + CleanupStack::PushL(settings); + + CMMAParameterRuleSet* rules = CMMAParameterRuleSet::NewLC(); + + // "bits" must be between 0 - 24 + TMMAParameterRuleInt bitsRule(KPropertyBits, 0, 24); + rules->AppendRuleL(&bitsRule); + + // "rate" must be positive + TMMAParameterRuleInt rateRule(KPropertyRate, 1); + rules->AppendRuleL(&rateRule); + + // "channels" must be 1 or 2 + TMMAParameterRuleInt channelsRule(KPropertyChannels, 1, 2); + rules->AppendRuleL(&channelsRule); + + // "signed" must be "signed" or "unsigned" + TMMAParameterRuleDes signedRule(KPropertySigned, KValidSignedValues, + MMA_PARAMETER_ARRAY_SIZE(KValidSignedValues)); + rules->AppendRuleL(&signedRule); + + // "endian" must be "little" or "big" + TMMAParameterRuleDes endianRule(KPropertyEndian, KValidEndianValues, + MMA_PARAMETER_ARRAY_SIZE(KValidEndianValues)); + rules->AppendRuleL(&endianRule); + + // "encoding" must be one of valid values + TMMAParameterRuleDes encodingRule(KPropertyEncoding); + rules->AppendRuleL(&encodingRule); + + CMMAPlayerProperties* properties = CMMAPlayerProperties::NewL(aProperties, *rules); + CleanupStack::PushL(properties); + + // validating properties + properties->ValidateL(); + + TInt bits = KDefaultBits; + properties->GetProperty(KPropertyBits, bits); + + settings->iRate = KDefaultRate; + properties->GetProperty(KPropertyRate, settings->iRate); + + settings->iChannels = KDefaultChannels; + properties->GetProperty(KPropertyChannels, settings->iChannels); + + + // Normally encoders are not streamable + settings->iStreamableFormat = EFalse; + + // signed=signed/unsigned (default is unsigned for 8bit, signed for 16bit) + TBool dataSigned = EFalse; + if (properties->Compare(KPropertyBits, 16)) + { + dataSigned = ETrue; + } + + if (properties->Compare(KPropertySigned, KPropertySignedSigned())) + { + dataSigned = ETrue; + } + else if (properties->Compare(KPropertySigned, KPropertySignedUnsigned())) + { + dataSigned = EFalse; + } + + // little by default + TBool endianLittle = ETrue; + if (properties->Compare(KPropertyEndian, KPropertyEndianBig())) + { + endianLittle = EFalse; + } + + settings->iDataType = KMMFFourCCCodeNULL; + + // encoding specific + + TPtrC encoding(NULL, 0); + properties->GetProperty(KPropertyEncoding, encoding); + + if ((encoding == KPropertyEncodingAmr()) || + (encoding == KPropertyEncodingGsm())) + { + // AMR format + encoding.Set(KContentTypeAmr()); + } + + else if (encoding == KPropertyEncodingUlaw()) + { + // AU format, ulaw codec + encoding.Set(KContentTypeAu()); + settings->iDataType = KMMFFourCCCodeMuLAW; + } + + else if (encoding == KPropertyEncodingAlaw()) + { + // AU format, alaw codec + encoding.Set(KContentTypeAu()); + settings->iDataType = KMMFFourCCCodeALAW; + } + + else if (encoding == KPropertyEncodingPcm()) + { + // wav format + encoding.Set(KContentTypeWav()); + } + + else if (encoding == KPropertyEncodingRaw()) + { + // raw format, default codec + encoding.Set(KContentTypeRaw()); + } + + else if ((encoding == KPropertyEncodingNone())) // this is the default case + { + encoding.Set(KDefaultAudioRecordContentType()); + } + + settings->iContentType = encoding.AllocL(); + + + // wav specific + if (*settings->iContentType == KContentTypeWav()) + { + if (bits == 8) + { + settings->iDataType = KMMFFourCCCodePCMU8; + } + + else if (bits == 16) + { + settings->iDataType = KMMFFourCCCodePCM16; + } + + else if (bits != KDefaultBits) + { + User::Leave(KErrNotSupported); + } + } + + // raw specific + if (*settings->iContentType == KContentTypeRaw()) + { + if (bits == 8) + { + if (dataSigned) + { + settings->iDataType = KMMFFourCCCodePCM8; + } + else + { + settings->iDataType = KMMFFourCCCodePCMU8; + } + } + + else if (bits == 16) + { + if (endianLittle) + { + if (dataSigned) + { + settings->iDataType = KMMFFourCCCodePCM16; + } + else + { + settings->iDataType = KMMFFourCCCodePCMU16; + } + } + else // Big endian + { + if (dataSigned) + { + settings->iDataType = KMMFFourCCCodePCM16B; + } + else + { + settings->iDataType = KMMFFourCCCodePCMU16B; + } + } + } + + else if (bits != KDefaultBits) // bits not 8 or 16 + { + User::Leave(KErrNotSupported); + } + + settings->iEncoding = TUid::Uid(KMmfUidFormatRAWWrite); + settings->iController = TUid::Uid(KMmfUidControllerAudio); + } + + + CleanupStack::PopAndDestroy(2); // rules, properties + CleanupStack::Pop(settings); + return settings; +} + +TMMAVideoSettings TMMAParameterValidator::ValidateVideoPropertiesL(const TDesC& aProperties) +{ + CheckEncodingL(aProperties); + TMMAVideoSettings settings; + CMMAParameterRuleSet* rules = CMMAParameterRuleSet::NewLC(); + + // "fps" is real, taking it as string and validating later + TMMAParameterRuleDes fpsRule(KPropertyFps); + rules->AppendRuleL(&fpsRule); + + // "width" must be positive + TMMAParameterRuleInt widthRule(KPropertyWidth, 1); + rules->AppendRuleL(&widthRule); + + // "height" must be positive + TMMAParameterRuleInt heightRule(KPropertyHeight, 1); + rules->AppendRuleL(&heightRule); + + // "encoding" can be anything in this point (actual validation will be done by MMF) + TMMAParameterRuleDes encodingRule(KPropertyEncoding); + rules->AppendRuleL(&encodingRule); + + CMMAPlayerProperties* properties = CMMAPlayerProperties::NewL(aProperties, *rules); + CleanupStack::PushL(properties); + + // validating properties + properties->ValidateL(); + + properties->GetProperty(KPropertyWidth, settings.iWidth = KSizeNotSet); + properties->GetProperty(KPropertyHeight, settings.iHeight = KSizeNotSet); + + TPtrC fps; + settings.iFps = KNoUserDefinedFps; + if (properties->GetProperty(KPropertyFps, fps)) + { + TLex lex(fps); + TReal32 fpsReal; + // try to get fps value from string + TInt err = lex.Val(fpsReal); + if (err == KErrNone) + { + // Check if there other characters after + // number ( 34xxx ) + if (!lex.Eos() || + (fpsReal <= 0)) + { + User::Leave(KErrArgument); + } + else + { + settings.iFps = fpsReal; + } + } + else if (err == KErrNoMemory) + { + User::Leave(KErrNoMemory); + } + else + { + // value is not available + User::Leave(KErrArgument); + } + } + + settings.iEncoding.Set(KDefaultVideoRecordContentType()); + properties->GetProperty(KPropertyEncoding, settings.iEncoding); + + CleanupStack::PopAndDestroy(2); // rules, properties + return settings; +} + +CMMAImageSettings* TMMAParameterValidator::ValidateImagePropertiesL(const TDesC& aProperties) +{ + CMMAImageSettings* settings = new(ELeave)CMMAImageSettings; + CleanupStack::PushL(settings); + + CMMAParameterRuleSet* rules = CMMAParameterRuleSet::NewLC(); + + // "width" must be positive + TMMAParameterRuleInt widthRule(KPropertyWidth, 1); + rules->AppendRuleL(&widthRule); + + // "height" must be positive + TMMAParameterRuleInt heightRule(KPropertyHeight, 1); + rules->AppendRuleL(&heightRule); + + // "encoding" final validation is done with image encoder + TMMAParameterRuleDes encodingRule(KPropertyEncoding); + rules->AppendRuleL(&encodingRule); + + // "color" can be anything in this point, it will be validated later + TMMAParameterRuleDes colorRule(KPropertyColor); + rules->AppendRuleL(&colorRule); + + // "type" must be "jfif" or "exif" + TMMAParameterRuleDes typeRule(KPropertyType, KValidTypes, + MMA_PARAMETER_ARRAY_SIZE(KValidTypes)); + rules->AppendRuleL(&typeRule); + + // "quality" must be between 0 and 100 + TMMAParameterRuleInt qualityRule(KPropertyQuality, 0, 100); + rules->AppendRuleL(&qualityRule); + + CMMAPlayerProperties* properties = CMMAPlayerProperties::NewL(aProperties, *rules); + CleanupStack::PushL(properties); + + // validating properties + properties->ValidateL(); + + properties->GetProperty(KPropertyWidth, settings->iWidth = KSizeNotSet); + properties->GetProperty(KPropertyHeight, settings->iHeight = KSizeNotSet); + + // do not set quality if user has not defined it + TInt quality = KNoUserDefinedQuality; + properties->GetProperty(KPropertyQuality, quality); + + TPtrC encoding; + if (properties->Compare(KPropertyEncoding, KFormatPng) || + properties->Compare(KPropertyEncoding, KContentTypePng)) + { //PNG + settings->iMimeType = CreateHBufC8FromUnicodeL(KContentTypePng); + TPngEncodeData* imageData = new(ELeave)TPngEncodeData(); + imageData->iBitsPerPixel = KDefaultBpp; + imageData->iColor = ETrue; + imageData->iPaletted = EFalse; + imageData->iLevel = TPngEncodeData::EDefaultCompression; + + CleanupStack::PushL(imageData); + TPtrC color; + if (properties->Compare(KPropertyColor, KPropertyRGB888())) + { + // default + } + else if (properties->Compare(KPropertyColor, KPropertyRGB444())) + { + imageData->iBitsPerPixel = KDefaultBpp444; + } + else if (properties->Compare(KPropertyColor, KPropertyGray16())) + { + imageData->iBitsPerPixel = KDefaultBppGray16; + imageData->iColor = EFalse; + } + else if (properties->Compare(KPropertyColor, KPropertyGray8())) + { + imageData->iBitsPerPixel = KDefaultBppGray8; + imageData->iColor = EFalse; + } + else if (properties->GetProperty(KPropertyColor, color)) + { + // not valid color parameter + User::Leave(KErrArgument); + } + settings->iImageData = CFrameImageData::NewL(); + User::LeaveIfError(settings->iImageData->AppendFrameData(imageData)); + // CFrameImageData took ownership of imageData + CleanupStack::Pop(imageData); + + // png quality setting not supported, "type" is only for jpeg. + TPtrC tmp; + if (quality != KNoUserDefinedQuality || + properties->GetProperty(KPropertyType, tmp) + ) + { + User::Leave(KErrArgument); + } + } + else if (properties->Compare(KPropertyEncoding, KFormatJpg) || + properties->Compare(KPropertyEncoding, KContentTypeJpg) || + properties->Compare(KPropertyEncoding, KContentTypeJpg2)) + { // JPG + settings->iMimeType = CreateHBufC8FromUnicodeL(KContentTypeJpg); + if (properties->Compare(KPropertyType, KPropertyJfif())) + { + settings->iType = CreateHBufC8FromUnicodeL(KPropertyJfif()); + } + else if (properties->Compare(KPropertyType, KPropertyExif())) + { + settings->iType = CreateHBufC8FromUnicodeL(KPropertyExif()); + } + else + { + settings->iType = CreateHBufC8FromUnicodeL(KPropertyExif()); + } + + TJpegImageData* imageData = new(ELeave)TJpegImageData(); + CleanupStack::PushL(imageData); + imageData->iQualityFactor = KDefaultQuality; + imageData->iSampleScheme = TJpegImageData::EColor444; + if (quality != KNoUserDefinedQuality) + { + imageData->iQualityFactor = quality; + } + settings->iImageData = CFrameImageData::NewL(); + User::LeaveIfError(settings->iImageData->AppendImageData(imageData)); + // CFrameImageData took ownership of imageData + CleanupStack::Pop(imageData); + + TPtrC tmp; + // jpg encoders colors cannot be configured, + // notice that if there was "type" defined it must be "jfif" + // and encoder will check that anyway. + if (properties->GetProperty(KPropertyColor, tmp)) + { + User::Leave(KErrArgument); + } + } + else if (properties->Compare(KPropertyEncoding, KFormatGif) || + properties->Compare(KPropertyEncoding, KContentTypeGif)) + {//GIF + settings->iMimeType = CreateHBufC8FromUnicodeL(KContentTypeGif); + TPtrC tmp; + // gif encoder is not configurable + if (properties->GetProperty(KPropertyColor, tmp) || + properties->GetProperty(KPropertyType, tmp) || + quality != KNoUserDefinedQuality) + { + User::Leave(KErrArgument); + } + } + else if (properties->Compare(KPropertyEncoding, KFormatBmp) || + properties->Compare(KPropertyEncoding, KContentTypeBmp)) + {//BMP + settings->iMimeType = CreateHBufC8FromUnicodeL(KContentTypeBmp); + TBmpImageData* imageData = new(ELeave)TBmpImageData(); + CleanupStack::PushL(imageData); + imageData->iBitsPerPixel = KDefaultBpp; + TPtrC color; + if (properties->Compare(KPropertyColor, KPropertyRGB888())) + { + // default + } + else if (properties->Compare(KPropertyColor, KPropertyRGB444())) + { + imageData->iBitsPerPixel = KDefaultBpp444; + } + else if (properties->GetProperty(KPropertyColor, color)) + { + // not valid color parameter + User::Leave(KErrArgument); + } + + settings->iImageData = CFrameImageData::NewL(); + User::LeaveIfError(settings->iImageData->AppendImageData(imageData)); + // CFrameImageData took ownership of imageData + CleanupStack::Pop(imageData); + + // quality not supported, "type" is only for jpg + TPtrC tmp; + if (quality != KNoUserDefinedQuality || + properties->GetProperty(KPropertyType, tmp)) + { + User::Leave(KErrArgument); + } + } + else if (properties->GetProperty(KPropertyEncoding, encoding)) + { // OTHER POSSIBLE TYPE + // trying to create encoder with only content/mime-type + settings->iMimeType = CreateHBufC8FromUnicodeL(encoding); + + // No extra parameters, only content-type + TPtrC tmp; + if (properties->GetProperty(KPropertyColor, tmp) || + properties->GetProperty(KPropertyType, tmp) || + quality != KNoUserDefinedQuality) + { + User::Leave(KErrArgument); + } + } + else // default: we had empty properties string + { + settings->iMimeType = CreateHBufC8FromUnicodeL(KContentTypePng); + } + CleanupStack::PopAndDestroy(properties); + CleanupStack::PopAndDestroy(rules); + CleanupStack::Pop(settings); + return settings; +} + +void TMMAParameterValidator::CheckEncodingL(const TDesC& aProperties) +{ + TInt encodingPos = aProperties.Find(KPropertyEncoding); + // empty properties is valid and + // encoding must be first parameter and must exist every time + if ((aProperties.Length() > 0) && + ((encodingPos == KErrNotFound) || + (encodingPos != 0))) + { + User::Leave(KErrArgument); + } +} + +HBufC8* TMMAParameterValidator::CreateHBufC8FromUnicodeL(const TDesC& aDes) +{ + HBufC8* tmp = HBufC8::NewL(aDes.Length()); + tmp->Des().Copy(aDes); + return tmp; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/videocontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/videocontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,311 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAVideoControl +* +*/ + + +//#include +//#include +#include "com_nokia_microedition_media_control_VideoControl.h" +#include "mmafunctionserver.h" +#include "cmmavideocontrol.h" +//#include "CMIDToolkit.h" +#include "cmmadeleterefevent.h" +#include + +#include + +//#include +//#include +#include "s60commonutils.h" +#include "jstringutils.h" +using namespace java::util; + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1construct +(JNIEnv* aJni, jobject aControlObject, jint aControlHandle, + jint aEventSourceHandle, jint aToolkitHandle) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1construct + "); + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl* >(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSourceHandle); + + + __ASSERT_DEBUG(videoControl, + User::Panic(_L("videocontrol::control is null"), + KErrArgument)); + __ASSERT_DEBUG(eventSource, + User::Panic(_L("videocontrol::eventsource is null"), + KErrArgument)); + + // reference must be done, that events can sent to java side + jobject controlObject = aJni->NewWeakGlobalRef(aControlObject); + + // CMIDToolkit* ptoolkit = JavaUnhand< CMIDToolkit >(aToolkitHandle); + + //JNIENV_TO_VM(aJni); + TInt error = eventSource->ExecuteTrap(&CMMAVideoControl::ConstructL, + videoControl, + controlObject, + eventSource, + eventSource->getValidJniEnv(), //Passes JavaVM*, not JNIEnv*. + (MMMAEventPoster*)eventSource/*, + ptoolkit*/); + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1construct - "); + return error; +} + + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1setDisplayProperty +(JNIEnv*, jobject, jint aControlHandle, jint aEventSourceHandle, + jint aPropertyA, jint aPropertyB, jint aPropertyType) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1setDisplayProperty"); + + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl* >(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + __ASSERT_DEBUG(videoControl, + User::Panic(_L("videocontrol::control is null"), + KErrArgument)); + __ASSERT_DEBUG(eventSource, + User::Panic(_L("videocontrol::eventsource is null"), + KErrArgument)); + + TInt error(eventSource->ExecuteTrap(&CMMAVideoControl::StaticSetPropertyL, + videoControl, + aPropertyType, + aPropertyA, + aPropertyB)); + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1setDisplayProperty -"); + return error; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1getControlProperty +(JNIEnv*, jobject, jint aControlHandle, jint aEventSourceHandle, + jint aPropertyType) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1getControlProperty"); + + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl* >(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + __ASSERT_DEBUG(videoControl, + User::Panic(_L("videocontrol::control is null"), + KErrArgument)); + __ASSERT_DEBUG(eventSource, + User::Panic(_L("videocontrol::evetnsource is null"), + KErrArgument)); + TInt returnValue(KErrNone); + + TInt error(eventSource->ExecuteTrap(&CMMAVideoControl::StaticGetPropertyL, + videoControl, + aPropertyType, + &returnValue)); + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1getControlProperty - "); + if (error == KErrNone) + { + return returnValue; + } + return error; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1getSnapshot +(JNIEnv* aJni, jobject, jint aControlHandle, jint aEventSourceHandle, + jstring aProperties) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1getSnapshot + "); + + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl* >(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + __ASSERT_DEBUG(videoControl, + User::Panic(_L("videocontrol::control is null"), + KErrArgument)); + __ASSERT_DEBUG(eventSource, + User::Panic(_L("videocontrol::evetnsource is null"), + KErrArgument)); + + JStringUtils properties(*aJni, aProperties); + TInt error(eventSource->ExecuteTrap(&CMMAVideoControl::TakeSnapShotL, + videoControl, + (const TDesC*)&properties)); + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1getSnapshot - "); + return error; +} + +/** + * Initializes dynamic display mode + * @return handle to MMMADirectContent or error code + */ +LOCAL_C jint InitDynamicMode(MMAFunctionServer* aEventSource, + CMMAVideoControl* aVideoControl, + jobject aGUIObject, + CMMAEvent* aDeleteRefEvent) +{ + TInt contentHandle = 0; + TInt error = aEventSource->ExecuteTrap( + &CMMAVideoControl::StaticInitDynamicModeL, + aVideoControl, + &contentHandle, + aEventSource, + aGUIObject, + aDeleteRefEvent); + + // if init failed return error code + if (error != KErrNone) + { + contentHandle = error; + } + return contentHandle; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1initDisplayMode +(JNIEnv* aJni, jobject aJavaVideoControl, jint aControlHandle, jint aEventSourceHandle, + jobject aJavaDisplayObj, jobject aComponent) +{ + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1initDisplayMode +"); + LOG1( EJavaMMAPI, EInfo, "aControlHandle = %d", aControlHandle); + LOG1( EJavaMMAPI, EInfo, "aEventSourceHandle = %d", aEventSourceHandle); +// LOG1( EJavaMMAPI, EInfo, "aComponentHandle = %d", aComponentHandle); + + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl* >(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + jobject javaVideoControlPeer = aJni->NewWeakGlobalRef(aJavaVideoControl); + + // Reference need to created to the component that component won't be deleted + // before display associated to it. + jobject componentRef = aJni->NewGlobalRef(aComponent); + if (componentRef == NULL) + { + return KErrNoMemory; + } + // Component reference need to be deleted in controls destructor. Created here to + // be sure that reference can be deleted. . + CMMAEvent* deleteRefEvent = new CMMADeleteRefEvent(componentRef); + // Cleanup stack is not needed, because static init takes the ownership and + // cannot leave before that. + if (!deleteRefEvent) + { + aJni->DeleteGlobalRef(componentRef); + return KErrNoMemory; + } + +// for javaside display object // TODO: delete this object after its not required in destructor of control + + // Reference need to created to the component that component won't be deleted + // before display associated to it. + jobject javaDisplayRef = aJni->NewGlobalRef(aJavaDisplayObj); + if (javaDisplayRef == NULL) + { + return KErrNoMemory; + } + + /*// other modes has component + if (aComponentHandle == 0) + { + return InitDynamicMode(eventSource, + videoControl, + componentRef, + deleteRefEvent); + } + */ + // MMIDComponent* component = JavaUnhand< MMIDComponent >(aComponentHandle); + + + __ASSERT_DEBUG(videoControl, + User::Panic(_L("videocontrol::control is null"), + KErrArgument)); +// __ASSERT_DEBUG(component, +// User::Panic(_L("videocontrol::component is null"), +// KErrArgument)); + __ASSERT_DEBUG(eventSource, + User::Panic(_L("videocontrol::eventsource is null"), + KErrArgument)); + TInt handle(0); + + TInt error(eventSource->ExecuteTrap(&CMMAVideoControl::StaticInitL, + videoControl, + javaDisplayRef, + eventSource, + &handle, + deleteRefEvent)); + LOG( EJavaMMAPI, EInfo, "Java_com_nokia_microedition_media_control_VideoControl__1initDisplayMode - "); + if (error == KErrNone) + { + return handle; + } + return error; +} + +JNIEXPORT jint JNICALL Java_com_nokia_microedition_media_control_VideoControl__1setForeground +(JNIEnv* /*aJni*/, jobject, jint aControlHandle, jint aEventSourceHandle, jint aIsForeground) +{ + LOG1( EJavaMMAPI, EInfo, "_1setForeground + FOREGROUND = %d",aIsForeground); + CMMAVideoControl* videoControl = + reinterpret_cast< CMMAVideoControl *>(aControlHandle); + + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + TInt handle(0); + TInt error(eventSource->ExecuteTrap(&CMMAVideoControl::StaticSetForegroundL, + videoControl, + aIsForeground)); + if (error == KErrNone) + { + LOG( EJavaMMAPI, EInfo, "_1setForeground -"); + return handle; + } + + LOG( EJavaMMAPI, EInfo, "_1setForeground -"); + return error; +} +JNIEXPORT jboolean JNICALL Java_com_nokia_microedition_media_control_VideoControl__1isESWT +(JNIEnv *, jobject) +{/* + MSwtClient* client = NULL; + TRAP_IGNORE(client = SWT::CreateClientL()); + + if (!client) + { + return false; // LCDUI midlet running + } + else + { + delete client; + client = NULL; + return true; // eSWT midlet running + } +*/ + // enable above code once you have support for eswt in 3.2.3, it is already enable for 5.0 +return false; +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/baseline/src/volumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/baseline/src/volumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class has JNI wrappers for CMMAVolumeControl +* +*/ + +//#include +//#include "mmapiutils.h" + +#include "com_nokia_microedition_media_control_VolumeControl.h" +#include "mmafunctionserver.h" +#include "cmmavolumecontrol.h" + + +/* + * Class: com_nokia_microedition_media_control_VolumeControl + * Method: _setLevel + * Signature: (III)I + */ + +JNIEXPORT int JNICALL Java_com_nokia_microedition_media_control_VolumeControl__1setLevel +(JNIEnv *, jclass , jint aEventSource, jint aVolumeControl, jint aLevel) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAVolumeControl* volumeControl = + reinterpret_cast< CMMAVolumeControl* >(aVolumeControl); + + TInt error = eventSource->ExecuteTrap(&CMMAVolumeControl::StaticSetLevelL, + volumeControl, + aLevel); + return error; +} + +/* + * Class: com_nokia_microedition_media_control_VolumeControl + * Method: _getLevel + * Signature: (II)I + */ + +JNIEXPORT int JNICALL Java_com_nokia_microedition_media_control_VolumeControl__1getLevel +(JNIEnv *, jclass , jint aEventSource, jint aVolumeControl) +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer* >(aEventSource); + + CMMAVolumeControl* volumeControl = + reinterpret_cast< CMMAVolumeControl* >(aVolumeControl); + + TInt level(0); + TInt error = eventSource->ExecuteTrap(&CMMAVolumeControl::StaticGetLevelL, + volumeControl, &level); + if (error == KErrNone) + { + return level; + } + return error; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,205 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + audio.encodings=:mobilemedia.DynamicPropertyHandler + supports.video.capture=:mobilemedia.DynamicPropertyHandler + video.encodings=:mobilemedia.DynamicPropertyHandler + microedition.media.version=1.2 + supports.audio.capture=true + supports.mixing=true + supports.recording=true + video.snapshot.encodings=encoding=png encoding=jpeg encoding=image/png encoding=image/jpeg encoding=image/jpg encoding=image/gif encoding=image/bmp + + + + + + + + + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/bwins/javamobilemediau.def --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/bwins/javamobilemediau.def Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,79 @@ +EXPORTS + ?jni_lookup@@YAP6AXXZPBD@Z @ 1 NONAME ; void (*)(void) jni_lookup(char const *) + ?SetLoopCount@CMMAPlayer@@UAEXH@Z @ 2 NONAME ; void CMMAPlayer::SetLoopCount(int) + ?PostObjectEvent@CMMAPlayer@@QAEXW4TEventType@CMMAPlayerEvent@@PAV_jobject@@@Z @ 3 NONAME ; void CMMAPlayer::PostObjectEvent(enum CMMAPlayerEvent::TEventType, class _jobject *) + ?PrefetchFileL@CMMAEMCAudioPlayer@@MAEXXZ @ 4 NONAME ; void CMMAEMCAudioPlayer::PrefetchFileL(void) + ?AddControlL@CMMAPlayer@@UAEXPAVCMMAControl@@@Z @ 5 NONAME ; void CMMAPlayer::AddControlL(class CMMAControl *) + ?NotifyWithStringEvent@CMMAVideoPlayer@@UAEXW4TEventType@CMMAPlayerEvent@@ABVTDesC16@@@Z @ 6 NONAME ; void CMMAVideoPlayer::NotifyWithStringEvent(enum CMMAPlayerEvent::TEventType, class TDesC16 const &) + ?PostStringEvent@CMMAPlayer@@QAEXW4TEventType@CMMAPlayerEvent@@ABVTDesC16@@@Z @ 7 NONAME ; void CMMAPlayer::PostStringEvent(enum CMMAPlayerEvent::TEventType, class TDesC16 const &) + ?SnapshotEncoded@CMMAVideoPlayer@@UAEPAVHBufC8@@XZ @ 8 NONAME ; class HBufC8 * CMMAVideoPlayer::SnapshotEncoded(void) + ?DoOpen@CMMAMMFPlayerBase@@MAEHVTUid@@ABVTDesC8@@01VTMMFPrioritySettings@@@Z @ 9 NONAME ; int CMMAMMFPlayerBase::DoOpen(class TUid, class TDesC8 const &, class TUid, class TDesC8 const &, class TMMFPrioritySettings) + ?StaticControl@CMMAPlayer@@SAPAVCMMAControl@@PAV1@H@Z @ 10 NONAME ; class CMMAControl * CMMAPlayer::StaticControl(class CMMAPlayer *, int) + ?Type@CMMAVideoPlayer@@MAEABVTDesC16@@XZ @ 11 NONAME ; class TDesC16 const & CMMAVideoPlayer::Type(void) + ??0CMMAEMCAudioVolumeControl@@IAE@AAVCMMAEMCAudioPlayer@@@Z @ 12 NONAME ; CMMAEMCAudioVolumeControl::CMMAEMCAudioVolumeControl(class CMMAEMCAudioPlayer &) + ?PublicClassName@CMMAControl@@UBEABVTDesC16@@XZ @ 13 NONAME ; class TDesC16 const & CMMAControl::PublicClassName(void) const + ?PostActionCompletedStart@CMMAPlayer@@QAEXXZ @ 14 NONAME ; void CMMAPlayer::PostActionCompletedStart(void) + ?Controller@CMMAMMFPlayerBase@@QAEAAVRMMFController@@XZ @ 15 NONAME ; class RMMFController & CMMAMMFPlayerBase::Controller(void) + ?PrefetchDataL@CMMAAudioPlayer@@MAEXABVTDesC8@@@Z @ 16 NONAME ; void CMMAAudioPlayer::PrefetchDataL(class TDesC8 const &) + ??0CMMAVideoUrlPlayer@@IAE@PAVCMMAMMFResolver@@@Z @ 17 NONAME ; CMMAVideoUrlPlayer::CMMAVideoUrlPlayer(class CMMAMMFResolver *) + ?CloseL@CMMAVideoUrlPlayer@@UAEXXZ @ 18 NONAME ; void CMMAVideoUrlPlayer::CloseL(void) + ?SnapshotBitmap@CMMAVideoPlayer@@UAEPAVCFbsBitmap@@XZ @ 19 NONAME ; class CFbsBitmap * CMMAVideoPlayer::SnapshotBitmap(void) + ?NewL@CTimeOutTimer@@SAPAV1@HAAVMTimeOutNotify@@@Z @ 20 NONAME ; class CTimeOutTimer * CTimeOutTimer::NewL(int, class MTimeOutNotify &) + ?StartL@CMMAVideoUrlPlayer@@UAEXXZ @ 21 NONAME ; void CMMAVideoUrlPlayer::StartL(void) + ?ReadCompletedL@CMMAEMCAudioPlayer@@UAEXHABVTDesC8@@@Z @ 22 NONAME ; void CMMAEMCAudioPlayer::ReadCompletedL(int, class TDesC8 const &) + ?NewL@CMMAEMCAudioVolumeControl@@SAPAV1@AAVCMMAEMCAudioPlayer@@@Z @ 23 NONAME ; class CMMAEMCAudioVolumeControl * CMMAEMCAudioVolumeControl::NewL(class CMMAEMCAudioPlayer &) + ?HandleEvent@CMMAVideoUrlPlayer@@MAEXABVTMMFEvent@@@Z @ 24 NONAME ; void CMMAVideoUrlPlayer::HandleEvent(class TMMFEvent const &) + ?ConstructL@CMMAVideoUrlPlayer@@IAEXABVTDesC16@@@Z @ 25 NONAME ; void CMMAVideoUrlPlayer::ConstructL(class TDesC16 const &) + ?SetDisplayL@CMMAVideoPlayer@@UAEXPAVMMMADisplay@@@Z @ 26 NONAME ; void CMMAVideoPlayer::SetDisplayL(class MMMADisplay *) + ?TakeSnapshotL@CMMAVideoPlayer@@UAE?AW4TEncoding@MMMASnapshot@@PAVTRequestStatus@@ABVTSize@@ABVCMMAImageSettings@@@Z @ 27 NONAME ; enum MMMASnapshot::TEncoding CMMAVideoPlayer::TakeSnapshotL(class TRequestStatus *, class TSize const &, class CMMAImageSettings const &) + ?StaticAddObjectFromHandleL@MMAFunctionServer@@SAXPAV1@H@Z @ 28 NONAME ; void MMAFunctionServer::StaticAddObjectFromHandleL(class MMAFunctionServer *, int) + ?SnapshotReady@CMMAVideoControl@@UAEXXZ @ 29 NONAME ; void CMMAVideoControl::SnapshotReady(void) + ?CreatePlayerL@CMMAMMFPlayerFactory@@MAEPAVCMMAPlayer@@PAVCMMFFormatSelectionParameters@@PBVTDesC16@@@Z @ 30 NONAME ; class CMMAPlayer * CMMAMMFPlayerFactory::CreatePlayerL(class CMMFFormatSelectionParameters *, class TDesC16 const *) + ?PlayCompleteL@CMMAEMCAudioPlayer@@MAEXH@Z @ 31 NONAME ; void CMMAEMCAudioPlayer::PlayCompleteL(int) + ?NewL@CMMAAudioVolumeControl@@SAPAV1@PAVCMMAAudioPlayer@@@Z @ 32 NONAME ; class CMMAAudioVolumeControl * CMMAAudioVolumeControl::NewL(class CMMAAudioPlayer *) + ?PrefetchDataL@CMMAEMCAudioPlayer@@MAEXABVTDesC8@@@Z @ 33 NONAME ; void CMMAEMCAudioPlayer::PrefetchDataL(class TDesC8 const &) + ?HandlePlaybackCompleteL@CMMAAudioPlayer@@UAEXXZ @ 34 NONAME ; void CMMAAudioPlayer::HandlePlaybackCompleteL(void) + ?RemoveStateListener@CMMAPlayer@@QAEXPAVMMMAPlayerStateListener@@@Z @ 35 NONAME ; void CMMAPlayer::RemoveStateListener(class MMMAPlayerStateListener *) + ??0CMMAEMCAudioPlayer@@IAE@PAVCMMAEMCResolver@@@Z @ 36 NONAME ; CMMAEMCAudioPlayer::CMMAEMCAudioPlayer(class CMMAEMCResolver *) + ?MidiClient@CMMAMIDIPlayer@@QBEPAVCMidiClientUtility@@XZ @ 37 NONAME ; class CMidiClientUtility * CMMAMIDIPlayer::MidiClient(void) const + ??1CMMAVideoUrlPlayer@@UAE@XZ @ 38 NONAME ; CMMAVideoUrlPlayer::~CMMAVideoUrlPlayer(void) + ?ErrorPlaybackComplete@CMMAAudioPlayer@@UAEXH@Z @ 39 NONAME ; void CMMAAudioPlayer::ErrorPlaybackComplete(int) + ??1CMMAEMCAudioPlayer@@UAE@XZ @ 40 NONAME ; CMMAEMCAudioPlayer::~CMMAEMCAudioPlayer(void) + ?MMFactory@CMMAEMCPlayerBase@@QAEPAVCMultimediaFactory@multimedia@@XZ @ 41 NONAME ; class multimedia::CMultimediaFactory * CMMAEMCPlayerBase::MMFactory(void) + ?Players@MMAFunctionServer@@QAEAAV?$RPointerArray@VCMMAPlayer@@@@XZ @ 42 NONAME ; class RPointerArray & MMAFunctionServer::Players(void) + ?PreparePluginSelectionParametersL@CMMAMMFPlayerFactory@@MAEXPAVCMMAMMFResolver@@PAVCMMFFormatSelectionParameters@@@Z @ 43 NONAME ; void CMMAMMFPlayerFactory::PreparePluginSelectionParametersL(class CMMAMMFResolver *, class CMMFFormatSelectionParameters *) + ?PostActionCompleted@CMMAPlayer@@QAEXH@Z @ 44 NONAME ; void CMMAPlayer::PostActionCompleted(int) + ?RealizeL@CMMAVideoUrlPlayer@@UAEXXZ @ 45 NONAME ; void CMMAVideoUrlPlayer::RealizeL(void) + ?SetPlayerInstanceObserver@MMAFunctionServer@@QAEXPAVMMMAPlayerInstanceObserver@@@Z @ 46 NONAME ; void MMAFunctionServer::SetPlayerInstanceObserver(class MMMAPlayerInstanceObserver *) + ?SetPlayerListenerObjectL@CMMAVideoPlayer@@UAEXPAV_jobject@@PAUJNIEnv_@@PAVMMMAEventPoster@@@Z @ 47 NONAME ; void CMMAVideoPlayer::SetPlayerListenerObjectL(class _jobject *, struct JNIEnv_ *, class MMMAEventPoster *) + ?RealizeL@CMMAEMCAudioPlayer@@UAEXXZ @ 48 NONAME ; void CMMAEMCAudioPlayer::RealizeL(void) + ?ControlCount@CMMAPlayer@@QAEHXZ @ 49 NONAME ; int CMMAPlayer::ControlCount(void) + ?DoSetLevelL@CMMAEMCAudioVolumeControl@@UAEXH@Z @ 50 NONAME ; void CMMAEMCAudioVolumeControl::DoSetLevelL(int) + ?PlayCompleteL@CMMAAudioPlayer@@MAEXH@Z @ 51 NONAME ; void CMMAAudioPlayer::PlayCompleteL(int) + ?SourceSize@CMMAVideoPlayer@@UAE?AVTSize@@XZ @ 52 NONAME ; class TSize CMMAVideoPlayer::SourceSize(void) + ?SnapshoterL@CMMAVideoPlayer@@UAEPAVMMMASnapshot@@XZ @ 53 NONAME ; class MMMASnapshot * CMMAVideoPlayer::SnapshoterL(void) + ?GetDuration@CMMAMMFPlayerBase@@UAEXPA_J@Z @ 54 NONAME ; void CMMAMMFPlayerBase::GetDuration(long long *) + ?AddPlayerFactoryL@CMMAManager@@QAEXPAVMMMAPlayerFactory@@@Z @ 55 NONAME ; void CMMAManager::AddPlayerFactoryL(class MMMAPlayerFactory *) + ??0CMMAVideoControl@@QAE@PAVMMMAGuiPlayer@@@Z @ 56 NONAME ; CMMAVideoControl::CMMAVideoControl(class MMMAGuiPlayer *) + ?ClassName@CMMAVideoControl@@UBEABVTDesC16@@XZ @ 57 NONAME ; class TDesC16 const & CMMAVideoControl::ClassName(void) const + ??1CMMAMMFPlayerFactory@@UAE@XZ @ 58 NONAME ; CMMAMMFPlayerFactory::~CMMAMMFPlayerFactory(void) + ?SetVolumeLevelL@CMMAVolumeControl@@QAEXHH@Z @ 59 NONAME ; void CMMAVolumeControl::SetVolumeLevelL(int, int) + ?PostActionCompletedFile@CMMAPlayer@@QAEXXZ @ 60 NONAME ; void CMMAPlayer::PostActionCompletedFile(void) + ?DoGetLevelL@CMMAEMCAudioVolumeControl@@UAEHXZ @ 61 NONAME ; int CMMAEMCAudioVolumeControl::DoGetLevelL(void) + ?ReadCompletedL@CMMAVideoPlayer@@MAEXHABVTDesC8@@@Z @ 62 NONAME ; void CMMAVideoPlayer::ReadCompletedL(int, class TDesC8 const &) + ?Type@CMMAEMCAudioPlayer@@UAEABVTDesC16@@XZ @ 63 NONAME ; class TDesC16 const & CMMAEMCAudioPlayer::Type(void) + ?GetMediaTime@CMMAVideoUrlPlayer@@UAEXPA_J@Z @ 64 NONAME ; void CMMAVideoUrlPlayer::GetMediaTime(long long *) + ?DeallocateL@CMMAVideoUrlPlayer@@UAEXXZ @ 65 NONAME ; void CMMAVideoUrlPlayer::DeallocateL(void) + ??0CMMAMMFPlayerFactory@@QAE@XZ @ 66 NONAME ; CMMAMMFPlayerFactory::CMMAMMFPlayerFactory(void) + ?AddStateListenerL@CMMAPlayer@@QAEXPAVMMMAPlayerStateListener@@@Z @ 67 NONAME ; void CMMAPlayer::AddStateListenerL(class MMMAPlayerStateListener *) + ?StreamControl@CMMAEMCPlayerBase@@QAEPAVMStreamControl@multimedia@@XZ @ 68 NONAME ; class multimedia::MStreamControl * CMMAEMCPlayerBase::StreamControl(void) + ?PrefetchFileL@CMMAAudioPlayer@@MAEXXZ @ 69 NONAME ; void CMMAAudioPlayer::PrefetchFileL(void) + ?PrefetchL@CMMAVideoUrlPlayer@@UAEXXZ @ 70 NONAME ; void CMMAVideoUrlPlayer::PrefetchL(void) + ?AddLevelL@CMMAVolumeControl@@QAEHXZ @ 71 NONAME ; int CMMAVolumeControl::AddLevelL(void) + ?ConstructL@CMMAEMCAudioPlayer@@IAEXXZ @ 72 NONAME ; void CMMAEMCAudioPlayer::ConstructL(void) + ?Control@CMMAPlayer@@QAEPAVCMMAControl@@H@Z @ 73 NONAME ; class CMMAControl * CMMAPlayer::Control(int) + ?PrefetchL@CMMAEMCAudioPlayer@@UAEXXZ @ 74 NONAME ; void CMMAEMCAudioPlayer::PrefetchL(void) + ?StopL@CMMAVideoUrlPlayer@@UAEXH@Z @ 75 NONAME ; void CMMAVideoUrlPlayer::StopL(int) + ??1CMMAVideoControl@@UAE@XZ @ 76 NONAME ; CMMAVideoControl::~CMMAVideoControl(void) + ?AddSourceStreamL@CMMAPlayer@@MAEPAVCMMASourceStream@@PAUJNIEnv_@@PAVMMAFunctionServer@@PAV_jobject@@@Z @ 77 NONAME ; class CMMASourceStream * CMMAPlayer::AddSourceStreamL(struct JNIEnv_ *, class MMAFunctionServer *, class _jobject *) + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/dc_exports.inf --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/dc_exports.inf Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,27 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Exports for direct content subsystem +* +*/ + + +#ifndef __MULTIMEDIA11_DC_EXPORTS_INF__ +#define __MULTIMEDIA11_DC_EXPORTS_INF__ + +PRJ_EXPORTS + +../baseline/inc/mmmacontainer.h |../../../javauis/inc/mmmacontainer.h +../baseline/inc/mmmadirectcontent.h |../../../javauis/inc/mmmadirectContent.h + +#endif diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/eabi/javamobilemediau.def --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/eabi/javamobilemediau.def Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,148 @@ +EXPORTS + _Z10jni_lookupPKc @ 1 NONAME + _ZN10CMMAPlayer11AddControlLEP11CMMAControl @ 2 NONAME + _ZN10CMMAPlayer12ControlCountEv @ 3 NONAME + _ZN10CMMAPlayer12SetLoopCountEi @ 4 NONAME + _ZN10CMMAPlayer15PostObjectEventEN15CMMAPlayerEvent10TEventTypeEP8_jobject @ 5 NONAME + _ZN10CMMAPlayer15PostStringEventEN15CMMAPlayerEvent10TEventTypeERK7TDesC16 @ 6 NONAME + _ZN10CMMAPlayer16AddSourceStreamLEP7JNIEnv_P17MMAFunctionServerP8_jobject @ 7 NONAME + _ZN10CMMAPlayer17AddStateListenerLEP23MMMAPlayerStateListener @ 8 NONAME + _ZN10CMMAPlayer19RemoveStateListenerEP23MMMAPlayerStateListener @ 9 NONAME + _ZN10CMMAPlayer7ControlEi @ 10 NONAME + _ZN11CMMAManager17AddPlayerFactoryLEP17MMMAPlayerFactory @ 11 NONAME + _ZN13CTimeOutTimer4NewLEiR14MTimeOutNotify @ 12 NONAME + _ZN15CMMAAudioPlayer13PlayCompleteLEi @ 13 NONAME + _ZN15CMMAAudioPlayer13PrefetchDataLERK6TDesC8 @ 14 NONAME + _ZN15CMMAAudioPlayer13PrefetchFileLEv @ 15 NONAME + _ZN15CMMAAudioPlayer21ErrorPlaybackCompleteEi @ 16 NONAME + _ZN15CMMAAudioPlayer23HandlePlaybackCompleteLEv @ 17 NONAME + _ZN15CMMAVideoPlayer10SourceSizeEv @ 18 NONAME + _ZN15CMMAVideoPlayer11SetDisplayLEP11MMMADisplay @ 19 NONAME + _ZN15CMMAVideoPlayer11SnapshoterLEv @ 20 NONAME + _ZN15CMMAVideoPlayer13TakeSnapshotLEP14TRequestStatusRK5TSizeRK17CMMAImageSettings @ 21 NONAME + _ZN15CMMAVideoPlayer14ReadCompletedLEiRK6TDesC8 @ 22 NONAME + _ZN15CMMAVideoPlayer14SnapshotBitmapEv @ 23 NONAME + _ZN15CMMAVideoPlayer15SnapshotEncodedEv @ 24 NONAME + _ZN15CMMAVideoPlayer21NotifyWithStringEventEN15CMMAPlayerEvent10TEventTypeERK7TDesC16 @ 25 NONAME + _ZN15CMMAVideoPlayer24SetPlayerListenerObjectLEP8_jobjectP7JNIEnv_P15MMMAEventPoster @ 26 NONAME + _ZN15CMMAVideoPlayer4TypeEv @ 27 NONAME + _ZN16CMMAVideoControl13SnapshotReadyEv @ 28 NONAME + _ZN16CMMAVideoControlC1EP13MMMAGuiPlayer @ 29 NONAME + _ZN16CMMAVideoControlC2EP13MMMAGuiPlayer @ 30 NONAME + _ZN16CMMAVideoControlD0Ev @ 31 NONAME + _ZN16CMMAVideoControlD1Ev @ 32 NONAME + _ZN16CMMAVideoControlD2Ev @ 33 NONAME + _ZN17CMMAEMCPlayerBase13StreamControlEv @ 34 NONAME + _ZN17CMMAEMCPlayerBase9MMFactoryEv @ 35 NONAME + _ZN17CMMAMMFPlayerBase10ControllerEv @ 36 NONAME + _ZN17CMMAMMFPlayerBase11GetDurationEPx @ 37 NONAME + _ZN17CMMAMMFPlayerBase6DoOpenE4TUidRK6TDesC8S0_S3_20TMMFPrioritySettings @ 38 NONAME + _ZN17CMMAVolumeControl15SetVolumeLevelLEii @ 39 NONAME + _ZN17CMMAVolumeControl9AddLevelLEv @ 40 NONAME + _ZN17MMAFunctionServer25SetPlayerInstanceObserverEP26MMMAPlayerInstanceObserver @ 41 NONAME + _ZN17MMAFunctionServer26StaticAddObjectFromHandleLEPS_i @ 42 NONAME + _ZN17MMAFunctionServer7PlayersEv @ 43 NONAME + _ZN18CMMAEMCAudioPlayer10ConstructLEv @ 44 NONAME + _ZN18CMMAEMCAudioPlayer13PlayCompleteLEi @ 45 NONAME + _ZN18CMMAEMCAudioPlayer13PrefetchDataLERK6TDesC8 @ 46 NONAME + _ZN18CMMAEMCAudioPlayer13PrefetchFileLEv @ 47 NONAME + _ZN18CMMAEMCAudioPlayer14ReadCompletedLEiRK6TDesC8 @ 48 NONAME + _ZN18CMMAEMCAudioPlayer4TypeEv @ 49 NONAME + _ZN18CMMAEMCAudioPlayer8RealizeLEv @ 50 NONAME + _ZN18CMMAEMCAudioPlayer9PrefetchLEv @ 51 NONAME + _ZN18CMMAEMCAudioPlayerC1EP15CMMAEMCResolver @ 52 NONAME + _ZN18CMMAEMCAudioPlayerC2EP15CMMAEMCResolver @ 53 NONAME + _ZN18CMMAEMCAudioPlayerD0Ev @ 54 NONAME + _ZN18CMMAEMCAudioPlayerD1Ev @ 55 NONAME + _ZN18CMMAEMCAudioPlayerD2Ev @ 56 NONAME + _ZN18CMMAVideoUrlPlayer10ConstructLERK7TDesC16 @ 57 NONAME + _ZN18CMMAVideoUrlPlayer11DeallocateLEv @ 58 NONAME + _ZN18CMMAVideoUrlPlayer11HandleEventERK9TMMFEvent @ 59 NONAME + _ZN18CMMAVideoUrlPlayer12GetMediaTimeEPx @ 60 NONAME + _ZN18CMMAVideoUrlPlayer5StopLEi @ 61 NONAME + _ZN18CMMAVideoUrlPlayer6CloseLEv @ 62 NONAME + _ZN18CMMAVideoUrlPlayer6StartLEv @ 63 NONAME + _ZN18CMMAVideoUrlPlayer8RealizeLEv @ 64 NONAME + _ZN18CMMAVideoUrlPlayer9PrefetchLEv @ 65 NONAME + _ZN18CMMAVideoUrlPlayerC1EP15CMMAMMFResolver @ 66 NONAME + _ZN18CMMAVideoUrlPlayerC2EP15CMMAMMFResolver @ 67 NONAME + _ZN18CMMAVideoUrlPlayerD0Ev @ 68 NONAME + _ZN18CMMAVideoUrlPlayerD1Ev @ 69 NONAME + _ZN18CMMAVideoUrlPlayerD2Ev @ 70 NONAME + _ZN20CMMAMMFPlayerFactory13CreatePlayerLEP29CMMFFormatSelectionParametersPK7TDesC16 @ 71 NONAME + _ZN20CMMAMMFPlayerFactory33PreparePluginSelectionParametersLEP15CMMAMMFResolverP29CMMFFormatSelectionParameters @ 72 NONAME + _ZN20CMMAMMFPlayerFactoryC2Ev @ 73 NONAME + _ZN20CMMAMMFPlayerFactoryD0Ev @ 74 NONAME + _ZN20CMMAMMFPlayerFactoryD1Ev @ 75 NONAME + _ZN20CMMAMMFPlayerFactoryD2Ev @ 76 NONAME + _ZN22CMMAAudioVolumeControl4NewLEP15CMMAAudioPlayer @ 77 NONAME + _ZN25CMMAEMCAudioVolumeControl11DoGetLevelLEv @ 78 NONAME + _ZN25CMMAEMCAudioVolumeControl11DoSetLevelLEi @ 79 NONAME + _ZN25CMMAEMCAudioVolumeControl4NewLER18CMMAEMCAudioPlayer @ 80 NONAME + _ZN25CMMAEMCAudioVolumeControlC1ER18CMMAEMCAudioPlayer @ 81 NONAME + _ZN25CMMAEMCAudioVolumeControlC2ER18CMMAEMCAudioPlayer @ 82 NONAME + _ZNK11CMMAControl15PublicClassNameEv @ 83 NONAME + _ZNK14CMMAMIDIPlayer10MidiClientEv @ 84 NONAME + _ZNK16CMMAVideoControl9ClassNameEv @ 85 NONAME + _ZTI10CMMAPlayer @ 86 NONAME + _ZTI11CMMAControl @ 87 NONAME + _ZTI13CTimeOutTimer @ 88 NONAME + _ZTI14CMMAMIDIPlayer @ 89 NONAME + _ZTI16CMMAVideoControl @ 90 NONAME + _ZTI17CMMAMMFPlayerBase @ 91 NONAME + _ZTI17CMMAStreamRequest @ 92 NONAME + _ZTI17CMMAVolumeControl @ 93 NONAME + _ZTI17MMAFunctionServer @ 94 NONAME + _ZTI18CHXMetaDataUtility @ 95 NONAME + _ZTI18CMMAVideoUrlPlayer @ 96 NONAME + _ZTI20CMMAMMFPlayerFactory @ 97 NONAME + _ZTI26CPlaybackCompletedCallback @ 98 NONAME + _ZTIN15CMMAMIDIControl23CChannelVolumeEventWaitE @ 99 NONAME + _ZTIN18CMMAVideoUrlPlayer26CMMAVideoUrlPlayerDelegateE @ 100 NONAME + _ZTIN18CMMAVideoUrlPlayer36CMMAVideoUrlPlayerClipStreamDelegateE @ 101 NONAME + _ZTIN18CMMAVideoUrlPlayer36CMMAVideoUrlPlayerLiveStreamDelegateE @ 102 NONAME + _ZTIN19CMMAStopTimeControl10CStopTimerE @ 103 NONAME + _ZTV10CMMAPlayer @ 104 NONAME + _ZTV11CMMAControl @ 105 NONAME + _ZTV13CTimeOutTimer @ 106 NONAME + _ZTV14CMMAMIDIPlayer @ 107 NONAME + _ZTV16CMMAVideoControl @ 108 NONAME + _ZTV17CMMAMMFPlayerBase @ 109 NONAME + _ZTV17CMMAStreamRequest @ 110 NONAME + _ZTV17CMMAVolumeControl @ 111 NONAME + _ZTV17MMAFunctionServer @ 112 NONAME + _ZTV18CHXMetaDataUtility @ 113 NONAME + _ZTV18CMMAVideoUrlPlayer @ 114 NONAME + _ZTV20CMMAMMFPlayerFactory @ 115 NONAME + _ZTV26CPlaybackCompletedCallback @ 116 NONAME + _ZTVN15CMMAMIDIControl23CChannelVolumeEventWaitE @ 117 NONAME + _ZTVN18CMMAVideoUrlPlayer26CMMAVideoUrlPlayerDelegateE @ 118 NONAME + _ZTVN18CMMAVideoUrlPlayer36CMMAVideoUrlPlayerClipStreamDelegateE @ 119 NONAME + _ZTVN18CMMAVideoUrlPlayer36CMMAVideoUrlPlayerLiveStreamDelegateE @ 120 NONAME + _ZTVN19CMMAStopTimeControl10CStopTimerE @ 121 NONAME + _ZThn160_N18CMMAVideoUrlPlayer11HandleEventERK9TMMFEvent @ 122 NONAME + _ZThn288_N15CMMAAudioPlayer21ErrorPlaybackCompleteEi @ 123 NONAME + _ZThn288_N15CMMAAudioPlayer23HandlePlaybackCompleteLEv @ 124 NONAME + _ZThn296_N15CMMAVideoPlayer10SourceSizeEv @ 125 NONAME + _ZThn296_N15CMMAVideoPlayer11SetDisplayLEP11MMMADisplay @ 126 NONAME + _ZThn296_N15CMMAVideoPlayer11SnapshoterLEv @ 127 NONAME + _ZThn296_N15CMMAVideoPlayer21NotifyWithStringEventEN15CMMAPlayerEvent10TEventTypeERK7TDesC16 @ 128 NONAME + _ZThn296_N18CMMAVideoUrlPlayerD0Ev @ 129 NONAME + _ZThn296_N18CMMAVideoUrlPlayerD1Ev @ 130 NONAME + _ZThn300_N15CMMAVideoPlayer13TakeSnapshotLEP14TRequestStatusRK5TSizeRK17CMMAImageSettings @ 131 NONAME + _ZThn300_N15CMMAVideoPlayer14SnapshotBitmapEv @ 132 NONAME + _ZThn300_N15CMMAVideoPlayer15SnapshotEncodedEv @ 133 NONAME + _ZThn300_N18CMMAVideoUrlPlayerD0Ev @ 134 NONAME + _ZThn300_N18CMMAVideoUrlPlayerD1Ev @ 135 NONAME + _ZThn4_N15CMMAVideoPlayer14ReadCompletedLEiRK6TDesC8 @ 136 NONAME + _ZThn4_N18CMMAEMCAudioPlayer14ReadCompletedLEiRK6TDesC8 @ 137 NONAME + _ZThn4_N18CMMAEMCAudioPlayerD0Ev @ 138 NONAME + _ZThn4_N18CMMAEMCAudioPlayerD1Ev @ 139 NONAME + _ZThn4_N18CMMAVideoUrlPlayerD0Ev @ 140 NONAME + _ZThn4_N18CMMAVideoUrlPlayerD1Ev @ 141 NONAME + _ZThn4_N20CMMAMMFPlayerFactoryD0Ev @ 142 NONAME + _ZThn4_N20CMMAMMFPlayerFactoryD1Ev @ 143 NONAME + _ZThn8_N16CMMAVideoControl13SnapshotReadyEv @ 144 NONAME + _ZThn8_N16CMMAVideoControlD0Ev @ 145 NONAME + _ZThn8_N16CMMAVideoControlD1Ev @ 146 NONAME + diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/exports.inf --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/exports.inf Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +PRJ_EXPORTS +#include +#include "dc_exports.inf" + +../camerasound/data/CamcorderJavaCapture.wav /epoc32/release/winscw/udeb/z/system/sounds/digital/CamcorderJavaCapture.wav +../camerasound/data/CamcorderJavaCapture.wav /epoc32/release/winscw/urel/z/system/sounds/digital/CamcorderJavaCapture.wav +../camerasound/data/CamcorderJavaCapture.wav /epoc32/release/armv5/udeb/z/system/sounds/digital/CamcorderJavaCapture.wav +../camerasound/data/CamcorderJavaCapture.wav /epoc32/release/armv5/urel/z/system/sounds/digital/CamcorderJavaCapture.wav + +../camerasound/data/CamcorderJavaStart.wav /epoc32/release/winscw/udeb/z/system/sounds/digital/CamcorderJavaStart.wav +../camerasound/data/CamcorderJavaStart.wav /epoc32/release/winscw/urel/z/system/sounds/digital/CamcorderJavaStart.wav +../camerasound/data/CamcorderJavaStart.wav /epoc32/release/armv5/udeb/z/system/sounds/digital/CamcorderJavaStart.wav +../camerasound/data/CamcorderJavaStart.wav /epoc32/release/armv5/urel/z/system/sounds/digital/CamcorderJavaStart.wav + +// Generic configuration interface for mobilemedia cenrep settings +// mobilemedia_102828A1 implementation specifics for cenrep data +../conf/mobilemedia.confml APP_LAYER_CONFML(mobilemedia.confml) +../conf/mobilemedia_102828A1.crml APP_LAYER_CRML(mobilemedia_102828A1.crml) \ No newline at end of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/build/javamobilemedia.pro --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/build/javamobilemedia.pro Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,130 @@ +# +# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +# All rights reserved. +# This component and the accompanying materials are made available +# under the terms of "Eclipse Public License v1.0" +# which accompanies this distribution, and is available +# at the URL "http://www.eclipse.org/legal/epl-v10.html". +# +# Initial Contributors: +# Nokia Corporation - initial contribution. +# +# Contributors: +# +# Description: +# + +TARGET=javamobilemedia +TEMPLATE=lib +CONFIG += omj java stl + +include(../../../inc/build_defines.pri) + +DEFINES += RD_JAVA_VOLUME_CONTROL +DEFINES += RD_JAVA_OMA_DRM_V2 + +INCLUDEPATH += /epoc32/include/mmf/common \ +# ../animated_gif/inc \ + ../baseline/inc \ + ../src_drmv2/inc \ + ../directcontent/inc \ + ../camerasound/inc \ + ../volumekeys/inc \ + ../audiostreaming/inc \ + /epoc32/include/mw/Qt \ + ../utils/inc + +# ../../remconobserver_akn/inc \ + +SOURCES += ../baseline/src/*.cpp \ + # ../animated_gif/src/*.cpp \ + ../camerasound/src/*.cpp \ + ../directcontent/src/*.cpp \ + ../src_drmv2/src/*.cpp \ + ../volumekeys/src/*.cpp \ + ../audiostreaming/src/*.cpp \ + ../utils/src/*.cpp + +contains(PROJECT_DEFINES,RD_JAVA_HTTP_EMC_ENABLED) { + INCLUDEPATH += ../baseline/inc.emc \ + ../audiostreaming/inc.emc + + SOURCES += ../baseline/src.emc/*.cpp \ + ../audiostreaming/src.emc/*.cpp + + LIBS += -lEnhancedMediaClient \ + -lMetaDataUtility \ + -lapmime\ + -lapgrfx \ + -lapmime \ + -lflogger + +} +else{ + INCLUDEPATH += ../baseline/inc.mmf \ + ../audiostreaming/inc.mmf + + SOURCES += ../baseline/src.mmf/*.cpp \ + ../audiostreaming/src.mmf/*.cpp +} + +contains(PROJECT_DEFINES,RD_JAVA_NGA_ENABLED) { + INCLUDEPATH += ../baseline/inc.nga + + SOURCES += ../baseline/src.nga/*.cpp + + LIBS += -lmediaclientvideodisplay +} +else { + INCLUDEPATH += ../baseline/inc.dsa + + SOURCES += ../baseline/src.dsa/*.cpp +} + +LIBS += -lAknIcon \ + -laknskins \ + -laknskinsrv \ + -lapgrfx \ + -lapmime \ + -lBitmapTransforms \ + -lDRMHelper \ + -lDrmAudioPlayUtility \ + -lImageConversion \ + -lIHL \ + -lMMFControllerFramework \ + -lMediaClientAudio \ + -lMmfStandardCustomCommands \ +# -lRemConCoreApi \ +# -lRemConInterfaceBase \ + -lbafl \ + -lbitgdi \ + -lcaf \ + -lcafutils \ + -lcentralrepository \ + -lcone \ + -lecam \ + -lecom \ + -leswtqt \ + -lefsrv \ + -leikcoctl \ + -leikcore \ + -lesock \ + -leuser \ + -lfbscli \ + -lflogger \ + -lmediaclientvideo \ + -lmidiclient \ + -lws32 \ + -lQtGui \ + # -ljavaremconobserver \ + +# Static libraries must use .lib, otherwise the platform build fails as +# qmake incorrectly defaults the library to a dynamic lib. +LIBS += -lhxmetadatautil.lib + + +!contains(PROJECT_DEFINES,RD_JAVA_HTTP_EMC_ENABLED) { + defBlock = "deffile ./~/javamobilemedia_5_0.def" +} + +include(../../../build/omj.pri) diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/camerasound/data/CamcorderJavaCapture.wav Binary file javauis/mmapi_qt/camerasound/data/CamcorderJavaCapture.wav has changed diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/camerasound/data/CamcorderJavaStart.wav Binary file javauis/mmapi_qt/camerasound/data/CamcorderJavaStart.wav has changed diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/camerasound/inc/cmmacamerasound.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/camerasound/inc/cmmacamerasound.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to play sound from file. +* +*/ + + +#ifndef CMMACAMERASOUND_H +#define CMMACAMERASOUND_H + +// INCLUDES +#include + +// CLASS DECLARATION +/** +* This class is used to play sound from file. +*/ +NONSHARABLE_CLASS(CMMACameraSound) : public CBase, + public MMdaAudioPlayerCallback +{ +public: // Constructor and destructor + + /** + * Two-phased constructor. + */ + static CMMACameraSound* NewLC(); + + /** + * Destructor. + */ + virtual ~CMMACameraSound(); + + +public: // New functions + + /** + * Plays sound from a file when capturing a image. + */ + static void PlayImageCaptureSoundL(); + + /** + * Plays sound from a file when video recording starts. + */ + static void PlayVideoRecordSoundL(); + +protected: // New functions + + /** + * Plays sound from a file. + * @param aFileName - The full path name of the file + * containing the audio data. + */ + void PlaySoundL(const TDesC& aFileName); + + +public: // from MMdaAudioPlayerCallback + + void MapcInitComplete(TInt aError, + const TTimeIntervalMicroSeconds& /*aDuration*/); + + void MapcPlayComplete(TInt aError); + + +private: // Constructors + + /** + * C++ default constructor. + */ + CMMACameraSound(); + + /** + * By default Symbian 2nd phase constructor is private. + */ + void ConstructL(); + +private: //Data + + CActiveSchedulerWait* iActiveSchedulerWait; // owned + + TInt iError; +}; + +#endif // CMMACAMERASOUND_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/camerasound/src/cmmacamerasound.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/camerasound/src/cmmacamerasound.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,150 @@ +/* +* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to play sound from file +* +*/ + + + +// INCLUDE FILES +#include "cmmacamerasound.h" + +#include +#include +#include + +//CONSTANTS +_LIT(KMMASnapshotSound, "Z:\\System\\Sounds\\Digital\\CamcorderJavaCapture.wav"); +_LIT(KMMAVideoSound, "Z:\\System\\Sounds\\Digital\\CamcorderJavaStart.wav"); + + +// ============================ MEMBER FUNCTIONS =============================== + +// ----------------------------------------------------------------------------- +// CMMACameraSound::CMMACameraSound +// C++ default constructor can NOT contain any code, that +// might leave. +// ----------------------------------------------------------------------------- +// +CMMACameraSound::CMMACameraSound() +{ +} + +// ----------------------------------------------------------------------------- +// CMMACameraSound::NewLC +// Two-phased constructor. +// ----------------------------------------------------------------------------- +// +CMMACameraSound* CMMACameraSound::NewLC() +{ + CMMACameraSound* self = new(ELeave) CMMACameraSound; + CleanupStack::PushL(self); + self->ConstructL(); + return self; +} + + +// Destructor +CMMACameraSound::~CMMACameraSound() +{ + delete iActiveSchedulerWait; +} + +// ----------------------------------------------------------------------------- +// CMMACameraSound::ConstructL +// Symbian 2nd phase constructor can leave. +// ----------------------------------------------------------------------------- +// +void CMMACameraSound::ConstructL() +{ + iActiveSchedulerWait = new(ELeave) CActiveSchedulerWait(); +} + +// ----------------------------------------------------------------------------- +// PlayImageCaptureSoundL() +// ----------------------------------------------------------------------------- +// +void CMMACameraSound::PlayImageCaptureSoundL() +{ + CMMACameraSound* cameraSound = NewLC(); + cameraSound->PlaySoundL(KMMASnapshotSound()); + CleanupStack::PopAndDestroy(cameraSound); +} + +// ----------------------------------------------------------------------------- +// PlayVideoRecordSoundL() +// ----------------------------------------------------------------------------- +// +void CMMACameraSound::PlayVideoRecordSoundL() +{ + CMMACameraSound* cameraSound = NewLC(); + cameraSound->PlaySoundL(KMMAVideoSound()); + CleanupStack::PopAndDestroy(cameraSound); +} + +// ----------------------------------------------------------------------------- +// PlaySoundL() +// ----------------------------------------------------------------------------- +// +void CMMACameraSound::PlaySoundL(const TDesC& aFileName) +{ + iError = KErrNone; + CMdaAudioPlayerUtility* player = + CMdaAudioPlayerUtility::NewFilePlayerL( + aFileName, *this, KAudioPriorityVideoRecording, + TMdaPriorityPreference(KAudioPrefCamera), NULL); + CleanupStack::PushL(player); + + //wait until init is completed + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + //leave if there was error in init + User::LeaveIfError(iError); + + player->Play(); + //wait until play is completed + if (!iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->Start(); + } + //leave if there was error in play + User::LeaveIfError(iError); + + //close player + player->Close(); + CleanupStack::PopAndDestroy(player); +} + +void CMMACameraSound::MapcInitComplete(TInt aError, + const TTimeIntervalMicroSeconds& /*aDuration*/) +{ + iError = aError; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } +} + +void CMMACameraSound::MapcPlayComplete(TInt aError) +{ + iError = aError; + if (iActiveSchedulerWait->IsStarted()) + { + iActiveSchedulerWait->AsyncStop(); + } +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/conf/mobilemedia.confml Binary file javauis/mmapi_qt/conf/mobilemedia.confml has changed diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/conf/mobilemedia_102828A1.crml Binary file javauis/mmapi_qt/conf/mobilemedia_102828A1.crml has changed diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/inc/cmmadcdisplay.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/inc/cmmadcdisplay.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,140 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +#ifndef CMMADCDISPLAY_H +#define CMMADCDISPLAY_H + +// INCLUDES +#include "mmmadisplay.h" +#include "mmmadirectcontent.h" +#include "cmmadisplay.h" + +// CONSTANTS + +// FORWARD DECLARATIONS +class MMMAGuiPlayer; +class MMMADisplayWindow; +class MMMAContainer; +class MMAFunctionServer; +class CMMADCRepaintEvent; + +// CLASS DECLARATION +/** +* This class is used with dynamic display mode to render direct content +* using direct container. +*/ +NONSHARABLE_CLASS(CMMADCDisplay): + public CMMADisplay, + public MMMADirectContent +{ +public: + /** + * Creates new instance. + * @param aPlayer provides content + */ + static CMMADCDisplay* NewLC(MMMAGuiPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aGUIObject); + virtual ~CMMADCDisplay(); + +public: // From MMMADisplay + void DrawFrameL(const CFbsBitmap* aBitmap); + void SetDisplaySizeL(const TSize& aSize); + void SetDisplayLocationL(const TPoint& aPosition); + TPoint DisplayLocation(); + void SetFullScreenL(TBool aFullScreen); + void SourceSizeChanged(const TSize& aSourceSize); + TBool IsVisible(); + + /** + * Gets notification that there is container to draw assigned + * + * @return ETrue if container have been set + * EFalse if container is not set + */ + virtual TBool HasContainer(); + + /** + * Gets resources necessary to start DirectScreenAccess + * Doesn't run in mmapi event server thread! + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aThreadType" Indicates the thread type (ESWT or MMAPI) + */ + void UIGetDSAResources( + MUiEventConsumer& aConsumer, + MMMADisplay::TThreadType aThreadType); + + /** + * Invokes a callback in ESWT thread + * + * @since S60 v5.0 + * @param "aConsumer" A consumer of callback + * @param "aCallbackId" A number identifying the callback + */ + void UIGetCallback(MUiEventConsumer& aConsumer, TInt aCallbackId); + +public: // From MMMADirectContent + void MdcContainerVisibilityChanged(TBool aVisible); + void MdcContentRectChanged(const TRect& aContentRect, + const TRect& aClipRect); + void MdcContainerWindowRectChanged(const TRect& aRect); + void MdcContainerDestroyed(); + void MdcSetContainer(MMMAContainer* aContainer); + CFbsBitmap* MdcFrameBuffer() const; + TSize MdcSourceSize(); + +public: // From CMMADisplay + void MdcContentBoundsChanged(const TRect& aRect); + +private: // new methods + /** + * Creates bitmap when bitmap mode is used + * @return error code + */ + TInt InitBitmapMode(); + + static void SetDrawRectL(CMMADCDisplay* aDisplay, + TSize* aSize); + + CMMADCDisplay(MMMAGuiPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aGUIObject); +private: // data + + // Not own. + MMMAContainer* iContainer; + + // Own. + CFbsBitmap* iBitmap; + + // Not own + MMAFunctionServer* iEventSource; + + // direct content java object + jobject iGUIObject; + + // Own + CMMADCRepaintEvent* iRepaint; + + // Not own + MMMAGuiPlayer* iPlayer; +}; + +#endif // CMMADCDISPLAY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/inc/cmmadcfullscreenevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/inc/cmmadcfullscreenevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content fullscreen event. +* +*/ + + +#ifndef CMMADCFULLSCREENEVENT_H +#define CMMADCFULLSCREENEVENT_H + +//#include +#include "cmmaevent.h" + + +// CLASS DECLARATION +/** +* This class is used to send direct content fullscreen event. +* +* +*/ +NONSHARABLE_CLASS(CMMADCFullScreenEvent): public CMMAEvent +{ +public: + /** + * Default constructor. + * @param aGUIObject Java object to set fullscreen status + * @param aFullScreen Indicates whether or not to render in full + * screen mode + */ + CMMADCFullScreenEvent(jobject aGUIObject, TBool aFullScreen); + +private: // from CJavaEvent + /** + * @param aJni JNI environment + */ + void Dispatch(JNIEnv& aJni); +}; + +#endif // CMMADCFULLSCREENEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/inc/cmmadcinvalidateevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/inc/cmmadcinvalidateevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content invalidate event +* +*/ + + +#ifndef CMMADCINVALIDATEEVENT_H +#define CMMADCINVALIDATEEVENT_H + +//#include +#include "cmmaevent.h" + + +// CLASS DECLARATION +/** +* This class is used to send direct content invalidate event. +* +*/ +NONSHARABLE_CLASS(CMMADCInvalidateEvent): public CMMAEvent +{ +public: + /** + * Constructor. + * @param aGUIObject Java object to invalidate + * @param aSize New size for direct content + */ + CMMADCInvalidateEvent(jobject aGUIObject, TSize aSize); + +private: // from CJavaEvent + /** + * @param aJni JNI environment + */ + void Dispatch(JNIEnv& aJni); + +private: + // New size to set + TSize iSize; +}; + +#endif // CMMADCINVALIDATEEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/inc/cmmadcrepaintevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/inc/cmmadcrepaintevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content repaint event. +* +*/ + + +#ifndef CMMADCREPAINTEVENT_H +#define CMMADCREPAINTEVENT_H + +//#include +#include "cmmaevent.h" + + +// CLASS DECLARATION +/** +* This class is used to send direct content repaint event. +* +*/ +NONSHARABLE_CLASS(CMMADCRepaintEvent): public CMMAEvent +{ +public: + /** + * Default constructor. + * @param aGUIObject Java object to call. + */ + CMMADCRepaintEvent(jobject aGUIObject); + + /** + * @return true if this event is active and may not be sent + */ + TBool IsActive(); + + /** + * Sets this event active and IsActive will return true. + * IsActive methos will return false after this event is dispatched. + */ + void SetActive(); + +private: // from CJavaEvent + /** + * @param aJni JNI environment + */ + void Dispatch(JNIEnv& aJni); + +}; + +#endif // CMMADCREPAINTEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/src/cmmadcdisplay.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/src/cmmadcdisplay.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,361 @@ +/* +* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + + +// Include Files +#include +#include +#include + +#include "cmmaplayerevent.h" +#include "mmmaguiplayer.h" +#include "mmmadisplaywindow.h" +#include "cmmadcdisplay.h" +#include "mmmacontainer.h" +#include "mmafunctionserver.h" +#include "cmmadcrepaintevent.h" +#include "cmmadcfullscreenevent.h" +#include "cmmadcinvalidateevent.h" + +// CONSTRUCTION +// Static constructor, leaves pointer to cleanup-stack +CMMADCDisplay* CMMADCDisplay::NewLC(MMMAGuiPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aGUIObject) +{ + CMMADCDisplay* self = + new(ELeave) CMMADCDisplay(aPlayer, aEventSource, aGUIObject); + CleanupStack::PushL(self); + self->iRepaint = new(ELeave) CMMADCRepaintEvent(aGUIObject); + return self; +} + +// Destructor (virtual by CBase) +CMMADCDisplay::~CMMADCDisplay() +{ + if (iContainer) + { + iContainer->MdcRemoveContent(); + } + delete iBitmap; + delete iRepaint; +} + +// interface MMMADisplay +void CMMADCDisplay::DrawFrameL(const CFbsBitmap* aBitmap) +{ + // This method is called only if bitmap is used. + TInt err = InitBitmapMode(); + + if (iVisible && iWindow && + iContainer && iContainer->MdcContainerVisibility() && + err == KErrNone) + { + iWindow->DrawFrameL(aBitmap); + + // container will draw bitmap obtained with MdcFrameBuffer method + if (!iRepaint->IsActive()) + { + iRepaint->SetActive(); + iEventSource->PostEvent(iRepaint, CMMAEvent::EEventPriority); + } + } +} + +// interface MMMADisplay +void CMMADCDisplay::SetDisplaySizeL(const TSize& aSize) +{ + LOG2( EJavaMMAPI, EInfo, "CMMADCDisplay::SetDisplaySizeL w %d h %d", + aSize.iWidth, aSize.iHeight); + // user rect contains size set from java. + iUserRect.SetSize(aSize); + + if (iContainer) + { + CMMADCInvalidateEvent* event = + new(ELeave)CMMADCInvalidateEvent(iGUIObject, aSize); + iEventSource->PostEvent(event, CMMAEvent::EEventPriority); + } +} + +// interface MMMADisplay +void CMMADCDisplay::SetDisplayLocationL(const TPoint& /*aPosition*/) +{ + LOG( EJavaMMAPI, EInfo, "CMMADCDisplay::SetDisplayLocationL"); + // This method only works when the USE_DIRECT_VIDEO mode is set. + // In USE_GUI_PRIMITIVE mode, this call will be ignored. +} + +// interface MMMADisplay +TPoint CMMADCDisplay::DisplayLocation() +{ + LOG( EJavaMMAPI, EInfo, "CMMADCDisplay::DisplayLocation"); + // This method returns always (0,0), + // because SetDisplayLocationL call is ignored. + return TPoint(0, 0); +} + +// interface MMMADisplay +void CMMADCDisplay::SetFullScreenL(TBool aFullScreen) +{ + LOG1( EJavaMMAPI, EInfo, "CMMADCDisplay::SetFullScreenL %d", aFullScreen); + // This method tries to set eSWT Widget size to its parent size. + // If real full screen mode is needed parent Composite must be in + // fullscreen mode (for example with MobileShell's setFullScreenMode method). + if (iContainer) + { + CMMADCFullScreenEvent* event = + new(ELeave)CMMADCFullScreenEvent(iGUIObject, aFullScreen); + iEventSource->PostEvent(event, CMMAEvent::EEventPriority); + } +} + +// interface MMMADisplay +void CMMADCDisplay::SourceSizeChanged(const TSize& aSourceSize) +{ + LOG2( EJavaMMAPI, EInfo, "CMMADCDisplay::SourceSizeChanged %d %d", + aSourceSize.iWidth, + aSourceSize.iHeight); + +#ifdef RD_JAVA_NGA_ENABLED + if (iWindow) + { + TPoint topLeft(0, 0); + iWindow->SetVideoCropRegion(TRect(topLeft,aSourceSize)); + } +#endif + + if (iWindow) + { + TRect tmp(TPoint(0, 0), aSourceSize); + iWindow->SetDrawRect(tmp); + iWindow->SetWindowRect(tmp,MMMADisplay::EMmaThread); + + // set visibility without using event server because this is called + // from MMA thread + if (iContainer) + { + if (iContainer->MdcContainerVisibility()) + { + iWindow->SetVisible(ETrue, EFalse); + } + } + } +} + +// interface MMMADisplay +TBool CMMADCDisplay::IsVisible() +{ + TBool visible = EFalse; + if (iContainer) + { + visible = iContainer->MdcContainerVisibility(); + } + // else invisible + + // return true if both are visible + return iVisible && visible; +} + + +// interface MMMADisplay +TBool CMMADCDisplay::HasContainer() +{ + return iContainer != NULL; +} + + +// interface MMMADirectContent +void CMMADCDisplay::MdcContainerVisibilityChanged(TBool aVisible) +{ + LOG1( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcContainerVisibilityChanged aVisible %d", + aVisible); + if (iWindow) + { + iWindow->SetVisible(aVisible && iVisible); + } + LOG( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcContainerVisibilityChanged OK"); +} + +// interface MMMADirectContent +void CMMADCDisplay::MdcContentRectChanged(const TRect& aContentRect, + const TRect& aParentRect) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADCDisplay::MdcContentRectChanged"); + if (iWindow) + { + TSize size = aContentRect.Size(); + iWindow->SetDrawRectThread(TRect(size)); + TInt err = iEventSource->ExecuteTrap(CMMADCDisplay::SetDrawRectL, + this, + &size); + if (err == KErrNone) + { + // bitmap window ignores window rect and position + iWindow->SetWindowRect(aParentRect,MMMADisplay::EUiThread); + iWindow->SetPosition(aContentRect.iTl - aParentRect.iTl); + } + } +} + +void CMMADCDisplay::MdcContainerWindowRectChanged(const TRect& +#ifdef RD_JAVA_NGA_ENABLED + aRect +#endif + ) +{ + LOG( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcContainerWindowRectChanged"); + +#ifdef RD_JAVA_NGA_ENABLED + if (iWindow) + { + iWindow->SetRWindowRect(aRect, MMMADisplay::EUiThread); + } +#endif +} + +// interface MMMADirectContent +void CMMADCDisplay::MdcContainerDestroyed() +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADCDisplay::MdcContainerDestroyed"); + if (iContainer) + { + iContainer->MdcRemoveContent(); + } + + iContainer = NULL; + if (iWindow) + { + iWindow->SetVisible(EFalse); + iWindow->ContainerDestroyed(); + } +} + +// interface MMMADirectContent +void CMMADCDisplay::MdcSetContainer(MMMAContainer* aContainer) +{ + iContainer = aContainer; + TSize sourceSize = iPlayer->SourceSize(); + LOG2( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcSetContainer source size %d %d", + sourceSize.iWidth, sourceSize.iHeight); + aContainer->MdcInvalidate(sourceSize); + if (iWindow) + { + // Notify window that container has been set + iWindow->ContainerSet(); + + TRect controlRect; + TRect parentRect; + iContainer->MdcGetContentRect(controlRect, parentRect); + + // bitmap window ignores window rect and position + iWindow->SetWindowRect(parentRect,MMMADisplay::EUiThread); + iWindow->SetPosition(controlRect.iTl - parentRect.iTl); + + LOG1( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcSetContainer container visible %d", + aContainer->MdcContainerVisibility()); + LOG1( EJavaMMAPI, EInfo, "CMMADCDisplay::MdcSetContainer content visible %d", + iVisible); + + iWindow->SetVisible(aContainer->MdcContainerVisibility() && + iVisible); + } +} + +// interface MMMADirectContent +CFbsBitmap* CMMADCDisplay::MdcFrameBuffer() const +{ + return iBitmap; +} + +// interface MMMADirectContent +TSize CMMADCDisplay::MdcSourceSize() +{ + return iPlayer->SourceSize(); +} + +void CMMADCDisplay::MdcContentBoundsChanged(const TRect& /*aRect*/) +{ +} + +void CMMADCDisplay::UIGetDSAResources( + MUiEventConsumer& aConsumer, + MMMADisplay::TThreadType aThreadType) +{ + if (iContainer) + { + iContainer->MdcGetDSAResources(aConsumer, aThreadType); + } +} + +void CMMADCDisplay::UIGetCallback( + MUiEventConsumer& aConsumer, + TInt aCallbackId) +{ + if (iContainer) + { + iContainer->MdcGetUICallback(aConsumer, aCallbackId); + } +} + +TInt CMMADCDisplay::InitBitmapMode() +{ + TInt errCode = KErrNone; + // If there is no bitmap, create one and set it to window + if (!iBitmap && iWindow) + { + iBitmap = new CFbsBitmap; + if (iBitmap) + { + errCode = iBitmap->Create(iPlayer->SourceSize(), + EColor16MA); + } + else + { + errCode = KErrNoMemory; + } + + if (errCode == KErrNone) + { + TRAP(errCode, + iWindow->SetDestinationBitmapL(iBitmap)); + } + } + return errCode; +} + +void CMMADCDisplay::SetDrawRectL(CMMADCDisplay* aDisplay, TSize* aSize) +{ + if (aDisplay->iBitmap) + { + User::LeaveIfError(aDisplay->iBitmap->Resize(*aSize)); + aDisplay->iWindow->SetDestinationBitmapL(aDisplay->iBitmap); + } +} + +CMMADCDisplay::CMMADCDisplay(MMMAGuiPlayer* aPlayer, + MMAFunctionServer* aEventSource, + jobject aGUIObject) +{ + iPlayer = aPlayer; + iEventSource = aEventSource; + iGUIObject = aGUIObject; + // GUI_PRIMITIVE is visible by default. + iVisible = ETrue; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/src/cmmadcfullscreenevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/src/cmmadcfullscreenevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content fullscreen event. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadcfullscreenevent.h" + +CMMADCFullScreenEvent::CMMADCFullScreenEvent(jobject aGUIObject, TBool aFullScreen): + CMMAEvent(EDisposableEvent) +{ + iListenerObject = aGUIObject; + iEventData = aFullScreen; +} + +// from CJavaEvent +void CMMADCFullScreenEvent::Dispatch(JNIEnv& aJni) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADCFullScreenEvent::Dispatch"); + iHandleEventMethod = aJni.GetMethodID(aJni.GetObjectClass(iListenerObject), + "setFullScreen", + "(Z)V"); + if (iHandleEventMethod && + (aJni.IsSameObject(iListenerObject, 0) == JNI_FALSE)) + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iEventData); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/src/cmmadcinvalidateevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/src/cmmadcinvalidateevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content invalidate event +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadcinvalidateevent.h" + +CMMADCInvalidateEvent::CMMADCInvalidateEvent(jobject aGUIObject, + TSize aSize): + CMMAEvent(EDisposableEvent) +{ + iListenerObject = aGUIObject; + iSize = aSize; +} + +// from CJavaEvent +void CMMADCInvalidateEvent::Dispatch(JNIEnv& aJni) +{ + LOG2( EJavaMMAPI, EInfo, "MMA::CMMADCInvalidateEvent::Dispatch w=%d h=%d", + iSize.iWidth, + iSize.iHeight); + + iHandleEventMethod = aJni.GetMethodID(aJni.GetObjectClass(iListenerObject), + "invalidate", + "(II)V"); + + // IsSameObject method will return true if iListenerObject has disappeared + if (iHandleEventMethod && + aJni.IsSameObject(iListenerObject, 0) == JNI_FALSE) + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod, + iSize.iWidth, + iSize.iHeight); + } +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/directcontent/src/cmmadcrepaintevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/directcontent/src/cmmadcrepaintevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to send direct content repaint event. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadcrepaintevent.h" + +CMMADCRepaintEvent::CMMADCRepaintEvent(jobject aGUIObject): + CMMAEvent(EReusableEvent) +{ + iListenerObject = aGUIObject; + iEventData = KErrNone; +} + +TBool CMMADCRepaintEvent::IsActive() +{ + return iEventData != KErrNone; +} + +void CMMADCRepaintEvent::SetActive() +{ + iEventData = KErrInUse; +} + +// from CJavaEvent +void CMMADCRepaintEvent::Dispatch(JNIEnv& aJni) +{ + // create method id if not allready created + if (!iHandleEventMethod) + { + iHandleEventMethod = aJni.GetMethodID(aJni.GetObjectClass(iListenerObject), + "repaint", + "()V"); + } + + // There is internal error if method cannot be found + __ASSERT_DEBUG(iHandleEventMethod, User::Invariant()); + + // IsSameObject method will return true if iListenerObject has disappeared + if (iHandleEventMethod && + aJni.IsSameObject(iListenerObject, 0) == JNI_FALSE) + { + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod); + } + + // IsActive will return EFalse after this + iEventData = KErrNone; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/inc/cmmadrmaudioplayer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/inc/cmmadrmaudioplayer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for playing MIDI. +* +*/ + + +#ifndef CMMADRMAUDIOPLAYER_H +#define CMMADRMAUDIOPLAYER_H + +// INCLUDES +#include "cmmaaudioplayer.h" +#include +#include + +// CONSTANTS +_LIT(KMMADRMPlayer, "DRMPlayer"); + +// FORWARD DECLARATIONS +class MMAFunctionServer; + +// CLASS DECLARATION +/** +* This class is used for playing DRM Audio. +* +*/ + +NONSHARABLE_CLASS(CMMADRMAudioPlayer): public CMMAPlayer, + public MDrmAudioPlayerCallback + +{ +public: // Construction + static CMMADRMAudioPlayer* NewLC(const TDesC& aContentType, + TFileName aFileName); + + // Destructor + ~CMMADRMAudioPlayer(); + +protected: + // C++ constructor + CMMADRMAudioPlayer(TFileName aFileName); + void ConstructL(const TDesC& aContentType); + +public: // new methods + CDrmPlayerUtility* DRMUtility() const; + +public: // from CMMAPlayer + void StartL(); + void StopL(TBool aPostEvent); + void RealizeL(); + void PrefetchL(); + void DeallocateL(); + void GetDuration(TInt64* aDuration); + void SetMediaTimeL(TInt64* aTime); + void GetMediaTime(TInt64* aMediaTime); + void CloseL(); + const TDesC& Type(); + +public: // from CMMAPlayer + void PlayCompleteL(TInt aError); + +public: // from MDrmAudioPlayerCallback + void MdapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration); + void MdapcPlayComplete(TInt aError); + +protected: + void CloseClientUtility(); + void ErrorPlaybackComplete(TInt aError); + +private: // Data + CDrmPlayerUtility* iUtility; + + TFileName iFileName; +}; + +#endif // CMMADRMAUDIOPLAYER_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/inc/cmmadrmmetadatacontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/inc/cmmadrmmetadatacontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMADRMMetaDataControl is a concrete class for getting +* metadata from drm files. +* +*/ + + +#ifndef CMMADRMMETADATACONTROL_H +#define CMMADRMMETADATACONTROL_H + +// INCLUDES +#include + +#include "cmmadrmaudioplayer.h" +#include "cmmametadatacontrol.h" + +// CLASS DECLARATION +/** +* This is a concrete class for getting metadata from drm files. +* +* +*/ + +NONSHARABLE_CLASS(CMMADRMMetaDataControl): public CMMAMetaDataControl +{ +public: + CMMADRMMetaDataControl(CMMADRMAudioPlayer* aPlayer); + +protected: // from CMMAMetaDataControl + + TInt KeyCountL(); + HBufC* KeyL(TInt aIndex); + + HBufC* KeyValueL(const TDesC& aKey); + +private: + /** + * Used to query metadata + */ + CMMADRMAudioPlayer* iPlayer; +}; + +#endif // CMMADRMMETADATACONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/inc/cmmadrmplayerfactory.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/inc/cmmadrmplayerfactory.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,74 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating DRM v2 players. +* +*/ + + +#ifndef CMMADRMPLAYERFACTORY_H +#define CMMADRMPLAYERFACTORY_H + +// INCLUDES +#include "mmmaplayerfactory.h" +#include "cmmavideoplayerfactory.h" + +class CMMAMMFResolver; + +// CLASS DECLARATION +/** +* This class is used for creating DRM players. +* +* +*/ +NONSHARABLE_CLASS(CMMADRMPlayerFactory): public CBase, public MMMAPlayerFactory +{ +public: // Constructor and destructor + static CMMADRMPlayerFactory* NewLC(CMMAVideoPlayerFactory* aVideoPlayerFactory); + + CMMADRMPlayerFactory(CMMAVideoPlayerFactory* aVideoPlayerFactory); + + ~CMMADRMPlayerFactory(); + +public: // From MMMAPlayerFactory + CMMAPlayer* CreatePlayerL(const TDesC& aContentType); + + CMMAPlayer* CreatePlayerL(const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& aParameters); + + CMMAPlayer* CreatePlayerL(const TDesC8& aHeaderData); + + void GetSupportedContentTypesL(const TDesC& aProtocol, + CDesC16Array& aMimeTypeArray); + + void GetSupportedProtocolsL(const TDesC& aContentType, + CDesC16Array& aProtocolArray); + +protected: + void UpdateRightsL(TInt aError, + const TDesC& aFileName); + + CMMAPlayer* CreateAudioPlayerL(const TDesC& aContentType, + const TDesC& aFileName); + + CMMAPlayer* CreateVideoPlayerL(const TDesC& aContentType, + const TDesC& aFileName); + + +private: //data + CMMAVideoPlayerFactory* iVideoPlayerFactory; + +}; + +#endif // CMMADRMPLAYERFACTORY_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/inc/cmmadrmratecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/inc/cmmadrmratecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements RateControl for DRMv2 audio player. +* +*/ + + +#ifndef CMMADRMRATECONTROL_H +#define CMMADRMRATECONTROL_H + +// INTERNAL INCLUDES +#include "cmmaratecontrol.h" // base class +#include "cmmadrmaudioplayer.h" + +// CLASS DECLARATION +/** +* This class implements RateControl for DRMv2 audio player. +* +*/ +NONSHARABLE_CLASS(CMMADRMRateControl): public CMMARateControl, + public MMMAPlayerStateListener +{ +public: + + static CMMADRMRateControl* NewL(CMMADRMAudioPlayer* aPlayer); + + /** + * Destructor. + */ + ~CMMADRMRateControl(); + +protected: + + /** + * Constructor. + */ + CMMADRMRateControl(CMMADRMAudioPlayer* aPlayer); + + void ConstructL(); + +public: // from MMMAPlayerStateListener + virtual void StateChanged(TInt aState); + +public: // New methods + /** + * @param aRate Rate to set in "milli-percentage".. + * @return Actual rate set. + */ + virtual TInt SetRateL(TInt aRate); + + /** + * @return The current playback rate in "milli-percentage". + */ + virtual TInt RateL(); + + +private: // Member data + + /** + * Used to obtain RMMFController reference to stop/start + * playback. + */ + CMMADRMAudioPlayer* iPlayer; + + /** + * Hold current rate value. + */ + TInt iCurrentRate; + +}; + +#endif // CMMADRMRATECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/inc/cmmadrmvolumecontrol.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/inc/cmmadrmvolumecontrol.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to audio player +* +*/ + + +#ifndef CMMADRMVOLUMECONTROL_H +#define CMMADRMVOLUMECONTROL_H + +#include "cmmavolumecontrol.h" + +class CMMADRMAudioPlayer; + +// CLASS DEFINITION +/* +----------------------------------------------------------------------------- + + DESCRIPTION + This class is used for setting volume to DRM audio player + +----------------------------------------------------------------------------- +*/ +NONSHARABLE_CLASS(CMMADRMVolumeControl): public CMMAVolumeControl +{ +public: + static CMMADRMVolumeControl* NewL(CMMADRMAudioPlayer* aPlayer); + +protected: + CMMADRMVolumeControl(CMMADRMAudioPlayer* aPlayer); + void ConstructL(); + + +public: // from CMMAVolumeControl + void DoSetLevelL(TInt aLevel); + TInt DoGetLevelL(); + +private: + CMMADRMAudioPlayer* iPlayer; +}; + +#endif // CMMADRMVOLUMECONTROL_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/src/cmmadrmaudioplayer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/src/cmmadrmaudioplayer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,342 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for MIDI. +* +*/ + + +// INCLUDE FILES +#include +#include +#include + +#include "cmmadrmaudioplayer.h" +#include "mmmadisplay.h" + +const TInt KErrorMessageSize = 32; +const TInt64 KDurationUnknown = -1; +const TInt KMediaStartTime = 0; +const TInt KMediaTimeDurationTreshold = 100000; + +_LIT(KErrDefaultError, "Symbian OS Error: %d"); + +CMMADRMAudioPlayer* CMMADRMAudioPlayer::NewLC(const TDesC& aContentType, + TFileName aFileName) +{ + CMMADRMAudioPlayer* self = new(ELeave) CMMADRMAudioPlayer(aFileName); + CleanupStack::PushL(self); + self->ConstructL(aContentType); + return self; +} + +CMMADRMAudioPlayer::~CMMADRMAudioPlayer() +{ + CloseClientUtility(); + delete iUtility; + + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMAudioPlayer::~CMMADRMAudioPlayer "); +} + +void CMMADRMAudioPlayer::ConstructL(const TDesC& aContentType) +{ + LOG( EJavaMMAPI, EInfo, "CMMADRMAudioPlayer::ConstructL"); + // Only file based sources are supported with DRM + if (iFileName == KNullDesC) + { + User::Leave(KErrNotSupported); + } + iContentType = aContentType.AllocL(); + iUtility = CDrmPlayerUtility::NewL(*this, KAudioPriorityRealOnePlayer, + (TMdaPriorityPreference) KAudioPrefRealOneLocalPlayback); + + CMMAPlayer::ConstructL(); +} + +CMMADRMAudioPlayer::CMMADRMAudioPlayer(TFileName aFileName): + CMMAPlayer(), + iFileName(aFileName) +{ +} + +CDrmPlayerUtility* CMMADRMAudioPlayer::DRMUtility() const +{ + return iUtility; +} + + +void CMMADRMAudioPlayer::RealizeL() +{ + LOG( EJavaMMAPI, EInfo, "CMMADRMAudioPlayer::RealizeL"); + CMMAPlayer::RealizeL(); +} + +void CMMADRMAudioPlayer::PrefetchL() +{ + LOG( EJavaMMAPI, EInfo, "CMMADRMAudioPlayer::PrefetchL"); + // Prefetch will be completed in init callback + iUtility->OpenFileL(iFileName); +} + +void CMMADRMAudioPlayer::DeallocateL() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: DeallocateL +"); + if (iState == EPrefetched) + { + CloseClientUtility(); + ChangeState(ERealized); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMAMidiPlayer: DeallocateL -"); +} + +void CMMADRMAudioPlayer::StartL() +{ + // start can't be called to not ready player + ASSERT(iState == EPrefetched); + + TInt64 time = TInt64(KMediaStartTime); + + // Media time is not fetched using GetMediaTime + // Because it adjusts the result if it is close + // to duration. + + TTimeIntervalMicroSeconds position(KMediaStartTime); + User::LeaveIfError(iUtility->GetPosition(position)); + + time = position.Int64(); + + TInt64 duration; + GetDuration(&duration); + if ((duration > 0) && (time > duration - KMediaTimeDurationTreshold)) + { + time = KMediaStartTime; + iUtility->SetPosition(time); + } + + iUtility->Play(); + PostActionCompletedStart(); + // inform java side + PostActionCompleted(KErrNone); // java start return + PostLongEvent(CMMAPlayerEvent::EStarted, time); + ChangeState(EStarted); +} + +void CMMADRMAudioPlayer::StopL(TBool aPostEvent) +{ + if (iState == EStarted) + { + User::LeaveIfError(iUtility->Pause()); + + if (aPostEvent) + { + TInt64 time; + GetMediaTime(&time); + PostLongEvent(CMMAPlayerEvent::EStopped, time); + } + // go back to prefetched state + ChangeState(EPrefetched); + } +} + +void CMMADRMAudioPlayer::GetDuration(TInt64* aDuration) +{ + if (iState < EPrefetched) + { + *aDuration = KDurationUnknown; + } + else + { + *aDuration = iUtility->Duration().Int64(); + } +} + +void CMMADRMAudioPlayer::SetMediaTimeL(TInt64* aTime) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADRMAudioPlayer::SetMediaTimeL + aTime: %d", *aTime); + // Duration is needed so we do not try to set media time + // too far away. If duration is not known, setting media time + // is not allowed. + + TInt64 duration = TInt64(KMediaStartTime); + GetDuration(&duration); + if (duration < KErrNone) + { + // If duration is not known, we will leave with suitable code. + User::Leave(KErrNotSupported); + } + + // Check if desired media time is past media duration and + // set it to duration in that case. Negative values are not + // checked here because it's done already in Java side. + + // If media time is attempted to set to duration, then + // it is set close to duration. This way + // when utility is then started, end of media event + // will come soon after. This is not indicated to Java + // side but instead returned that the media time was + // set to duration. + + TTimeIntervalMicroSeconds position; + if (*aTime >= duration) + { + *aTime = duration; + position = duration - KMediaTimeDurationTreshold; + } + else + { + position = *aTime; + } + + iUtility->SetPosition(position); + + // Inform about the position change to the StateListeners + ChangeState(iState); + + // Get the actual media time + GetMediaTime(aTime); +} + +void CMMADRMAudioPlayer::GetMediaTime(TInt64* aMediaTime) +{ + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADRMAudioPlayer::GetMediaTime + aMediaTime: %d", *aMediaTime); + TTimeIntervalMicroSeconds position; + TInt64 duration = TInt64(KMediaStartTime); + + // Error code discarded on purpose + GetDuration(&duration); + + TInt error(iUtility->GetPosition(position)); + if (error == KErrNone) + { + // set return value + *aMediaTime = position.Int64(); + //if duration is unknown and position 0, player is realized and + //we can not know media time + if ((duration == KDurationUnknown) && (position == 0)) + { + *aMediaTime = KTimeUnknown; + } + } + else + { + // media time cannot be get + *aMediaTime = KTimeUnknown; + } + + // Second part of the set media time workaround. + // If position is close to duration, then media + // time of duration is returned instead. + + // If the duration is zero or not known + // then this adjustment is not done. + if ((duration > KErrNone) && + (*aMediaTime >= duration - KMediaTimeDurationTreshold)) + { + *aMediaTime = duration; + } + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADRMAudioPlayer::GetMediaTime - aMediaTime: %d", *aMediaTime); +} + +void CMMADRMAudioPlayer::CloseL() +{ + CMMAPlayer::CloseL(); + CloseClientUtility(); +} + +const TDesC& CMMADRMAudioPlayer::Type() +{ + return KMMADRMPlayer; +} + +void CMMADRMAudioPlayer::PlayCompleteL(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA: CMMADRMAudioPlayer: PlayCompleteL: Error=%d", aError); + TInt64 time; + GetDuration(&time); + + // Send 'Stopped' only when stop() is called. + PostLongEvent(CMMAPlayerEvent::EEndOfMedia, time); + + ChangeState(EPrefetched); // ready to play again + + if (aError == KErrNone) + { + iRepeatCount++; + + if (iRepeatForever || iRepeatCount < iRepeatNumberOfTimes) + { + StartL(); + } + else + { + iRepeatCount = 0; + TTimeIntervalMicroSeconds position(time); + iUtility->SetPosition(position); + } + } + else + { + // error has occured, setting correct number of + // repeats for next start + SetLoopCount(iRepeatNumberOfTimes); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMADRMAudioPlayer: PlayCompleteL -"); +} + +void CMMADRMAudioPlayer::MdapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/) +{ + ELOG1( EJavaMMAPI, "MMA::CMMADRMAudioPlayer::MdapcInitComplete: aError = %d", aError); + if (!aError) + { + ChangeState(EPrefetched); + } + PostActionCompleted(aError); +} + +void CMMADRMAudioPlayer::MdapcPlayComplete(TInt aError) +{ + if (aError) + { + ErrorPlaybackComplete(aError); + } + else + { + TRAPD(error, PlayCompleteL(KErrNone)); + if (error) + { + ErrorPlaybackComplete(error); + } + } +} + +void CMMADRMAudioPlayer::CloseClientUtility() +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMADRMAudioPlayer: CloseClientUtility +"); + if (iUtility) + { + iUtility->Close(); + } + LOG( EJavaMMAPI, EInfo, "MMA: CMMADRMAudioPlayer: CloseClientUtility -"); +} + +void CMMADRMAudioPlayer::ErrorPlaybackComplete(TInt aError) +{ + ELOG1( EJavaMMAPI, "MMA::CMMADRMAudioPlayer::ErrorPlaybackComplete: aError = %d", aError); + TBuf errorMessage; + errorMessage.Format(KErrDefaultError, aError); + PostStringEvent(CMMAPlayerEvent::EError, errorMessage); + + CloseClientUtility(); + ChangeState(ERealized); +} +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/src/cmmadrmmetadatacontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/src/cmmadrmmetadatacontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: CMMADRMMetaDataControl is a concrete class for getting +* metadata from DRM files. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmadrmmetadatacontrol.h" + +CMMADRMMetaDataControl::CMMADRMMetaDataControl( + CMMADRMAudioPlayer* aPlayer) + : iPlayer(aPlayer) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMMetaDataControl constructor called."); +} + +TInt CMMADRMMetaDataControl::KeyCountL() +{ + TInt entries; + User::LeaveIfError(iPlayer->DRMUtility()->GetNumberOfMetaDataEntries(entries)); + return entries; +} + +HBufC* CMMADRMMetaDataControl::KeyL(TInt aIndex) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMADRMMetaDataControl::KeyL"); + CMMFMetaDataEntry* currEntry = + iPlayer->DRMUtility()->GetMetaDataEntryL(aIndex); + CleanupStack::PushL(currEntry); + HBufC* key = currEntry->Name().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + return key; +} + + +/* + * Get the value of given drm metadata key. The ownership of the created value + * (descriptor) is passed to the caller. + */ +HBufC* CMMADRMMetaDataControl::KeyValueL(const TDesC& aKey) +{ + LOG( EJavaMMAPI, EInfo, "MMA: CMMADRMMetaDataControl::KeyValueL"); + + HBufC* retVal = NULL; + CMMFMetaDataEntry* currEntry = NULL; + + TInt nEntries; + User::LeaveIfError(iPlayer->DRMUtility()->GetNumberOfMetaDataEntries(nEntries)); + + for (TInt i = 0; i < nEntries; ++i) + { + currEntry = iPlayer->DRMUtility()->GetMetaDataEntryL(i); + + if (0 == aKey.Compare(currEntry->Name())) + { + CleanupStack::PushL(currEntry); + retVal = currEntry->Value().AllocL(); + CleanupStack::PopAndDestroy(); // currEntry + break; + } + + delete currEntry; + } + + User::LeaveIfNull(retVal); + return retVal; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/src/cmmadrmplayerfactory.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/src/cmmadrmplayerfactory.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,257 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for creating DRM v2 player. +* +*/ + + +// INCLUDE FILES +#include + +#include +#include +#include + +#include "cmmadrmplayerfactory.h" +#include "cmmadrmaudioplayer.h" +#include "cmmadrmvolumecontrol.h" +#include "cmmastoptimecontrol.h" +#include "cmmadrmmetadatacontrol.h" +#include "cmmadrmratecontrol.h" +#include "cmmavideoplayer.h" + +_LIT(KMMAAudio, "audio"); +// this (get from caf) cannot be recognized is it audio or video +_LIT(KMMARMCafMimeType, "application/vnd.rn-realmedia"); +// drm v2 file suffix +_LIT(KMMADRMv2SuffixODF, "odf"); + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::NewLC +// --------------------------------------------------------------------------- +// +CMMADRMPlayerFactory* CMMADRMPlayerFactory::NewLC(CMMAVideoPlayerFactory* aVideoPlayerFactory) +{ + CMMADRMPlayerFactory* pFactory = + new(ELeave) CMMADRMPlayerFactory(aVideoPlayerFactory); + CleanupStack::PushL(pFactory); + return pFactory; +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CMMADRMPlayerFactory +// --------------------------------------------------------------------------- +// +CMMADRMPlayerFactory::CMMADRMPlayerFactory(CMMAVideoPlayerFactory* aVideoPlayerFactory) + :iVideoPlayerFactory(aVideoPlayerFactory) +{ +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::~CMMADRMPlayerFactory +// --------------------------------------------------------------------------- +// +CMMADRMPlayerFactory::~CMMADRMPlayerFactory() +{ +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CreatePlayerL +// --------------------------------------------------------------------------- +// +CMMAPlayer* CMMADRMPlayerFactory::CreatePlayerL(const TDesC& /*aContentType*/) +{ + // only file is supported + return NULL; +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CreatePlayerL +// --------------------------------------------------------------------------- +// +CMMAPlayer* CMMADRMPlayerFactory::CreatePlayerL( + const TDesC& aProtocol, + const TDesC& aMiddlePart, + const TDesC& /*aProperties*/) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreatePlayerL +"); + CMMAPlayer* player = NULL; + if (aProtocol == KMMAFileProtocol) + { + // we are most likely going to play this file + ContentAccess::TIntent intent = ContentAccess::EPlay; + + ContentAccess::CContent* contentObj = ContentAccess::CContent::NewL(aMiddlePart); + CleanupStack::PushL(contentObj); + + ContentAccess::CData* dataObj = NULL; + TRAPD(openContentErr, dataObj = contentObj->OpenContentL(intent)); + CleanupStack::PushL(dataObj); + + ELOG1( EJavaMMAPI, "MMA::CMMADRMPlayerFactory::CreatePlayerL openContentErr: %d", openContentErr); + if (KErrCA_LowerLimit <= openContentErr && openContentErr <= KErrCA_UpperLimit) + { + // handle error, possible update rights + UpdateRightsL(openContentErr, aMiddlePart); + User::Leave(openContentErr); + } + else + { + User::LeaveIfError(openContentErr); + } + + ContentAccess::RStringAttributeSet stringAttributeSet; + CleanupClosePushL(stringAttributeSet); + stringAttributeSet.AddL(ContentAccess::EMimeType); + + User::LeaveIfError(dataObj->GetStringAttributeSet(stringAttributeSet)); + + TBuf mimeType; + TInt err = stringAttributeSet.GetValue(ContentAccess::EMimeType, mimeType); + if (err == KErrNone) + { + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreatePlayerL, no err, mime type = %S", mimeType.PtrZ()); + // we use 16bit mimeType + HBufC* mimeTypeBuf = HBufC::NewLC(mimeType.Length()); + mimeTypeBuf->Des().Copy(mimeType); + + if (((mimeTypeBuf->Length() >= KMMAAudio().Length()) && + (mimeTypeBuf->Left(KMMAAudio().Length()) == KMMAAudio)) || + ((KErrNone == mimeTypeBuf->Compare(KMMARMCafMimeType)) && + (aMiddlePart.Right(KMMADRMv2SuffixODF().Length()) == + KMMADRMv2SuffixODF()))) + { + // if content-type starts with "audio" or + // if it's KMMARMCafMimeType and file suffix is ODF + // then create audio player + player = CreateAudioPlayerL(*mimeTypeBuf, aMiddlePart); + } + else + { + // otherwise try video player + player = CreateVideoPlayerL(*mimeTypeBuf, aMiddlePart); + } + CleanupStack::PopAndDestroy(mimeTypeBuf); + } + else + { + ELOG1( EJavaMMAPI, "MMA::CMMADRMPlayerFactory::CreatePlayerL get mime err: %d", err); + LOG1( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreatePlayerL mime type = %S", mimeType.PtrZ()); + User::Leave(err); + } + CleanupStack::PopAndDestroy(3); //dataObj, contentObj, stringAttributeSet + } + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreatePlayerL -"); + return player; +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CreatePlayerL +// --------------------------------------------------------------------------- +// +CMMAPlayer* CMMADRMPlayerFactory::CreatePlayerL(const TDesC8& /*aHeaderData*/) +{ + // only file is supported + return NULL; +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::GetSupportedContentTypesL +// --------------------------------------------------------------------------- +// +void CMMADRMPlayerFactory::GetSupportedContentTypesL(const TDesC& /*aProtocol*/, + CDesC16Array& /*aMimeTypeArray*/) +{ + // DRM Supports same content-types as others, no need to add +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::GetSupportedProtocolsL +// --------------------------------------------------------------------------- +// +void CMMADRMPlayerFactory::GetSupportedProtocolsL( + const TDesC& /*aContentType*/, + CDesC16Array& /*aProtocolArray*/) +{ + // DRM Supports same protocols as others, no need to add +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::UpdateRightsL +// --------------------------------------------------------------------------- +// +void CMMADRMPlayerFactory::UpdateRightsL(TInt aError, + const TDesC& aFileName) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::UpdateRightsL +"); + CDRMHelper* helper = CDRMHelper::NewLC(); + TInt code = helper->HandleErrorL(aError, aFileName); + if (code == 0) + { + User::Leave(aError); + } + CleanupStack::PopAndDestroy(helper); +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CreateAudioPlayerL +// --------------------------------------------------------------------------- +// +CMMAPlayer* CMMADRMPlayerFactory::CreateAudioPlayerL(const TDesC& aContentType, + const TDesC& aFileName) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreateAudioPlayerL +"); + CMMADRMAudioPlayer* player = CMMADRMAudioPlayer::NewLC(aContentType, + aFileName); + + CMMADRMVolumeControl* volumeControl = CMMADRMVolumeControl::NewL(player); + CleanupStack::PushL(volumeControl); + player->AddControlL(volumeControl); + CleanupStack::Pop(volumeControl); + + CMMAStopTimeControl* stopTimeControl = CMMAStopTimeControl::NewL(player); + CleanupStack::PushL(stopTimeControl); + player->AddControlL(stopTimeControl); + CleanupStack::Pop(stopTimeControl); + + CMMADRMMetaDataControl* metaDataControl = + new(ELeave)CMMADRMMetaDataControl(player); + CleanupStack::PushL(metaDataControl); + player->AddControlL(metaDataControl); + CleanupStack::Pop(metaDataControl); + + CMMADRMRateControl* drmRateControl = CMMADRMRateControl::NewL(player); + CleanupStack::PushL(drmRateControl); + player->AddControlL(drmRateControl); + CleanupStack::Pop(drmRateControl); + + CleanupStack::Pop(player); + return player; +} + +// --------------------------------------------------------------------------- +// CMMADRMPlayerFactory::CreateVideoPlayerL +// --------------------------------------------------------------------------- +// +CMMAPlayer* CMMADRMPlayerFactory::CreateVideoPlayerL(const TDesC& aContentType, + const TDesC& aFileName) +{ + LOG( EJavaMMAPI, EInfo, "MMA::CMMADRMPlayerFactory::CreateVideoPlayerL +"); + CMMAPlayer* player = + iVideoPlayerFactory->CreatePlayerWithFileL(aContentType, &aFileName); + + return player; +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/src/cmmadrmratecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/src/cmmadrmratecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class implements generic RateControl functionality. +* +*/ + + +// INCLUDE FILES +#include "logger.h" +#include + +#include "cmmadrmratecontrol.h" + +CMMADRMRateControl* CMMADRMRateControl::NewL(CMMADRMAudioPlayer* aPlayer) +{ + CMMADRMRateControl* self = new(ELeave) CMMADRMRateControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +CMMADRMRateControl::~CMMADRMRateControl() +{ + LOG(EJavaMMAPI,EInfo,"MMA:CMMADRMRateControl::~CMMADRMRateControl"); + if (iPlayer) + { + iPlayer->RemoveStateListener(this); + } +} + +CMMADRMRateControl::CMMADRMRateControl(CMMADRMAudioPlayer* aPlayer) : + iPlayer(aPlayer), iCurrentRate(KMMADefaultRate) +{ + LOG(EJavaMMAPI,EInfo,"MMA:CMMADRMRateControl::CMMADRMRateControl"); +} + +void CMMADRMRateControl::ConstructL() +{ + iPlayer->AddStateListenerL(this); +} + +void CMMADRMRateControl::StateChanged(TInt aState) +{ + LOG(EJavaMMAPI,EInfo,"MMA:CMMADRMRateControl::StateChanged"); + if (aState == CMMAPlayer::EStarted && iCurrentRate == KMMAMinRate) + { + iPlayer->DRMUtility()->Stop(); + } +} + +TInt CMMADRMRateControl::SetRateL(TInt aRate) +{ + LOG(EJavaMMAPI,EInfo,"MMA:CMMADRMRateControl::SetRateL"); + if (aRate <= KMMAMinRate) + { + iCurrentRate = KMMAMinRate; + } + else + { + iCurrentRate = KMMADefaultRate; + } + + if (iPlayer->State() == CMMAPlayer::EStarted) + { + if (iCurrentRate == KMMAMinRate) + { + iPlayer->DRMUtility()->Stop(); + } + else + { + iPlayer->DRMUtility()->Play(); + } + } + return iCurrentRate; +} + +TInt CMMADRMRateControl::RateL() +{ + return iCurrentRate; +} + + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/src_drmv2/src/cmmadrmvolumecontrol.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/src_drmv2/src/cmmadrmvolumecontrol.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for setting volume to DRMv2 audio player +* +*/ + + +#include "logger.h" +#include "cmmadrmvolumecontrol.h" +#include "cmmadrmaudioplayer.h" + +CMMADRMVolumeControl::CMMADRMVolumeControl(CMMADRMAudioPlayer* aPlayer) + : CMMAVolumeControl(aPlayer) +{ + iPlayer = aPlayer; +} + +void CMMADRMVolumeControl::ConstructL() +{ + ConstructBaseL(); +} +CMMADRMVolumeControl* CMMADRMVolumeControl::NewL(CMMADRMAudioPlayer* aPlayer) +{ + CMMADRMVolumeControl* self = new(ELeave)CMMADRMVolumeControl(aPlayer); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(); + return self; +} + +void CMMADRMVolumeControl::DoSetLevelL(TInt aLevel) +{ + CDrmPlayerUtility* utility = iPlayer->DRMUtility(); + TInt maxVolume = utility->MaxVolume(); + utility->SetVolume(aLevel * maxVolume / KMMAVolumeMaxLevel); +} + +TInt CMMADRMVolumeControl::DoGetLevelL() +{ + CDrmPlayerUtility* utility = iPlayer->DRMUtility(); + TInt maxVolume = utility->MaxVolume(); + TInt volume = 0; + User::LeaveIfError(utility->GetVolume(volume)); + // result is in range 0..100 + return (volume * KMMAVolumeMaxLevel / maxVolume); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/utils/inc/TimeOutTimer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/utils/inc/TimeOutTimer.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Timer for comms time-outs +* +*/ + + +#ifndef TIMEOUTTIMER_H +#define TIMEOUTTIMER_H + +#include +#include + +// MTimeOutNotify: used in conjunction with CTimeOutTimer class +class MTimeOutNotify +{ +public: + virtual void TimerExpired() = 0; +}; + +// CTimeOutTimer: timer for comms time-outs +class CTimeOutTimer : public CTimer +{ +public: + IMPORT_C static CTimeOutTimer* NewL(const TInt aPriority, MTimeOutNotify& aTimeOutNotify); + ~CTimeOutTimer(); + +protected: + CTimeOutTimer(const TInt aPriority); + void ConstructL(MTimeOutNotify& aTimeOutNotify); + virtual void RunL(); + +private: + MTimeOutNotify* iNotify; +}; + +#endif // TIMEOUTTIMER_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/utils/inc/mmapiutils.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/utils/inc/mmapiutils.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +#ifndef MMAPIUTILS_H +#define MMAPIUTILS_H +#include "jni.h" +#include "e32base.h" +#include "BADESCA.H" + +class MMAPIUtils +{ +public: + + static TInt CopyToJava(JNIEnv& aJni, const TDesC8& aNativeBuffer, + jbyteArray aJavaBuffer, TInt aOffset, TInt aLength); + static jstring CreateJavaString(JNIEnv& aJni, const TDesC16& aString); + + static jobjectArray CopyToNewJavaStringArrayL(JNIEnv& aJni, const CDesCArray& aNativeArray); + + static void AddToJavaStringArrayL(JNIEnv& aJni, jobjectArray& aContainer, TInt aPosition, const TDesC& aString); +}; + +#endif // MMAPIUTILS_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/utils/src/TimeOutTimer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/utils/src/TimeOutTimer.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Timer for comms time-outs +* +*/ + + +#include "TimeOutTimer.h" + +CTimeOutTimer::CTimeOutTimer(const TInt aPriority) + : CTimer(aPriority) +{ +} + +CTimeOutTimer::~CTimeOutTimer() +{ + Cancel(); +} + + +EXPORT_C CTimeOutTimer* CTimeOutTimer::NewL(const TInt aPriority, MTimeOutNotify& aTimeOutNotify) +{ + CTimeOutTimer *p = new(ELeave) CTimeOutTimer(aPriority); + CleanupStack::PushL(p); + p->ConstructL(aTimeOutNotify); + CleanupStack::Pop(); + return p; +} + +void CTimeOutTimer::ConstructL(MTimeOutNotify &aTimeOutNotify) +{ + iNotify=&aTimeOutNotify; + CTimer::ConstructL(); + CActiveScheduler::Add(this); +} + +void CTimeOutTimer::RunL() +// Timer request has completed, so notify the timer's owner +{ + iNotify->TimerExpired(); +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/utils/src/mmapiutils.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/utils/src/mmapiutils.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ +#include "mmapiutils.h" +#include "s60commonutils.h" +using namespace java::util; + +enum TJavaArrayPanic +{ + EBadOffsetIntoJavaArray, + EWritingOverEndOfJavaArray, + EBadOffsetIntoJavaArrayForRead, + EReadingOverEndOfJavaArray, +}; + + +/** + * Copies data from the native to the Java array. + * @return The number of bytes copied. + */ +TInt MMAPIUtils::CopyToJava(JNIEnv& aJni, const TDesC8& aNativeBuffer, + jbyteArray aJavaBuffer, TInt aOffset, TInt aLength) +{ + __ASSERT_DEBUG(aOffset <= aJni.GetArrayLength(aJavaBuffer), + User::Panic(_L("ArrayUtils"), EBadOffsetIntoJavaArray)); + __ASSERT_DEBUG(aLength <= aJni.GetArrayLength(aJavaBuffer) - aOffset, + User::Panic(_L("ArrayUtils"), EWritingOverEndOfJavaArray)); + + TInt nativeBufferLength = aNativeBuffer.Length(); + TInt length = (nativeBufferLength < aLength) ? nativeBufferLength : aLength; + TUint8* nativeBufferPtr = const_cast(aNativeBuffer.Ptr()); + jbyte* jNativeBufferPtr = reinterpret_cast(nativeBufferPtr); + aJni.SetByteArrayRegion(aJavaBuffer, aOffset, length, jNativeBufferPtr); + return length; +} + +jobjectArray MMAPIUtils::CopyToNewJavaStringArrayL(JNIEnv& aJni, const CDesCArray& aNativeArray) +{ + jclass stringClass = aJni.FindClass("java/lang/String"); + User::LeaveIfNull(stringClass); + // + jobjectArray result = aJni.NewObjectArray(aNativeArray.Count(), stringClass, NULL); + if (result != NULL) + { + TPtrC item; + for (int i=0; i + +#include "mmmaeventposter.h" +#include "cmmadeleterefevent.h" +#include "cmmaforegroundevent.h" + +// xm-radio fix +//#include "CMIDToolkit.h" +//#include "lcdui.h" + +#include +#include + +// CLASS DECLARATION +/** +* +* Class is used to find out from java is midlet foreground or not +*/ +NONSHARABLE_CLASS(CMMAForeground) : public CBase/*, public MMIDEnvObserver, public MCoeForegroundObserver*/ +{ +public: + + /** + * Creates and returns a new instance of this class. + * @param aEventPoster for posting event to java side + * @param aForegroundListener java side foreground object + * @param aJavaMethod java side method id + * @return New instance from this class. + */ + static CMMAForeground* NewL(MMMAEventPoster* aEventPoster, + jobject aForegroundListener, + jmethodID aJavaMethod/*, + CMIDToolkit* aToolkit*/); // xm-radio fix + /** + * Destructor. + */ + ~CMMAForeground(); + +protected: + + /** + * C++ constructor + */ + CMMAForeground(); + + /** + * Second phase constructor + * @param aEventPoster for posting event to java side + * @param aForegroundListener java side foreground object + * @param aJavaMethod java side method id + */ + void ConstructL(MMMAEventPoster* aEventPoster, + jobject aForegroundListener, + jmethodID aJavaMethod/*, + CMIDToolkit* aToolkit*/); // xm-radio fix + +public: // New methods + + + /** + * Tells is midlet foreground or not + * @return boolean + */ + TBool IsForeground(); + + /** + * Sets member boolean iIsForeground + */ + void SetForeground(TBool aIsForeground); + +public: // from MMIDEnvObserver + + // void HandleSwitchOnL(TBool /*aSwitchOn*/); + + /** + * Handles the case when the MIDlet is brought to the foreground. + */ + // void HandleForegroundL(TBool /*aForeground*/); + + /** + * Handles a change to resources which are shared accross the environment. + */ + // void HandleResourceChangeL(TInt /*aType*/); + +public: + /** Handles the application coming to the foreground. */ + void HandleGainingForeground(); + + /** Handles the application going into the background. */ + void HandleLosingForeground(); + +private: // Member data + + CActiveSchedulerWait* iActiveScheduler; // owned + MMMAEventPoster* iEventPoster; // not owned + CMMAForegroundEvent* iForegroundEvent; // owned + + //Event is used to destroy reference to associated java object, + //when foreground is destroyed. + CMMADeleteRefEvent* iDeleteRefEvent; // owned + + jobject iForegroundListener; + jmethodID iJavaMethod; + + TBool iIsForeground; + // xm-radio fix + //CMIDToolkit* iToolkit; + //MMIDEnv* iMidEnv; +}; + +#endif // CMMAFOREGROUND_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/inc/cmmaforegroundevent.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/inc/cmmaforegroundevent.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +#ifndef CMMAFOREGROUNDEVENT_H +#define CMMAFOREGROUNDEVENT_H + +// INCLUDES +#include "cmmaevent.h" + +// CLASS DECLARATION +/** +* This class is used to post events to the java. +* +* +*/ + +NONSHARABLE_CLASS(CMMAForegroundEvent) : public CMMAEvent +{ +public: // Construction + /** + * Constructor. + * + * @param aNotifyObject java side foreground object + * @param aHandleEventMethod java side method id + * @param aDisposable Indicates if this event will be destroyed + * after dispatch. + */ + CMMAForegroundEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable = EDisposableEvent); + + +private: // from CMMAEvent + + void Dispatch(JNIEnv& aJni); + +}; + +#endif // CMMAFOREGROUNDEVENT_H diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/inc/cmmaglobalvolume.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/inc/cmmaglobalvolume.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for global volume +* +*/ + + +#ifndef CMMAGLOBALVOLUME_H +#define CMMAGLOBALVOLUME_H + +// INTERNAL INCLUDES +#include "cmmavolumecontrol.h" +#include "mmmavolumekeyslistener.h" + +class CMMAPlayer; +class CMMAForeground; +class CRepository; +class CMMAVolumeKeysListener; + +// CLASS DECLARATION +/** + * This class is used for global volume setting + * @since S60 3.2 + */ +NONSHARABLE_CLASS(CMMAGlobalVolume) : public CBase, + public MMMAVolumeKeysListener +{ +private: // Type definitions + + // Volume control, index and player holder + class TMMAPlayerHolder + { + public: + // Volume index + TInt iVolumeIndex; + // Player which contains the volume control + CMMAPlayer* iPlayer; + // Volume control from the player + CMMAVolumeControl* iVolumeControl; + }; + +public: // Constructor and destructors + + /** + * NewL + * Creates an instance from this class + * @param aForeground Foreground listener. The ownership is transferred + * to this class + * @return New instance from this class. The caller takes ownership + * of the returned object + */ + static CMMAGlobalVolume* NewL(CMMAForeground* aForeground); + + /** + * Destructor + */ + virtual ~CMMAGlobalVolume(); + +public: // New methods + + /** + * Adds new player for listening global volume. Players which + * do not have volume control are simply ignored + * + * @param aPlayer Player which receives volume key notifications + */ + void AddPlayerL(CMMAPlayer* aPlayer); + + /** + * Removes player from listening global volume + */ + void RemovePlayer(CMMAPlayer* aPlayer); + +public: // From MMMAVolumeKeysListener + + /** + * Handles volume up event + */ + void VolumeUp(); + + /** + * Handles volume down event + */ + void VolumeDown(); + +private: // New methods + + /** + * Finds volume control from a player + * + * @param aPlayer Player from which the volume control is searched + * @return Volume control instance. NULL is returned if the player + * does not support volume control feature + */ + CMMAVolumeControl* FindVolumeControl(CMMAPlayer* aPlayer); + + /** + * Sets volume level for all registered volume controls + * @param aLevel New volume level + */ + void SetControlVolumeLevels(TInt aLevel); + +private: // Private constructors + + /** + * C++ constructor + * @param aForeground Foreground listener + */ + CMMAGlobalVolume(CMMAForeground* aForeground); + + /** + * Second phase constructor + */ + void ConstructL(); + +protected: // Data + + // Current global volume level + TInt iLevel; + // Foreground listener. Owned + CMMAForeground* iForeground; + // MMA setting repository. Owned + CRepository* iSettingsStore; + // Volume keys listener. Owned + CMMAVolumeKeysListener* iVolumeKeysListener; + // Array of volume controls + RArray< TMMAPlayerHolder > iControlList; +}; + +#endif // CMMAGLOBALVOLUME_H + +// End of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/inc/cmmavolumekeyslistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/inc/cmmavolumekeyslistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class handles the volume keys update events +* +* +*/ + + +#ifndef CMMAVOLUMEKEYSLISTENER_H +#define CMMAVOLUMEKEYSLISTENER_H + +// EXTERNAL INCLUDES +#include +/*#include +#include +#include +*/ +// INTERNAL INCLUDES +#include "mmmavolumekeyslistener.h" + +// CLASS DECLARATION +class CRemConInterfaceSelector; +class CRemConCoreApiTarget; + +// CLASS DECLARATION +/** + *This class handles the volume keys update events + * + */ +NONSHARABLE_CLASS(CMMAVolumeKeysListener) : public CBase/*, public MRemConCoreApiTargetObserver*/ +{ +public: // Constructors and destructor + + /** + * Creates and returns a new instance of this class. + * @param aListener Listener for key events + */ + static CMMAVolumeKeysListener* NewL(MMMAVolumeKeysListener* aListener); + + // Destructor + ~CMMAVolumeKeysListener(); + +private: // Constructors + + // Default constructor + CMMAVolumeKeysListener(); + + /** + * Second phase constructor. + * @param aListener Listener for key events + */ + void ConstructL(MMMAVolumeKeysListener* aListener); + +public: // New functions + + + void HandleTimerEvent(); + + + // From MRemConCoreApiTargetObserver + /* void MrccatoPlay(TRemConCoreApiPlaybackSpeed aSpeed, + TRemConCoreApiButtonAction aButtonAct); + + void MrccatoCommand(TRemConCoreApiOperationId aOperationId, + TRemConCoreApiButtonAction aButtonAct); + + void MrccatoTuneFunction(TBool aTwoPart, TUint aMajorChannel, + TUint aMinorChannel, + TRemConCoreApiButtonAction aButtonAct); + + void MrccatoSelectDiskFunction(TUint aDisk, + TRemConCoreApiButtonAction aButtonAct); + + void MrccatoSelectAvInputFunction( + TUint8 aAvInputSignalNumber, + TRemConCoreApiButtonAction aButtonAct); + void MrccatoSelectAudioInputFunction( + TUint8 aAudioInputSignalNumber, + TRemConCoreApiButtonAction aButtonAct); + + */ + +private: + + /** + * TimerCallback + * This is the callback function called from timer. + */ + static TInt TimerCallback(TAny* aThis); + +private: + CRemConInterfaceSelector* iInterfaceSelector; //owned + CRemConCoreApiTarget* iCoreTarget; //owned by iInterfaceSelector + + // For getting timer ticks/events, owned + CPeriodic* iTimer; + // Marks if volume is increased or decreased + TBool iUp; + // Listener listening events. Used + MMMAVolumeKeysListener* iListener; + /* CJavaRemConManager *iJavaRemConManager; + CJavaRemConObserver *iJavaRemConObserver; + */ +}; + +#endif // CMMAVOLUMEKEYSLISTENER_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/inc/mmaprivatecrkeys.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/inc/mmaprivatecrkeys.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: MMA private Central Repository uids and keys +* +*/ + + +#ifndef MMAPRIVATECRKEYS_H +#define MMAPRIVATECRKEYS_H + +// MMA settings store Central Repository uid +const TUid KCRUidMobileMedia = { 0x102828A1 }; +// Key identifier for Volume level setting +const TUint32 KMobileMediaVolumeLevel = 0x00000001; + +#endif // MMAPRIVATECRKEYS_H + +// End of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/inc/mmmavolumekeyslistener.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/inc/mmmavolumekeyslistener.h Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: The class derived from this class handles the volume keys +* update events +* +* +*/ + + + +#ifndef MMMAVOLUMEKEYSLISTENER_H +#define MMMAVOLUMEKEYSLISTENER_H + +#include + +// CLASS DECLARATION +/** +* The class derived from this class handles the volume keys +* update events +*/ +NONSHARABLE_CLASS(MMMAVolumeKeysListener) +{ +public: // Constructors and destructor + + //Virtual destructor, public allows delete + virtual ~MMMAVolumeKeysListener() {}; + +public: // Abstract methods + /** + * Called when volume key is clicked/pressed up + */ + virtual void VolumeUp() = 0; + + /** + * Called when volume key is clicked/pressed down + */ + virtual void VolumeDown() = 0; +}; + +#endif // MMMAVOLUMEKEYSLISTENER_H + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/javasrc/com/nokia/microedition/volumekeys/ForegroundListener.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/javasrc/com/nokia/microedition/volumekeys/ForegroundListener.java Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,150 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: + * +*/ + + +// PACKAGE +package com.nokia.microedition.volumekeys; + +// IMPORTS +import com.nokia.microedition.media.NativeError; +import java.lang.OutOfMemoryError; +//import com.nokia.microedition.volumekeys.LCDUIForegroundListener; + +import org.eclipse.swt.*; +import org.eclipse.swt.widgets.*; +import javax.microedition.lcdui.*; +import org.eclipse.swt.widgets.Display; + + +// for xm-radio fix +//import com.symbian.midp.runtime.ToolkitInvoker; + +// CLASS DESCRIPTION +/** + * Provides information about the state of the MIDlet + */ +public class ForegroundListener implements Listener +{ + //private final LCDUIForegroundListener iLCDUIForegroundListener; + private final int iForegroundHandle; + private final int iEventSourceHandle; + // Added for MMAPI UI 3.x + private boolean flagForground = true; + // private MMAPILCDUIInvokerImpl obj; + + /* + * Constructor. Creates Foreground listener + * The listener is added to Event source native side + */ + public ForegroundListener(int aEventSourceHandle) + { + iEventSourceHandle = aEventSourceHandle; + // Added for MMAPI UI 3.x + // obj = new MMAPILCDUIInvokerImpl(); + // obj.AddObservertoDisplay(this); + System.out.println("inside ForgroundLIstener constructor before _initialize"); + iForegroundHandle = _initialize(aEventSourceHandle, this/*, iToolkitHandle*/); + System.out.println("inside ForgroundLIstener constructor after _initialize"); + if (iForegroundHandle < NativeError.KErrNone) + { + throw new OutOfMemoryError("Foreground initialization failed."); + } + + + + } + + +public void init() +{ +final ForegroundListener listener = this; +System.out.println("inside init()...."); + +try{ + final org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + System.out.println("inside init()....1"); + + + disp.syncExec(new Runnable() { + public void run() { + org.eclipse.swt.widgets.Display disp = com.nokia.mj.impl.nokialcdui.LCDUIInvoker.getEswtDisplay(); + disp.addFilter(SWT.Activate,listener); + disp.addFilter(SWT.Deactivate,listener); + } + }); +} +catch(Exception e) +{ + System.out.println("inside init()....exception is " + e.toString()); +} + + +} + + + // Added for MMAPI UI 3.x + + public boolean isForeground() + { + return flagForground; + } + + /* + * From org.eclipse.swt.widget.Listener interface + * Handling all the event + * Used to filter out the event which can be used for Foreground/Background notification + */ + public void handleEvent(Event event) + { + System.out.println("ForegroundListener :handle event is called"); + if(event.type == SWT.Activate) + { + System.out.println("handle event got a event: not in background"); + flagForground = true; + // update(); + + } + else if(event.type == SWT.Deactivate) + { + System.out.println("handle event got a event: in background"); + flagForground = false; + // update(); + } + } + + /* + * Called from handleEvent callback function to notify native about the midlet foreground status + */ + public synchronized void update() + { + boolean isFg = isForeground(); + System.out.println("ForegroundListener.java inside update() : before calling native function "); + _setForeground(iEventSourceHandle, iForegroundHandle, isFg); + System.out.println("ForegroundListener.java inside update() : after calling native function "); + } + + private native int _initialize(int aEventSourceHandle, + Object aForegroundListener/*, + int atoolkitHandle*/); // xm-radio fix + + private native void _setForeground(int aEventSourceHandle, + int aForegroundHandle, + boolean aForeground); + +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/src/Foreground.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/src/Foreground.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,172 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: JNI implementation for handling midlet foreground status +* +*/ + + +// EXTERNAL INCLUDES +//#include +#include + +//#include +//#include + +// INTERNAL INCLUDES +#include "com_nokia_microedition_volumekeys_ForegroundListener.h" +#include "cmmaforeground.h" +#include "mmafunctionserver.h" +#include "cmmaglobalvolume.h" + +// for xm-radio fix +//#include "CMIDToolkit.h" + +/** + * Static delegator function for initialize. + * @param aReturnHandle Native class object. + * @param aEventSource Event source handle. + * @param aForegroundListener ForegroundListener java object. + * @param aJavaMethod java method ID. + */ +LOCAL_C void CreateForegroundL( + TInt* aReturnHandle, + MMAFunctionServer* aEventSource, + jobject aForegroundListener, + jmethodID aJavaMethod/*, + CMIDToolkit* aToolkit*/) // xm-radio fix +{ + CMMAForeground* foreground = + CMMAForeground::NewL(aEventSource, + aForegroundListener, + aJavaMethod/*, + aToolkit */// xm-radio fix + ); + CleanupStack::PushL(foreground); + + // Create global volume which handles the volume events + CMMAGlobalVolume* globalVolume = CMMAGlobalVolume::NewL(foreground); + // Global volume takes the ownership of the foreground listener + CleanupStack::Pop(foreground); + // Set global volume to MMA event source. The ownership transfers to + // MMA event sources as it handles adding and removing players + aEventSource->SetGlobalVolume(globalVolume); + *aReturnHandle = reinterpret_cast (foreground); +} + +/* + * Class: com_nokia_microedition_volumekeys_ForegroundListener + * Method: _initialize + * Signature: (ILjava/lang/Object;)I + */ +JNIEXPORT jint JNICALL Java_com_nokia_microedition_volumekeys_ForegroundListener__1initialize +(JNIEnv* aJni, + jobject /*aJobject*/, + jint aEventSourceHandle, + jobject aForegroundListener /*, + jint aToolkitHandle*/) // for xm-radio fix +{ + MMAFunctionServer* eventSource = + reinterpret_cast< MMAFunctionServer *>(aEventSourceHandle); + + jobject fgListenerObject = NULL; + fgListenerObject = aJni->NewWeakGlobalRef(aForegroundListener); + + jclass foregroundListenerClass = aJni->GetObjectClass(fgListenerObject); + + jmethodID javaMethod = aJni->GetMethodID( + foregroundListenerClass, + "update", + "()V"); + + TInt foregroundHandle = NULL; + + // xm-radio fix + /* + CMIDToolkit* ptoolkit = JavaUnhand< CMIDToolkit >(aToolkitHandle); +*/ + jint error = eventSource->ExecuteTrap(CreateForegroundL, + &foregroundHandle, + eventSource, + fgListenerObject, + javaMethod/*, + ptoolkit*/); // xm-radio fix + + if (error != KErrNone) + { + aJni->DeleteGlobalRef(fgListenerObject); + } + + return (error != KErrNone) ? error : foregroundHandle; +} + +/** + * Static delegator function for setforeground + * @param aCMMAForeground native class. + * @param aIsForeground boolean is midlet foreground or not. + + */ +LOCAL_C void SetForeground( + CMMAForeground* aCMMAForeground, + TBool aIsForeground) +{ + aCMMAForeground->SetForeground(aIsForeground); +} + +/* +* Class: com_nokia_microedition_volumekeys_ForegroundListener +* Method: _setForeground +* Signature: (IZ)V +*/ +JNIEXPORT void JNICALL Java_com_nokia_microedition_volumekeys_ForegroundListener__1setForeground +(JNIEnv* /*aJni*/, + jobject /*aJobject*/, + jint aEventSourceHandle, + jint aForegroundHandle, + jboolean aIsForeground) +{ + MMAFunctionServer* eventSource = + reinterpret_cast(aEventSourceHandle); + + CMMAForeground* nativeHandle = + reinterpret_cast(aForegroundHandle); + + eventSource->ExecuteV(SetForeground, + nativeHandle, + (TBool) aIsForeground); +} + + +/* +JNIEXPORT jboolean JNICALL Java_com_nokia_microedition_volumekeys_ForegroundListener__1isESWT +(JNIEnv *, jobject) +{ + + + MSwtClient* client = NULL; + TRAP_IGNORE(client = SWT::CreateClientL()); + + if (!client) + { + return false; // LCDUI midlet running + } + else + { + delete client; + client = NULL; + return true; // eSWT midlet running + } +} + +*/ +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/src/cmmaforeground.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/src/cmmaforeground.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,182 @@ +/* +* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: Class is used to find out from java is midlet foreground or not +* +*/ + + + +// INCLUDE FILES +#include + +#include "cmmaforeground.h" +#include "cmmaforegroundevent.h" +// INCLUDE FILES +#include + +// xm-radio fix +//#include "cmidenv.h" + +CMMAForeground* CMMAForeground::NewL(MMMAEventPoster* aEventPoster, + jobject aForegroundListener, + jmethodID aJavaMethod/* , + CMIDToolkit* aToolkit*/) +{ + LOG( EJavaMMAPI, EInfo, "CMMAForeground::NewL + "); + CMMAForeground* self = new(ELeave) CMMAForeground; + + CleanupStack::PushL(self); + self->ConstructL(aEventPoster, aForegroundListener, aJavaMethod/*, aToolkit*/); + CleanupStack::Pop(); + + LOG( EJavaMMAPI, EInfo, "CMMAForeground::NewL - "); + return self; +} + +CMMAForeground::~CMMAForeground() +{ + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() + "); + /* if (iMidEnv) + { + // unregister for getting the foreground change event + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() : iMidEnv RemoveObserver +"); + iMidEnv->RemoveObserver(*this); + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() : iMidEnv RemoveObserver -"); + } + + CEikonEnv* eikEnv = ((CEikonEnv*)CEikonEnv::Static()); + + if (eikEnv) + { + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() : eikEnv RemoveForegroundObserver +"); + eikEnv->RemoveForegroundObserver(*this); + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() : eikEnv RemoveForegroundObserver -"); + } +*/ + if (iEventPoster && iDeleteRefEvent) + { + iEventPoster->PostEvent(iDeleteRefEvent); + } + else + { + delete iDeleteRefEvent; + } + delete iForegroundEvent; + delete iActiveScheduler; + LOG( EJavaMMAPI, EInfo, "CMMAForeground::~CMMAForeground() - "); +} + +CMMAForeground::CMMAForeground() + : iIsForeground(ETrue) // Initialize IsForeground to true, we might have already missed the event (HandleForegroundL), events before observer registration +{ +} + +void CMMAForeground::ConstructL(MMMAEventPoster* aEventPoster, + jobject aForegroundListener, + jmethodID aJavaMethod /* , + CMIDToolkit* aToolkit*/) // xm-radio fix +{ + LOG1( EJavaMMAPI, EInfo, "CMMAForeground::ConstructL + ISFOREGROUND = %d",iIsForeground); + + iActiveScheduler = new(ELeave) CActiveSchedulerWait(); + iEventPoster = aEventPoster; + iForegroundListener = aForegroundListener; + iJavaMethod = aJavaMethod; + + iForegroundEvent = new(ELeave) CMMAForegroundEvent( + aForegroundListener, + aJavaMethod, + CMMAEvent::EReusableEvent); + iDeleteRefEvent = new(ELeave) CMMADeleteRefEvent(aForegroundListener); + + // xm-radio fix + /* + iToolkit = aToolkit; + + if (iToolkit) + { + DEBUG("CMMAForeground::ConstructL : iToolkit->Env(); +"); + iMidEnv = iToolkit->Env(); + DEBUG("CMMAForeground::ConstructL : iToolkit->Env(); -"); + } + + if (iMidEnv) + { + DEBUG("CMMAForeground::ConstructL : iMidEnv->AddObserverL + "); + // register for getting the foreground change event + iMidEnv->AddObserverL(*this); + DEBUG("CMMAForeground::ConstructL : iMidEnv->AddObserverL - "); + } + + CEikonEnv* eikEnv = ((CEikonEnv*)CEikonEnv::Static()); + + if (eikEnv) + { + DEBUG("CMMAForeground::ConstructL - eikAppUi->AddForegroundObserverL() + "); + eikEnv->AddForegroundObserverL(*this); + DEBUG("CMMAForeground::ConstructL - eikAppUi->AddForegroundObserverL() - "); + } + */ + LOG( EJavaMMAPI, EInfo, "CMMAForeground::ConstructL - "); +} + +TBool CMMAForeground::IsForeground() +{ + LOG2( EJavaMMAPI, EInfo, "THREADID = %d : CMMAForeground::IsForeground : ISFOREGROUND = %d",RThread().Id().Id(),iIsForeground); + return iIsForeground; +} + +void CMMAForeground::SetForeground(TBool aIsForeground) +{ + iIsForeground = aIsForeground; + LOG1( EJavaMMAPI, EInfo, "CMMAForeground::SetForeground - ISFOREGROUND = %d",iIsForeground); +} + +// Implement MMIDEnvObserver +/* +void CMMAForeground::HandleSwitchOnL(TBool aSwitchOn) +{ + // Dummy implementation, no intent to do anything +} +*/ +/** + * Handles the case when the MIDlet is brought to the foreground. + */ + /* +void CMMAForeground::HandleForegroundL(TBool aForeground) +{ + LOG1( EJavaMMAPI, EInfo, "CMMAForeground::HandleForegroundL %d", aForeground); + iIsForeground = aForeground; +} +*/ +/** + * Handles a change to resources which are shared accross the environment. + */ +/*void CMMAForeground::HandleResourceChangeL(TInt aType) +{ + // Dummy implementation, no intent to do anything +} +*/ +// Handles the application coming to the foreground. +void CMMAForeground::HandleGainingForeground() +{ + iIsForeground = ETrue; +} + +// Handles the application going into the background. +void CMMAForeground::HandleLosingForeground() +{ + iIsForeground = EFalse; +} +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/src/cmmaforegroundevent.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/src/cmmaforegroundevent.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used to post events to the java. +* +*/ + + +// INCLUDE FILES +#include + +#include "cmmaforegroundevent.h" + +CMMAForegroundEvent::CMMAForegroundEvent(jobject aNotifyObject, + jmethodID aHandleEventMethod, + TDisposability aDisposable): + CMMAEvent(aNotifyObject, aHandleEventMethod, aDisposable) +{ + +} + +void CMMAForegroundEvent::Dispatch(JNIEnv& aJni) +{ + aJni.CallVoidMethod(iListenerObject, + iHandleEventMethod); +} + +// END OF FILE diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/src/cmmaglobalvolume.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/src/cmmaglobalvolume.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,241 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class is used for global volume +* +*/ + + +// CLASS HEADER +#include "cmmaglobalvolume.h" + +// INTERNAL INCLUDES +#include "cmmaplayer.h" +#include "cmmaforeground.h" +#include "cmmavolumekeyslistener.h" +#include "mmaprivatecrkeys.h" + +// EXTERNAL INCLUDES +#include +#include + +// UNNAMED LOCAL NAMESPACE +namespace +{ +// Volume level step size +const TInt KMMAVolumeLevelStep = 10; +// Error when setting new volume level for a control +_LIT(KMMAGlobalVolumeSetError, "Can't set volume level"); +} + + +// ============================ MEMBER FUNCTIONS ============================= + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::NewL +// --------------------------------------------------------------------------- +// +CMMAGlobalVolume* CMMAGlobalVolume::NewL(CMMAForeground* aForeground) +{ + CMMAGlobalVolume* self = new(ELeave) CMMAGlobalVolume(aForeground); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::~CMMAGlobalVolume +// --------------------------------------------------------------------------- +// +CMMAGlobalVolume::~CMMAGlobalVolume() +{ + delete iVolumeKeysListener; + //delete iSettingsStore; + delete iForeground; + iControlList.Close(); +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::AddPlayerL +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::AddPlayerL(CMMAPlayer* aPlayer) +{ + // Find if the player has a volume control + CMMAVolumeControl* control = FindVolumeControl(aPlayer); + + // Ignore adding new player if it does not support volume control + if (control) + { + TMMAPlayerHolder playerHolder; + // Create new volume control and level index pair + playerHolder.iVolumeControl = control; + playerHolder.iVolumeIndex = control->AddLevelL(); + playerHolder.iPlayer = aPlayer; + // Set current volume level for the control + control->SetVolumeLevelL(playerHolder.iVolumeIndex, iLevel); + // Add created pair to the control list + iControlList.AppendL(playerHolder); + } +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::RemovePlayer +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::RemovePlayer(CMMAPlayer* aPlayer) +{ + // Find if the player has a volume control + CMMAVolumeControl* control = FindVolumeControl(aPlayer); + + // Ignore adding new player if it does not support volume control + if (control) + { + // Check that if this type of volume control can be found from + // the control list and remove it + TInt count(iControlList.Count()); + for (TInt i(0); i < count; i++) + { + const TMMAPlayerHolder& holder = iControlList[ i ]; + if (control == holder.iVolumeControl) + { + iControlList.Remove(i); + break; + } + } + } +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::VolumeUp +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::VolumeUp() +{ + LOG1( EJavaMMAPI, EInfo, "THREADID = %d : CMMAGlobalVolume: VolumeUp: +", RThread().Id().Id()); + // Adjust volume if midlet is in foreground and the volume level value + // is not too high, in this case it cannot be set over KMMAVolumeMaxLevel + if (iForeground->IsForeground() && (iLevel < KMMAVolumeMaxLevel)) + { + LOG( EJavaMMAPI, EInfo, "CMMAGlobalVolume: VolumeUp: Volume up"); + // Check that the current volume level is not increased too much + TInt level = + iLevel > (KMMAVolumeMaxLevel - KMMAVolumeLevelStep) ? + KMMAVolumeMaxLevel - iLevel : iLevel + KMMAVolumeLevelStep; + // Increase level by new value + SetControlVolumeLevels(level); + } + LOG( EJavaMMAPI, EInfo, "CMMAGlobalVolume: VolumeUp: -"); +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::VolumeDown +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::VolumeDown() +{ + LOG1( EJavaMMAPI, EInfo, "THREADID = %d : CMMAGlobalVolume: VolumeDown: +", RThread().Id().Id()); + // Adjust volume if midlet is in foreground and the volume value + // is not too low, in this case it cannot be set under zero + if (iForeground->IsForeground() && (iLevel > 0)) + { + LOG( EJavaMMAPI, EInfo, "CMMAGlobalVolume: VolumeDown: Volume down"); + // Check that the currnet volume level is not decreased too much + TInt level = + iLevel < KMMAVolumeLevelStep ? + 0 : iLevel - KMMAVolumeLevelStep; + // Decrease level by new value + SetControlVolumeLevels(level); + } + LOG( EJavaMMAPI, EInfo, "CMMAGlobalVolume: VolumeDown: -"); +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::FindVolumeControl +// --------------------------------------------------------------------------- +// +CMMAVolumeControl* CMMAGlobalVolume::FindVolumeControl(CMMAPlayer* aPlayer) +{ + TInt count(aPlayer->ControlCount()); + for (TInt i(0); i < count; i++) + { + CMMAControl* control = aPlayer->Control(i); + // Check that if this control supports volume control + if (control->ClassName() == KMMAVolumeControlName) + { + return static_cast< CMMAVolumeControl* >(control); + } + } + // Does not support volume control + return NULL; +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::SetControlVolumeLevels +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::SetControlVolumeLevels(TInt aLevel) +{ + TInt count(iControlList.Count()); + // Adjust volume for all current volume controls associated + for (TInt i(0); i < count; i++) + { + const TMMAPlayerHolder& hdr = iControlList[ i ]; + // Set new volume level for this control + TRAPD(error, + hdr.iVolumeControl->SetVolumeLevelL(hdr.iVolumeIndex, aLevel)); + if (error != KErrNone) + { + hdr.iPlayer->PostStringEvent( + CMMAPlayerEvent::EError, + KMMAGlobalVolumeSetError()); + } + } + + iLevel = aLevel; + LOG1( EJavaMMAPI, EInfo, + "CMMAGlobalVolume::SetControlVolumeLevels - iLevel = %d", iLevel); + + // Store new volume to MMA global settings. Error cannot be reported + // in any sophisticated way so we just have to ignore it. Debug builds + // may panic in this case + TInt error = iSettingsStore->Set(KMobileMediaVolumeLevel, aLevel); + __ASSERT_DEBUG(error == KErrNone, User::Invariant()); +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::CMMAGlobalVolume +// --------------------------------------------------------------------------- +// +CMMAGlobalVolume::CMMAGlobalVolume(CMMAForeground* aForeground) : + iLevel(KMMAVolumeMaxLevel), + iForeground(aForeground) +{ +} + +// --------------------------------------------------------------------------- +// CMMAGlobalVolume::ConstructL +// --------------------------------------------------------------------------- +// +void CMMAGlobalVolume::ConstructL() +{ + iVolumeKeysListener = CMMAVolumeKeysListener::NewL(this); + // TO-DO remove TRAP_IGNORE + // TRAP_IGNORE(err,iSettingsStore = CRepository::NewL(KCRUidMobileMedia)); + + // Get level from the settings store + //User::LeaveIfError(iSettingsStore->Get(KMobileMediaVolumeLevel, iLevel)); +} + +// End of file diff -r 2a9601315dfc -r 98ccebc37403 javauis/mmapi_qt/volumekeys/src/cmmavolumekeyslistener.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/javauis/mmapi_qt/volumekeys/src/cmmavolumekeyslistener.cpp Fri May 14 15:47:24 2010 +0300 @@ -0,0 +1,267 @@ +/* +* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: This class handles the volume keysupdate events +* +*/ + + +// INCLUDE FILES +/*#include +#include +#include +*/ +//#include +#include + +#include "cmmavolumekeyslistener.h" + +// CONSTANTS + +// Keyboard delays and repeat periods +//const TInt KFirstTimerExpiryInterval = KAknKeyboardRepeatInitialDelay; +// For second time onwards ,the duration of the time interval, is below +// Should not be greater than 1 Minute +// const TInt KTimerExpiryInterval = KAknStandardKeyboardRepeatRate; + +CMMAVolumeKeysListener* CMMAVolumeKeysListener::NewL(MMMAVolumeKeysListener* aListener) +{ + CMMAVolumeKeysListener* self = new(ELeave) CMMAVolumeKeysListener(); + CleanupStack::PushL(self); + self->ConstructL(aListener); + CleanupStack::Pop(); + return self; +} + +CMMAVolumeKeysListener::~CMMAVolumeKeysListener() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::~CMMAVolumeKeysListener() +"); + /* if ((NULL != iJavaRemConObserver) && (NULL != iJavaRemConManager)) + { + iJavaRemConManager->RemoveObserver(*iJavaRemConObserver); + } + + if (NULL != iJavaRemConObserver) + { + delete iJavaRemConObserver; + iJavaRemConObserver = NULL; + } + + if (NULL != iJavaRemConManager) + { + delete iJavaRemConManager; + iJavaRemConManager = NULL; + } +*/ + if (NULL != iTimer) + { + iTimer->Cancel(); + delete iTimer; + } + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::~CMMAVolumeKeysListener() -"); +} + +CMMAVolumeKeysListener::CMMAVolumeKeysListener() +{ +} + +void CMMAVolumeKeysListener::ConstructL(MMMAVolumeKeysListener* aListener) +{ + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::ConstructL +"); + /*iJavaRemConObserver = CJavaRemConObserver::NewL(*this); + iJavaRemConManager = CJavaRemConManager::NewL(); + iJavaRemConManager->SetObserverL(*iJavaRemConObserver); +*/ + // Timer for implementing Pressed/Released/Clicked feature. + iTimer = CPeriodic::NewL(CActive::EPriorityStandard); + + iListener = aListener; + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::ConstructL -"); +} + +/* +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoPlay() +// Called when Play button is pressed/clicked/released +// ---------------------------------------------------------------------------- +void CMMAVolumeKeysListener::MrccatoPlay(TRemConCoreApiPlaybackSpeed aSpeed, + TRemConCoreApiButtonAction aButtonAct) +{ +} +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoCommand() +// This function receives the events when following buttons are press/click/rel +// - Volume Up , Volume Down +// ---------------------------------------------------------------------------- +void CMMAVolumeKeysListener::MrccatoCommand(TRemConCoreApiOperationId aOperationId, + TRemConCoreApiButtonAction aButtonAct) +{ + switch (aOperationId) + { + case ERemConCoreApiVolumeUp: + { + iUp = ETrue; + switch (aButtonAct) + { + case ERemConCoreApiButtonPress: + { + // Start Timer + if (!iTimer->IsActive()) + { + // Start Timer + iTimer->Start(KFirstTimerExpiryInterval, + KTimerExpiryInterval, + TCallBack(TimerCallback, this)); + } + break; + } + case ERemConCoreApiButtonRelease: + { + if (iTimer->IsActive()) + { + iTimer->Cancel(); + } + break; + } + case ERemConCoreApiButtonClick: + { + iListener->VolumeUp(); + break; + } + default: + { + break; + } + } + break; + } + case ERemConCoreApiVolumeDown: + { + iUp = EFalse; + switch (aButtonAct) + { + case ERemConCoreApiButtonPress: + { + // Start Timer + if (!iTimer->IsActive()) + { + // Start Timer + iTimer->Start(KFirstTimerExpiryInterval, + KTimerExpiryInterval, + TCallBack(TimerCallback, this)); + } + break; + } + case ERemConCoreApiButtonRelease: + { + if (iTimer->IsActive()) + { + iTimer->Cancel(); + } + break; + } + case ERemConCoreApiButtonClick: + { + iListener->VolumeDown(); + break; + } + default: + { + break; + } + } + break; + } + default: + { + break; + } + } +} + +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoTuneFunction() +// +// ---------------------------------------------------------------------------- + +void CMMAVolumeKeysListener::MrccatoTuneFunction(TBool aTwoPart, + TUint aMajorChannel, + TUint aMinorChannel, + TRemConCoreApiButtonAction aButtonAct) +{ +} + +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoSelectDiskFunction() +// +// ---------------------------------------------------------------------------- +void CMMAVolumeKeysListener::MrccatoSelectDiskFunction(TUint aDisk, + TRemConCoreApiButtonAction aButtonAct) +{ +} + +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoSelectAvInputFunction() +// +// ---------------------------------------------------------------------------- +void CMMAVolumeKeysListener::MrccatoSelectAvInputFunction(TUint8 aAvInputSignalNumber, + TRemConCoreApiButtonAction aButtonAct) +{ +} + +// ---------------------------------------------------------------------------- +// void CMMAVolumeKeysListener::MrccatoSelectAudioInputFunction() +// +// ---------------------------------------------------------------------------- +void CMMAVolumeKeysListener::MrccatoSelectAudioInputFunction(TUint8 aAudioInputSignalNumber, + TRemConCoreApiButtonAction aButtonAct) +{ +} + +*/ +// ----------------------------------------------------------------------- +// CMMAVolumeKeysListener::HandleTimerEvent +// Description: When Timer is expired, this function is called from +// callback function. +// return : +// ----------------------------------------------------------------------- +// +void CMMAVolumeKeysListener::HandleTimerEvent() +{ + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::HandleTimerEvent +"); + if (iUp) + { + iListener->VolumeUp(); + } + else + { + iListener->VolumeDown(); + } + LOG( EJavaMMAPI, EInfo, "CMMAVolumeKeysListener::HandleTimerEvent -"); +} + +// ----------------------------------------------------------------------- +// CMMAVolumeKeysListener::TimerCallback +// Description: When Timer is expired, this function is called +// return : +// ----------------------------------------------------------------------- +// +TInt CMMAVolumeKeysListener::TimerCallback(TAny* aThis) +{ + CMMAVolumeKeysListener* listener = + static_cast< CMMAVolumeKeysListener* >(aThis); + listener->HandleTimerEvent(); + return 0; +} + +// End of File diff -r 2a9601315dfc -r 98ccebc37403 javauis/nokiasound_akn/javasrc/com/nokia/mid/sound/Sound.java --- a/javauis/nokiasound_akn/javasrc/com/nokia/mid/sound/Sound.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/nokiasound_akn/javasrc/com/nokia/mid/sound/Sound.java Fri May 14 15:47:24 2010 +0300 @@ -108,6 +108,7 @@ private static final int NOT_SUPPORTED_ERROR = 3; private static final int ERR_NOT_READY = -18; + private static final int ERR_ARGUMENT = -6; private int iHandle; @@ -362,6 +363,10 @@ { throw new RuntimeException(Integer.toString(err)); } + else if (err == ERR_ARGUMENT) + { + throw new IllegalArgumentException("Data is invalid"); + } iState = SOUND_STOPPED; } @@ -410,7 +415,7 @@ iCurrentType = type; int err = _init(iHandle, iCurrentType, data, 0, 0); - if (err == ERR_NOT_READY) + if (err == ERR_NOT_READY || err == ERR_ARGUMENT ) { throw new IllegalArgumentException("Data is invalid"); } diff -r 2a9601315dfc -r 98ccebc37403 javauis/nokiasound_akn/src/cmidsound.cpp --- a/javauis/nokiasound_akn/src/cmidsound.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/nokiasound_akn/src/cmidsound.cpp Fri May 14 15:47:24 2010 +0300 @@ -205,10 +205,18 @@ TInt CMIDSound::DoPlay(TInt aLoop) { JELOG2(EJavaUI); - TInt state = iMIDSound->State(); - if (state != CMIDSoundImpl::EReadyToPlay) + + if ( iMIDSound ) { - return state; + TInt state = iMIDSound->State(); + if (state != CMIDSoundImpl::EReadyToPlay) + { + return state; + } + } + else + { + return CMIDSoundImpl::ENotSupported; } if (!IsAudioEnabled()) { diff -r 2a9601315dfc -r 98ccebc37403 javauis/nokiauiapi_qt/build/build.xml --- a/javauis/nokiauiapi_qt/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/nokiauiapi_qt/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -36,8 +36,8 @@ - + diff -r 2a9601315dfc -r 98ccebc37403 javauis/nokiauiapi_qt/library/os.cpp --- a/javauis/nokiauiapi_qt/library/os.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/nokiauiapi_qt/library/os.cpp Fri May 14 15:47:24 2010 +0300 @@ -17,7 +17,7 @@ -#include +#include #include #include #include diff -r 2a9601315dfc -r 98ccebc37403 javauis/runtimeui_akn/javasrc.s60/com/nokia/mj/impl/rt/ui/avkon/RuntimeUiAvkon.java --- a/javauis/runtimeui_akn/javasrc.s60/com/nokia/mj/impl/rt/ui/avkon/RuntimeUiAvkon.java Mon May 03 12:27:20 2010 +0300 +++ b/javauis/runtimeui_akn/javasrc.s60/com/nokia/mj/impl/rt/ui/avkon/RuntimeUiAvkon.java Fri May 14 15:47:24 2010 +0300 @@ -24,9 +24,6 @@ /** * Runtime UI AVKON implementation. - * - * @author Nokia Corporation - * @version $Rev: 0 $ */ public class RuntimeUiAvkon extends RuntimeUi { diff -r 2a9601315dfc -r 98ccebc37403 javauis/runtimeui_akn/loc/javausermessages.loc --- a/javauis/runtimeui_akn/loc/javausermessages.loc Mon May 03 12:27:20 2010 +0300 +++ b/javauis/runtimeui_akn/loc/javausermessages.loc Fri May 14 15:47:24 2010 +0300 @@ -383,6 +383,12 @@ // #define qtn_java_secur_cert_disabling "Disabling a certificate may prevent you from installing or running some applications. Continue?" +// d:Certificate management message +// d:for deleting certificate +// l:popup_note_window +// +#define qtn_java_secur_cert_deleting "Deleting a certificate may prevent you from installing or running some applications. Continue?" + // d:Security message for platform message // d:for using network // l:popup_info_list_pane_t2/opt1 diff -r 2a9601315dfc -r 98ccebc37403 javauis/runtimeui_qt/build/build.xml --- a/javauis/runtimeui_qt/build/build.xml Mon May 03 12:27:20 2010 +0300 +++ b/javauis/runtimeui_qt/build/build.xml Fri May 14 15:47:24 2010 +0300 @@ -23,9 +23,6 @@ - - diff -r 2a9601315dfc -r 98ccebc37403 javauis/runtimeui_qt/loc/dummy.txt diff -r 2a9601315dfc -r 98ccebc37403 javauis/runtimeui_qt/src.s60/runtimeuiqt.cpp --- a/javauis/runtimeui_qt/src.s60/runtimeuiqt.cpp Mon May 03 12:27:20 2010 +0300 +++ b/javauis/runtimeui_qt/src.s60/runtimeuiqt.cpp Fri May 14 15:47:24 2010 +0300 @@ -31,7 +31,7 @@ CleanupStack::PushL(messageBox); messageBox->SetTextL(aShortMsg); - messageBox->SetTimeoutL(HbPopup::NoTimeout); + messageBox->SetTimeout(HbPopup::NoTimeout); // Read localised versions instead of hard coded values. _LIT(KOkButtonText, "OK"); @@ -41,13 +41,13 @@ _LIT(KDetailsButtonText, "Details"); messageBox->SetButtonTextL(CHbDeviceMessageBoxSymbian::EAcceptButton, KOkButtonText); - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); messageBox->SetButtonTextL(CHbDeviceMessageBoxSymbian::ERejectButton, KDetailsButtonText); - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::ERejectButton, ETrue); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::ERejectButton, ETrue); if (messageBox->ExecL() == CHbDeviceMessageBoxSymbian::ERejectButton) { - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::ERejectButton, EFalse); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::ERejectButton, EFalse); messageBox->SetTextL(aDetailedMsg); (void)messageBox->ExecL(); } @@ -55,7 +55,7 @@ else { messageBox->SetButtonTextL(CHbDeviceMessageBoxSymbian::EAcceptButton, KOkButtonText); - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); (void)messageBox->ExecL(); } messageBox->Close(); @@ -69,16 +69,16 @@ CleanupStack::PushL(messageBox); messageBox->SetTextL(aQuestion); - messageBox->SetTimeoutL(HbPopup::NoTimeout); + messageBox->SetTimeout(HbPopup::NoTimeout); // Read localised versions instead of hard coded values. _LIT(KAllowButtonText, "Allow"); _LIT(KDenyButtonText, "Deny"); messageBox->SetButtonTextL(CHbDeviceMessageBoxSymbian::EAcceptButton, KAllowButtonText); - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::EAcceptButton, ETrue); messageBox->SetButtonTextL(CHbDeviceMessageBoxSymbian::ERejectButton, KDenyButtonText); - messageBox->SetButtonL(CHbDeviceMessageBoxSymbian::ERejectButton, ETrue); + messageBox->SetButton(CHbDeviceMessageBoxSymbian::ERejectButton, ETrue); // by default the answer is Allow int result = 0; diff -r 2a9601315dfc -r 98ccebc37403 javauis/subsystem_qt.mk --- a/javauis/subsystem_qt.mk Mon May 03 12:27:20 2010 +0300 +++ b/javauis/subsystem_qt.mk Fri May 14 15:47:24 2010 +0300 @@ -14,4 +14,6 @@ # Description: Makefile for Qt based components and subsystems # -COMPONENTS += eswt_qt/build lcdui_qt/build runtimeui_qt/build nokiauiapi_qt/build +COMPONENTS += eswt_qt/build lcdui_qt/build runtimeui_qt/build nokiauiapi_qt/build mmapi_qt/build + +SYMBIAN_ONLY += mmapi_qt/build diff -r 2a9601315dfc -r 98ccebc37403 jrt_plat/java_env_info_api/inc/javaenvinfo.h --- a/jrt_plat/java_env_info_api/inc/javaenvinfo.h Mon May 03 12:27:20 2010 +0300 +++ b/jrt_plat/java_env_info_api/inc/javaenvinfo.h Fri May 14 15:47:24 2010 +0300 @@ -71,7 +71,7 @@ IMPORT_C static HBufC* GetPlatformInfoL(); private: - static TVersion JavaEnvInfo::GetJavaVersionL(); + static TVersion GetJavaVersionL(); }; } diff -r 2a9601315dfc -r 98ccebc37403 jrt_plat/java_registry_api/inc/javaregistryentry.h --- a/jrt_plat/java_registry_api/inc/javaregistryentry.h Mon May 03 12:27:20 2010 +0300 +++ b/jrt_plat/java_registry_api/inc/javaregistryentry.h Fri May 14 15:47:24 2010 +0300 @@ -148,8 +148,7 @@ * @return MJavaAttribute poiter to instance, which contain attribute. * If attribute doesn't exist return NULL. */ - IMPORT_C const MJavaAttribute* - CJavaRegistryEntry::AttributeL(const TDesC& aName) const; + IMPORT_C const MJavaAttribute* AttributeL(const TDesC& aName) const; /** * CJavaRegistryEntry::Attributes method gets the @@ -158,8 +157,7 @@ * @since S60 v5.0 * @return RPointerArray& with all additional attributes. */ - IMPORT_C const RPointerArray& - CJavaRegistryEntry::AttributesL() const; + IMPORT_C const RPointerArray& AttributesL() const; protected: diff -r 2a9601315dfc -r 98ccebc37403 layers.sysdef.xml --- a/layers.sysdef.xml Mon May 03 12:27:20 2010 +0300 +++ b/layers.sysdef.xml Fri May 14 15:47:24 2010 +0300 @@ -12,12 +12,26 @@ qmakeArgs="-r" filter="!sf_build" /> + + + + + + + + +