Compare commits

..

1 Commits

Author SHA1 Message Date
(no author)
61705a999e This commit was manufactured by cvs2svn to create tag 'arelease'.
git-svn-id: svn://10.0.0.236/tags/arelease@142510 18797224-902f-48f8-a5cc-f745e15eee43
2003-05-15 21:16:28 +00:00
139 changed files with 6162 additions and 14381 deletions

View File

@@ -0,0 +1,12 @@
// stdafx.cpp : source file that includes just the standard includes
// stdafx.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
#ifdef _ATL_STATIC_REGISTRY
#include <statreg.h>
#include <statreg.cpp>
#endif
#include <atlimpl.cpp>

View File

@@ -0,0 +1,28 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#if !defined(AFX_STDAFX_H__3B3A8A37_A147_4D96_BFA3_51B0F69B5D8D__INCLUDED_)
#define AFX_STDAFX_H__3B3A8A37_A147_4D96_BFA3_51B0F69B5D8D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define STRICT
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0400
#endif
#define _ATL_APARTMENT_THREADED
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
#include <comdef.h>
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__3B3A8A37_A147_4D96_BFA3_51B0F69B5D8D__INCLUDED)

View File

@@ -0,0 +1,28 @@
#ifndef XPCDispUtilities_h
#define XPCDispUtilities_h
template <class T>
inline
HRESULT XPCCreateInstance(const CLSID & clsid, const IID & iid, T ** result)
{
return CoCreateInstance(clsid, 0, CLSCTX_ALL, iid, reinterpret_cast<void**>(result));
}
DISPID GetIDsOfNames(IDispatch * pIDispatch , CComBSTR const & name)
{
DISPID dispid;
OLECHAR * pName = name;
HRESULT hresult = pIDispatch->GetIDsOfNames(
IID_NULL,
&pName,
1,
LOCALE_SYSTEM_DEFAULT,
&dispid);
if (!SUCCEEDED(hresult))
{
dispid = 0;
}
return dispid;
}
#endif

View File

@@ -0,0 +1,86 @@
// XPCIDispatchTest.cpp : Implementation of DLL Exports.
// Note: Proxy/Stub Information
// To build a separate proxy/stub DLL,
// run nmake -f IDispatchTestps.mk in the project directory.
#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "XPCIDispatchTest.h"
#include "XPCIDispatchTest_i.c"
#include "nsXPCDispTestMethods.h"
#include "nsXPCDispSimple.h"
#include "nsXPCDispTestNoIDispatch.h"
#include "nsXPCDispTestProperties.h"
#include "nsXPCDispTestArrays.h"
#include "nsXPCDispTestScriptOn.h"
#include "nsXPCDispTestScriptOff.h"
#include "nsXPCDispTestWrappedJS.h"
CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_nsXPCDispTestMethods, nsXPCDispTestMethods)
OBJECT_ENTRY(CLSID_nsXPCDispSimple, nsXPCDispSimple)
OBJECT_ENTRY(CLSID_nsXPCDispTestNoIDispatch, nsXPCDispTestNoIDispatch)
OBJECT_ENTRY(CLSID_nsXPCDispTestProperties, nsXPCDispTestProperties)
OBJECT_ENTRY(CLSID_nsXPCDispTestArrays, nsXPCDispTestArrays)
OBJECT_ENTRY(CLSID_nsXPCDispTestScriptOn, nsXPCDispTestScriptOn)
OBJECT_ENTRY(CLSID_nsXPCDispTestScriptOff, nsXPCDispTestScriptOff)
OBJECT_ENTRY(CLSID_nsXPCDispTestWrappedJS, nsXPCDispTestWrappedJS)
END_OBJECT_MAP()
/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
_Module.Init(ObjectMap, hInstance, &LIBID_IDispatchTestLib);
DisableThreadLibraryCalls(hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH)
_Module.Term();
return TRUE; // ok
}
/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE
STDAPI DllCanUnloadNow(void)
{
return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
return _Module.GetClassObject(rclsid, riid, ppv);
}
/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
// registers object, typelib and all interfaces in typelib
return _Module.RegisterServer(TRUE);
}
/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
return _Module.UnregisterServer(TRUE);
}
#include "nsXPCDispTestWrappedJS.h"

View File

@@ -0,0 +1,9 @@
; XPCIDispatchTest.def : Declares the module parameters.
LIBRARY "XPCIDispatchTest.DLL"
EXPORTS
DllCanUnloadNow @1 PRIVATE
DllGetClassObject @2 PRIVATE
DllRegisterServer @3 PRIVATE
DllUnregisterServer @4 PRIVATE

View File

@@ -0,0 +1,318 @@
# Microsoft Developer Studio Project File - Name="XPCIDispatchTest" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
CFG=XPCIDispatchTest - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "XPCIDispatchTest.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "XPCIDispatchTest.mak" CFG="XPCIDispatchTest - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "XPCIDispatchTest - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "XPCIDispatchTest - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "XPCIDispatchTest - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MTd /W3 /Gm /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /Yu"stdafx.h" /FD /GZ /c
# ADD CPP /nologo /MTd /W4 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /Yu"stdafx.h" /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
# Begin Custom Build - Performing registration
OutDir=.\Debug
TargetPath=.\Debug\XPCIDispatchTest.dll
InputPath=.\Debug\XPCIDispatchTest.dll
SOURCE="$(InputPath)"
"$(OutDir)\regsvr32.trg" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
regsvr32 /s /c "$(TargetPath)"
echo regsvr32 exec. time > "$(OutDir)\regsvr32.trg"
# End Custom Build
!ELSEIF "$(CFG)" == "XPCIDispatchTest - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "XPCIDispatchTest___Win32_Release"
# PROP BASE Intermediate_Dir "XPCIDispatchTest___Win32_Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MT /W3 /O1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "_ATL_DLL" /D "_ATL_MIN_CRT" /Yu"stdafx.h" /FD /c
# ADD CPP /nologo /MT /W3 /GX /O1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "_ATL_DLL" /D "_ATL_MIN_CRT" /Yu"stdafx.h" /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
# Begin Custom Build - Performing registration
OutDir=.\Release
TargetPath=.\Release\XPCIDispatchTest.dll
InputPath=.\Release\XPCIDispatchTest.dll
SOURCE="$(InputPath)"
"$(OutDir)\regsvr32.trg" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
regsvr32 /s /c "$(TargetPath)"
echo regsvr32 exec. time > "$(OutDir)\regsvr32.trg"
# End Custom Build
!ENDIF
# Begin Target
# Name "XPCIDispatchTest - Win32 Debug"
# Name "XPCIDispatchTest - Win32 Release"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\nsXPCDispSimple.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestArrays.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestMethods.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestNoIDispatch.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestProperties.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOff.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOn.cpp
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestWrappedJS.cpp
# End Source File
# Begin Source File
SOURCE=.\StdAfx.cpp
# ADD CPP /Yc"stdafx.h"
# End Source File
# Begin Source File
SOURCE=.\XPCIDispatchTest.cpp
# End Source File
# Begin Source File
SOURCE=.\XPCIDispatchTest.def
# End Source File
# Begin Source File
SOURCE=.\XPCIDispatchTest.idl
# ADD MTL /tlb ".\XPCIDispatchTest.tlb" /h "XPCIDispatchTest.h" /iid "XPCIDispatchTest_i.c" /Oicf
# End Source File
# Begin Source File
SOURCE=.\XPCIDispatchTest.rc
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\nsXPCDispSimple.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestArrays.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestMethods.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestNoIDispatch.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestProperties.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOff.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOn.h
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestWrappedJS.h
# End Source File
# Begin Source File
SOURCE=.\Resource.h
# End Source File
# Begin Source File
SOURCE=.\StdAfx.h
# End Source File
# Begin Source File
SOURCE=.\XPCDispUtilities.h
# End Source File
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# Begin Source File
SOURCE=.\nsXPCDispSimple.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestArrays.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestMethods.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestNoIDispatch.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestNoScript.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestProperties.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOff.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestScriptOn.rgs
# End Source File
# Begin Source File
SOURCE=.\nsXPCDispTestWrappedJS.rgs
# End Source File
# End Group
# Begin Group "JS Files"
# PROP Default_Filter "js"
# Begin Group "WrappedCOM"
# PROP Default_Filter ""
# Begin Group "Arrays"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\Tests\WrappedCOM\Arrays\XPCIDispatchArrayTests.js
# End Source File
# End Group
# Begin Group "Attributes"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\Tests\WrappedCOM\Attributes\XPCIDispatchAttributeTests.js
# End Source File
# End Group
# Begin Group "General"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\Tests\WrappedCOM\General\XPCIDispatchInstantiations.js
# End Source File
# Begin Source File
SOURCE=..\Tests\WrappedCOM\General\XPCStress.js
# End Source File
# End Group
# Begin Group "Methods"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\Tests\WrappedCOM\Methods\XPCIDispatchMethodTests.js
# End Source File
# End Group
# Begin Source File
SOURCE=..\Tests\WrappedCOM\shell.js
# End Source File
# End Group
# Begin Group "WrappedJS"
# PROP Default_Filter ""
# Begin Group "General (WJS)"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\Tests\WrappedJS\General\XPCIDispatchTestWrappedJS.js
# End Source File
# End Group
# Begin Source File
SOURCE=..\Tests\WrappedJS\shell.js
# End Source File
# End Group
# End Group
# End Target
# End Project

View File

@@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "XPCIDispatchTest"=.\XPCIDispatchTest.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -0,0 +1,454 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// XPCIDispatchTest.idl : IDL source for XPCIDispatchTest.dll
//
// This file will be processed by the MIDL tool to
// produce the type library (XPCIDispatchTest.tlb) and marshalling code.
import "oaidl.idl";
import "ocidl.idl";
import "objsafe.idl";
[
uuid(83A51226-F49D-488A-8F78-75BB2F927F4C),
version(1.0),
helpstring("XPCIDispatchTest 1.0 Type Library")
]
library IDispatchTestLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
[
object,
uuid(0de5dbae-1d78-45cb-91a2-24516fef2837),
dual,
helpstring("nsIXPCDispSimple interface"),
pointer_default(unique)
]
interface nsIXPCDispSimple : IDispatch
{
[id(1), helpstring("Simple method returning the name of the class")]
HRESULT ClassName([out]BSTR * name);
[propget, id(2), helpstring("Simple number property")]
HRESULT Number([out, retval]long * result);
[propput, id(2), helpstring("Simple number property")]
HRESULT Number([in]long result);
}
[
uuid(9F39237C-D179-4260-8EF3-4B6D4D7D5570),
helpstring("nsXPCDispSimple Class")
]
coclass nsXPCDispSimple
{
[default] interface nsIXPCDispSimple;
};
[
object,
uuid(47bf6c99-a30c-4105-8af6-de76dcfdd6dd),
dual,
helpstring("nsIXPCDispTestMethods interface"),
pointer_default(unique)
]
interface nsIXPCDispTestMethods : IDispatch
{
/* Return values test */
[id(1), helpstring("method with no parameters")]
HRESULT NoParameters();
[id(2), helpstring("method that returns a string")]
HRESULT ReturnBSTR([out, retval]BSTR * result);
[id(3), helpstring("method that returns a 32 bit signed integer")]
HRESULT ReturnI4([out, retval]int * result);
[id(4), helpstring("method that returns an 8 bit unsigned integer")]
HRESULT ReturnUI1([out, retval]unsigned char * result);
[id(5), helpstring("method that returns a 16 bit signed integer")]
HRESULT ReturnI2([out, retval]short * result);
[id(6), helpstring("method that returns a 32 bit floating point number")]
HRESULT ReturnR4([out, retval]float * result);
[id(7), helpstring("method that returns a 64 bit floating point number")]
HRESULT ReturnR8([out, retval]double * result);
[id(8), helpstring("method that returns a boolean")]
HRESULT ReturnBool([out, retval]VARIANT_BOOL * result);
[id(9), helpstring("method that returns an IDispatch pointer")]
HRESULT ReturnIDispatch([out, retval]IDispatch ** result);
[id(10), helpstring("method that returns an error")]
HRESULT ReturnError([out, retval]SCODE * result);
[id(12), helpstring("method that returns a date")]
HRESULT ReturnDate([out, retval]DATE * result);
[id(13), helpstring("method that returns an IUnknown")]
HRESULT ReturnIUnknown([out, retval]IUnknown ** result);
[id(14), helpstring("method that returns a signed 8 bit integer")]
HRESULT ReturnI1([out, retval]char * result);
[id(15), helpstring("method that returns an unsigned 16 bit integer")]
HRESULT ReturnUI2([out, retval]unsigned short * result);
[id(16), helpstring("method that returns an unsigned 32 bit integer")]
HRESULT ReturnUI4([out, retval]unsigned long * result);
[id(17), helpstring("method that returns an integer")]
HRESULT ReturnInt([out, retval]int * result);
[id(18), helpstring("method that returns an unsigned integer")]
HRESULT ReturnUInt([out, retval]unsigned int * result);
/* Single input parameter tests */
[id(19), helpstring("method that takes a string")]
HRESULT TakesBSTR([in]BSTR result);
[id(20), helpstring("method that takes a 32 bit signed integer")]
HRESULT TakesI4([in]int result);
[id(21), helpstring("method that takes an 8 bit unsigned integer")]
HRESULT TakesUI1([in]unsigned char result);
[id(22), helpstring("method that takes a 16 bit signed integer")]
HRESULT TakesI2([in]short result);
[id(23), helpstring("method that takes a 32 bit floating point number")]
HRESULT TakesR4([in]float result);
[id(24), helpstring("method that takes a 64 bit floating point number")]
HRESULT TakesR8([in]double result);
[id(25), helpstring("method that takes a boolean")]
HRESULT TakesBool([in]VARIANT_BOOL result);
[id(26), helpstring("method that takes an IDispatch pointer")]
HRESULT TakesIDispatch([in]IDispatch * result);
[id(27), helpstring("method that takes an error")]
HRESULT TakesError([in]SCODE result);
[id(29), helpstring("method that takes a date")]
HRESULT TakesDate([in]DATE result);
[id(30), helpstring("method that takes an IUnknown")]
HRESULT TakesIUnknown([in]IUnknown * result);
[id(31), helpstring("method that takes a signed 8 bit integer")]
HRESULT TakesI1([in]char result);
[id(32), helpstring("method that takes an unsigned 16 bit integer")]
HRESULT TakesUI2([in]unsigned short result);
[id(33), helpstring("method that takes an unsigned 32 bit integer")]
HRESULT TakesUI4([in]unsigned long result);
[id(34), helpstring("method that takes an integer")]
HRESULT TakesInt([in]int result);
[id(35), helpstring("method that takes an unsigned integer")]
HRESULT TakesUInt([in]unsigned int result);
/* output parameter tests */
[id(36), helpstring("method that outputs a string")]
HRESULT OutputsBSTR([out]BSTR * result);
[id(37), helpstring("method that outputs a 32 bit signed integer")]
HRESULT OutputsI4([out]long * result);
[id(38), helpstring("method that outputs an 8 bit unsigned integer")]
HRESULT OutputsUI1([out]unsigned char * result);
[id(39), helpstring("method that outputs a 16 bit signed integer")]
HRESULT OutputsI2([out]short * result);
[id(40), helpstring("method that outputs a 32 bit floating point number")]
HRESULT OutputsR4([out]float * result);
[id(41), helpstring("method that outputs a 64 bit floating point number")]
HRESULT OutputsR8([out]double * result);
[id(42), helpstring("method that outputs a boolean")]
HRESULT OutputsBool([out]VARIANT_BOOL * result);
[id(43), helpstring("method that outputs an IDispatch pointer")]
HRESULT OutputsIDispatch([out]IDispatch ** result);
[id(44), helpstring("method that outputs an error")]
HRESULT OutputsError([out]SCODE * result);
[id(46), helpstring("method that outputs a date")]
HRESULT OutputsDate([out]DATE * result);
[id(47), helpstring("method that outputs an IUnknown")]
HRESULT OutputsIUnknown([out]IUnknown ** result);
[id(48), helpstring("method that outputs a signed 8 bit integer")]
HRESULT OutputsI1([out]char * result);
[id(49), helpstring("method that outputs an unsigned 16 bit integer")]
HRESULT OutputsUI2([out]unsigned short * result);
[id(50), helpstring("method that outputs an unsigned 32 bit integer")]
HRESULT OutputsUI4([out]unsigned long * result);
/* in/outparameter tests */
[id(53), helpstring("method that in/outs a string")]
HRESULT InOutsBSTR([in, out]BSTR * result);
[id(54), helpstring("method that in/outs a 32 bit signed integer")]
HRESULT InOutsI4([in, out]long * result);
[id(55), helpstring("method that in/outs an 8 bit unsigned integer")]
HRESULT InOutsUI1([in, out]unsigned char * result);
[id(56), helpstring("method that in/outs a 16 bit signed integer")]
HRESULT InOutsI2([in, out]short * result);
[id(57), helpstring("method that in/outs a 32 bit floating point number")]
HRESULT InOutsR4([in, out]float * result);
[id(58), helpstring("method that in/outs a 64 bit floating point number")]
HRESULT InOutsR8([in, out]double * result);
[id(59), helpstring("method that in/outs a boolean")]
HRESULT InOutsBool([in, out]VARIANT_BOOL * result);
[id(60), helpstring("method that in/outs an IDispatch pointer")]
HRESULT InOutsIDispatch([in, out]IDispatch ** result);
[id(61), helpstring("method that in/outs an error")]
HRESULT InOutsError([in, out]SCODE * result);
[id(63), helpstring("method that in/outs a date")]
HRESULT InOutsDate([in, out]DATE * result);
[id(64), helpstring("method that in/outs an IUnknown")]
HRESULT InOutsIUnknown([in, out]IUnknown ** result);
[id(65), helpstring("method that in/outs a signed 8 bit integer")]
HRESULT InOutsI1([in, out]char * result);
[id(66), helpstring("method that in/outs an unsigned 16 bit integer")]
HRESULT InOutsUI2([in, out]unsigned short * result);
[id(67), helpstring("method that in/outs an unsigned 32 bit integer")]
HRESULT InOutsUI4([in, out]unsigned long * result);
/* input and return tests*/
[id(70), helpstring("method that takes an long and returns it")]
HRESULT OneParameterWithReturn([in]long input, [out,retval]long* result);
[id(71), helpstring("method that takes a string and returns it")]
HRESULT StringInputAndReturn([in]BSTR str, [out, retval]BSTR* result);
[id(72), helpstring("method that takes an IDispatch and returns it")]
HRESULT IDispatchInputAndReturn([in]IDispatch* input, [out,retval]IDispatch** result);
/* Multiple parameters */
[id(73), helpstring("method that takes two parameters")]
HRESULT TwoParameters([in]long one, [in]long two);
[id(74), helpstring("method that takes 12 input parameters")]
HRESULT TwelveInParameters([in]long one, [in]long two, [in]long three,
[in]long four, [in]long five, [in]long six,
[in]long seven, [in]long eight,
[in]long nine, [in]long ten,
[in]long eleven, [in]long twelve);
[id(75), helpstring("method that takes 12 out parameters")]
HRESULT TwelveOutParameters([out]long *one, [out]long *two,
[out]long *three, [out]long *four,
[out]long *five, [out]long *six,
[out]long *seven, [out]long *eight,
[out]long *nine, [out]long *ten,
[out]long *eleven, [out]long *twelve);
[id(76), helpstring("method that takes 12 input string parameters")]
HRESULT TwelveStrings([in]BSTR one, [in]BSTR two, [in]BSTR three,
[in]BSTR four, [in]BSTR five, [in]BSTR six,
[in]BSTR seven, [in]BSTR eight, [in]BSTR nine,
[in]BSTR ten, [in]BSTR eleven, [in]BSTR twelve);
[id(77), helpstring("method that takes 12 input string parameters")]
HRESULT TwelveOutStrings([out]BSTR* one, [out]BSTR* two,
[out]BSTR* three, [out]BSTR* four,
[out]BSTR* five, [out]BSTR* six,
[out]BSTR* seven, [out]BSTR* eight,
[out]BSTR* nine, [out]BSTR* ten,
[out]BSTR* eleven, [out]BSTR* twelve);
[id(78), helpstring("method that takes 12 input string parameters")]
HRESULT TwelveIDispatch([in]IDispatch* one, [in]IDispatch* two,
[in]IDispatch* three, [in]IDispatch* four,
[in]IDispatch* five, [in]IDispatch* six,
[in]IDispatch* seven, [in]IDispatch* eight,
[in]IDispatch* nine, [in]IDispatch* ten,
[in]IDispatch* eleven,
[in]IDispatch* twelve);
[id(79), helpstring("method that takes 12 input string parameters")]
HRESULT TwelveOutIDispatch([out]IDispatch** one,
[out]IDispatch** two,
[out]IDispatch** three,
[out]IDispatch** four,
[out]IDispatch** five,
[out]IDispatch** six,
[out]IDispatch** seven,
[out]IDispatch** eight,
[out]IDispatch** nine,
[out]IDispatch** ten,
[out]IDispatch** eleven,
[out]IDispatch** twelve);
[id(80), helpstring("method that generates an error")]
HRESULT CreateError();
}
[
uuid(745D1149-9F46-418C-B176-71EAA98974BA),
helpstring("nsXPCDispTestMethods Class")
]
coclass nsXPCDispTestMethods
{
[default] interface nsIXPCDispTestMethods;
};
[
object,
uuid(f876c083-ae00-4b78-93b8-8305980f0864),
dual,
helpstring("nsIXPCDispTestArrays interface"),
pointer_default(unique)
]
interface nsIXPCDispTestArrays : IDispatch
{
[id(1), helpstring("returns a SAFEARRAY")]
HRESULT ReturnSafeArray([out, retval]SAFEARRAY(VARIANT)* result);
[id(2), helpstring("returns a SAFEARRAY")]
HRESULT ReturnSafeArrayBSTR([out, retval]SAFEARRAY(VARIANT)* result);
[id(3), helpstring("returns a SAFEARRAY")]
HRESULT ReturnSafeArrayIDispatch([out, retval]SAFEARRAY(VARIANT)* result);
[id(4), helpstring("method that takes a SAFEARRAY")]
HRESULT TakesSafeArray([in]SAFEARRAY(VARIANT) array);
[id(5), helpstring("method that takes a SAFEARRAY")]
HRESULT TakesSafeArrayBSTR([in]SAFEARRAY(VARIANT) array);
[id(6), helpstring("method that takes a SAFEARRAY")]
HRESULT TakesSafeArrayIDispatch([in]SAFEARRAY(VARIANT) array);
[id(7), helpstring("method that takes a SAFEARRAY")]
HRESULT InOutSafeArray([in, out]SAFEARRAY(VARIANT) * array);
[id(8), helpstring("method that takes a SAFEARRAY")]
HRESULT InOutSafeArrayBSTR([in, out]SAFEARRAY(VARIANT) * array);
[id(9), helpstring("method that takes a SAFEARRAY")]
HRESULT InOutSafeArrayIDispatch([in, out]SAFEARRAY(VARIANT) * array);
}
[
uuid(AB085C43-C619-48C8-B68C-C495BDE12DFB),
helpstring("nsXPCDispTestArrays Class")
]
coclass nsXPCDispTestArrays
{
[default] interface nsIXPCDispTestArrays;
};
[
object,
uuid(9782107f-14cc-40b2-b0cd-988d81a46e9e),
dual,
helpstring("nsIXPCDispTestNoIDispatch interface"),
pointer_default(unique)
]
interface nsIXPCDispTestNoIDispatch : IUnknown
{
}
[
uuid(7414404F-A4CC-4E3C-9B32-BB20CB22F541),
helpstring("nsXPCDispTestNoIDispatch Class")
]
coclass nsXPCDispTestNoIDispatch
{
[default] interface nsIXPCDispTestNoIDispatch;
};
[
object,
uuid(7830CACE-5019-489D-8B69-029E70CF39B7),
dual,
helpstring("nsIXPCDispTestProperties Interface"),
pointer_default(unique)
]
interface nsIXPCDispTestProperties : IDispatch
{
[propget, id(1), helpstring("property Short")] HRESULT Short([out, retval] short *pVal);
[propput, id(1), helpstring("property Short")] HRESULT Short([in] short newVal);
[propget, id(2), helpstring("property Long")] HRESULT Long([out, retval] long *pVal);
[propput, id(2), helpstring("property Long")] HRESULT Long([in] long newVal);
[propget, id(3), helpstring("property Float")] HRESULT Float([out, retval] float *pVal);
[propput, id(3), helpstring("property Float")] HRESULT Float([in] float newVal);
[propget, id(4), helpstring("property Double")] HRESULT Double([out, retval] double *pVal);
[propput, id(4), helpstring("property Double")] HRESULT Double([in] double newVal);
[propget, id(5), helpstring("property Currency")] HRESULT Currency([out, retval] CURRENCY *pVal);
[propput, id(5), helpstring("property Currency")] HRESULT Currency([in] CURRENCY newVal);
[propget, id(6), helpstring("property Date")] HRESULT Date([out, retval] DATE *pVal);
[propput, id(6), helpstring("property Date")] HRESULT Date([in] DATE newVal);
[propget, id(7), helpstring("property String")] HRESULT String([out, retval] BSTR *pVal);
[propput, id(7), helpstring("property String")] HRESULT String([in] BSTR newVal);
[propget, id(8), helpstring("property DispatchPtr")] HRESULT DispatchPtr([out, retval] IDispatch* *pVal);
[propput, id(8), helpstring("property DispatchPtr")] HRESULT DispatchPtr([in] IDispatch* newVal);
[propget, id(9), helpstring("property SCode")] HRESULT SCode([out, retval] SCODE *pVal);
[propput, id(9), helpstring("property SCode")] HRESULT SCode([in] SCODE newVal);
[propget, id(10), helpstring("property Boolean")] HRESULT Boolean([out, retval] BOOL *pVal);
[propput, id(10), helpstring("property Boolean")] HRESULT Boolean([in] BOOL newVal);
[propget, id(11), helpstring("property Variant")] HRESULT Variant([out, retval] VARIANT *pVal);
[propput, id(11), helpstring("property Variant")] HRESULT Variant([in] VARIANT newVal);
[propget, id(12), helpstring("property COMPtr")] HRESULT COMPtr([out, retval] IUnknown* *pVal);
[propput, id(12), helpstring("property COMPtr")] HRESULT COMPtr([in] IUnknown* newVal);
[propget, id(13), helpstring("property Char")] HRESULT Char([out, retval] unsigned char *pVal);
[propput, id(13), helpstring("property Char")] HRESULT Char([in] unsigned char newVal);
[propget, id(14), helpstring("property ParameterizedProperty")] HRESULT ParameterizedProperty([in]long aIndex, [out, retval] long *pVal);
[propput, id(14), helpstring("property ParameterizedProperty")] HRESULT ParameterizedProperty([in]long aIndex, [in] long newVal);
[propget, id(15), helpstring("property ParameterizedPropertyCount")] HRESULT ParameterizedPropertyCount([out, retval] long *pVal);
};
[
object,
uuid(0797788A-CB08-4995-BD45-7BF8C468DE21),
dual,
helpstring("nsIXPCDispTestScriptOn Interface"),
pointer_default(unique)
]
interface nsIXPCDispTestScriptOn : IDispatch
{
};
[
uuid(2A06373F-3E61-4882-A3D7-A104F70B09ED),
helpstring("nsXPCDispTestScriptOn Class")
]
coclass nsXPCDispTestScriptOn
{
[default] interface nsIXPCDispTestScriptOn;
};
[
object,
uuid(EE6F9DB5-890F-422D-B9DC-9C5AB5A1D654),
dual,
helpstring("nsIXPCDispTestScriptOff Interface"),
pointer_default(unique)
]
interface nsIXPCDispTestScriptOff : IDispatch
{
};
[
object,
uuid(D84352CA-1A01-4E72-9072-77AFA669B3AD),
dual,
helpstring("nsIXPCDispTestWrappedJS Interface"),
pointer_default(unique)
]
interface nsIXPCDispTestWrappedJS : IDispatch
{
[id(1), helpstring("method TestParamTypes")] HRESULT TestParamTypes([in] IDispatch * obj, [out, retval]BSTR * errMsg);
};
[
uuid(EAEE6BB2-C005-4B91-BCA7-6613236F6F69),
helpstring("nsXPCDispTestWrappedJS Class")
]
coclass nsXPCDispTestWrappedJS
{
[default] interface nsIXPCDispTestWrappedJS;
};
[
uuid(959CD122-9826-4757-BA09-DE327D55F9E7),
helpstring("nsXPCDispTestScriptOff Class")
]
coclass nsXPCDispTestScriptOff
{
[default] interface nsIXPCDispTestScriptOff;
};
[
uuid(D8B4265B-1768-4CA9-A285-7CCAEEB51C74),
helpstring("nsXPCDispTestProperties Class")
]
coclass nsXPCDispTestProperties
{
[default] interface nsIXPCDispTestProperties;
};
};

View File

@@ -0,0 +1,145 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"1 TYPELIB ""XPCIDispatchTest.tlb""\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "CompanyName", "\0"
VALUE "FileDescription", "XPCIDispatchTest Module\0"
VALUE "FileVersion", "1, 0, 0, 1\0"
VALUE "InternalName", "XPCIDispatchTest\0"
VALUE "LegalCopyright", "Copyright 2002\0"
VALUE "OriginalFilename", "XPCIDispatchTest.DLL\0"
VALUE "ProductName", "XPCIDispatchTest Module\0"
VALUE "ProductVersion", "1, 0, 0, 1\0"
VALUE "OLESelfRegister", "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
#endif // !_MAC
/////////////////////////////////////////////////////////////////////////////
//
// REGISTRY
//
IDR_nsXPCDispTestMethods REGISTRY DISCARDABLE "nsXPCDispTestMethods.rgs"
IDR_nsXPCDispSimple REGISTRY DISCARDABLE "nsXPCDispSimple.rgs"
IDR_nsXPCDispTestNoIDispatch REGISTRY DISCARDABLE "nsXPCDispTestNoIDispatch.rgs"
IDR_nsXPCDispTestProperties REGISTRY DISCARDABLE "nsXPCDispTestProperties.rgs"
IDR_nsXPCDispTestArrays REGISTRY DISCARDABLE "nsXPCDispTestArrays.rgs"
IDR_nsXPCDispTestScriptOn REGISTRY DISCARDABLE "nsXPCDispTestScriptOn.rgs"
IDR_nsXPCDispTestScriptOff REGISTRY DISCARDABLE "nsXPCDispTestScriptOff.rgs"
IDR_nsXPCDispTestWrappedJS REGISTRY DISCARDABLE "nsXPCDispTestWrappedJS.rgs"
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE DISCARDABLE
BEGIN
IDS_PROJNAME "XPCIDispatchTest"
IDS_NSXPCDISPTTESTMETHODS_DESC "nsXPCDisptTestMethods Class"
IDS_NSXPCDISPTESTMETHODS_DESC "nsXPCDispTestMethods Class"
IDS_NSXPCDISPSIMPLE_DESC "nsXPCDispSimple Class"
IDS_NSXPCDISPTESTNOIDISPATCH_DESC "nsXPCDispTestNoIDispatch Class"
IDS_NSXPCDISPTESTNOSCRIPT_DESC "nsXPCDispTestNoScript Class"
IDS_NSXPCDISPTESTPROPERTIES_DESC "nsXPCDispTestProperties Class"
END
STRINGTABLE DISCARDABLE
BEGIN
IDS_NSXPCDISPTESTARRAYS_DESC "nsXPCDispTestArrays Class"
IDS_NSXPCDISPTESTSCRIPTON_DESC "nsXPCDispTestScriptOn Class"
IDS_NSXPCDISPTESTSCRIPTOFF_DESC "nsXPCDispTestScriptOff Class"
IDS_NSXPCDISPTESTWRAPPEDJS_DESC "nsXPCDispTestWrappedJS Class"
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
1 TYPELIB "XPCIDispatchTest.tlb"
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -0,0 +1,44 @@
// nsXPCDispSimple.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispSimple.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispSimple::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispSimple,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP nsXPCDispSimple::ClassName(BSTR * name)
{
if (name == NULL)
return E_POINTER;
CComBSTR x("nsXPCDispSimple");
*name = x.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispSimple::get_Number(LONG * result)
{
if (result == NULL)
return E_POINTER;
*result = mNumber;
return S_OK;
}
STDMETHODIMP nsXPCDispSimple::put_Number(LONG result)
{
mNumber = result;
return S_OK;
}

View File

@@ -0,0 +1,56 @@
// nsXPCDispSimple.h: Definition of the nsXPCDispSimple class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPSIMPLE_H__5502A675_46D9_4762_A7F9_1A023A052152__INCLUDED_)
#define AFX_NSXPCDISPSIMPLE_H__5502A675_46D9_4762_A7F9_1A023A052152__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispSimple
class nsXPCDispSimple :
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispSimple,&CLSID_nsXPCDispSimple>,
public IDispatchImpl<nsIXPCDispSimple, &IID_nsIXPCDispSimple, &LIBID_IDispatchTestLib>
{
public:
nsXPCDispSimple() : mNumber(5) {}
BEGIN_CATEGORY_MAP(nsXPCDispSimple)
IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
END_CATEGORY_MAP()
BEGIN_COM_MAP(nsXPCDispSimple)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(nsIXPCDispSimple)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispSimple)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispSimple)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispSimple
public:
// nsIXPCDispSimple
STDMETHOD(ClassName)(BSTR * name);
STDMETHOD(get_Number)(LONG * result);
STDMETHOD(put_Number)(LONG result);
template <class T>
static HRESULT CreateInstance(T ** result)
{
return CoCreateInstance(CLSID_nsXPCDispSimple, 0, CLSCTX_ALL,
__uuidof(T),
reinterpret_cast<void**>(result));
}
private:
long mNumber;
};
#endif // !defined(AFX_NSXPCDISPSIMPLE_H__5502A675_46D9_4762_A7F9_1A023A052152__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispSimple.1 = s 'nsXPCDispSimple Class'
{
CLSID = s '{9F39237C-D179-4260-8EF3-4B6D4D7D5570}'
}
XPCIDispatchTest.nsXPCDispSimple = s 'nsXPCDispSimple Class'
{
CLSID = s '{9F39237C-D179-4260-8EF3-4B6D4D7D5570}'
}
NoRemove CLSID
{
ForceRemove {9F39237C-D179-4260-8EF3-4B6D4D7D5570} = s 'nsXPCDispSimple Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispSimple.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispSimple'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,221 @@
// nsXPCDispTestArrays.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestArrays.h"
unsigned int zero = 0;
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestArrays::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestArrays,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP nsXPCDispTestArrays::ReturnSafeArray(LPSAFEARRAY * result)
{
if (result == NULL)
return E_POINTER;
*result = SafeArrayCreateVector(VT_I4, 0, 3);
for (long index = 0; index < 3; ++index)
{
SafeArrayPutElement(*result, &index, &index);
}
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::ReturnSafeArrayBSTR(LPSAFEARRAY * result)
{
if (result == NULL)
return E_POINTER;
*result = SafeArrayCreateVector(VT_BSTR, 0, 3);
for (long index = 0; index < 3; ++index)
{
_variant_t var(index);
HRESULT hr = VariantChangeType(&var, &var, VARIANT_ALPHABOOL, VT_BSTR);
if (FAILED(hr))
return hr;
SafeArrayPutElement(*result, &index, var.bstrVal);
}
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::ReturnSafeArrayIDispatch(LPSAFEARRAY * result)
{
if (result == NULL)
return E_POINTER;
*result = SafeArrayCreateVector(VT_DISPATCH, 0, 3);
for (long index = 0; index < 3; ++index)
{
CComPtr<nsIXPCDispSimple> ptr;
ptr.CoCreateInstance(CLSID_nsXPCDispSimple);
SafeArrayPutElement(*result, &index, ptr.p);
}
return S_OK;
}
#define RETURN_IF_FAIL(x) hr = x; if (FAILED(hr)) return hr;
STDMETHODIMP nsXPCDispTestArrays::TakesSafeArray(LPSAFEARRAY array)
{
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(array, 1, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(array, 1, &ubound));
if (ubound != 3)
return E_FAIL;
for (long index = lbound; index <= ubound; ++index)
{
_variant_t value;
RETURN_IF_FAIL(SafeArrayGetElement(array, &index, &value));
if (value != _variant_t(index))
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::TakesSafeArrayBSTR(LPSAFEARRAY array)
{
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(array, 1, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(array, 1, &ubound));
if (ubound != 3)
return E_FAIL;
for (long index = lbound; index <= ubound; ++index)
{
_variant_t value;
RETURN_IF_FAIL(SafeArrayGetElement(array, &index, &value));
_variant_t test(index);
if (_bstr_t(value) != _bstr_t(test))
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::TakesSafeArrayIDispatch(LPSAFEARRAY array)
{
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(array, 0, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(array, 0, &ubound));
if (ubound != 3)
return E_FAIL;
for (long index = lbound; index <= ubound; ++index)
{
_variant_t value;
RETURN_IF_FAIL(SafeArrayGetElement(array, &index, &value));
// We need to do more here, but this is good enough for now
if (!value.pdispVal)
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::InOutSafeArray(LPSAFEARRAY * array)
{
if (array == NULL)
return E_POINTER;
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(*array, 0, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(*array, 0, &ubound));
if (ubound != 3)
return E_FAIL;
LPSAFEARRAY newArray = SafeArrayCreateVector(VT_I4, lbound, ubound);
for (long index = lbound; index <= ubound; ++index)
{
long value;
RETURN_IF_FAIL(SafeArrayGetElement(*array, &index, &value));
if (value != index)
return E_FAIL;
value += 42;
RETURN_IF_FAIL(SafeArrayPutElement(newArray, &index, &value));
}
SafeArrayDestroy(*array);
*array = newArray;
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::InOutSafeArrayBSTR(LPSAFEARRAY * array)
{
if (array == NULL)
return E_POINTER;
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(*array, 0, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(*array, 0, &ubound));
if (ubound != 3)
return E_FAIL;
LPSAFEARRAY newArray = SafeArrayCreateVector(VT_BSTR, lbound, ubound);
for (long index = lbound; index <= ubound; ++index)
{
BSTR value;
RETURN_IF_FAIL(SafeArrayGetElement(*array, &index, &value));
_bstr_t newValue(value, TRUE);
newValue += L"Appended";
RETURN_IF_FAIL(SafeArrayPutElement(newArray, &index, newValue.copy()));
}
SafeArrayDestroy(*array);
*array = newArray;
return S_OK;
}
STDMETHODIMP nsXPCDispTestArrays::InOutSafeArrayIDispatch(LPSAFEARRAY * array)
{
if (array == NULL)
return E_POINTER;
long lbound;
long ubound;
HRESULT hr;
RETURN_IF_FAIL(SafeArrayGetLBound(*array, 0, &lbound));
if (lbound != 0)
return E_FAIL;
RETURN_IF_FAIL(SafeArrayGetUBound(*array, 0, &ubound));
if (ubound != 3)
return E_FAIL;
LPSAFEARRAY newArray = SafeArrayCreateVector(VT_DISPATCH, lbound, ubound);
for (long index = lbound; index <= ubound; ++index)
{
IDispatch* value;
RETURN_IF_FAIL(SafeArrayGetElement(*array, &index, &value));
RETURN_IF_FAIL(SafeArrayPutElement(newArray, &index, &value));
}
SafeArrayDestroy(*array);
*array = newArray;
return S_OK;
}

View File

@@ -0,0 +1,53 @@
// nsXPCDispTestArrays.h: Definition of the nsXPCDispTestArrays class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTARRAYS_H__5F59BD4C_16A4_4BD6_8281_796DE6A2889C__INCLUDED_)
#define AFX_NSXPCDISPTESTARRAYS_H__5F59BD4C_16A4_4BD6_8281_796DE6A2889C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestArrays
class nsXPCDispTestArrays :
public IDispatchImpl<nsIXPCDispTestArrays, &IID_nsIXPCDispTestArrays, &LIBID_IDispatchTestLib>,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestArrays,&CLSID_nsXPCDispTestArrays>
{
public:
nsXPCDispTestArrays() {}
BEGIN_CATEGORY_MAP(nsXPCDispTestArrays)
IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
END_CATEGORY_MAP()
BEGIN_COM_MAP(nsXPCDispTestArrays)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(nsIXPCDispTestArrays)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestArrays)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestArrays)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestArrays
public:
// nsIXPCDispTestArrays
STDMETHOD(ReturnSafeArray)(LPSAFEARRAY * result);
STDMETHOD(ReturnSafeArrayBSTR)(LPSAFEARRAY * result);
STDMETHOD(ReturnSafeArrayIDispatch)(LPSAFEARRAY * result);
STDMETHOD(TakesSafeArray)(LPSAFEARRAY array);
STDMETHOD(TakesSafeArrayBSTR)(LPSAFEARRAY array);
STDMETHOD(TakesSafeArrayIDispatch)(LPSAFEARRAY array);
STDMETHOD(InOutSafeArray)(LPSAFEARRAY * array);
STDMETHOD(InOutSafeArrayBSTR)(LPSAFEARRAY * array);
STDMETHOD(InOutSafeArrayIDispatch)(LPSAFEARRAY * array);
};
#endif // !defined(AFX_NSXPCDISPTESTARRAYS_H__5F59BD4C_16A4_4BD6_8281_796DE6A2889C__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestArrays.1 = s 'nsXPCDispTestArrays Class'
{
CLSID = s '{AB085C43-C619-48C8-B68C-C495BDE12DFB}'
}
XPCIDispatchTest.nsXPCDispTestArrays = s 'nsXPCDispTestArrays Class'
{
CLSID = s '{AB085C43-C619-48C8-B68C-C495BDE12DFB}'
}
NoRemove CLSID
{
ForceRemove {AB085C43-C619-48C8-B68C-C495BDE12DFB} = s 'nsXPCDispTestArrays Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestArrays.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestArrays'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,699 @@
// nsXPCDispTestMethods.cpp : Implementation of CIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestMethods.h"
#include "XPCDispUtilities.h"
#include "nsXPCDispSimple.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestMethods::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestMethods,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP nsXPCDispTestMethods::NoParameters()
{
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnBSTR(BSTR * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR x("Boo");
*result = x.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnI4(INT * result)
{
if (result == NULL)
return E_POINTER;
*result = 99999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnUI1(BYTE * result)
{
if (result == NULL)
return E_POINTER;
*result = 99;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnI2(SHORT * result)
{
if (result == NULL)
return E_POINTER;
*result = 9999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnR4(FLOAT * result)
{
if (result == NULL)
return E_POINTER;
*result = 99999.1f;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnR8(DOUBLE * result)
{
if (result == NULL)
return E_POINTER;
*result = 99999999999.99;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnBool(VARIANT_BOOL * result)
{
if (result == NULL)
return E_POINTER;
*result = VARIANT_TRUE;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnIDispatch(IDispatch * * result)
{
if (result == NULL)
return E_POINTER;
return nsXPCDispSimple::CreateInstance(result);
}
STDMETHODIMP nsXPCDispTestMethods::ReturnError(SCODE * result)
{
if (result == NULL)
return E_POINTER;
*result = E_FAIL;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnDate(DATE * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR dateStr(L"5/2/02");
return VarDateFromStr(dateStr, LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE, result);
}
STDMETHODIMP nsXPCDispTestMethods::ReturnIUnknown(IUnknown * * result)
{
if (result == NULL)
return E_POINTER;
return XPCCreateInstance<IUnknown>(CLSID_nsXPCDispTestNoIDispatch, IID_IUnknown, result);
}
STDMETHODIMP nsXPCDispTestMethods::ReturnI1(unsigned char * result)
{
if (result == NULL)
return E_POINTER;
*result = 120;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnUI2(USHORT * result)
{
if (result == NULL)
return E_POINTER;
*result = 9999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnUI4(ULONG * result)
{
if (result == NULL)
return E_POINTER;
*result = 3000000000;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnInt(INT * result)
{
if (result == NULL)
return E_POINTER;
*result = -999999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::ReturnUInt(UINT * result)
{
if (result == NULL)
return E_POINTER;
*result = 3000000000;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::TakesBSTR(BSTR result)
{
CComBSTR str(result);
static CComBSTR test(L"TakesBSTR");
return str == test ? S_OK: E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesI4(INT result)
{
return result == 999999 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesUI1(BYTE result)
{
return result == 42 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesI2(SHORT result)
{
return result == 32000 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesR4(FLOAT result)
{
// Hopefully we won't run into any precision/rounding issues
return result == 99999.99f ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesR8(DOUBLE result)
{
// Hopefully we won't run into any precision/rounding issues
return result == 999999999.99 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesBool(VARIANT_BOOL result)
{
return result ? S_OK : E_FAIL;
}
inline
HRESULT GetProperty(IDispatch *pDisp, const CComBSTR & name, CComVariant& output)
{
DISPID dispid = GetIDsOfNames(pDisp, name);
DISPPARAMS dispParams;
dispParams.cArgs = 0;
dispParams.cNamedArgs = 0;
dispParams.rgdispidNamedArgs = 0;
dispParams.rgvarg = 0;
return pDisp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT,DISPATCH_PROPERTYGET, &dispParams, &output, 0, 0);
}
inline
HRESULT PutProperty(IDispatch *pDisp, const CComBSTR & name, const CComVariant& input)
{
DISPPARAMS dispParams;
DISPID did = DISPID_PROPERTYPUT;
dispParams.cArgs = 1;
CComVariant var(input);
dispParams.rgvarg = &var;
dispParams.cNamedArgs = 1;
dispParams.rgdispidNamedArgs = &did;
CComVariant result;
DISPID dispID = GetIDsOfNames(pDisp, name);
return pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT,
DISPATCH_PROPERTYPUT, &dispParams, &result,
0, 0);
}
HRESULT VerifynsXPCDispSimple(IDispatch * result)
{
CComVariant property;
HRESULT hResult = GetProperty(result, L"Number", property);
CComVariant test((long)5);
if (FAILED(hResult))
return hResult;
if (property != test)
return E_FAIL;
return PutProperty(result, L"Number", 76);
}
STDMETHODIMP nsXPCDispTestMethods::TakesIDispatch(IDispatch * result)
{
return VerifynsXPCDispSimple(result);
}
STDMETHODIMP nsXPCDispTestMethods::TakesError(SCODE result)
{
return result == E_FAIL ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesDate(DATE result)
{
CComBSTR dateStr(L"5/2/02");
DATE myDate;
HRESULT hResult = VarDateFromStr(dateStr, LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE, &myDate);
if (SUCCEEDED(hResult))
return myDate == result ? S_OK : E_FAIL;
else
return hResult;
}
STDMETHODIMP nsXPCDispTestMethods::TakesIUnknown(IUnknown * result)
{
CComPtr<IUnknown> ptr(result);
ULONG before = result->AddRef();
ULONG after = result->Release();
CComQIPtr<nsIXPCDispTestNoIDispatch> noIDispatch(ptr);
return before - 1 == after ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesI1(unsigned char result)
{
return result == 42 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesUI2(USHORT result)
{
return result == 50000 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesUI4(ULONG result)
{
return result == 0xF0000000 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesInt(INT result)
{
return result == -10000000 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TakesUInt(UINT result)
{
return result == 0xE0000000 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsBSTR(BSTR * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR x("Boo");
*result = x.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsI4(LONG * result)
{
if (result == NULL)
return E_POINTER;
*result = 99999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsUI1(BYTE * result)
{
if (result == NULL)
return E_POINTER;
*result = 99;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsI2(SHORT * result)
{
if (result == NULL)
return E_POINTER;
*result = 9999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsR4(FLOAT * result)
{
if (result == NULL)
return E_POINTER;
*result = 999999.1f;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsR8(DOUBLE * result)
{
if (result == NULL)
return E_POINTER;
*result = 99999999999.99;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsBool(VARIANT_BOOL * result)
{
if (result == NULL)
return E_POINTER;
*result = VARIANT_TRUE;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsIDispatch(IDispatch * * result)
{
if (result == NULL)
return E_POINTER;
return nsXPCDispSimple::CreateInstance(result);
}
STDMETHODIMP nsXPCDispTestMethods::OutputsError(SCODE * result)
{
if (result == NULL)
return E_POINTER;
*result = E_FAIL;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsDate(DATE * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR dateStr(L"5/2/02");
return VarDateFromStr(dateStr, LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE, result);
}
STDMETHODIMP nsXPCDispTestMethods::OutputsIUnknown(IUnknown * * result)
{
if (result == NULL)
return E_POINTER;
return XPCCreateInstance<IUnknown>(CLSID_nsXPCDispTestNoIDispatch, IID_IUnknown, result);
}
STDMETHODIMP nsXPCDispTestMethods::OutputsI1(unsigned char * result)
{
if (result == NULL)
return E_POINTER;
*result = L'x';
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsUI2(USHORT * result)
{
if (result == NULL)
return E_POINTER;
*result = 9999;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OutputsUI4(ULONG * result)
{
if (result == NULL)
return E_POINTER;
*result = 3000000000;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsBSTR(BSTR * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR str(*result);
str += L"Appended";
SysFreeString(*result);
*result = str.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsI4(LONG * result)
{
if (result == NULL)
return E_POINTER;
*result -= 4000000;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsUI1(BYTE * result)
{
if (result == NULL)
return E_POINTER;
*result -= 42;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsI2(SHORT * result)
{
if (result == NULL)
return E_POINTER;
*result += 10000;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsR4(FLOAT * result)
{
if (result == NULL)
return E_POINTER;
*result += 5.05f;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsR8(DOUBLE * result)
{
if (result == NULL)
return E_POINTER;
*result += 50000000.00000005;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsBool(VARIANT_BOOL * result)
{
if (result == NULL)
return E_POINTER;
*result = !*result;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsIDispatch(IDispatch * * result)
{
if (result == NULL)
return E_POINTER;
CComPtr<nsIXPCDispSimple> ptr;
ptr.CoCreateInstance(CLSID_nsXPCDispSimple);
CComPtr<IDispatch> incoming(*result);
CComVariant value;
HRESULT hResult = GetProperty(incoming, L"Number", value);
if (FAILED(hResult))
return hResult;
if (value.lVal != 10)
return E_FAIL;
hResult = ptr->put_Number(value.lVal + 5);
if (FAILED(hResult))
return hResult;
*result = ptr.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsError(SCODE * result)
{
if (result == NULL)
return E_POINTER;
*result += 1;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsDate(DATE * result)
{
if (result == NULL)
return E_POINTER;
ULONG days;
HRESULT hResult = VarUI4FromDate(*result, &days);
if (FAILED(hResult))
return hResult;
return VarDateFromUI4(days + 1, result);
}
STDMETHODIMP nsXPCDispTestMethods::InOutsIUnknown(IUnknown * * result)
{
if (result == NULL)
return E_POINTER;
CComPtr<IUnknown> ptr(*result);
ULONG before = (*result)->AddRef();
ULONG after = (*result)->Release();
if (before - 1 != after)
return E_FAIL;
return nsXPCDispSimple::CreateInstance(result);
}
STDMETHODIMP nsXPCDispTestMethods::InOutsI1(unsigned char * result)
{
if (result == NULL)
return E_POINTER;
++*result;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsUI2(USHORT * result)
{
if (result == NULL)
return E_POINTER;
*result += 42;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::InOutsUI4(ULONG * result)
{
if (result == NULL)
return E_POINTER;
*result -= 42;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::OneParameterWithReturn(LONG input,
LONG * result)
{
if (result == NULL)
return E_POINTER;
*result = input + 42;
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::StringInputAndReturn(BSTR str,
BSTR * result)
{
if (result == NULL)
return E_POINTER;
CComBSTR input(str);
input += L"Appended";
*result = input.Detach();
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::IDispatchInputAndReturn(IDispatch * input, IDispatch * * result)
{
if (result == NULL)
return E_POINTER;
HRESULT hResult = VerifynsXPCDispSimple(input);
hResult = XPCCreateInstance<IDispatch>(CLSID_nsXPCDispSimple, IID_IDispatch, result);
if (FAILED(hResult))
return hResult;
CComVariant variant;
hResult = GetProperty(input, L"Number", variant);
if (FAILED(hResult))
return hResult;
return PutProperty(*result, L"Number", variant.lVal + 5);
}
STDMETHODIMP nsXPCDispTestMethods::TwoParameters(LONG one, LONG two)
{
return one + 1 == two ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TwelveInParameters(LONG one, LONG two,
LONG three, LONG four,
LONG five, LONG six,
LONG seven, LONG eight,
LONG nine, LONG ten,
LONG eleven, LONG twelve)
{
return one + two + three + four + five + six + seven + eight + nine +
ten + eleven + twelve == 78 ? S_OK : E_FAIL;
}
STDMETHODIMP nsXPCDispTestMethods::TwelveOutParameters(LONG * one, LONG * two,
LONG * three,
LONG * four,
LONG * five, LONG * six,
LONG * seven,
LONG * eight,
LONG * nine, LONG * ten,
LONG * eleven,
LONG * twelve)
{
if (one == 0 || two == 0 || three == 0 || four == 0 ||
five == 0 || six == 0 || seven == 0 || eight == 0 ||
nine == 0 || ten == 0 || eleven == 0 || twelve == 0)
return E_POINTER;
*one = 1;
*two = 2;
*three = 3;
*four = 4;
*five = 5;
*six = 6;
*seven = 7;
*eight = 8;
*nine = 9;
*ten = 10;
*eleven = 11;
*twelve = 12;
return S_OK;
}
inline
boolean Equals(BSTR left, const char * str)
{
return CComBSTR(left) == str;
}
#define TESTPARAM(val) Equals(val, #val)
STDMETHODIMP nsXPCDispTestMethods::TwelveStrings(BSTR one, BSTR two, BSTR three, BSTR four, BSTR five, BSTR six, BSTR seven, BSTR eight, BSTR nine, BSTR ten, BSTR eleven, BSTR twelve)
{
return TESTPARAM(one) && TESTPARAM(two) && TESTPARAM(three) &&
TESTPARAM(four) && TESTPARAM(five) && TESTPARAM(six) &&
TESTPARAM(seven) && TESTPARAM(eight) && TESTPARAM(nine) &&
TESTPARAM(ten) && TESTPARAM(eleven) && TESTPARAM(twelve) ?
S_OK : E_FAIL;
}
#define ASSIGNPARAM(val) \
if (val == 0) \
return E_POINTER; \
*val = CComBSTR(#val).Detach()
STDMETHODIMP nsXPCDispTestMethods::TwelveOutStrings(BSTR * one, BSTR * two, BSTR * three, BSTR * four, BSTR * five, BSTR * six, BSTR * seven, BSTR * eight, BSTR * nine, BSTR * ten, BSTR * eleven, BSTR * twelve)
{
ASSIGNPARAM(one);
ASSIGNPARAM(two);
ASSIGNPARAM(three);
ASSIGNPARAM(four);
ASSIGNPARAM(five);
ASSIGNPARAM(six);
ASSIGNPARAM(seven);
ASSIGNPARAM(eight);
ASSIGNPARAM(nine);
ASSIGNPARAM(ten);
ASSIGNPARAM(eleven);
ASSIGNPARAM(twelve);
return S_OK;
}
#define VERIFYSIMPLE(param) \
hResult = VerifynsXPCDispSimple(param); \
if (FAILED(hResult)) \
return hResult
STDMETHODIMP nsXPCDispTestMethods::TwelveIDispatch(IDispatch * one,
IDispatch * two,
IDispatch * three,
IDispatch * four,
IDispatch * five,
IDispatch * six,
IDispatch * seven,
IDispatch * eight,
IDispatch * nine,
IDispatch * ten,
IDispatch * eleven,
IDispatch * twelve)
{
HRESULT hResult;
VERIFYSIMPLE(one);
VERIFYSIMPLE(two);
VERIFYSIMPLE(three);
VERIFYSIMPLE(four);
VERIFYSIMPLE(five);
VERIFYSIMPLE(six);
VERIFYSIMPLE(seven);
VERIFYSIMPLE(eight);
VERIFYSIMPLE(nine);
VERIFYSIMPLE(ten);
VERIFYSIMPLE(eleven);
VERIFYSIMPLE(twelve);
return S_OK;
}
#define ASSIGNSIMPLE(param) \
if (param == 0) \
return E_POINTER; \
hResult = nsXPCDispSimple::CreateInstance(param); \
if (FAILED(hResult)) \
return hResult; \
STDMETHODIMP nsXPCDispTestMethods::TwelveOutIDispatch(IDispatch * * one,
IDispatch * * two,
IDispatch * * three,
IDispatch * * four,
IDispatch * * five,
IDispatch * * six,
IDispatch * * seven,
IDispatch * * eight,
IDispatch * * nine,
IDispatch * * ten,
IDispatch * * eleven,
IDispatch * * twelve){
HRESULT hResult;
ASSIGNSIMPLE(one);
ASSIGNSIMPLE(two);
ASSIGNSIMPLE(three);
ASSIGNSIMPLE(four);
ASSIGNSIMPLE(five);
ASSIGNSIMPLE(six);
ASSIGNSIMPLE(seven);
ASSIGNSIMPLE(eight);
ASSIGNSIMPLE(nine);
ASSIGNSIMPLE(ten);
ASSIGNSIMPLE(eleven);
ASSIGNSIMPLE(twelve);
return S_OK;
}
STDMETHODIMP nsXPCDispTestMethods::CreateError()
{
CComBSTR someText(L"CreateError Test");
ICreateErrorInfo * pCreateError;
IErrorInfo * pError;
HRESULT result = CreateErrorInfo(&pCreateError);
if (FAILED(result))
return E_NOTIMPL;
result = pCreateError->QueryInterface(&pError);
if (FAILED(result))
return E_NOTIMPL;
result = pCreateError->SetDescription(someText);
if (FAILED(result))
return E_NOTIMPL;
result = pCreateError->SetGUID(IID_nsIXPCDispTestMethods);
if (FAILED(result))
return E_NOTIMPL;
CComBSTR source(L"XPCIDispatchTest.nsXPCDispTestMethods.1");
result = pCreateError->SetSource(source);
if (FAILED(result))
return E_NOTIMPL;
result = SetErrorInfo(0, pError);
if (FAILED(result))
return E_NOTIMPL;
pError->Release();
pCreateError->Release();
return E_FAIL;
}

View File

@@ -0,0 +1,138 @@
// nsXPCDispTestMethods.h: Definition of the nsXPCDispTestMethods class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTMETHODS_H__A516B1D7_1971_419C_AE35_EDFAC27D1227__INCLUDED_)
#define AFX_NSXPCDISPTESTMETHODS_H__A516B1D7_1971_419C_AE35_EDFAC27D1227__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
#include "XPCIDispatchTest.h"
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestMethods
class nsXPCDispTestMethods :
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestMethods,&CLSID_nsXPCDispTestMethods>,
public IDispatchImpl<nsIXPCDispTestMethods, &IID_nsIXPCDispTestMethods, &LIBID_IDispatchTestLib>
{
public:
nsXPCDispTestMethods() {}
BEGIN_CATEGORY_MAP(nsXPCDispTestMethods)
IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
END_CATEGORY_MAP()
BEGIN_COM_MAP(nsXPCDispTestMethods)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(nsIXPCDispTestMethods)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestMethods)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestMethods)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestMethods
public:
// nsIXPCDispTestMethod
STDMETHOD(NoParameters)();
STDMETHOD(ReturnBSTR)(BSTR * result);
STDMETHOD(ReturnI4)(INT * result);
STDMETHOD(ReturnUI1)(BYTE * result);
STDMETHOD(ReturnI2)(SHORT * result);
STDMETHOD(ReturnR4)(FLOAT * result);
STDMETHOD(ReturnR8)(DOUBLE * result);
STDMETHOD(ReturnBool)(VARIANT_BOOL * result);
STDMETHOD(ReturnIDispatch)(IDispatch * * result);
STDMETHOD(ReturnError)(SCODE * result);
STDMETHOD(ReturnDate)(DATE * result);
STDMETHOD(ReturnIUnknown)(IUnknown * * result);
STDMETHOD(ReturnI1)(unsigned char * result);
STDMETHOD(ReturnUI2)(USHORT * result);
STDMETHOD(ReturnUI4)(ULONG * result);
STDMETHOD(ReturnInt)(INT * result);
STDMETHOD(ReturnUInt)(UINT * result);
STDMETHOD(TakesBSTR)(BSTR result);
STDMETHOD(TakesI4)(INT result);
STDMETHOD(TakesUI1)(BYTE result);
STDMETHOD(TakesI2)(SHORT result);
STDMETHOD(TakesR4)(FLOAT result);
STDMETHOD(TakesR8)(DOUBLE result);
STDMETHOD(TakesBool)(VARIANT_BOOL result);
STDMETHOD(TakesIDispatch)(IDispatch * result);
STDMETHOD(TakesError)(SCODE result);
STDMETHOD(TakesDate)(DATE result);
STDMETHOD(TakesIUnknown)(IUnknown * result);
STDMETHOD(TakesI1)(unsigned char result);
STDMETHOD(TakesUI2)(USHORT result);
STDMETHOD(TakesUI4)(ULONG result);
STDMETHOD(TakesInt)(INT result);
STDMETHOD(TakesUInt)(UINT result);
STDMETHOD(OutputsBSTR)(BSTR * result);
STDMETHOD(OutputsI4)(LONG * result);
STDMETHOD(OutputsUI1)(BYTE * result);
STDMETHOD(OutputsI2)(SHORT * result);
STDMETHOD(OutputsR4)(FLOAT * result);
STDMETHOD(OutputsR8)(DOUBLE * result);
STDMETHOD(OutputsBool)(VARIANT_BOOL * result);
STDMETHOD(OutputsIDispatch)(IDispatch * * result);
STDMETHOD(OutputsError)(SCODE * result);
STDMETHOD(OutputsDate)(DATE * result);
STDMETHOD(OutputsIUnknown)(IUnknown * * result);
STDMETHOD(OutputsI1)(unsigned char * result);
STDMETHOD(OutputsUI2)(USHORT * result);
STDMETHOD(OutputsUI4)(ULONG * result);
STDMETHOD(InOutsBSTR)(BSTR * result);
STDMETHOD(InOutsI4)(LONG * result);
STDMETHOD(InOutsUI1)(BYTE * result);
STDMETHOD(InOutsI2)(SHORT * result);
STDMETHOD(InOutsR4)(FLOAT * result);
STDMETHOD(InOutsR8)(DOUBLE * result);
STDMETHOD(InOutsBool)(VARIANT_BOOL * result);
STDMETHOD(InOutsIDispatch)(IDispatch * * result);
STDMETHOD(InOutsError)(SCODE * result);
STDMETHOD(InOutsDate)(DATE * result);
STDMETHOD(InOutsIUnknown)(IUnknown * * result);
STDMETHOD(InOutsI1)(unsigned char * result);
STDMETHOD(InOutsUI2)(USHORT * result);
STDMETHOD(InOutsUI4)(ULONG * result);
STDMETHOD(OneParameterWithReturn)(LONG input, LONG * result);
STDMETHOD(StringInputAndReturn)(BSTR str, BSTR * result);
STDMETHOD(IDispatchInputAndReturn)(IDispatch * input, IDispatch** result);
STDMETHOD(TwoParameters)(LONG one, LONG two);
STDMETHOD(TwelveInParameters)(LONG one, LONG two, LONG three, LONG four,
LONG five, LONG six, LONG seven, LONG eight,
LONG nine, LONG ten, LONG eleven,
LONG twelve);
STDMETHOD(TwelveOutParameters)(LONG * one, LONG * two, LONG * three,
LONG * four, LONG * five, LONG * six,
LONG * seven, LONG * eight, LONG * nine,
LONG * ten, LONG * eleven, LONG * twelve);
STDMETHOD(TwelveStrings)(BSTR one, BSTR two, BSTR three, BSTR four,
BSTR five, BSTR six, BSTR seven, BSTR eight,
BSTR nine, BSTR ten, BSTR eleven, BSTR twelve);
STDMETHOD(TwelveOutStrings)(BSTR * one, BSTR * two, BSTR * three,
BSTR * four, BSTR * five, BSTR * six,
BSTR * seven, BSTR * eight, BSTR * nine,
BSTR * ten, BSTR * eleven, BSTR * twelve);
STDMETHOD(TwelveIDispatch)(IDispatch * one, IDispatch * two,
IDispatch * three, IDispatch * four,
IDispatch * five, IDispatch * six,
IDispatch * seven, IDispatch * eight,
IDispatch * nine, IDispatch * ten,
IDispatch * eleven, IDispatch * twelve);
STDMETHOD(TwelveOutIDispatch)(IDispatch * * one, IDispatch * * two,
IDispatch * * three, IDispatch * * four,
IDispatch * * five, IDispatch * * six,
IDispatch * * seven, IDispatch * * eight,
IDispatch * * nine, IDispatch * * ten,
IDispatch * * eleven, IDispatch * * twelve);
STDMETHOD(CreateError)();
};
#endif // !defined(AFX_NSXPCDISPTESTMETHODS_H__A516B1D7_1971_419C_AE35_EDFAC27D1227__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestMethods.1 = s 'nsXPCDispTestMethods Class'
{
CLSID = s '{745D1149-9F46-418C-B176-71EAA98974BA}'
}
XPCIDispatchTest.nsXPCDispTestMethods = s 'nsXPCDispTestMethods Class'
{
CLSID = s '{745D1149-9F46-418C-B176-71EAA98974BA}'
}
NoRemove CLSID
{
ForceRemove {745D1149-9F46-418C-B176-71EAA98974BA} = s 'nsXPCDispTestMethods Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestMethods.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestMethods'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,23 @@
// nsXPCDispTestNoIDispatch.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestNoIDispatch.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestNoIDispatch::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestNoIDispatch,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}

View File

@@ -0,0 +1,41 @@
// nsXPCDispTestNoIDispatch.h: Definition of the nsXPCDispTestNoIDispatch class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTNOIDISPATCH_H__E4B74F67_BA6B_4654_8674_E60E487129F7__INCLUDED_)
#define AFX_NSXPCDISPTESTNOIDISPATCH_H__E4B74F67_BA6B_4654_8674_E60E487129F7__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestNoIDispatch
class nsXPCDispTestNoIDispatch :
public nsIXPCDispTestNoIDispatch,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestNoIDispatch,&CLSID_nsXPCDispTestNoIDispatch>
{
public:
nsXPCDispTestNoIDispatch() {}
BEGIN_COM_MAP(nsXPCDispTestNoIDispatch)
COM_INTERFACE_ENTRY(nsIXPCDispTestNoIDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
//DECLARE_NOT_AGGREGATABLE(nsXPCDispTestNoIDispatch)
// Remove the comment from the line above if you don't want your object to
// support aggregation.
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestNoIDispatch)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestNoIDispatch
public:
};
#endif // !defined(AFX_NSXPCDISPTESTNOIDISPATCH_H__E4B74F67_BA6B_4654_8674_E60E487129F7__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestNoIDispatch.1 = s 'nsXPCDispTestNoIDispatch Class'
{
CLSID = s '{7414404F-A4CC-4E3C-9B32-BB20CB22F541}'
}
XPCIDispatchTest.nsXPCDispTestNoIDispatch = s 'nsXPCDispTestNoIDispatch Class'
{
CLSID = s '{7414404F-A4CC-4E3C-9B32-BB20CB22F541}'
}
NoRemove CLSID
{
ForceRemove {7414404F-A4CC-4E3C-9B32-BB20CB22F541} = s 'nsXPCDispTestNoIDispatch Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestNoIDispatch.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestNoIDispatch'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,256 @@
// nsXPCDispTestProperties.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestProperties.h"
const long PARAMETERIZED_PROPERTY_COUNT = 5;
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestProperties::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestProperties,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
nsXPCDispTestProperties::nsXPCDispTestProperties() :
mChar('a'),
mBOOL(FALSE),
mSCode(0),
mDATE(0),
mDouble(0.0),
mFloat(0.0f),
mLong(0),
mShort(0),
mParameterizedProperty(new long[PARAMETERIZED_PROPERTY_COUNT])
{
mCURRENCY.int64 = 0;
CComBSTR string("Initial value");
mBSTR = string.Detach();
for (long index = 0; index < PARAMETERIZED_PROPERTY_COUNT; ++index)
mParameterizedProperty[index] = index + 1;
}
nsXPCDispTestProperties::~nsXPCDispTestProperties()
{
delete [] mParameterizedProperty;
}
STDMETHODIMP nsXPCDispTestProperties::get_Short(short *pVal)
{
*pVal = mShort;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Short(short newVal)
{
mShort = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Long(long *pVal)
{
*pVal = mLong;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Long(long newVal)
{
mLong = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Float(float *pVal)
{
*pVal = mFloat;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Float(float newVal)
{
mFloat = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Double(double *pVal)
{
*pVal = mDouble;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Double(double newVal)
{
mDouble = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Currency(CURRENCY *pVal)
{
*pVal = mCURRENCY;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Currency(CURRENCY newVal)
{
mCURRENCY = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Date(DATE *pVal)
{
*pVal = mDATE;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Date(DATE newVal)
{
mDATE = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_String(BSTR *pVal)
{
*pVal = mBSTR.Copy();
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_String(BSTR newVal)
{
mBSTR = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_DispatchPtr(IDispatch **pVal)
{
mIDispatch.CopyTo(pVal);
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_DispatchPtr(IDispatch *newVal)
{
mIDispatch = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_SCode(SCODE *pVal)
{
*pVal = mSCode;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_SCode(SCODE newVal)
{
mSCode = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Boolean(BOOL *pVal)
{
*pVal = mBOOL;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Boolean(BOOL newVal)
{
mBOOL = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Variant(VARIANT *pVal)
{
::VariantCopy(pVal, &mVariant);
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Variant(VARIANT newVal)
{
mVariant = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_COMPtr(IUnknown **pVal)
{
mIUnknown.CopyTo(pVal);
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_COMPtr(IUnknown *newVal)
{
mIUnknown = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_Char(unsigned char *pVal)
{
*pVal = mChar;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_Char(unsigned char newVal)
{
mChar = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_ParameterizedProperty(long aIndex, long *pVal)
{
if (aIndex < 0 || aIndex >= PARAMETERIZED_PROPERTY_COUNT)
return E_FAIL;
*pVal = mParameterizedProperty[aIndex];
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::put_ParameterizedProperty(long aIndex, long newVal)
{
if (aIndex < 0 || aIndex >= PARAMETERIZED_PROPERTY_COUNT)
return E_FAIL;
mParameterizedProperty[aIndex] = newVal;
return S_OK;
}
STDMETHODIMP nsXPCDispTestProperties::get_ParameterizedPropertyCount(long *pVal)
{
*pVal = PARAMETERIZED_PROPERTY_COUNT;
return S_OK;
}

View File

@@ -0,0 +1,88 @@
// nsXPCDispTestProperties.h: Definition of the nsXPCDispTestProperties class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTPROPERTIES_H__9E10C7AC_36AF_4A3A_91C7_2CFB9EB166A5__INCLUDED_)
#define AFX_NSXPCDISPTESTPROPERTIES_H__9E10C7AC_36AF_4A3A_91C7_2CFB9EB166A5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestProperties
class nsXPCDispTestProperties :
public IDispatchImpl<nsIXPCDispTestProperties, &IID_nsIXPCDispTestProperties, &LIBID_IDispatchTestLib>,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestProperties,&CLSID_nsXPCDispTestProperties>
{
public:
nsXPCDispTestProperties();
virtual ~nsXPCDispTestProperties();
BEGIN_CATEGORY_MAP(nsXPCDispTestProperties)
IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
END_CATEGORY_MAP()
BEGIN_COM_MAP(nsXPCDispTestProperties)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(nsIXPCDispTestProperties)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestProperties)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestProperties)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestProperties
public:
STDMETHOD(get_ParameterizedPropertyCount)(/*[out, retval]*/ long *pVal);
STDMETHOD(get_ParameterizedProperty)(/*[in]*/long aIndex, /*[out, retval]*/ long *pVal);
STDMETHOD(put_ParameterizedProperty)(/*[in]*/long aIndex, /*[in]*/ long newVal);
STDMETHOD(get_Char)(/*[out, retval]*/ unsigned char *pVal);
STDMETHOD(put_Char)(/*[in]*/ unsigned char newVal);
STDMETHOD(get_COMPtr)(/*[out, retval]*/ IUnknown* *pVal);
STDMETHOD(put_COMPtr)(/*[in]*/ IUnknown* newVal);
STDMETHOD(get_Variant)(/*[out, retval]*/ VARIANT *pVal);
STDMETHOD(put_Variant)(/*[in]*/ VARIANT newVal);
STDMETHOD(get_Boolean)(/*[out, retval]*/ BOOL *pVal);
STDMETHOD(put_Boolean)(/*[in]*/ BOOL newVal);
STDMETHOD(get_SCode)(/*[out, retval]*/ SCODE *pVal);
STDMETHOD(put_SCode)(/*[in]*/ SCODE newVal);
STDMETHOD(get_DispatchPtr)(/*[out, retval]*/ IDispatch* *pVal);
STDMETHOD(put_DispatchPtr)(/*[in]*/ IDispatch* newVal);
STDMETHOD(get_String)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_String)(/*[in]*/ BSTR newVal);
STDMETHOD(get_Date)(/*[out, retval]*/ DATE *pVal);
STDMETHOD(put_Date)(/*[in]*/ DATE newVal);
STDMETHOD(get_Currency)(/*[out, retval]*/ CURRENCY *pVal);
STDMETHOD(put_Currency)(/*[in]*/ CURRENCY newVal);
STDMETHOD(get_Double)(/*[out, retval]*/ double *pVal);
STDMETHOD(put_Double)(/*[in]*/ double newVal);
STDMETHOD(get_Float)(/*[out, retval]*/ float *pVal);
STDMETHOD(put_Float)(/*[in]*/ float newVal);
STDMETHOD(get_Long)(/*[out, retval]*/ long *pVal);
STDMETHOD(put_Long)(/*[in]*/ long newVal);
STDMETHOD(get_Short)(/*[out, retval]*/ short *pVal);
STDMETHOD(put_Short)(/*[in]*/ short newVal);
private:
unsigned char mChar;
CComPtr<IUnknown> mIUnknown;
CComVariant mVariant;
BOOL mBOOL;
SCODE mSCode;
CComPtr<IDispatch> mIDispatch;
CComBSTR mBSTR;
DATE mDATE;
CURRENCY mCURRENCY;
double mDouble;
float mFloat;
long mLong;
short mShort;
long * mParameterizedProperty;
};
#endif // !defined(AFX_NSXPCDISPTESTPROPERTIES_H__9E10C7AC_36AF_4A3A_91C7_2CFB9EB166A5__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestProperties.1 = s 'nsXPCDispTestProperties Class'
{
CLSID = s '{D8B4265B-1768-4CA9-A285-7CCAEEB51C74}'
}
XPCIDispatchTest.nsXPCDispTestProperties = s 'nsXPCDispTestProperties Class'
{
CLSID = s '{D8B4265B-1768-4CA9-A285-7CCAEEB51C74}'
}
NoRemove CLSID
{
ForceRemove {D8B4265B-1768-4CA9-A285-7CCAEEB51C74} = s 'nsXPCDispTestProperties Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestProperties.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestProperties'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,23 @@
// nsXPCDispTestScriptOff.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestScriptOff.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestScriptOff::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestScriptOff,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}

View File

@@ -0,0 +1,43 @@
// nsXPCDispTestScriptOff.h: Definition of the nsXPCDispTestScriptOff class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTSCRIPTOFF_H__EEC88DE0_F502_4893_9918_4E435DBC9815__INCLUDED_)
#define AFX_NSXPCDISPTESTSCRIPTOFF_H__EEC88DE0_F502_4893_9918_4E435DBC9815__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
#include <ATLCTL.H>
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestScriptOff
class nsXPCDispTestScriptOff :
public IDispatchImpl<nsIXPCDispTestScriptOff, &IID_nsIXPCDispTestScriptOff, &LIBID_IDispatchTestLib>,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestScriptOff,&CLSID_nsXPCDispTestScriptOff>,
public IObjectSafetyImpl<nsXPCDispTestScriptOff, 0>
{
public:
nsXPCDispTestScriptOff() {}
BEGIN_COM_MAP(nsXPCDispTestScriptOff)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(nsIXPCDispTestScriptOff)
COM_INTERFACE_ENTRY(IObjectSafety)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestScriptOff)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestScriptOff)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestScriptOff
public:
};
#endif // !defined(AFX_NSXPCDISPTESTSCRIPTOFF_H__EEC88DE0_F502_4893_9918_4E435DBC9815__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestScriptOff.1 = s 'nsXPCDispTestScriptOff Class'
{
CLSID = s '{959CD122-9826-4757-BA09-DE327D55F9E7}'
}
XPCIDispatchTest.nsXPCDispTestScriptOff = s 'nsXPCDispTestScriptOff Class'
{
CLSID = s '{959CD122-9826-4757-BA09-DE327D55F9E7}'
}
NoRemove CLSID
{
ForceRemove {959CD122-9826-4757-BA09-DE327D55F9E7} = s 'nsXPCDispTestScriptOff Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestScriptOff.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestScriptOff'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,29 @@
// nsXPCDispTestScriptOn.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestScriptOn.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestScriptOn::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestScriptOn,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
nsXPCDispTestScriptOn::nsXPCDispTestScriptOn()
{
m_dwCurrentSafety = INTERFACESAFE_FOR_UNTRUSTED_CALLER |
INTERFACESAFE_FOR_UNTRUSTED_DATA;
}

View File

@@ -0,0 +1,45 @@
// nsXPCDispTestScriptOn.h: Definition of the nsXPCDispTestScriptOn class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTSCRIPTON_H__C037D462_C403_48FF_A02F_6C36544F0833__INCLUDED_)
#define AFX_NSXPCDISPTESTSCRIPTON_H__C037D462_C403_48FF_A02F_6C36544F0833__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
#include <ATLCTL.H>
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestScriptOn
class nsXPCDispTestScriptOn :
public IDispatchImpl<nsIXPCDispTestScriptOn, &IID_nsIXPCDispTestScriptOn, &LIBID_IDispatchTestLib>,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestScriptOn,&CLSID_nsXPCDispTestScriptOn>,
public IObjectSafetyImpl<nsXPCDispTestScriptOn,
INTERFACESAFE_FOR_UNTRUSTED_CALLER |
INTERFACESAFE_FOR_UNTRUSTED_DATA>
{
public:
nsXPCDispTestScriptOn();
BEGIN_COM_MAP(nsXPCDispTestScriptOn)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(nsIXPCDispTestScriptOn)
COM_INTERFACE_ENTRY(IObjectSafety)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestScriptOn)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestScriptOn)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestScriptOn
public:
};
#endif // !defined(AFX_NSXPCDISPTESTSCRIPTON_H__C037D462_C403_48FF_A02F_6C36544F0833__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestScriptOn.1 = s 'nsXPCDispTestScriptOn Class'
{
CLSID = s '{2A06373F-3E61-4882-A3D7-A104F70B09ED}'
}
XPCIDispatchTest.nsXPCDispTestScriptOn = s 'nsXPCDispTestScriptOn Class'
{
CLSID = s '{2A06373F-3E61-4882-A3D7-A104F70B09ED}'
}
NoRemove CLSID
{
ForceRemove {2A06373F-3E61-4882-A3D7-A104F70B09ED} = s 'nsXPCDispTestScriptOn Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestScriptOn.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestScriptOn'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,177 @@
// nsXPCDispTestWrappedJS.cpp : Implementation of CXPCIDispatchTestApp and DLL registration.
#include "stdafx.h"
#include "XPCIDispatchTest.h"
#include "nsXPCDispTestWrappedJS.h"
#include <string>
#include <sstream>
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP nsXPCDispTestWrappedJS::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_nsIXPCDispTestWrappedJS,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
struct TestData
{
typedef bool (*CompFunc)(const _variant_t & left, const _variant_t & right);
TestData(const char * name, const _variant_t & value, CompFunc cf) :
mName(name), mValue(value), mCompFunc(cf) {}
const char * mName;
_variant_t mValue;
CompFunc mCompFunc;
};
bool CompareVariant(const _variant_t & left, const _variant_t & right)
{
return left == right;
}
// These should be a template but VC++6 is brain dead in this area
#define CompareFunction(type) \
bool CompareVariant##type(const _variant_t & left, const _variant_t & right) \
{ \
return static_cast<type>(left) == static_cast<type>(right); \
}
CompareFunction(long);
CompareFunction(float);
CompareFunction(double);
CompareFunction(_bstr_t);
DISPID GetIDsOfNames(IDispatch * pIDispatch , char const * i_Method)
{
DISPID dispid;
CComBSTR method(i_Method);
OLECHAR * pMethod = method;
HRESULT hresult = pIDispatch->GetIDsOfNames(
IID_NULL,
&pMethod,
1,
LOCALE_SYSTEM_DEFAULT,
&dispid);
if (!SUCCEEDED(hresult))
{
dispid = 0;
}
return dispid;
}
namespace
{
inline
_bstr_t ConvertVariantFromBSTR(_variant_t & variant)
{
VARIANT temp = variant;
if (SUCCEEDED(VariantChangeType(&temp, &temp, 0, VT_BSTR)))
{
variant.Attach(temp);
return static_cast<_bstr_t>(variant);
}
return "**Type Conversion failed";
}
std::string DispInvoke(IDispatch * obj, const TestData & testData)
{
// Perform a put on the property
ITypeInfo * pTypeInfo;
obj->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &pTypeInfo);
DISPID dispID = ::GetIDsOfNames(obj, testData.mName);
DISPPARAMS dispParams;
dispParams.cArgs = 1;
dispParams.rgvarg = const_cast<VARIANT*>(&reinterpret_cast<const VARIANT&>(testData.mValue));
dispParams.cNamedArgs = 1;
DISPID propPut = DISPID_PROPERTYPUT;
dispParams.rgdispidNamedArgs = &propPut;
_variant_t result1;
HRESULT hResult = obj->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, &dispParams, &result1, 0, 0);
if (FAILED(hResult))
{
std::ostringstream msg;
msg << "IDispatch::Invoke on " << testData.mName << " failed to set property with result " << hResult;
return msg.str();
}
dispParams.cArgs = 1;
dispParams.rgvarg = const_cast<VARIANT*>(&reinterpret_cast<const VARIANT&>(testData.mValue));
dispParams.cNamedArgs = 0;
dispParams.rgdispidNamedArgs = 0;
_variant_t result2;
hResult = obj->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispParams, &result2, 0, 0);
if (FAILED(hResult))
{
std::ostringstream msg;
msg << "IDispatch::Invoke on " << testData.mName << " failed to retrieve property with result " << hResult;
return msg.str();
}
if (!testData.mCompFunc(result2,testData.mValue))
{
std::ostringstream msg;
VARIANT temp = testData.mValue;
char const * const desired = SUCCEEDED(VariantChangeType(&temp, &temp, 0, VT_BSTR)) ? 0 : "**Conversion Failed";
char const * const actual = SUCCEEDED(VariantChangeType(&result2, &result2, 0, VT_BSTR)) ? 0 : "**Conversion Failed";
msg << testData.mName << " ["
<< (desired ? desired : static_cast<char const *>(static_cast<_bstr_t>(testData.mValue))) << "] ["
<< (actual ? actual : static_cast<char const *>(static_cast<_bstr_t>(result2))) << "]";
return msg.str();
}
return std::string();
}
}
STDMETHODIMP nsXPCDispTestWrappedJS::TestParamTypes(IDispatch *obj, BSTR *errMsg)
{
CComPtr<IDispatch> ptr;
CComBSTR progID("XPCIDispatchTest.nsXPCDispSimple.1");
ptr.CoCreateInstance(progID);
_variant_t dispatchPtr;
dispatchPtr = static_cast<IDispatch*>(ptr);
CURRENCY currency;
currency.int64 = 55555;
_variant_t date(3000.0, VT_DATE);
_variant_t nullVariant;
nullVariant.ChangeType(VT_NULL);
const TestData tests[] =
{
TestData("Boolean", _variant_t(true), CompareVariant),
TestData("Short", _variant_t(short(4200)), reinterpret_cast<TestData::CompFunc>(CompareVariantlong)),
TestData("Long", _variant_t(long(-42000000)), CompareVariantlong),
TestData("Float", _variant_t(float(4.5)), CompareVariantfloat),
TestData("Double", _variant_t(-11111.11), CompareVariant),
// TestData("Currency", _variant_t(currency), CompareVariantdouble),
TestData("Date", date, CompareVariant_bstr_t),
TestData("String", _variant_t("A String"), CompareVariant),
TestData("DispatchPtr", dispatchPtr, CompareVariant),
// TestData("SCode", _variant_t(long(5), VT_ERROR), CompareVariant_bstr_t),
TestData("Variant", nullVariant, CompareVariant),
TestData("Char", _variant_t(BYTE('x')), CompareVariant_bstr_t)
};
std::string errors;
for (size_t index = 0; index < sizeof(tests) / sizeof(TestData); ++index)
{
std::string msg = DispInvoke(obj, tests[index]);
if (!msg.empty())
{
errors += msg;
errors += "\r\n";
}
}
CComBSTR errorMsg(errors.c_str());
*errMsg = errorMsg.Detach();
return S_OK;
}

View File

@@ -0,0 +1,50 @@
// nsXPCDispTestWrappedJS.h: Definition of the nsXPCDispTestWrappedJS class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NSXPCDISPTESTWRAPPEDJS_H__DAAB3C99_1894_40C2_B12B_A360739F8977__INCLUDED_)
#define AFX_NSXPCDISPTESTWRAPPEDJS_H__DAAB3C99_1894_40C2_B12B_A360739F8977__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// nsXPCDispTestWrappedJS
class nsXPCDispTestWrappedJS :
public IDispatchImpl<nsIXPCDispTestWrappedJS, &IID_nsIXPCDispTestWrappedJS, &LIBID_IDispatchTestLib>,
public ISupportErrorInfo,
public CComObjectRoot,
public CComCoClass<nsXPCDispTestWrappedJS,&CLSID_nsXPCDispTestWrappedJS>
{
public:
nsXPCDispTestWrappedJS() {}
BEGIN_CATEGORY_MAP(nsXPCDispTestWrappedJS)
IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
END_CATEGORY_MAP()
BEGIN_COM_MAP(nsXPCDispTestWrappedJS)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(nsIXPCDispTestWrappedJS)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(nsXPCDispTestWrappedJS)
DECLARE_REGISTRY_RESOURCEID(IDR_nsXPCDispTestWrappedJS)
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// nsIXPCDispTestWrappedJS
public:
/**
* This tests interacting with JS Objects via IDispatch
* @param obj the object being tested
* @param errMsg string receiving any error message, blank if no error
*/
STDMETHOD(TestParamTypes)(/*[in]*/ IDispatch * obj,
/*[out]*/BSTR * errMsg);
};
#endif // !defined(AFX_NSXPCDISPTESTWRAPPEDJS_H__DAAB3C99_1894_40C2_B12B_A360739F8977__INCLUDED_)

View File

@@ -0,0 +1,23 @@
HKCR
{
XPCIDispatchTest.nsXPCDispTestWrappedJS.1 = s 'nsXPCDispTestWrappedJS Class'
{
CLSID = s '{EAEE6BB2-C005-4B91-BCA7-6613236F6F69}'
}
XPCIDispatchTest.nsXPCDispTestWrappedJS = s 'nsXPCDispTestWrappedJS Class'
{
CLSID = s '{EAEE6BB2-C005-4B91-BCA7-6613236F6F69}'
}
NoRemove CLSID
{
ForceRemove {EAEE6BB2-C005-4B91-BCA7-6613236F6F69} = s 'nsXPCDispTestWrappedJS Class'
{
ProgID = s 'XPCIDispatchTest.nsXPCDispTestWrappedJS.1'
VersionIndependentProgID = s 'XPCIDispatchTest.nsXPCDispTestWrappedJS'
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'both'
}
}
}
}

View File

@@ -0,0 +1,36 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by XPCIDispatchTest.rc
//
#define IDS_PROJNAME 100
#define IDS_NSXPCDISPTTESTMETHODS_DESC 101
#define IDR_nsXPCDisptTestMethods 102
#define IDS_NSXPCDISPTESTMETHODS_DESC 103
#define IDR_nsXPCDispTestMethods 104
#define IDS_NSXPCDISPSIMPLE_DESC 105
#define IDR_nsXPCDispSimple 106
#define IDS_NSXPCDISPTESTNOIDISPATCH_DESC 107
#define IDR_nsXPCDispTestNoIDispatch 108
#define IDS_NSXPCDISPTESTNOSCRIPT_DESC 109
#define IDR_nsXPCDispTestNoScript 110
#define IDS_NSXPCDISPTESTPROPERTIES_DESC 111
#define IDR_nsXPCDispTestProperties 112
#define IDS_NSXPCDISPTESTARRAYS_DESC 113
#define IDR_nsXPCDispTestArrays 114
#define IDS_NSXPCDISPTESTSCRIPTON_DESC 115
#define IDR_nsXPCDispTestScriptOn 116
#define IDS_NSXPCDISPTESTSCRIPTOFF_DESC 117
#define IDR_nsXPCDispTestScriptOff 118
#define IDS_NSXPCDISPTESTWRAPPEDJS_DESC 119
#define IDR_nsXPCDispTestWrappedJS 120
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 204
#define _APS_NEXT_COMMAND_VALUE 32768
#define _APS_NEXT_CONTROL_VALUE 201
#define _APS_NEXT_SYMED_VALUE 121
#endif
#endif

View File

@@ -0,0 +1,54 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Verify that we can access but not overwrite the values of read-only
* attributes.
*/
test();
function test()
{
printStatus("Testing arrays");
var obj = COMObject(CLSID_nsXPCDispTestArrays);
var anArray = [ 0, 1, 2, 3];
obj.TakesSafeArray(anArray);
var strArray = [ "0", "1", "2", "3"];
obj.TakesSafeArrayBSTR(strArray);
return 0;
}

View File

@@ -0,0 +1,150 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* \file XPCIDispatchAttributeTests.js
* Test IDispatch properties and also type conversion
*/
try
{
// Test object used to test IDispatch property.
testObject = { one : 1, two : 2, three : 'three' };
test();
}
catch (e)
{
reportFailure("Unhandled exception encountered: " + e.toString());
}
/**
* Main function to perform test
*/
function test()
{
printStatus("Read-Write Attributes");
/*
* These values come from xpctest_attributes.idl and xpctest_attributes.cpp
*/
o = COMObject(CLSID_nsXPCDispTestProperties);
// Check the class an interface to make sure they're ok
reportCompare(
"object",
typeof o,
"typeof COMObject(CLSID_nsXPCDispTestProperties)");
// Make sure we can read the values
testProperty("o.Boolean", ["true", "1","testObject", "'T'", "'F'", "'true'","'false'"], false);
testProperty("o.Char", ["32"], true);
testProperty("o.COMPtr", ["0"], true);
testProperty("o.Currency", ["0", "0.5", "10000.00"], true);
testProperty("o.Date", ["'04/01/03'"], false);
testProperty("o.DispatchPtr", ["testObject"], false);
testProperty("o.Double", ["5.555555555555555555555", "5.555555555555555555555", "5", "-5"], true);
testProperty("o.Float", ["-5.55555555", "5.5555555", "5", "-5"], true);
testProperty("o.Long", ["-5", "1073741823", "-1073741824", "1073741824", "-1073741825", "5.5"], true);
testProperty("o.SCode", ["5"], true);
testProperty("o.Short", ["5", "-5", "32767", "-32768"], true);
testProperty("o.String", ["'A String'", "'c'", "5", "true"], false);
testProperty("o.Variant", ["'A Variant String'", "testObject", "10", "5.5"], false);
// Parameterized property tests
for (index = 0; index < o.ParameterizedPropertyCount; ++index)
compareExpression(
"o.ParameterizedProperty(index)",
index + 1,
"Reading initial value from parameterized property " + index);
for (index = 0; index < o.ParameterizedPropertyCount; ++index)
compareExpression(
"o.ParameterizedProperty(index) = index + 5",
index + 5,
"Assigning parameterized property " + index);
for (index = 0; index < o.ParameterizedPropertyCount; ++index)
compareExpression(
"o.ParameterizedProperty(index)",
index + 5,
"Reading new value from parameterized property " + index);
}
/**
* Tests retrieving a value from a property and setting multiple values on
* the property
*/
function testProperty(propertyExpression, values, tryString)
{
print(propertyExpression);
try
{
reportCompare(
eval(propertyExpression),
eval(propertyExpression),
propertyExpression);
}
catch (e)
{
reportFailure("Testing initial value of " + propertyExpression + " Exception: " + e.toString());
}
for (i = 0; i < values.length; ++i)
{
var value = values[i];
var expression = propertyExpression + "=" + value;
print(expression);
try
{
reportCompare(
eval(expression),
eval(value),
expression);
if (tryString)
{
expression = propertyExpression + "='" + value + "'";
print(expression);
reportCompare(
eval(expression),
eval("'" + value + "'"),
expression);
}
}
catch (e)
{
reportFailure("Testing assignment: " + expression + " Exception: " + e.toString());
}
}
}

View File

@@ -0,0 +1,122 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Verify that we can access but not overwrite the values of read-only
* attributes.
*/
test();
function testInstantiate(name, id, scriptable, methods)
{
var IDISPATCH_TEXT = "[xpconnect wrapped IDispatch";
var obj = COMObject(id);
var value = obj.toString().substr(0, IDISPATCH_TEXT.length);
reportCompare(
IDISPATCH_TEXT,
value,
"var obj = COMObject(" + id + ");");
try
{
obj = COMObject(id);
}
catch (e)
{
if (scriptable)
{
reportFailure("COMObject('" + id + "') generated an exception");
}
return;
}
value = obj.toString().substr(0, IDISPATCH_TEXT.length);
reportCompare(
scriptable ? IDISPATCH_TEXT : undefined,
scriptable ? value : obj,
"var obj = COMObject(" + id + ");");
}
function testEnumeration(compInfo)
{
var obj = COMObject(compInfo.cid);
compareObject(obj, compInfo, "Enumeration Test");
}
function test()
{
try
{
printStatus("Instantiation Tests - " + objectsDesc.length + " objects to test");
for (index = 0; index < objectsDesc.length; ++index)
{
compInfo = objectsDesc[index];
printStatus("Testing " + compInfo.name);
testInstantiate(compInfo.name, compInfo.cid, compInfo.scriptable);
testInstantiate(compInfo.name, compInfo.progid, compInfo.scriptable);
}
// Test a non-existant COM object
var obj;
try
{
obj = COMObject("dwbnonexistantobject");
printFailure("var obj = COMObject('dwbnonexistantobject'); did not throw an exception");
}
catch (e)
{
}
try
{
obj = COMObject("dwbnonexistantobject");
printFailure("obj = COMObject('dwbnonexistantobject'); did not throw an exception");
}
catch (e)
{
}
printStatus("Enumeration Tests - testing " + objectsDesc.length + " objects");
for (var index = 0; index < objectsDesc.length; ++index)
{
printStatus("Enumerating " + objectsDesc[index].name);
testEnumeration(objectsDesc[index]);
}
}
catch (e)
{
reportFailure("Unhandled exception occured:" + e.toString());
}
}

View File

@@ -0,0 +1,58 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Make repeated calls so GC kicks in and we can check for memory leaks.
*/
test();
function test()
{
printStatus("Stress testing");
for (index = 0; index < 10000; ++index)
{
for (x = 0; x < objectsDesc.length; ++x)
{
var obj = COMObject(objectsDesc[x].cid);
for (prop in obj)
{
print(index + ":" +objectsDesc[x].name + ":" + prop);
}
}
}
}

View File

@@ -0,0 +1,376 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Verify that we can access but not overwrite the values of read-only
* attributes.
*/
test();
function TestOutMethod(obj, method, value)
{
printDebug("TestOutMethod - " + method);
var x = new Object();
try
{
obj[method](x);
reportCompare(value, x.value, "Testing output parameter: " + method);
}
catch (e)
{
reportFailure("Testing output parameter failed: " + method + ": " + e.toString());
}
}
function TestReturnMethod(obj, method, value)
{
printDebug("TestReturnMethod - " + method);
try
{
reportCompare(value, obj[method](), "Testing output parameter: " + method);
}
catch (e)
{
reportFailure("Testing return value failed: " + method + ": " + e.toString());
}
}
function TestInputMethod(obj, method, value)
{
printDebug("TestInputMethod - " + method);
try
{
obj[method.toLowerCase()](value);
}
catch (e)
{
reportFailure("Testing input parameter failed: " + method + ": " + e.toString());
}
}
function TestInOutMethod(obj, method, inValue, outValue)
{
printDebug("TestInOutMethod - " + method);
try
{
var param = { value : inValue };
obj[method](param);
reportCompare(outValue, param.value, "Testing in/out parameter: " + method);
}
catch (e)
{
reportFailure("Testing in/out parameter failed: " + method + ": " + e.toString());
}
}
function test()
{
printStatus("Testing methods");
var obj = COMObject(CLSID_nsXPCDispTestMethods);
try
{
obj.NoParameters();
}
catch (e)
{
reportFailure("NoParameters failed: " + e.toString());
}
printStatus("Test method - Return values");
TestReturnMethod(obj, "ReturnBSTR", "Boo");
TestReturnMethod(obj, "ReturnI4",99999);
TestReturnMethod(obj, "ReturnUI1", 99);
TestReturnMethod(obj, "ReturnI2",9999);
TestReturnMethod(obj, "ReturnR4",99999.1);
TestReturnMethod(obj, "ReturnR8", 99999999999.99);
TestReturnMethod(obj, "ReturnBool", true);
printStatus("TestReturnMethod - ReturnIDispatch");
compareObject(obj.ReturnIDispatch(), nsXPCDispSimpleDesc, "Test method - Return IDispatch");
var E_FAIL= -2147467259;
TestReturnMethod(obj, "ReturnError", E_FAIL);
TestReturnMethod(obj, "ReturnDate", "5/2/2002");
// TestReturnMethod(obj, ReturnIUnknown(IUnknown * * result)
TestReturnMethod(obj, "ReturnI1", 120);
TestReturnMethod(obj, "ReturnUI2", 9999);
TestReturnMethod(obj, "ReturnUI4", 3000000000);
TestReturnMethod(obj, "ReturnInt", -999999);
TestReturnMethod(obj, "ReturnUInt", 3000000000);
printStatus("Test method - Input params");
TestInputMethod(obj, "TakesBSTR", "TakesBSTR");
TestInputMethod(obj, "TakesI4", 999999);
TestInputMethod(obj, "TakesUI1", 42);
TestInputMethod(obj, "TakesI2", 32000);
TestInputMethod(obj, "TakesR4", 99999.99);
TestInputMethod(obj, "TakesR8", 999999999.99);
TestInputMethod(obj, "TakesBool", true);
var x = { Number : 5, ClassName : "nsXPCDispSimple" };
TestInputMethod(obj, "TakesIDispatch", x);
// This would always fail, type mismatch (no way to indicate this is going
// to an error, and there's no automatic conversion from integers to error
// codes
// TestInputMethod(obj, "TakesError", E_FAIL);
TestInputMethod(obj, "TakesDate", "5/2/2002");
// TestInputMethod(obj, TakesIUnknown, );
TestInputMethod(obj, "TakesI1", 42);
TestInputMethod(obj, "TakesUI2", 50000);
TestInputMethod(obj, "TakesUI4", 4026531840);
TestInputMethod(obj, "TakesInt", -10000000);
TestInputMethod(obj, "TakesUInt", 3758096384);
printStatus("Test method - Output params");
TestOutMethod(obj, "OutputsBSTR", "Boo");
TestOutMethod(obj, "OutputsI4",99999);
TestOutMethod(obj, "OutputsUI1", 99);
TestOutMethod(obj, "OutputsI2",9999);
TestOutMethod(obj, "OutputsR4",999999.1);
TestOutMethod(obj, "OutputsR8", 99999999999.99);
TestOutMethod(obj, "OutputsBool", true);
var outParam = new Object();
obj.OutputsIDispatch(outParam);
compareObject(outParam.value, nsXPCDispSimpleDesc, "Test method - Output params");
TestOutMethod(obj, "OutputsError", E_FAIL);
TestOutMethod(obj, "OutputsDate", "5/2/2002");
// TestOutMethod(obj, OutputsIUnknown(IUnknown * * result)
TestOutMethod(obj, "OutputsI1", 120);
TestOutMethod(obj, "OutputsUI2", 9999);
TestOutMethod(obj, "OutputsUI4", 3000000000);
printStatus("Test method - In/out params");
TestInOutMethod(obj, "InOutsBSTR", "String", "StringAppended");
TestInOutMethod(obj, "InOutsI4", 2000000, -2000000);
TestInOutMethod(obj, "InOutsUI1", 50, 8);
TestInOutMethod(obj, "InOutsI2", -1000, 9000);
TestInOutMethod(obj, "InOutsR4", -2.05, 3.0);
TestInOutMethod(obj, "InOutsR8", -5.5, 49999994.50000005);
TestInOutMethod(obj, "InOutsBool", true, false);
TestInOutMethod(obj, "InOutsBool", false, true);
var inoutParam = { value : {ClassName : "InOutTest", Number : 10 } };
try
{
obj.InOutsIDispatch(inoutParam);
if (inoutParam.value.Number != 15)
reportFailure("Testing in/out parameter failed: IDispatch");
}
catch (e)
{
reportFailure("Testing in/out parameter failed: IDispatch - " + e.toString());
}
// See the TakesError case
//TestInOutMethod(obj, "InOutsError", E_FAIL, E_FAIL + 1);
TestInOutMethod(obj, "InOutsDate", "5/23/2001", "5/24/2001");
//TestInOutMethod(obj, InOutsIUnknown(IUnknown * * result)
TestInOutMethod(obj, "InOutsI1", -42, -41);
TestInOutMethod(obj, "InOutsUI2", 43, 85);
TestInOutMethod(obj, "InOutsUI4", 88, 46);
try
{
reportCompare(obj.OneParameterWithReturn(-20), 22, "Testing OneParameterWithReturn");
}
catch (e)
{
reportFailure("Testing OneParameterWithReturn: " + e.toString());
}
try
{
reportCompare(obj.StringInputAndReturn("A String "), "A String Appended", "Testing StringInputAndReturn");
}
catch (e)
{
reportFailure("Testing StringInputAndReturn: " + e.toString());
}
try
{
var inoutIDispatch = { className : "inouttest", Number : 5 };
var result = obj.IDispatchInputAndReturn(inoutIDispatch);
reportCompare(81, result.Number, "IDispatchInputAndReturn");
}
catch (e)
{
reportFailure("Testing IDispatchInputAndReturn: " + e.toString());
}
try
{
obj.TwoParameters(1, 2);
}
catch (e)
{
reportFailure("Testing TwoParameters: " + e.toString());
}
try
{
obj.TwelveInParameters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
}
catch (e)
{
reportFailure("Testing TwelveInParameters: " + e.toString());
}
try
{
var out1 = new Object();
var out2 = new Object();
var out3 = new Object();
var out4 = new Object();
var out5 = new Object();
var out6 = new Object();
var out7 = new Object();
var out8 = new Object();
var out9 = new Object();
var out10 = new Object();
var out11 = new Object();
var out12 = new Object();
obj.TwelveOutParameters(out1, out2, out3, out4, out5, out6, out7, out8, out9, out10, out11, out12);
reportCompare(78, out1.value + out2.value + out3.value + out4.value + out5.value + out6.value + out7.value + out8.value + out9.value + out10.value + out11.value + out12.value, "Testing TwelveOutParameters");
}
catch (e)
{
reportFailure("Testing TwelveOutParameters: " + e.toString());
}
try
{
obj.TwelveStrings("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve");
}
catch (e)
{
reportFailure("Testing TwelveStrings: " + e.toString());
}
try
{
var out1 = new Object();
var out2 = new Object();
var out3 = new Object();
var out4 = new Object();
var out5 = new Object();
var out6 = new Object();
var out7 = new Object();
var out8 = new Object();
var out9 = new Object();
var out10 = new Object();
var out11 = new Object();
var out12 = new Object();
obj.TwelveOutStrings(out1, out2, out3, out4, out5, out6, out7, out8, out9, out10, out11, out12);
reportCompare(true, out1.value == "one" && out2.value == "two" &&
out3.value == "three" && out4.value == "four" &&
out5.value == "five" && out6.value == "six" &&
out7.value == "seven" && out8.value == "eight" &&
out9.value == "nine" && out10.value == "ten" &&
out11.value == "eleven" && out12.value == "twelve",
"Testing TwelveOutString");
}
catch (e)
{
reportFailure("Testing TwelveOutParameters: " + e.toString());
}
try
{
var out1 = { className : "out1", Number : 5 };
var out2 = { className : "out2", Number : 5 };
var out3 = { className : "out3", Number : 5 };
var out4 = { className : "out4", Number : 5 };
var out5 = { className : "out5", Number : 5 };
var out6 = { className : "out6", Number : 5 };
var out7 = { className : "out7", Number : 5 };
var out8 = { className : "out8", Number : 5 };
var out9 = { className : "out9", Number : 5 };
var out10 = { className : "out10", Number : 5 };
var out11 = { className : "out11", Number : 5 };
var out12 = { className : "out12", Number : 5 };
obj.TwelveIDispatch(out1, out2, out3, out4, out5, out6, out7, out8, out9, out10, out11, out12);
}
catch (e)
{
reportFailure("Testing TwelveIDispatch: " + e.toString());
}
try
{
var out1 = new Object();
var out2 = new Object();
var out3 = new Object();
var out4 = new Object();
var out5 = new Object();
var out6 = new Object();
var out7 = new Object();
var out8 = new Object();
var out9 = new Object();
var out10 = new Object();
var out11 = new Object();
var out12 = new Object();
obj.TwelveOutIDispatch(out1, out2, out3, out4, out5, out6, out7, out8, out9, out10, out11, out12);
print("out1.value" + out1.value.Number);
reportCompare(true, out1.value.Number == 5 && out2.value.Number == 5 &&
out3.value.Number == 5 && out4.value.Number == 5 &&
out5.value.Number == 5 && out6.value.Number == 5 &&
out7.value.Number == 5 && out8.value.Number == 5 &&
out9.value.Number == 5 && out10.value.Number == 5 &&
out11.value.Number == 5 && out12.value.Number == 5,
"Testing TwelveOutIDispatch");
compareObject(out1.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out1");
compareObject(out2.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out2");
compareObject(out3.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out3");
compareObject(out4.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out4");
compareObject(out5.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out5");
compareObject(out6.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out6");
compareObject(out7.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out7");
compareObject(out8.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out8");
compareObject(out9.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out9");
compareObject(out10.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out10");
compareObject(out11.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out11");
compareObject(out12.value, nsXPCDispSimpleDesc, "Testing TwelveOutParameters - out12");
}
catch (e)
{
reportFailure("Testing TwelveOutIDispatch: " + e.toString());
}
try
{
obj.CreateError();
reportFailure("Testing CreateError: Didn't generate a catchable exception");
}
catch (e)
{
reportCompare(true, e.toString().search("CreateError Test") != -1, "Testing CreateError");
}
}

View File

@@ -0,0 +1,361 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Mozilla Communicator client code, released March
* 31, 1998.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Rob Ginda rginda@netscape.com
*/
FAILED = "FAILED!: ";
STATUS = "STATUS: ";
BUGNUMBER = "BUGNUMBER: ";
DEBUGLINE = "DEBUG: ";
DEBUG = false;
VERBOSE = false;
var CLSID_nsXPCDispSimple = "{9F39237C-D179-4260-8EF3-4B6D4D7D5570}";
var ProgID_nsXPCDispSimple = "XPCIDispatchTest.nsXPCDispSimple.1";
var nsXPCDispSimpleDesc =
{
name : "nsXPCDispSimple",
cid : CLSID_nsXPCDispSimple,
progid : ProgID_nsXPCDispSimple,
scriptable : true,
methods :
[
"ClassName",
"Number"
]
};
var CLSID_nsXPCDispTestMethods = "{745D1149-9F46-418C-B176-71EAA98974BA}";
var ProgID_nsXPCDispTestMethods = "XPCIDispatchTest.nsXPCDispTestMethods.1";
var nsXPCDispTestMethodsDesc =
{
name : "nsXPCDispTestMethods",
cid : CLSID_nsXPCDispTestMethods,
progid : ProgID_nsXPCDispTestMethods,
scriptable : true,
methods :
[
"NoParameters", "ReturnBSTR", "ReturnI4",
"ReturnUI1", "ReturnI2", "ReturnR4", "ReturnR8", "ReturnBool",
"ReturnIDispatch", "ReturnError", "ReturnDate",
"ReturnIUnknown", "ReturnI1", "ReturnUI2", "ReturnUI4",
"ReturnInt", "ReturnUInt", "TakesBSTR", "TakesI4", "TakesUI1",
"TakesI2", "TakesR4", "TakesR8", "TakesBool",
"TakesIDispatch", "TakesError", "TakesDate", "TakesIUnknown",
"TakesI1", "TakesUI2", "TakesUI4", "TakesInt", "TakesUInt",
"OutputsBSTR", "OutputsI4", "OutputsUI1", "OutputsI2",
"OutputsR4", "OutputsR8", "OutputsBool", "OutputsIDispatch",
"OutputsError", "OutputsDate", "OutputsIUnknown", "OutputsI1",
"OutputsUI2", "OutputsUI4", "InOutsBSTR", "InOutsI4",
"InOutsUI1", "InOutsI2", "InOutsR4", "InOutsR8", "InOutsBool",
"InOutsIDispatch", "InOutsError", "InOutsDate",
"InOutsIUnknown", "InOutsI1", "InOutsUI2", "InOutsUI4",
"InOutsInt", "InOutsUInt", "OneParameterWithReturn",
"StringInputAndReturn", "IDispatchInputAndReturn",
"TwoParameters", "TwelveInParameters", "TwelveOutParameters",
"TwelveStrings", "TwelveOutStrings", "TwelveIDispatch",
"TwelveOutIDispatch", "CreateError"
]
};
var CLSID_nsXPCDispTestArrays = "{AB085C43-C619-48C8-B68C-C495BDE12DFB}";
var ProgID_nsXPCDispTestArrays = "XPCIDispatchTest.nsXPCDispTestArrays.1";
var nsXPCDispTestArraysDesc =
{
name : "nsXPCDispTestArrays",
cid : CLSID_nsXPCDispTestArrays,
progid : ProgID_nsXPCDispTestArrays,
scriptable : true,
methods :
[
"ReturnSafeArray", "ReturnSafeArrayBSTR", "ReturnSafeArrayIDispatch",
"TakesSafeArray", "TakesSafeArrayBSTR", "TakesSafeArrayIDispatch",
"InOutSafeArray", "InOutSafeArrayBSTR", "InOutSafeArrayIDispatch"
]
};
var CLSID_nsXPCDispTestNoIDispatch = "{7414404F-A4CC-4E3C-9B32-BB20CB22F541}";
var ProgID_nsXPCDispTestNoIDispatch = "XPCIDispatchTest.nsXPCDispTestNoIDispatch.1";
var CLSID_nsXPCDispTestNoScript = "{F8D54F00-4FC4-4731-B467-10F1CB8DB0AD}";
var ProgID_nsXPCDispTestNoScript = "XPCIDispatchTest.nsXPCDispTestNoScript.1";
var CLSID_nsXPCDispTestProperties = "{D8B4265B-1768-4CA9-A285-7CCAEEB51C74}";
var ProgID_nsXPCDispTestProperties = "XPCIDispatchTest.nsXPCDispTestProperties.1";
var nsXPCDispTestPropertiesDesc =
{
name : "nsXPCDispTestProperties",
cid : CLSID_nsXPCDispTestProperties,
progid : ProgID_nsXPCDispTestProperties,
scriptable : true,
methods :
[
"Short", "Long", "Float", "Double", "Currency",
"Date", "String", "DispatchPtr", "SCode", "Boolean", "Variant",
"COMPtr", "Char"
]
};
var CLSID_nsXPCDispTestScriptOn = "{2A06373F-3E61-4882-A3D7-A104F70B09ED}";
var ProgID_nsXPCDispTestScriptOn = "XPCIDispatchTest.nsXPCDispTestScriptOn.1";
var nsXPCDispTestScriptOnDesc =
{
name : "nsXPCDispTestScriptOn",
cid : CLSID_nsXPCDispTestScriptOn,
progid : ProgID_nsXPCDispTestScriptOn,
scriptable : true,
methods : [ ]
};
var CLSID_nsXPCDispTestScriptOff = "{959CD122-9826-4757-BA09-DE327D55F9E7}";
var ProgID_nsXPCDispTestScriptOff = "XPCIDispatchTest.nsXPCDispTestScriptOff.1";
var nsXPCDispTestScriptOffDesc =
{
name : "nsXPCDispTestScriptOff",
cid : CLSID_nsXPCDispTestScriptOff,
progid : ProgID_nsXPCDispTestScriptOff,
scriptable : false,
methods : [ ]
};
var CLSID_nsXPCDispTestWrappedJS = "{EAEE6BB2-C005-4B91-BCA7-6613236F6F69}";
var ProgID_nsXPCDispTestWrappedJS = "XPCIDispatchTest.nsXPCDispTestWrappedJS.1";
var nsXPCDispTestWrappedJSDesc =
{
name : "nsXPCDispTestWrappedJS",
cid : CLSID_nsXPCDispTestWrappedJS,
progid : ProgID_nsXPCDispTestWrappedJS,
scriptable : true,
methods :
[
"TestParamTypes"
]
};
// create list of COM components
var objectsDesc =
[
nsXPCDispSimpleDesc,
nsXPCDispTestMethodsDesc,
nsXPCDispTestArraysDesc,
nsXPCDispTestPropertiesDesc,
nsXPCDispTestScriptOnDesc,
nsXPCDispTestScriptOffDesc,
nsXPCDispTestWrappedJSDesc
];
function findProp(prop, array, marked)
{
len = array.length;
for (index = 0; index < len; ++index)
{
if (prop == array[index])
{
marked[index] = true;
return true;
}
}
return false;
}
function compareObject(obj, objDesc, testName)
{
if (obj == undefined)
{
reportFailure("compareObject passed an invalid object");
return;
}
var marked = new Array();
for (prop in obj)
{
printDebug("Found " + prop);
reportCompare(
true,
findProp(prop, objDesc.methods, marked),
testName + ": " + prop + " exists on " + objDesc.name + ", but was not expected");
}
len = objDesc.methods.length;
for (var index = 0; index < len; ++index)
{
reportCompare(
true,
marked[index],
testName + ": " + objDesc.methods[index] + " does not exist on " + objDesc.name);
}
}
function compareExpression(expression, expectedResult, testName)
{
if (VERBOSE && (typeof testName != "undefined"))
printStatus(testName + " - evaluating:" + expression);
try
{
reportCompare(
expectedResult,
eval(expression),
testName);
}
catch (e)
{
reportFailure(expression + " generated the following exception:" + e.toString());
}
}
var callStack = new Array();
/*
* Report a failure in the 'accepted' manner
*/
function reportFailure (msg)
{
var lines = msg.split ("\n");
var l;
var funcName = currentFunc();
var prefix = (funcName) ? "[reported from " + funcName + "] ": "";
for (var i=0; i<lines.length; i++)
print (FAILED + prefix + lines[i]);
}
/*
* Print a non-failure message.
*/
function printDebug (msg)
{
if (DEBUG)
{
var lines = msg.split ("\n");
var l;
for (var i=0; i<lines.length; i++)
print (DEBUGLINE + lines[i]);
}
}
/*
* Print a non-failure message.
*/
function printStatus (msg)
{
var lines = msg.split ("\n");
var l;
for (var i=0; i<lines.length; i++)
print (STATUS + lines[i]);
}
/*
* Print a bugnumber message.
*/
function printBugNumber (num)
{
print (BUGNUMBER + num);
}
/*
* Compare expected result to actual result, if they differ (in value and/or
* type) report a failure. If description is provided, include it in the
* failure report.
*/
function reportCompare (expected, actual, description)
{
var expected_t = typeof expected;
var actual_t = typeof actual;
var output = "";
if ((VERBOSE) && (typeof description != "undefined"))
printStatus ("Comparing '" + description + "'");
if (expected_t != actual_t)
output += "Type mismatch, expected type " + expected_t +
", actual type " + actual_t + "\n";
else if (VERBOSE)
printStatus ("Expected type '" + actual_t + "' matched actual " +
"type '" + expected_t + "'");
if (expected != actual)
output += "Expected value '" + expected + "', Actual value '" + actual +
"'\n";
else if (VERBOSE)
printStatus ("Expected value '" + actual + "' matched actual " +
"value '" + expected + "'");
if (output != "")
{
if (typeof description != "undefined")
reportFailure (description);
reportFailure (output);
}
}
/*
* Puts funcName at the top of the call stack. This stack is used to show
* a function-reported-from field when reporting failures.
*/
function enterFunc (funcName)
{
if (!funcName.match(/\(\)$/))
funcName += "()";
callStack.push(funcName);
}
/*
* Pops the top funcName off the call stack. funcName is optional, and can be
* used to check push-pop balance.
*/
function exitFunc (funcName)
{
var lastFunc = callStack.pop();
if (funcName)
{
if (!funcName.match(/\(\)$/))
funcName += "()";
if (lastFunc != funcName)
reportFailure ("Test driver failure, expected to exit function '" +
funcName + "' but '" + lastFunc + "' came off " +
"the stack");
}
}
/*
* Peeks at the top of the call stack.
*/
function currentFunc()
{
return callStack[callStack.length - 1];
}

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the IDispatch implementation for XPConnect
*
* The Initial Developer of the Original Code is
* David Bradley.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* \file
* This file contains the tests for making sure that JS Objects access via the IDispatch interface
* work properly
*/
test();
function test()
{
try
{
var variantObj = Components.classes["@mozilla.org/variant;1"].createInstance(Components.interfaces.nsIVariant);
var jsobj =
{
Boolean : false,
Short : 0,
Long : 0,
Float : 0.0,
Double : 0.0,
Currency : 0.0,
Date : new Date(),
String : "",
DispatchPtr : {},
SCode : 0,
Variant : variantObj,
Char : 'a'
};
var obj = COMObject(CLSID_nsXPCDispTestWrappedJS);
reportCompare(
obj.TestParamTypes(jsobj),
"",
"Testing IDispatch wrapped JS objects");
}
catch (e)
{
reportFailure(e.toString());
}
}

View File

@@ -0,0 +1,361 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Mozilla Communicator client code, released March
* 31, 1998.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Rob Ginda rginda@netscape.com
*/
FAILED = "FAILED!: ";
STATUS = "STATUS: ";
BUGNUMBER = "BUGNUMBER: ";
DEBUGLINE = "DEBUG: ";
DEBUG = false;
VERBOSE = false;
var CLSID_nsXPCDispSimple = "{9F39237C-D179-4260-8EF3-4B6D4D7D5570}";
var ProgID_nsXPCDispSimple = "XPCIDispatchTest.nsXPCDispSimple.1";
var nsXPCDispSimpleDesc =
{
name : "nsXPCDispSimple",
cid : CLSID_nsXPCDispSimple,
progid : ProgID_nsXPCDispSimple,
scriptable : true,
methods :
[
"ClassName",
"Number"
]
};
var CLSID_nsXPCDispTestMethods = "{745D1149-9F46-418C-B176-71EAA98974BA}";
var ProgID_nsXPCDispTestMethods = "XPCIDispatchTest.nsXPCDispTestMethods.1";
var nsXPCDispTestMethodsDesc =
{
name : "nsXPCDispTestMethods",
cid : CLSID_nsXPCDispTestMethods,
progid : ProgID_nsXPCDispTestMethods,
scriptable : true,
methods :
[
"NoParameters", "ReturnBSTR", "ReturnI4",
"ReturnUI1", "ReturnI2", "ReturnR4", "ReturnR8", "ReturnBool",
"ReturnIDispatch", "ReturnError", "ReturnDate",
"ReturnIUnknown", "ReturnI1", "ReturnUI2", "ReturnUI4",
"ReturnInt", "ReturnUInt", "TakesBSTR", "TakesI4", "TakesUI1",
"TakesI2", "TakesR4", "TakesR8", "TakesBool",
"TakesIDispatch", "TakesError", "TakesDate", "TakesIUnknown",
"TakesI1", "TakesUI2", "TakesUI4", "TakesInt", "TakesUInt",
"OutputsBSTR", "OutputsI4", "OutputsUI1", "OutputsI2",
"OutputsR4", "OutputsR8", "OutputsBool", "OutputsIDispatch",
"OutputsError", "OutputsDate", "OutputsIUnknown", "OutputsI1",
"OutputsUI2", "OutputsUI4", "InOutsBSTR", "InOutsI4",
"InOutsUI1", "InOutsI2", "InOutsR4", "InOutsR8", "InOutsBool",
"InOutsIDispatch", "InOutsError", "InOutsDate",
"InOutsIUnknown", "InOutsI1", "InOutsUI2", "InOutsUI4",
"InOutsInt", "InOutsUInt", "OneParameterWithReturn",
"StringInputAndReturn", "IDispatchInputAndReturn",
"TwoParameters", "TwelveInParameters", "TwelveOutParameters",
"TwelveStrings", "TwelveOutStrings", "TwelveIDispatch",
"TwelveOutIDispatch", "CreateError"
]
};
var CLSID_nsXPCDispTestArrays = "{AB085C43-C619-48C8-B68C-C495BDE12DFB}";
var ProgID_nsXPCDispTestArrays = "XPCIDispatchTest.nsXPCDispTestArrays.1";
var nsXPCDispTestArraysDesc =
{
name : "nsXPCDispTestArrays",
cid : CLSID_nsXPCDispTestArrays,
progid : ProgID_nsXPCDispTestArrays,
scriptable : true,
methods :
[
"ReturnSafeArray", "ReturnSafeArrayBSTR", "ReturnSafeArrayIDispatch",
"TakesSafeArray", "TakesSafeArrayBSTR", "TakesSafeArrayIDispatch",
"InOutSafeArray", "InOutSafeArrayBSTR", "InOutSafeArrayIDispatch"
]
};
var CLSID_nsXPCDispTestNoIDispatch = "{7414404F-A4CC-4E3C-9B32-BB20CB22F541}";
var ProgID_nsXPCDispTestNoIDispatch = "XPCIDispatchTest.nsXPCDispTestNoIDispatch.1";
var CLSID_nsXPCDispTestNoScript = "{F8D54F00-4FC4-4731-B467-10F1CB8DB0AD}";
var ProgID_nsXPCDispTestNoScript = "XPCIDispatchTest.nsXPCDispTestNoScript.1";
var CLSID_nsXPCDispTestProperties = "{D8B4265B-1768-4CA9-A285-7CCAEEB51C74}";
var ProgID_nsXPCDispTestProperties = "XPCIDispatchTest.nsXPCDispTestProperties.1";
var nsXPCDispTestPropertiesDesc =
{
name : "nsXPCDispTestProperties",
cid : CLSID_nsXPCDispTestProperties,
progid : ProgID_nsXPCDispTestProperties,
scriptable : true,
methods :
[
"Short", "Long", "Float", "Double", "Currency",
"Date", "String", "DispatchPtr", "SCode", "Boolean", "Variant",
"COMPtr", "Char"
]
};
var CLSID_nsXPCDispTestScriptOn = "{2A06373F-3E61-4882-A3D7-A104F70B09ED}";
var ProgID_nsXPCDispTestScriptOn = "XPCIDispatchTest.nsXPCDispTestScriptOn.1";
var nsXPCDispTestScriptOnDesc =
{
name : "nsXPCDispTestScriptOn",
cid : CLSID_nsXPCDispTestScriptOn,
progid : ProgID_nsXPCDispTestScriptOn,
scriptable : true,
methods : [ ]
};
var CLSID_nsXPCDispTestScriptOff = "{959CD122-9826-4757-BA09-DE327D55F9E7}";
var ProgID_nsXPCDispTestScriptOff = "XPCIDispatchTest.nsXPCDispTestScriptOff.1";
var nsXPCDispTestScriptOffDesc =
{
name : "nsXPCDispTestScriptOff",
cid : CLSID_nsXPCDispTestScriptOff,
progid : ProgID_nsXPCDispTestScriptOff,
scriptable : false,
methods : [ ]
};
var CLSID_nsXPCDispTestWrappedJS = "{EAEE6BB2-C005-4B91-BCA7-6613236F6F69}";
var ProgID_nsXPCDispTestWrappedJS = "XPCIDispatchTest.nsXPCDispTestWrappedJS.1";
var nsXPCDispTestWrappedJSDesc =
{
name : "nsXPCDispTestWrappedJS",
cid : CLSID_nsXPCDispTestWrappedJS,
progid : ProgID_nsXPCDispTestWrappedJS,
scriptable : true,
methods :
[
"TestParamTypes"
]
};
// create list of COM components
var objectsDesc =
[
nsXPCDispSimpleDesc,
nsXPCDispTestMethodsDesc,
nsXPCDispTestArraysDesc,
nsXPCDispTestPropertiesDesc,
nsXPCDispTestScriptOnDesc,
nsXPCDispTestScriptOffDesc,
nsXPCDispTestWrappedJSDesc
];
function findProp(prop, array, marked)
{
len = array.length;
for (index = 0; index < len; ++index)
{
if (prop == array[index])
{
marked[index] = true;
return true;
}
}
return false;
}
function compareObject(obj, objDesc, testName)
{
if (obj == undefined)
{
reportFailure("compareObject passed an invalid object");
return;
}
var marked = new Array();
for (prop in obj)
{
printDebug("Found " + prop);
reportCompare(
true,
findProp(prop, objDesc.methods, marked),
testName + ": " + prop + " exists on " + objDesc.name + ", but was not expected");
}
len = objDesc.methods.length;
for (var index = 0; index < len; ++index)
{
reportCompare(
true,
marked[index],
testName + ": " + objDesc.methods[index] + " does not exist on " + objDesc.name);
}
}
function compareExpression(expression, expectedResult, testName)
{
if (VERBOSE && (typeof testName != "undefined"))
printStatus(testName + " - evaluating:" + expression);
try
{
reportCompare(
expectedResult,
eval(expression),
testName);
}
catch (e)
{
reportFailure(expression + " generated the following exception:" + e.toString());
}
}
var callStack = new Array();
/*
* Report a failure in the 'accepted' manner
*/
function reportFailure (msg)
{
var lines = msg.split ("\n");
var l;
var funcName = currentFunc();
var prefix = (funcName) ? "[reported from " + funcName + "] ": "";
for (var i=0; i<lines.length; i++)
print (FAILED + prefix + lines[i]);
}
/*
* Print a non-failure message.
*/
function printDebug (msg)
{
if (DEBUG)
{
var lines = msg.split ("\n");
var l;
for (var i=0; i<lines.length; i++)
print (DEBUGLINE + lines[i]);
}
}
/*
* Print a non-failure message.
*/
function printStatus (msg)
{
var lines = msg.split ("\n");
var l;
for (var i=0; i<lines.length; i++)
print (STATUS + lines[i]);
}
/*
* Print a bugnumber message.
*/
function printBugNumber (num)
{
print (BUGNUMBER + num);
}
/*
* Compare expected result to actual result, if they differ (in value and/or
* type) report a failure. If description is provided, include it in the
* failure report.
*/
function reportCompare (expected, actual, description)
{
var expected_t = typeof expected;
var actual_t = typeof actual;
var output = "";
if ((VERBOSE) && (typeof description != "undefined"))
printStatus ("Comparing '" + description + "'");
if (expected_t != actual_t)
output += "Type mismatch, expected type " + expected_t +
", actual type " + actual_t + "\n";
else if (VERBOSE)
printStatus ("Expected type '" + actual_t + "' matched actual " +
"type '" + expected_t + "'");
if (expected != actual)
output += "Expected value '" + expected + "', Actual value '" + actual +
"'\n";
else if (VERBOSE)
printStatus ("Expected value '" + actual + "' matched actual " +
"value '" + expected + "'");
if (output != "")
{
if (typeof description != "undefined")
reportFailure (description);
reportFailure (output);
}
}
/*
* Puts funcName at the top of the call stack. This stack is used to show
* a function-reported-from field when reporting failures.
*/
function enterFunc (funcName)
{
if (!funcName.match(/\(\)$/))
funcName += "()";
callStack.push(funcName);
}
/*
* Pops the top funcName off the call stack. funcName is optional, and can be
* used to check push-pop balance.
*/
function exitFunc (funcName)
{
var lastFunc = callStack.pop();
if (funcName)
{
if (!funcName.match(/\(\)$/))
funcName += "()";
if (lastFunc != funcName)
reportFailure ("Test driver failure, expected to exit function '" +
funcName + "' but '" + lastFunc + "' came off " +
"the stack");
}
}
/*
* Peeks at the top of the call stack.
*/
function currentFunc()
{
return callStack[callStack.length - 1];
}

View File

@@ -0,0 +1 @@
perl jsDriver.pl -e xpcshell %1 %2 %3 %4 %5 %6 %7 %8 %9

File diff suppressed because it is too large Load Diff

View File

@@ -1,58 +0,0 @@
#!/usr/bin/env python
import cgitb; cgitb.enable()
import sys
import cgi
import time
import re
from pysqlite2 import dbapi2 as sqlite
print "Content-type: text/plain\n\n"
form = cgi.FieldStorage()
# incoming query string has the following parameters:
# user=name
# (REQUIRED) user that made this annotation
# tbox=foopy
# (REQUIRED) name of the tinderbox to annotate
# data=string
# annotation to record
# time=seconds
# time since the epoch in GMT of this test result; if ommitted, current time at time of script run is used
tbox = form.getfirst("tbox")
user = form.getfirst("user")
data = form.getfirst("data")
timeval = form.getfirst("time")
if timeval is None:
timeval = int(time.time())
if (user is None) or (tbox is None) or (data is None):
print "Bad args"
sys.exit()
if re.match(r"[^A-Za-z0-9]", tbox):
print "Bad tbox name"
sys.exit()
db = sqlite.connect("db/" + tbox + ".sqlite")
try:
db.execute("CREATE TABLE test_results (test_name STRING, test_time INTEGER, test_value FLOAT, test_data BLOB);")
db.execute("CREATE TABLE annotations (anno_user STRING, anno_time INTEGER, anno_string STRING);")
db.execute("CREATE INDEX test_name_idx ON test_results.test_name")
db.execute("CREATE INDEX test_time_idx ON test_results.test_time")
db.execute("CREATE INDEX anno_time_idx ON annotations.anno_time")
except:
pass
db.execute("INSERT INTO annotations VALUES (?,?,?)", (user, timeval, data))
db.commit()
print "Inserted."
sys.exit()

View File

@@ -1,59 +0,0 @@
#!/usr/bin/env python
#
# bonsaibouncer
#
# Bounce a request to bonsai.mozilla.org, getting around silly
# cross-domain XMLHTTPRequest deficiencies.
#
import cgitb; cgitb.enable()
import os
import sys
import cgi
import gzip
import urllib
from urllib import quote
import cStringIO
bonsai = "http://bonsai.mozilla.org/cvsquery.cgi";
def main():
#doGzip = 0
#try:
# if string.find(os.environ["HTTP_ACCEPT_ENCODING"], "gzip") != -1:
# doGzip = 1
#except:
# pass
form = cgi.FieldStorage()
treeid = form.getfirst("treeid")
module = form.getfirst("module")
branch = form.getfirst("branch")
mindate = form.getfirst("mindate")
maxdate = form.getfirst("maxdate")
xml_nofiles = form.getfirst("xml_nofiles")
if not treeid or not module or not branch or not mindate or not maxdate:
print "Content-type: text/plain\n\n"
print "ERROR"
return
url = bonsai + "?" + "branchtype=match&sortby=Date&date=explicit&cvsroot=%2Fcvsroot&xml=1"
url += "&treeid=%s&module=%s&branch=%s&mindate=%s&maxdate=%s" % (quote(treeid), quote(module), quote(branch), quote(mindate), quote(maxdate))
if (xml_nofiles):
url += "&xml_nofiles=1"
urlstream = urllib.urlopen(url)
sys.stdout.write("Content-type: text/xml\n\n")
for s in urlstream:
sys.stdout.write(s)
urlstream.close()
main()

View File

@@ -1,216 +0,0 @@
#!/usr/bin/env python
import cgitb; cgitb.enable()
import sys
import cgi
import time
import re
from graphsdb import db
#if var is a valid number returns a value other than None
def checkNumber(var):
if var is None:
return 1
reNumber = re.compile('^[0-9.]*$')
return reNumber.match(var)
#if var is a valid string returns a value other than None
def checkString(var):
if var is None:
return 1
reString = re.compile('^[0-9A-Za-z._()\- ]*$')
return reString.match(var)
print "Content-type: text/plain\n\n"
link_format = "RETURN:%s:%.2f:%sspst=range&spstart=%d&spend=%d&bpst=cursor&bpstart=%d&bpend=%d&m1tid=%d&m1bl=0&m1avg=0\n"
link_str = ""
form = cgi.FieldStorage()
# incoming query string has the following parameters:
# type=discrete|continuous
# indicates discrete vs. continuous dataset, defaults to continuous
# value=n
# (REQUIRED) value to be recorded as the actual test value
# tbox=foopy
# (REQUIRED) name of the tinderbox reporting the value (or rather, the name that is to be given this set of data)
# testname=test
# (REQUIRED) the name of this test
# data=rawdata
# raw data for this test
# time=seconds
# time since the epoch in GMT of this test result; if ommitted, current time at time of script run is used
# date
# date that the test was run - this is for discrete graphs
# branch=1.8.1,1.8.0 or 1.9.0
# name of the branch that the build was generated for
# branchid=id
# date of the build
# http://wiki.mozilla.org/MozillaQualityAssurance:Build_Ids
#takes as input a file for parsing in csv with the format:
# value,testname,tbox,time,data,branch,branchid,type,data
# Create the DB schema if it doesn't already exist
# XXX can pull out dataset_info.machine and dataset_info.{test,test_type} into two separate tables,
# if we need to.
# value,testname,tbox,time,data,branch,branchid,type,data
fields = ["value", "testname", "tbox", "timeval", "date", "branch", "branchid", "type", "data"]
strFields = ["type", "data", "tbox", "testname", "branch", "branchid"]
numFields = ["date", "timeval", "value"]
d_ids = []
all_ids = []
all_types = []
if form.has_key("filename"):
val = form["filename"]
if val.file:
print "found a file"
for line in val.file:
line = line.rstrip("\n\r")
contents = line.split(',')
#clear any previous content in the fields variables - stops reuse of data over lines
for field in fields:
globals()[field] = ''
if len(contents) < 7:
print "Incompatable file format"
sys.exit(500)
for field, content in zip(fields, contents):
globals()[field] = content
for strField in strFields:
if not globals().has_key(strField):
continue
if not checkString(globals()[strField]):
print "Invalid string arg: ", strField, " '" + globals()[strField] + "'"
sys.exit(500)
for numField in numFields:
if not globals().has_key(numField):
continue
if not checkNumber(globals()[numField]):
print "Invalid string arg: ", numField, " '" + globals()[numField] + "'"
sys.exit(500)
#do some checks to ensure that we are enforcing the requirement rules of the script
if (not type):
type = "continuous"
if (not timeval):
timeval = int(time.time())
if (type == "discrete") and (not date):
print "Bad args, need a valid date"
sys.exit(500)
if (not value) or (not tbox) or (not testname):
print "Bad args"
sys.exit(500)
# figure out our dataset id
setid = -1
# Not a big fan of this while loop. If something goes wrong with the select it will insert until the script times out.
while setid == -1:
cur = db.cursor()
cur.execute("SELECT id FROM dataset_info WHERE type <=> ? AND machine <=> ? AND test <=> ? AND test_type <=> ? AND extra_data <=> ? AND branch <=> ? AND date <=> ? limit 1",
(type, tbox, testname, "perf", "branch="+branch, branch, date))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_info (type, machine, test, test_type, extra_data, branch, date) VALUES (?,?,?,?,?,?,?)",
(type, tbox, testname, "perf", "branch="+branch, branch, date))
else:
setid = res[0][0]
db.execute("INSERT INTO dataset_values (dataset_id, time, value) VALUES (?,?,?)", (setid, timeval, value))
db.execute("INSERT INTO dataset_branchinfo (dataset_id, time, branchid) VALUES (?,?,?)", (setid, timeval, branchid))
if data and data != "":
db.execute("INSERT INTO dataset_extra_data (dataset_id, time, data) VALUES (?,?,?)", (setid, timeval, data))
if (type == "discrete"):
if not setid in d_ids:
d_ids.append(setid)
if not setid in all_ids:
all_ids.append(setid)
all_types.append(type)
for setid, type in zip(all_ids, all_types):
cur = db.cursor()
cur.execute("SELECT MIN(time), MAX(time), test FROM dataset_values, dataset_info WHERE dataset_id = ? and id = dataset_id GROUP BY test", (setid,))
res = cur.fetchall()
cur.close()
tstart = res[0][0]
tend = res[0][1]
testname = res[0][2]
if type == "discrete":
link_str += (link_format % (testname, float(-1), "dgraph.html#name=" + testname + "&", tstart, tend, tstart, tend, setid,))
else:
tstart = 0
link_str += (link_format % (testname, float(-1), "graph.html#",tstart, tend, tstart, tend, setid,))
#this code auto-adds a set of continuous data for each series of discrete data sets - creating an overview of the data
# generated by a given test (matched by machine, test, test_type, extra_data and branch)
for setid in d_ids:
cur = db.cursor()
#throw out the largest value and take the average of the rest
cur.execute("SELECT AVG(value) FROM dataset_values WHERE dataset_id = ? and value != (SELECT MAX(value) from dataset_values where dataset_id = ?)", (setid, setid,))
res = cur.fetchall()
cur.close()
avg = res[0][0]
if avg is not None:
cur = db.cursor()
cur.execute("SELECT machine, test, test_type, extra_data, branch, date FROM dataset_info WHERE id = ?", (setid,))
res = cur.fetchall()
cur.close()
tbox = res[0][0]
testname = res[0][1]
test_type = res[0][2]
extra_data = res[0][3]
branch = str(res[0][4])
timeval = res[0][5]
date = ''
cur = db.cursor()
cur.execute("SELECT branchid FROM dataset_branchinfo WHERE dataset_id = ?", (setid,))
res = cur.fetchall()
cur.close()
branchid = res[0][0]
dsetid = -1
while dsetid == -1 :
cur = db.cursor()
cur.execute("SELECT id from dataset_info where type = ? AND machine <=> ? AND test = ? AND test_type = ? AND extra_data = ? AND branch <=> ? AND date <=> ? limit 1",
("continuous", tbox, testname+"_avg", "perf", "branch="+branch, branch, date))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_info (type, machine, test, test_type, extra_data, branch, date) VALUES (?,?,?,?,?,?,?)",
("continuous", tbox, testname+"_avg", "perf", "branch="+branch, branch, date))
else:
dsetid = res[0][0]
cur = db.cursor()
cur.execute("SELECT * FROM dataset_values WHERE dataset_id=? AND time <=> ? limit 1", (dsetid, timeval))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_values (dataset_id, time, value) VALUES (?,?,?)", (dsetid, timeval, avg))
db.execute("INSERT INTO dataset_branchinfo (dataset_id, time, branchid) VALUES (?,?,?)", (dsetid, timeval, branchid))
else:
db.execute("UPDATE dataset_values SET value=? WHERE dataset_id=? AND time <=> ?", (avg, dsetid, timeval))
db.execute("UPDATE dataset_branchinfo SET branchid=? WHERE dataset_id=? AND time <=> ?", (branchid, dsetid, timeval))
cur = db.cursor()
cur.execute("SELECT MIN(time), MAX(time) FROM dataset_values WHERE dataset_id = ?", (dsetid,))
res = cur.fetchall()
cur.close()
tstart = 0
tend = res[0][1]
link_str += (link_format % (testname, float(avg), "graph.html#", tstart, tend, tstart, tend, dsetid,))
db.commit()
print "Inserted."
print link_str
sys.exit()

View File

@@ -1,175 +0,0 @@
#!/usr/bin/env python
import cgitb; cgitb.enable()
import sys
import cgi
import time
import re
from graphsdb import db
#if var is a valid number returns a value other than None
def checkNumber(var):
if var is None:
return 1
reNumber = re.compile('^[0-9.]*$')
return reNumber.match(var)
#if var is a valid string returns a value other than None
def checkString(var):
if var is None:
return 1
reString = re.compile('^[0-9A-Za-z._()\- ]*$')
return reString.match(var)
print "Content-type: text/plain\n\n"
link_format = "RETURN:%.2f:%sspst=range&spstart=%d&spend=%d&bpst=cursor&bpstart=%d&bpend=%d&m1tid=%d&m1bl=0&m1avg=0\n"
link_str = ""
form = cgi.FieldStorage()
# incoming query string has the following parameters:
# type=discrete|continuous
# indicates discrete vs. continuous dataset, defaults to continuous
# value=n
# (REQUIRED) value to be recorded as the actual test value
# tbox=foopy
# (REQUIRED) name of the tinderbox reporting the value (or rather, the name that is to be given this set of data)
# testname=test
# (REQUIRED) the name of this test
# data=rawdata
# raw data for this test
# time=seconds
# time since the epoch in GMT of this test result; if ommitted, current time at time of script run is used
# date
# date that the test was run - this is for discrete graphs
# branch=1.8.1,1.8.0 or 1.9.0
# name of the branch that the build was generated for
# branchid=id
# date of the build
# http://wiki.mozilla.org/MozillaQualityAssurance:Build_Ids
#make sure that we are getting clean data from the user
for strField in ["type", "data", "tbox", "testname", "branch", "branchid"]:
val = form.getfirst(strField)
if not checkString(val):
print "Invalid string arg: ", strField, " '" + val + "'"
sys.exit(500)
globals()[strField] = val
for numField in ["date", "time", "value"]:
val = form.getfirst(numField)
if numField == "time":
numField = "timeval"
if not checkNumber(val):
print "Invalid num arg: ", numField, " '" + val + "'"
sys.exit(500)
globals()[numField] = val
#do some checks to ensure that we are enforcing the requirement rules of the script
if (not type):
type = "continuous"
if (not timeval):
timeval = int(time.time())
if (type == "discrete") and (not date):
print "Bad args, need a valid date"
sys.exit(500)
if (not value) or (not tbox) or (not testname):
print "Bad args"
sys.exit(500)
# Create the DB schema if it doesn't already exist
# XXX can pull out dataset_info.machine and dataset_info.{test,test_type} into two separate tables,
# if we need to.
# figure out our dataset id
setid = -1
while setid == -1:
cur = db.cursor()
cur.execute("SELECT id FROM dataset_info WHERE type <=> ? AND machine <=> ? AND test <=> ? AND test_type <=> ? AND extra_data=? AND branch <=> ? AND date <=> ?",
(type, tbox, testname, "perf", "branch="+branch, branch, date))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_info (type, machine, test, test_type, extra_data, branch, date) VALUES (?,?,?,?,?,?,?)",
(type, tbox, testname, "perf", "branch="+branch, branch, date))
else:
setid = res[0][0]
db.execute("INSERT INTO dataset_values (dataset_id, time, value) VALUES (?,?,?)", (setid, timeval, value))
db.execute("INSERT INTO dataset_branchinfo (dataset_id, time, branchid) VALUES (?,?,?)", (setid, timeval, branchid))
if data and data != "":
db.execute("INSERT INTO dataset_extra_data (dataset_id, time, data) VALUES (?,?,?)", (setid, timeval, data))
cur = db.cursor()
cur.execute("SELECT MIN(time), MAX(time) FROM dataset_values WHERE dataset_id = ?", (setid,))
res = cur.fetchall()
cur.close()
tstart = res[0][0]
tend = res[0][1]
if type == "discrete":
link_str += (link_format % (float(-1), "dgraph.html#name=" + testname + "&", tstart, tend, tstart, tend, setid,))
else:
tstart = 0
link_str += (link_format % (float(-1), "graph.html#",tstart, tend, tstart, tend, setid,))
#this code auto-adds a set of continuous data for each series of discrete data sets - creating an overview of the data
# generated by a given test (matched by machine, test, test_type, extra_data and branch)
# it is not terribly efficient as it updates the tracking number on the continuous set each time a point is added
# to the discrete set. If the efficiency becomes a concern we can re-examine the code - for now it is a good
# solution for generating the secondary, tracking data.
if type == "discrete" :
timeval = date
date = ''
cur = db.cursor()
#throw out the largest value and take the average of the rest
cur.execute("SELECT AVG(value) FROM dataset_values WHERE dataset_id = ? and value != (SELECT MAX(value) from dataset_values where dataset_id = ?)", (setid, setid,))
res = cur.fetchall()
cur.close()
avg = res[0][0]
if avg is not None:
setid = -1
while setid == -1 :
cur = db.cursor()
cur.execute("SELECT id from dataset_info where type <=> ? AND machine <=> ? AND test <=> ? AND test_type <=> ? AND extra_data <=> ? AND branch <=> ? AND date <=> ?",
("continuous", tbox, testname+"_avg", "perf", "branch="+branch, branch, date))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_info (type, machine, test, test_type, extra_data, branch, date) VALUES (?,?,?,?,?,?,?)",
("continuous", tbox, testname+"_avg", "perf", "branch="+branch, branch, date))
else:
setid = res[0][0]
cur = db.cursor()
cur.execute("SELECT * FROM dataset_values WHERE dataset_id=? AND time <=> ?", (setid, timeval))
res = cur.fetchall()
cur.close()
if len(res) == 0:
db.execute("INSERT INTO dataset_values (dataset_id, time, value) VALUES (?,?,?)", (setid, timeval, avg))
db.execute("INSERT INTO dataset_branchinfo (dataset_id, time, branchid) VALUES (?,?,?)", (setid, timeval, branchid))
else:
db.execute("UPDATE dataset_values SET value=? WHERE dataset_id=? AND time <=> ?", (avg, setid, timeval))
db.execute("UPDATE dataset_branchinfo SET branchid=? WHERE dataset_id=? AND time <=> ?", (branchid, setid, timeval))
cur = db.cursor()
cur.execute("SELECT MIN(time), MAX(time) FROM dataset_values WHERE dataset_id = ?", (setid,))
res = cur.fetchall()
cur.close()
tstart = 0
tend = res[0][1]
link_str += (link_format % (float(avg), "graph.html#", tstart, tend, tstart, tend, setid,))
db.commit()
print "Inserted."
print link_str
sys.exit()

View File

@@ -1,20 +0,0 @@
import MySQLdb
from MySQLdb import *
class GraphConnection(MySQLdb.connections.Connection):
def execute(self,query, args):
cur = self.cursor()
result = cur.execute(query,args)
cur.close()
return result
class GraphsCursor(MySQLdb.cursors.Cursor):
def execute(self, query, args=None):
query = query.replace('?','%s')
return MySQLdb.cursors.Cursor.execute(self, query, args)
def connect(*args,**kwargs):
kwargs['cursorclass'] = GraphsCursor
return GraphConnection(*args,**kwargs)

View File

@@ -1,105 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Perf-o-matic-too</title>
<link rel="stylesheet" type="text/css" href="js/graph.css"></link>
<!-- MochiKit -->
<script type="text/javascript" src="js/mochikit/MochiKit.js"></script>
<!-- YUI -->
<script type="text/javascript" src="js/yui/yahoo.js"></script>
<script type="text/javascript" src="js/yui/dom.js"></script>
<script type="text/javascript" src="js/yui/event.js"></script>
<script type="text/javascript" src="js/yui/animation.js"></script>
<script type="text/javascript" src="js/yui/container.js"></script>
<!-- Core -->
<script type="text/javascript" src="js/TinderboxData.js"></script>
<script type="text/javascript" src="js/DataSet.js"></script>
<script type="text/javascript" src="js/GraphCanvas.js"></script>
<script type="text/javascript" src="js/dGraphFormModule.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
<script type="text/javascript" src="js/ResizeGraph.js"></script>
<!-- BonsaiService needs e4x -->
<script type="text/javascript; e4x=1" src="js/BonsaiService.js"></script>
</head>
<body onload="loadingDone(DISCRETE_GRAPH)">
<!--<h1>Graph</h1>-->
<!-- Take your damn divs and floats and clears and shove 'em! -->
<div style="width: 710px; height:20px; margin-left:10px ">
<span id="loading" class="loading"></span>
</div>
<form action="javascript:;">
<table class="graphconfig-no" width="100%">
<tr style="vertical-align: top">
<td class="graphconfig-list">
<div id="graphforms"></div>
</td>
<td class="graphconfig-test-list">
<div id="graphforms-test-list"></div>
</td>
<td class="dgraphconfig">
<!--
<div id="baseline">
<span>Use </span><select id="baselineDropdown"><option value="0">nothing</option></select><span> as a baseline</span><br>
</div>
-->
<br>
<div id="formend">
<input id="graphbutton" type="submit" onclick="onGraph()" value="Graph It!">
<!-- <label for="baseline">No baseline</label><input type="radio" name="baseline" checked onclick="onNoBaseLineClick()"> -->
</br> </br>
<div><a id="linktothis" href="dgraph.html">Link to this graph</a> </div>
</br>
<div><a id="dumptocsv" href="dumpdata.cgi">Dump to csv</a> </div>
</div>
</tr>
</table>
</form>
<!-- small graph -->
<div style="width: 900px; height:20px">
<center><span id="status" class="status"></span></center>
</div>
<div id="container" style="width: 100%">
<!-- these are absolute size, so we wrap them in a div that can overflow -->
<div id="graph-container" style="width: 900px; margin:auto">
<div id="smallgraph-labels-x" style="position: relative; left: 51px; margin-left: 1px; margin-right: 1px; height: 30px; width: 700px"></div>
<div id="smallgraph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; height: 76px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888; padding-top: 1px;" id="smallgraph" height="75" width="650"></canvas>
<br/>
<br/>
<div id="graph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; margin-top: 1px; margin-bottom: 1px; height: 300px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888;" id="graph" height="300" width="650"></canvas>
<div id="graph-labels-x" style="position: relative; left: 50px; margin-left: 1px; margin-right: 1px; height: 50px; width: 700px"></div>
</div>
<div id="graph-label-container" style="float:left;margin-top:30px;">
<span id="graph-label-list" class="graph-label-list-member" align="left"></span>
</div>
</div>
<script>
ResizableBigGraph = new ResizeGraph();
ResizableBigGraph.init('graph');
</script>
</body>
</html>

View File

@@ -1,127 +0,0 @@
#!/usr/bin/env python
import cgitb; cgitb.enable()
import os
import sys
import cgi
import time
import re
import gzip
import minjson as json
import cStringIO
from graphsdb import db
#
# returns a plain text file containing the information for a given dataset in two csv tables
# the first table containing the dataset info (branch, date, etc)
# the second table containing the databaset values
#
# incoming query string:
#
# setid=number
# Where number is a valid setid
#
# starttime=tval
# Start time to return results from, in seconds since GMT epoch
# endtime=tval
# End time, in seconds since GMT epoch
def doError(errCode):
errString = "unknown error"
if errCode == -1:
errString = "bad tinderbox"
elif errCode == -2:
errString = "bad test name"
print "{ resultcode: " + str(errCode) + ", error: '" + errString + "' }"
def esc(val):
delim = '"'
val = delim + str(val).replace(delim, delim + delim) + delim
return val
def dumpData(fo, setid, starttime, endtime):
s1 = ""
s2 = ""
if starttime:
s1 = " AND time >= B." + starttime
if endtime:
s2 = " AND time <= B." + endtime
cur = db.cursor()
setid = ",".join(setid)
fo.write("dataset,machine,branch,test,date\n")
cur.execute("SELECT B.id, B.machine, B.branch, B.test, B.date FROM dataset_info as B WHERE id IN (%s) %s %s ORDER BY id" % (setid, s1, s2,))
for row in cur:
fo.write ('%s,%s,%s,%s,%s\n' % (esc(row[0]), esc(row[1]), esc(row[2]), esc(row[3]), esc(row[4])))
fo.write("dataset,time,value,buildid,data\n")
cur.close()
cur = db.cursor()
#cur.execute("SELECT dataset_id, time, value, branchid, data from ((dataset_values NATURAL JOIN dataset_branchinfo) NATURAL JOIN dataset_extra_data) WHERE dataset_id IN (%s) %s %s ORDER BY dataset_id, time" % (setid, s1, s2,))
cur.execute("SELECT dataset_values.dataset_id, dataset_values.time, dataset_values.value, dataset_branchinfo.branchid, dataset_extra_data.data FROM dataset_values LEFT JOIN dataset_branchinfo ON dataset_values.dataset_id = dataset_branchinfo.dataset_id AND dataset_values.time = dataset_branchinfo.time LEFT JOIN dataset_extra_data ON dataset_values.dataset_id = dataset_extra_data.dataset_id AND dataset_values.time = dataset_extra_data.time WHERE dataset_values.dataset_id IN (%s) %s %s ORDER BY dataset_values.dataset_id, dataset_values.time" % (setid, s1, s2))
for row in cur:
fo.write ('%s,%s,%s,%s,%s\n' % (esc(row[0]), esc(row[1]), esc(row[2]), esc(row[3]), esc(row[4])))
cur.close()
#if var is a number returns a value other than None
def checkNumber(var):
if var is None:
return 1
reNumber = re.compile('^[0-9.]*$')
return reNumber.match(var)
#if var is a string returns a value other than None
def checkString(var):
if var is None:
return 1
reString = re.compile('^[0-9A-Za-z._()\- ]*$')
return reString.match(var)
doGzip = 0
try:
if "gzip" in os.environ["HTTP_ACCEPT_ENCODING"]:
doGzip = 1
except:
pass
form = cgi.FieldStorage()
for numField in ["setid"]:
val = form.getlist(numField)
for v in val:
if not checkNumber(v):
print "Invalid string arg: ", numField, " '" + v + "'"
sys.exit(500)
globals()[numField] = val
for numField in ["starttime", "endtime"]:
val = form.getfirst(numField)
if not checkNumber(val):
print "Invalid string arg: ", numField, " '" + val + "'"
sys.exit(500)
globals()[numField] = val
if not setid:
print "Content-Type: text/plain\n"
print "No data set selected\n"
sys.exit(500)
zbuf = cStringIO.StringIO()
zfile = zbuf
if doGzip == 1:
zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9)
dumpData(zfile, setid, starttime, endtime)
sys.stdout.write("Content-Type: text/plain\n")
if doGzip == 1:
zfile.close()
sys.stdout.write("Content-Encoding: gzip\n")
sys.stdout.write("\n")
sys.stdout.write(zbuf.getvalue())

View File

@@ -1,105 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Perf-o-matic-too</title>
<link rel="stylesheet" type="text/css" href="js/graph.css"></link>
<!-- MochiKit -->
<script type="text/javascript" src="js/mochikit/MochiKit.js"></script>
<!-- YUI -->
<script type="text/javascript" src="js/yui/yahoo.js"></script>
<script type="text/javascript" src="js/yui/dom.js"></script>
<script type="text/javascript" src="js/yui/event.js"></script>
<script type="text/javascript" src="js/yui/animation.js"></script>
<script type="text/javascript" src="js/yui/container.js"></script>
<!-- Core -->
<script type="text/javascript" src="js/TinderboxData.js"></script>
<script type="text/javascript" src="js/DataSet.js"></script>
<script type="text/javascript" src="js/GraphCanvas.js"></script>
<script type="text/javascript" src="js/edGraphFormModule.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
<script type="text/javascript" src="js/ResizeGraph.js"></script>
<!-- BonsaiService needs e4x -->
<script type="text/javascript; e4x=1" src="js/BonsaiService.js"></script>
</head>
<body onload="loadingDone(DATA_GRAPH)">
<!--<h1>Graph</h1>-->
<!-- Take your damn divs and floats and clears and shove 'em! -->
<div style="width: 710px; height:20px; margin-left:10px ">
<span id="loading" class="loading"></span>
</div>
<form action="javascript:;">
<table class="graphconfig-no" width="100%">
<tr style="vertical-align: top">
<td class="graphconfig-list">
<div id="graphforms"></div>
</td>
<td class="graphconfig-test-list">
<div id="graphforms-test-list"></div>
</td>
<td class="dgraphconfig">
<!--
<div id="baseline">
<span>Use </span><select id="baselineDropdown"><option value="0">nothing</option></select><span> as a baseline</span><br>
</div>
-->
<br>
<div id="formend">
<input id="graphbutton" type="submit" onclick="onGraph()" value="Graph It!">
<!-- <label for="baseline">No baseline</label><input type="radio" name="baseline" checked onclick="onNoBaseLineClick()"> -->
</br> </br>
<div><a id="linktothis" href="edgraph.html">Link to this graph</a> </div>
</br>
<div><a id="dumptocsv" href="dumpdata.cgi">Dump to csv</a> </div>
</div>
</tr>
</table>
</form>
<!-- small graph -->
<div style="width: 900px; height:20px">
<center><span id="status" class="status"></span></center>
</div>
<div id="container" style="width: 100%">
<!-- these are absolute size, so we wrap them in a div that can overflow -->
<div id="graph-container" style="width: 900px; margin:auto">
<div id="smallgraph-labels-x" style="position: relative; left: 51px; margin-left: 1px; margin-right: 1px; height: 30px; width: 700px"></div>
<div id="smallgraph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; height: 76px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888; padding-top: 1px;" id="smallgraph" height="75" width="650"></canvas>
<br/>
<br/>
<div id="graph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; margin-top: 1px; margin-bottom: 1px; height: 300px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888;" id="graph" height="300" width="650"></canvas>
<div id="graph-labels-x" style="position: relative; left: 50px; margin-left: 1px; margin-right: 1px; height: 50px; width: 700px"></div>
</div>
<div id="graph-label-container" style="float:left;margin-top:30px;">
<span id="graph-label-list" class="graph-label-list-member" align="left"></span>
</div>
</div>
<script>
ResizableBigGraph = new ResizeGraph();
ResizableBigGraph.init('graph');
</script>
</body>
</html>

View File

@@ -1,47 +0,0 @@
#!/usr/bin/perl
print "Content-type: text/plain\n\n";
#foreach my $k (keys(%ENV)) {
# print "$k => " . $ENV{$k} . "\n";
#}
my $QS = $ENV{"QUERY_STRING"};
my %query = ();
{
my @qp = split /\&/,$QS;
foreach my $q (@qp) {
my @qp1 = split /=/,$q;
$query{$qp1[0]} = $qp1[1];
}
}
if (defined($query{"setid"})) {
my $testid = $query{"setid"};
print "{ resultcode: 0, results: [";
srand();
my $lv = 200 + rand (100);
foreach my $k (1 .. 500) {
#my $kv = $k;
#my $v = $k;
my $kv = 1148589000 + ($k*60*20);
my $v = $lv;
$lv = $lv + (rand(10) - 5);
print "$kv, $v, ";
}
print "] }";
} else {
print "{ resultcode: 0, results: [
{ id: 1, machine: 'tbox1', test: 'test1', test_type: 'perf', extra_data: null },
{ id: 4, machine: 'tbox2', test: 'test1', test_type: 'perf', extra_data: null },
{ id: 3, machine: 'tbox1', test: 'test3', test_type: 'perf', extra_data: null },
{ id: 6, machine: 'tbox3', test: 'test3', test_type: 'perf', extra_data: null },
{ id: 2, machine: 'tbox1', test: 'test2', test_type: 'perf', extra_data: null },
{ id: 5, machine: 'tbox2', test: 'test2', test_type: 'perf', extra_data: null },
] }";
}

View File

@@ -1,276 +0,0 @@
#!/usr/bin/env python
import cgitb; cgitb.enable()
import os
import sys
import cgi
import time
import re
import gzip
import minjson as json
import cStringIO
from graphsdb import db
#
# All objects are returned in the form:
# {
# resultcode: n,
# ...
# }
#
# The ... is dependant on the result type.
#
# Result codes:
# 0 success
# -1 bad tinderbox
# -2 bad test name
#
# incoming query string:
# tbox=name
# tinderbox name
#
# If only tbox specified, returns array of test names for that tinderbox in data
# If invalid tbox specified, returns error -1
#
# test=testname
# test name
#
# Returns results for that test in .results, in array of [time0, value0, time1, value1, ...]
# Also returns .annotations for that dataset, in array of [time0, string0, time1, string1, ...]
#
# raw=1
# Same as full results, but includes raw data for test in .rawdata, in form [time0, rawdata0, ...]
#
# starttime=tval
# Start time to return results from, in seconds since GMT epoch
# endtime=tval
# End time, in seconds since GMT epoch
#
# getlist=1
# To be combined with branch, machine and testname
# Returns a list of distinct branches, machines or testnames in the database
#
# if neither getlist nor setid are found in the query string the returned results will be a list
# of tests, limited by a given datelimit, branch, machine and testname
# ie) dgetdata?datelimit=1&branch=1.8 will return all tests in the database that are not older than a day and that
# were run on the 1.8 branch
def doError(errCode):
errString = "unknown error"
if errCode == -1:
errString = "bad tinderbox"
elif errCode == -2:
errString = "bad test name"
print "{ resultcode: " + str(errCode) + ", error: '" + errString + "' }"
def doGetList(fo, type, branch, machine, testname):
results = []
s1 = ""
if branch:
s1 = "SELECT DISTINCT branch FROM dataset_info"
if machine:
s1 = "SELECT DISTINCT machine FROM dataset_info"
if testname:
s1 = "SELECT DISTINCT test FROM dataset_info"
cur = db.cursor()
cur.execute(s1 + " WHERE type = ?", (type,))
for row in cur:
results.append({ "value": row[0] })
cur.close()
fo.write(json.write( {"resultcode": 0, "results": results} ))
def doListTests(fo, type, datelimit, branch, machine, testname, graphby):
results = []
s1 = ""
# FIXME: This could be vulnerable to SQL injection! Although it looks like checkstring should catch bad strings.
if branch:
s1 += " AND branch = '" + branch + "' "
if machine:
s1 += " AND machine = '" + machine + "' "
if testname:
s1 += " AND test = '" + testname + "' "
cur = db.cursor()
if graphby and graphby == 'bydata':
cur.execute("SELECT id, machine, test, test_type, dataset_extra_data.data, extra_data, branch FROM dataset_extra_data JOIN dataset_info ON dataset_extra_data.dataset_id = dataset_info.id WHERE type = ? AND test_type != ? and (date >= ?) " + s1 +" GROUP BY machine,test,test_type,dataset_extra_data.data, extra_data, branch", (type, "baseline", datelimit))
else:
cur.execute("SELECT id, machine, test, test_type, date, extra_data, branch FROM dataset_info WHERE type = ? AND test_type != ? and (date >= ?)" + s1, (type, "baseline", datelimit))
for row in cur:
if graphby and graphby == 'bydata':
results.append( {"id": row[0],
"machine": row[1],
"test": row[2],
"test_type": row[3],
"data": row[4],
"extra_data": row[5],
"branch": row[6]})
else:
results.append( {"id": row[0],
"machine": row[1],
"test": row[2],
"test_type": row[3],
"date": row[4],
"extra_data": row[5],
"branch": row[6]})
cur.close()
fo.write (json.write( {"resultcode": 0, "results": results} ))
def getByDataResults(cur,setid,extradata,starttime,endtime):
s1 = ""
s2 = ""
cur.execute("""
SELECT dataset_info.date,avg(dataset_values.value)
FROM dataset_info
JOIN dataset_extra_data
ON dataset_extra_data.dataset_id = dataset_info.id
JOIN dataset_values
ON dataset_extra_data.time = dataset_values.time
AND dataset_info.id = dataset_values.dataset_id
WHERE
(dataset_info.machine,dataset_info.test,dataset_info.test_type,dataset_info.extra_data,dataset_info.branch) = (SELECT machine,test,test_type,extra_data,branch from dataset_info where id = ? limit 1)
AND dataset_extra_data.data = ?
GROUP BY dataset_info.date ORDER BY dataset_info.date
""", (setid,extradata))
def doSendResults(fo, setid, starttime, endtime, raw, graphby, extradata=None):
s1 = ""
s2 = ""
if starttime:
s1 = " AND time >= " + starttime
if endtime:
s2 = " AND time <= " + endtime
fo.write ("{ resultcode: 0,")
cur = db.cursor()
if not graphby or graphby == "time":
cur.execute("SELECT time, value FROM dataset_values WHERE dataset_id = ? " + s1 + s2 + " ORDER BY time", (setid,))
else:
getByDataResults(cur,setid, extradata,starttime,endtime)
fo.write ("results: [")
for row in cur:
if row[1] == 'nan':
continue
fo.write ("%s,%s," % (row[0], row[1]))
cur.close()
fo.write ("],")
cur = db.cursor()
cur.execute("SELECT time, value FROM annotations WHERE dataset_id = ? " + s1 + s2 + " ORDER BY time", (setid,))
fo.write ("annotations: [")
for row in cur:
fo.write("%s,'%s'," % (row[0], row[1]))
cur.close()
fo.write ("],")
cur = db.cursor()
cur.execute("SELECT test FROM dataset_info WHERE id = ?", (setid,))
row = cur.fetchone()
test_name = row[0]
cur.execute("SELECT id, extra_data FROM dataset_info WHERE test = ? and test_type = ?", (test_name, "baseline"))
baselines = cur.fetchall()
fo.write ("baselines: {")
for baseline in baselines:
cur.execute("SELECT value FROM dataset_values WHERE dataset_id = ? LIMIT 1", (baseline[0],))
row = cur.fetchone()
fo.write("'%s': '%s'," % (baseline[1], row[0]))
fo.write("},")
cur.close()
if raw:
cur = db.cursor()
cur.execute("SELECT time, data FROM dataset_extra_data WHERE dataset_id = ? " + s1 + s2 + " ORDER BY time", (setid,))
fo.write ("rawdata: [")
for row in cur:
blob = row[1]
if "\\" in blob:
blob = blob.replace("\\", "\\\\")
if "'" in blob:
blob = blob.replace("'", "\\'")
fo.write("%s,'%s'," % (row[0], blob))
cur.close()
fo.write ("],")
cur = db.cursor()
cur.execute("SELECT avg(value), max(value), min(value) from dataset_values where dataset_id = ? " + s1 + s2 + " GROUP BY dataset_id", (setid,))
fo.write("stats: [")
for row in cur:
fo.write("%s, %s, %s," %(row[0], row[1], row[2]))
cur.close()
fo.write("],")
fo.write ("}")
#if var is a number returns a value other than None
def checkNumber(var):
if var is None:
return 1
reNumber = re.compile('^[0-9.]*$')
return reNumber.match(var)
#if var is a string returns a value other than None
def checkString(var):
if var is None:
return 1
reString = re.compile('^[0-9A-Za-z._()\- ]*$')
return reString.match(var)
doGzip = 0
try:
if "gzip" in os.environ["HTTP_ACCEPT_ENCODING"]:
doGzip = 1
except:
pass
form = cgi.FieldStorage()
#make sure that we are getting clean data from the user
for strField in ["type", "machine", "branch", "test", "graphby","extradata"]:
val = form.getfirst(strField)
if strField == "test":
strField = "testname"
if not checkString(val):
print "Invalid string arg: ", strField, " '" + val + "'"
sys.exit(500)
globals()[strField] = val
for numField in ["setid", "raw", "starttime", "endtime", "datelimit", "getlist"]:
val = form.getfirst(numField)
if not checkNumber(val):
print "Invalid string arg: ", numField, " '" + val + "'"
sys.exit(500)
globals()[numField] = val
if not datelimit:
datelimit = 0
zbuf = cStringIO.StringIO()
zfile = zbuf
if doGzip == 1:
zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
if not setid and not getlist:
doListTests(zfile, type, datelimit, branch, machine, testname, graphby)
elif not getlist:
doSendResults(zfile, setid, starttime, endtime, raw, graphby,extradata)
else:
doGetList(zfile, type, branch, machine, testname)
sys.stdout.write("Content-Type: text/plain\n")
if doGzip == 1:
zfile.close()
sys.stdout.write("Content-Encoding: gzip\n")
sys.stdout.write("\n")
sys.stdout.write(zbuf.getvalue())

View File

@@ -1,115 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Perf-o-matic</title>
<link rel="stylesheet" type="text/css" href="js/graph.css">
<!-- MochiKit -->
<script type="text/javascript" src="js/mochikit/MochiKit.js"></script>
<!-- YUI -->
<script type="text/javascript" src="js/yui/yahoo.js"></script>
<script type="text/javascript" src="js/yui/dom.js"></script>
<script type="text/javascript" src="js/yui/event.js"></script>
<script type="text/javascript" src="js/yui/animation.js"></script>
<script type="text/javascript" src="js/yui/container.js"></script>
<!-- Core -->
<script type="text/javascript" src="js/TinderboxData.js"></script>
<script type="text/javascript" src="js/DataSet.js"></script>
<script type="text/javascript" src="js/GraphCanvas.js"></script>
<script type="text/javascript" src="js/GraphFormModule.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
<script type="text/javascript" src="js/ResizeGraph.js"></script>
<!-- BonsaiService needs e4x -->
<script type="text/javascript; e4x=1" src="js/BonsaiService.js"></script>
</head>
<body onload="loadingDone(CONTINUOUS_GRAPH)">
<!--<h1>Graph</h1>-->
<!-- Take your damn divs and floats and clears and shove 'em! -->
<div style="width: 710px; height:20px; margin-left:10px ">
<span id="loading" class="loading"></span>
</div>
<form action="javascript:;">
<table class="graphconfig-no" width="100%">
<tr style="vertical-align: top">
<td class="graphconfig">
<table>
<tr style="vertical-align: top;">
<td>Show</td>
<td>
<input id="load-all-radio" type="radio" name="dataload" onclick="onDataLoadChanged()" checked>
<label>all data</label><br>
<input id="load-days-radio" type="radio" name="dataload" onclick="onDataLoadChanged()">
<label>previous</label> <input type="text" value="30" id="load-days-entry" size="3" onchange="onDataLoadChanged()"> <label>days</label>
</td>
</tr>
</table>
<div id="baseline">
<span>Use </span><select id="baselineDropdown"><option value="0">nothing</option></select><span> as a baseline</span><br>
</div>
<br>
<div id="formend">
<input type="submit" onclick="onGraph()" value="Graph It!">
</br> </br>
<!-- <label for="baseline">No baseline</label><input type="radio" name="baseline" checked onclick="onNoBaseLineClick()"> -->
<a id="linktothis" href="graph.html">Link to this graph</a>
</br>
<div><a id="dumptocsv" href="dumpdata.cgi">Dump to csv</a> </div>
</div>
<br>
<input style="display:none" id="bonsaibutton" type="button" onclick="onUpdateBonsai()" value="Refresh Bonsai Data">
</td>
<td class="graphconfig-list">
<div id="graphforms"></div>
<div id="addone">
<img src="js/img/plus.png" class="plusminus" onclick="addGraphForm()" alt="Plus">
</div>
</td>
</tr>
</table>
</form>
<!-- small graph -->
<div style="width: 900px; height:20px">
<center><span id="status" class="status"></span></center>
</div>
<!-- these are absolute size, so we wrap them in a div that can overflow -->
<div id="graph-container" style="margin:auto; width:900px;">
<div id="smallgraph-labels-x" style="position: relative; left: 51px; margin-left: 1px; margin-right: 1px; height: 30px; width: 700px"></div>
<div id="smallgraph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; height: 76px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888; padding-top: 1px;" id="smallgraph" height="75" width="700"></canvas>
<br/>
<br/>
<div id="graph-labels-y" style="position: relative; left: 0px; top: 0px; float: left; margin-top: 1px; margin-bottom: 1px; height: 300px; width: 50px;"></div>
<canvas style="clear: left; border: 1px solid #888;" id="graph" height="300" width="700"></canvas>
<div id="graph-labels-x" style="position: relative; left: 50px; margin-left: 1px; margin-right: 1px; height: 50px; width: 700px"></div>
</div>
<script>
ResizableBigGraph = new ResizeGraph();
ResizableBigGraph.init('graph');
</script>
</body>
</html>

View File

@@ -1,6 +0,0 @@
from pysqlite2 import dbapi2 as sqlite
from databases import mysql as MySQLdb
db = MySQLdb.connect("localhost","o","o","o_graphs")

View File

@@ -1,111 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function BonsaiService() {
}
BonsaiService.prototype = {
// this could cache stuff, so that we only have to request the bookend data
// if we want a wider range, but it's probably not worth it for now.
//
// The callback is called with an object argument which contains:
// {
// times: [ t1, t2, t3, .. ],
// who: [ w1, w2, w3, .. ],
// log: [ l1, l2, l3, .. ],
// files: [ [ r11, f11, r12, f12, r13, f13, .. ], [ r21, f21, r22, f22, r23, f23, .. ], .. ]
// }
//
// r = revision number, as a string, e.g. "1.15"
// f = file, e.g. "mozilla/widget/foo.cpp"
//
// arg1 = callback, arg2 = null
// arg1 = includeFiles, arg2 = callback
requestCheckinsBetween: function (startDate, endDate, arg1, arg2) {
var includeFiles = arg1;
var callback = arg2;
if (arg2 == null) {
callback = arg1;
includeFiles = null;
}
var queryargs = {
treeid: "default",
module: "SeaMonkeyAll",
branch: "HEAD",
mindate: startDate,
maxdate: endDate
};
if (!includeFiles)
queryargs.xml_nofiles = "1";
log ("bonsai request: ", queryString(queryargs));
doSimpleXMLHttpRequest (bonsaicgi, queryargs)
.addCallbacks(
function (obj) {
var result = { times: [], who: [], comment: [], files: null };
if (includeFiles)
result.files = [];
// strip out the xml declaration
var s = obj.responseText.replace(/<\?xml version="1.0"\?>/, "");
var bq = new XML(s);
for (var i = 0; i < bq.ci.length(); i++) {
var ci = bq.ci[i];
result.times.push(ci.@date);
result.who.push(ci.@who);
result.comment.push(ci.log.text().toString());
if (includeFiles) {
var files = [];
for (var j = 0; j < ci.files.f.length(); j++) {
var f = ci.files.f[j];
files.push(f.@rev);
files.push(f.text().toString());
}
result.files.push(files);
}
}
callback.call (window, result);
},
function () { alert ("Error talking to bonsai"); });
},
};

View File

@@ -1,273 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function TimeDataSet(data) {
this.data = data;
}
TimeDataSet.prototype = {
data: null,
indicesForTimeRange: function (startTime, endTime) {
var startIndex = -1;
var endIndex = -1;
if (this.data[0] > endTime ||
this.data[this.data.length-2] < startTime)
return null;
for (var i = 0; i < this.data.length/2; i++) {
if (startIndex == -1 && this.data[i*2] >= startTime) {
startIndex = i;
} else if (startIndex != -1 && this.data[i*2] > endTime) {
endIndex = i;
return [startIndex, endIndex];
}
}
endIndex = (this.data.length/2) - 1;
return [startIndex, endIndex];
},
};
function TimeValueDataSet(data, color) {
this.data = data;
this.firstTime = data[0];
if (data.length > 2)
this.lastTime = data[data.length-2];
else
this.lastTime = data[0];
if (color) {
this.color = color;
} else {
this.color = "#000000";
}
log ("new tds:", this.firstTime, this.lastTime);
this.relativeToSets = new Array();
}
TimeValueDataSet.prototype = {
__proto__: new TimeDataSet(),
firstTime: 0,
lastTime: 0,
data: null, // array: [time0, value0, time1, value1, ...]
relativeTo: null,
color: "black",
title: '',
minMaxValueForTimeRange: function (startTime, endTime) {
var minValue = Number.POSITIVE_INFINITY;
var maxValue = Number.NEGATIVE_INFINITY;
for (var i = 0; i < this.data.length/2; i++) {
var t = this.data[i*2];
if (t >= startTime && t <= endTime) {
var v = this.data[i*2+1];
if (v < minValue)
minValue = v;
if (v > maxValue)
maxValue = v;
}
}
return [minValue, maxValue];
},
// create a new ds that's the average of this ds's values,
// with the average sampled over the given interval,
// at every avginterval/2
createAverage: function (avginterval) {
if (avginterval <= 0)
throw "avginterval <= 0";
if (this.averageDataSet != null &&
this.averageInterval == avginterval)
{
return this.averageDataSet;
}
var newdata = [];
var time0 = this.data[0];
var val0 = 0;
var count0 = 0;
var time1 = time0 + avginterval/2;
var val1 = 0;
var count1 = 0;
var ns = this.data.length/2;
for (var i = 0; i < ns; i++) {
var t = this.data[i*2];
var v = this.data[i*2+1];
if (t > time0+avginterval) {
newdata.push(time0 + avginterval/2);
newdata.push(count0 ? (val0 / count0) : 0);
// catch up
while (time1 < t) {
time0 += avginterval/2;
time1 = time0;
}
time0 = time1;
val0 = val1;
count0 = count1;
time1 = time0 + avginterval/2;
val1 = 0;
count1 = 0;
}
val0 += v;
count0++;
if (t > time1) {
val1 += v;
count1++;
}
}
if (count0 > 0) {
newdata.push(time0 + avginterval/2);
newdata.push(val0 / count0);
}
var newds = new TimeValueDataSet(newdata, lighterColor(this.color));
newds.averageOf = this;
this.averageDataSet = newds;
this.averageInterval = avginterval;
return newds;
},
// create a new dataset with this ds's data,
// relative to otherds
createRelativeTo: function (otherds, absval) {
if (otherds == this) {
log("error, same ds");
return null;
}
for each (var s in this.relativeToSets) {
if (s.relativeTo == otherds)
return s;
}
var firstTime = this.firstTime;
var lastTime = this.lastTime;
if (otherds.firstTime > firstTime)
firstTime = otherds.firstTime;
if (otherds.lastTime < lastTime)
lastTime = otherds.lastTime;
var newdata = [];
var thisidx = this.indicesForTimeRange (firstTime, lastTime);
var otheridx = this.indicesForTimeRange (firstTime, lastTime);
var o = otheridx[0];
var ov, ov1, ov2, ot1, ot2;
for (var i = thisidx[0]; i < thisidx[1]; i++) {
var t = this.data[i*2];
var tv = this.data[i*2+1];
while (otherds.data[o*2] < t)
o++;
ot1 = otherds.data[o*2];
ov1 = otherds.data[o*2+1];
if (o < otheridx[1]) {
ot2 = otherds.data[o*2+2];
ov2 = otherds.data[o*2+3];
} else {
ot2 = ot1;
ov2 = ov1;
}
var d = (t-ot1)/(ot2-ot1);
ov = (1-d) * ov1 + d * ov2;
newdata.push(t);
//log ("i", i, "tv", tv, "ov", ov, "t", t, "ot1", ot1, "ot2", ot2, "ov1", ov1, "ov2", ov2);
//log ("i", i, "tv", tv, "ov", ov, "tv/ov", tv/ov, "ov/tv", ov/tv);
if (absval) {
newdata.push(tv-ov);
} else {
if (tv > ov)
newdata.push((tv/ov) - 1);
else
newdata.push(-((ov/tv) - 1));
}
}
var newds = new TimeValueDataSet(newdata, this.color);
newds.relativeTo = otherds;
this.relativeToSets.push(newds);
return newds;
},
};
function TimeStringDataSet(data) {
this.data = data;
}
TimeStringDataSet.prototype = {
__proto__: new TimeDataSet(),
data: null,
onDataSetChanged: null,
init: function () {
},
addString: function (time, string) {
},
removeStringAt: function (index) {
},
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,192 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var GraphFormModules = [];
var GraphFormModuleCount = 0;
function GraphFormModule(userConfig) {
GraphFormModuleCount++;
this.__proto__.__proto__.constructor.call(this, "graphForm" + GraphFormModuleCount, userConfig);
}
GraphFormModule.prototype = {
__proto__: new YAHOO.widget.Module(),
imageRoot: "",
testId: null,
baseline: false,
average: false,
color: "#000000",
onLoadingDone : new YAHOO.util.CustomEvent("onloadingdone"),
onLoading : new YAHOO.util.CustomEvent("onloading"),
init: function (el, userConfig) {
var self = this;
this.__proto__.__proto__.init.call(this, el/*, userConfig*/);
this.cfg = new YAHOO.util.Config(this);
this.cfg.addProperty("testid", { suppressEvent: true });
this.cfg.addProperty("average", { suppressEvent: true });
this.cfg.addProperty("baseline", { suppressEvent: true });
if (userConfig)
this.cfg.applyConfig(userConfig, true);
var form, td, el;
form = new DIV({ class: "graphform-line" });
td = new SPAN();
/*
el = new IMG({ src: "js/img/plus.png", class: "plusminus",
onclick: function(event) { addGraphForm(); } });
td.appendChild(el);
*/
el = new IMG({ src: "js/img/minus.png", class: "plusminus",
onclick: function(event) { self.remove(); } });
td.appendChild(el);
form.appendChild(td);
td = new SPAN();
el = new DIV({ id: "whee", style: "display: inline; border: 1px solid black; height: 15; " +
"padding-right: 15; vertical-align: middle; margin: 3px;" });
this.colorDiv = el;
td.appendChild(el);
form.appendChild(td);
td = new SPAN();
el = new SELECT({ name: "testname",
class: "testname",
onchange: function(event) { self.onChangeTest(); } });
this.testSelect = el;
td.appendChild(el);
form.appendChild(td);
td = new SPAN({ style: "padding-left: 10px;"});
appendChildNodes(td, "Average:");
el = new INPUT({ name: "average",
type: "checkbox",
onchange: function(event) { self.average = event.target.checked; } });
this.averageCheckbox = el;
td.appendChild(el);
form.appendChild(td);
this.setBody (form);
var forceTestId = null;
this.average = false;
if (userConfig) {
forceTestId = this.cfg.getProperty("testid");
avg = this.cfg.getProperty("average");
baseline = this.cfg.getProperty("baseline");
if (avg == 1) {
this.averageCheckbox.checked = true;
this.average = true;
}
if (baseline == 1)
this.onBaseLineRadioClick();
}
Tinderbox.requestTestList(function (tests) {
var opts = [];
// let's sort by machine name
var sortedTests = Array.sort(tests, function (a, b) {
if (a.machine < b.machine) return -1;
if (a.machine > b.machine) return 1;
if (a.test < b.test) return -1;
if (a.test > b.test) return 1;
if (a.test_type < b.test_type) return -1;
if (a.test_type > b.test_type) return 1;
return 0;
});
for each (var test in sortedTests) {
var tstr = test.machine + " - " + test.test + " - " + test.branch;
opts.push(new OPTION({ value: test.id }, tstr));
}
replaceChildNodes(self.testSelect, opts);
if (forceTestId != null) {
self.testSelect.value = forceTestId;
} else {
self.testSelect.value = sortedTests[0].id;
}
setTimeout(function () { self.onChangeTest(forceTestId); }, 0);
self.onLoadingDone.fire();
});
GraphFormModules.push(this);
},
getQueryString: function (prefix) {
return prefix + "tid=" + this.testId + "&" + prefix + "bl=" + (this.baseline ? "1" : "0")
+ "&" + prefix + "avg=" + (this.average? "1" : "0");
},
getDumpString: function () {
return "setid=" + this.testId;
},
onChangeTest: function (forceTestId) {
this.testId = this.testSelect.value;
},
onBaseLineRadioClick: function () {
GraphFormModules.forEach(function (g) { g.baseline = false; });
this.baseline = true;
},
setColor: function (newcolor) {
this.color = newcolor;
this.colorDiv.style.backgroundColor = colorToRgbString(newcolor);
},
remove: function () {
if (GraphFormModules.length == 1)
return;
var nf = [];
for each (var f in GraphFormModules) {
if (f != this)
nf.push(f);
}
GraphFormModules = nf;
this.destroy();
},
};

View File

@@ -1,161 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Jeremiah Orem <oremj@oremj.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function ResizeGraph() {
}
ResizeGraph.prototype = {
margin_right: 25,
margin_bottom: 25,
resizing: false,
active: false,
element: null,
handle: null,
startX: null,
startY: null,
startHeight: null,
startWidth: null,
startTop: null,
startLeft: null,
currentDirection: '',
init: function(elem) {
this.handle = elem;
this.element = getElement(elem);
connect(this.handle,'onmousedown',this, 'mouseDownFunc');
connect(document,'onmouseup',this, 'mouseUpFunc');
connect(this.handle,'onmousemove',this, 'mouseMoveFunc');
connect(document,'onmousemove',this, 'updateElement');
},
directions: function(e) {
var pointer = e.mouse();
var graphPosition = elementPosition(this.handle);
var dimensions = elementDimensions(this.handle);
var dir = '';
if ( pointer.page.x > (graphPosition.x + dimensions.w) - this.margin_right ) {
dir= "e";
}
else if ( pointer.page.y > (graphPosition.y + dimensions.h) - this.margin_bottom ) {
dir = "s";
}
return dir;
},
draw: function(e) {
var pointer = [e.mouse().page.x, e.mouse().page.y];
var style = this.element.style;
if (this.currentDirection.indexOf('s') != -1) {
var newHeight = this.startHeight + pointer[1] - this.startY;
if (newHeight > this.margin_bottom) {
style.height = newHeight + "px";
this.element.height = newHeight;
}
}
if (this.currentDirection.indexOf('e') != -1) {
var newWidth = this.startWidth + pointer[0] - this.startX;
if (newWidth > this.margin_right) {
if (newWidth > 900) {
getElement('graph-container').style.width = (newWidth + 200) + "px";
}
style.width = newWidth + "px";
this.element.width = newWidth;
}
}
},
mouseDownFunc: function(e)
{
var dir = this.directions(e);
pointer = e.mouse();
if (dir.length > 0 ) {
this.active = true;
var dimensions = elementDimensions(this.handle);
var graphPosition = elementPosition(this.handle);
this.startTop = graphPosition.y;
this.startLeft = graphPosition.x;
this.startHeight = dimensions.h;
this.startWidth = dimensions.w;
this.startX = pointer.page.x + document.body.scrollLeft + document.documentElement.scrollLeft;
this.startY = pointer.page.y + document.body.scrollLeft + document.documentElement.scrollLeft;
this.currentDirection = dir;
e.stop();
}
},
mouseMoveFunc: function(e)
{
pointer = e.mouse();
graphPosition = elementPosition(this.handle);
dimensions = elementDimensions(this.handle);
dir = this.directions(e);
if(dir.length > 0) {
getElement(this.handle).style.cursor = dir + "-resize";
}
else {
getElement(this.handle).style.cursor = '';
}
},
updateElement: function(e)
{
if( this.active ) {
if ( ! this.resizing ) {
var style = getElement(this.handle).style;
this.resizing = true;
style.position = "relative";
}
this.draw(e);
e.stop()
return false;
}
},
finishResize: function(e,success) {
this.active = false;
this.resizing = false;
},
mouseUpFunc: function(e)
{
if(this.active && this.resizing) {
this.finishResize(e,true);
BigPerfGraph.resize();
e.stop();
}
this.active = false;
this.resizing = false;
},
};

View File

@@ -1,417 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
* Alice Nodelman <anodelman@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//const getdatacgi = "getdata-fake.cgi?";
//const getdatacgi = "http://localhost:9050/getdata.cgi?";
const getdatacgi = "getdata.cgi?"
function checkErrorReturn(obj) {
if (!obj || obj.resultcode != 0) {
alert ("Error: " + (obj ? (obj.error + "(" + obj.resultcode + ")") : "(nil)"));
return false;
}
return true;
}
function TinderboxData() {
this.onTestListAvailable = new YAHOO.util.CustomEvent("testlistavailable");
this.onDataSetAvailable = new YAHOO.util.CustomEvent("datasetavailable");
this.testList = null;
this.testData = {};
}
TinderboxData.prototype = {
testList: null,
testData: null,
onTestListAvailable: null,
onDataSetAvailable: null,
defaultLoadRange: null,
raw: 0,
init: function () {
var self = this;
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
loadJSONDoc(getdatacgi + "type=continuous")
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
self.testList = obj.results;
//log("default test list" + self.testList);
self.onTestListAvailable.fire(self.testList);
},
function () {alert ("Error talking to " + getdatacgi + ""); });
},
requestTestList: function (callback) {
//log("requestTestList default");
var self = this;
if (this.testList != null) {
callback.call (window, this.testList);
} else {
var cb =
function (type, args, obj) {
self.onTestListAvailable.unsubscribe(cb, obj);
obj.call (window, args[0]);
};
this.onTestListAvailable.subscribe (cb, callback);
}
},
// arg1 = startTime, arg2 = endTime, arg3 = callback
// arg1 = callback, arg2/arg3 == null
requestDataSetFor: function (testId, arg1, arg2, arg3) {
var self = this;
var startTime = arg1;
var endTime = arg2;
var callback = arg3;
if (arg1 && arg2 == null && arg3 == null) {
callback = arg1;
if (this.defaultLoadRange) {
startTime = this.defaultLoadRange[0];
endTime = this.defaultLoadRange[1];
//log ("load range using default", startTime, endTime);
} else {
startTime = null;
endTime = null;
}
}
if (testId in this.testData) {
var ds = this.testData[testId];
//log ("Can maybe use cached?");
if ((ds.requestedFirstTime == null && ds.requestedLastTime == null) ||
(ds.requestedFirstTime <= startTime &&
ds.requestedLastTime >= endTime))
{
//log ("Using cached ds");
callback.call (window, testId, ds);
return;
}
// this can be optimized, if we request just the bookend bits,
// but that's overkill
if (ds.firstTime < startTime)
startTime = ds.firstTime;
if (ds.lastTime > endTime)
endTime = ds.lastTime;
}
var cb =
function (type, args, obj) {
if (args[0] != testId ||
args[2] > startTime ||
args[3] < endTime)
{
// not useful for us; there's another
// outstanding request for our time range, so wait for that
return;
}
self.onDataSetAvailable.unsubscribe(cb, obj);
obj.call (window, args[0], args[1]);
};
this.onDataSetAvailable.subscribe (cb, callback);
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
var reqstr = getdatacgi + "setid=" + testId;
if (startTime)
reqstr += "&starttime=" + startTime;
if (endTime)
reqstr += "&endtime=" + endTime;
//raw data is the extra_data column
if (this.raw)
reqstr += "&raw=1";
//log (reqstr);
loadJSONDoc(reqstr)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
var ds = new TimeValueDataSet(obj.results);
//this is the the case of a discrete graph - where the entire test run is always requested
//so the start and end points are the first and last entries in the returned data set
if (!startTime && !endTime) {
startTime = ds.data[0];
endTime = ds.data[ds.data.length -2];
}
ds.requestedFirstTime = startTime;
ds.requestedLastTime = endTime;
self.testData[testId] = ds;
if (obj.annotations)
ds.annotations = new TimeStringDataSet(obj.annotations);
if (obj.baselines)
ds.baselines = obj.baselines;
if (obj.rawdata)
ds.rawdata = obj.rawdata;
if (obj.stats)
ds.stats = obj.stats;
self.onDataSetAvailable.fire(testId, ds, startTime, endTime);
},
function (obj) {alert ("Error talking to " + getdatacgi + " (" + obj + ")"); log (obj.stack); });
},
clearValueDataSets: function () {
//log ("clearvalueDatasets");
this.tinderboxTestData = {};
},
};
function DiscreteTinderboxData() {
};
DiscreteTinderboxData.prototype = {
__proto__: new TinderboxData(),
init: function () {
},
requestTestList: function (limitDate, branch, machine, testname, callback) {
var self = this;
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
var limiters = "";
var tDate = 0;
if (limitDate != null) {
tDate = new Date().getTime();
tDate -= limitDate * 86400 * 1000;
//log ("returning test lists greater than this date" + (new Date(tDate)).toGMTString());
//TODO hack hack hack
tDate = Math.floor(tDate/1000)
}
if (branch != null) limiters += "&branch=" + branch;
if (machine != null) limiters += "&machine=" + machine;
if (testname != null) limiters += "&test=" + testname;
//log("drequestTestList: " + getdatacgi + "type=discrete&datelimit=" + tDate + limiters);
loadJSONDoc(getdatacgi + "type=discrete&datelimit=" + tDate + limiters)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
self.testList = obj.results;
//log ("testlist: " + self.testList);
callback.call(window, self.testList);
},
function () {alert ("requestTestList: Error talking to " + getdatacgi + ""); });
},
requestSearchList: function (branch, machine, testname, callback) {
var self = this;
limiters = "";
if (branch != null) limiters += "&branch=" + branch;
if (machine != null) limiters += "&machine=" + machine;
if (testname != null) limiters += "&test=" + testname;
//log(getdatacgi + "getlist=1&type=discrete" + limiters);
loadJSONDoc(getdatacgi + "getlist=1&type=discrete" + limiters)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
callback.call(window, obj.results);
},
function () {alert ("requestSearchList: Error talking to " + getdatacgi); });
},
};
function ExtraDataTinderboxData() {
};
ExtraDataTinderboxData.prototype = {
__proto__: new TinderboxData(),
init: function () {
},
requestTestList: function (limitDate, branch, machine, testname, callback) {
var self = this;
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
var limiters = "";
var tDate = 0;
if (limitDate != null) {
tDate = new Date().getTime();
tDate -= limitDate * 86400 * 1000;
//log ("returning test lists greater than this date" + (new Date(tDate)).toGMTString());
//TODO hack hack hack
tDate = Math.floor(tDate/1000)
}
if (branch != null) limiters += "&branch=" + branch;
if (machine != null) limiters += "&machine=" + machine;
if (testname != null) limiters += "&test=" + testname;
//log("drequestTestList: " + getdatacgi + "type=discrete&datelimit=" + tDate + limiters);
loadJSONDoc(getdatacgi + "type=discrete&graphby=bydata&datelimit=" + tDate + limiters)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
self.testList = obj.results;
//log ("testlist: " + self.testList);
callback.call(window, self.testList);
},
function () {alert ("requestTestList: Error talking to " + getdatacgi + ""); });
},
requestSearchList: function (branch, machine, testname, callback) {
var self = this;
limiters = "";
if (branch != null) limiters += "&branch=" + branch;
if (machine != null) limiters += "&machine=" + machine;
if (testname != null) limiters += "&test=" + testname;
//log(getdatacgi + "getlist=1&type=discrete" + limiters);
loadJSONDoc(getdatacgi + "getlist=1&type=discrete" + limiters)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
callback.call(window, obj.results);
},
function () {alert ("requestSearchList: Error talking to " + getdatacgi); });
},
// arg1 = startTime, arg2 = endTime, arg3 = callback
// arg1 = callback, arg2/arg3 == null
requestDataSetFor: function (testId, arg1, arg2, arg3) {
var self = this;
var startTime = arg1;
var endTime = arg2;
var callback = arg3;
var tempArray = new Array();
tempArray = testId.split("_",2);
testId = tempArray[0];
var extradata = tempArray[1];
if (arg1 && arg2 == null && arg3 == null) {
callback = arg1;
if (this.defaultLoadRange) {
startTime = this.defaultLoadRange[0];
endTime = this.defaultLoadRange[1];
//log ("load range using default", startTime, endTime);
} else {
startTime = null;
endTime = null;
}
}
if (testId in this.testData) {
var ds = this.testData[testId];
//log ("Can maybe use cached?");
if ((ds.requestedFirstTime == null && ds.requestedLastTime == null) ||
(ds.requestedFirstTime <= startTime &&
ds.requestedLastTime >= endTime))
{
//log ("Using cached ds");
callback.call (window, testId, ds);
return;
}
// this can be optimized, if we request just the bookend bits,
// but that's overkill
if (ds.firstTime < startTime)
startTime = ds.firstTime;
if (ds.lastTime > endTime)
endTime = ds.lastTime;
}
var cb =
function (type, args, obj) {
if (args[0] != testId ||
args[2] > startTime ||
args[3] < endTime)
{
// not useful for us; there's another
// outstanding request for our time range, so wait for that
return;
}
self.onDataSetAvailable.unsubscribe(cb, obj);
obj.call (window, args[0], args[1]);
};
this.onDataSetAvailable.subscribe (cb, callback);
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
var reqstr = getdatacgi + "setid=" + testId;
if (startTime)
reqstr += "&starttime=" + startTime;
if (endTime)
reqstr += "&endtime=" + endTime;
//raw data is the extra_data column
if (this.raw)
reqstr += "&raw=1";
reqstr += "&graphby=bydata";
reqstr += "&extradata=" + extradata;
//log (reqstr);
loadJSONDoc(reqstr)
.addCallbacks(
function (obj) {
if (!checkErrorReturn(obj)) return;
var ds = new TimeValueDataSet(obj.results);
//this is the the case of a discrete graph - where the entire test run is always requested
//so the start and end points are the first and last entries in the returned data set
if (!startTime && !endTime) {
startTime = ds.data[0];
endTime = ds.data[ds.data.length -2];
}
ds.requestedFirstTime = startTime;
ds.requestedLastTime = endTime;
self.testData[testId] = ds;
if (obj.annotations)
ds.annotations = new TimeStringDataSet(obj.annotations);
if (obj.baselines)
ds.baselines = obj.baselines;
if (obj.rawdata)
ds.rawdata = obj.rawdata;
if (obj.stats)
ds.stats = obj.stats;
self.onDataSetAvailable.fire(testId, ds, startTime, endTime);
},
function (obj) {alert ("Error talking to " + getdatacgi + " (" + obj + ")"); log (obj.stack); });
},
};

View File

@@ -1,381 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
* Alice Nodelman <anodelman@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var GraphFormModules = [];
var GraphFormModuleCount = 0;
function DiscreteGraphFormModule(userConfig, userName) {
GraphFormModuleCount++;
//log("userName: " + userName);
//this.__proto__.__proto__.constructor.call(this, "graphForm" + GraphFormModuleCount, userConfig, userName);
this.init("graphForm" + GraphFormModuleCount, userConfig, userName);
}
DiscreteGraphFormModule.prototype = {
__proto__: new YAHOO.widget.Module(),
imageRoot: "",
testId: null,
testIds: null,
testText: "",
baseline: false,
average: false,
name: "",
limitDays: null,
isLimit: null,
onLoadingDone : new YAHOO.util.CustomEvent("onloadingdone"),
onLoading : new YAHOO.util.CustomEvent("onloading"),
addedInitialInfo : new YAHOO.util.CustomEvent("addedinitialinfo"),
init: function (el, userConfig, userName) {
var self = this;
//log("el " + el + " userConfig " + userConfig + " userName " + userName);
this.__proto__.__proto__.init.call(this, el/*, userConfig*/);
this.cfg = new YAHOO.util.Config(this);
this.cfg.addProperty("testid", { suppressEvent: true });
this.cfg.addProperty("average", { suppressEvent: true });
this.cfg.addProperty("baseline", { suppressEvent: true });
if (userConfig)
this.cfg.applyConfig(userConfig, true);
var form, td, el;
var tbl;
var tbl_row;
var tbl_col;
tbl = new TABLE({});
tbl_row = new TR({});
tbl_col = new TD({colspan: 2});
appendChildNodes(tbl_col,"Limit selection list by:");
appendChildNodes(tbl_row, tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col,"Choose test(s) to graph:");
appendChildNodes(tbl_row, tbl_col);
tbl.appendChild(tbl_row);
tbl_row = new TR({});
form = new DIV({ class: "graphform-line" });
tbl_col = new TD({});
el = new INPUT({ name: "dataload" + GraphFormModules.length,
id: "all-days-radio",
type: "radio",
checked: 1,
onchange: function(event) { self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
tbl_col.appendChild(el);
appendChildNodes(tbl_col, "all tests");
tbl_col.appendChild(new DIV({}));
el = new INPUT({ name: "dataload" + GraphFormModules.length,
type: "radio",
onchange: function(event) { self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);} });
this.isLimit = el;
tbl_col.appendChild(el);
appendChildNodes(tbl_col, "previous ");
el = new INPUT({ name: "load-days-entry",
id: "load-days-entry",
type: "text",
size: "3",
value: "5",
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);} } });
this.limitDays = el;
tbl_col.appendChild(el);
appendChildNodes(tbl_col, " days");
tbl_row.appendChild(tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col, "Branch: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "branchname",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.branchSelect = el;
Tinderbox.requestSearchList(1, null, null, function (list) {
var opts = [];
opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
replaceChildNodes(self.branchSelect, opts);
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl_col = new TD({rowspan: 2, colspan: 2});
span = new SPAN({id: "listname"});
appendChildNodes(tbl_col, span);
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "testname",
class: "testname",
multiple: true,
center: true,
size: 20,
onchange: function(event) { self.onChangeTest(); } });
this.testSelect = el;
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl.appendChild(tbl_row);
tbl_row = new TR({});
tbl_col = new TD({});
appendChildNodes(tbl_col, "Machine: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "machinename",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.machineSelect = el;
Tinderbox.requestSearchList(null, 1, null, function (list) {
var opts = [];
opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
replaceChildNodes(self.machineSelect, opts);
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col, "Test name: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "testtypename",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.testtypeSelect = el;
var forceTestIds = null;
this.average = false;
if (userConfig) {
forceTestIds = userConfig;
}
//log ("userName: " + userName);
Tinderbox.requestSearchList(null, null, 1, function (list) {
var opts = [];
//opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
if ((userName) && (userName == listvalue.value)) {
opts.push(new OPTION({ value: listvalue.value, selected : true}, listvalue.value));
}
else {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
}
replaceChildNodes(self.testtypeSelect, opts);
if (forceTestIds == null) {
self.testtypeSelect.options[0].selected = true;
self.update(null, null, null, self.testtypeSelect.value, forceTestIds);
}
else {
self.update(null, null, null, userName, forceTestIds);
}
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
/*
tbl_col = new TD({rowspan: 2, colspan: 2});
el = new SELECT({ name: "testname",
class: "testname",
multiple: true,
size: 20,
onchange: function(event) { self.onChangeTest(); } });
this.testSelect = el;
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
*/
tbl.appendChild(tbl_row);
form.appendChild(tbl);
this.setBody (form);
/*
var forceTestIds = null;
this.average = false;
if (userConfig) {
forceTestIds = userConfig;
}
*/
//self.update(null, null, null, null, forceTestIds);
GraphFormModules.push(this);
},
getQueryString: function (prefix) {
var qstring = '';
ctr = 1;
for each (var opt in this.testSelect.options) {
if (opt.selected) {
prefixed = prefix + ctr;
qstring += "&" + prefixed + "tid=" + opt.value + "&" + prefixed + "bl=" + (this.baseline ? "1" : "0")
+ "&" + prefixed + "avg=" + (this.average? "1" : "0");
ctr++
}
}
return qstring;
},
getDumpString: function () {
var prefix = '';
var dstring = '';
for each (var opt in this.testSelect.options) {
if (opt.selected) {
dstring += prefix + "setid=" + opt.value;
prefix = "&";
}
}
return dstring;
},
onChangeTest: function (forceTestIds) {
this.testId = this.testSelect.value;
//log("setting testId: " + this.testId);
this.testIds = [];
for each (var opt in this.testSelect.options) {
if (opt.selected) {
//log("opt: " + opt.value);
this.testIds.push([opt.value, opt.text]);
}
}
//log("testIDs: " + this.testIds);
//log(this.testSelect.options[this.testSelect.selectedIndex].text);
this.testText = this.testSelect.options[this.testSelect.selectedIndex];
this.addedInitialInfo.fire();
this.name = this.testtypeSelect.value;
},
onBaseLineRadioClick: function () {
GraphFormModules.forEach(function (g) { g.baseline = false; });
this.baseline = true;
},
remove: function () {
var nf = [];
for each (var f in GraphFormModules) {
if (f != this)
nf.push(f);
}
GraphFormModules = nf;
this.destroy();
},
update: function (limitD, branch, machine, testname, forceTestIds) {
var self = this;
this.onLoading.fire("updating test list");
//log ("attempting to update graphformmodule, forceTestIds " + forceTestIds);
Tinderbox.requestTestList(limitD, branch, machine, testname, function (tests) {
var opts = [];
var branch_opts = [];
if (tests == '') {
log("empty test list");
self.onLoadingDone.fire();
replaceChildNodes(self.testSelect, null);
btn = getElement("graphbutton");
btn.disabled = true;
return;
}
// let's sort by machine name
var sortedTests = Array.sort(tests, function (a, b) {
if (a.machine < b.machine) return -1;
if (a.machine > b.machine) return 1;
if (a.test < b.test) return -1;
if (a.test > b.test) return 1;
if (a.test_type < b.test_type) return -1;
if (a.test_type > b.test_type) return 1;
if (a.date < b.date) return -1;
if (a.date > b.date) return 1;
return 0;
});
for each (var test in sortedTests) {
var d = new Date(test.date*1000);
var s1 = (d.getHours() < 10 ? "0" : "") + d.getHours() + (d.getMinutes() < 10 ? ":0" : ":") + d.getMinutes() +
//(d.getSeconds() < 10 ? ":0" : ":") + d.getSeconds() +
" " + (d.getDate() < 10 ? "0" : "") + d.getDate();
s1 += "/" + MONTH_ABBREV[d.getMonth()] + "/" + (d.getFullYear() -2000 < 10 ? "0" : "") + (d.getFullYear() - 2000);
//(d.getYear() + 1900);
var padstr = "--------------------";
var tstr = "" + //test.test + padstr.substr(0, 20-test.test.length) +
test.branch.toString() + padstr.substr(0, 6-test.branch.toString().length) +
"-" + test.machine + padstr.substr(0, 10-test.machine.length) +
"-" + s1;
startSelected = false;
if (forceTestIds != null) {
if ((forceTestIds == test.id) || (forceTestIds.indexOf(Number(test.id)) > -1)) {
startSelected = true;
}
}
if (startSelected) {
//log("starting with an initial selection");
opts.push(new OPTION({ value: test.id, selected: true}, tstr));
}
else {
opts.push(new OPTION({ value: test.id}, tstr));
}
}
replaceChildNodes(self.testSelect, opts);
if (forceTestIds == null) {
self.testSelect.options[0].selected = true;
//self.testSelect.value = sortedTests[0].id;
}
replaceChildNodes("listname", null);
appendChildNodes("listname","Select from " + testname + ":");
btn = getElement("graphbutton");
btn.disabled = false;
setTimeout(function () { self.onChangeTest(forceTestIds); }, 0);
self.onLoadingDone.fire();
});
},
};

View File

@@ -1,376 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
* Alice Nodelman <anodelman@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var GraphFormModules = [];
var GraphFormModuleCount = 0;
function ExtraDataGraphFormModule(userConfig, userName) {
GraphFormModuleCount++;
//log("userName: " + userName);
//this.__proto__.__proto__.constructor.call(this, "graphForm" + GraphFormModuleCount, userConfig, userName);
this.init("graphForm" + GraphFormModuleCount, userConfig, userName);
}
ExtraDataGraphFormModule.prototype = {
__proto__: new YAHOO.widget.Module(),
imageRoot: "",
testId: null,
testIds: null,
testText: "",
baseline: false,
average: false,
name: "",
limitDays: null,
isLimit: null,
onLoadingDone : new YAHOO.util.CustomEvent("onloadingdone"),
onLoading : new YAHOO.util.CustomEvent("onloading"),
addedInitialInfo : new YAHOO.util.CustomEvent("addedinitialinfo"),
init: function (el, userConfig, userName) {
var self = this;
//log("el " + el + " userConfig " + userConfig + " userName " + userName);
this.__proto__.__proto__.init.call(this, el/*, userConfig*/);
this.cfg = new YAHOO.util.Config(this);
this.cfg.addProperty("testid", { suppressEvent: true });
this.cfg.addProperty("average", { suppressEvent: true });
this.cfg.addProperty("baseline", { suppressEvent: true });
if (userConfig)
this.cfg.applyConfig(userConfig, true);
var form, td, el;
var tbl;
var tbl_row;
var tbl_col;
tbl = new TABLE({});
tbl_row = new TR({});
tbl_col = new TD({colspan: 2});
appendChildNodes(tbl_col,"Limit selection list by:");
appendChildNodes(tbl_row, tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col,"Choose test(s) to graph:");
appendChildNodes(tbl_row, tbl_col);
tbl.appendChild(tbl_row);
tbl_row = new TR({});
form = new DIV({ class: "graphform-line" });
tbl_col = new TD({});
el = new INPUT({ name: "dataload" + GraphFormModules.length,
id: "all-days-radio",
type: "radio",
checked: 1,
onchange: function(event) { self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
tbl_col.appendChild(el);
appendChildNodes(tbl_col, "all tests");
tbl_col.appendChild(new DIV({}));
el = new INPUT({ name: "dataload" + GraphFormModules.length,
type: "radio",
onchange: function(event) { self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);} });
this.isLimit = el;
tbl_col.appendChild(el);
appendChildNodes(tbl_col, "previous ");
el = new INPUT({ name: "load-days-entry",
id: "load-days-entry",
type: "text",
size: "3",
value: "5",
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);} } });
this.limitDays = el;
tbl_col.appendChild(el);
appendChildNodes(tbl_col, " days");
tbl_row.appendChild(tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col, "Branch: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "branchname",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.branchSelect = el;
Tinderbox.requestSearchList(1, null, null, function (list) {
var opts = [];
opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
replaceChildNodes(self.branchSelect, opts);
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl_col = new TD({rowspan: 2, colspan: 2});
span = new SPAN({id: "listname"});
appendChildNodes(tbl_col, span);
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "testname",
class: "testname",
multiple: true,
center: true,
size: 20,
onchange: function(event) { self.onChangeTest(); } });
this.testSelect = el;
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl.appendChild(tbl_row);
tbl_row = new TR({});
tbl_col = new TD({});
appendChildNodes(tbl_col, "Machine: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "machinename",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.machineSelect = el;
Tinderbox.requestSearchList(null, 1, null, function (list) {
var opts = [];
opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
replaceChildNodes(self.machineSelect, opts);
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
tbl_col = new TD({});
appendChildNodes(tbl_col, "Test name: ");
appendChildNodes(tbl_col, new BR({}));
el = new SELECT({ name: "testtypename",
class: "other",
size: 5,
onchange: function(event) { if (self.isLimit.checked) {
self.update(self.limitDays.value, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value);}
else self.update(null, self.branchSelect.value, self.machineSelect.value, self.testtypeSelect.value); } });
this.testtypeSelect = el;
var forceTestIds = null;
this.average = false;
if (userConfig) {
forceTestIds = userConfig;
}
//log ("userName: " + userName);
Tinderbox.requestSearchList(null, null, 1, function (list) {
var opts = [];
//opts.push(new OPTION({value: null, selected: true}, "all"));
for each (var listvalue in list) {
if ((userName) && (userName == listvalue.value)) {
opts.push(new OPTION({ value: listvalue.value, selected : true}, listvalue.value));
}
else {
opts.push(new OPTION({ value: listvalue.value}, listvalue.value));
}
}
replaceChildNodes(self.testtypeSelect, opts);
if (forceTestIds == null) {
self.testtypeSelect.options[0].selected = true;
self.update(null, null, null, self.testtypeSelect.value, forceTestIds);
}
else {
self.update(null, null, null, userName, forceTestIds);
}
});
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
/*
tbl_col = new TD({rowspan: 2, colspan: 2});
el = new SELECT({ name: "testname",
class: "testname",
multiple: true,
size: 20,
onchange: function(event) { self.onChangeTest(); } });
this.testSelect = el;
tbl_col.appendChild(el);
tbl_row.appendChild(tbl_col);
*/
tbl.appendChild(tbl_row);
form.appendChild(tbl);
this.setBody (form);
/*
var forceTestIds = null;
this.average = false;
if (userConfig) {
forceTestIds = userConfig;
}
*/
//self.update(null, null, null, null, forceTestIds);
GraphFormModules.push(this);
},
getQueryString: function (prefix) {
var qstring = '';
ctr = 1;
for each (var opt in this.testSelect.options) {
if (opt.selected) {
prefixed = prefix + ctr;
qstring += "&" + prefixed + "tid=" + opt.value + "&" + prefixed + "bl=" + (this.baseline ? "1" : "0")
+ "&" + prefixed + "avg=" + (this.average? "1" : "0");
ctr++
}
}
return qstring;
},
getDumpString: function () {
var prefix = '';
var dstring = '';
for each (var opt in this.testSelect.options) {
if (opt.selected) {
dstring += prefix + "setid=" + opt.value;
prefix = "&";
}
}
return dstring;
},
onChangeTest: function (forceTestIds) {
this.testId = this.testSelect.value;
//log("setting testId: " + this.testId);
this.testIds = [];
for each (var opt in this.testSelect.options) {
if (opt.selected) {
//log("opt: " + opt.value);
this.testIds.push([opt.value, opt.text]);
}
}
//log("testIDs: " + this.testIds);
//log(this.testSelect.options[this.testSelect.selectedIndex].text);
this.testText = this.testSelect.options[this.testSelect.selectedIndex];
this.addedInitialInfo.fire();
this.name = this.testtypeSelect.value;
},
onBaseLineRadioClick: function () {
GraphFormModules.forEach(function (g) { g.baseline = false; });
this.baseline = true;
},
remove: function () {
var nf = [];
for each (var f in GraphFormModules) {
if (f != this)
nf.push(f);
}
GraphFormModules = nf;
this.destroy();
},
update: function (limitD, branch, machine, testname, forceTestIds) {
var self = this;
this.onLoading.fire("updating test list");
//log ("attempting to update graphformmodule, forceTestIds " + forceTestIds);
Tinderbox.requestTestList(limitD, branch, machine, testname, function (tests) {
var opts = [];
var branch_opts = [];
if (tests == '') {
log("empty test list");
self.onLoadingDone.fire();
replaceChildNodes(self.testSelect, null);
btn = getElement("graphbutton");
btn.disabled = true;
return;
}
// let's sort by machine name
var sortedTests = Array.sort(tests, function (a, b) {
if (a.machine < b.machine) return -1;
if (a.machine > b.machine) return 1;
if (a.test < b.test) return -1;
if (a.test > b.test) return 1;
if (a.test_type < b.test_type) return -1;
if (a.test_type > b.test_type) return 1;
if (a.data < b.data) return -1;
if (a.data > b.data) return 1;
return 0;
});
for each (var test in sortedTests) {
var s1 = test.data;
var padstr = "--------------------";
var tstr = "" + //test.test + padstr.substr(0, 20-test.test.length) +
test.branch.toString() + padstr.substr(0, 6-test.branch.toString().length) +
"-" + test.machine + padstr.substr(0, 10-test.machine.length) +
"-" + s1;
startSelected = false;
if (forceTestIds != null) {
if ((forceTestIds == test.id) || (forceTestIds.indexOf(Number(test.id)) > -1)) {
startSelected = true;
}
}
if (startSelected) {
//log("starting with an initial selection");
opts.push(new OPTION({ value: test.id + "_" + test.data, selected: true}, tstr));
}
else {
opts.push(new OPTION({ value: test.id + "_" + test.data}, tstr));
}
}
replaceChildNodes(self.testSelect, opts);
if (forceTestIds == null) {
self.testSelect.options[0].selected = true;
//self.testSelect.value = sortedTests[0].id;
}
replaceChildNodes("listname", null);
appendChildNodes("listname","Select from " + testname + ":");
btn = getElement("graphbutton");
btn.disabled = false;
setTimeout(function () { self.onChangeTest(forceTestIds); }, 0);
self.onLoadingDone.fire();
});
},
};

View File

@@ -1,87 +0,0 @@
.graphconfig {
background-color: #cccccc;
-moz-border-radius: 10px 0 0 10px;
padding: 10px;
width: 15em;
}
.dgraphconfig {
background-color: #cccccc;
-moz-border-radius: 10px 0 0 10px;
padding: 10px;
width: 7em;
}
.graphconfig-list {
background-color: #cccccc;
-moz-border-radius: 0 10px 10px 0;
padding: 10px;
}
/* Yuck */
.graphform-line, .baseline {
margin-bottom: 5px;
}
.graphform-first-span {
/* font-weight: bold; */
}
/*
#graphforms div .bd .graphform-line .graphform-first-span:after {
content: "For ";
}
.module + .module .bd .graphform-line .graphform-first-span:after {
content: "and " ! important;
}
*/
select.tinderbox, select.testname {
font-family: monospace;
width: 350px;
}
select.other {
font-family: monospace;
width: 225px;
}
.plusminus {
padding: 3px;
vertical-align: middle;
}
.plusminus:hover {
background: #999;
}
.plusminushidden {
width: 20px;
height: 20px;
visibility: hidden;
}
.y-axis-label {
font-family: Tahoma, Verdana, Vera Sans, "Bitstream Vera Sans", Arial, Helvetica, sans-serif;
font-size: 75%;
vertical-align: middle;
text-align: right;
}
.x-axis-label {
font-family: Tahoma, Verdana, Vera Sans, "Bitstream Vera Sans", Arial, Helvetica, sans-serif;
font-size: 75%;
padding: 0px;
vertical-align: top;
text-align: center;
}
.status {
color: blue;
}
/* debug */
/*div { border: 1px solid blue; }*/

View File

@@ -1,661 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is new-graph code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (Original Author)
* Alice Nodelman <anodelman@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// all times are in seconds
const ONE_HOUR_SECONDS = 60*60;
const ONE_DAY_SECONDS = 24*ONE_HOUR_SECONDS;
const ONE_WEEK_SECONDS = 7*ONE_DAY_SECONDS;
const ONE_YEAR_SECONDS = 365*ONE_DAY_SECONDS; // leap years whatever.
const MONTH_ABBREV = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
const CONTINUOUS_GRAPH = 0;
const DISCRETE_GRAPH = 1;
const DATA_GRAPH = 2;
const bonsaicgi = "bonsaibouncer.cgi";
// more days than this and we'll force user confirmation for the bonsai query
const bonsaiNoForceDays = 90;
// the default average interval
var gAverageInterval = 3*ONE_HOUR_SECONDS;
var gCurrentLoadRange = null;
var gForceBonsai = false;
var Tinderbox;
var BigPerfGraph;
var SmallPerfGraph;
var Bonsai;
var graphType;
function loadingDone(graphTypePref) {
//createLoggingPane(true);
graphType = graphTypePref;
if (graphType == CONTINUOUS_GRAPH) {
Tinderbox = new TinderboxData();
SmallPerfGraph = new CalendarTimeGraph("smallgraph");
BigPerfGraph = new CalendarTimeGraph("graph");
onDataLoadChanged();
} else if (graphType == DATA_GRAPH) {
Tinderbox = new ExtraDataTinderboxData();
SmallPerfGraph = new CalendarTimeGraph("smallgraph");
BigPerfGraph = new CalendarTimeGraph("graph");
}
else {
Tinderbox = new DiscreteTinderboxData();
Tinderbox.raw = 1;
SmallPerfGraph = new DiscreteGraph("smallgraph");
BigPerfGraph = new DiscreteGraph("graph");
onDiscreteDataLoadChanged();
}
Tinderbox.init();
if (BonsaiService)
Bonsai = new BonsaiService();
SmallPerfGraph.yLabelHeight = 20;
SmallPerfGraph.setSelectionType("range");
BigPerfGraph.setSelectionType("cursor");
BigPerfGraph.setCursorType("free");
SmallPerfGraph.onSelectionChanged.
subscribe (function (type, args, obj) {
log ("selchanged");
if (args[0] == "range") {
if (args[1] && args[2]) {
var t1 = args[1];
var t2 = args[2];
var foundIndexes = [];
// make sure that there are at least two points
// on at least one graph for this
var foundPoints = false;
var dss = BigPerfGraph.dataSets;
for (var i = 0; i < dss.length; i++) {
var idcs = dss[i].indicesForTimeRange(t1, t2);
if (idcs[1] - idcs[0] > 1) {
foundPoints = true;
break;
}
foundIndexes.push(idcs);
}
if (!foundPoints) {
// we didn't find at least two points in at least
// one graph; so munge the time numbers until we do.
log("Orig t1 " + t1 + " t2 " + t2);
for (var i = 0; i < dss.length; i++) {
if (foundIndexes[i][0] > 0) {
t1 = Math.min(dss[i].data[(foundIndexes[i][0] - 1) * 2], t1);
} else if (foundIndexes[i][1]+1 < (ds.data.length/2)) {
t2 = Math.max(dss[i].data[(foundIndexes[i][1] + 1) * 2], t2);
}
}
log("Fixed t1 " + t1 + " t2 " + t2);
}
BigPerfGraph.setTimeRange (t1, t2);
} else {
BigPerfGraph.setTimeRange (SmallPerfGraph.startTime, SmallPerfGraph.endTime);
}
BigPerfGraph.autoScale();
BigPerfGraph.redraw();
}
updateLinkToThis();
updateDumpToCsv();
});
if (graphType == CONTINUOUS_GRAPH) {
BigPerfGraph.onCursorMoved.
subscribe (function (type, args, obj) {
var time = args[0];
var val = args[1];
if (time != null && val != null) {
// cheat
showStatus("Date: " + formatTime(time) + " Value: " + val.toFixed(2));
} else {
showStatus(null);
}
});
BigPerfGraph.onNewGraph.
subscribe (function(type, args, obj) {
if (args[0].length >= GraphFormModules.length) {
clearLoadingAnimation();
}
});
}
else if (graphType == DATA_GRAPH) {
BigPerfGraph.onCursorMoved.
subscribe (function (type, args, obj) {
var time = args[0];
var val = args[1];
if (time != null && val != null) {
// cheat
showStatus("Date: " + formatTime(time) + " Value: " + val.toFixed(2));
} else {
showStatus(null);
}
});
BigPerfGraph.onNewGraph.
subscribe (function(type, args, obj) {
showGraphList(args[0]);
});
}
else {
BigPerfGraph.onCursorMoved.
subscribe (function (type, args, obj) {
var time = args[0];
var val = args[1];
var extra_data = args[2]
if (time != null && val != null) {
// cheat
showStatus("Interval: " + Math.floor(time) + " Value: " + val.toFixed(2) + " " + extra_data);
} else {
showStatus(null);
}
});
BigPerfGraph.onNewGraph.
subscribe (function(type, args, obj) {
showGraphList(args[0]);
});
}
if (document.location.hash) {
handleHash(document.location.hash);
} else {
if (graphType == CONTINUOUS_GRAPH) {
addGraphForm();
}
else if ( graphType == DATA_GRAPH ) {
addExtraDataGraphForm();
}
else {
addDiscreteGraphForm();
}
}
}
function addExtraDataGraphForm(config, name) {
showLoadingAnimation("populating lists");
var ed = new ExtraDataGraphFormModule(config, name);
ed.onLoading.subscribe (function(type,args,obj) { showLoadingAnimation(args[0]);});
ed.onLoadingDone.subscribe (function(type,args,obj) { clearLoadingAnimation();});
if (config) {
ed.addedInitialInfo.subscribe(function(type,args,obj) { graphInitial();});
}
ed.render (getElement("graphforms"));
return ed;
}
function addDiscreteGraphForm(config, name) {
showLoadingAnimation("populating lists");
//log("name: " + name);
var m = new DiscreteGraphFormModule(config, name);
m.onLoading.subscribe (function(type,args,obj) { showLoadingAnimation(args[0]);});
m.onLoadingDone.subscribe (function(type,args,obj) { clearLoadingAnimation();});
if (config) {
m.addedInitialInfo.subscribe(function(type,args,obj) { graphInitial();});
}
m.render (getElement("graphforms"));
//m.setColor(randomColor());
return m;
}
function addGraphForm(config) {
showLoadingAnimation("populating list");
var m = new GraphFormModule(config);
m.render (getElement("graphforms"));
m.setColor(randomColor());
m.onLoading.subscribe (function(type,args,obj) { showLoadingAnimation(args[0]);});
m.onLoadingDone.subscribe (function(type,args,obj) { clearLoadingAnimation();});
return m;
}
function onNoBaseLineClick() {
GraphFormModules.forEach (function (g) { g.baseline = false; });
}
// whether the bonsai data query should redraw the graph or not
var gReadyForRedraw = true;
function onUpdateBonsai() {
BigPerfGraph.deleteAllMarkers();
getElement("bonsaibutton").disabled = true;
if (gCurrentLoadRange) {
if ((gCurrentLoadRange[1] - gCurrentLoadRange[0]) < (bonsaiNoForceDays * ONE_DAY_SECONDS) || gForceBonsai) {
Bonsai.requestCheckinsBetween (gCurrentLoadRange[0], gCurrentLoadRange[1],
function (bdata) {
for (var i = 0; i < bdata.times.length; i++) {
BigPerfGraph.addMarker (bdata.times[i], bdata.who[i] + ": " + bdata.comment[i]);
}
if (gReadyForRedraw)
BigPerfGraph.redraw();
getElement("bonsaibutton").disabled = false;
});
}
}
}
function onGraph() {
showLoadingAnimation("building graph");
showStatus(null);
for each (var g in [BigPerfGraph, SmallPerfGraph]) {
g.clearDataSets();
g.setTimeRange(null, null);
}
gReadyForRedraw = false;
// do the actual graph data request
var baselineModule = null;
GraphFormModules.forEach (function (g) { if (g.baseline) baselineModule = g; });
if (baselineModule) {
Tinderbox.requestDataSetFor (baselineModule.testId,
function (testid, ds) {
try {
//log ("Got results for baseline: '" + testid + "' ds: " + ds);
ds.color = baselineModule.color;
onGraphLoadRemainder(ds);
} catch(e) { log(e); }
});
} else {
onGraphLoadRemainder();
}
}
function onGraphLoadRemainder(baselineDataSet) {
for each (var graphModule in GraphFormModules) {
//log ("onGraphLoadRemainder: ", graphModule.id, graphModule.testId, "color:", graphModule.color, "average:", graphModule.average);
// this would have been loaded earlier
if (graphModule.baseline)
continue;
var autoExpand = true;
if (SmallPerfGraph.selectionType == "range" &&
SmallPerfGraph.selectionStartTime &&
SmallPerfGraph.selectionEndTime)
{
if (gCurrentLoadRange && (SmallPerfGraph.selectionStartTime < gCurrentLoadRange[0] ||
SmallPerfGraph.selectionEndTime > gCurrentLoadRange[1]))
{
SmallPerfGraph.selectionStartTime = Math.max (SmallPerfGraph.selectionStartTime, gCurrentLoadRange[0]);
SmallPerfGraph.selectionEndTime = Math.min (SmallPerfGraph.selectionEndTime, gCurrentLoadRange[1]);
}
BigPerfGraph.setTimeRange (SmallPerfGraph.selectionStartTime, SmallPerfGraph.selectionEndTime);
autoExpand = false;
}
// we need a new closure here so that we can get the right value
// of graphModule in our closure
var makeCallback = function (module, color, title) {
return function (testid, ds) {
try {
log("ds.firstTime " + ds.firstTime + " ds.lastTime " + ds.lastTime);
if (undefined == ds.firstTime || !ds.lastTime) {
// got a data set with no data in this time range, or damaged data
// better to not graph
for each (g in [BigPerfGraph, SmallPerfGraph]) {
g.clearGraph();
}
showStatus("No data in the given time range");
clearLoadingAnimation();
}
else {
ds.color = color;
if (title) {
ds.title = title;
}
if (baselineDataSet)
ds = ds.createRelativeTo(baselineDataSet);
//log ("got ds: (", module.id, ")", ds.firstTime, ds.lastTime, ds.data.length);
var avgds = null;
if (baselineDataSet == null &&
module.average)
{
avgds = ds.createAverage(gAverageInterval);
}
if (avgds)
log ("got avgds: (", module.id, ")", avgds.firstTime, avgds.lastTime, avgds.data.length);
for each (g in [BigPerfGraph, SmallPerfGraph]) {
g.addDataSet(ds);
if (avgds)
g.addDataSet(avgds);
if (g == SmallPerfGraph || autoExpand) {
g.expandTimeRange(Math.max(ds.firstTime, gCurrentLoadRange ? gCurrentLoadRange[0] : ds.firstTime),
Math.min(ds.lastTime, gCurrentLoadRange ? gCurrentLoadRange[1] : ds.lastTime));
}
g.autoScale();
g.redraw();
gReadyForRedraw = true;
}
//if (graphType == CONTINUOUS_GRAPH) {
updateLinkToThis();
updateDumpToCsv();
//}
}
} catch(e) { log(e); }
};
};
if (graphModule.testIds) {
for each (var testId in graphModule.testIds) {
// log ("working with testId: " + testId);
Tinderbox.requestDataSetFor (testId[0], makeCallback(graphModule, randomColor(), testId[1]));
}
}
else {
// log ("working with standard, single testId");
Tinderbox.requestDataSetFor (graphModule.testId, makeCallback(graphModule, graphModule.color));
}
}
}
function onDataLoadChanged() {
log ("loadchanged");
if (getElement("load-days-radio").checked) {
var dval = new Number(getElement("load-days-entry").value);
log ("dval", dval);
if (dval <= 0) {
//getElement("load-days-entry").style.background-color = "red";
return;
} else {
//getElement("load-days-entry").style.background-color = "inherit";
}
var d2 = Math.ceil(Date.now() / 1000);
d2 = (d2 - (d2 % ONE_DAY_SECONDS)) + ONE_DAY_SECONDS;
var d1 = Math.floor(d2 - (dval * ONE_DAY_SECONDS));
log ("drange", d1, d2);
Tinderbox.defaultLoadRange = [d1, d2];
gCurrentLoadRange = [d1, d2];
} else {
Tinderbox.defaultLoadRange = null;
gCurrentLoadRange = null;
}
Tinderbox.clearValueDataSets();
// hack, reset colors
randomColorBias = 0;
}
function onExtraDataLoadChanged() {
log ("loadchanged");
Tinderbox.defaultLoadRange = null;
gCurrentLoadRange = null;
// hack, reset colors
randomColorBias = 0;
}
function onDiscreteDataLoadChanged() {
log ("loadchanged");
Tinderbox.defaultLoadRange = null;
gCurrentLoadRange = null;
// hack, reset colors
randomColorBias = 0;
}
function findGraphModule(testId) {
for each (var gm in GraphFormModules) {
if (gm.testId == testId)
return gm;
}
return null;
}
function updateDumpToCsv() {
var ds = "?"
prefix = ""
for each (var gm in GraphFormModules) {
ds += prefix + gm.getDumpString();
prefix = "&"
}
log ("ds");
getElement("dumptocsv").href = "http://" + document.location.host + "/dumpdata.cgi" + ds;
}
function updateLinkToThis() {
var qs = "";
qs += SmallPerfGraph.getQueryString("sp");
qs += "&";
qs += BigPerfGraph.getQueryString("bp");
if (graphType == CONTINUOUS_GRAPH) {
var ctr = 1;
for each (var gm in GraphFormModules) {
qs += "&" + gm.getQueryString("m" + ctr);
ctr++;
}
}
else {
qs += "&";
qs += "name=" + GraphFormModules[0].name;
for each (var gm in GraphFormModules) {
qs += gm.getQueryString("m");
}
}
getElement("linktothis").href = document.location.pathname + "#" + qs;
}
function handleHash(hash) {
var qsdata = {};
for each (var s in hash.substring(1).split("&")) {
var q = s.split("=");
qsdata[q[0]] = q[1];
}
if (graphType == CONTINUOUS_GRAPH) {
var ctr = 1;
while (("m" + ctr + "tid") in qsdata) {
var prefix = "m" + ctr;
addGraphForm({testid: qsdata[prefix + "tid"],
average: qsdata[prefix + "avg"]});
ctr++;
}
}
else {
var ctr=1;
testids = [];
while (("m" + ctr + "tid") in qsdata) {
var prefix = "m" + ctr;
testids.push(Number(qsdata[prefix + "tid"]));
ctr++;
}
// log("qsdata[name] " + qsdata["name"]);
addDiscreteGraphForm(testids, qsdata["name"]);
}
SmallPerfGraph.handleQueryStringData("sp", qsdata);
BigPerfGraph.handleQueryStringData("bp", qsdata);
var tstart = new Number(qsdata["spstart"]);
var tend = new Number(qsdata["spend"]);
//Tinderbox.defaultLoadRange = [tstart, tend];
if (graphType == CONTINUOUS_GRAPH) {
Tinderbox.requestTestList(function (tests) {
setTimeout (onGraph, 0); // let the other handlers do their thing
});
}
}
function graphInitial() {
GraphFormModules[0].addedInitialInfo.unsubscribeAll();
Tinderbox.requestTestList(null, null, null, null, function (tests) {
setTimeout(onGraph, 0);
});
}
function showStatus(s) {
replaceChildNodes("status", s);
}
function showLoadingAnimation(message) {
//log("starting loading animation: " + message);
td = new SPAN();
el = new IMG({ src: "js/img/Throbber-small.gif"});
appendChildNodes(td, el);
appendChildNodes(td, " loading: " + message + " ");
replaceChildNodes("loading", td);
}
function clearLoadingAnimation() {
//log("ending loading animation");
replaceChildNodes("loading", null);
}
function showGraphList(s) {
replaceChildNodes("graph-label-list",null);
// log("s: " +s);
var tbl = new TABLE({});
var tbl_tr = new TR();
appendChildNodes(tbl_tr, new TD(""));
appendChildNodes(tbl_tr, new TD("avg"));
appendChildNodes(tbl_tr, new TD("max"));
appendChildNodes(tbl_tr, new TD("min"));
appendChildNodes(tbl_tr, new TD("test name"));
appendChildNodes(tbl, tbl_tr);
for each (var ds in s) {
var tbl_tr = new TR();
var rstring = ds.stats + " ";
var colorDiv = new DIV({ id: "whee", style: "display: inline; border: 1px solid black; height: 15; " +
"padding-right: 15; vertical-align: middle; margin: 3px;" });
colorDiv.style.backgroundColor = colorToRgbString(ds.color);
// log("ds.stats" + ds.stats);
appendChildNodes(tbl_tr, colorDiv);
for each (var val in ds.stats) {
appendChildNodes(tbl_tr, new TD(val.toFixed(2)));
}
appendChildNodes(tbl, tbl_tr);
appendChildNodes(tbl_tr, new TD(ds.title));
}
appendChildNodes("graph-label-list", tbl);
if (s.length == GraphFormModules[0].testIds.length) {
clearLoadingAnimation();
}
//replaceChildNodes("graph-label-list",rstring);
}
/* Get some pre-set colors in for the first 5 graphs, thens start randomly generating stuff */
var presetColorIndex = 0;
var presetColors = [
[0.0, 0.0, 0.7, 1.0],
[0.0, 0.5, 0.0, 1.0],
[0.7, 0.0, 0.0, 1.0],
[0.7, 0.0, 0.7, 1.0],
[0.0, 0.7, 0.7, 1.0]
];
var randomColorBias = 0;
function randomColor() {
if (presetColorIndex < presetColors.length) {
return presetColors[presetColorIndex++];
}
var col = [
(Math.random()*0.5) + ((randomColorBias==0) ? 0.5 : 0.2),
(Math.random()*0.5) + ((randomColorBias==1) ? 0.5 : 0.2),
(Math.random()*0.5) + ((randomColorBias==2) ? 0.5 : 0.2),
1.0
];
randomColorBias++;
if (randomColorBias == 3)
randomColorBias = 0;
return col;
}
function lighterColor(col) {
return [
Math.min(0.85, col[0] * 1.2),
Math.min(0.85, col[1] * 1.2),
Math.min(0.85, col[2] * 1.2),
col[3]
];
}
function colorToRgbString(col) {
// log ("in colorToRgbString");
if (col[3] < 1) {
return "rgba("
+ Math.floor(col[0]*255) + ","
+ Math.floor(col[1]*255) + ","
+ Math.floor(col[2]*255) + ","
+ col[3]
+ ")";
}
return "rgb("
+ Math.floor(col[0]*255) + ","
+ Math.floor(col[1]*255) + ","
+ Math.floor(col[2]*255) + ")";
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 825 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 156 B

View File

@@ -1,637 +0,0 @@
/***
MochiKit.Async 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide("MochiKit.Async");
dojo.require("MochiKit.Base");
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Async depends on MochiKit.Base!";
}
if (typeof(MochiKit.Async) == 'undefined') {
MochiKit.Async = {};
}
MochiKit.Async.NAME = "MochiKit.Async";
MochiKit.Async.VERSION = "1.3.1";
MochiKit.Async.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Async.toString = function () {
return this.__repr__();
};
MochiKit.Async.Deferred = function (/* optional */ canceller) {
this.chain = [];
this.id = this._nextId();
this.fired = -1;
this.paused = 0;
this.results = [null, null];
this.canceller = canceller;
this.silentlyCancelled = false;
this.chained = false;
};
MochiKit.Async.Deferred.prototype = {
repr: function () {
var state;
if (this.fired == -1) {
state = 'unfired';
} else if (this.fired === 0) {
state = 'success';
} else {
state = 'error';
}
return 'Deferred(' + this.id + ', ' + state + ')';
},
toString: MochiKit.Base.forwardCall("repr"),
_nextId: MochiKit.Base.counter(),
cancel: function () {
var self = MochiKit.Async;
if (this.fired == -1) {
if (this.canceller) {
this.canceller(this);
} else {
this.silentlyCancelled = true;
}
if (this.fired == -1) {
this.errback(new self.CancelledError(this));
}
} else if ((this.fired === 0) && (this.results[0] instanceof self.Deferred)) {
this.results[0].cancel();
}
},
_pause: function () {
/***
Used internally to signal that it's waiting on another Deferred
***/
this.paused++;
},
_unpause: function () {
/***
Used internally to signal that it's no longer waiting on another
Deferred.
***/
this.paused--;
if ((this.paused === 0) && (this.fired >= 0)) {
this._fire();
}
},
_continue: function (res) {
/***
Used internally when a dependent deferred fires.
***/
this._resback(res);
this._unpause();
},
_resback: function (res) {
/***
The primitive that means either callback or errback
***/
this.fired = ((res instanceof Error) ? 1 : 0);
this.results[this.fired] = res;
this._fire();
},
_check: function () {
if (this.fired != -1) {
if (!this.silentlyCancelled) {
throw new MochiKit.Async.AlreadyCalledError(this);
}
this.silentlyCancelled = false;
return;
}
},
callback: function (res) {
this._check();
if (res instanceof MochiKit.Async.Deferred) {
throw new Error("Deferred instances can only be chained if they are the result of a callback");
}
this._resback(res);
},
errback: function (res) {
this._check();
var self = MochiKit.Async;
if (res instanceof self.Deferred) {
throw new Error("Deferred instances can only be chained if they are the result of a callback");
}
if (!(res instanceof Error)) {
res = new self.GenericError(res);
}
this._resback(res);
},
addBoth: function (fn) {
if (arguments.length > 1) {
fn = MochiKit.Base.partial.apply(null, arguments);
}
return this.addCallbacks(fn, fn);
},
addCallback: function (fn) {
if (arguments.length > 1) {
fn = MochiKit.Base.partial.apply(null, arguments);
}
return this.addCallbacks(fn, null);
},
addErrback: function (fn) {
if (arguments.length > 1) {
fn = MochiKit.Base.partial.apply(null, arguments);
}
return this.addCallbacks(null, fn);
},
addCallbacks: function (cb, eb) {
if (this.chained) {
throw new Error("Chained Deferreds can not be re-used");
}
this.chain.push([cb, eb]);
if (this.fired >= 0) {
this._fire();
}
return this;
},
_fire: function () {
/***
Used internally to exhaust the callback sequence when a result
is available.
***/
var chain = this.chain;
var fired = this.fired;
var res = this.results[fired];
var self = this;
var cb = null;
while (chain.length > 0 && this.paused === 0) {
// Array
var pair = chain.shift();
var f = pair[fired];
if (f === null) {
continue;
}
try {
res = f(res);
fired = ((res instanceof Error) ? 1 : 0);
if (res instanceof MochiKit.Async.Deferred) {
cb = function (res) {
self._continue(res);
};
this._pause();
}
} catch (err) {
fired = 1;
if (!(err instanceof Error)) {
err = new MochiKit.Async.GenericError(err);
}
res = err;
}
}
this.fired = fired;
this.results[fired] = res;
if (cb && this.paused) {
// this is for "tail recursion" in case the dependent deferred
// is already fired
res.addBoth(cb);
res.chained = true;
}
}
};
MochiKit.Base.update(MochiKit.Async, {
evalJSONRequest: function (/* req */) {
return eval('(' + arguments[0].responseText + ')');
},
succeed: function (/* optional */result) {
var d = new MochiKit.Async.Deferred();
d.callback.apply(d, arguments);
return d;
},
fail: function (/* optional */result) {
var d = new MochiKit.Async.Deferred();
d.errback.apply(d, arguments);
return d;
},
getXMLHttpRequest: function () {
var self = arguments.callee;
if (!self.XMLHttpRequest) {
var tryThese = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
function () {
throw new MochiKit.Async.BrowserComplianceError("Browser does not support XMLHttpRequest");
}
];
for (var i = 0; i < tryThese.length; i++) {
var func = tryThese[i];
try {
self.XMLHttpRequest = func;
return func();
} catch (e) {
// pass
}
}
}
return self.XMLHttpRequest();
},
_nothing: function () {},
_xhr_onreadystatechange: function (d) {
// MochiKit.Logging.logDebug('this.readyState', this.readyState);
if (this.readyState == 4) {
// IE SUCKS
try {
this.onreadystatechange = null;
} catch (e) {
try {
this.onreadystatechange = MochiKit.Async._nothing;
} catch (e) {
}
}
var status = null;
try {
status = this.status;
if (!status && MochiKit.Base.isNotEmpty(this.responseText)) {
// 0 or undefined seems to mean cached or local
status = 304;
}
} catch (e) {
// pass
// MochiKit.Logging.logDebug('error getting status?', repr(items(e)));
}
// 200 is OK, 304 is NOT_MODIFIED
if (status == 200 || status == 304) { // OK
d.callback(this);
} else {
var err = new MochiKit.Async.XMLHttpRequestError(this, "Request failed");
if (err.number) {
// XXX: This seems to happen on page change
d.errback(err);
} else {
// XXX: this seems to happen when the server is unreachable
d.errback(err);
}
}
}
},
_xhr_canceller: function (req) {
// IE SUCKS
try {
req.onreadystatechange = null;
} catch (e) {
try {
req.onreadystatechange = MochiKit.Async._nothing;
} catch (e) {
}
}
req.abort();
},
sendXMLHttpRequest: function (req, /* optional */ sendContent) {
if (typeof(sendContent) == "undefined" || sendContent === null) {
sendContent = "";
}
var m = MochiKit.Base;
var self = MochiKit.Async;
var d = new self.Deferred(m.partial(self._xhr_canceller, req));
try {
req.onreadystatechange = m.bind(self._xhr_onreadystatechange,
req, d);
req.send(sendContent);
} catch (e) {
try {
req.onreadystatechange = null;
} catch (ignore) {
// pass
}
d.errback(e);
}
return d;
},
doSimpleXMLHttpRequest: function (url/*, ...*/) {
var self = MochiKit.Async;
var req = self.getXMLHttpRequest();
if (arguments.length > 1) {
var m = MochiKit.Base;
var qs = m.queryString.apply(null, m.extend(null, arguments, 1));
if (qs) {
url += "?" + qs;
}
}
req.open("GET", url, true);
return self.sendXMLHttpRequest(req);
},
loadJSONDoc: function (url) {
var self = MochiKit.Async;
var d = self.doSimpleXMLHttpRequest.apply(self, arguments);
d = d.addCallback(self.evalJSONRequest);
return d;
},
wait: function (seconds, /* optional */value) {
var d = new MochiKit.Async.Deferred();
var m = MochiKit.Base;
if (typeof(value) != 'undefined') {
d.addCallback(function () { return value; });
}
var timeout = setTimeout(
m.bind("callback", d),
Math.floor(seconds * 1000));
d.canceller = function () {
try {
clearTimeout(timeout);
} catch (e) {
// pass
}
};
return d;
},
callLater: function (seconds, func) {
var m = MochiKit.Base;
var pfunc = m.partial.apply(m, m.extend(null, arguments, 1));
return MochiKit.Async.wait(seconds).addCallback(
function (res) { return pfunc(); }
);
}
});
MochiKit.Async.DeferredLock = function () {
this.waiting = [];
this.locked = false;
this.id = this._nextId();
};
MochiKit.Async.DeferredLock.prototype = {
__class__: MochiKit.Async.DeferredLock,
acquire: function () {
d = new MochiKit.Async.Deferred();
if (this.locked) {
this.waiting.push(d);
} else {
this.locked = true;
d.callback(this);
}
return d;
},
release: function () {
if (!this.locked) {
throw TypeError("Tried to release an unlocked DeferredLock");
}
this.locked = false;
if (this.waiting.length > 0) {
this.locked = true;
this.waiting.shift().callback(this);
}
},
_nextId: MochiKit.Base.counter(),
repr: function () {
var state;
if (this.locked) {
state = 'locked, ' + this.waiting.length + ' waiting';
} else {
state = 'unlocked';
}
return 'DeferredLock(' + this.id + ', ' + state + ')';
},
toString: MochiKit.Base.forwardCall("repr")
};
MochiKit.Async.DeferredList = function (list, /* optional */fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller) {
this.list = list;
this.resultList = new Array(this.list.length);
// Deferred init
this.chain = [];
this.id = this._nextId();
this.fired = -1;
this.paused = 0;
this.results = [null, null];
this.canceller = canceller;
this.silentlyCancelled = false;
if (this.list.length === 0 && !fireOnOneCallback) {
this.callback(this.resultList);
}
this.finishedCount = 0;
this.fireOnOneCallback = fireOnOneCallback;
this.fireOnOneErrback = fireOnOneErrback;
this.consumeErrors = consumeErrors;
var index = 0;
MochiKit.Base.map(MochiKit.Base.bind(function (d) {
d.addCallback(MochiKit.Base.bind(this._cbDeferred, this), index, true);
d.addErrback(MochiKit.Base.bind(this._cbDeferred, this), index, false);
index += 1;
}, this), this.list);
};
MochiKit.Base.update(MochiKit.Async.DeferredList.prototype,
MochiKit.Async.Deferred.prototype);
MochiKit.Base.update(MochiKit.Async.DeferredList.prototype, {
_cbDeferred: function (index, succeeded, result) {
this.resultList[index] = [succeeded, result];
this.finishedCount += 1;
if (this.fired !== 0) {
if (succeeded && this.fireOnOneCallback) {
this.callback([index, result]);
} else if (!succeeded && this.fireOnOneErrback) {
this.errback(result);
} else if (this.finishedCount == this.list.length) {
this.callback(this.resultList);
}
}
if (!succeeded && this.consumeErrors) {
result = null;
}
return result;
}
});
MochiKit.Async.gatherResults = function (deferredList) {
var d = new MochiKit.Async.DeferredList(deferredList, false, true, false);
d.addCallback(function (results) {
var ret = [];
for (var i = 0; i < results.length; i++) {
ret.push(results[i][1]);
}
return ret;
});
return d;
};
MochiKit.Async.maybeDeferred = function (func) {
var self = MochiKit.Async;
var result;
try {
var r = func.apply(null, MochiKit.Base.extend([], arguments, 1));
if (r instanceof self.Deferred) {
result = r;
} else if (r instanceof Error) {
result = self.fail(r);
} else {
result = self.succeed(r);
}
} catch (e) {
result = self.fail(e);
}
return result;
};
MochiKit.Async.EXPORT = [
"AlreadyCalledError",
"CancelledError",
"BrowserComplianceError",
"GenericError",
"XMLHttpRequestError",
"Deferred",
"succeed",
"fail",
"getXMLHttpRequest",
"doSimpleXMLHttpRequest",
"loadJSONDoc",
"wait",
"callLater",
"sendXMLHttpRequest",
"DeferredLock",
"DeferredList",
"gatherResults",
"maybeDeferred"
];
MochiKit.Async.EXPORT_OK = [
"evalJSONRequest"
];
MochiKit.Async.__new__ = function () {
var m = MochiKit.Base;
var ne = m.partial(m._newNamedError, this);
ne("AlreadyCalledError",
function (deferred) {
/***
Raised by the Deferred if callback or errback happens
after it was already fired.
***/
this.deferred = deferred;
}
);
ne("CancelledError",
function (deferred) {
/***
Raised by the Deferred cancellation mechanism.
***/
this.deferred = deferred;
}
);
ne("BrowserComplianceError",
function (msg) {
/***
Raised when the JavaScript runtime is not capable of performing
the given function. Technically, this should really never be
raised because a non-conforming JavaScript runtime probably
isn't going to support exceptions in the first place.
***/
this.message = msg;
}
);
ne("GenericError",
function (msg) {
this.message = msg;
}
);
ne("XMLHttpRequestError",
function (req, msg) {
/***
Raised when an XMLHttpRequest does not complete for any reason.
***/
this.req = req;
this.message = msg;
try {
// Strange but true that this can raise in some cases.
this.number = req.status;
} catch (e) {
// pass
}
}
);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
m.nameFunctions(this);
};
MochiKit.Async.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Async);

File diff suppressed because it is too large Load Diff

View File

@@ -1,825 +0,0 @@
/***
MochiKit.Color 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito and others. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Color');
dojo.require('MochiKit.Base');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Color depends on MochiKit.Base";
}
if (typeof(MochiKit.Color) == "undefined") {
MochiKit.Color = {};
}
MochiKit.Color.NAME = "MochiKit.Color";
MochiKit.Color.VERSION = "1.3.1";
MochiKit.Color.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Color.toString = function () {
return this.__repr__();
};
MochiKit.Color.Color = function (red, green, blue, alpha) {
if (typeof(alpha) == 'undefined' || alpha === null) {
alpha = 1.0;
}
this.rgb = {
r: red,
g: green,
b: blue,
a: alpha
};
};
// Prototype methods
MochiKit.Color.Color.prototype = {
__class__: MochiKit.Color.Color,
colorWithAlpha: function (alpha) {
var rgb = this.rgb;
var m = MochiKit.Color;
return m.Color.fromRGB(rgb.r, rgb.g, rgb.b, alpha);
},
colorWithHue: function (hue) {
// get an HSL model, and set the new hue...
var hsl = this.asHSL();
hsl.h = hue;
var m = MochiKit.Color;
// convert back to RGB...
return m.Color.fromHSL(hsl);
},
colorWithSaturation: function (saturation) {
// get an HSL model, and set the new hue...
var hsl = this.asHSL();
hsl.s = saturation;
var m = MochiKit.Color;
// convert back to RGB...
return m.Color.fromHSL(hsl);
},
colorWithLightness: function (lightness) {
// get an HSL model, and set the new hue...
var hsl = this.asHSL();
hsl.l = lightness;
var m = MochiKit.Color;
// convert back to RGB...
return m.Color.fromHSL(hsl);
},
darkerColorWithLevel: function (level) {
var hsl = this.asHSL();
hsl.l = Math.max(hsl.l - level, 0);
var m = MochiKit.Color;
return m.Color.fromHSL(hsl);
},
lighterColorWithLevel: function (level) {
var hsl = this.asHSL();
hsl.l = Math.min(hsl.l + level, 1);
var m = MochiKit.Color;
return m.Color.fromHSL(hsl);
},
blendedColor: function (other, /* optional */ fraction) {
if (typeof(fraction) == 'undefined' || fraction === null) {
fraction = 0.5;
}
var sf = 1.0 - fraction;
var s = this.rgb;
var d = other.rgb;
var df = fraction;
return MochiKit.Color.Color.fromRGB(
(s.r * sf) + (d.r * df),
(s.g * sf) + (d.g * df),
(s.b * sf) + (d.b * df),
(s.a * sf) + (d.a * df)
);
},
compareRGB: function (other) {
var a = this.asRGB();
var b = other.asRGB();
return MochiKit.Base.compare(
[a.r, a.g, a.b, a.a],
[b.r, b.g, b.b, b.a]
);
},
isLight: function () {
return this.asHSL().b > 0.5;
},
isDark: function () {
return (!this.isLight());
},
toHSLString: function () {
var c = this.asHSL();
var ccc = MochiKit.Color.clampColorComponent;
var rval = this._hslString;
if (!rval) {
var mid = (
ccc(c.h, 360).toFixed(0)
+ "," + ccc(c.s, 100).toPrecision(4) + "%"
+ "," + ccc(c.l, 100).toPrecision(4) + "%"
);
var a = c.a;
if (a >= 1) {
a = 1;
rval = "hsl(" + mid + ")";
} else {
if (a <= 0) {
a = 0;
}
rval = "hsla(" + mid + "," + a + ")";
}
this._hslString = rval;
}
return rval;
},
toRGBString: function () {
var c = this.rgb;
var ccc = MochiKit.Color.clampColorComponent;
var rval = this._rgbString;
if (!rval) {
var mid = (
ccc(c.r, 255).toFixed(0)
+ "," + ccc(c.g, 255).toFixed(0)
+ "," + ccc(c.b, 255).toFixed(0)
);
if (c.a != 1) {
rval = "rgba(" + mid + "," + c.a + ")";
} else {
rval = "rgb(" + mid + ")";
}
this._rgbString = rval;
}
return rval;
},
asRGB: function () {
return MochiKit.Base.clone(this.rgb);
},
toHexString: function () {
var m = MochiKit.Color;
var c = this.rgb;
var ccc = MochiKit.Color.clampColorComponent;
var rval = this._hexString;
if (!rval) {
rval = ("#" +
m.toColorPart(ccc(c.r, 255)) +
m.toColorPart(ccc(c.g, 255)) +
m.toColorPart(ccc(c.b, 255))
);
this._hexString = rval;
}
return rval;
},
asHSV: function () {
var hsv = this.hsv;
var c = this.rgb;
if (typeof(hsv) == 'undefined' || hsv === null) {
hsv = MochiKit.Color.rgbToHSV(this.rgb);
this.hsv = hsv;
}
return MochiKit.Base.clone(hsv);
},
asHSL: function () {
var hsl = this.hsl;
var c = this.rgb;
if (typeof(hsl) == 'undefined' || hsl === null) {
hsl = MochiKit.Color.rgbToHSL(this.rgb);
this.hsl = hsl;
}
return MochiKit.Base.clone(hsl);
},
toString: function () {
return this.toRGBString();
},
repr: function () {
var c = this.rgb;
var col = [c.r, c.g, c.b, c.a];
return this.__class__.NAME + "(" + col.join(", ") + ")";
}
};
// Constructor methods
MochiKit.Base.update(MochiKit.Color.Color, {
fromRGB: function (red, green, blue, alpha) {
// designated initializer
var Color = MochiKit.Color.Color;
if (arguments.length == 1) {
var rgb = red;
red = rgb.r;
green = rgb.g;
blue = rgb.b;
if (typeof(rgb.a) == 'undefined') {
alpha = undefined;
} else {
alpha = rgb.a;
}
}
return new Color(red, green, blue, alpha);
},
fromHSL: function (hue, saturation, lightness, alpha) {
var m = MochiKit.Color;
return m.Color.fromRGB(m.hslToRGB.apply(m, arguments));
},
fromHSV: function (hue, saturation, value, alpha) {
var m = MochiKit.Color;
return m.Color.fromRGB(m.hsvToRGB.apply(m, arguments));
},
fromName: function (name) {
var Color = MochiKit.Color.Color;
// Opera 9 seems to "quote" named colors(?!)
if (name.charAt(0) == '"') {
name = name.substr(1, name.length - 2);
}
var htmlColor = Color._namedColors[name.toLowerCase()];
if (typeof(htmlColor) == 'string') {
return Color.fromHexString(htmlColor);
} else if (name == "transparent") {
return Color.transparentColor();
}
return null;
},
fromString: function (colorString) {
var self = MochiKit.Color.Color;
var three = colorString.substr(0, 3);
if (three == "rgb") {
return self.fromRGBString(colorString);
} else if (three == "hsl") {
return self.fromHSLString(colorString);
} else if (colorString.charAt(0) == "#") {
return self.fromHexString(colorString);
}
return self.fromName(colorString);
},
fromHexString: function (hexCode) {
if (hexCode.charAt(0) == '#') {
hexCode = hexCode.substring(1);
}
var components = [];
var i, hex;
if (hexCode.length == 3) {
for (i = 0; i < 3; i++) {
hex = hexCode.substr(i, 1);
components.push(parseInt(hex + hex, 16) / 255.0);
}
} else {
for (i = 0; i < 6; i += 2) {
hex = hexCode.substr(i, 2);
components.push(parseInt(hex, 16) / 255.0);
}
}
var Color = MochiKit.Color.Color;
return Color.fromRGB.apply(Color, components);
},
_fromColorString: function (pre, method, scales, colorCode) {
// parses either HSL or RGB
if (colorCode.indexOf(pre) === 0) {
colorCode = colorCode.substring(colorCode.indexOf("(", 3) + 1, colorCode.length - 1);
}
var colorChunks = colorCode.split(/\s*,\s*/);
var colorFloats = [];
for (var i = 0; i < colorChunks.length; i++) {
var c = colorChunks[i];
var val;
var three = c.substring(c.length - 3);
if (c.charAt(c.length - 1) == '%') {
val = 0.01 * parseFloat(c.substring(0, c.length - 1));
} else if (three == "deg") {
val = parseFloat(c) / 360.0;
} else if (three == "rad") {
val = parseFloat(c) / (Math.PI * 2);
} else {
val = scales[i] * parseFloat(c);
}
colorFloats.push(val);
}
return this[method].apply(this, colorFloats);
},
fromComputedStyle: function (elem, style, mozillaEquivalentCSS) {
var d = MochiKit.DOM;
var cls = MochiKit.Color.Color;
for (elem = d.getElement(elem); elem; elem = elem.parentNode) {
var actualColor = d.computedStyle.apply(d, arguments);
if (!actualColor) {
continue;
}
var color = cls.fromString(actualColor);
if (!color) {
break;
}
if (color.asRGB().a > 0) {
return color;
}
}
return null;
},
fromBackground: function (elem) {
var cls = MochiKit.Color.Color;
return cls.fromComputedStyle(
elem, "backgroundColor", "background-color") || cls.whiteColor();
},
fromText: function (elem) {
var cls = MochiKit.Color.Color;
return cls.fromComputedStyle(
elem, "color", "color") || cls.blackColor();
},
namedColors: function () {
return MochiKit.Base.clone(MochiKit.Color.Color._namedColors);
}
});
// Module level functions
MochiKit.Base.update(MochiKit.Color, {
clampColorComponent: function (v, scale) {
v *= scale;
if (v < 0) {
return 0;
} else if (v > scale) {
return scale;
} else {
return v;
}
},
_hslValue: function (n1, n2, hue) {
if (hue > 6.0) {
hue -= 6.0;
} else if (hue < 0.0) {
hue += 6.0;
}
var val;
if (hue < 1.0) {
val = n1 + (n2 - n1) * hue;
} else if (hue < 3.0) {
val = n2;
} else if (hue < 4.0) {
val = n1 + (n2 - n1) * (4.0 - hue);
} else {
val = n1;
}
return val;
},
hsvToRGB: function (hue, saturation, value, alpha) {
if (arguments.length == 1) {
var hsv = hue;
hue = hsv.h;
saturation = hsv.s;
value = hsv.v;
alpha = hsv.a;
}
var red;
var green;
var blue;
if (saturation === 0) {
red = 0;
green = 0;
blue = 0;
} else {
var i = Math.floor(hue * 6);
var f = (hue * 6) - i;
var p = value * (1 - saturation);
var q = value * (1 - (saturation * f));
var t = value * (1 - (saturation * (1 - f)));
switch (i) {
case 1: red = q; green = value; blue = p; break;
case 2: red = p; green = value; blue = t; break;
case 3: red = p; green = q; blue = value; break;
case 4: red = t; green = p; blue = value; break;
case 5: red = value; green = p; blue = q; break;
case 6: // fall through
case 0: red = value; green = t; blue = p; break;
}
}
return {
r: red,
g: green,
b: blue,
a: alpha
};
},
hslToRGB: function (hue, saturation, lightness, alpha) {
if (arguments.length == 1) {
var hsl = hue;
hue = hsl.h;
saturation = hsl.s;
lightness = hsl.l;
alpha = hsl.a;
}
var red;
var green;
var blue;
if (saturation === 0) {
red = lightness;
green = lightness;
blue = lightness;
} else {
var m2;
if (lightness <= 0.5) {
m2 = lightness * (1.0 + saturation);
} else {
m2 = lightness + saturation - (lightness * saturation);
}
var m1 = (2.0 * lightness) - m2;
var f = MochiKit.Color._hslValue;
var h6 = hue * 6.0;
red = f(m1, m2, h6 + 2);
green = f(m1, m2, h6);
blue = f(m1, m2, h6 - 2);
}
return {
r: red,
g: green,
b: blue,
a: alpha
};
},
rgbToHSV: function (red, green, blue, alpha) {
if (arguments.length == 1) {
var rgb = red;
red = rgb.r;
green = rgb.g;
blue = rgb.b;
alpha = rgb.a;
}
var max = Math.max(Math.max(red, green), blue);
var min = Math.min(Math.min(red, green), blue);
var hue;
var saturation;
var value = max;
if (min == max) {
hue = 0;
saturation = 0;
} else {
var delta = (max - min);
saturation = delta / max;
if (red == max) {
hue = (green - blue) / delta;
} else if (green == max) {
hue = 2 + ((blue - red) / delta);
} else {
hue = 4 + ((red - green) / delta);
}
hue /= 6;
if (hue < 0) {
hue += 1;
}
if (hue > 1) {
hue -= 1;
}
}
return {
h: hue,
s: saturation,
v: value,
a: alpha
};
},
rgbToHSL: function (red, green, blue, alpha) {
if (arguments.length == 1) {
var rgb = red;
red = rgb.r;
green = rgb.g;
blue = rgb.b;
alpha = rgb.a;
}
var max = Math.max(red, Math.max(green, blue));
var min = Math.min(red, Math.min(green, blue));
var hue;
var saturation;
var lightness = (max + min) / 2.0;
var delta = max - min;
if (delta === 0) {
hue = 0;
saturation = 0;
} else {
if (lightness <= 0.5) {
saturation = delta / (max + min);
} else {
saturation = delta / (2 - max - min);
}
if (red == max) {
hue = (green - blue) / delta;
} else if (green == max) {
hue = 2 + ((blue - red) / delta);
} else {
hue = 4 + ((red - green) / delta);
}
hue /= 6;
if (hue < 0) {
hue += 1;
}
if (hue > 1) {
hue -= 1;
}
}
return {
h: hue,
s: saturation,
l: lightness,
a: alpha
};
},
toColorPart: function (num) {
num = Math.round(num);
var digits = num.toString(16);
if (num < 16) {
return '0' + digits;
}
return digits;
},
__new__: function () {
var m = MochiKit.Base;
this.Color.fromRGBString = m.bind(
this.Color._fromColorString, this.Color, "rgb", "fromRGB",
[1.0/255.0, 1.0/255.0, 1.0/255.0, 1]
);
this.Color.fromHSLString = m.bind(
this.Color._fromColorString, this.Color, "hsl", "fromHSL",
[1.0/360.0, 0.01, 0.01, 1]
);
var third = 1.0 / 3.0;
var colors = {
// NSColor colors plus transparent
black: [0, 0, 0],
blue: [0, 0, 1],
brown: [0.6, 0.4, 0.2],
cyan: [0, 1, 1],
darkGray: [third, third, third],
gray: [0.5, 0.5, 0.5],
green: [0, 1, 0],
lightGray: [2 * third, 2 * third, 2 * third],
magenta: [1, 0, 1],
orange: [1, 0.5, 0],
purple: [0.5, 0, 0.5],
red: [1, 0, 0],
transparent: [0, 0, 0, 0],
white: [1, 1, 1],
yellow: [1, 1, 0]
};
var makeColor = function (name, r, g, b, a) {
var rval = this.fromRGB(r, g, b, a);
this[name] = function () { return rval; };
return rval;
};
for (var k in colors) {
var name = k + "Color";
var bindArgs = m.concat(
[makeColor, this.Color, name],
colors[k]
);
this.Color[name] = m.bind.apply(null, bindArgs);
}
var isColor = function () {
for (var i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof Color)) {
return false;
}
}
return true;
};
var compareColor = function (a, b) {
return a.compareRGB(b);
};
m.nameFunctions(this);
m.registerComparator(this.Color.NAME, isColor, compareColor);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
}
});
MochiKit.Color.EXPORT = [
"Color"
];
MochiKit.Color.EXPORT_OK = [
"clampColorComponent",
"rgbToHSL",
"hslToRGB",
"rgbToHSV",
"hsvToRGB",
"toColorPart"
];
MochiKit.Color.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Color);
// Full table of css3 X11 colors <http://www.w3.org/TR/css3-color/#X11COLORS>
MochiKit.Color.Color._namedColors = {
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
grey: "#808080",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32"
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,208 +0,0 @@
/***
MochiKit.DateTime 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.DateTime');
}
if (typeof(MochiKit) == 'undefined') {
MochiKit = {};
}
if (typeof(MochiKit.DateTime) == 'undefined') {
MochiKit.DateTime = {};
}
MochiKit.DateTime.NAME = "MochiKit.DateTime";
MochiKit.DateTime.VERSION = "1.3.1";
MochiKit.DateTime.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.DateTime.toString = function () {
return this.__repr__();
};
MochiKit.DateTime.isoDate = function (str) {
str = str + "";
if (typeof(str) != "string" || str.length === 0) {
return null;
}
var iso = str.split('-');
if (iso.length === 0) {
return null;
}
return new Date(iso[0], iso[1] - 1, iso[2]);
};
MochiKit.DateTime._isoRegexp = /(\d{4,})(?:-(\d{1,2})(?:-(\d{1,2})(?:[T ](\d{1,2}):(\d{1,2})(?::(\d{1,2})(?:\.(\d+))?)?(?:(Z)|([+-])(\d{1,2})(?::(\d{1,2}))?)?)?)?)?/;
MochiKit.DateTime.isoTimestamp = function (str) {
str = str + "";
if (typeof(str) != "string" || str.length === 0) {
return null;
}
var res = str.match(MochiKit.DateTime._isoRegexp);
if (typeof(res) == "undefined" || res === null) {
return null;
}
var year, month, day, hour, min, sec, msec;
year = parseInt(res[1], 10);
if (typeof(res[2]) == "undefined" || res[2] === '') {
return new Date(year);
}
month = parseInt(res[2], 10) - 1;
day = parseInt(res[3], 10);
if (typeof(res[4]) == "undefined" || res[4] === '') {
return new Date(year, month, day);
}
hour = parseInt(res[4], 10);
min = parseInt(res[5], 10);
sec = (typeof(res[6]) != "undefined" && res[6] !== '') ? parseInt(res[6], 10) : 0;
if (typeof(res[7]) != "undefined" && res[7] !== '') {
msec = Math.round(1000.0 * parseFloat("0." + res[7]));
} else {
msec = 0;
}
if ((typeof(res[8]) == "undefined" || res[8] === '') && (typeof(res[9]) == "undefined" || res[9] === '')) {
return new Date(year, month, day, hour, min, sec, msec);
}
var ofs;
if (typeof(res[9]) != "undefined" && res[9] !== '') {
ofs = parseInt(res[10], 10) * 3600000;
if (typeof(res[11]) != "undefined" && res[11] !== '') {
ofs += parseInt(res[11], 10) * 60000;
}
if (res[9] == "-") {
ofs = -ofs;
}
} else {
ofs = 0;
}
return new Date(Date.UTC(year, month, day, hour, min, sec, msec) - ofs);
};
MochiKit.DateTime.toISOTime = function (date, realISO/* = false */) {
if (typeof(date) == "undefined" || date === null) {
return null;
}
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
var lst = [
((realISO && (hh < 10)) ? "0" + hh : hh),
((mm < 10) ? "0" + mm : mm),
((ss < 10) ? "0" + ss : ss)
];
return lst.join(":");
};
MochiKit.DateTime.toISOTimestamp = function (date, realISO/* = false*/) {
if (typeof(date) == "undefined" || date === null) {
return null;
}
var sep = realISO ? "T" : " ";
var foot = realISO ? "Z" : "";
if (realISO) {
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
}
return MochiKit.DateTime.toISODate(date) + sep + MochiKit.DateTime.toISOTime(date, realISO) + foot;
};
MochiKit.DateTime.toISODate = function (date) {
if (typeof(date) == "undefined" || date === null) {
return null;
}
var _padTwo = MochiKit.DateTime._padTwo;
return [
date.getFullYear(),
_padTwo(date.getMonth() + 1),
_padTwo(date.getDate())
].join("-");
};
MochiKit.DateTime.americanDate = function (d) {
d = d + "";
if (typeof(d) != "string" || d.length === 0) {
return null;
}
var a = d.split('/');
return new Date(a[2], a[0] - 1, a[1]);
};
MochiKit.DateTime._padTwo = function (n) {
return (n > 9) ? n : "0" + n;
};
MochiKit.DateTime.toPaddedAmericanDate = function (d) {
if (typeof(d) == "undefined" || d === null) {
return null;
}
var _padTwo = MochiKit.DateTime._padTwo;
return [
_padTwo(d.getMonth() + 1),
_padTwo(d.getDate()),
d.getFullYear()
].join('/');
};
MochiKit.DateTime.toAmericanDate = function (d) {
if (typeof(d) == "undefined" || d === null) {
return null;
}
return [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('/');
};
MochiKit.DateTime.EXPORT = [
"isoDate",
"isoTimestamp",
"toISOTime",
"toISOTimestamp",
"toISODate",
"americanDate",
"toPaddedAmericanDate",
"toAmericanDate"
];
MochiKit.DateTime.EXPORT_OK = [];
MochiKit.DateTime.EXPORT_TAGS = {
":common": MochiKit.DateTime.EXPORT,
":all": MochiKit.DateTime.EXPORT
};
MochiKit.DateTime.__new__ = function () {
// MochiKit.Base.nameFunctions(this);
var base = this.NAME + ".";
for (var k in this) {
var o = this[k];
if (typeof(o) == 'function' && typeof(o.NAME) == 'undefined') {
try {
o.NAME = base + k;
} catch (e) {
// pass
}
}
}
};
MochiKit.DateTime.__new__();
if (typeof(MochiKit.Base) != "undefined") {
MochiKit.Base._exportSymbols(this, MochiKit.DateTime);
} else {
(function (globals, module) {
if ((typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
|| (typeof(MochiKit.__compat__) == 'boolean' && MochiKit.__compat__)) {
var all = module.EXPORT_TAGS[":all"];
for (var i = 0; i < all.length; i++) {
globals[all[i]] = module[all[i]];
}
}
})(this, MochiKit.DateTime);
}

View File

@@ -1,294 +0,0 @@
/***
MochiKit.Format 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Format');
}
if (typeof(MochiKit) == 'undefined') {
MochiKit = {};
}
if (typeof(MochiKit.Format) == 'undefined') {
MochiKit.Format = {};
}
MochiKit.Format.NAME = "MochiKit.Format";
MochiKit.Format.VERSION = "1.3.1";
MochiKit.Format.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Format.toString = function () {
return this.__repr__();
};
MochiKit.Format._numberFormatter = function (placeholder, header, footer, locale, isPercent, precision, leadingZeros, separatorAt, trailingZeros) {
return function (num) {
num = parseFloat(num);
if (typeof(num) == "undefined" || num === null || isNaN(num)) {
return placeholder;
}
var curheader = header;
var curfooter = footer;
if (num < 0) {
num = -num;
} else {
curheader = curheader.replace(/-/, "");
}
var me = arguments.callee;
var fmt = MochiKit.Format.formatLocale(locale);
if (isPercent) {
num = num * 100.0;
curfooter = fmt.percent + curfooter;
}
num = MochiKit.Format.roundToFixed(num, precision);
var parts = num.split(/\./);
var whole = parts[0];
var frac = (parts.length == 1) ? "" : parts[1];
var res = "";
while (whole.length < leadingZeros) {
whole = "0" + whole;
}
if (separatorAt) {
while (whole.length > separatorAt) {
var i = whole.length - separatorAt;
//res = res + fmt.separator + whole.substring(i, whole.length);
res = fmt.separator + whole.substring(i, whole.length) + res;
whole = whole.substring(0, i);
}
}
res = whole + res;
if (precision > 0) {
while (frac.length < trailingZeros) {
frac = frac + "0";
}
res = res + fmt.decimal + frac;
}
return curheader + res + curfooter;
};
};
MochiKit.Format.numberFormatter = function (pattern, placeholder/* = "" */, locale/* = "default" */) {
// http://java.sun.com/docs/books/tutorial/i18n/format/numberpattern.html
// | 0 | leading or trailing zeros
// | # | just the number
// | , | separator
// | . | decimal separator
// | % | Multiply by 100 and format as percent
if (typeof(placeholder) == "undefined") {
placeholder = "";
}
var match = pattern.match(/((?:[0#]+,)?[0#]+)(?:\.([0#]+))?(%)?/);
if (!match) {
throw TypeError("Invalid pattern");
}
var header = pattern.substr(0, match.index);
var footer = pattern.substr(match.index + match[0].length);
if (header.search(/-/) == -1) {
header = header + "-";
}
var whole = match[1];
var frac = (typeof(match[2]) == "string" && match[2] != "") ? match[2] : "";
var isPercent = (typeof(match[3]) == "string" && match[3] != "");
var tmp = whole.split(/,/);
var separatorAt;
if (typeof(locale) == "undefined") {
locale = "default";
}
if (tmp.length == 1) {
separatorAt = null;
} else {
separatorAt = tmp[1].length;
}
var leadingZeros = whole.length - whole.replace(/0/g, "").length;
var trailingZeros = frac.length - frac.replace(/0/g, "").length;
var precision = frac.length;
var rval = MochiKit.Format._numberFormatter(
placeholder, header, footer, locale, isPercent, precision,
leadingZeros, separatorAt, trailingZeros
);
var m = MochiKit.Base;
if (m) {
var fn = arguments.callee;
var args = m.concat(arguments);
rval.repr = function () {
return [
self.NAME,
"(",
map(m.repr, args).join(", "),
")"
].join("");
};
}
return rval;
};
MochiKit.Format.formatLocale = function (locale) {
if (typeof(locale) == "undefined" || locale === null) {
locale = "default";
}
if (typeof(locale) == "string") {
var rval = MochiKit.Format.LOCALE[locale];
if (typeof(rval) == "string") {
rval = arguments.callee(rval);
MochiKit.Format.LOCALE[locale] = rval;
}
return rval;
} else {
return locale;
}
};
MochiKit.Format.twoDigitAverage = function (numerator, denominator) {
if (denominator) {
var res = numerator / denominator;
if (!isNaN(res)) {
return MochiKit.Format.twoDigitFloat(numerator / denominator);
}
}
return "0";
};
MochiKit.Format.twoDigitFloat = function (someFloat) {
var sign = (someFloat < 0 ? '-' : '');
var s = Math.floor(Math.abs(someFloat) * 100).toString();
if (s == '0') {
return s;
}
if (s.length < 3) {
while (s.charAt(s.length - 1) == '0') {
s = s.substring(0, s.length - 1);
}
return sign + '0.' + s;
}
var head = sign + s.substring(0, s.length - 2);
var tail = s.substring(s.length - 2, s.length);
if (tail == '00') {
return head;
} else if (tail.charAt(1) == '0') {
return head + '.' + tail.charAt(0);
} else {
return head + '.' + tail;
}
};
MochiKit.Format.lstrip = function (str, /* optional */chars) {
str = str + "";
if (typeof(str) != "string") {
return null;
}
if (!chars) {
return str.replace(/^\s+/, "");
} else {
return str.replace(new RegExp("^[" + chars + "]+"), "");
}
};
MochiKit.Format.rstrip = function (str, /* optional */chars) {
str = str + "";
if (typeof(str) != "string") {
return null;
}
if (!chars) {
return str.replace(/\s+$/, "");
} else {
return str.replace(new RegExp("[" + chars + "]+$"), "");
}
};
MochiKit.Format.strip = function (str, /* optional */chars) {
var self = MochiKit.Format;
return self.rstrip(self.lstrip(str, chars), chars);
};
MochiKit.Format.truncToFixed = function (aNumber, precision) {
aNumber = Math.floor(aNumber * Math.pow(10, precision));
var res = (aNumber * Math.pow(10, -precision)).toFixed(precision);
if (res.charAt(0) == ".") {
res = "0" + res;
}
return res;
};
MochiKit.Format.roundToFixed = function (aNumber, precision) {
return MochiKit.Format.truncToFixed(
aNumber + 0.5 * Math.pow(10, -precision),
precision
);
};
MochiKit.Format.percentFormat = function (someFloat) {
return MochiKit.Format.twoDigitFloat(100 * someFloat) + '%';
};
MochiKit.Format.EXPORT = [
"truncToFixed",
"roundToFixed",
"numberFormatter",
"formatLocale",
"twoDigitAverage",
"twoDigitFloat",
"percentFormat",
"lstrip",
"rstrip",
"strip"
];
MochiKit.Format.LOCALE = {
en_US: {separator: ",", decimal: ".", percent: "%"},
de_DE: {separator: ".", decimal: ",", percent: "%"},
fr_FR: {separator: " ", decimal: ",", percent: "%"},
"default": "en_US"
};
MochiKit.Format.EXPORT_OK = [];
MochiKit.Format.EXPORT_TAGS = {
':all': MochiKit.Format.EXPORT,
':common': MochiKit.Format.EXPORT
};
MochiKit.Format.__new__ = function () {
// MochiKit.Base.nameFunctions(this);
var base = this.NAME + ".";
var k, v, o;
for (k in this.LOCALE) {
o = this.LOCALE[k];
if (typeof(o) == "object") {
o.repr = function () { return this.NAME; };
o.NAME = base + "LOCALE." + k;
}
}
for (k in this) {
o = this[k];
if (typeof(o) == 'function' && typeof(o.NAME) == 'undefined') {
try {
o.NAME = base + k;
} catch (e) {
// pass
}
}
}
};
MochiKit.Format.__new__();
if (typeof(MochiKit.Base) != "undefined") {
MochiKit.Base._exportSymbols(this, MochiKit.Format);
} else {
(function (globals, module) {
if ((typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
|| (typeof(MochiKit.__compat__) == 'boolean' && MochiKit.__compat__)) {
var all = module.EXPORT_TAGS[":all"];
for (var i = 0; i < all.length; i++) {
globals[all[i]] = module[all[i]];
}
}
})(this, MochiKit.Format);
}

View File

@@ -1,789 +0,0 @@
/***
MochiKit.Iter 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Iter');
dojo.require('MochiKit.Base');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Iter depends on MochiKit.Base!";
}
if (typeof(MochiKit.Iter) == 'undefined') {
MochiKit.Iter = {};
}
MochiKit.Iter.NAME = "MochiKit.Iter";
MochiKit.Iter.VERSION = "1.3.1";
MochiKit.Base.update(MochiKit.Iter, {
__repr__: function () {
return "[" + this.NAME + " " + this.VERSION + "]";
},
toString: function () {
return this.__repr__();
},
registerIteratorFactory: function (name, check, iterfactory, /* optional */ override) {
MochiKit.Iter.iteratorRegistry.register(name, check, iterfactory, override);
},
iter: function (iterable, /* optional */ sentinel) {
var self = MochiKit.Iter;
if (arguments.length == 2) {
return self.takewhile(
function (a) { return a != sentinel; },
iterable
);
}
if (typeof(iterable.next) == 'function') {
return iterable;
} else if (typeof(iterable.iter) == 'function') {
return iterable.iter();
}
try {
return self.iteratorRegistry.match(iterable);
} catch (e) {
var m = MochiKit.Base;
if (e == m.NotFound) {
e = new TypeError(typeof(iterable) + ": " + m.repr(iterable) + " is not iterable");
}
throw e;
}
},
count: function (n) {
if (!n) {
n = 0;
}
var m = MochiKit.Base;
return {
repr: function () { return "count(" + n + ")"; },
toString: m.forwardCall("repr"),
next: m.counter(n)
};
},
cycle: function (p) {
var self = MochiKit.Iter;
var m = MochiKit.Base;
var lst = [];
var iterator = self.iter(p);
return {
repr: function () { return "cycle(...)"; },
toString: m.forwardCall("repr"),
next: function () {
try {
var rval = iterator.next();
lst.push(rval);
return rval;
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
if (lst.length === 0) {
this.next = function () {
throw self.StopIteration;
};
} else {
var i = -1;
this.next = function () {
i = (i + 1) % lst.length;
return lst[i];
};
}
return this.next();
}
}
};
},
repeat: function (elem, /* optional */n) {
var m = MochiKit.Base;
if (typeof(n) == 'undefined') {
return {
repr: function () {
return "repeat(" + m.repr(elem) + ")";
},
toString: m.forwardCall("repr"),
next: function () {
return elem;
}
};
}
return {
repr: function () {
return "repeat(" + m.repr(elem) + ", " + n + ")";
},
toString: m.forwardCall("repr"),
next: function () {
if (n <= 0) {
throw MochiKit.Iter.StopIteration;
}
n -= 1;
return elem;
}
};
},
next: function (iterator) {
return iterator.next();
},
izip: function (p, q/*, ...*/) {
var m = MochiKit.Base;
var next = MochiKit.Iter.next;
var iterables = m.map(iter, arguments);
return {
repr: function () { return "izip(...)"; },
toString: m.forwardCall("repr"),
next: function () { return m.map(next, iterables); }
};
},
ifilter: function (pred, seq) {
var m = MochiKit.Base;
seq = MochiKit.Iter.iter(seq);
if (pred === null) {
pred = m.operator.truth;
}
return {
repr: function () { return "ifilter(...)"; },
toString: m.forwardCall("repr"),
next: function () {
while (true) {
var rval = seq.next();
if (pred(rval)) {
return rval;
}
}
// mozilla warnings aren't too bright
return undefined;
}
};
},
ifilterfalse: function (pred, seq) {
var m = MochiKit.Base;
seq = MochiKit.Iter.iter(seq);
if (pred === null) {
pred = m.operator.truth;
}
return {
repr: function () { return "ifilterfalse(...)"; },
toString: m.forwardCall("repr"),
next: function () {
while (true) {
var rval = seq.next();
if (!pred(rval)) {
return rval;
}
}
// mozilla warnings aren't too bright
return undefined;
}
};
},
islice: function (seq/*, [start,] stop[, step] */) {
var self = MochiKit.Iter;
var m = MochiKit.Base;
seq = self.iter(seq);
var start = 0;
var stop = 0;
var step = 1;
var i = -1;
if (arguments.length == 2) {
stop = arguments[1];
} else if (arguments.length == 3) {
start = arguments[1];
stop = arguments[2];
} else {
start = arguments[1];
stop = arguments[2];
step = arguments[3];
}
return {
repr: function () {
return "islice(" + ["...", start, stop, step].join(", ") + ")";
},
toString: m.forwardCall("repr"),
next: function () {
var rval;
while (i < start) {
rval = seq.next();
i++;
}
if (start >= stop) {
throw self.StopIteration;
}
start += step;
return rval;
}
};
},
imap: function (fun, p, q/*, ...*/) {
var m = MochiKit.Base;
var self = MochiKit.Iter;
var iterables = m.map(self.iter, m.extend(null, arguments, 1));
var map = m.map;
var next = self.next;
return {
repr: function () { return "imap(...)"; },
toString: m.forwardCall("repr"),
next: function () {
return fun.apply(this, map(next, iterables));
}
};
},
applymap: function (fun, seq, self) {
seq = MochiKit.Iter.iter(seq);
var m = MochiKit.Base;
return {
repr: function () { return "applymap(...)"; },
toString: m.forwardCall("repr"),
next: function () {
return fun.apply(self, seq.next());
}
};
},
chain: function (p, q/*, ...*/) {
// dumb fast path
var self = MochiKit.Iter;
var m = MochiKit.Base;
if (arguments.length == 1) {
return self.iter(arguments[0]);
}
var argiter = m.map(self.iter, arguments);
return {
repr: function () { return "chain(...)"; },
toString: m.forwardCall("repr"),
next: function () {
while (argiter.length > 1) {
try {
return argiter[0].next();
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
argiter.shift();
}
}
if (argiter.length == 1) {
// optimize last element
var arg = argiter.shift();
this.next = m.bind("next", arg);
return this.next();
}
throw self.StopIteration;
}
};
},
takewhile: function (pred, seq) {
var self = MochiKit.Iter;
seq = self.iter(seq);
return {
repr: function () { return "takewhile(...)"; },
toString: MochiKit.Base.forwardCall("repr"),
next: function () {
var rval = seq.next();
if (!pred(rval)) {
this.next = function () {
throw self.StopIteration;
};
this.next();
}
return rval;
}
};
},
dropwhile: function (pred, seq) {
seq = MochiKit.Iter.iter(seq);
var m = MochiKit.Base;
var bind = m.bind;
return {
"repr": function () { return "dropwhile(...)"; },
"toString": m.forwardCall("repr"),
"next": function () {
while (true) {
var rval = seq.next();
if (!pred(rval)) {
break;
}
}
this.next = bind("next", seq);
return rval;
}
};
},
_tee: function (ident, sync, iterable) {
sync.pos[ident] = -1;
var m = MochiKit.Base;
var listMin = m.listMin;
return {
repr: function () { return "tee(" + ident + ", ...)"; },
toString: m.forwardCall("repr"),
next: function () {
var rval;
var i = sync.pos[ident];
if (i == sync.max) {
rval = iterable.next();
sync.deque.push(rval);
sync.max += 1;
sync.pos[ident] += 1;
} else {
rval = sync.deque[i - sync.min];
sync.pos[ident] += 1;
if (i == sync.min && listMin(sync.pos) != sync.min) {
sync.min += 1;
sync.deque.shift();
}
}
return rval;
}
};
},
tee: function (iterable, n/* = 2 */) {
var rval = [];
var sync = {
"pos": [],
"deque": [],
"max": -1,
"min": -1
};
if (arguments.length == 1) {
n = 2;
}
var self = MochiKit.Iter;
iterable = self.iter(iterable);
var _tee = self._tee;
for (var i = 0; i < n; i++) {
rval.push(_tee(i, sync, iterable));
}
return rval;
},
list: function (iterable) {
// Fast-path for Array and Array-like
var m = MochiKit.Base;
if (typeof(iterable.slice) == 'function') {
return iterable.slice();
} else if (m.isArrayLike(iterable)) {
return m.concat(iterable);
}
var self = MochiKit.Iter;
iterable = self.iter(iterable);
var rval = [];
try {
while (true) {
rval.push(iterable.next());
}
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
return rval;
}
// mozilla warnings aren't too bright
return undefined;
},
reduce: function (fn, iterable, /* optional */initial) {
var i = 0;
var x = initial;
var self = MochiKit.Iter;
iterable = self.iter(iterable);
if (arguments.length < 3) {
try {
x = iterable.next();
} catch (e) {
if (e == self.StopIteration) {
e = new TypeError("reduce() of empty sequence with no initial value");
}
throw e;
}
i++;
}
try {
while (true) {
x = fn(x, iterable.next());
}
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
}
return x;
},
range: function (/* [start,] stop[, step] */) {
var start = 0;
var stop = 0;
var step = 1;
if (arguments.length == 1) {
stop = arguments[0];
} else if (arguments.length == 2) {
start = arguments[0];
stop = arguments[1];
} else if (arguments.length == 3) {
start = arguments[0];
stop = arguments[1];
step = arguments[2];
} else {
throw new TypeError("range() takes 1, 2, or 3 arguments!");
}
if (step === 0) {
throw new TypeError("range() step must not be 0");
}
return {
next: function () {
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
throw MochiKit.Iter.StopIteration;
}
var rval = start;
start += step;
return rval;
},
repr: function () {
return "range(" + [start, stop, step].join(", ") + ")";
},
toString: MochiKit.Base.forwardCall("repr")
};
},
sum: function (iterable, start/* = 0 */) {
var x = start || 0;
var self = MochiKit.Iter;
iterable = self.iter(iterable);
try {
while (true) {
x += iterable.next();
}
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
}
return x;
},
exhaust: function (iterable) {
var self = MochiKit.Iter;
iterable = self.iter(iterable);
try {
while (true) {
iterable.next();
}
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
}
},
forEach: function (iterable, func, /* optional */self) {
var m = MochiKit.Base;
if (arguments.length > 2) {
func = m.bind(func, self);
}
// fast path for array
if (m.isArrayLike(iterable)) {
try {
for (var i = 0; i < iterable.length; i++) {
func(iterable[i]);
}
} catch (e) {
if (e != MochiKit.Iter.StopIteration) {
throw e;
}
}
} else {
self = MochiKit.Iter;
self.exhaust(self.imap(func, iterable));
}
},
every: function (iterable, func) {
var self = MochiKit.Iter;
try {
self.ifilterfalse(func, iterable).next();
return false;
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
return true;
}
},
sorted: function (iterable, /* optional */cmp) {
var rval = MochiKit.Iter.list(iterable);
if (arguments.length == 1) {
cmp = MochiKit.Base.compare;
}
rval.sort(cmp);
return rval;
},
reversed: function (iterable) {
var rval = MochiKit.Iter.list(iterable);
rval.reverse();
return rval;
},
some: function (iterable, func) {
var self = MochiKit.Iter;
try {
self.ifilter(func, iterable).next();
return true;
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
return false;
}
},
iextend: function (lst, iterable) {
if (MochiKit.Base.isArrayLike(iterable)) {
// fast-path for array-like
for (var i = 0; i < iterable.length; i++) {
lst.push(iterable[i]);
}
} else {
var self = MochiKit.Iter;
iterable = self.iter(iterable);
try {
while (true) {
lst.push(iterable.next());
}
} catch (e) {
if (e != self.StopIteration) {
throw e;
}
}
}
return lst;
},
groupby: function(iterable, /* optional */ keyfunc) {
var m = MochiKit.Base;
var self = MochiKit.Iter;
if (arguments.length < 2) {
keyfunc = m.operator.identity;
}
iterable = self.iter(iterable);
// shared
var pk = undefined;
var k = undefined;
var v;
function fetch() {
v = iterable.next();
k = keyfunc(v);
};
function eat() {
var ret = v;
v = undefined;
return ret;
};
var first = true;
return {
repr: function () { return "groupby(...)"; },
next: function() {
// iterator-next
// iterate until meet next group
while (k == pk) {
fetch();
if (first) {
first = false;
break;
}
}
pk = k;
return [k, {
next: function() {
// subiterator-next
if (v == undefined) { // Is there something to eat?
fetch();
}
if (k != pk) {
throw self.StopIteration;
}
return eat();
}
}];
}
};
},
groupby_as_array: function (iterable, /* optional */ keyfunc) {
var m = MochiKit.Base;
var self = MochiKit.Iter;
if (arguments.length < 2) {
keyfunc = m.operator.identity;
}
iterable = self.iter(iterable);
var result = [];
var first = true;
var prev_key;
while (true) {
try {
var value = iterable.next();
var key = keyfunc(value);
} catch (e) {
if (e == self.StopIteration) {
break;
}
throw e;
}
if (first || key != prev_key) {
var values = [];
result.push([key, values]);
}
values.push(value);
first = false;
prev_key = key;
}
return result;
},
arrayLikeIter: function (iterable) {
var i = 0;
return {
repr: function () { return "arrayLikeIter(...)"; },
toString: MochiKit.Base.forwardCall("repr"),
next: function () {
if (i >= iterable.length) {
throw MochiKit.Iter.StopIteration;
}
return iterable[i++];
}
};
},
hasIterateNext: function (iterable) {
return (iterable && typeof(iterable.iterateNext) == "function");
},
iterateNextIter: function (iterable) {
return {
repr: function () { return "iterateNextIter(...)"; },
toString: MochiKit.Base.forwardCall("repr"),
next: function () {
var rval = iterable.iterateNext();
if (rval === null || rval === undefined) {
throw MochiKit.Iter.StopIteration;
}
return rval;
}
};
}
});
MochiKit.Iter.EXPORT_OK = [
"iteratorRegistry",
"arrayLikeIter",
"hasIterateNext",
"iterateNextIter",
];
MochiKit.Iter.EXPORT = [
"StopIteration",
"registerIteratorFactory",
"iter",
"count",
"cycle",
"repeat",
"next",
"izip",
"ifilter",
"ifilterfalse",
"islice",
"imap",
"applymap",
"chain",
"takewhile",
"dropwhile",
"tee",
"list",
"reduce",
"range",
"sum",
"exhaust",
"forEach",
"every",
"sorted",
"reversed",
"some",
"iextend",
"groupby",
"groupby_as_array"
];
MochiKit.Iter.__new__ = function () {
var m = MochiKit.Base;
this.StopIteration = new m.NamedError("StopIteration");
this.iteratorRegistry = new m.AdapterRegistry();
// Register the iterator factory for arrays
this.registerIteratorFactory(
"arrayLike",
m.isArrayLike,
this.arrayLikeIter
);
this.registerIteratorFactory(
"iterateNext",
this.hasIterateNext,
this.iterateNextIter
);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
m.nameFunctions(this);
};
MochiKit.Iter.__new__();
//
// XXX: Internet Explorer blows
//
if (!MochiKit.__compat__) {
reduce = MochiKit.Iter.reduce;
}
MochiKit.Base._exportSymbols(this, MochiKit.Iter);

View File

@@ -1,290 +0,0 @@
/***
MochiKit.Logging 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Logging');
dojo.require('MochiKit.Base');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Logging depends on MochiKit.Base!";
}
if (typeof(MochiKit.Logging) == 'undefined') {
MochiKit.Logging = {};
}
MochiKit.Logging.NAME = "MochiKit.Logging";
MochiKit.Logging.VERSION = "1.3.1";
MochiKit.Logging.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Logging.toString = function () {
return this.__repr__();
};
MochiKit.Logging.EXPORT = [
"LogLevel",
"LogMessage",
"Logger",
"alertListener",
"logger",
"log",
"logError",
"logDebug",
"logFatal",
"logWarning"
];
MochiKit.Logging.EXPORT_OK = [
"logLevelAtLeast",
"isLogMessage",
"compareLogMessage"
];
MochiKit.Logging.LogMessage = function (num, level, info) {
this.num = num;
this.level = level;
this.info = info;
this.timestamp = new Date();
};
MochiKit.Logging.LogMessage.prototype = {
repr: function () {
var m = MochiKit.Base;
return 'LogMessage(' +
m.map(
m.repr,
[this.num, this.level, this.info]
).join(', ') + ')';
},
toString: MochiKit.Base.forwardCall("repr")
};
MochiKit.Base.update(MochiKit.Logging, {
logLevelAtLeast: function (minLevel) {
var self = MochiKit.Logging;
if (typeof(minLevel) == 'string') {
minLevel = self.LogLevel[minLevel];
}
return function (msg) {
var msgLevel = msg.level;
if (typeof(msgLevel) == 'string') {
msgLevel = self.LogLevel[msgLevel];
}
return msgLevel >= minLevel;
};
},
isLogMessage: function (/* ... */) {
var LogMessage = MochiKit.Logging.LogMessage;
for (var i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof LogMessage)) {
return false;
}
}
return true;
},
compareLogMessage: function (a, b) {
return MochiKit.Base.compare([a.level, a.info], [b.level, b.info]);
},
alertListener: function (msg) {
alert(
"num: " + msg.num +
"\nlevel: " + msg.level +
"\ninfo: " + msg.info.join(" ")
);
}
});
MochiKit.Logging.Logger = function (/* optional */maxSize) {
this.counter = 0;
if (typeof(maxSize) == 'undefined' || maxSize === null) {
maxSize = -1;
}
this.maxSize = maxSize;
this._messages = [];
this.listeners = {};
this.useNativeConsole = false;
};
MochiKit.Logging.Logger.prototype = {
clear: function () {
this._messages.splice(0, this._messages.length);
},
logToConsole: function (msg) {
if (typeof(window) != "undefined" && window.console
&& window.console.log) {
// Safari
window.console.log(msg);
} else if (typeof(opera) != "undefined" && opera.postError) {
// Opera
opera.postError(msg);
} else if (typeof(printfire) == "function") {
// FireBug
printfire(msg);
}
},
dispatchListeners: function (msg) {
for (var k in this.listeners) {
var pair = this.listeners[k];
if (pair.ident != k || (pair[0] && !pair[0](msg))) {
continue;
}
pair[1](msg);
}
},
addListener: function (ident, filter, listener) {
if (typeof(filter) == 'string') {
filter = MochiKit.Logging.logLevelAtLeast(filter);
}
var entry = [filter, listener];
entry.ident = ident;
this.listeners[ident] = entry;
},
removeListener: function (ident) {
delete this.listeners[ident];
},
baseLog: function (level, message/*, ...*/) {
var msg = new MochiKit.Logging.LogMessage(
this.counter,
level,
MochiKit.Base.extend(null, arguments, 1)
);
this._messages.push(msg);
this.dispatchListeners(msg);
if (this.useNativeConsole) {
this.logToConsole(msg.level + ": " + msg.info.join(" "));
}
this.counter += 1;
while (this.maxSize >= 0 && this._messages.length > this.maxSize) {
this._messages.shift();
}
},
getMessages: function (howMany) {
var firstMsg = 0;
if (!(typeof(howMany) == 'undefined' || howMany === null)) {
firstMsg = Math.max(0, this._messages.length - howMany);
}
return this._messages.slice(firstMsg);
},
getMessageText: function (howMany) {
if (typeof(howMany) == 'undefined' || howMany === null) {
howMany = 30;
}
var messages = this.getMessages(howMany);
if (messages.length) {
var lst = map(function (m) {
return '\n [' + m.num + '] ' + m.level + ': ' + m.info.join(' ');
}, messages);
lst.unshift('LAST ' + messages.length + ' MESSAGES:');
return lst.join('');
}
return '';
},
debuggingBookmarklet: function (inline) {
if (typeof(MochiKit.LoggingPane) == "undefined") {
alert(this.getMessageText());
} else {
MochiKit.LoggingPane.createLoggingPane(inline || false);
}
}
};
MochiKit.Logging.__new__ = function () {
this.LogLevel = {
ERROR: 40,
FATAL: 50,
WARNING: 30,
INFO: 20,
DEBUG: 10
};
var m = MochiKit.Base;
m.registerComparator("LogMessage",
this.isLogMessage,
this.compareLogMessage
);
var partial = m.partial;
var Logger = this.Logger;
var baseLog = Logger.prototype.baseLog;
m.update(this.Logger.prototype, {
debug: partial(baseLog, 'DEBUG'),
log: partial(baseLog, 'INFO'),
error: partial(baseLog, 'ERROR'),
fatal: partial(baseLog, 'FATAL'),
warning: partial(baseLog, 'WARNING')
});
// indirectly find logger so it can be replaced
var self = this;
var connectLog = function (name) {
return function () {
self.logger[name].apply(self.logger, arguments);
};
};
this.log = connectLog('log');
this.logError = connectLog('error');
this.logDebug = connectLog('debug');
this.logFatal = connectLog('fatal');
this.logWarning = connectLog('warning');
this.logger = new Logger();
this.logger.useNativeConsole = true;
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
m.nameFunctions(this);
};
if (typeof(printfire) == "undefined" &&
typeof(document) != "undefined" && document.createEvent &&
typeof(dispatchEvent) != "undefined") {
// FireBug really should be less lame about this global function
printfire = function () {
printfire.args = arguments;
var ev = document.createEvent("Events");
ev.initEvent("printfire", false, true);
dispatchEvent(ev);
};
}
MochiKit.Logging.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Logging);

View File

@@ -1,356 +0,0 @@
/***
MochiKit.LoggingPane 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.LoggingPane');
dojo.require('MochiKit.Logging');
dojo.require('MochiKit.Base');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Logging", []);
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined' || typeof(MochiKit.Logging) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.LoggingPane depends on MochiKit.Base and MochiKit.Logging!";
}
if (typeof(MochiKit.LoggingPane) == 'undefined') {
MochiKit.LoggingPane = {};
}
MochiKit.LoggingPane.NAME = "MochiKit.LoggingPane";
MochiKit.LoggingPane.VERSION = "1.3.1";
MochiKit.LoggingPane.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.LoggingPane.toString = function () {
return this.__repr__();
};
MochiKit.LoggingPane.createLoggingPane = function (inline/* = false */) {
var m = MochiKit.LoggingPane;
inline = !(!inline);
if (m._loggingPane && m._loggingPane.inline != inline) {
m._loggingPane.closePane();
m._loggingPane = null;
}
if (!m._loggingPane || m._loggingPane.closed) {
m._loggingPane = new m.LoggingPane(inline, MochiKit.Logging.logger);
}
return m._loggingPane;
};
MochiKit.LoggingPane.LoggingPane = function (inline/* = false */, logger/* = MochiKit.Logging.logger */) {
/* Use a div if inline, pop up a window if not */
/* Create the elements */
if (typeof(logger) == "undefined" || logger === null) {
logger = MochiKit.Logging.logger;
}
this.logger = logger;
var update = MochiKit.Base.update;
var updatetree = MochiKit.Base.updatetree;
var bind = MochiKit.Base.bind;
var clone = MochiKit.Base.clone;
var win = window;
var uid = "_MochiKit_LoggingPane";
if (typeof(MochiKit.DOM) != "undefined") {
win = MochiKit.DOM.currentWindow();
}
if (!inline) {
// name the popup with the base URL for uniqueness
var url = win.location.href.split("?")[0].replace(/[:\/.><&]/g, "_");
var name = uid + "_" + url;
var nwin = win.open("", name, "dependent,resizable,height=200");
if (!nwin) {
alert("Not able to open debugging window due to pop-up blocking.");
return undefined;
}
nwin.document.write(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" '
+ '"http://www.w3.org/TR/html4/loose.dtd">'
+ '<html><head><title>[MochiKit.LoggingPane]</title></head>'
+ '<body></body></html>'
);
nwin.document.close();
nwin.document.title += ' ' + win.document.title;
win = nwin;
}
var doc = win.document;
this.doc = doc;
// Connect to the debug pane if it already exists (i.e. in a window orphaned by the page being refreshed)
var debugPane = doc.getElementById(uid);
var existing_pane = !!debugPane;
if (debugPane && typeof(debugPane.loggingPane) != "undefined") {
debugPane.loggingPane.logger = this.logger;
debugPane.loggingPane.buildAndApplyFilter();
return debugPane.loggingPane;
}
if (existing_pane) {
// clear any existing contents
var child;
while ((child = debugPane.firstChild)) {
debugPane.removeChild(child);
}
} else {
debugPane = doc.createElement("div");
debugPane.id = uid;
}
debugPane.loggingPane = this;
var levelFilterField = doc.createElement("input");
var infoFilterField = doc.createElement("input");
var filterButton = doc.createElement("button");
var loadButton = doc.createElement("button");
var clearButton = doc.createElement("button");
var closeButton = doc.createElement("button");
var logPaneArea = doc.createElement("div");
var logPane = doc.createElement("div");
/* Set up the functions */
var listenerId = uid + "_Listener";
this.colorTable = clone(this.colorTable);
var messages = [];
var messageFilter = null;
var messageLevel = function (msg) {
var level = msg.level;
if (typeof(level) == "number") {
level = MochiKit.Logging.LogLevel[level];
}
return level;
};
var messageText = function (msg) {
return msg.info.join(" ");
};
var addMessageText = bind(function (msg) {
var level = messageLevel(msg);
var text = messageText(msg);
var c = this.colorTable[level];
var p = doc.createElement("span");
p.className = "MochiKit-LogMessage MochiKit-LogLevel-" + level;
p.style.cssText = "margin: 0px; white-space: -moz-pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word; wrap-option: emergency; color: " + c;
p.appendChild(doc.createTextNode(level + ": " + text));
logPane.appendChild(p);
logPane.appendChild(doc.createElement("br"));
if (logPaneArea.offsetHeight > logPaneArea.scrollHeight) {
logPaneArea.scrollTop = 0;
} else {
logPaneArea.scrollTop = logPaneArea.scrollHeight;
}
}, this);
var addMessage = function (msg) {
messages[messages.length] = msg;
addMessageText(msg);
};
var buildMessageFilter = function () {
var levelre, infore;
try {
/* Catch any exceptions that might arise due to invalid regexes */
levelre = new RegExp(levelFilterField.value);
infore = new RegExp(infoFilterField.value);
} catch(e) {
/* If there was an error with the regexes, do no filtering */
logDebug("Error in filter regex: " + e.message);
return null;
}
return function (msg) {
return (
levelre.test(messageLevel(msg)) &&
infore.test(messageText(msg))
);
};
};
var clearMessagePane = function () {
while (logPane.firstChild) {
logPane.removeChild(logPane.firstChild);
}
};
var clearMessages = function () {
messages = [];
clearMessagePane();
};
var closePane = bind(function () {
if (this.closed) {
return;
}
this.closed = true;
if (MochiKit.LoggingPane._loggingPane == this) {
MochiKit.LoggingPane._loggingPane = null;
}
this.logger.removeListener(listenerId);
debugPane.loggingPane = null;
if (inline) {
debugPane.parentNode.removeChild(debugPane);
} else {
this.win.close();
}
}, this);
var filterMessages = function () {
clearMessagePane();
for (var i = 0; i < messages.length; i++) {
var msg = messages[i];
if (messageFilter === null || messageFilter(msg)) {
addMessageText(msg);
}
}
};
this.buildAndApplyFilter = function () {
messageFilter = buildMessageFilter();
filterMessages();
this.logger.removeListener(listenerId);
this.logger.addListener(listenerId, messageFilter, addMessage);
};
var loadMessages = bind(function () {
messages = this.logger.getMessages();
filterMessages();
}, this);
var filterOnEnter = bind(function (event) {
event = event || window.event;
key = event.which || event.keyCode;
if (key == 13) {
this.buildAndApplyFilter();
}
}, this);
/* Create the debug pane */
var style = "display: block; z-index: 1000; left: 0px; bottom: 0px; position: fixed; width: 100%; background-color: white; font: " + this.logFont;
if (inline) {
style += "; height: 10em; border-top: 2px solid black";
} else {
style += "; height: 100%;";
}
debugPane.style.cssText = style;
if (!existing_pane) {
doc.body.appendChild(debugPane);
}
/* Create the filter fields */
style = {"cssText": "width: 33%; display: inline; font: " + this.logFont};
updatetree(levelFilterField, {
"value": "FATAL|ERROR|WARNING|INFO|DEBUG",
"onkeypress": filterOnEnter,
"style": style
});
debugPane.appendChild(levelFilterField);
updatetree(infoFilterField, {
"value": ".*",
"onkeypress": filterOnEnter,
"style": style
});
debugPane.appendChild(infoFilterField);
/* Create the buttons */
style = "width: 8%; display:inline; font: " + this.logFont;
filterButton.appendChild(doc.createTextNode("Filter"));
filterButton.onclick = bind("buildAndApplyFilter", this);
filterButton.style.cssText = style;
debugPane.appendChild(filterButton);
loadButton.appendChild(doc.createTextNode("Load"));
loadButton.onclick = loadMessages;
loadButton.style.cssText = style;
debugPane.appendChild(loadButton);
clearButton.appendChild(doc.createTextNode("Clear"));
clearButton.onclick = clearMessages;
clearButton.style.cssText = style;
debugPane.appendChild(clearButton);
closeButton.appendChild(doc.createTextNode("Close"));
closeButton.onclick = closePane;
closeButton.style.cssText = style;
debugPane.appendChild(closeButton);
/* Create the logging pane */
logPaneArea.style.cssText = "overflow: auto; width: 100%";
logPane.style.cssText = "width: 100%; height: " + (inline ? "8em" : "100%");
logPaneArea.appendChild(logPane);
debugPane.appendChild(logPaneArea);
this.buildAndApplyFilter();
loadMessages();
if (inline) {
this.win = undefined;
} else {
this.win = win;
}
this.inline = inline;
this.closePane = closePane;
this.closed = false;
return this;
};
MochiKit.LoggingPane.LoggingPane.prototype = {
"logFont": "8pt Verdana,sans-serif",
"colorTable": {
"ERROR": "red",
"FATAL": "darkred",
"WARNING": "blue",
"INFO": "black",
"DEBUG": "green"
}
};
MochiKit.LoggingPane.EXPORT_OK = [
"LoggingPane"
];
MochiKit.LoggingPane.EXPORT = [
"createLoggingPane"
];
MochiKit.LoggingPane.__new__ = function () {
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": MochiKit.Base.concat(this.EXPORT, this.EXPORT_OK)
};
MochiKit.Base.nameFunctions(this);
MochiKit.LoggingPane._loggingPane = null;
};
MochiKit.LoggingPane.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.LoggingPane);

View File

@@ -1,152 +0,0 @@
/***
MochiKit.MochiKit 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(MochiKit) == 'undefined') {
MochiKit = {};
}
if (typeof(MochiKit.MochiKit) == 'undefined') {
MochiKit.MochiKit = {};
}
MochiKit.MochiKit.NAME = "MochiKit.MochiKit";
MochiKit.MochiKit.VERSION = "1.3.1";
MochiKit.MochiKit.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.MochiKit.toString = function () {
return this.__repr__();
};
MochiKit.MochiKit.SUBMODULES = [
"Base",
"Iter",
"Logging",
"DateTime",
"Format",
"Async",
"DOM",
"LoggingPane",
"Color",
"Signal",
"Visual"
];
if (typeof(JSAN) != 'undefined' || typeof(dojo) != 'undefined') {
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.MochiKit');
dojo.require("MochiKit.*");
}
if (typeof(JSAN) != 'undefined') {
// hopefully this makes it easier for static analysis?
JSAN.use("MochiKit.Base", []);
JSAN.use("MochiKit.Iter", []);
JSAN.use("MochiKit.Logging", []);
JSAN.use("MochiKit.DateTime", []);
JSAN.use("MochiKit.Format", []);
JSAN.use("MochiKit.Async", []);
JSAN.use("MochiKit.DOM", []);
JSAN.use("MochiKit.LoggingPane", []);
JSAN.use("MochiKit.Color", []);
JSAN.use("MochiKit.Signal", []);
JSAN.use("MochiKit.Visual", []);
}
(function () {
var extend = MochiKit.Base.extend;
var self = MochiKit.MochiKit;
var modules = self.SUBMODULES;
var EXPORT = [];
var EXPORT_OK = [];
var EXPORT_TAGS = {};
var i, k, m, all;
for (i = 0; i < modules.length; i++) {
m = MochiKit[modules[i]];
extend(EXPORT, m.EXPORT);
extend(EXPORT_OK, m.EXPORT_OK);
for (k in m.EXPORT_TAGS) {
EXPORT_TAGS[k] = extend(EXPORT_TAGS[k], m.EXPORT_TAGS[k]);
}
all = m.EXPORT_TAGS[":all"];
if (!all) {
all = extend(null, m.EXPORT, m.EXPORT_OK);
}
var j;
for (j = 0; j < all.length; j++) {
k = all[j];
self[k] = m[k];
}
}
self.EXPORT = EXPORT;
self.EXPORT_OK = EXPORT_OK;
self.EXPORT_TAGS = EXPORT_TAGS;
}());
} else {
if (typeof(MochiKit.__compat__) == 'undefined') {
MochiKit.__compat__ = true;
}
(function () {
var scripts = document.getElementsByTagName("script");
var kXULNSURI = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var base = null;
var baseElem = null;
var allScripts = {};
var i;
for (i = 0; i < scripts.length; i++) {
var src = scripts[i].getAttribute("src");
if (!src) {
continue;
}
allScripts[src] = true;
if (src.match(/MochiKit.js$/)) {
base = src.substring(0, src.lastIndexOf('MochiKit.js'));
baseElem = scripts[i];
}
}
if (base === null) {
return;
}
var modules = MochiKit.MochiKit.SUBMODULES;
for (var i = 0; i < modules.length; i++) {
if (MochiKit[modules[i]]) {
continue;
}
var uri = base + modules[i] + '.js';
if (uri in allScripts) {
continue;
}
if (document.documentElement &&
document.documentElement.namespaceURI == kXULNSURI) {
// XUL
var s = document.createElementNS(kXULNSURI, 'script');
s.setAttribute("id", "MochiKit_" + base + modules[i]);
s.setAttribute("src", uri);
s.setAttribute("type", "application/x-javascript");
baseElem.parentNode.appendChild(s);
} else {
// HTML
/*
DOM can not be used here because Safari does
deferred loading of scripts unless they are
in the document or inserted with document.write
This is not XHTML compliant. If you want XHTML
compliance then you must use the packed version of MochiKit
or include each script individually (basically unroll
these document.write calls into your XHTML source)
*/
document.write('<script src="' + uri +
'" type="text/javascript"></script>');
}
};
})();
}

View File

@@ -1,73 +0,0 @@
/***
MochiKit.MockDOM 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(MochiKit) == "undefined") {
var MochiKit = {};
}
if (typeof(MochiKit.MockDOM) == "undefined") {
MochiKit.MockDOM = {};
}
MochiKit.MockDOM.NAME = "MochiKit.MockDOM";
MochiKit.MockDOM.VERSION = "1.3.1";
MochiKit.MockDOM.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.MockDOM.toString = function () {
return this.__repr__();
};
MochiKit.MockDOM.createDocument = function () {
var doc = new MochiKit.MockDOM.MockElement("DOCUMENT");
doc.body = doc.createElement("BODY");
doc.appendChild(doc.body);
return doc;
};
MochiKit.MockDOM.MockElement = function (name, data) {
this.nodeName = name.toUpperCase();
if (typeof(data) == "string") {
this.nodeValue = data;
this.nodeType = 3;
} else {
this.nodeType = 1;
this.childNodes = [];
}
if (name.substring(0, 1) == "<") {
var nameattr = name.substring(
name.indexOf('"') + 1, name.lastIndexOf('"'));
name = name.substring(1, name.indexOf(" "));
this.nodeName = name.toUpperCase();
this.setAttribute("name", nameattr);
}
};
MochiKit.MockDOM.MockElement.prototype = {
createElement: function (nodeName) {
return new MochiKit.MockDOM.MockElement(nodeName);
},
createTextNode: function (text) {
return new MochiKit.MockDOM.MockElement("text", text);
},
setAttribute: function (name, value) {
this[name] = value;
},
getAttribute: function (name) {
return this[name];
},
appendChild: function (child) {
this.childNodes.push(child);
},
toString: function () {
return "MockElement(" + this.nodeName + ")";
}
};

View File

@@ -1,680 +0,0 @@
/***
MochiKit.Signal 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2006 Jonathan Gardner, Beau Hartshorne, Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Signal');
dojo.require('MochiKit.Base');
dojo.require('MochiKit.DOM');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use('MochiKit.Base', []);
JSAN.use('MochiKit.DOM', []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw '';
}
} catch (e) {
throw 'MochiKit.Signal depends on MochiKit.Base!';
}
try {
if (typeof(MochiKit.DOM) == 'undefined') {
throw '';
}
} catch (e) {
throw 'MochiKit.Signal depends on MochiKit.DOM!';
}
if (typeof(MochiKit.Signal) == 'undefined') {
MochiKit.Signal = {};
}
MochiKit.Signal.NAME = 'MochiKit.Signal';
MochiKit.Signal.VERSION = '1.3.1';
MochiKit.Signal._observers = [];
MochiKit.Signal.Event = function (src, e) {
this._event = e || window.event;
this._src = src;
};
MochiKit.Base.update(MochiKit.Signal.Event.prototype, {
__repr__: function() {
var repr = MochiKit.Base.repr;
var str = '{event(): ' + repr(this.event()) +
', src(): ' + repr(this.src()) +
', type(): ' + repr(this.type()) +
', target(): ' + repr(this.target()) +
', modifier(): ' + '{alt: ' + repr(this.modifier().alt) +
', ctrl: ' + repr(this.modifier().ctrl) +
', meta: ' + repr(this.modifier().meta) +
', shift: ' + repr(this.modifier().shift) +
', any: ' + repr(this.modifier().any) + '}';
if (this.type() && this.type().indexOf('key') === 0) {
str += ', key(): {code: ' + repr(this.key().code) +
', string: ' + repr(this.key().string) + '}';
}
if (this.type() && (
this.type().indexOf('mouse') === 0 ||
this.type().indexOf('click') != -1 ||
this.type() == 'contextmenu')) {
str += ', mouse(): {page: ' + repr(this.mouse().page) +
', client: ' + repr(this.mouse().client);
if (this.type() != 'mousemove') {
str += ', button: {left: ' + repr(this.mouse().button.left) +
', middle: ' + repr(this.mouse().button.middle) +
', right: ' + repr(this.mouse().button.right) + '}}';
} else {
str += '}';
}
}
if (this.type() == 'mouseover' || this.type() == 'mouseout') {
str += ', relatedTarget(): ' + repr(this.relatedTarget());
}
str += '}';
return str;
},
toString: function () {
return this.__repr__();
},
src: function () {
return this._src;
},
event: function () {
return this._event;
},
type: function () {
return this._event.type || undefined;
},
target: function () {
return this._event.target || this._event.srcElement;
},
relatedTarget: function () {
if (this.type() == 'mouseover') {
return (this._event.relatedTarget ||
this._event.fromElement);
} else if (this.type() == 'mouseout') {
return (this._event.relatedTarget ||
this._event.toElement);
}
// throw new Error("relatedTarget only available for 'mouseover' and 'mouseout'");
return undefined;
},
modifier: function () {
var m = {};
m.alt = this._event.altKey;
m.ctrl = this._event.ctrlKey;
m.meta = this._event.metaKey || false; // IE and Opera punt here
m.shift = this._event.shiftKey;
m.any = m.alt || m.ctrl || m.shift || m.meta;
return m;
},
key: function () {
var k = {};
if (this.type() && this.type().indexOf('key') === 0) {
/*
If you're looking for a special key, look for it in keydown or
keyup, but never keypress. If you're looking for a Unicode
chracter, look for it with keypress, but never keyup or
keydown.
Notes:
FF key event behavior:
key event charCode keyCode
DOWN ku,kd 0 40
DOWN kp 0 40
ESC ku,kd 0 27
ESC kp 0 27
a ku,kd 0 65
a kp 97 0
shift+a ku,kd 0 65
shift+a kp 65 0
1 ku,kd 0 49
1 kp 49 0
shift+1 ku,kd 0 0
shift+1 kp 33 0
IE key event behavior:
(IE doesn't fire keypress events for special keys.)
key event keyCode
DOWN ku,kd 40
DOWN kp undefined
ESC ku,kd 27
ESC kp 27
a ku,kd 65
a kp 97
shift+a ku,kd 65
shift+a kp 65
1 ku,kd 49
1 kp 49
shift+1 ku,kd 49
shift+1 kp 33
Safari key event behavior:
(Safari sets charCode and keyCode to something crazy for
special keys.)
key event charCode keyCode
DOWN ku,kd 63233 40
DOWN kp 63233 63233
ESC ku,kd 27 27
ESC kp 27 27
a ku,kd 97 65
a kp 97 97
shift+a ku,kd 65 65
shift+a kp 65 65
1 ku,kd 49 49
1 kp 49 49
shift+1 ku,kd 33 49
shift+1 kp 33 33
*/
/* look for special keys here */
if (this.type() == 'keydown' || this.type() == 'keyup') {
k.code = this._event.keyCode;
k.string = (MochiKit.Signal._specialKeys[k.code] ||
'KEY_UNKNOWN');
return k;
/* look for characters here */
} else if (this.type() == 'keypress') {
/*
Special key behavior:
IE: does not fire keypress events for special keys
FF: sets charCode to 0, and sets the correct keyCode
Safari: sets keyCode and charCode to something stupid
*/
k.code = 0;
k.string = '';
if (typeof(this._event.charCode) != 'undefined' &&
this._event.charCode !== 0 &&
!MochiKit.Signal._specialMacKeys[this._event.charCode]) {
k.code = this._event.charCode;
k.string = String.fromCharCode(k.code);
} else if (this._event.keyCode &&
typeof(this._event.charCode) == 'undefined') { // IE
k.code = this._event.keyCode;
k.string = String.fromCharCode(k.code);
}
return k;
}
}
// throw new Error('This is not a key event');
return undefined;
},
mouse: function () {
var m = {};
var e = this._event;
if (this.type() && (
this.type().indexOf('mouse') === 0 ||
this.type().indexOf('click') != -1 ||
this.type() == 'contextmenu')) {
m.client = new MochiKit.DOM.Coordinates(0, 0);
if (e.clientX || e.clientY) {
m.client.x = (!e.clientX || e.clientX < 0) ? 0 : e.clientX;
m.client.y = (!e.clientY || e.clientY < 0) ? 0 : e.clientY;
}
m.page = new MochiKit.DOM.Coordinates(0, 0);
if (e.pageX || e.pageY) {
m.page.x = (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
m.page.y = (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
} else {
/*
IE keeps the document offset in:
document.documentElement.clientTop ||
document.body.clientTop
and:
document.documentElement.clientLeft ||
document.body.clientLeft
see:
http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/getboundingclientrect.asp
The offset is (2,2) in standards mode and (0,0) in quirks
mode.
*/
var de = MochiKit.DOM._document.documentElement;
var b = MochiKit.DOM._document.body;
m.page.x = e.clientX +
(de.scrollLeft || b.scrollLeft) -
(de.clientLeft || b.clientLeft);
m.page.y = e.clientY +
(de.scrollTop || b.scrollTop) -
(de.clientTop || b.clientTop);
}
if (this.type() != 'mousemove') {
m.button = {};
m.button.left = false;
m.button.right = false;
m.button.middle = false;
/* we could check e.button, but which is more consistent */
if (e.which) {
m.button.left = (e.which == 1);
m.button.middle = (e.which == 2);
m.button.right = (e.which == 3);
/*
Mac browsers and right click:
- Safari doesn't fire any click events on a right
click:
http://bugzilla.opendarwin.org/show_bug.cgi?id=6595
- Firefox fires the event, and sets ctrlKey = true
- Opera fires the event, and sets metaKey = true
oncontextmenu is fired on right clicks between
browsers and across platforms.
*/
} else {
m.button.left = !!(e.button & 1);
m.button.right = !!(e.button & 2);
m.button.middle = !!(e.button & 4);
}
}
return m;
}
// throw new Error('This is not a mouse event');
return undefined;
},
stop: function () {
this.stopPropagation();
this.preventDefault();
},
stopPropagation: function () {
if (this._event.stopPropagation) {
this._event.stopPropagation();
} else {
this._event.cancelBubble = true;
}
},
preventDefault: function () {
if (this._event.preventDefault) {
this._event.preventDefault();
} else {
this._event.returnValue = false;
}
}
});
/* Safari sets keyCode to these special values onkeypress. */
MochiKit.Signal._specialMacKeys = {
3: 'KEY_ENTER',
63289: 'KEY_NUM_PAD_CLEAR',
63276: 'KEY_PAGE_UP',
63277: 'KEY_PAGE_DOWN',
63275: 'KEY_END',
63273: 'KEY_HOME',
63234: 'KEY_ARROW_LEFT',
63232: 'KEY_ARROW_UP',
63235: 'KEY_ARROW_RIGHT',
63233: 'KEY_ARROW_DOWN',
63302: 'KEY_INSERT',
63272: 'KEY_DELETE'
};
/* for KEY_F1 - KEY_F12 */
for (i = 63236; i <= 63242; i++) {
MochiKit.Signal._specialMacKeys[i] = 'KEY_F' + (i - 63236 + 1); // no F0
}
/* Standard keyboard key codes. */
MochiKit.Signal._specialKeys = {
8: 'KEY_BACKSPACE',
9: 'KEY_TAB',
12: 'KEY_NUM_PAD_CLEAR', // weird, for Safari and Mac FF only
13: 'KEY_ENTER',
16: 'KEY_SHIFT',
17: 'KEY_CTRL',
18: 'KEY_ALT',
19: 'KEY_PAUSE',
20: 'KEY_CAPS_LOCK',
27: 'KEY_ESCAPE',
32: 'KEY_SPACEBAR',
33: 'KEY_PAGE_UP',
34: 'KEY_PAGE_DOWN',
35: 'KEY_END',
36: 'KEY_HOME',
37: 'KEY_ARROW_LEFT',
38: 'KEY_ARROW_UP',
39: 'KEY_ARROW_RIGHT',
40: 'KEY_ARROW_DOWN',
44: 'KEY_PRINT_SCREEN',
45: 'KEY_INSERT',
46: 'KEY_DELETE',
59: 'KEY_SEMICOLON', // weird, for Safari and IE only
91: 'KEY_WINDOWS_LEFT',
92: 'KEY_WINDOWS_RIGHT',
93: 'KEY_SELECT',
106: 'KEY_NUM_PAD_ASTERISK',
107: 'KEY_NUM_PAD_PLUS_SIGN',
109: 'KEY_NUM_PAD_HYPHEN-MINUS',
110: 'KEY_NUM_PAD_FULL_STOP',
111: 'KEY_NUM_PAD_SOLIDUS',
144: 'KEY_NUM_LOCK',
145: 'KEY_SCROLL_LOCK',
186: 'KEY_SEMICOLON',
187: 'KEY_EQUALS_SIGN',
188: 'KEY_COMMA',
189: 'KEY_HYPHEN-MINUS',
190: 'KEY_FULL_STOP',
191: 'KEY_SOLIDUS',
192: 'KEY_GRAVE_ACCENT',
219: 'KEY_LEFT_SQUARE_BRACKET',
220: 'KEY_REVERSE_SOLIDUS',
221: 'KEY_RIGHT_SQUARE_BRACKET',
222: 'KEY_APOSTROPHE'
// undefined: 'KEY_UNKNOWN'
};
/* for KEY_0 - KEY_9 */
for (var i = 48; i <= 57; i++) {
MochiKit.Signal._specialKeys[i] = 'KEY_' + (i - 48);
}
/* for KEY_A - KEY_Z */
for (i = 65; i <= 90; i++) {
MochiKit.Signal._specialKeys[i] = 'KEY_' + String.fromCharCode(i);
}
/* for KEY_NUM_PAD_0 - KEY_NUM_PAD_9 */
for (i = 96; i <= 105; i++) {
MochiKit.Signal._specialKeys[i] = 'KEY_NUM_PAD_' + (i - 96);
}
/* for KEY_F1 - KEY_F12 */
for (i = 112; i <= 123; i++) {
MochiKit.Signal._specialKeys[i] = 'KEY_F' + (i - 112 + 1); // no F0
}
MochiKit.Base.update(MochiKit.Signal, {
__repr__: function () {
return '[' + this.NAME + ' ' + this.VERSION + ']';
},
toString: function () {
return this.__repr__();
},
_unloadCache: function () {
var self = MochiKit.Signal;
var observers = self._observers;
for (var i = 0; i < observers.length; i++) {
self._disconnect(observers[i]);
}
delete self._observers;
try {
window.onload = undefined;
} catch(e) {
// pass
}
try {
window.onunload = undefined;
} catch(e) {
// pass
}
},
_listener: function (src, func, obj, isDOM) {
var E = MochiKit.Signal.Event;
if (!isDOM) {
return MochiKit.Base.bind(func, obj);
}
obj = obj || src;
if (typeof(func) == "string") {
return function (nativeEvent) {
obj[func].apply(obj, [new E(src, nativeEvent)]);
};
} else {
return function (nativeEvent) {
func.apply(obj, [new E(src, nativeEvent)]);
};
}
},
connect: function (src, sig, objOrFunc/* optional */, funcOrStr) {
src = MochiKit.DOM.getElement(src);
var self = MochiKit.Signal;
if (typeof(sig) != 'string') {
throw new Error("'sig' must be a string");
}
var obj = null;
var func = null;
if (typeof(funcOrStr) != 'undefined') {
obj = objOrFunc;
func = funcOrStr;
if (typeof(funcOrStr) == 'string') {
if (typeof(objOrFunc[funcOrStr]) != "function") {
throw new Error("'funcOrStr' must be a function on 'objOrFunc'");
}
} else if (typeof(funcOrStr) != 'function') {
throw new Error("'funcOrStr' must be a function or string");
}
} else if (typeof(objOrFunc) != "function") {
throw new Error("'objOrFunc' must be a function if 'funcOrStr' is not given");
} else {
func = objOrFunc;
}
if (typeof(obj) == 'undefined' || obj === null) {
obj = src;
}
var isDOM = !!(src.addEventListener || src.attachEvent);
var listener = self._listener(src, func, obj, isDOM);
if (src.addEventListener) {
src.addEventListener(sig.substr(2), listener, false);
} else if (src.attachEvent) {
src.attachEvent(sig, listener); // useCapture unsupported
}
var ident = [src, sig, listener, isDOM, objOrFunc, funcOrStr];
self._observers.push(ident);
return ident;
},
_disconnect: function (ident) {
// check isDOM
if (!ident[3]) { return; }
var src = ident[0];
var sig = ident[1];
var listener = ident[2];
if (src.removeEventListener) {
src.removeEventListener(sig.substr(2), listener, false);
} else if (src.detachEvent) {
src.detachEvent(sig, listener); // useCapture unsupported
} else {
throw new Error("'src' must be a DOM element");
}
},
disconnect: function (ident) {
var self = MochiKit.Signal;
var observers = self._observers;
var m = MochiKit.Base;
if (arguments.length > 1) {
// compatibility API
var src = MochiKit.DOM.getElement(arguments[0]);
var sig = arguments[1];
var obj = arguments[2];
var func = arguments[3];
for (var i = observers.length - 1; i >= 0; i--) {
var o = observers[i];
if (o[0] === src && o[1] === sig && o[4] === obj && o[5] === func) {
self._disconnect(o);
observers.splice(i, 1);
return true;
}
}
} else {
var idx = m.findIdentical(observers, ident);
if (idx >= 0) {
self._disconnect(ident);
observers.splice(idx, 1);
return true;
}
}
return false;
},
disconnectAll: function(src/* optional */, sig) {
src = MochiKit.DOM.getElement(src);
var m = MochiKit.Base;
var signals = m.flattenArguments(m.extend(null, arguments, 1));
var self = MochiKit.Signal;
var disconnect = self._disconnect;
var observers = self._observers;
if (signals.length === 0) {
// disconnect all
for (var i = observers.length - 1; i >= 0; i--) {
var ident = observers[i];
if (ident[0] === src) {
disconnect(ident);
observers.splice(i, 1);
}
}
} else {
var sigs = {};
for (var i = 0; i < signals.length; i++) {
sigs[signals[i]] = true;
}
for (var i = observers.length - 1; i >= 0; i--) {
var ident = observers[i];
if (ident[0] === src && ident[1] in sigs) {
disconnect(ident);
observers.splice(i, 1);
}
}
}
},
signal: function (src, sig) {
var observers = MochiKit.Signal._observers;
src = MochiKit.DOM.getElement(src);
var args = MochiKit.Base.extend(null, arguments, 2);
var errors = [];
for (var i = 0; i < observers.length; i++) {
var ident = observers[i];
if (ident[0] === src && ident[1] === sig) {
try {
ident[2].apply(src, args);
} catch (e) {
errors.push(e);
}
}
}
if (errors.length == 1) {
throw errors[0];
} else if (errors.length > 1) {
var e = new Error("Multiple errors thrown in handling 'sig', see errors property");
e.errors = errors;
throw e;
}
}
});
MochiKit.Signal.EXPORT_OK = [];
MochiKit.Signal.EXPORT = [
'connect',
'disconnect',
'signal',
'disconnectAll'
];
MochiKit.Signal.__new__ = function (win) {
var m = MochiKit.Base;
this._document = document;
this._window = win;
try {
this.connect(window, 'onunload', this._unloadCache);
} catch (e) {
// pass: might not be a browser
}
this.EXPORT_TAGS = {
':common': this.EXPORT,
':all': m.concat(this.EXPORT, this.EXPORT_OK)
};
m.nameFunctions(this);
};
MochiKit.Signal.__new__(this);
//
// XXX: Internet Explorer blows
//
if (!MochiKit.__compat__) {
connect = MochiKit.Signal.connect;
disconnect = MochiKit.Signal.disconnect;
disconnectAll = MochiKit.Signal.disconnectAll;
signal = MochiKit.Signal.signal;
}
MochiKit.Base._exportSymbols(this, MochiKit.Signal);

View File

@@ -1,181 +0,0 @@
/***
MochiKit.Test 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Test');
dojo.require('MochiKit.Base');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Test depends on MochiKit.Base!";
}
if (typeof(MochiKit.Test) == 'undefined') {
MochiKit.Test = {};
}
MochiKit.Test.NAME = "MochiKit.Test";
MochiKit.Test.VERSION = "1.3.1";
MochiKit.Test.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Test.toString = function () {
return this.__repr__();
};
MochiKit.Test.EXPORT = ["runTests"];
MochiKit.Test.EXPORT_OK = [];
MochiKit.Test.runTests = function (obj) {
if (typeof(obj) == "string") {
obj = JSAN.use(obj);
}
var suite = new MochiKit.Test.Suite();
suite.run(obj);
};
MochiKit.Test.Suite = function () {
this.testIndex = 0;
MochiKit.Base.bindMethods(this);
};
MochiKit.Test.Suite.prototype = {
run: function (obj) {
try {
obj(this);
} catch (e) {
this.traceback(e);
}
},
traceback: function (e) {
var items = MochiKit.Iter.sorted(MochiKit.Base.items(e));
print("not ok " + this.testIndex + " - Error thrown");
for (var i = 0; i < items.length; i++) {
var kv = items[i];
if (kv[0] == "stack") {
kv[1] = kv[1].split(/\n/)[0];
}
this.print("# " + kv.join(": "));
}
},
print: function (s) {
print(s);
},
is: function (got, expected, /* optional */message) {
var res = 1;
var msg = null;
try {
res = MochiKit.Base.compare(got, expected);
} catch (e) {
msg = "Can not compare " + typeof(got) + ":" + typeof(expected);
}
if (res) {
msg = "Expected value did not compare equal";
}
if (!res) {
return this.testResult(true, message);
}
return this.testResult(false, message,
[[msg], ["got:", got], ["expected:", expected]]);
},
testResult: function (pass, msg, failures) {
this.testIndex += 1;
if (pass) {
this.print("ok " + this.testIndex + " - " + msg);
return;
}
this.print("not ok " + this.testIndex + " - " + msg);
if (failures) {
for (var i = 0; i < failures.length; i++) {
this.print("# " + failures[i].join(" "));
}
}
},
isDeeply: function (got, expected, /* optional */message) {
var m = MochiKit.Base;
var res = 1;
try {
res = m.compare(got, expected);
} catch (e) {
// pass
}
if (res === 0) {
return this.ok(true, message);
}
var gk = m.keys(got);
var ek = m.keys(expected);
gk.sort();
ek.sort();
if (m.compare(gk, ek)) {
// differing keys
var cmp = {};
var i;
for (i = 0; i < gk.length; i++) {
cmp[gk[i]] = "got";
}
for (i = 0; i < ek.length; i++) {
if (ek[i] in cmp) {
delete cmp[ek[i]];
} else {
cmp[ek[i]] = "expected";
}
}
var diffkeys = m.keys(cmp);
diffkeys.sort();
var gotkeys = [];
var expkeys = [];
while (diffkeys.length) {
var k = diffkeys.shift();
if (k in Object.prototype) {
continue;
}
(cmp[k] == "got" ? gotkeys : expkeys).push(k);
}
}
return this.testResult((!res), msg,
(msg ? [["got:", got], ["expected:", expected]] : undefined)
);
},
ok: function (res, message) {
return this.testResult(res, message);
}
};
MochiKit.Test.__new__ = function () {
var m = MochiKit.Base;
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
m.nameFunctions(this);
};
MochiKit.Test.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Test);

View File

@@ -1,402 +0,0 @@
/***
MochiKit.Visual 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito and others. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide('MochiKit.Visual');
dojo.require('MochiKit.Base');
dojo.require('MochiKit.DOM');
dojo.require('MochiKit.Color');
}
if (typeof(JSAN) != 'undefined') {
JSAN.use("MochiKit.Base", []);
JSAN.use("MochiKit.DOM", []);
JSAN.use("MochiKit.Color", []);
}
try {
if (typeof(MochiKit.Base) == 'undefined' ||
typeof(MochiKit.DOM) == 'undefined' ||
typeof(MochiKit.Color) == 'undefined') {
throw "";
}
} catch (e) {
throw "MochiKit.Visual depends on MochiKit.Base, MochiKit.DOM and MochiKit.Color!";
}
if (typeof(MochiKit.Visual) == "undefined") {
MochiKit.Visual = {};
}
MochiKit.Visual.NAME = "MochiKit.Visual";
MochiKit.Visual.VERSION = "1.3.1";
MochiKit.Visual.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
MochiKit.Visual.toString = function () {
return this.__repr__();
};
MochiKit.Visual._RoundCorners = function (e, options) {
e = MochiKit.DOM.getElement(e);
this._setOptions(options);
if (this.options.__unstable__wrapElement) {
e = this._doWrap(e);
}
var color = this.options.color;
var C = MochiKit.Color.Color;
if (this.options.color == "fromElement") {
color = C.fromBackground(e);
} else if (!(color instanceof C)) {
color = C.fromString(color);
}
this.isTransparent = (color.asRGB().a <= 0);
var bgColor = this.options.bgColor;
if (this.options.bgColor == "fromParent") {
bgColor = C.fromBackground(e.offsetParent);
} else if (!(bgColor instanceof C)) {
bgColor = C.fromString(bgColor);
}
this._roundCornersImpl(e, color, bgColor);
};
MochiKit.Visual._RoundCorners.prototype = {
_doWrap: function (e) {
var parent = e.parentNode;
var doc = MochiKit.DOM.currentDocument();
if (typeof(doc.defaultView) == "undefined"
|| doc.defaultView === null) {
return e;
}
var style = doc.defaultView.getComputedStyle(e, null);
if (typeof(style) == "undefined" || style === null) {
return e;
}
var wrapper = MochiKit.DOM.DIV({"style": {
display: "block",
// convert padding to margin
marginTop: style.getPropertyValue("padding-top"),
marginRight: style.getPropertyValue("padding-right"),
marginBottom: style.getPropertyValue("padding-bottom"),
marginLeft: style.getPropertyValue("padding-left"),
// remove padding so the rounding looks right
padding: "0px"
/*
paddingRight: "0px",
paddingLeft: "0px"
*/
}});
wrapper.innerHTML = e.innerHTML;
e.innerHTML = "";
e.appendChild(wrapper);
return e;
},
_roundCornersImpl: function (e, color, bgColor) {
if (this.options.border) {
this._renderBorder(e, bgColor);
}
if (this._isTopRounded()) {
this._roundTopCorners(e, color, bgColor);
}
if (this._isBottomRounded()) {
this._roundBottomCorners(e, color, bgColor);
}
},
_renderBorder: function (el, bgColor) {
var borderValue = "1px solid " + this._borderColor(bgColor);
var borderL = "border-left: " + borderValue;
var borderR = "border-right: " + borderValue;
var style = "style='" + borderL + ";" + borderR + "'";
el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>";
},
_roundTopCorners: function (el, color, bgColor) {
var corner = this._createCorner(bgColor);
for (var i = 0; i < this.options.numSlices; i++) {
corner.appendChild(
this._createCornerSlice(color, bgColor, i, "top")
);
}
el.style.paddingTop = 0;
el.insertBefore(corner, el.firstChild);
},
_roundBottomCorners: function (el, color, bgColor) {
var corner = this._createCorner(bgColor);
for (var i = (this.options.numSlices - 1); i >= 0; i--) {
corner.appendChild(
this._createCornerSlice(color, bgColor, i, "bottom")
);
}
el.style.paddingBottom = 0;
el.appendChild(corner);
},
_createCorner: function (bgColor) {
var dom = MochiKit.DOM;
return dom.DIV({style: {backgroundColor: bgColor.toString()}});
},
_createCornerSlice: function (color, bgColor, n, position) {
var slice = MochiKit.DOM.SPAN();
var inStyle = slice.style;
inStyle.backgroundColor = color.toString();
inStyle.display = "block";
inStyle.height = "1px";
inStyle.overflow = "hidden";
inStyle.fontSize = "1px";
var borderColor = this._borderColor(color, bgColor);
if (this.options.border && n === 0) {
inStyle.borderTopStyle = "solid";
inStyle.borderTopWidth = "1px";
inStyle.borderLeftWidth = "0px";
inStyle.borderRightWidth = "0px";
inStyle.borderBottomWidth = "0px";
// assumes css compliant box model
inStyle.height = "0px";
inStyle.borderColor = borderColor.toString();
} else if (borderColor) {
inStyle.borderColor = borderColor.toString();
inStyle.borderStyle = "solid";
inStyle.borderWidth = "0px 1px";
}
if (!this.options.compact && (n == (this.options.numSlices - 1))) {
inStyle.height = "2px";
}
this._setMargin(slice, n, position);
this._setBorder(slice, n, position);
return slice;
},
_setOptions: function (options) {
this.options = {
corners: "all",
color: "fromElement",
bgColor: "fromParent",
blend: true,
border: false,
compact: false,
__unstable__wrapElement: false
};
MochiKit.Base.update(this.options, options);
this.options.numSlices = (this.options.compact ? 2 : 4);
},
_whichSideTop: function () {
var corners = this.options.corners;
if (this._hasString(corners, "all", "top")) {
return "";
}
var has_tl = (corners.indexOf("tl") != -1);
var has_tr = (corners.indexOf("tr") != -1);
if (has_tl && has_tr) {
return "";
}
if (has_tl) {
return "left";
}
if (has_tr) {
return "right";
}
return "";
},
_whichSideBottom: function () {
var corners = this.options.corners;
if (this._hasString(corners, "all", "bottom")) {
return "";
}
var has_bl = (corners.indexOf('bl') != -1);
var has_br = (corners.indexOf('br') != -1);
if (has_bl && has_br) {
return "";
}
if (has_bl) {
return "left";
}
if (has_br) {
return "right";
}
return "";
},
_borderColor: function (color, bgColor) {
if (color == "transparent") {
return bgColor;
} else if (this.options.border) {
return this.options.border;
} else if (this.options.blend) {
return bgColor.blendedColor(color);
}
return "";
},
_setMargin: function (el, n, corners) {
var marginSize = this._marginSize(n) + "px";
var whichSide = (
corners == "top" ? this._whichSideTop() : this._whichSideBottom()
);
var style = el.style;
if (whichSide == "left") {
style.marginLeft = marginSize;
style.marginRight = "0px";
} else if (whichSide == "right") {
style.marginRight = marginSize;
style.marginLeft = "0px";
} else {
style.marginLeft = marginSize;
style.marginRight = marginSize;
}
},
_setBorder: function (el, n, corners) {
var borderSize = this._borderSize(n) + "px";
var whichSide = (
corners == "top" ? this._whichSideTop() : this._whichSideBottom()
);
var style = el.style;
if (whichSide == "left") {
style.borderLeftWidth = borderSize;
style.borderRightWidth = "0px";
} else if (whichSide == "right") {
style.borderRightWidth = borderSize;
style.borderLeftWidth = "0px";
} else {
style.borderLeftWidth = borderSize;
style.borderRightWidth = borderSize;
}
},
_marginSize: function (n) {
if (this.isTransparent) {
return 0;
}
var o = this.options;
if (o.compact && o.blend) {
var smBlendedMarginSizes = [1, 0];
return smBlendedMarginSizes[n];
} else if (o.compact) {
var compactMarginSizes = [2, 1];
return compactMarginSizes[n];
} else if (o.blend) {
var blendedMarginSizes = [3, 2, 1, 0];
return blendedMarginSizes[n];
} else {
var marginSizes = [5, 3, 2, 1];
return marginSizes[n];
}
},
_borderSize: function (n) {
var o = this.options;
var borderSizes;
if (o.compact && (o.blend || this.isTransparent)) {
return 1;
} else if (o.compact) {
borderSizes = [1, 0];
} else if (o.blend) {
borderSizes = [2, 1, 1, 1];
} else if (o.border) {
borderSizes = [0, 2, 0, 0];
} else if (this.isTransparent) {
borderSizes = [5, 3, 2, 1];
} else {
return 0;
}
return borderSizes[n];
},
_hasString: function (str) {
for (var i = 1; i< arguments.length; i++) {
if (str.indexOf(arguments[i]) != -1) {
return true;
}
}
return false;
},
_isTopRounded: function () {
return this._hasString(this.options.corners,
"all", "top", "tl", "tr"
);
},
_isBottomRounded: function () {
return this._hasString(this.options.corners,
"all", "bottom", "bl", "br"
);
},
_hasSingleTextChild: function (el) {
return (el.childNodes.length == 1 && el.childNodes[0].nodeType == 3);
}
};
MochiKit.Visual.roundElement = function (e, options) {
new MochiKit.Visual._RoundCorners(e, options);
};
MochiKit.Visual.roundClass = function (tagName, className, options) {
var elements = MochiKit.DOM.getElementsByTagAndClassName(
tagName, className
);
for (var i = 0; i < elements.length; i++) {
MochiKit.Visual.roundElement(elements[i], options);
}
};
// Compatibility with MochiKit 1.0
MochiKit.Visual.Color = MochiKit.Color.Color;
MochiKit.Visual.getElementsComputedStyle = MochiKit.DOM.computedStyle;
/* end of Rico adaptation */
MochiKit.Visual.__new__ = function () {
var m = MochiKit.Base;
m.nameFunctions(this);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
};
MochiKit.Visual.EXPORT = [
"roundElement",
"roundClass"
];
MochiKit.Visual.EXPORT_OK = [];
MochiKit.Visual.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Visual);

View File

@@ -1,17 +0,0 @@
dojo.hostenv.conditionalLoadModule({
"common": [
"MochiKit.Base",
"MochiKit.Iter",
"MochiKit.Logging",
"MochiKit.DateTime",
"MochiKit.Format",
"MochiKit.Async",
"MochiKit.Color"
],
"browser": [
"MochiKit.DOM",
"MochiKit.LoggingPane",
"MochiKit.Visual"
]
});
dojo.hostenv.moduleLoaded("MochiKit.*");

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 971 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 591 B

View File

@@ -1,163 +0,0 @@
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
/* Container Styles */
.calcontainer {*height:1%;} /* IE */
.calcontainer:after {content:'.';clear:both;display:block;visibility:hidden;height:0;} /* others */
.calbordered {
float:left;
padding:5px;
background-color:#F7F9FB;
border:1px solid #7B9EBD;
}
.calbordered .title {
font:73% Arial,Helvetica,sans-serif;
color:#000;
font-weight:bold;
margin-bottom:5px;
height:auto;
width:304px;
position:relative;
}
.title .close-icon {
position:absolute;
right:0;
top:0;
border:none;
}
.cal2up {
float:left;
}
.calnavleft {
position:absolute;
top:0;
bottom:0;
height:12px;
left:2px;
}
.calnavright {
position:absolute;
top:0;
bottom:0;
height:12px;
right:2px;
}
/* Calendar element styles */
.calendar {
font:73% Arial,Helvetica,sans-serif;
text-align:center;
border-spacing:0;
}
td.calcell {
width:1.5em;
height:1em;
border:1px solid #E0E0E0;
background-color:#FFF;
}
.calendar.wait td.calcell {
color:#999;
background-color:#CCC;
}
.calendar.wait td.calcell a {
color:#999;
font-style:italic;
}
td.calcell a {
color:#003DB8;
text-decoration:none;
}
td.calcell.today {
border:1px solid #000;
}
td.calcell.oom {
cursor:default;
color:#999;
background-color:#EEE;
border:1px solid #E0E0E0;
}
td.calcell.selected {
color:#003DB8;
background-color:#FFF19F;
border:1px solid #FF9900;
}
td.calcell.calcellhover {
cursor:pointer;
color:#FFF;
background-color:#FF9900;
border:1px solid #FF9900;
}
/* Added to perform some correction for Opera 8.5
hover redraw bug */
table:hover {
background-color:#FFF;
}
td.calcell.calcellhover a {
color:#FFF;
}
td.calcell.restricted {
text-decoration:line-through;
}
td.calcell.previous {
color:#CCC;
}
td.calcell.highlight1 { background-color:#CCFF99; }
td.calcell.highlight2 { background-color:#99CCFF; }
td.calcell.highlight3 { background-color:#FFCCCC; }
td.calcell.highlight4 { background-color:#CCFF99; }
.calhead {
border:1px solid #E0E0E0;
vertical-align:middle;
background-color:#FFF;
}
.calheader {
position:relative;
width:100%;
}
.calheader img {
border:none;
}
.calweekdaycell {
color:#666;
font-weight:normal;
}
.calfoot {
background-color:#EEE;
}
.calrowhead, .calrowfoot {
color:#666;
font-size:9px;
font-style:italic;
font-weight:normal;
width:15px;
}
.calrowhead {
border-right-width:2px;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 B

View File

@@ -1,206 +0,0 @@
.overlay {
position:absolute;
display:block;
}
.tt {
visibility:hidden;
position:absolute;
color:#333;
background-color:#FDFFB4;
font-family:arial,helvetica,verdana,sans-serif;
padding:2px;
border:1px solid #FCC90D;
font:100% sans-serif;
width:auto;
}
* html body.masked select {
visibility:hidden;
}
* html div.panel-container select {
visibility:inherit;
}
* html div.drag select {
visibility:hidden;
}
* html div.hide-select select {
visibility:hidden;
}
.mask {
z-index:0;
display:none;
position:absolute;
top:0;
left:0;
background-color:#CCC;
-moz-opacity: 0.5;
opacity:.50;
filter: alpha(opacity=50);
}
.mask[id]{ /* IE6 and below Can't See This */
position:fixed;
}
.hide-scrollbars * {
overflow:hidden;
}
.hide-scrollbars textarea, .hide-scrollbars select {
overflow:hidden;
display:none;
}
.show-scrollbars textarea, .show-scrollbars select {
overflow:visible;
}
.panel-container {
position:absolute;
background-color:transparent;
z-index:6;
visibility:hidden;
overflow:visible;
width:auto;
}
.panel-container.matte {
padding:3px;
background-color:#FFF;
}
.panel-container.matte .underlay {
display:none;
}
.panel-container.shadow {
padding:0px;
background-color:transparent;
}
.panel-container.shadow .underlay {
visibility:inherit;
position:absolute;
background-color:#CCC;
top:3px;left:3px;
z-index:0;
width:100%;
height:100%;
-moz-opacity: 0.7;
opacity:.70;
filter:alpha(opacity=70);
}
.panel {
visibility:hidden;
border-collapse:separate;
position:relative;
left:0px;top:0px;
font:1em Arial;
background-color:#FFF;
border:1px solid #000;
z-index:1;
overflow:auto;
}
.panel .hd {
background-color:#3d77cb;
color:#FFF;
font-size:1em;
height:1em;
border:1px solid #FFF;
border-bottom:1px solid #000;
font-weight:bold;
overflow:hidden;
padding:4px;
}
.panel .bd {
overflow:hidden;
padding:4px;
}
.panel .bd p {
margin:0 0 1em;
}
.panel .close {
position:absolute;
top:5px;
right:4px;
z-index:6;
height:12px;
width:12px;
margin:0px;
padding:0px;
background-repeat:no-repeat;
cursor:pointer;
visibility:inherit;
}
.panel .close.nonsecure {
background-image:url(http://us.i1.yimg.com/us.yimg.com/i/nt/ic/ut/alt3/close12_1.gif);
}
.panel .close.secure {
background-image:url(https://a248.e.akamai.net/sec.yimg.com/i/nt/ic/ut/alt3/close12_1.gif);
}
.panel .ft {
padding:4px;
overflow:hidden;
}
.simple-dialog .bd .icon {
background-repeat:no-repeat;
width:16px;
height:16px;
margin-right:10px;
float:left;
}
.dialog .ft, .simple-dialog .ft {
padding-bottom:5px;
padding-right:5px;
text-align:right;
}
.dialog form, .simple-dialog form {
margin:0;
}
.button-group button {
font:100 76% verdana;
text-decoration:none;
background-color: #E4E4E4;
color: #333;
cursor: hand;
vertical-align: middle;
border: 2px solid #797979;
border-top-color:#FFF;
border-left-color:#FFF;
margin:2px;
padding:2px;
}
.button-group button.default {
font-weight:bold;
}
.button-group button:hover, .button-group button.hover {
border:2px solid #90A029;
background-color:#EBF09E;
border-top-color:#FFF;
border-left-color:#FFF;
}
.button-group button:active {
border:2px solid #E4E4E4;
background-color:#BBB;
border-top-color:#333;
border-left-color:#333;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 928 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 601 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 B

Some files were not shown because too many files have changed in this diff Show More