From df9807ce08af0de3338d6b5932c425c4e9b28126 Mon Sep 17 00:00:00 2001 From: "edburns%acm.org" Date: Tue, 8 May 2001 20:34:31 +0000 Subject: [PATCH] bug 79278 This checkin migrates javaDOM to use the new nsIWebProgressListener interface, removing its dependency on the now non-existant nsIDocumentLoaderObserver. It has only been tested inside webclient. QA needs to do the standalone javaDOM tests. The following files are in this bugfix: dom/jni/org_mozilla_dom_DOMAccessor.cpp dom/src/nsIJavaDOM.h dom/src/nsJavaDOMImpl.cpp dom/src/nsJavaDOMImpl.h webclient/classes_spec/org/mozilla/webclient/test/EMWindow.java webclient/classes_spec/org/mozilla/webclient/wrapper_native/CurrentPageImpl.java git-svn-id: svn://10.0.0.236/trunk@94264 18797224-902f-48f8-a5cc-f745e15eee43 --- .../dom/jni/org_mozilla_dom_DOMAccessor.cpp | 256 ++- mozilla/java/dom/src/nsIJavaDOM.h | 144 +- mozilla/java/dom/src/nsJavaDOMImpl.cpp | 1413 ++++++------ mozilla/java/dom/src/nsJavaDOMImpl.h | 144 +- .../org/mozilla/webclient/test/EMWindow.java | 1906 ++++++++--------- .../wrapper_native/CurrentPageImpl.java | 554 ++--- 6 files changed, 2259 insertions(+), 2158 deletions(-) diff --git a/mozilla/java/dom/jni/org_mozilla_dom_DOMAccessor.cpp b/mozilla/java/dom/jni/org_mozilla_dom_DOMAccessor.cpp index 9ccf6f966bf..2ba3d9f4412 100644 --- a/mozilla/java/dom/jni/org_mozilla_dom_DOMAccessor.cpp +++ b/mozilla/java/dom/jni/org_mozilla_dom_DOMAccessor.cpp @@ -1,118 +1,138 @@ - -#include "prlog.h" -#include "javaDOMGlobals.h" -#include "nsIDocumentLoader.h" -#include "nsIDocumentLoaderObserver.h" -#include "nsIServiceManager.h" -#include "nsCURILoader.h" - -#include "nsIJavaDOM.h" -#include "org_mozilla_dom_DOMAccessor.h" - -static NS_DEFINE_IID(kDocLoaderServiceCID, NS_DOCUMENTLOADER_SERVICE_CID); -static NS_DEFINE_IID(kJavaDOMCID, NS_JAVADOM_CID); - -/* - * Class: org_mozilla_dom_DOMAccessor - * Method: register - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_register - (JNIEnv *env, jclass jthis) -{ - if (!JavaDOMGlobals::log) { - JavaDOMGlobals::Initialize(env); - } - nsresult rv = NS_OK; - NS_WITH_SERVICE(nsIDocumentLoader, docLoaderService, kDocLoaderServiceCID, &rv); - if (NS_FAILED(rv) || !docLoaderService) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::register: GetService(JavaDOM) failed: %x\n", - rv)); - } else { - NS_WITH_SERVICE(nsIDocumentLoaderObserver, javaDOM, kJavaDOMCID, &rv); - if (NS_FAILED(rv) || !javaDOM) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::register: GetService(JavaDOM) failed: %x\n", - rv)); - } else { - rv = docLoaderService->AddObserver((nsIDocumentLoaderObserver*)javaDOM); - if (NS_FAILED(rv)) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::register: AddObserver(JavaDOM) failed x\n", - rv)); - } - } - } -} - -/* - * Class: org_mozilla_dom_DOMAccessor - * Method: unregister - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_unregister - (JNIEnv *, jclass jthis) -{ - PR_LOG(JavaDOMGlobals::log, PR_LOG_DEBUG, - ("DOMAccessor::unregister: unregistering %x\n", jthis)); - - nsresult rv = NS_OK; - NS_WITH_SERVICE(nsIDocumentLoader, docLoaderService, kDocLoaderServiceCID, &rv); - if (NS_FAILED(rv) || !docLoaderService) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::unregister: GetService(DocLoaderService) failed %x\n", - rv)); - } else { - NS_WITH_SERVICE(nsIDocumentLoaderObserver, javaDOM, kJavaDOMCID, &rv); - if (NS_FAILED(rv) || !javaDOM) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::unregister: GetService(JavaDOM) failed %x\n", - rv)); - } else { - rv = docLoaderService->RemoveObserver((nsIDocumentLoaderObserver*)javaDOM); - if (NS_FAILED(rv)) { - PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, - ("DOMAccessor::unregister: RemoveObserver(JavaDOM) failed x\n", - rv)); - } - } - } -} - -/* - * Class: org_mozilla_dom_DOMAccessor - * Method: createElement - * Signature: (J)Lorg/w3c/dom/Element; - */ -JNIEXPORT jobject JNICALL Java_org_mozilla_dom_DOMAccessor_getNodeByHandle - (JNIEnv *env, jclass jthis, jlong p) -{ - if (!JavaDOMGlobals::log) { - JavaDOMGlobals::Initialize(env); - } - nsIDOMNode *node = (nsIDOMNode*)p; - return JavaDOMGlobals::CreateNodeSubtype(env, node); -} - -/* - * Class: org_mozilla_dom_DOMAccessor - * Method: doGC - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_doGC - (JNIEnv *, jclass) -{ - JavaDOMGlobals::TakeOutGarbage(); -} - -JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_initialize -(JNIEnv *env, jclass) -{ - if (!JavaDOMGlobals::log) { - JavaDOMGlobals::Initialize(env); - } - -} - - + +#include "prlog.h" +#include "javaDOMGlobals.h" +#include "nsIDocumentLoader.h" +#include "nsIWebProgress.h" +#include "nsIWebProgressListener.h" +#include "nsIServiceManager.h" +#include "nsCURILoader.h" + +#include "nsIJavaDOM.h" +#include "org_mozilla_dom_DOMAccessor.h" + +static NS_DEFINE_IID(kJavaDOMCID, NS_JAVADOM_CID); + +/* + * Class: org_mozilla_dom_DOMAccessor + * Method: register + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_register + (JNIEnv *env, jclass jthis) +{ + if (!JavaDOMGlobals::log) { + JavaDOMGlobals::Initialize(env); + } + nsresult rv = NS_OK; + nsCOMPtr docLoaderService = + do_GetService(NS_URI_LOADER_CONTRACTID, &rv); + nsCOMPtr webProgressService; + + if (NS_FAILED(rv) || !docLoaderService) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::register: GetService(JavaDOM) failed: %x\n", + rv)); + } else { + NS_WITH_SERVICE(nsIWebProgressListener, javaDOM, kJavaDOMCID, &rv); + if (NS_FAILED(rv) || !javaDOM) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::register: GetService(JavaDOM) failed: %x\n", + rv)); + } else { + webProgressService = do_QueryInterface(docLoaderService, &rv); + if (NS_FAILED(rv) || !webProgressService) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::register: QueryInterface(nsIWebProgressService) failed: %x\n", + rv)); + } else { + rv = webProgressService->AddProgressListener((nsIWebProgressListener*)javaDOM); + if (NS_FAILED(rv)) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::register: AddObserver(JavaDOM) failed x\n", + rv)); + } + } + } + } +} + +/* + * Class: org_mozilla_dom_DOMAccessor + * Method: unregister + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_unregister + (JNIEnv *, jclass jthis) +{ + PR_LOG(JavaDOMGlobals::log, PR_LOG_DEBUG, + ("DOMAccessor::unregister: unregistering %x\n", jthis)); + + nsresult rv = NS_OK; + nsCOMPtr docLoaderService = + do_GetService(NS_URI_LOADER_CONTRACTID, &rv); + nsCOMPtr webProgressService; + + if (NS_FAILED(rv) || !docLoaderService) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::unregister: GetService(DocLoaderService) failed %x\n", + rv)); + } else { + NS_WITH_SERVICE(nsIWebProgressListener, javaDOM, kJavaDOMCID, &rv); + if (NS_FAILED(rv) || !javaDOM) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::unregister: GetService(JavaDOM) failed %x\n", + rv)); + } else { + webProgressService = do_QueryInterface(docLoaderService, &rv); + if (NS_FAILED(rv) || !webProgressService) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::unregister: QueryInterface(nsIWebProgressService) failed: %x\n", + rv)); + } else { + rv = webProgressService->RemoveProgressListener((nsIWebProgressListener*)javaDOM); + if (NS_FAILED(rv)) { + PR_LOG(JavaDOMGlobals::log, PR_LOG_ERROR, + ("DOMAccessor::unregister: RemoveObserver(JavaDOM) failed x\n", + rv)); + } + } + } + } +} + +/* + * Class: org_mozilla_dom_DOMAccessor + * Method: createElement + * Signature: (J)Lorg/w3c/dom/Element; + */ +JNIEXPORT jobject JNICALL Java_org_mozilla_dom_DOMAccessor_getNodeByHandle + (JNIEnv *env, jclass jthis, jlong p) +{ + if (!JavaDOMGlobals::log) { + JavaDOMGlobals::Initialize(env); + } + nsIDOMNode *node = (nsIDOMNode*)p; + return JavaDOMGlobals::CreateNodeSubtype(env, node); +} + +/* + * Class: org_mozilla_dom_DOMAccessor + * Method: doGC + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_doGC + (JNIEnv *, jclass) +{ + JavaDOMGlobals::TakeOutGarbage(); +} + +JNIEXPORT void JNICALL Java_org_mozilla_dom_DOMAccessor_initialize +(JNIEnv *env, jclass) +{ + if (!JavaDOMGlobals::log) { + JavaDOMGlobals::Initialize(env); + } + +} + + diff --git a/mozilla/java/dom/src/nsIJavaDOM.h b/mozilla/java/dom/src/nsIJavaDOM.h index 214c2f6c7f4..4406fde8992 100644 --- a/mozilla/java/dom/src/nsIJavaDOM.h +++ b/mozilla/java/dom/src/nsIJavaDOM.h @@ -1,75 +1,69 @@ -/* - 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 mozilla.org code. - - The Initial Developer of the Original Code is Sun Microsystems, - Inc. Portions created by Sun are - Copyright (C) 1999 Sun Microsystems, Inc. All - Rights Reserved. - - Contributor(s): -*/ - -#ifndef __nsIJavaDOM_h__ -#define __nsIJavaDOM_h__ - -#include "nsISupports.h" -#include "nsString.h" -#include "nsIDocumentLoaderObserver.h" -#include "jni.h" - -class nsIURI; - -/* {9cc0ca50-0e31-11d3-8a61-0004ac56c4a5} */ -#define NS_IJAVADOM_IID_STR "9cc0ca50-0e31-11d3-8a61-0004ac56c4a5" -#define NS_IJAVADOM_IID \ - {0x9cc0ca50, 0x0e31, 0x11d3, \ - { 0x8a, 0x61, 0x00, 0x04, 0xac, 0x56, 0xc4, 0xa5 }} -#define NS_JAVADOM_CID \ - {0xd6b2e820, 0x9113, 0x11d3, \ - { 0x9c, 0x11, 0x0, 0x10, 0x5a , 0xe3, 0x80 , 0x1e }} - -class nsIJavaDOM : public nsIDocumentLoaderObserver { - public: - NS_DEFINE_STATIC_IID_ACCESSOR(NS_IJAVADOM_IID) - - /* nsIDocumentLoaderObserver methods */ - NS_IMETHOD OnStartDocumentLoad(nsIDocumentLoader* loader, - nsIURI* aURL, - const char* aCommand) = 0; - - NS_IMETHOD OnEndDocumentLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsresult aStatus) = 0; - - NS_IMETHOD OnStartURLLoad(nsIDocumentLoader* loader, - nsIRequest* request) = 0; - - NS_IMETHOD OnProgressURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - PRUint32 aProgress, - PRUint32 aProgressMax) = 0; - - NS_IMETHOD OnStatusURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsString& aMsg) = 0; - - NS_IMETHOD OnEndURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsresult aStatus) = 0; - - NS_IMETHOD HandleUnknownContentType(nsIDocumentLoader* loader, - nsIChannel* channel, - const char *aContentType, - const char *aCommand) = 0; -}; -#endif /* __nsIJavaDOM_h__ */ +/* + 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 mozilla.org code. + + The Initial Developer of the Original Code is Sun Microsystems, + Inc. Portions created by Sun are + Copyright (C) 1999 Sun Microsystems, Inc. All + Rights Reserved. + + Contributor(s): +*/ + +#ifndef __nsIJavaDOM_h__ +#define __nsIJavaDOM_h__ + +#include "nsISupports.h" +#include "nsString.h" +#include "nsIWebProgressListener.h" +#include "jni.h" + +class nsIURI; + +/* {9cc0ca50-0e31-11d3-8a61-0004ac56c4a5} */ +#define NS_IJAVADOM_IID_STR "9cc0ca50-0e31-11d3-8a61-0004ac56c4a5" +#define NS_IJAVADOM_IID \ + {0x9cc0ca50, 0x0e31, 0x11d3, \ + { 0x8a, 0x61, 0x00, 0x04, 0xac, 0x56, 0xc4, 0xa5 }} +#define NS_JAVADOM_CID \ + {0xd6b2e820, 0x9113, 0x11d3, \ + { 0x9c, 0x11, 0x0, 0x10, 0x5a , 0xe3, 0x80 , 0x1e }} + +class nsIJavaDOM : public nsIWebProgressListener { + public: + NS_DEFINE_STATIC_IID_ACCESSOR(NS_IJAVADOM_IID) + + NS_IMETHOD OnStateChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, + PRInt32 aStateFlags, PRUint32 aStatus) = 0; + + NS_IMETHOD OnProgressChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, PRInt32 aCurSelfProgress, + PRInt32 aMaxSelfProgress, + PRInt32 aCurTotalProgress, + PRInt32 aMaxTotalProgress) = 0; + + NS_IMETHOD OnLocationChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, nsIURI *location) = 0; + + NS_IMETHOD OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, + nsresult aStatus, const PRUnichar *aMessage) = 0; + + NS_IMETHOD OnSecurityChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, PRInt32 state) = 0; + + + NS_IMETHOD HandleUnknownContentType(nsIDocumentLoader* loader, + nsIChannel* channel, + const char *aContentType, + const char *aCommand) = 0; +}; +#endif /* __nsIJavaDOM_h__ */ diff --git a/mozilla/java/dom/src/nsJavaDOMImpl.cpp b/mozilla/java/dom/src/nsJavaDOMImpl.cpp index 8af060e9261..d5ba570d617 100644 --- a/mozilla/java/dom/src/nsJavaDOMImpl.cpp +++ b/mozilla/java/dom/src/nsJavaDOMImpl.cpp @@ -1,658 +1,755 @@ -/* - 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 mozilla.org code. - - The Initial Developer of the Original Code is Sun Microsystems, - Inc. Portions created by Sun are - Copyright (C) 1999 Sun Microsystems, Inc. All - Rights Reserved. - - Contributor(s): -*/ - -#include "prenv.h" -#include "nsISupportsUtils.h" -#include "nsIURL.h" -#include "nsIChannel.h" -#include "nsIDocument.h" -#include "nsIDocumentLoader.h" -#include "nsIDocumentLoaderObserver.h" -#include "nsIDocumentViewer.h" -#include "nsIDOMDocument.h" -#include "nsIDocShell.h" -#include "nsJavaDOMImpl.h" - -#include "nsIModule.h" -#include "nsIGenericFactory.h" - -#if defined(DEBUG) -#include -#include "nsIDOMElement.h" -#include "nsIDOMNodeList.h" -#include "nsIDOMNamedNodeMap.h" -static void dump_document(nsIDOMDocument* dom, const char* urlSpec); -static void dump_node(FILE* of, nsIDOMNode* node, int indent, - PRBool isMapNode); -static void dump_map(FILE* of, nsIDOMNamedNodeMap* map, int indent); -static char* strip_whitespace(const PRUnichar* input, int length); -static const char* describe_type(int type); -#endif - -#ifdef JAVA_DOM_OJI_ENABLE -#include "ProxyJNI.h" -#include "nsIServiceManager.h" -nsJVMManager* nsJavaDOMImpl::jvmManager = NULL; -JavaDOMSecurityContext* nsJavaDOMImpl::securityContext = NULL; -static NS_DEFINE_CID(kJVMManagerCID,NS_JVMMANAGER_CID); -#else -JavaVM* nsJavaDOMImpl::jvm = NULL; -#endif - -static NS_DEFINE_IID(kIDocShellIID, NS_IDOCSHELL_IID); -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static NS_DEFINE_IID(kIJavaDOMIID, NS_IJAVADOM_IID); -static NS_DEFINE_IID(kIDocumentViewerIID, NS_IDOCUMENT_VIEWER_IID); -static NS_DEFINE_IID(kIDOMDocumentIID, NS_IDOMDOCUMENT_IID); -static NS_DEFINE_IID(kIDocumentLoaderObserverIID, NS_IDOCUMENT_LOADER_OBSERVER_IID); - -NS_IMPL_ADDREF(nsJavaDOMImpl); -NS_IMPL_RELEASE(nsJavaDOMImpl); - -jclass nsJavaDOMImpl::domAccessorClass = NULL; - -jmethodID nsJavaDOMImpl::startURLLoadMID = NULL; -jmethodID nsJavaDOMImpl::endURLLoadMID = NULL; -jmethodID nsJavaDOMImpl::progressURLLoadMID = NULL; -jmethodID nsJavaDOMImpl::statusURLLoadMID = NULL; -jmethodID nsJavaDOMImpl::startDocumentLoadMID = NULL; -jmethodID nsJavaDOMImpl::endDocumentLoadMID = NULL; - -#define NS_JAVADOM_PROGID \ -"component://netscape/blackwood/java-dom" - -NS_GENERIC_FACTORY_CONSTRUCTOR(nsJavaDOMImpl) - -static nsModuleComponentInfo components[] = -{ - { - "Java DOM", - NS_JAVADOM_CID, - NS_JAVADOM_PROGID, - nsJavaDOMImplConstructor - } -}; - -NS_IMPL_NSGETMODULE("JavaDOMModule",components); - -NS_IMETHODIMP nsJavaDOMImpl::QueryInterface(REFNSIID aIID, void** aInstance) -{ - if (NULL == aInstance) - return NS_ERROR_NULL_POINTER; - - *aInstance = NULL; - - if (aIID.Equals(kIJavaDOMIID)) { - *aInstance = (void*) ((nsIJavaDOM*)this); - NS_ADDREF_THIS(); - return NS_OK; - } - if (aIID.Equals(kIDocumentLoaderObserverIID)) { - *aInstance = (void*) ((nsIDocumentLoaderObserver*)this); - NS_ADDREF_THIS(); - return NS_OK; - } - if (aIID.Equals(kISupportsIID)) { - *aInstance = (void*) ((nsISupports*)this); - NS_ADDREF_THIS(); - return NS_OK; - } - - return NS_NOINTERFACE; -} - -nsJavaDOMImpl::nsJavaDOMImpl() -{ - NS_INIT_ISUPPORTS(); -} - -PRBool nsJavaDOMImpl::Init(JNIEnv** jniEnv) { - JNIEnv* env = GetJNIEnv(); - if (!env) return PR_FALSE; - *jniEnv = env; - - if (!domAccessorClass) { - domAccessorClass = env->FindClass("org/mozilla/dom/DOMAccessor"); - if (!domAccessorClass) return PR_FALSE; - domAccessorClass = (jclass) env->NewGlobalRef(domAccessorClass); - if (!domAccessorClass) return PR_FALSE; - - startURLLoadMID = - env->GetStaticMethodID(domAccessorClass, - "startURLLoad", - "(Ljava/lang/String;Ljava/lang/String;J)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - - endURLLoadMID = - env->GetStaticMethodID(domAccessorClass, - "endURLLoad", - "(Ljava/lang/String;IJ)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - - progressURLLoadMID = - env->GetStaticMethodID(domAccessorClass, - "progressURLLoad", - "(Ljava/lang/String;IIJ)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - - statusURLLoadMID = - env->GetStaticMethodID(domAccessorClass, - "statusURLLoad", - "(Ljava/lang/String;Ljava/lang/String;J)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - - startDocumentLoadMID = - env->GetStaticMethodID(domAccessorClass, - "startDocumentLoad", - "(Ljava/lang/String;)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - - endDocumentLoadMID = - env->GetStaticMethodID(domAccessorClass, - "endDocumentLoad", - "(Ljava/lang/String;IJ)V"); - if (Cleanup(env) == PR_TRUE) { - domAccessorClass = NULL; - return PR_FALSE; - } - } - return PR_TRUE; -} - -nsJavaDOMImpl::~nsJavaDOMImpl() -{ -} - -PRBool nsJavaDOMImpl::Cleanup(JNIEnv* env) -{ - if (env->ExceptionOccurred()) { - env->ExceptionDescribe(); - return PR_TRUE; - } - return PR_FALSE; -} - -nsIDOMDocument* nsJavaDOMImpl::GetDocument(nsIDocumentLoader* loader) -{ - nsIDocShell* docshell = nsnull; - nsISupports* container = nsnull; - nsIContentViewer* contentv = nsnull; - nsIDocumentViewer* docv = nsnull; - nsIDocument* document = nsnull; - nsIDOMDocument* domDoc = nsnull; - - nsresult rv = loader->GetContainer(&container); - if (NS_SUCCEEDED(rv) && container) { - rv = container->QueryInterface(kIDocShellIID, (void**) &docshell); - container->Release(); - if (NS_SUCCEEDED(rv) && docshell) { - rv = docshell->GetContentViewer(&contentv); - docshell->Release(); - if (NS_SUCCEEDED(rv) && contentv) { - rv = contentv->QueryInterface(kIDocumentViewerIID, (void**) &docv); - contentv->Release(); - if (NS_SUCCEEDED(rv) && docv) { - rv = docv->GetDocument(document); - docv->Release(); - if (NS_SUCCEEDED(rv) && document) { - rv = document->QueryInterface(kIDOMDocumentIID, (void**) &domDoc); - if (NS_SUCCEEDED(rv) && docv) { - return domDoc; - } - } - } - } - } - } - - fprintf(stderr, - "nsJavaDOMImpl::GetDocument: failed: " - "container=%x, webshell=%x, contentViewer=%x, " - "documentViewer=%x, document=%x, " - "domDocument=%x, error=%x\n", - (unsigned) (void*) container, - (unsigned) (void*) docshell, - (unsigned) (void*) contentv, - (unsigned) (void*) docv, - (unsigned) (void*) document, - (unsigned) (void*) domDoc, - rv); - return NULL; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnStartDocumentLoad(nsIDocumentLoader* loader, - nsIURI* aURL, - const char* aCommand) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - if (aURL) - aURL->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - env->CallStaticVoidMethod(domAccessorClass, - startDocumentLoadMID, - jURL); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnEndDocumentLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsresult aStatus) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - nsIURI* url = nsnull; - nsCOMPtr channel = do_QueryInterface(request); - if (channel && NS_SUCCEEDED(channel->GetURI(&url))) - url->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - nsIDOMDocument* domDoc = GetDocument(loader); - env->CallStaticVoidMethod(domAccessorClass, - endDocumentLoadMID, - jURL, - (jint) aStatus, - (jlong)domDoc); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnStartURLLoad(nsIDocumentLoader* loader, - nsIRequest* request) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - nsIURI* url = nsnull; - nsCOMPtr channel = do_QueryInterface(request); - if (channel && NS_SUCCEEDED(channel->GetURI(&url))) - url->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - char* contentType = (char*) ""; - if (channel) - channel->GetContentType(&contentType); - if (!contentType) - contentType = (char*) ""; - jstring jContentType = env->NewStringUTF(contentType); - if (!jContentType) return NS_ERROR_FAILURE; - - nsIDOMDocument* domDoc = GetDocument(loader); - env->CallStaticVoidMethod(domAccessorClass, - startURLLoadMID, - jURL, - jContentType, - (jlong)domDoc); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnProgressURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - PRUint32 aProgress, - PRUint32 aProgressMax) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - nsIURI* url = nsnull; - nsCOMPtr channel = do_QueryInterface(request); - if (channel && NS_SUCCEEDED(channel->GetURI(&url))) - url->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - nsIDOMDocument* domDoc = GetDocument(loader); - env->CallStaticVoidMethod(domAccessorClass, - progressURLLoadMID, - jURL, - (jint) aProgress, - (jint) aProgressMax, - (jlong)domDoc); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnStatusURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsString& aMsg) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - nsIURI* url = nsnull; - nsCOMPtr channel = do_QueryInterface(request); - if (channel && NS_SUCCEEDED(channel->GetURI(&url))) - url->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - const PRUnichar* cMsg = aMsg.GetUnicode(); - jstring jMessage = env->NewString(cMsg, aMsg.Length()); - if (!jMessage) return NS_ERROR_FAILURE; - - nsIDOMDocument* domDoc = GetDocument(loader); - env->CallStaticVoidMethod(domAccessorClass, - statusURLLoadMID, - jURL, - jMessage, - (jlong)domDoc); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::OnEndURLLoad(nsIDocumentLoader* loader, - nsIRequest* request, - nsresult aStatus) -{ - JNIEnv* env = NULL; - if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; - - char* urlSpec = (char*) ""; - nsIURI* url = nsnull; - nsCOMPtr channel = do_QueryInterface(request); - if (channel && NS_SUCCEEDED(channel->GetURI(&url))) - url->GetSpec(&urlSpec); - jstring jURL = env->NewStringUTF(urlSpec); - if (!jURL) return NS_ERROR_FAILURE; - - nsIDOMDocument* domDoc = GetDocument(loader); -#if defined(DEBUG) - dump_document(domDoc, urlSpec); -#endif - env->CallStaticVoidMethod(domAccessorClass, - endURLLoadMID, - jURL, - (jint) aStatus, - (jlong)domDoc); - if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; - return NS_OK; -} - -NS_IMETHODIMP nsJavaDOMImpl::HandleUnknownContentType(nsIDocumentLoader* loader, - nsIChannel* channel, - const char *aContentType, - const char *aCommand) -{ - return NS_OK; -} - -JNIEnv* nsJavaDOMImpl::GetJNIEnv() { - JNIEnv* env; -#ifdef JAVA_DOM_OJI_ENABLE - nsresult result; - if (!jvmManager) { - NS_WITH_SERVICE(nsIJVMManager, _jvmManager, kJVMManagerCID, &result); - if (NS_SUCCEEDED(result)) { - jvmManager = (nsJVMManager*)((nsIJVMManager*)_jvmManager); - } - } - if (!jvmManager) { - return NULL; - } - jvmManager->CreateProxyJNI(NULL,&env); -// if (!securityContext) { -// securityContext = new JavaDOMSecurityContext(); -// } -// SetSecurityContext(env, securityContext); - SetSecurityContext(env, new JavaDOMSecurityContext()); -#else /* JAVA_DOM_OJI_ENABLE */ - if (!jvm) { - StartJVM(); - } -#ifdef XP_PC - jvm->AttachCurrentThread((void**)&env,NULL); -#else - jvm->AttachCurrentThread(&env,NULL); -#endif -#endif /* JAVA_DOM_OJI_ENABLE */ - return env; -} - -#ifndef JAVA_DOM_OJI_ENABLE -void nsJavaDOMImpl::StartJVM(void) { - jsize jvmCount; - JNI_GetCreatedJavaVMs(&jvm, 1, &jvmCount); - if (jvmCount) { - return; - } - - JNIEnv *env = NULL; - JDK1_1InitArgs vm_args; - JNI_GetDefaultJavaVMInitArgs(&vm_args); - vm_args.version = 0x00010001; - vm_args.verifyMode = JNI_TRUE; -#ifdef DEBUG - vm_args.verbose = JNI_TRUE; - vm_args.enableVerboseGC = JNI_TRUE; -#endif // DEBUG - char* cp = PR_GetEnv("CLASSPATH"); - char* p = new char[strlen(cp) + strlen(vm_args.classpath) + 2]; - strcpy(p, vm_args.classpath); - if (cp) { -#ifdef XP_PC - strcat(p, ";"); -#else - strcat(p, ":"); -#endif - strcat(p, cp); - vm_args.classpath = p; - } - -#ifdef DISABLE_JIT - /* workaround to get java dom to work on Linux */ - char **props = new char*[2]; - props[0]="java.compiler="; - props[1]=0; - vm_args.properties = props; -#endif - -#ifdef DEBUG - printf("classpath is \"%s\"\n", vm_args.classpath); -#endif // DEBUG -#ifdef XP_PC - jint rv = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); -#else - jint rv = JNI_CreateJavaVM(&jvm, &env, &vm_args); -#endif - if (rv < 0) { - printf("\n JAVA DOM: could not start jvm\n"); - } else { - printf("\n JAVA DOM: successfully started jvm\n"); - } - delete[] p; -} -#endif /* JAVA_DOM_OJI_ENABLE */ - - -#if defined(DEBUG) -static void dump_document(nsIDOMDocument* domDoc, const char* urlSpec) -{ - if (!domDoc) return; - - if (strstr(urlSpec, ".xul") || - strstr(urlSpec, ".js") || - strstr(urlSpec, ".css") || - strstr(urlSpec, "file:")) return; - - FILE* of = fopen("dom-cpp.txt", "a"); - if (!of) { - perror("nsJavaDOMImpl::dump_document: failed to open output file\n"); - return; - } - - nsIDOMElement* element = nsnull; - nsresult rv = domDoc->GetDocumentElement(&element); - if (NS_FAILED(rv) || !element) - return; - - (void) element->Normalize(); - - fprintf(of, "\n+++ %s +++\n", urlSpec); - dump_node(of, (nsIDOMNode*) element, 0, PR_FALSE); - fprintf(of, "\n"); - fflush(of); - fclose(of); -} - -static void dump_node(FILE* of, nsIDOMNode* node, int indent, - PRBool isMapNode) -{ - if (!node) return; - - fprintf(of, "\n"); - for (int i=0; i < indent; i++) - fprintf(of, " "); - - nsString name; - nsString value; - PRUint16 type; - - node->GetNodeName(name); - node->GetNodeValue(value); - node->GetNodeType(&type); - - const PRUnichar* cname = name.GetUnicode(); - const PRUnichar* cvalue = value.GetUnicode(); - char* cnorm = strip_whitespace(cvalue, value.Length()); - fprintf(of, "name=\"%s\" type=%s value=\"%s\"", - cname, describe_type(type), cnorm); - delete[] cnorm; - - if (isMapNode) return; - - nsIDOMNamedNodeMap* map = nsnull; - node->GetAttributes(&map); - dump_map(of, map, indent); - - nsIDOMNodeList* children = nsnull; - node->GetChildNodes(&children); - if (!children) return; - - PRUint32 length=0; - children->GetLength(&length); - for (PRUint32 j=0; j < length; j++) { - nsIDOMNode* child = nsnull; - children->Item(j, &child); - dump_node(of, child, indent+2, PR_FALSE); - } -} - -static void dump_map(FILE* of, nsIDOMNamedNodeMap* map, int indent) -{ - if (!map) return; - - fprintf(of, "\n"); - PRUint32 length=0; - map->GetLength(&length); - if (length > 0) { - for (int i=0; i < indent; i++) - fprintf(of, " "); - fprintf(of, "------- start attributes -------"); - } - - for (PRUint32 j=0; j < length; j++) { - nsIDOMNode* node = nsnull; - map->Item(j, &node); - dump_node(of, node, indent, PR_TRUE); - } - - if (length > 0) { - fprintf(of, "\n"); - for (int k=0; k < indent; k++) - fprintf(of, " "); - fprintf(of, "------- end attributes -------"); - } -} - -static char* strip_whitespace(const PRUnichar* input, int length) -{ - if (!input || length < 1) { - char* out = new char[1]; - out[0] = 0; - return out; - } - - char* out = new char[length+1]; - char* op = out; - const PRUnichar* ip = input; - PRUnichar c = ' '; - PRUnichar pc = ' '; - int i = 0; - - for (c = *ip++; i++ +#include "nsIDOMElement.h" +#include "nsIDOMNodeList.h" +#include "nsIDOMNamedNodeMap.h" +static void dump_document(nsIDOMDocument* dom, const char* urlSpec); +static void dump_node(FILE* of, nsIDOMNode* node, int indent, + PRBool isMapNode); +static void dump_map(FILE* of, nsIDOMNamedNodeMap* map, int indent); +static char* strip_whitespace(const PRUnichar* input, int length); +static const char* describe_type(int type); +#endif + +#ifdef JAVA_DOM_OJI_ENABLE +#include "ProxyJNI.h" +#include "nsIServiceManager.h" +nsJVMManager* nsJavaDOMImpl::jvmManager = NULL; +JavaDOMSecurityContext* nsJavaDOMImpl::securityContext = NULL; +static NS_DEFINE_CID(kJVMManagerCID,NS_JVMMANAGER_CID); +#else +JavaVM* nsJavaDOMImpl::jvm = NULL; +#endif + +static NS_DEFINE_IID(kIDocShellIID, NS_IDOCSHELL_IID); +static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); +static NS_DEFINE_IID(kIJavaDOMIID, NS_IJAVADOM_IID); +static NS_DEFINE_IID(kIDocumentViewerIID, NS_IDOCUMENT_VIEWER_IID); +static NS_DEFINE_IID(kIDOMDocumentIID, NS_IDOMDOCUMENT_IID); +static NS_DEFINE_IID(kIWebProgressListenerIID, NS_IWEBPROGRESSLISTENER_IID); + +NS_IMPL_ADDREF(nsJavaDOMImpl); +NS_IMPL_RELEASE(nsJavaDOMImpl); + +jclass nsJavaDOMImpl::domAccessorClass = NULL; + +jmethodID nsJavaDOMImpl::startURLLoadMID = NULL; +jmethodID nsJavaDOMImpl::endURLLoadMID = NULL; +jmethodID nsJavaDOMImpl::progressURLLoadMID = NULL; +jmethodID nsJavaDOMImpl::statusURLLoadMID = NULL; +jmethodID nsJavaDOMImpl::startDocumentLoadMID = NULL; +jmethodID nsJavaDOMImpl::endDocumentLoadMID = NULL; + +#define NS_JAVADOM_PROGID \ +"component://netscape/blackwood/java-dom" + +NS_GENERIC_FACTORY_CONSTRUCTOR(nsJavaDOMImpl) + +static nsModuleComponentInfo components[] = +{ + { + "Java DOM", + NS_JAVADOM_CID, + NS_JAVADOM_PROGID, + nsJavaDOMImplConstructor + } +}; + +NS_IMPL_NSGETMODULE("JavaDOMModule",components); + +NS_IMETHODIMP nsJavaDOMImpl::QueryInterface(REFNSIID aIID, void** aInstance) +{ + if (NULL == aInstance) + return NS_ERROR_NULL_POINTER; + + *aInstance = NULL; + + if (aIID.Equals(kIJavaDOMIID)) { + *aInstance = (void*) ((nsIJavaDOM*)this); + NS_ADDREF_THIS(); + return NS_OK; + } + if (aIID.Equals(kIWebProgressListenerIID)) { + *aInstance = (void*) ((nsIWebProgressListener*)this); + NS_ADDREF_THIS(); + return NS_OK; + } + if (aIID.Equals(kISupportsIID)) { + *aInstance = (void*) ((nsISupports*)this); + NS_ADDREF_THIS(); + return NS_OK; + } + + return NS_NOINTERFACE; +} + +nsJavaDOMImpl::nsJavaDOMImpl() +{ + NS_INIT_ISUPPORTS(); +} + +PRBool nsJavaDOMImpl::Init(JNIEnv** jniEnv) { + JNIEnv* env = GetJNIEnv(); + if (!env) return PR_FALSE; + *jniEnv = env; + + if (!domAccessorClass) { + domAccessorClass = env->FindClass("org/mozilla/dom/DOMAccessor"); + if (!domAccessorClass) return PR_FALSE; + domAccessorClass = (jclass) env->NewGlobalRef(domAccessorClass); + if (!domAccessorClass) return PR_FALSE; + + startURLLoadMID = + env->GetStaticMethodID(domAccessorClass, + "startURLLoad", + "(Ljava/lang/String;Ljava/lang/String;J)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + + endURLLoadMID = + env->GetStaticMethodID(domAccessorClass, + "endURLLoad", + "(Ljava/lang/String;IJ)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + + progressURLLoadMID = + env->GetStaticMethodID(domAccessorClass, + "progressURLLoad", + "(Ljava/lang/String;IIJ)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + + statusURLLoadMID = + env->GetStaticMethodID(domAccessorClass, + "statusURLLoad", + "(Ljava/lang/String;Ljava/lang/String;J)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + + startDocumentLoadMID = + env->GetStaticMethodID(domAccessorClass, + "startDocumentLoad", + "(Ljava/lang/String;)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + + endDocumentLoadMID = + env->GetStaticMethodID(domAccessorClass, + "endDocumentLoad", + "(Ljava/lang/String;IJ)V"); + if (Cleanup(env) == PR_TRUE) { + domAccessorClass = NULL; + return PR_FALSE; + } + } + return PR_TRUE; +} + +nsJavaDOMImpl::~nsJavaDOMImpl() +{ +} + +PRBool nsJavaDOMImpl::Cleanup(JNIEnv* env) +{ + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + return PR_TRUE; + } + return PR_FALSE; +} + +nsIDOMDocument* nsJavaDOMImpl::GetDocument(nsIDocumentLoader* loader) +{ + nsIDocShell* docshell = nsnull; + nsISupports* container = nsnull; + nsIContentViewer* contentv = nsnull; + nsIDocumentViewer* docv = nsnull; + nsIDocument* document = nsnull; + nsIDOMDocument* domDoc = nsnull; + + nsresult rv = loader->GetContainer(&container); + if (NS_SUCCEEDED(rv) && container) { + rv = container->QueryInterface(kIDocShellIID, (void**) &docshell); + container->Release(); + if (NS_SUCCEEDED(rv) && docshell) { + rv = docshell->GetContentViewer(&contentv); + docshell->Release(); + if (NS_SUCCEEDED(rv) && contentv) { + rv = contentv->QueryInterface(kIDocumentViewerIID, (void**) &docv); + contentv->Release(); + if (NS_SUCCEEDED(rv) && docv) { + rv = docv->GetDocument(document); + docv->Release(); + if (NS_SUCCEEDED(rv) && document) { + rv = document->QueryInterface(kIDOMDocumentIID, (void**) &domDoc); + if (NS_SUCCEEDED(rv) && docv) { + return domDoc; + } + } + } + } + } + } + + fprintf(stderr, + "nsJavaDOMImpl::GetDocument: failed: " + "container=%x, webshell=%x, contentViewer=%x, " + "documentViewer=%x, document=%x, " + "domDocument=%x, error=%x\n", + (unsigned) (void*) container, + (unsigned) (void*) docshell, + (unsigned) (void*) contentv, + (unsigned) (void*) docv, + (unsigned) (void*) document, + (unsigned) (void*) domDoc, + rv); + return NULL; +} + +// +// nsIWebProgressListener implementation +// + +NS_IMETHODIMP nsJavaDOMImpl::OnStateChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, + PRInt32 aStateFlags, + PRUint32 aStatus) +{ + nsXPIDLString name; + nsresult rv; + + + if ((aStateFlags & STATE_START) && (aStateFlags & STATE_IS_DOCUMENT)) { + if (NS_FAILED(rv = aRequest->GetName(getter_Copies(name)))) { + return rv; + } + doStartDocumentLoad(name.get()); + } + if ((aStateFlags & STATE_STOP) && (aStateFlags & STATE_IS_DOCUMENT)) { + doEndDocumentLoad(aWebProgress, aRequest, aStatus); + } + + return NS_OK; +} + +NS_IMETHODIMP nsJavaDOMImpl::OnSecurityChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, + PRInt32 state) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +/* void onProgressChange (in nsIChannel channel, in long curSelfProgress, in long maxSelfProgress, in long curTotalProgress, in long maxTotalProgress); */ +NS_IMETHODIMP nsJavaDOMImpl::OnProgressChange(nsIWebProgress *aWebProgress, + nsIRequest *request, + PRInt32 aCurSelfProgress, + PRInt32 aMaxSelfProgress, + PRInt32 curTotalProgress, + PRInt32 maxTotalProgress) +{ + nsCOMPtr domWin; + nsCOMPtr domDoc; + nsresult rv; + + if (nsnull != aWebProgress) { + if (NS_SUCCEEDED(aWebProgress->GetDOMWindow(getter_AddRefs(domWin))) + && domWin) { + if (NS_FAILED(rv = domWin->GetDocument(getter_AddRefs(domDoc)))) { + return rv; + } + } + } + + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + char* urlSpec = (char*) ""; + nsIURI* url = nsnull; + nsCOMPtr channel = do_QueryInterface(request); + if (channel && NS_SUCCEEDED(channel->GetURI(&url))) + url->GetSpec(&urlSpec); + jstring jURL = env->NewStringUTF(urlSpec); + if (!jURL) return NS_ERROR_FAILURE; + // PENDING(edburns): this leaks. + + env->CallStaticVoidMethod(domAccessorClass, + progressURLLoadMID, + jURL, + (jint) curTotalProgress, + (jint) maxTotalProgress, + (jlong)domDoc.get()); + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} + +/* void onStatusChange (in nsIChannel channel, in long progressStatusFlags); */ +NS_IMETHODIMP nsJavaDOMImpl::OnStatusChange(nsIWebProgress *aWebProgress, + nsIRequest *request, + nsresult aStatus, + const PRUnichar *cMsg) +{ + nsCOMPtr domWin; + nsCOMPtr domDoc; + nsresult rv; + + if (nsnull != aWebProgress) { + if (NS_SUCCEEDED(aWebProgress->GetDOMWindow(getter_AddRefs(domWin))) + && domWin) { + if (NS_FAILED(rv = domWin->GetDocument(getter_AddRefs(domDoc)))) { + return rv; + } + } + } + + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + char* urlSpec = (char*) ""; + nsIURI* url = nsnull; + nsCOMPtr channel = do_QueryInterface(request); + if (channel && NS_SUCCEEDED(channel->GetURI(&url))) + url->GetSpec(&urlSpec); + jstring jURL = env->NewStringUTF(urlSpec); + if (!jURL) return NS_ERROR_FAILURE; + // PENDING(edburns): this leaks + + jstring jMessage = env->NewString(cMsg, nsCRT::strlen(cMsg)); + if (!jMessage) return NS_ERROR_FAILURE; + + env->CallStaticVoidMethod(domAccessorClass, + statusURLLoadMID, + jURL, + jMessage, + (jlong)domDoc.get()); + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} + +/* void onLocationChange (in nsIURI location); */ +NS_IMETHODIMP nsJavaDOMImpl::OnLocationChange(nsIWebProgress *aWebProgress, + nsIRequest *aRequest, + nsIURI *location) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +// +// helper methods for nsIWebProgressListener +// + +NS_IMETHODIMP nsJavaDOMImpl::doStartDocumentLoad(const PRUnichar *documentName) +{ + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + if (!documentName) { + return NS_ERROR_FAILURE; + } + jstring jURL = env->NewString(documentName, nsCRT::strlen(documentName)); + if (!jURL) return NS_ERROR_FAILURE; + + env->CallStaticVoidMethod(domAccessorClass, + startDocumentLoadMID, + jURL); + // PENDING(edburns): this leaks jURL. A bug? + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} + +NS_IMETHODIMP nsJavaDOMImpl::doStartUrlLoad(const PRUnichar *documentName) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP nsJavaDOMImpl::doEndDocumentLoad(nsIWebProgress *aWebProgress, + nsIRequest *request, + PRUint32 aStatus) +{ + nsCOMPtr domWin; + nsCOMPtr domDoc; + nsresult rv; + + if (nsnull != aWebProgress) { + if (NS_SUCCEEDED(aWebProgress->GetDOMWindow(getter_AddRefs(domWin))) + && domWin) { + if (NS_FAILED(rv = domWin->GetDocument(getter_AddRefs(domDoc)))) { + return rv; + } + } + } + + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + char* urlSpec = (char*) ""; + nsIURI* url = nsnull; + nsCOMPtr channel = do_QueryInterface(request); + if (channel && NS_SUCCEEDED(channel->GetURI(&url))) + url->GetSpec(&urlSpec); + jstring jURL = env->NewStringUTF(urlSpec); + if (!jURL) return NS_ERROR_FAILURE; + + env->CallStaticVoidMethod(domAccessorClass, + endDocumentLoadMID, + jURL, + (jint) aStatus, + (jlong)domDoc.get()); + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} + +#if 0 +NS_IMETHODIMP nsJavaDOMImpl::OnStartURLLoad(nsIDocumentLoader* loader, + nsIRequest* request) +{ + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + char* urlSpec = (char*) ""; + nsIURI* url = nsnull; + nsCOMPtr channel = do_QueryInterface(request); + if (channel && NS_SUCCEEDED(channel->GetURI(&url))) + url->GetSpec(&urlSpec); + jstring jURL = env->NewStringUTF(urlSpec); + if (!jURL) return NS_ERROR_FAILURE; + + char* contentType = (char*) ""; + if (channel) + channel->GetContentType(&contentType); + if (!contentType) + contentType = (char*) ""; + jstring jContentType = env->NewStringUTF(contentType); + if (!jContentType) return NS_ERROR_FAILURE; + + nsIDOMDocument* domDoc = GetDocument(loader); + env->CallStaticVoidMethod(domAccessorClass, + startURLLoadMID, + jURL, + jContentType, + (jlong)domDoc); + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} + +NS_IMETHODIMP nsJavaDOMImpl::OnEndURLLoad(nsIDocumentLoader* loader, + nsIRequest* request, + nsresult aStatus) +{ + JNIEnv* env = NULL; + if (Init(&env) == PR_FALSE) return NS_ERROR_FAILURE; + + char* urlSpec = (char*) ""; + nsIURI* url = nsnull; + nsCOMPtr channel = do_QueryInterface(request); + if (channel && NS_SUCCEEDED(channel->GetURI(&url))) + url->GetSpec(&urlSpec); + jstring jURL = env->NewStringUTF(urlSpec); + if (!jURL) return NS_ERROR_FAILURE; + + nsIDOMDocument* domDoc = GetDocument(loader); +#if defined(DEBUG) + dump_document(domDoc, urlSpec); +#endif + env->CallStaticVoidMethod(domAccessorClass, + endURLLoadMID, + jURL, + (jint) aStatus, + (jlong)domDoc); + if (Cleanup(env) == PR_TRUE) return NS_ERROR_FAILURE; + return NS_OK; +} +#endif + +NS_IMETHODIMP nsJavaDOMImpl::HandleUnknownContentType(nsIDocumentLoader* loader, + nsIChannel* channel, + const char *aContentType, + const char *aCommand) +{ + return NS_OK; +} + +JNIEnv* nsJavaDOMImpl::GetJNIEnv() { + JNIEnv* env; +#ifdef JAVA_DOM_OJI_ENABLE + nsresult result; + if (!jvmManager) { + NS_WITH_SERVICE(nsIJVMManager, _jvmManager, kJVMManagerCID, &result); + if (NS_SUCCEEDED(result)) { + jvmManager = (nsJVMManager*)((nsIJVMManager*)_jvmManager); + } + } + if (!jvmManager) { + return NULL; + } + jvmManager->CreateProxyJNI(NULL,&env); +// if (!securityContext) { +// securityContext = new JavaDOMSecurityContext(); +// } +// SetSecurityContext(env, securityContext); + SetSecurityContext(env, new JavaDOMSecurityContext()); +#else /* JAVA_DOM_OJI_ENABLE */ + if (!jvm) { + StartJVM(); + } +#ifdef XP_PC + jvm->AttachCurrentThread((void**)&env,NULL); +#else + jvm->AttachCurrentThread(&env,NULL); +#endif +#endif /* JAVA_DOM_OJI_ENABLE */ + return env; +} + +#ifndef JAVA_DOM_OJI_ENABLE +void nsJavaDOMImpl::StartJVM(void) { + jsize jvmCount; + JNI_GetCreatedJavaVMs(&jvm, 1, &jvmCount); + if (jvmCount) { + return; + } + + JNIEnv *env = NULL; + JDK1_1InitArgs vm_args; + JNI_GetDefaultJavaVMInitArgs(&vm_args); + vm_args.version = 0x00010001; + vm_args.verifyMode = JNI_TRUE; +#ifdef DEBUG + vm_args.verbose = JNI_TRUE; + vm_args.enableVerboseGC = JNI_TRUE; +#endif // DEBUG + char* cp = PR_GetEnv("CLASSPATH"); + char* p = new char[strlen(cp) + strlen(vm_args.classpath) + 2]; + strcpy(p, vm_args.classpath); + if (cp) { +#ifdef XP_PC + strcat(p, ";"); +#else + strcat(p, ":"); +#endif + strcat(p, cp); + vm_args.classpath = p; + } + +#ifdef DISABLE_JIT + /* workaround to get java dom to work on Linux */ + char **props = new char*[2]; + props[0]="java.compiler="; + props[1]=0; + vm_args.properties = props; +#endif + +#ifdef DEBUG + printf("classpath is \"%s\"\n", vm_args.classpath); +#endif // DEBUG +#ifdef XP_PC + jint rv = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); +#else + jint rv = JNI_CreateJavaVM(&jvm, &env, &vm_args); +#endif + if (rv < 0) { + printf("\n JAVA DOM: could not start jvm\n"); + } else { + printf("\n JAVA DOM: successfully started jvm\n"); + } + delete[] p; +} +#endif /* JAVA_DOM_OJI_ENABLE */ + + +#if defined(DEBUG) +static void dump_document(nsIDOMDocument* domDoc, const char* urlSpec) +{ + if (!domDoc) return; + + if (strstr(urlSpec, ".xul") || + strstr(urlSpec, ".js") || + strstr(urlSpec, ".css") || + strstr(urlSpec, "file:")) return; + + FILE* of = fopen("dom-cpp.txt", "a"); + if (!of) { + perror("nsJavaDOMImpl::dump_document: failed to open output file\n"); + return; + } + + nsIDOMElement* element = nsnull; + nsresult rv = domDoc->GetDocumentElement(&element); + if (NS_FAILED(rv) || !element) + return; + + (void) element->Normalize(); + + fprintf(of, "\n+++ %s +++\n", urlSpec); + dump_node(of, (nsIDOMNode*) element, 0, PR_FALSE); + fprintf(of, "\n"); + fflush(of); + fclose(of); +} + +static void dump_node(FILE* of, nsIDOMNode* node, int indent, + PRBool isMapNode) +{ + if (!node) return; + + fprintf(of, "\n"); + for (int i=0; i < indent; i++) + fprintf(of, " "); + + nsString name; + nsString value; + PRUint16 type; + + node->GetNodeName(name); + node->GetNodeValue(value); + node->GetNodeType(&type); + + const PRUnichar* cname = name.GetUnicode(); + const PRUnichar* cvalue = value.GetUnicode(); + char* cnorm = strip_whitespace(cvalue, value.Length()); + fprintf(of, "name=\"%s\" type=%s value=\"%s\"", + cname, describe_type(type), cnorm); + delete[] cnorm; + + if (isMapNode) return; + + nsIDOMNamedNodeMap* map = nsnull; + node->GetAttributes(&map); + dump_map(of, map, indent); + + nsIDOMNodeList* children = nsnull; + node->GetChildNodes(&children); + if (!children) return; + + PRUint32 length=0; + children->GetLength(&length); + for (PRUint32 j=0; j < length; j++) { + nsIDOMNode* child = nsnull; + children->Item(j, &child); + dump_node(of, child, indent+2, PR_FALSE); + } +} + +static void dump_map(FILE* of, nsIDOMNamedNodeMap* map, int indent) +{ + if (!map) return; + + fprintf(of, "\n"); + PRUint32 length=0; + map->GetLength(&length); + if (length > 0) { + for (int i=0; i < indent; i++) + fprintf(of, " "); + fprintf(of, "------- start attributes -------"); + } + + for (PRUint32 j=0; j < length; j++) { + nsIDOMNode* node = nsnull; + map->Item(j, &node); + dump_node(of, node, indent, PR_TRUE); + } + + if (length > 0) { + fprintf(of, "\n"); + for (int k=0; k < indent; k++) + fprintf(of, " "); + fprintf(of, "------- end attributes -------"); + } +} + +static char* strip_whitespace(const PRUnichar* input, int length) +{ + if (!input || length < 1) { + char* out = new char[1]; + out[0] = 0; + return out; + } + + char* out = new char[length+1]; + char* op = out; + const PRUnichar* ip = input; + PRUnichar c = ' '; + PRUnichar pc = ' '; + int i = 0; + + for (c = *ip++; i++ - * Ian Wilkinson - * Mark Goddard - * Ed Burns - * Ashutosh Kulkarni - * Louis-Philippe Gagnon - * Jason Mawdsley - */ - -package org.mozilla.webclient.test; - -/* - * EMWindow.java - */ - -import java.awt.*; -import java.awt.event.*; - -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.*; - -import java.util.Enumeration; -import java.util.Properties; -import java.util.*; - -import org.mozilla.webclient.*; -import org.mozilla.util.Assert; - -import org.w3c.dom.Document; - -import java.io.File; -import java.io.FileInputStream; - -/** - * - - * This is a test application for using the BrowserControl. - - * - * @version $Id: EMWindow.java,v 1.26 2001-05-08 04:50:27 edburns%acm.org Exp $ - * - * @see org.mozilla.webclient.BrowserControlFactory - - */ - -public class EMWindow extends Frame implements DialogClient, ActionListener, DocumentLoadListener, MouseListener, Prompt, PrefChangedCallback { - static final int defaultWidth = 640; - static final int defaultHeight = 480; - - private int winNum; - - private TextField urlField; - private BrowserControl browserControl; - private BrowserControlCanvas browserCanvas; - - private Navigation navigation = null; - private CurrentPage currentPage; - private History history; - private static Preferences prefs; - private Bookmarks bookmarks; - private BookmarksFrame bookmarksFrame = null; - private TreeModel bookmarksTree; - private DOMViewerFrame domViewer; - private Panel controlPanel; - private Panel statusPanel; - private Panel buttonsPanel; - private FindDialog findDialog = null; -private PasswordDialog passDialog = null; -private UniversalDialog uniDialog = null; - private MenuBar menuBar; - private Menu historyMenu; - private MenuItem backMenuItem; - private MenuItem forwardMenuItem; - private HistoryActionListener historyActionListener = null; - private Menu bookmarksMenu; - private Label statusLabel; - private String currentURL; - - private Document currentDocument = null; - - private EmbeddedMozilla creator; - - private Component forwardButton; - private Component backButton; - private Component stopButton; - private Component refreshButton; - - private PopupMenu popup; - private MenuItem popup_ViewSource, popup_SelectAll; - private PopupActionListener contextListener; - - - public static void main(String [] arg) - { - } - - - public EMWindow (String title, String binDir, String url, int winnum, EmbeddedMozilla Creator) - { - super(title); - popup = new PopupMenu(); - creator = Creator; - currentURL = url; - winNum = winnum; - System.out.println("constructed with binDir: " + binDir + " url: " + - url); - setSize(defaultWidth, defaultHeight); - - // Create the Menu Bar - menuBar = new MenuBar(); - this.setMenuBar(menuBar); - Menu fileMenu = new Menu("File"); - Menu viewMenu = new Menu("View"); - Menu searchMenu = new Menu("Search"); - Menu editMenu = new Menu("Edit"); - MenuItem newItem = new MenuItem("New Window"); - MenuItem closeItem = new MenuItem("Close"); - MenuItem findItem = new MenuItem("Find"); - MenuItem findNextItem = new MenuItem("Find Next"); - MenuItem sourceItem = new MenuItem("View Page Source as String"); - MenuItem pageInfoItem = new MenuItem("View Page Info"); - MenuItem selectAllItem = new MenuItem("Select All"); - MenuItem copyItem = new MenuItem("Copy"); - menuBar.add(fileMenu); - menuBar.add(viewMenu); - menuBar.add(searchMenu); - menuBar.add(editMenu); - fileMenu.add(newItem); - newItem.addActionListener(this); - fileMenu.add(closeItem); - closeItem.addActionListener(this); - searchMenu.add(findItem); - findItem.addActionListener(this); - searchMenu.add(findNextItem); - findNextItem.addActionListener(this); - - historyMenu = new Menu("History"); - backMenuItem = new MenuItem("Back"); - backMenuItem.addActionListener(this); - historyMenu.add(backMenuItem); - forwardMenuItem = new MenuItem("Forward"); - forwardMenuItem.addActionListener(this); - historyMenu.add(forwardMenuItem); - menuBar.add(historyMenu); - - bookmarksMenu = new Menu("Bookmarks"); - MenuItem addBookmark = new MenuItem("Add Current Page"); - addBookmark.addActionListener(this); - bookmarksMenu.add(addBookmark); - - addBookmark = new MenuItem("Add Current Page In New Folder"); - addBookmark.addActionListener(this); - bookmarksMenu.add(addBookmark); - - MenuItem manageBookmarks = new MenuItem("Manage Bookmarks..."); - manageBookmarks.addActionListener(this); - bookmarksMenu.add(manageBookmarks); - menuBar.add(bookmarksMenu); - - Menu streamMenu = new Menu("Stream"); - MenuItem streamFromFile = new MenuItem("Load Stream From File..."); - streamFromFile.addActionListener(this); - streamMenu.add(streamFromFile); - MenuItem randomStream = new MenuItem("Load Random HTML InputStream"); - randomStream.addActionListener(this); - streamMenu.add(randomStream); - menuBar.add(streamMenu); - - viewMenu.add(sourceItem); - sourceItem.addActionListener(this); - viewMenu.add(pageInfoItem); - pageInfoItem.addActionListener(this); - editMenu.add(selectAllItem); - selectAllItem.addActionListener(this); - editMenu.add(copyItem); - copyItem.addActionListener(this); - - // Create the URL field - urlField = new TextField("", 30); - urlField.addActionListener(this); - urlField.setText(url); - - - // Create the buttons sub panel - buttonsPanel = new Panel(); - buttonsPanel.setLayout(new GridBagLayout()); - - // Add the buttons - backButton = makeItem(buttonsPanel, "Back", 0, 0, 1, 1, 0.0, 0.0); - backButton.setEnabled(false); - forwardButton = makeItem(buttonsPanel, "Forward", 1, 0, 1, 1, 0.0, 0.0); - forwardButton.setEnabled(false); - stopButton = makeItem(buttonsPanel, "Stop", 2, 0, 1, 1, 0.0, 0.0); - stopButton.setEnabled(false); - refreshButton = makeItem(buttonsPanel, "Refresh", 3, 0, 1, 1, 0.0, 0.0); - refreshButton.setEnabled(false); - makeItem(buttonsPanel, "DOMViewer", 4, 0, 1, 1, 0.0, 0.0); - - // Create the control panel - controlPanel = new Panel(); - controlPanel.setLayout(new BorderLayout()); - - // Add the URL field, and the buttons panel - Panel centerPanel = new Panel(); - centerPanel.setLayout(new BorderLayout()); - centerPanel.add(urlField, BorderLayout.NORTH); - - // controlPanel.add(urlField, BorderLayout.CENTER); - controlPanel.add(centerPanel, BorderLayout.CENTER); - controlPanel.add(buttonsPanel, BorderLayout.WEST); - - // create the status panel - statusPanel = new Panel(); - statusPanel.setLayout(new BorderLayout()); - - // create and add the statusLabel - statusLabel = new Label("", Label.LEFT); - statusLabel.setBackground(Color.lightGray); - statusPanel.add(statusLabel, BorderLayout.CENTER); - - // Create the browser - try { - BrowserControlFactory.setAppData(binDir); - browserControl = BrowserControlFactory.newBrowserControl(); - browserCanvas = - (BrowserControlCanvas) - browserControl.queryInterface(BrowserControl.BROWSER_CONTROL_CANVAS_NAME); - - } - catch(Exception e) { - System.out.println("Can't create BrowserControl: " + - e.getMessage()); - } - Assert.assert(null != browserCanvas); - browserCanvas.setSize(defaultWidth, defaultHeight); - - // Add the control panel and the browserCanvas - add(controlPanel, BorderLayout.NORTH); - add(browserCanvas, BorderLayout.CENTER); - add(statusPanel, BorderLayout.SOUTH); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.out.println("Got windowClosing"); - System.out.println("destroying the BrowserControl"); - EMWindow.this.delete(); - // should close the BrowserControlCanvas - creator.DestroyEMWindow(winNum); - } - - public void windowClosed(WindowEvent e) { - System.out.println("Got windowClosed"); - } - }); - - // Create the Context Menus - add(popup); - - popup.add(popup_ViewSource = new MenuItem("View Source as ByteArray")); - popup.add(popup_SelectAll = new MenuItem("Select All")); - - contextListener = new PopupActionListener(); - - popup_ViewSource.addActionListener (contextListener); - popup_SelectAll.addActionListener (contextListener); - - show(); - toFront(); - - try { - navigation = (Navigation) - browserControl.queryInterface(BrowserControl.NAVIGATION_NAME); - navigation.setPrompt(this); - currentPage = (CurrentPage) - browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); - history = (History) - browserControl.queryInterface(BrowserControl.HISTORY_NAME); - prefs = (Preferences) - browserControl.queryInterface(BrowserControl.PREFERENCES_NAME); - prefs.registerPrefChangedCallback(this, - "network.cookie.warnAboutCookies", - "This IS the Closure!"); - prefs.setPref("network.cookie.warnAboutCookies", "true"); - prefs.setPref("browser.cache.disk_cache_size", "0"); - - // pull out the proxies, and make java aware of them - Properties prefsProps = prefs.getPrefs(); - String proxyHost = (String) prefsProps.get("network.proxy.http"); - String proxyPort = (String) prefsProps.get("network.proxy.http_port"); - if (null != proxyHost && null != proxyPort) { - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - } - - //prefsProps = prefs.getPrefs(); - //prefsProps.list(System.out); // This works, try it! - } - catch (Exception e) { - System.out.println(e.toString()); - } - - try { - EventRegistration eventRegistration = - (EventRegistration) - browserControl.queryInterface(BrowserControl.EVENT_REGISTRATION_NAME); - eventRegistration.addDocumentLoadListener(this); - eventRegistration.addMouseListener(this); - - // PENDING(edburns): test code, replace with production code - bookmarks = - (Bookmarks) - browserControl.queryInterface(BrowserControl.BOOKMARKS_NAME); - System.out.println("debug: edburns: got Bookmarks instance"); - - bookmarksTree = bookmarks.getBookmarks(); - - /********* - - TreeNode bookmarksRoot = (TreeNode) bookmarksTree.getRoot(); - - System.out.println("debug: edburns: testing the Enumeration"); - int childCount = bookmarksRoot.getChildCount(); - System.out.println("debug: edburns: root has " + childCount + - " children."); - - Enumeration rootChildren = bookmarksRoot.children(); - TreeNode currentChild; - - int i = 0, childIndex; - while (rootChildren.hasMoreElements()) { - currentChild = (TreeNode) rootChildren.nextElement(); - System.out.println("debug: edburns: bookmarks root has children! child: " + i + " name: " + currentChild.toString()); - i++; - } - - System.out.println("debug: edburns: testing getChildAt(" + --i + "): "); - currentChild = bookmarksRoot.getChildAt(i); - System.out.println("debug: edburns: testing getIndex(Child " + - i + "): index should be " + i + "."); - childIndex = bookmarksRoot.getIndex(currentChild); - System.out.println("debug: edburns: index is: " + childIndex); - *****/ - - /********** - - - System.out.println("debug: edburns: got new entry"); - - Properties entryProps = entry.getProperties(); - - System.out.println("debug: edburns: entry url: " + - entryProps.getProperty(BookmarkEntry.URL)); - bookmarks.addBookmark(folder, entry); - **********/ - } - catch (Exception e) { - System.out.println(e.toString()); - } - - if (null != navigation) { - navigation.loadURL(url); - } - } // EMWindow() ctor - -public void delete() -{ - browserCanvas.setVisible(false); - if (null != bookmarksFrame) { - bookmarksFrame.setVisible(false); - bookmarksFrame.dispose(); - bookmarksFrame = null; - } - if (null != domViewer) { - domViewer.setVisible(false); - domViewer.dispose(); - domViewer = null; - } - BrowserControlFactory.deleteBrowserControl(browserControl); - browserControl = null; - this.hide(); - this.dispose(); - urlField = null; - browserCanvas = null; - currentPage = null; - bookmarks = null; - bookmarksTree = null; - controlPanel = null; - buttonsPanel = null; - currentDocument = null; -} - - -public void actionPerformed (ActionEvent evt) -{ - String command = evt.getActionCommand(); - - try { - - if (command.equals("New Window")) { - creator.CreateEMWindow(); - } - else if (command.equals("Close")) { - System.out.println("Got windowClosing"); - System.out.println("destroying the BrowserControl"); - EMWindow.this.delete(); - // should close the BrowserControlCanvas - creator.DestroyEMWindow(winNum); - } - else if (command.equals("Find")) { - if (null == findDialog) { - Frame f = new Frame(); - f.setSize(350,150); - findDialog = new FindDialog(this, this, - "Find in Page", "Find ", - "", 20, false); - findDialog.setModal(false); - } - findDialog.setVisible(true); - // currentPage.findInPage("Sun", true, true); - } - else if (command.equals("Find Next")) { - currentPage.findNextInPage(); - } - else if (command.equals("View Page Source as String")) { - String sou = currentPage.getSource(); - System.out.println("+++++++++++ Page Source is +++++++++++\n\n" + sou); - } - else if (command.equals("View Page Info")) { - currentPage.getPageInfo(); - } - else if (command.equals("Select All")) { - currentPage.selectAll(); - } - else if (command.equals("Copy")) { - currentPage.copyCurrentSelectionToSystemClipboard(); - } - else if(command.equals("Stop")) { - navigation.stop(); - } - else if (command.equals("Refresh")) { - navigation.refresh(Navigation.LOAD_NORMAL); - } - else if (command.equals("Add Current Page")) { - if (null == bookmarksTree) { - bookmarksTree = bookmarks.getBookmarks(); - } - BookmarkEntry entry = - bookmarks.newBookmarkEntry(urlField.getText()); - bookmarks.addBookmark(null, entry); - } - else if (command.equals("Add Current Page In New Folder")) { - if (null == bookmarksTree) { - bookmarksTree = bookmarks.getBookmarks(); - } - BookmarkEntry folder = bookmarks.newBookmarkFolder("newFolder"); - bookmarks.addBookmark(null, folder); - BookmarkEntry entry = - bookmarks.newBookmarkEntry(urlField.getText()); - bookmarks.addBookmark(folder, entry); - } - else if (command.equals("Manage Bookmarks...")) { - if (null == bookmarksTree) { - bookmarksTree = bookmarks.getBookmarks(); - } - - if (null == bookmarksFrame) { - bookmarksFrame = new BookmarksFrame(bookmarksTree, - browserControl); - bookmarksFrame.setSize(new Dimension(320,480)); - bookmarksFrame.setLocation(defaultWidth + 5, 0); - } - bookmarksFrame.setVisible(true); - } - else if (command.equals("Load Stream From File...")) { - FileDialog fileDialog = new FileDialog(this, "Pick an HTML file", - FileDialog.LOAD); - fileDialog.show(); - String file = fileDialog.getFile(); - String directory = fileDialog.getDirectory(); - - if ((null != file) && (null != directory) && - (0 < file.length()) && (0 < directory.length())) { - String absPath = directory + file; - - FileInputStream fis = new FileInputStream(absPath); - File tFile = new File(absPath); - - System.out.println("debug: edburns: file: " + absPath); - - navigation.loadFromStream(fis, "file:///hello.html", - "text/html", (int) tFile.length(), - null); - } - } - else if (command.equals("Load Random HTML InputStream")) { - RandomHTMLInputStream rhis = new RandomHTMLInputStream(3); - System.out.println("debug: edburns: created RandomHTMLInputStream"); - navigation.loadFromStream(rhis, "http://randomstream.com/", - "text/html", -1, null); - } - else if (command.equals("DOMViewer")) { - if (null == domViewer) { - domViewer = new DOMViewerFrame("DOM Viewer", creator); - domViewer.setSize(new Dimension(300, 600)); - domViewer.setLocation(defaultWidth + 5, 0); - } - if (null != currentDocument) { - domViewer.setDocument(currentDocument); - domViewer.setVisible(true); - } - } - else if (command.equals("Back")) { - if (history.canBack()) { - history.back(); - } - } - else if (command.equals("Forward")) { - if (history.canForward()) { - history.forward(); - } - } - else if (command.equals(" ")) { - } - else { - navigation.loadURL(urlField.getText()); - } - } - catch (Exception e) { - System.out.println(e.getMessage()); - } -} // actionPerformed() - - -public void dialogDismissed(Dialog d) { - if (d == passDialog || d == uniDialog) { - return; - } - if(findDialog.wasClosed()) { - System.out.println("Find Dialog Closed"); - } - else { - String searchString = findDialog.getTextField().getText(); - if(searchString == null) { - System.out.println("Java ERROR - SearchString not received from Dialog Box" + - searchString); - } - else if(searchString.equals("")) { - System.out.println("Clear button selected"); - try { - CurrentPage currentPage = (CurrentPage) - browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); - currentPage.resetFind(); - } - catch (Exception e) { - System.out.println(e.getMessage()); - } - } - else { - System.out.println("Tring to Find String - " + searchString); - System.out.println("Parameters are - Backwrads = " + findDialog.backwards + " and Matchcase = " + findDialog.matchcase); - try { - CurrentPage currentPage = (CurrentPage) - browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); - currentPage.findInPage(searchString, !findDialog.backwards, findDialog.matchcase); - } - catch (Exception e) { - System.out.println(e.getMessage()); - } - } - } -} - -public void dialogCancelled(Dialog d) { - System.out.println("Find Dialog Closed"); -} - - - - -private Component makeItem (Panel p, Object arg, int x, int y, int w, int h, double weightx, double weighty) -{ - GridBagLayout gbl = (GridBagLayout) p.getLayout(); - GridBagConstraints c = new GridBagConstraints(); - Component comp = null; - - c.fill = GridBagConstraints.BOTH; - c.gridx = x; - c.gridy = y; - c.gridwidth = w; - c.gridheight = h; - c.weightx = weightx; - c.weighty = weighty; - if (arg instanceof String) { - Button b; - - comp = b = new Button((String) arg); - b.addActionListener(this); - - p.add(comp); - gbl.setConstraints(comp, c); - - if (((String)arg).equals(" ")) { - b.setEnabled(false); - } - } - return comp; -} // makeItem() - - -// -// From WebclientEventListener sub-interfaces -// - -/** - - * Important: do not call any webclient methods during this callback. - * It may caus your app to deadlock. - - */ - -public void eventDispatched(WebclientEvent event) -{ - boolean enabledState; - String status; - - if (event instanceof DocumentLoadEvent) { - switch ((int) event.getType()) { - case ((int) DocumentLoadEvent.START_DOCUMENT_LOAD_EVENT_MASK): - stopButton.setEnabled(true); - refreshButton.setEnabled(true); - currentURL = (String) event.getEventData(); - System.out.println("debug: edburns: Currently Viewing: " + - currentURL); - statusLabel.setText("Starting to load " + currentURL); - urlField.setText(currentURL); - currentDocument = null; - break; - case ((int) DocumentLoadEvent.END_DOCUMENT_LOAD_EVENT_MASK): - stopButton.setEnabled(false); - backButton.setEnabled(history.canBack()); - backMenuItem.setEnabled(history.canBack()); - forwardButton.setEnabled(history.canForward()); - forwardMenuItem.setEnabled(history.canForward()); - populateHistoryMenu(); - statusLabel.setText("Done."); - // currentDocument = currentPage.getDOM(); - // add the new document to the domViewer - // if (null != currentDocument && null != domViewer) { - // domViewer.setDocument(currentDocument); - // } - - break; - case ((int) DocumentLoadEvent.PROGRESS_URL_LOAD_EVENT_MASK): - status = "Status: " + (String) event.getEventData(); - statusLabel.setText(status); - break; - case ((int) DocumentLoadEvent.STATUS_URL_LOAD_EVENT_MASK): - status = "Status: " + (String) event.getEventData(); - statusLabel.setText(status); - break; - } - } -} - -/** - - * This method exercises the rest of the history API that isn't - * exercised elsewhere in the browser. - - */ - -private void populateHistoryMenu() -{ - int i = 0; - int histLen = 0; - int curIndex = 0; - String curUrl; - MenuItem curItem; - historyMenu.removeAll(); - - if (null == historyActionListener) { - historyActionListener = new HistoryActionListener(); - if (null == historyActionListener) { - return; - } - } - - // add back these MenuItems - historyMenu.add(backMenuItem); - historyMenu.add(forwardMenuItem); - - // now populate the menu with history items - histLen = history.getHistoryLength(); - curIndex = history.getCurrentHistoryIndex(); - for (i = 0; i < histLen; i++) { - // PENDING(put in code to truncate unruly long URLs) - curUrl = history.getURLForIndex(i); - - // It's important that we prepend the index. This is used in - // the actionListener to load by index. - - if (i == curIndex) { - curUrl = Integer.toString(i) + " * " + curUrl; - } - else { - curUrl = Integer.toString(i) + " " + curUrl; - } - curItem = new MenuItem(curUrl); - curItem.addActionListener(historyActionListener); - historyMenu.add(curItem); - } -} - -// -// From MouseListener -// - -public void mouseClicked(java.awt.event.MouseEvent e) -{ - int modifiers = e.getModifiers(); - if (0 != (modifiers & InputEvent.BUTTON1_MASK)) { - System.out.println("Button1 "); - } - if (0 != (modifiers & InputEvent.BUTTON2_MASK)) { - System.out.println("Button2 "); - } - if (0 != (modifiers & InputEvent.BUTTON3_MASK)) { - System.out.println("Button3 "); - popup.show(this, e.getX(), e.getY()); - } -} - -public void mouseEntered(java.awt.event.MouseEvent e) -{ - if (e instanceof WCMouseEvent) { - WCMouseEvent wcMouseEvent = (WCMouseEvent) e; - Properties eventProps = - (Properties) wcMouseEvent.getWebclientEvent().getEventData(); - if (null == eventProps) { - return; - } - if (e.isAltDown()) { - System.out.println("Alt "); - } - if (e.isControlDown()) { - System.out.println("Ctrl "); - } - if (e.isShiftDown()) { - System.out.println("Shift "); - } - if (e.isMetaDown()) { - System.out.println("Meta "); - } - String href = eventProps.getProperty("href"); - if (null != href) { - // if it's a relative URL - if (null != currentURL && -1 == href.indexOf("://")) { - int lastSlashIndex = currentURL.lastIndexOf('/'); - if (-1 == lastSlashIndex) { - href = currentURL + "/" + href; - } - else { - href = currentURL.substring(0, lastSlashIndex) + "/"+ href; - } - } - statusLabel.setText(href); - } - } -} - -public void mouseExited(java.awt.event.MouseEvent e) -{ - statusLabel.setText(""); -} - -public void mousePressed(java.awt.event.MouseEvent e) -{ -} - -public void mouseReleased(java.awt.event.MouseEvent e) -{ -} - -// -// Prompt methods -// - -public boolean promptUsernameAndPassword(String dialogTitle, - String text, - String passwordRealm, - int savePassword, - Properties fillThis) -{ - if (null == fillThis) { - return false; - } - if (null == passDialog) { - if (dialogTitle.equals("")) { - dialogTitle = "Basic Authentication Test"; - } - passDialog = new PasswordDialog(this, this, - dialogTitle, text, passwordRealm, - 20, true, fillThis); - if (null == passDialog) { - return false; - } - passDialog.setModal(true); - } - passDialog.setVisible(true); - - return passDialog.wasOk(); -} - -public boolean universalDialog(String titleMessage, - String dialogTitle, - String text, - String checkboxMsg, - String button0Text, - String button1Text, - String button2Text, - String button3Text, - String editfield1Msg, - String editfield2Msg, - int numButtons, - int numEditfields, - boolean editfield1Password, - Properties fillThis) -{ - System.out.println("titleMessage " + titleMessage); - System.out.println("dialogTitle " + dialogTitle); - System.out.println("text " + text); - System.out.println("checkboxMsg " + checkboxMsg); - System.out.println("button0Text " + button0Text); - System.out.println("button1Text " + button1Text); - System.out.println("button2Text " + button2Text); - System.out.println("button3Text " + button3Text); - System.out.println("editfield1Msg " + editfield1Msg); - System.out.println("editfield2Msg " + editfield2Msg); - System.out.println("numButtons " + numButtons); - System.out.println("numEditfields " + numEditfields); - System.out.println("editfield1Password " + editfield1Password); - - fillThis.put("editfield1Value", "edit1"); - fillThis.put("editfield2Value", "edit2"); - fillThis.put("checkboxState", "true"); - if (null == fillThis) { - return false; - } - if (null == uniDialog) { - if (dialogTitle.equals("")) { - dialogTitle = "Universal Dialog"; - } - uniDialog = new UniversalDialog(this, this, dialogTitle); - if (null == uniDialog) { - return false; - } - uniDialog.setParms(titleMessage, dialogTitle, text, checkboxMsg, - button0Text, button1Text, button2Text, - editfield1Msg, editfield2Msg, numButtons, - numEditfields, editfield1Password, fillThis); - uniDialog.setModal(true); - } - - uniDialog.setVisible(true); - - return true; -} - -// -// PrefChangedCallback -// -public int prefChanged(String prefName, Object closure) -{ - System.out.println("prefChanged: " + prefName + " closure: " + closure); - return 0; -} - -class HistoryActionListener implements ActionListener -{ - -public void actionPerformed(ActionEvent event) -{ - String command = event.getActionCommand(); - - if (null == command) { - return; - } - - // pull out the leading integer - Integer index; - int space = command.indexOf((int)' '); - if (-1 == space) { - return; - } - - index = new Integer(command.substring(0, space)); - - EMWindow.this.history.setCurrentHistoryIndex(index.intValue()); -} - -} - -class PopupActionListener implements ActionListener { -public void actionPerformed(ActionEvent event) { - String command = event.getActionCommand(); - if (command.equals("View Source as ByteArray")) - { - System.out.println("I will now View Source"); - byte source[] = EMWindow.this.currentPage.getSourceBytes(); - String sou = new String(source); - System.out.println("+++++++++++ Page Source is +++++++++++\n\n" + sou); - } - else if (command.equals("Select All")) - { - System.out.println("I will now Select All"); - EMWindow.this.currentPage.selectAll(); - } -} -} - - -// -// Package methods -// - -Navigation getNavigation() -{ - return navigation; -} - -} - -// EOF +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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 RaptorCanvas. + * + * The Initial Developer of the Original Code is Kirk Baker and + * Ian Wilkinson. Portions created by Kirk Baker and Ian Wilkinson are + * Copyright (C) 1999 Kirk Baker and Ian Wilkinson. All + * Rights Reserved. + * + * Contributor(s): Kirk Baker + * Ian Wilkinson + * Mark Goddard + * Ed Burns + * Ashutosh Kulkarni + * Louis-Philippe Gagnon + * Jason Mawdsley + */ + +package org.mozilla.webclient.test; + +/* + * EMWindow.java + */ + +import java.awt.*; +import java.awt.event.*; + +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.*; + +import java.util.Enumeration; +import java.util.Properties; +import java.util.*; + +import org.mozilla.webclient.*; +import org.mozilla.util.Assert; + +import org.w3c.dom.Document; + +import java.io.File; +import java.io.FileInputStream; + +/** + * + + * This is a test application for using the BrowserControl. + + * + * @version $Id: EMWindow.java,v 1.27 2001-05-08 20:34:27 edburns%acm.org Exp $ + * + * @see org.mozilla.webclient.BrowserControlFactory + + */ + +public class EMWindow extends Frame implements DialogClient, ActionListener, DocumentLoadListener, MouseListener, Prompt, PrefChangedCallback { + static final int defaultWidth = 640; + static final int defaultHeight = 480; + + private int winNum; + + private TextField urlField; + private BrowserControl browserControl; + private BrowserControlCanvas browserCanvas; + + private Navigation navigation = null; + private CurrentPage currentPage; + private History history; + private static Preferences prefs; + private Bookmarks bookmarks; + private BookmarksFrame bookmarksFrame = null; + private TreeModel bookmarksTree; + private DOMViewerFrame domViewer; + private Panel controlPanel; + private Panel statusPanel; + private Panel buttonsPanel; + private FindDialog findDialog = null; +private PasswordDialog passDialog = null; +private UniversalDialog uniDialog = null; + private MenuBar menuBar; + private Menu historyMenu; + private MenuItem backMenuItem; + private MenuItem forwardMenuItem; + private HistoryActionListener historyActionListener = null; + private Menu bookmarksMenu; + private Label statusLabel; + private String currentURL; + + private Document currentDocument = null; + + private EmbeddedMozilla creator; + + private Component forwardButton; + private Component backButton; + private Component stopButton; + private Component refreshButton; + + private PopupMenu popup; + private MenuItem popup_ViewSource, popup_SelectAll; + private PopupActionListener contextListener; + + + public static void main(String [] arg) + { + } + + + public EMWindow (String title, String binDir, String url, int winnum, EmbeddedMozilla Creator) + { + super(title); + popup = new PopupMenu(); + creator = Creator; + currentURL = url; + winNum = winnum; + System.out.println("constructed with binDir: " + binDir + " url: " + + url); + setSize(defaultWidth, defaultHeight); + + // Create the Menu Bar + menuBar = new MenuBar(); + this.setMenuBar(menuBar); + Menu fileMenu = new Menu("File"); + Menu viewMenu = new Menu("View"); + Menu searchMenu = new Menu("Search"); + Menu editMenu = new Menu("Edit"); + MenuItem newItem = new MenuItem("New Window"); + MenuItem closeItem = new MenuItem("Close"); + MenuItem findItem = new MenuItem("Find"); + MenuItem findNextItem = new MenuItem("Find Next"); + MenuItem sourceItem = new MenuItem("View Page Source as String"); + MenuItem pageInfoItem = new MenuItem("View Page Info"); + MenuItem selectAllItem = new MenuItem("Select All"); + MenuItem copyItem = new MenuItem("Copy"); + menuBar.add(fileMenu); + menuBar.add(viewMenu); + menuBar.add(searchMenu); + menuBar.add(editMenu); + fileMenu.add(newItem); + newItem.addActionListener(this); + fileMenu.add(closeItem); + closeItem.addActionListener(this); + searchMenu.add(findItem); + findItem.addActionListener(this); + searchMenu.add(findNextItem); + findNextItem.addActionListener(this); + + historyMenu = new Menu("History"); + backMenuItem = new MenuItem("Back"); + backMenuItem.addActionListener(this); + historyMenu.add(backMenuItem); + forwardMenuItem = new MenuItem("Forward"); + forwardMenuItem.addActionListener(this); + historyMenu.add(forwardMenuItem); + menuBar.add(historyMenu); + + bookmarksMenu = new Menu("Bookmarks"); + MenuItem addBookmark = new MenuItem("Add Current Page"); + addBookmark.addActionListener(this); + bookmarksMenu.add(addBookmark); + + addBookmark = new MenuItem("Add Current Page In New Folder"); + addBookmark.addActionListener(this); + bookmarksMenu.add(addBookmark); + + MenuItem manageBookmarks = new MenuItem("Manage Bookmarks..."); + manageBookmarks.addActionListener(this); + bookmarksMenu.add(manageBookmarks); + menuBar.add(bookmarksMenu); + + Menu streamMenu = new Menu("Stream"); + MenuItem streamFromFile = new MenuItem("Load Stream From File..."); + streamFromFile.addActionListener(this); + streamMenu.add(streamFromFile); + MenuItem randomStream = new MenuItem("Load Random HTML InputStream"); + randomStream.addActionListener(this); + streamMenu.add(randomStream); + menuBar.add(streamMenu); + + viewMenu.add(sourceItem); + sourceItem.addActionListener(this); + viewMenu.add(pageInfoItem); + pageInfoItem.addActionListener(this); + editMenu.add(selectAllItem); + selectAllItem.addActionListener(this); + editMenu.add(copyItem); + copyItem.addActionListener(this); + + // Create the URL field + urlField = new TextField("", 30); + urlField.addActionListener(this); + urlField.setText(url); + + + // Create the buttons sub panel + buttonsPanel = new Panel(); + buttonsPanel.setLayout(new GridBagLayout()); + + // Add the buttons + backButton = makeItem(buttonsPanel, "Back", 0, 0, 1, 1, 0.0, 0.0); + backButton.setEnabled(false); + forwardButton = makeItem(buttonsPanel, "Forward", 1, 0, 1, 1, 0.0, 0.0); + forwardButton.setEnabled(false); + stopButton = makeItem(buttonsPanel, "Stop", 2, 0, 1, 1, 0.0, 0.0); + stopButton.setEnabled(false); + refreshButton = makeItem(buttonsPanel, "Refresh", 3, 0, 1, 1, 0.0, 0.0); + refreshButton.setEnabled(false); + makeItem(buttonsPanel, "DOMViewer", 4, 0, 1, 1, 0.0, 0.0); + + // Create the control panel + controlPanel = new Panel(); + controlPanel.setLayout(new BorderLayout()); + + // Add the URL field, and the buttons panel + Panel centerPanel = new Panel(); + centerPanel.setLayout(new BorderLayout()); + centerPanel.add(urlField, BorderLayout.NORTH); + + // controlPanel.add(urlField, BorderLayout.CENTER); + controlPanel.add(centerPanel, BorderLayout.CENTER); + controlPanel.add(buttonsPanel, BorderLayout.WEST); + + // create the status panel + statusPanel = new Panel(); + statusPanel.setLayout(new BorderLayout()); + + // create and add the statusLabel + statusLabel = new Label("", Label.LEFT); + statusLabel.setBackground(Color.lightGray); + statusPanel.add(statusLabel, BorderLayout.CENTER); + + // Create the browser + try { + BrowserControlFactory.setAppData(binDir); + browserControl = BrowserControlFactory.newBrowserControl(); + browserCanvas = + (BrowserControlCanvas) + browserControl.queryInterface(BrowserControl.BROWSER_CONTROL_CANVAS_NAME); + + } + catch(Exception e) { + System.out.println("Can't create BrowserControl: " + + e.getMessage()); + } + Assert.assert(null != browserCanvas); + browserCanvas.setSize(defaultWidth, defaultHeight); + + // Add the control panel and the browserCanvas + add(controlPanel, BorderLayout.NORTH); + add(browserCanvas, BorderLayout.CENTER); + add(statusPanel, BorderLayout.SOUTH); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.out.println("Got windowClosing"); + System.out.println("destroying the BrowserControl"); + EMWindow.this.delete(); + // should close the BrowserControlCanvas + creator.DestroyEMWindow(winNum); + } + + public void windowClosed(WindowEvent e) { + System.out.println("Got windowClosed"); + } + }); + + // Create the Context Menus + add(popup); + + popup.add(popup_ViewSource = new MenuItem("View Source as ByteArray")); + popup.add(popup_SelectAll = new MenuItem("Select All")); + + contextListener = new PopupActionListener(); + + popup_ViewSource.addActionListener (contextListener); + popup_SelectAll.addActionListener (contextListener); + + show(); + toFront(); + + try { + navigation = (Navigation) + browserControl.queryInterface(BrowserControl.NAVIGATION_NAME); + navigation.setPrompt(this); + currentPage = (CurrentPage) + browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); + history = (History) + browserControl.queryInterface(BrowserControl.HISTORY_NAME); + prefs = (Preferences) + browserControl.queryInterface(BrowserControl.PREFERENCES_NAME); + prefs.registerPrefChangedCallback(this, + "network.cookie.warnAboutCookies", + "This IS the Closure!"); + prefs.setPref("network.cookie.warnAboutCookies", "true"); + prefs.setPref("browser.cache.disk_cache_size", "0"); + + // pull out the proxies, and make java aware of them + Properties prefsProps = prefs.getPrefs(); + String proxyHost = (String) prefsProps.get("network.proxy.http"); + String proxyPort = (String) prefsProps.get("network.proxy.http_port"); + if (null != proxyHost && null != proxyPort) { + System.setProperty("http.proxyHost", proxyHost); + System.setProperty("http.proxyPort", proxyPort); + } + + //prefsProps = prefs.getPrefs(); + //prefsProps.list(System.out); // This works, try it! + } + catch (Exception e) { + System.out.println(e.toString()); + } + + try { + EventRegistration eventRegistration = + (EventRegistration) + browserControl.queryInterface(BrowserControl.EVENT_REGISTRATION_NAME); + eventRegistration.addDocumentLoadListener(this); + eventRegistration.addMouseListener(this); + + // PENDING(edburns): test code, replace with production code + bookmarks = + (Bookmarks) + browserControl.queryInterface(BrowserControl.BOOKMARKS_NAME); + System.out.println("debug: edburns: got Bookmarks instance"); + + bookmarksTree = bookmarks.getBookmarks(); + + /********* + + TreeNode bookmarksRoot = (TreeNode) bookmarksTree.getRoot(); + + System.out.println("debug: edburns: testing the Enumeration"); + int childCount = bookmarksRoot.getChildCount(); + System.out.println("debug: edburns: root has " + childCount + + " children."); + + Enumeration rootChildren = bookmarksRoot.children(); + TreeNode currentChild; + + int i = 0, childIndex; + while (rootChildren.hasMoreElements()) { + currentChild = (TreeNode) rootChildren.nextElement(); + System.out.println("debug: edburns: bookmarks root has children! child: " + i + " name: " + currentChild.toString()); + i++; + } + + System.out.println("debug: edburns: testing getChildAt(" + --i + "): "); + currentChild = bookmarksRoot.getChildAt(i); + System.out.println("debug: edburns: testing getIndex(Child " + + i + "): index should be " + i + "."); + childIndex = bookmarksRoot.getIndex(currentChild); + System.out.println("debug: edburns: index is: " + childIndex); + *****/ + + /********** + + + System.out.println("debug: edburns: got new entry"); + + Properties entryProps = entry.getProperties(); + + System.out.println("debug: edburns: entry url: " + + entryProps.getProperty(BookmarkEntry.URL)); + bookmarks.addBookmark(folder, entry); + **********/ + } + catch (Exception e) { + System.out.println(e.toString()); + } + + if (null != navigation) { + navigation.loadURL(url); + } + } // EMWindow() ctor + +public void delete() +{ + browserCanvas.setVisible(false); + if (null != bookmarksFrame) { + bookmarksFrame.setVisible(false); + bookmarksFrame.dispose(); + bookmarksFrame = null; + } + if (null != domViewer) { + domViewer.setVisible(false); + domViewer.dispose(); + domViewer = null; + } + BrowserControlFactory.deleteBrowserControl(browserControl); + browserControl = null; + this.hide(); + this.dispose(); + urlField = null; + browserCanvas = null; + currentPage = null; + bookmarks = null; + bookmarksTree = null; + controlPanel = null; + buttonsPanel = null; + currentDocument = null; +} + + +public void actionPerformed (ActionEvent evt) +{ + String command = evt.getActionCommand(); + + try { + + if (command.equals("New Window")) { + creator.CreateEMWindow(); + } + else if (command.equals("Close")) { + System.out.println("Got windowClosing"); + System.out.println("destroying the BrowserControl"); + EMWindow.this.delete(); + // should close the BrowserControlCanvas + creator.DestroyEMWindow(winNum); + } + else if (command.equals("Find")) { + if (null == findDialog) { + Frame f = new Frame(); + f.setSize(350,150); + findDialog = new FindDialog(this, this, + "Find in Page", "Find ", + "", 20, false); + findDialog.setModal(false); + } + findDialog.setVisible(true); + // currentPage.findInPage("Sun", true, true); + } + else if (command.equals("Find Next")) { + currentPage.findNextInPage(); + } + else if (command.equals("View Page Source as String")) { + String sou = currentPage.getSource(); + System.out.println("+++++++++++ Page Source is +++++++++++\n\n" + sou); + } + else if (command.equals("View Page Info")) { + currentPage.getPageInfo(); + } + else if (command.equals("Select All")) { + currentPage.selectAll(); + } + else if (command.equals("Copy")) { + currentPage.copyCurrentSelectionToSystemClipboard(); + } + else if(command.equals("Stop")) { + navigation.stop(); + } + else if (command.equals("Refresh")) { + navigation.refresh(Navigation.LOAD_NORMAL); + } + else if (command.equals("Add Current Page")) { + if (null == bookmarksTree) { + bookmarksTree = bookmarks.getBookmarks(); + } + BookmarkEntry entry = + bookmarks.newBookmarkEntry(urlField.getText()); + bookmarks.addBookmark(null, entry); + } + else if (command.equals("Add Current Page In New Folder")) { + if (null == bookmarksTree) { + bookmarksTree = bookmarks.getBookmarks(); + } + BookmarkEntry folder = bookmarks.newBookmarkFolder("newFolder"); + bookmarks.addBookmark(null, folder); + BookmarkEntry entry = + bookmarks.newBookmarkEntry(urlField.getText()); + bookmarks.addBookmark(folder, entry); + } + else if (command.equals("Manage Bookmarks...")) { + if (null == bookmarksTree) { + bookmarksTree = bookmarks.getBookmarks(); + } + + if (null == bookmarksFrame) { + bookmarksFrame = new BookmarksFrame(bookmarksTree, + browserControl); + bookmarksFrame.setSize(new Dimension(320,480)); + bookmarksFrame.setLocation(defaultWidth + 5, 0); + } + bookmarksFrame.setVisible(true); + } + else if (command.equals("Load Stream From File...")) { + FileDialog fileDialog = new FileDialog(this, "Pick an HTML file", + FileDialog.LOAD); + fileDialog.show(); + String file = fileDialog.getFile(); + String directory = fileDialog.getDirectory(); + + if ((null != file) && (null != directory) && + (0 < file.length()) && (0 < directory.length())) { + String absPath = directory + file; + + FileInputStream fis = new FileInputStream(absPath); + File tFile = new File(absPath); + + System.out.println("debug: edburns: file: " + absPath); + + navigation.loadFromStream(fis, "file:///hello.html", + "text/html", (int) tFile.length(), + null); + } + } + else if (command.equals("Load Random HTML InputStream")) { + RandomHTMLInputStream rhis = new RandomHTMLInputStream(3); + System.out.println("debug: edburns: created RandomHTMLInputStream"); + navigation.loadFromStream(rhis, "http://randomstream.com/", + "text/html", -1, null); + } + else if (command.equals("DOMViewer")) { + if (null == domViewer) { + domViewer = new DOMViewerFrame("DOM Viewer", creator); + domViewer.setSize(new Dimension(300, 600)); + domViewer.setLocation(defaultWidth + 5, 0); + } + if (null != currentDocument) { + domViewer.setDocument(currentDocument); + domViewer.setVisible(true); + } + } + else if (command.equals("Back")) { + if (history.canBack()) { + history.back(); + } + } + else if (command.equals("Forward")) { + if (history.canForward()) { + history.forward(); + } + } + else if (command.equals(" ")) { + } + else { + navigation.loadURL(urlField.getText()); + } + } + catch (Exception e) { + System.out.println(e.getMessage()); + } +} // actionPerformed() + + +public void dialogDismissed(Dialog d) { + if (d == passDialog || d == uniDialog) { + return; + } + if(findDialog.wasClosed()) { + System.out.println("Find Dialog Closed"); + } + else { + String searchString = findDialog.getTextField().getText(); + if(searchString == null) { + System.out.println("Java ERROR - SearchString not received from Dialog Box" + + searchString); + } + else if(searchString.equals("")) { + System.out.println("Clear button selected"); + try { + CurrentPage currentPage = (CurrentPage) + browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); + currentPage.resetFind(); + } + catch (Exception e) { + System.out.println(e.getMessage()); + } + } + else { + System.out.println("Tring to Find String - " + searchString); + System.out.println("Parameters are - Backwrads = " + findDialog.backwards + " and Matchcase = " + findDialog.matchcase); + try { + CurrentPage currentPage = (CurrentPage) + browserControl.queryInterface(BrowserControl.CURRENT_PAGE_NAME); + currentPage.findInPage(searchString, !findDialog.backwards, findDialog.matchcase); + } + catch (Exception e) { + System.out.println(e.getMessage()); + } + } + } +} + +public void dialogCancelled(Dialog d) { + System.out.println("Find Dialog Closed"); +} + + + + +private Component makeItem (Panel p, Object arg, int x, int y, int w, int h, double weightx, double weighty) +{ + GridBagLayout gbl = (GridBagLayout) p.getLayout(); + GridBagConstraints c = new GridBagConstraints(); + Component comp = null; + + c.fill = GridBagConstraints.BOTH; + c.gridx = x; + c.gridy = y; + c.gridwidth = w; + c.gridheight = h; + c.weightx = weightx; + c.weighty = weighty; + if (arg instanceof String) { + Button b; + + comp = b = new Button((String) arg); + b.addActionListener(this); + + p.add(comp); + gbl.setConstraints(comp, c); + + if (((String)arg).equals(" ")) { + b.setEnabled(false); + } + } + return comp; +} // makeItem() + + +// +// From WebclientEventListener sub-interfaces +// + +/** + + * Important: do not call any webclient methods during this callback. + * It may caus your app to deadlock. + + */ + +public void eventDispatched(WebclientEvent event) +{ + boolean enabledState; + String status; + + if (event instanceof DocumentLoadEvent) { + switch ((int) event.getType()) { + case ((int) DocumentLoadEvent.START_DOCUMENT_LOAD_EVENT_MASK): + stopButton.setEnabled(true); + refreshButton.setEnabled(true); + currentURL = (String) event.getEventData(); + System.out.println("debug: edburns: Currently Viewing: " + + currentURL); + statusLabel.setText("Starting to load " + currentURL); + urlField.setText(currentURL); + currentDocument = null; + break; + case ((int) DocumentLoadEvent.END_DOCUMENT_LOAD_EVENT_MASK): + stopButton.setEnabled(false); + backButton.setEnabled(history.canBack()); + backMenuItem.setEnabled(history.canBack()); + forwardButton.setEnabled(history.canForward()); + forwardMenuItem.setEnabled(history.canForward()); + populateHistoryMenu(); + statusLabel.setText("Done."); + currentDocument = currentPage.getDOM(); + // add the new document to the domViewer + if (null != currentDocument && null != domViewer) { + domViewer.setDocument(currentDocument); + } + + break; + case ((int) DocumentLoadEvent.PROGRESS_URL_LOAD_EVENT_MASK): + status = "Status: " + (String) event.getEventData(); + statusLabel.setText(status); + break; + case ((int) DocumentLoadEvent.STATUS_URL_LOAD_EVENT_MASK): + status = "Status: " + (String) event.getEventData(); + statusLabel.setText(status); + break; + } + } +} + +/** + + * This method exercises the rest of the history API that isn't + * exercised elsewhere in the browser. + + */ + +private void populateHistoryMenu() +{ + int i = 0; + int histLen = 0; + int curIndex = 0; + String curUrl; + MenuItem curItem; + historyMenu.removeAll(); + + if (null == historyActionListener) { + historyActionListener = new HistoryActionListener(); + if (null == historyActionListener) { + return; + } + } + + // add back these MenuItems + historyMenu.add(backMenuItem); + historyMenu.add(forwardMenuItem); + + // now populate the menu with history items + histLen = history.getHistoryLength(); + curIndex = history.getCurrentHistoryIndex(); + for (i = 0; i < histLen; i++) { + // PENDING(put in code to truncate unruly long URLs) + curUrl = history.getURLForIndex(i); + + // It's important that we prepend the index. This is used in + // the actionListener to load by index. + + if (i == curIndex) { + curUrl = Integer.toString(i) + " * " + curUrl; + } + else { + curUrl = Integer.toString(i) + " " + curUrl; + } + curItem = new MenuItem(curUrl); + curItem.addActionListener(historyActionListener); + historyMenu.add(curItem); + } +} + +// +// From MouseListener +// + +public void mouseClicked(java.awt.event.MouseEvent e) +{ + int modifiers = e.getModifiers(); + if (0 != (modifiers & InputEvent.BUTTON1_MASK)) { + System.out.println("Button1 "); + } + if (0 != (modifiers & InputEvent.BUTTON2_MASK)) { + System.out.println("Button2 "); + } + if (0 != (modifiers & InputEvent.BUTTON3_MASK)) { + System.out.println("Button3 "); + popup.show(this, e.getX(), e.getY()); + } +} + +public void mouseEntered(java.awt.event.MouseEvent e) +{ + if (e instanceof WCMouseEvent) { + WCMouseEvent wcMouseEvent = (WCMouseEvent) e; + Properties eventProps = + (Properties) wcMouseEvent.getWebclientEvent().getEventData(); + if (null == eventProps) { + return; + } + if (e.isAltDown()) { + System.out.println("Alt "); + } + if (e.isControlDown()) { + System.out.println("Ctrl "); + } + if (e.isShiftDown()) { + System.out.println("Shift "); + } + if (e.isMetaDown()) { + System.out.println("Meta "); + } + String href = eventProps.getProperty("href"); + if (null != href) { + // if it's a relative URL + if (null != currentURL && -1 == href.indexOf("://")) { + int lastSlashIndex = currentURL.lastIndexOf('/'); + if (-1 == lastSlashIndex) { + href = currentURL + "/" + href; + } + else { + href = currentURL.substring(0, lastSlashIndex) + "/"+ href; + } + } + statusLabel.setText(href); + } + } +} + +public void mouseExited(java.awt.event.MouseEvent e) +{ + statusLabel.setText(""); +} + +public void mousePressed(java.awt.event.MouseEvent e) +{ +} + +public void mouseReleased(java.awt.event.MouseEvent e) +{ +} + +// +// Prompt methods +// + +public boolean promptUsernameAndPassword(String dialogTitle, + String text, + String passwordRealm, + int savePassword, + Properties fillThis) +{ + if (null == fillThis) { + return false; + } + if (null == passDialog) { + if (dialogTitle.equals("")) { + dialogTitle = "Basic Authentication Test"; + } + passDialog = new PasswordDialog(this, this, + dialogTitle, text, passwordRealm, + 20, true, fillThis); + if (null == passDialog) { + return false; + } + passDialog.setModal(true); + } + passDialog.setVisible(true); + + return passDialog.wasOk(); +} + +public boolean universalDialog(String titleMessage, + String dialogTitle, + String text, + String checkboxMsg, + String button0Text, + String button1Text, + String button2Text, + String button3Text, + String editfield1Msg, + String editfield2Msg, + int numButtons, + int numEditfields, + boolean editfield1Password, + Properties fillThis) +{ + System.out.println("titleMessage " + titleMessage); + System.out.println("dialogTitle " + dialogTitle); + System.out.println("text " + text); + System.out.println("checkboxMsg " + checkboxMsg); + System.out.println("button0Text " + button0Text); + System.out.println("button1Text " + button1Text); + System.out.println("button2Text " + button2Text); + System.out.println("button3Text " + button3Text); + System.out.println("editfield1Msg " + editfield1Msg); + System.out.println("editfield2Msg " + editfield2Msg); + System.out.println("numButtons " + numButtons); + System.out.println("numEditfields " + numEditfields); + System.out.println("editfield1Password " + editfield1Password); + + fillThis.put("editfield1Value", "edit1"); + fillThis.put("editfield2Value", "edit2"); + fillThis.put("checkboxState", "true"); + if (null == fillThis) { + return false; + } + if (null == uniDialog) { + if (dialogTitle.equals("")) { + dialogTitle = "Universal Dialog"; + } + uniDialog = new UniversalDialog(this, this, dialogTitle); + if (null == uniDialog) { + return false; + } + uniDialog.setParms(titleMessage, dialogTitle, text, checkboxMsg, + button0Text, button1Text, button2Text, + editfield1Msg, editfield2Msg, numButtons, + numEditfields, editfield1Password, fillThis); + uniDialog.setModal(true); + } + + uniDialog.setVisible(true); + + return true; +} + +// +// PrefChangedCallback +// +public int prefChanged(String prefName, Object closure) +{ + System.out.println("prefChanged: " + prefName + " closure: " + closure); + return 0; +} + +class HistoryActionListener implements ActionListener +{ + +public void actionPerformed(ActionEvent event) +{ + String command = event.getActionCommand(); + + if (null == command) { + return; + } + + // pull out the leading integer + Integer index; + int space = command.indexOf((int)' '); + if (-1 == space) { + return; + } + + index = new Integer(command.substring(0, space)); + + EMWindow.this.history.setCurrentHistoryIndex(index.intValue()); +} + +} + +class PopupActionListener implements ActionListener { +public void actionPerformed(ActionEvent event) { + String command = event.getActionCommand(); + if (command.equals("View Source as ByteArray")) + { + System.out.println("I will now View Source"); + byte source[] = EMWindow.this.currentPage.getSourceBytes(); + String sou = new String(source); + System.out.println("+++++++++++ Page Source is +++++++++++\n\n" + sou); + } + else if (command.equals("Select All")) + { + System.out.println("I will now Select All"); + EMWindow.this.currentPage.selectAll(); + } +} +} + + +// +// Package methods +// + +Navigation getNavigation() +{ + return navigation; +} + +} + +// EOF diff --git a/mozilla/java/webclient/classes_spec/org/mozilla/webclient/wrapper_native/CurrentPageImpl.java b/mozilla/java/webclient/classes_spec/org/mozilla/webclient/wrapper_native/CurrentPageImpl.java index 57dca62719b..a41fa60d165 100644 --- a/mozilla/java/webclient/classes_spec/org/mozilla/webclient/wrapper_native/CurrentPageImpl.java +++ b/mozilla/java/webclient/classes_spec/org/mozilla/webclient/wrapper_native/CurrentPageImpl.java @@ -1,277 +1,277 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * 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 RaptorCanvas. - * - * The Initial Developer of the Original Code is Kirk Baker and - * Ian Wilkinson. Portions created by Kirk Baker and Ian Wilkinson are - * Copyright (C) 1999 Kirk Baker and Ian Wilkinson. All - * Rights Reserved. - * - * Contributor(s): Ed Burns - */ - -package org.mozilla.webclient.wrapper_native; - -import org.mozilla.util.Assert; -import org.mozilla.util.Log; -import org.mozilla.util.ParameterCheck; - -import org.mozilla.webclient.BrowserControl; -import org.mozilla.webclient.CurrentPage; -import org.mozilla.webclient.WindowControl; -import org.mozilla.webclient.WrapperFactory; - -import java.util.Properties; -import java.io.*; -import java.net.*; - -import org.w3c.dom.Document; - -import org.mozilla.webclient.UnimplementedException; - -import org.mozilla.dom.DOMAccessor; - -public class CurrentPageImpl extends ImplObjectNative implements CurrentPage -{ -// -// Protected Constants -// - -// -// Class Variables -// - -private static boolean domInitialized = false; - -// -// Instance Variables -// - -// Attribute Instance Variables - - -// Relationship Instance Variables - -// -// Constructors and Initializers -// - -public CurrentPageImpl(WrapperFactory yourFactory, - BrowserControl yourBrowserControl) -{ - super(yourFactory, yourBrowserControl); - // force the class to be loaded, thus loading the JNI library - if (!domInitialized) { - // DOMAccessor.initialize(); - } -} - -// -// Class methods -// - -// -// General Methods -// - -// -// Methods from CurrentPage -// - -public void copyCurrentSelectionToSystemClipboard() -{ - myFactory.throwExceptionIfNotInitialized(); - Assert.assert(-1 != nativeWebShell); - - synchronized(myBrowserControl) { - nativeCopyCurrentSelectionToSystemClipboard(nativeWebShell); - } -} - -public void findInPage(String stringToFind, boolean forward, boolean matchCase) -{ - ParameterCheck.nonNull(stringToFind); - myFactory.throwExceptionIfNotInitialized(); - - synchronized(myBrowserControl) { - nativeFindInPage(nativeWebShell, stringToFind, forward, matchCase); - } -} - -public void findNextInPage() -{ - myFactory.throwExceptionIfNotInitialized(); - - synchronized(myBrowserControl) { - nativeFindNextInPage(nativeWebShell); - } -} - -public String getCurrentURL() -{ - String result = null; - myFactory.throwExceptionIfNotInitialized(); - - synchronized(myBrowserControl) { - result = nativeGetCurrentURL(nativeWebShell); - } - return result; -} - -public Document getDOM() -{ - Document result = nativeGetDOM(nativeWebShell); - return result; -} - -public Properties getPageInfo() -{ - Properties result = null; - - /* synchronized(myBrowserControl) { - result = nativeGetPageInfo(nativeWebShell); - } - return result; - */ - - throw new UnimplementedException("\nUnimplementedException -----\n API Function CurrentPage::getPageInfo has not yet been implemented.\n"); -} - - - -public String getSource() -{ - myFactory.throwExceptionIfNotInitialized(); - String HTMLContent; - String currURL = getCurrentURL(); - System.out.println("\nThe Current URL is -- " + currURL); - try { - URL aURL = new URL(currURL); - URLConnection connection = aURL.openConnection(); - connection.connect(); - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - boolean more = true; - while (more) - { - String line = in.readLine(); - if (line == null) more = false; - else - { - HTMLContent = HTMLContent + line; - } - } - } - catch (Throwable e) - { - System.out.println("Error occurred while establishing connection -- \n ERROR - " + e); - } - - return HTMLContent; -} - -public byte [] getSourceBytes() -{ - byte [] result = null; - myFactory.throwExceptionIfNotInitialized(); - - - String HTMLContent; - String currURL = getCurrentURL(); - System.out.println("\nThe Current URL is -- " + currURL); - try { - URL aURL = new URL(currURL); - URLConnection connection = aURL.openConnection(); - connection.connect(); - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - boolean more = true; - while (more) - { - String line = in.readLine(); - if (line == null) more = false; - else - { - HTMLContent = HTMLContent + line; - } - } - } - catch (Throwable e) - { - System.out.println("Error occurred while establishing connection -- \n ERROR - " + e); - } - result = HTMLContent.getBytes(); - return result; -} - -public void resetFind() -{ - myFactory.throwExceptionIfNotInitialized(); - - synchronized(myBrowserControl) { - nativeResetFind(nativeWebShell); - } -} - -public void selectAll() -{ - myFactory.throwExceptionIfNotInitialized(); - - synchronized(myBrowserControl) { - nativeSelectAll(nativeWebShell); - } -} - -// -// Native methods -// - -native public void nativeCopyCurrentSelectionToSystemClipboard(int webShellPtr); - -native public void nativeFindInPage(int webShellPtr, String stringToFind, boolean forward, boolean matchCase); - -native public void nativeFindNextInPage(int webShellPtr); - -native public String nativeGetCurrentURL(int webShellPtr); - -native public Document nativeGetDOM(int webShellPtr); - -// webclient.PageInfo getPageInfo(); - -/* PENDING(ashuk): remove this from here and in the motif directory - * native public String nativeGetSource(); - - * native public byte [] nativeGetSourceBytes(int webShellPtr, boolean viewMode); - */ - -native public void nativeResetFind(int webShellPtr); - -native public void nativeSelectAll(int webShellPtr); - - -// ----VERTIGO_TEST_START - -// -// Test methods -// - -public static void main(String [] args) -{ - Assert.setEnabled(true); - Log.setApplicationName("CurrentPageImpl"); - Log.setApplicationVersion("0.0"); - Log.setApplicationVersionDate("$Id: CurrentPageImpl.java,v 1.13 2001-05-08 16:58:36 ashuk%eng.sun.com Exp $"); - -} - -// ----VERTIGO_TEST_END - -} // end of class CurrentPageImpl +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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 RaptorCanvas. + * + * The Initial Developer of the Original Code is Kirk Baker and + * Ian Wilkinson. Portions created by Kirk Baker and Ian Wilkinson are + * Copyright (C) 1999 Kirk Baker and Ian Wilkinson. All + * Rights Reserved. + * + * Contributor(s): Ed Burns + */ + +package org.mozilla.webclient.wrapper_native; + +import org.mozilla.util.Assert; +import org.mozilla.util.Log; +import org.mozilla.util.ParameterCheck; + +import org.mozilla.webclient.BrowserControl; +import org.mozilla.webclient.CurrentPage; +import org.mozilla.webclient.WindowControl; +import org.mozilla.webclient.WrapperFactory; + +import java.util.Properties; +import java.io.*; +import java.net.*; + +import org.w3c.dom.Document; + +import org.mozilla.webclient.UnimplementedException; + +import org.mozilla.dom.DOMAccessor; + +public class CurrentPageImpl extends ImplObjectNative implements CurrentPage +{ +// +// Protected Constants +// + +// +// Class Variables +// + +private static boolean domInitialized = false; + +// +// Instance Variables +// + +// Attribute Instance Variables + + +// Relationship Instance Variables + +// +// Constructors and Initializers +// + +public CurrentPageImpl(WrapperFactory yourFactory, + BrowserControl yourBrowserControl) +{ + super(yourFactory, yourBrowserControl); + // force the class to be loaded, thus loading the JNI library + if (!domInitialized) { + DOMAccessor.initialize(); + } +} + +// +// Class methods +// + +// +// General Methods +// + +// +// Methods from CurrentPage +// + +public void copyCurrentSelectionToSystemClipboard() +{ + myFactory.throwExceptionIfNotInitialized(); + Assert.assert(-1 != nativeWebShell); + + synchronized(myBrowserControl) { + nativeCopyCurrentSelectionToSystemClipboard(nativeWebShell); + } +} + +public void findInPage(String stringToFind, boolean forward, boolean matchCase) +{ + ParameterCheck.nonNull(stringToFind); + myFactory.throwExceptionIfNotInitialized(); + + synchronized(myBrowserControl) { + nativeFindInPage(nativeWebShell, stringToFind, forward, matchCase); + } +} + +public void findNextInPage() +{ + myFactory.throwExceptionIfNotInitialized(); + + synchronized(myBrowserControl) { + nativeFindNextInPage(nativeWebShell); + } +} + +public String getCurrentURL() +{ + String result = null; + myFactory.throwExceptionIfNotInitialized(); + + synchronized(myBrowserControl) { + result = nativeGetCurrentURL(nativeWebShell); + } + return result; +} + +public Document getDOM() +{ + Document result = nativeGetDOM(nativeWebShell); + return result; +} + +public Properties getPageInfo() +{ + Properties result = null; + + /* synchronized(myBrowserControl) { + result = nativeGetPageInfo(nativeWebShell); + } + return result; + */ + + throw new UnimplementedException("\nUnimplementedException -----\n API Function CurrentPage::getPageInfo has not yet been implemented.\n"); +} + + + +public String getSource() +{ + myFactory.throwExceptionIfNotInitialized(); + String HTMLContent; + String currURL = getCurrentURL(); + System.out.println("\nThe Current URL is -- " + currURL); + try { + URL aURL = new URL(currURL); + URLConnection connection = aURL.openConnection(); + connection.connect(); + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + boolean more = true; + while (more) + { + String line = in.readLine(); + if (line == null) more = false; + else + { + HTMLContent = HTMLContent + line; + } + } + } + catch (Throwable e) + { + System.out.println("Error occurred while establishing connection -- \n ERROR - " + e); + } + + return HTMLContent; +} + +public byte [] getSourceBytes() +{ + byte [] result = null; + myFactory.throwExceptionIfNotInitialized(); + + + String HTMLContent; + String currURL = getCurrentURL(); + System.out.println("\nThe Current URL is -- " + currURL); + try { + URL aURL = new URL(currURL); + URLConnection connection = aURL.openConnection(); + connection.connect(); + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + boolean more = true; + while (more) + { + String line = in.readLine(); + if (line == null) more = false; + else + { + HTMLContent = HTMLContent + line; + } + } + } + catch (Throwable e) + { + System.out.println("Error occurred while establishing connection -- \n ERROR - " + e); + } + result = HTMLContent.getBytes(); + return result; +} + +public void resetFind() +{ + myFactory.throwExceptionIfNotInitialized(); + + synchronized(myBrowserControl) { + nativeResetFind(nativeWebShell); + } +} + +public void selectAll() +{ + myFactory.throwExceptionIfNotInitialized(); + + synchronized(myBrowserControl) { + nativeSelectAll(nativeWebShell); + } +} + +// +// Native methods +// + +native public void nativeCopyCurrentSelectionToSystemClipboard(int webShellPtr); + +native public void nativeFindInPage(int webShellPtr, String stringToFind, boolean forward, boolean matchCase); + +native public void nativeFindNextInPage(int webShellPtr); + +native public String nativeGetCurrentURL(int webShellPtr); + +native public Document nativeGetDOM(int webShellPtr); + +// webclient.PageInfo getPageInfo(); + +/* PENDING(ashuk): remove this from here and in the motif directory + * native public String nativeGetSource(); + + * native public byte [] nativeGetSourceBytes(int webShellPtr, boolean viewMode); + */ + +native public void nativeResetFind(int webShellPtr); + +native public void nativeSelectAll(int webShellPtr); + + +// ----VERTIGO_TEST_START + +// +// Test methods +// + +public static void main(String [] args) +{ + Assert.setEnabled(true); + Log.setApplicationName("CurrentPageImpl"); + Log.setApplicationVersion("0.0"); + Log.setApplicationVersionDate("$Id: CurrentPageImpl.java,v 1.14 2001-05-08 20:34:31 edburns%acm.org Exp $"); + +} + +// ----VERTIGO_TEST_END + +} // end of class CurrentPageImpl