text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef MODULES_UTIL_OPHASHTABLE_H
#define MODULES_UTIL_OPHASHTABLE_H
/* NOTE: See modules/util/stringhash.h for a string-indexed hash table that
* keeps copies of keys internally. */
/**
* The OpHashFunctions object contains the hash and
* compare functions used by a OpHashTable that do not
* hash on ponter values.
*
*/
class OpHashFunctions
{
public:
virtual ~OpHashFunctions() {}
/**
* Calculates the hash value for a key.
* the hash key.
*/
virtual UINT32 Hash(const void* key) = 0;
/**
* Compares if to keys are equal.
*/
virtual BOOL KeysAreEqual(const void* key1, const void* key2) = 0;
};
class ChainedHashBackend;
class OpHashTable;
class OpGenericVector;
class ChainedHashLink
{
public:
const void* key;
void* data;
ChainedHashLink* next;
BOOL used;
};
class OpHashIterator
{
public:
virtual ~OpHashIterator() {}
/**
* Makes sure that the first key and data
* can be read with GetKey() and GetData().
* @return OpStatus::OK, there was a first element.
* @return OpStatus::ERR, the hash table that is represented by the iterator is empty.
*/
virtual OP_STATUS First() = 0;
/**
* Makes sure that the next key and data
* can be read with GetKey() and GetData().
* @return OpStatus::OK, there was a next element.
* @return OpStatus::ERR, the hash table that is represented by the iterator didn't have a next element.
*/
virtual OP_STATUS Next() = 0;
/**
* Works only after a call to First() or Next()
* @return the key for the current element.
*/
virtual const void* GetKey() const = 0;
/**
* Works only after a call to First() or Next()
* @return the data for the current element.
*/
virtual void* GetData() const = 0;
};
class ChainedHashIterator : public OpHashIterator
{
public:
ChainedHashIterator(const ChainedHashBackend* backend);
virtual OP_STATUS First();
virtual OP_STATUS Next();
virtual const void* GetKey() const;
virtual void* GetData() const;
/**
* Set key and data that is current in the iterator.
* Called from OpHashTable::Iterate().
* @param key the key to set.
* @param data the data to set.
*/
void SetKeyAndData(const void* key, void* data);
/**
* Set hash link pos that is current in the iterator.
* Value will be -1 when we get an error, or before we have called First().
* Called from OpHashTable::Iterate().
*/
void SetHashLinkPos(INT32 pos);
/**
* @return the hash link pos, -1 if First() has not been called, or if we have traversed the complete hash table.
*/
INT32 GetHashLinkPos() const;
private:
const ChainedHashBackend* backend;
const void* key;
void* data;
INT32 hash_link_pos;
};
/**
* Class used to iterate over an HashBackend.
* This way we can skip the iterator object allocation
*/
class OpHashTableForEachListener
{
public:
virtual void HandleKeyData(const void* key, void* data) = 0;
};
class ChainedHashBackend
{
public:
ChainedHashBackend();
~ChainedHashBackend();
/** Initialize the hash back-end.
*
* Specify the number of elements and array size (the ratio defines the
* density of the hash table, which affects performance). Called from
* OpHashTable.
*
* @param hash_functions The OpHashFunctions object to use in computing hash values.
* @param array_size size of the array that is used for spreading the hash values.
* @param max_nr_of_elements nr of elements that the hash table can hold.
* @return OpStatus::OK, everything went well.
* @return OpStatus::ERR_NO_MEMORY, out of memory.
*/
OP_STATUS Init(OpHashFunctions* hash_functions, UINT32 array_size, UINT32 max_nr_of_elements);
/**
* Adds a key and data to the HashBackend.
* Called from OpHashTable.
* @param key the key to add.
* @param data the data to add.
* @return OpStatus::OK, if the element was added.
* @return OpStatus::ERR, if the element was already added.
*/
OP_STATUS Add(const void* key, void* data);
/**
* Like Add(), but updates the data associated with the key if it is
* already in the hash table. It is the caller's responsibility to make
* sure the old data value is not lost (if it is a pointer that needs to be
* deleted, for example).
*
* @param key The key to update the data for.
* @param data The new data value.
* @param old_data If non-null, receives the old data value at the key.
* Unmodified if the key is not in the table.
*
* @retval TRUE The key was already in the hash table.
* @retval FALSE Otherwise.
*/
BOOL Update(const void* key, void* data, void** old_data);
/**
* Get the data corresponding to a key.
* Called from OpHashTable.
* @param key the key for the element to get.
* @param data where the found data is placed.
* @return OpStatus::OK, if the element was found.
* @return OpStatus::ERR, if the element was not in the HashBackend.
*/
OP_STATUS GetData(const void* key, void** data) const;
/**
* Remove the key/value pair corresponding to the key.
* Called from OpHashTable.
* @param key the key in the key/value pair that should be removed.
* @param data where the removed data is placed.
* @return OpStatus::OK, if the element was removed.
* @return OpStatus::ERR, if the element was not in the list.
*/
OP_STATUS Remove(const void* key, void** data);
/**
* Get an iterator to iterate the HashBackend.
* The returned iterator is to be freed by the caller.
* Called from OpHashTable.
* @return the iterator for the HashBackend, or NULL if OOM.
*/
OpHashIterator* GetIterator() const;
/**
* Call function for each (key, data) pair in the hash table.
*/
void ForEach(void (*function)(const void *, void *));
void ForEach(void (*function)(const void *, void *, OpHashTable *), OpHashTable* table);
void ForEach(OpHashTableForEachListener* listener);
/**
* Add all data elements to an OpGenericVector (the order is random, ie. how they appear in hash table)
*/
OP_STATUS CopyAllToVector(OpGenericVector& vector) const;
/**
* Add all data elements to another OpHashTable
*/
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const;
/**
* Modifies the iterator to point to the first element in
* the ChainedHashBackend.
* Called from ChainedHashIterator::First().
* @param iterator the iterator that is modified.
* @return OpStatus::OK if the backend had an element.
* @return OpStatus::ERR if the backend was empty.
*/
OP_STATUS First(ChainedHashIterator* iterator) const;
/**
* Modifies the iterator to point to the next element in
* the ChainedHashBackend.
* Called from ChainedHashIterator::Next().
* @param iterator the iterator that is modified.
* @return OpStatus::OK if the backend had a next element.
* @return OpStatus::ERR if the backend did not have a next element.
*/
OP_STATUS Next(ChainedHashIterator* iterator) const;
/**
* Bring this object to its default constructed stated, destroying/deallocating its substructures as necessary.
*/
void CleanUp(BOOL destroy_substructures=TRUE);
private:
UINT32 Hash(const void* key, UINT32 tableSize) const;
ChainedHashLink* GetNewLink();
void FreeLink(ChainedHashLink* link);
BOOL FindElm(UINT32 array_pos, const void* key, ChainedHashLink** link, ChainedHashLink** prev_link) const;
OP_STATUS Iterate(ChainedHashIterator* iterator, UINT32 start_pos) const;
OpHashFunctions* hash_functions;
UINT32 table_size;
UINT32 nr_of_hash_links;
ChainedHashLink** hash_array;
ChainedHashLink* hash_links;
ChainedHashLink* first_free_link;
};
class OpHashTable : public OpHashFunctions
{
public:
OpHashTable(OpHashFunctions* hashFunctions = NULL,
BOOL useChainedHashing = TRUE);
virtual ~OpHashTable();
void SetHashFunctions(OpHashFunctions* hashFunctions) {hash_functions = hashFunctions;}
/**
* Adds a key with data to the hash table.
*
* Return/Leave values:
* OpStatus::OK if we could add the key and data.
* OpStatus::ERR the key was already in the hash table.
* OpStatus::ERR_NO_MEMORY if we could not add because of OOM.
*/
OP_STATUS Add(const void* key, void* data);
void AddL(const void* key, void* data);
/**
* Like Add(), but updates the data associated with the key if it is
* already in the hash table. It is the caller's responsibility to make
* sure the old data value is not lost (if it is a pointer that needs to be
* deleted, for example). The DeleteAll() method will not delete a pointer
* value that has been replaced via Update().
*
* @param key The key to update the data for.
* @param data The new data value.
* @param old_data If non-null, receives the old data value at the key.
* Unmodified if the key is not in the table.
* @param had_key If non-null, receives TRUE if the key was already in
* the table and FALSE otherwise. This is needed as
* old_data might be 0.
*
* @retval OpStatus::OK The key was successfully inserted/updated.
* @retval OpStatus::ERR_NO_MEMORY The update failed because of OOM.
*/
OP_STATUS Update(const void* key,
void* data,
void** old_data = NULL,
BOOL* had_key = NULL);
/**
* Gets data in the pointer pointer data.
*
* Return/Leave values:
* @return OpStatus::OK, we get some data from the table.
* @return OpStatus::ERR, the key was not in the hash table.
*/
OP_STATUS GetData(const void* key, void** data) const;
/**
* Remove an element from the hash table.
* @param key the key for the element to remove.
* @param data here will the data be added.
* @return OpStatus::OK, if everything went well.
* @return OpStatus::ERR, if element was not in hash table.
*/
OP_STATUS Remove(const void* key, void** data);
/**
* Get an iterator for the hash table.
* @return the iterator, or NULL if OOM.
*/
OpHashIterator* GetIterator();
/**
* Call function for each (key, data) pair in the hash table.
*/
void ForEach(void (*function)(const void *, void *));
void ForEach(void (*function)(const void *, void *, OpHashTable *));
void ForEach(OpHashTableForEachListener* listener);
/**
* Remove all elements
*/
void RemoveAll();
/**
* Delete all elements. To use this, you must overload Delete(void* data).
* Note that this method will not delete pointers that have been replaced
* via calls to Update().
*/
void DeleteAll();
/**
* Add all data elements to an OpGenericVector (the order is random, ie. how they appear in hash table)
*/
OP_STATUS CopyAllToVector(OpGenericVector& vector) const;
/**
* Add all data elements to another OpHashTable
*/
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const;
/**
* Any item with that key?
*/
BOOL Contains(const void* key) const {void* data; return GetData(key, &data) == OpStatus::OK;}
/**
* Any item with that key and exactsame data?
*/
BOOL Contains(const void* key, void* data) const {void* other_data; return GetData(key, &other_data) == OpStatus::OK && data == other_data;}
/**
* Get number of items in hashtable
*/
INT32 GetCount() const {return nr_of_elements;}
/**
* Set minimum nr of elements (to speed up Adding lots of items where that number of items is known)
*/
void SetMinimumCount(UINT32 minimum_count);
/* Default OpHashFunctions */
virtual UINT32 Hash(const void* key);
virtual BOOL KeysAreEqual(const void* key1, const void* key2);
protected:
virtual void Delete(void* /*data*/) {OP_ASSERT(0);} // must be overloaded to be able to delete
private:
OP_STATUS Init();
BOOL IsInitialized() const;
BOOL IsChained() const;
void SetInitialized(BOOL initialized);
void SetChained(BOOL chained);
OP_STATUS Rehash(UINT16 size_index);
OP_STATUS GrowIfNeeded();
OpHashFunctions* hash_functions;
ChainedHashBackend hash_backend;
UINT32 nr_of_elements;
UINT32 minimum_nr_of_elements;
UINT16 hash_size_index;
UINT16 flags;
static void DeleteFunc(const void *key, void *data, OpHashTable* table);
};
class OpGenericStringHashTable : protected OpHashTable
{
public:
OpGenericStringHashTable(BOOL case_sensitive = FALSE) : OpHashTable(), m_case_sensitive(case_sensitive) {SetHashFunctions(this);}
OP_STATUS Add(const uni_char* key, void* data) {return OpHashTable::Add((void*)key, data);}
void AddL(const uni_char* key, void* data) {OpHashTable::AddL((void*)key, data);}
OP_STATUS GetData(const uni_char* key, void** data) const {return OpHashTable::GetData((void*)key, data);}
OP_STATUS Remove(const uni_char* key, void** data) {return OpHashTable::Remove((void*)key, data);}
OpHashIterator* GetIterator() {return OpHashTable::GetIterator();}
void ForEach(void (*function)(const void *, void *)) {OpHashTable::ForEach(function);}
void ForEach(void (*function)(const void *, void *, OpHashTable *)) {OpHashTable::ForEach(function);}
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() {OpHashTable::RemoveAll();}
void DeleteAll() {OpHashTable::DeleteAll();}
BOOL Contains(const uni_char* key) const {return OpHashTable::Contains((void*)key);}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpHashTable::CopyAllToVector(vector);}
INT32 GetCount() const {return OpHashTable::GetCount();}
// expose this to the outside world
static UINT32 HashString(const uni_char* key, BOOL case_sensitive);
static UINT32 HashString(const uni_char* key, unsigned str_length, BOOL case_sensitive);
// OpHashFunctions interface
virtual UINT32 Hash(const void* key);
virtual BOOL KeysAreEqual(const void* key1, const void* key2);
void SetMinimumCount(UINT32 minimum_count){ return OpHashTable::SetMinimumCount(minimum_count); }
private:
BOOL m_case_sensitive;
};
class OpGenericString8HashTable : protected OpHashTable
{
public:
OpGenericString8HashTable(BOOL case_sensitive = FALSE) : OpHashTable(), m_case_sensitive(case_sensitive) {SetHashFunctions(this);}
OP_STATUS Add(const char* key, void* data) {return OpHashTable::Add((void*)key, data);}
void AddL(const char* key, void* data) {OpHashTable::AddL((void*)key, data);}
OP_STATUS GetData(const char* key, void** data) const {return OpHashTable::GetData((void*)key, data);}
OP_STATUS Remove(const char* key, void** data) {return OpHashTable::Remove((void*)key, data);}
OpHashIterator* GetIterator() {return OpHashTable::GetIterator();}
void ForEach(void (*function)(const void *, void *)) {OpHashTable::ForEach(function);}
void ForEach(void (*function)(const void *, void *, OpHashTable *)) {OpHashTable::ForEach(function);}
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() {OpHashTable::RemoveAll();}
void DeleteAll() {OpHashTable::DeleteAll();}
BOOL Contains(const char* key) const {return OpHashTable::Contains((void*)key);}
INT32 GetCount() const {return OpHashTable::GetCount();}
// expose this to the outside world
static UINT32 HashString(const char* key, BOOL case_sensitive);
static UINT32 HashString(const char* key, unsigned str_length, BOOL case_sensitive);
// OpHashFunctions interface
virtual UINT32 Hash(const void* key);
virtual BOOL KeysAreEqual(const void* key1, const void* key2);
void SetMinimumCount(UINT32 minimum_count){ return OpHashTable::SetMinimumCount(minimum_count); }
private:
BOOL m_case_sensitive;
};
template<class T>
class OpStringHashTable : private OpGenericStringHashTable
{
public:
OpStringHashTable(BOOL case_sensitive = FALSE) : OpGenericStringHashTable(case_sensitive) {}
OP_STATUS Add(const uni_char* key, T* data) {return OpGenericStringHashTable::Add(key, (void*)data);}
void AddL(const uni_char* key, T* data) {OpGenericStringHashTable::AddL(key, (void*)data);}
OP_STATUS GetData(const uni_char* key, T** data) const {return OpGenericStringHashTable::GetData(key, (void**)data);}
BOOL Contains(const uni_char* key) const {return OpGenericStringHashTable::Contains(key);}
OP_STATUS Remove(const uni_char* key, T** data) {return OpGenericStringHashTable::Remove(key, (void**)data);}
OpHashIterator* GetIterator() {return OpGenericStringHashTable::GetIterator();}
void ForEach(void (*function)(const void *, void *)) {OpGenericStringHashTable::ForEach(function);}
void ForEach(void (*function)(const void *, void *, OpHashTable *)) {OpGenericStringHashTable::ForEach(function);}
void ForEach(OpHashTableForEachListener* listener) {OpGenericStringHashTable::ForEach(listener);}
void RemoveAll() {OpGenericStringHashTable::RemoveAll();}
void DeleteAll() {OpGenericStringHashTable::DeleteAll();}
virtual void Delete(void* data) {OP_DELETE((T*) data );}
INT32 GetCount() const {return OpGenericStringHashTable::GetCount();}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpGenericStringHashTable::CopyAllToVector(vector);}
void SetMinimumCount(UINT32 minimum_count){ OpGenericStringHashTable::SetMinimumCount(minimum_count); }
};
template<class T>
class OpString8HashTable : private OpGenericString8HashTable
{
public:
OpString8HashTable(BOOL case_sensitive = FALSE) : OpGenericString8HashTable(case_sensitive) {}
OP_STATUS Add(const char* key, T* data) {return OpGenericString8HashTable::Add(key, (void*)data);}
void AddL(const char* key, T* data) {OpGenericString8HashTable::AddL(key, (void*)data);}
OP_STATUS GetData(const char* key, T** data) const {return OpGenericString8HashTable::GetData(key, (void**)data);}
BOOL Contains(const char* key) const {return OpGenericString8HashTable::Contains(key);}
OP_STATUS Remove(const char* key, T** data) {return OpGenericString8HashTable::Remove(key, (void**)data);}
OpHashIterator* GetIterator() {return OpGenericString8HashTable::GetIterator();}
void ForEach(void (*function)(const void *, void *)) {OpGenericString8HashTable::ForEach(function);}
void ForEach(void (*function)(const void *, void *, OpHashTable *)) {OpGenericString8HashTable::ForEach(function);}
void ForEach(OpHashTableForEachListener* listener) {OpGenericString8HashTable::ForEach(listener);}
void RemoveAll() {OpGenericString8HashTable::RemoveAll();}
void DeleteAll() {OpGenericString8HashTable::DeleteAll();}
virtual void Delete(void* data) {OP_DELETE((T*) data );}
INT32 GetCount() const {return OpGenericString8HashTable::GetCount();}
void SetMinimumCount(UINT32 minimum_count){ OpGenericString8HashTable::SetMinimumCount(minimum_count); }
};
template<class T>
class OpAutoStringHashTable : public OpStringHashTable<T>
{
public:
OpAutoStringHashTable(BOOL case_sensitive = FALSE) : OpStringHashTable<T>(case_sensitive) {}
virtual ~OpAutoStringHashTable() {this->DeleteAll();}
};
template<class T>
class OpAutoString8HashTable : public OpString8HashTable<T>
{
public:
OpAutoString8HashTable(BOOL case_sensitive = FALSE) : OpString8HashTable<T>(case_sensitive) {}
virtual ~OpAutoString8HashTable() {this->DeleteAll();}
};
template<class T>
class OpINT32HashTable : protected OpHashTable
{
public:
OpINT32HashTable() : OpHashTable() {}
OP_STATUS Add(INT32 key, T* data) {return OpHashTable::Add(reinterpret_cast<void*>(key), (void*)data);}
OP_STATUS GetData(INT32 key, T** data) const {return OpHashTable::GetData(reinterpret_cast<void*>(key), (void**)data);}
BOOL Contains(INT32 key) const {return OpHashTable::Contains(reinterpret_cast<void*>(key));}
OP_STATUS Remove(INT32 key, T** data) {return OpHashTable::Remove(reinterpret_cast<void*>(key), (void**)data);}
OpHashIterator* GetIterator() {return OpHashTable::GetIterator();}
void ForEach(void (*function)(const void *, void *)) {OpHashTable::ForEach(function);}
void ForEach(void (*function)(const void *, void *, OpHashTable *)) {OpHashTable::ForEach(function);}
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() {OpHashTable::RemoveAll();}
void DeleteAll() {OpHashTable::DeleteAll();}
virtual void Delete(void* data) {OP_DELETE((T*) data );}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpHashTable::CopyAllToVector(vector);}
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const {return OpHashTable::CopyAllToHashTable(hash_table);}
INT32 GetCount() const {return OpHashTable::GetCount();}
void SetMinimumCount(UINT32 minimum_count) {OpHashTable::SetMinimumCount(minimum_count);}
};
/* Helper template for storing non-pointer POD types as either
the keys or the values (or both) of a hash table. Note that it is still okay
to use a pointer type for either the keys or the values (or both, though
there might be better alternatives for that).
Note: DeleteAll() is a no-op for this hash table type. Be careful not to
leak memory if you store pointers as values.
Note: KeyType and ValueType need to fit in a void*. Rather than
instantiating this template yourself, prefer to use one of the
specializations below the class definition.
The methods in this template class call through to the base class
versions; see OpHashTable for documentation. */
template<class KeyType, class ValueType>
class OpGenericHashTable : protected OpHashTable
{
public:
OpGenericHashTable() : OpHashTable()
{
/* Make sure KeyType and ValueType fit in a void*, which is
what the underlying table class (OpHashTable) uses. */
OP_STATIC_ASSERT(sizeof(KeyType) <= sizeof(void*) &&
sizeof(ValueType) <= sizeof(void*));
}
OP_STATUS Add(KeyType key, ValueType data)
{
return OpHashTable::Add(KeyToConstVoidP(key), ValueToVoidP(data));
}
OP_STATUS Update(KeyType key,
ValueType data,
ValueType *old_data = NULL,
BOOL *key_was_in = NULL)
{
/* Use of 'conv' ensures we can safely write sizeof(void*) bytes, even
when sizeof(ValueType) < sizeof(void*) */
union { ValueType value; void *voidp; } conv;
conv.voidp = NULL;
conv.value = ValueType();
RETURN_IF_ERROR(OpHashTable::Update(KeyToConstVoidP(key),
ValueToVoidP(data),
old_data ? &conv.voidp : NULL,
key_was_in));
if (old_data)
*old_data = conv.value;
return OpStatus::OK;
}
OP_STATUS GetData(KeyType key, ValueType *data) const
{
/* Use of 'conv' ensures we can safely write sizeof(void*) bytes, even
when sizeof(ValueType) < sizeof(void*) */
union { ValueType value; void *voidp; } conv;
RETURN_IF_ERROR(OpHashTable::GetData(KeyToConstVoidP(key), &conv.voidp));
*data = conv.value;
return OpStatus::OK;
}
BOOL Contains(KeyType key) const
{
return OpHashTable::Contains(KeyToConstVoidP(key));
}
OP_STATUS Remove(KeyType key, ValueType *data)
{
/* Use of 'conv' ensures we can safely write sizeof(void*) bytes, even
when sizeof(ValueType) < sizeof(void*) */
union { ValueType value; void *voidp; } conv;
RETURN_IF_ERROR(OpHashTable::Remove(KeyToConstVoidP(key), &conv.voidp));
*data = conv.value;
return OpStatus::OK;
}
OpHashIterator* GetIterator() { return OpHashTable::GetIterator(); }
void ForEach( void (*function)(const void*, void*) ) { OpHashTable::ForEach(function); }
void ForEach( void (*function)(const void*, void*, OpHashTable*) ) { OpHashTable::ForEach(function); }
void ForEach(OpHashTableForEachListener* listener) { OpHashTable::ForEach(listener); }
void RemoveAll() { OpHashTable::RemoveAll(); }
void DeleteAll() { OpHashTable::DeleteAll(); }
virtual void Delete(void* data)
{
/* This method will be called if DeleteAll() is ever called on the
OpGenericHashTable instance. As the intent of such a kill is likely
to free pointers, and as this class is not designed to hold pointer
values (there are better alternatives), flag this with an assert. */
OP_ASSERT(!"OpGenericHashTable is not meant to hold pointer values");
}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const { return OpHashTable::CopyAllToVector(vector); }
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const { return OpHashTable::CopyAllToHashTable(hash_table); }
INT32 GetCount() const { return OpHashTable::GetCount(); }
void SetMinimumCount(UINT32 minimum_count) { OpHashTable::SetMinimumCount(minimum_count); }
private:
/* Helper functions for storing arbitrary data inside pointers. Strictly
speaking, writing one member of a union and reading the value back via
another results in undefined behavior, but enough programs depend on
this working "as expected" that it'll probably keep working. */
static const void *KeyToConstVoidP(KeyType key)
{
union { KeyType key; const void *cvoidp; } conv;
conv.cvoidp = 0; // Needed in case sizeof(const void*) > sizeof(KeyType)
conv.key = key;
return conv.cvoidp;
}
static void *ValueToVoidP(ValueType value)
{
union { ValueType value; void *voidp; } conv;
conv.voidp = 0; // Needed in case sizeof(void*) > sizeof(ValueType)
conv.value = value;
return conv.voidp;
}
};
// Specializations of the helper template OpGenericHashTable
typedef OpGenericHashTable<UINT32, UINT32> OpUINT32ToUINT32HashTable;
template <class T>
class OpAutoINT32HashTable : public OpINT32HashTable<T>
{
public:
OpAutoINT32HashTable() : OpINT32HashTable<T>() { }
virtual ~OpAutoINT32HashTable() { OpINT32HashTable<T>::DeleteAll(); }
};
template <class KeyType, class DataType>
class OpPointerHashTable : protected OpHashTable
{
public:
OpPointerHashTable() : OpHashTable() {}
OpPointerHashTable(OpHashFunctions* hashFunctions, BOOL useChainedHashing = TRUE) :
OpHashTable(hashFunctions,useChainedHashing)
{}
OP_STATUS Add(const KeyType* key, DataType* data) { return OpHashTable::Add((const void *)(key), (void *)(data)); }
OP_STATUS Remove(const KeyType* key, DataType** data) { return OpHashTable::Remove((const void *)(key), (void **)(data)); }
OP_STATUS GetData(const KeyType* key, DataType** data) const { return OpHashTable::GetData((const void *)(key), (void **)(data)); }
BOOL Contains(const KeyType* key) const { return OpHashTable::Contains((const void *)(key)); }
OpHashIterator* GetIterator() { return OpHashTable::GetIterator(); }
void ForEach(void (*function)(const void *, void *)) { OpHashTable::ForEach(function); }
void ForEach(void (*function)(const void *, void *, OpHashTable *)) { OpHashTable::ForEach(function); }
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() { OpHashTable::RemoveAll(); }
void DeleteAll() { OpHashTable::DeleteAll(); }
virtual void Delete(void* data) {OP_DELETE((DataType *)(data) ); }
INT32 GetCount() const { return OpHashTable::GetCount(); }
void SetMinimumCount(UINT32 minimum_count){ OpHashTable::SetMinimumCount(minimum_count); }
void SetHashFunctions(OpHashFunctions* hashFunctions) {OpHashTable::SetHashFunctions(hashFunctions);}
};
template <class KeyType, typename IdType>
class OpPointerIdHashTable : protected OpHashTable
{
public:
OpPointerIdHashTable() : OpHashTable() {}
OpPointerIdHashTable(OpHashFunctions* hashFunctions, BOOL useChainedHashing = TRUE) :
OpHashTable(hashFunctions,useChainedHashing)
{}
OP_STATUS Add(const KeyType* key, IdType id) { return OpHashTable::Add((const void *)(key), (void *)(INTPTR)(id)); }
OP_STATUS Remove(const KeyType* key, IdType* id)
{
void* value;
OP_STATUS status = OpHashTable::Remove((const void *)(key), &value);
if (OpStatus::IsSuccess(status))
*id = static_cast<IdType>(reinterpret_cast<UINTPTR>(value));
return status;
}
OP_STATUS GetData(const KeyType* key, IdType* id) const
{
void* value;
OP_STATUS status = OpHashTable::GetData((const void *)(key), &value);
if (OpStatus::IsSuccess(status))
*id = static_cast<IdType>(reinterpret_cast<UINTPTR>(value));
return status;
}
BOOL Contains(const KeyType* key) const { return OpHashTable::Contains((const void *)(key)); }
OpHashIterator* GetIterator() { return OpHashTable::GetIterator(); }
void ForEach(void (*function)(const void *, void *)) { OpHashTable::ForEach(function); }
void ForEach(void (*function)(const void *, void *, OpHashTable *)) { OpHashTable::ForEach(function); }
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() { OpHashTable::RemoveAll(); }
void DeleteAll() { OpHashTable::DeleteAll(); }
INT32 GetCount() const { return OpHashTable::GetCount(); }
void SetMinimumCount(UINT32 minimum_count){ OpHashTable::SetMinimumCount(minimum_count); }
void SetHashFunctions(OpHashFunctions* hashFunctions) {OpHashTable::SetHashFunctions(hashFunctions);}
};
template <class KeyType, class DataType>
class OpAutoPointerHashTable : public OpPointerHashTable<KeyType, DataType>
{
public:
OpAutoPointerHashTable() : OpPointerHashTable<KeyType, DataType>() { }
virtual ~OpAutoPointerHashTable() { OpPointerHashTable<KeyType, DataType>::DeleteAll(); }
};
class OpGenericPointerSet : public OpHashTable
{
public:
OpGenericPointerSet() : OpHashTable() {}
OP_STATUS Add(void* data) {return OpHashTable::Add(data, data);}
BOOL Contains(void* data) const {return OpHashTable::Contains(data);}
OP_STATUS Remove(void* data) {return OpHashTable::Remove(data, &data);}
OpHashIterator* GetIterator() {return OpHashTable::GetIterator();}
void ForEach(OpHashTableForEachListener* listener) {OpHashTable::ForEach(listener);}
void RemoveAll() {OpHashTable::RemoveAll();}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpHashTable::CopyAllToVector(vector);}
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const {return OpHashTable::CopyAllToHashTable(hash_table);}
INT32 GetCount() const {return OpHashTable::GetCount();}
void SetMinimumCount(UINT32 minimum_count) {OpHashTable::SetMinimumCount(minimum_count);}
};
template<class T>
class OpPointerSet : private OpGenericPointerSet
{
public:
OpPointerSet() : OpGenericPointerSet() {}
OP_STATUS Add(T* data) {return OpGenericPointerSet::Add(data);}
BOOL Contains(T* data) const {return OpGenericPointerSet::Contains(data);}
OP_STATUS Remove(T* data) {return OpGenericPointerSet::Remove(data);}
OpHashIterator* GetIterator() {return OpGenericPointerSet::GetIterator();}
void ForEach(OpHashTableForEachListener* listener) {OpGenericPointerSet::ForEach(listener);}
void RemoveAll() {OpGenericPointerSet::RemoveAll();}
void DeleteAll() {OpGenericPointerSet::DeleteAll();}
virtual void Delete(void* data) {OP_DELETE((T*) data );}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpGenericPointerSet::CopyAllToVector(vector);}
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const {return OpGenericPointerSet::CopyAllToHashTable(hash_table);}
INT32 GetCount() const {return OpHashTable::GetCount();}
};
class OpINT32Set : private OpGenericPointerSet
{
public:
/** Callback class for ForEach(). */
class ForEachIterator{
public:
virtual void HandleInteger(INT32 data) = 0;
};
OpINT32Set() : OpGenericPointerSet() {}
OP_STATUS Add(INT32 data) {return OpGenericPointerSet::Add(INT_TO_PTR(data));}
BOOL Contains(INT32 data) const {return OpGenericPointerSet::Contains(INT_TO_PTR(data));}
OP_STATUS Remove(INT32 data) {return OpGenericPointerSet::Remove(INT_TO_PTR(data));}
OpHashIterator* GetIterator() {return OpGenericPointerSet::GetIterator();}
void RemoveAll() {OpGenericPointerSet::RemoveAll();}
OP_STATUS CopyAllToVector(OpGenericVector& vector) const {return OpGenericPointerSet::CopyAllToVector(vector);}
OP_STATUS CopyAllToHashTable(OpHashTable& hash_table) const {return OpGenericPointerSet::CopyAllToHashTable(hash_table);}
INT32 GetCount() const {return OpGenericPointerSet::GetCount();}
void SetMinimumCount(UINT32 minimum_count) {OpGenericPointerSet::SetMinimumCount(minimum_count);}
void ForEach(ForEachIterator* itr) {
struct LocalItr : public OpHashTableForEachListener {
ForEachIterator* m_itr;
LocalItr(ForEachIterator* itr) : m_itr(itr) {}
virtual void HandleKeyData(const void* key, void* data)
{ m_itr->HandleInteger(PTR_TO_INTEGRAL(INT32, key)); }
} local_itr(itr);
OpGenericPointerSet::ForEach(&local_itr);
}
};
typedef OpINT32Set OpIntegerHashTable;
class OpStringHashSet : private OpStringHashTable<uni_char>
{
public:
OpStringHashSet() : OpStringHashTable<uni_char>() {}
OP_STATUS Add(uni_char* data) {return OpStringHashTable<uni_char>::Add(data, data);}
BOOL Contains(const uni_char* data) const {return OpStringHashTable<uni_char>::Contains(data);}
OP_STATUS Remove(uni_char* data) {return OpStringHashTable<uni_char>::Remove(data, &data);}
OpHashIterator* GetIterator() {return OpStringHashTable<uni_char>::GetIterator();}
void RemoveAll() {OpStringHashTable<uni_char>::RemoveAll();}
OP_STATUS CopyAllToVector(OpVector<uni_char>& vector) const {return OpStringHashTable<uni_char>::CopyAllToVector(*reinterpret_cast<OpGenericVector*>(&vector));}
INT32 GetCount() const {return OpStringHashTable<uni_char>::GetCount();}
void SetMinimumCount(UINT32 minimum_count) {OpStringHashTable<uni_char>::SetMinimumCount(minimum_count);}
virtual void Delete(void* data) { OP_DELETEA(reinterpret_cast<uni_char*>(data));}
void DeleteAll() { OpStringHashTable<uni_char>::DeleteAll();}
};
class OpConstStringHashSet : private OpStringHashTable<const uni_char>
{
public:
OpConstStringHashSet() : OpStringHashTable<const uni_char>() {}
OP_STATUS Add(const uni_char* data) {return OpStringHashTable<const uni_char>::Add(data, data);}
BOOL Contains(const uni_char* data) const {return OpStringHashTable<const uni_char>::Contains(data);}
OP_STATUS Remove(const uni_char* data) {return OpStringHashTable<const uni_char>::Remove(data, &data);}
OpHashIterator* GetIterator() {return OpStringHashTable<const uni_char>::GetIterator();}
void RemoveAll() {OpStringHashTable<const uni_char>::RemoveAll();}
OP_STATUS CopyAllToVector(OpVector<const uni_char>& vector) const {return OpStringHashTable<const uni_char>::CopyAllToVector(*reinterpret_cast<OpGenericVector*>(&vector));}
INT32 GetCount() const {return OpStringHashTable<const uni_char>::GetCount();}
void SetMinimumCount(UINT32 minimum_count) {OpStringHashTable<const uni_char>::SetMinimumCount(minimum_count);}
virtual void Delete(void* data) { OP_DELETEA(reinterpret_cast<uni_char*>(data));}
void DeleteAll() { OpStringHashTable<const uni_char>::DeleteAll();}
};
class OpAutoStringHashSet : public OpStringHashSet
{
public:
~OpAutoStringHashSet() { DeleteAll(); }
};
#endif // !MODULES_UTIL_OPHASHTABLE_H
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef FUNCTION_DEF_HPP
#define FUNCTION_DEF_HPP
#include <boost/ptr_container/ptr_vector.hpp>
#include "basis.hpp"
#include "Teuchos_ParameterList.hpp"
#include <Kokkos_Core.hpp>
#if defined (KOKKOS_HAVE_CUDA) || defined (KOKKOS_ENABLE_CUDA)
#define TUSAS_DEVICE __device__
#define TUSAS_HAVE_CUDA
#else
#define TUSAS_DEVICE /**/
#endif
/** Definition for residual function. Each residual function is called at each Gauss point for each equation with this signature:
- NAME: name of function to call
- const boost::ptr_vector<Basis> &basis: an array of basis function objects indexed by equation
- const int &i: the current test function (row in residual vector)
- const double &dt_: the timestep size as prescribed in input file
- const double &t_theta_: the timestep parameter as prescribed in input file
- const double &time: the current simulation time
- const int &eqn_id: the index of the current equation
*/
#define RES_FUNC(NAME) double NAME(const boost::ptr_vector<Basis> &basis,\
const int &i,\
const double &dt_,\
const double &dtold_,\
const double &t_theta_,\
const double &t_theta2_,\
const double &time,\
const int &eqn_id)
/** Definition for precondition function. Each precondition function is called at each Gauss point for each equation with this signature:
- NAME: name of function to call
- const boost::ptr_vector<Basis> &basis: an array of basis function objects indexed by equation
- const int &i: the current basis function (row in preconditioning matrix)
- const int &j: the current test function (column in preconditioning matrix)
- const double &dt_: the timestep size as prescribed in input file
- const double &t_theta_: the timestep parameter as prescribed in input file
- const double &time: the current simulation time
- const int &eqn_id: the index of the current equation
*/
#define PRE_FUNC(NAME) double NAME(const boost::ptr_vector<Basis> &basis,\
const int &i,\
const int &j,\
const double &dt_,\
const double &t_theta_,\
const int &eqn_id)
/** Definition for initialization function. Each initialization function is called at each node for each equation at the beginning of the simualtaion with this signature:
- NAME: name of function to call
- const double &x: the x-ccordinate of the node
- const double &y: the y-ccordinate of the node
- const double &z: the z-ccordinate of the node
- const int &eqn_id: the index of the current equation
*/
#define INI_FUNC(NAME) double NAME(const double &x,\
const double &y,\
const double &z,\
const int &eqn_id)
/** Definition for Dirichlet function. Each Dirichlet function is called at each node for each equation with this signature:
- NAME: name of function to call
- const double &x: the x-ccordinate of the node
- const double &y: the y-ccordinate of the node
- const double &z: the z-ccordinate of the node
- const int &eqn_id: the index of the current equation
- const double &t: the current time
*/
#define DBC_FUNC(NAME) double NAME(const double &x,\
const double &y,\
const double &z,\
const double &t)
/** Definition for Neumann function. Each Neumann function is called at each Gauss point for the current equation with this signature:
- NAME: name of function to call
- const Basis *basis: basis function object for current equation
- const int &i: the current basis function (row in residual vector)
- const double &dt_: the timestep size as prescribed in input file
- const double &t_theta_: the timestep parameter as prescribed in input file
- const double &time: the current simulation time
*/
#define NBC_FUNC(NAME) double NAME(const Basis *basis,\
const int &i,\
const double &dt_,\
const double &t_theta_,\
const double &time)
/** Definition for post-process function. Each post-process function is called at each node for each equation at the end of each timestep with this signature:
- NAME: name of function to call
- const double *u: an array of solution values indexed by equation
- const double *gradu: an array of gradient values indexed by equation, coordinates (NULL unless error estimation is activated)
- const double *xyz: an array of coordinates indexed by equation, coordinates
- const double &time: the current simulation time
*/
#define PPR_FUNC(NAME) double NAME(const double *u,\
const double *uold,\
const double *uoldold,\
const double *gradu,\
const double *xyz,\
const double &time,\
const double &dt,\
const double &dtold,\
const int &eqn_id)
/** Parameter function to propogate information from input file. Each parameter function is called at the beginning of each simulation.
- NAME: name of function to call
- Teuchos::ParameterList *plist: paramterlist containing information defined in input file
*/
#define PARAM_FUNC(NAME) void NAME(Teuchos::ParameterList *plist)
namespace heat
{
/** Residual function for heat equation test problem. */
RES_FUNC(residual_heat_test_)
{
//for heat eqn:
//u[x,y,t]=exp(-2 pi^2 t)sin(pi x)sin(pi y)
//for neumann:
//u[x,y,t]=exp( -1/4 pi^2 t)sin(pi/4 x)
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
double dtestdz = basis[0].dphidz[i];
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double ut = (u-uold)/dt_*test;
double divgradu = (basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
double divgradu_old = (basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return ut + t_theta_*divgradu + (1.-t_theta_)*divgradu_old;
}
PRE_FUNC(prec_heat_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
double dtestdz = basis[0].dphidz[i];
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz;
double u_t =test * basis[0].phi[j]/dt_;
return u_t + t_theta_*divgrad;
}
INI_FUNC(init_heat_test_)
{
double pi = 3.141592653589793;
return sin(pi*x)*sin(pi*y);
}
}//namespace heat
namespace timeonly
{
const double pi = 3.141592653589793;
//const double lambda = 10.;//pi*pi;
const double lambda = pi*pi;
const double ff(const double &u)
{
return -lambda*u;
}
RES_FUNC(residual_test_)
{
//test function
const double test = basis[0].phi[i];
//u, phi
const double u[3] = {basis[0].uu,basis[0].uuold,basis[0].uuoldold};
const double ut = (u[0]-u[1])/dt_*test;
const double f[3] = {ff(u[0])*test,ff(u[1])*test,ff(u[2])*test};
//std::cout<<u[1]<<" "<<u[2]<<std::endl;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
INI_FUNC(init_test_)
{
return 1.;
}
PPR_FUNC(postproc1_)
{
const double uu = u[eqn_id];
// const double x = xyz[0];
// const double y = xyz[1];
const double pi = 3.141592653589793;
//d2udt2 = 4 E^(-2 \[Pi]^2 t) \[Pi]^4 Sin[\[Pi] x] Sin[\[Pi] y];
const double uex = exp(-lambda*time);
return uex-uu;
}
PPR_FUNC(postproc2_)
{
//const double uu = u[eqn_id];
// const double x = xyz[0];
// const double y = xyz[1];
//const double pi = 3.141592653589793;
//d2udt2 = 4 E^(-2 \[Pi]^2 t) \[Pi]^4 Sin[\[Pi] x] Sin[\[Pi] y];
const double uex = exp(-lambda*time);
return uex;
}
PPR_FUNC(postproc3_)
{
//const double uu = u[eqn_id];
// const double x = xyz[0];
// const double y = xyz[1];
//const double pi = 3.141592653589793;
//d2udt2 = 4 E^(-2 \[Pi]^2 t) \[Pi]^4 Sin[\[Pi] x] Sin[\[Pi] y];
//const double uex = exp(-pi*pi*time);
return u[eqn_id];
}
}//namespace timeonly
namespace autocatalytic4
{
//https://documen.site/download/math-3795-lecture-18-numerical-solution-of-ordinary-differential-equations-goals_pdf#
//https://media.gradebuddy.com/documents/2449908/0c88cf76-7605-4aec-b2ad-513ddbebefec.pdf
const double k1 = .0001;
const double k2 = 1.;
const double k3 = .0008;
RES_FUNC(residual_a_)
{
const double test = basis[0].phi[i];
//u, phi
const double u = basis[0].uu;
const double uold = basis[0].uuold;
const double uoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
//std::cout<<ut<<" "<<dt_<<" "<<time<<std::endl;
double f[3];
f[0] = (-k1*u - k2*u*basis[1].uu)*test;
f[1] = (-k1*uold - k2*u*basis[1].uuold)*test;
f[2] = (-k1*uoldold - k2*u*basis[1].uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_b_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[1].uu;
const double uold = basis[1].uuold;
//const double uoldold = basis[1].uuoldold;
const double a = basis[0].uu;
const double aold = basis[0].uuold;
const double aoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k1*a - k2*a*u + 2.*k3*basis[2].uu)*test;
f[1] = (k1*aold - k2*aold*uold + 2.*k3*basis[2].uuold)*test;
f[2] = (k1*aoldold - k2*aoldold*basis[1].uuoldold + 2.*k3*basis[2].uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_ab_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[2].uu;
const double uold = basis[2].uuold;
//const double uoldold = basis[1].uuoldold;
const double b = basis[1].uu;
const double bold = basis[1].uuold;
const double boldold = basis[1].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k2*b*basis[0].uu - k3*u)*test;
f[1] = (k2*bold*basis[0].uuold - k3*uold)*test;
f[2] = (k2*boldold*basis[0].uuoldold - k3*basis[2].uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_c_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[3].uu;
const double uold = basis[3].uuold;
//const double uoldold = basis[1].uuoldold;
const double a = basis[0].uu;
const double aold = basis[0].uuold;
const double aoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k1*a + k3*basis[2].uu)*test;
f[1] = (k1*aold + k3*basis[2].uuold)*test;
f[2] = (k1*aoldold + k3*basis[2].uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
INI_FUNC(init_a_)
{
return 1.;
}
INI_FUNC(init_b_)
{
return 0.;
}
INI_FUNC(init_ab_)
{
return 0.;
}
INI_FUNC(init_c_)
{
return 0.;
}
}//namespace autocatalytic4
namespace chem
{
//https://documen.site/download/math-3795-lecture-18-numerical-solution-of-ordinary-differential-equations-goals_pdf#
//https://media.gradebuddy.com/documents/2449908/0c88cf76-7605-4aec-b2ad-513ddbebefec.pdf
const double k1 = .01;
const double k2 = 1.;
const double k3 = .0008;
RES_FUNC(residual_a_)
{
const double test = basis[0].phi[i];
//u, phi
const double u = basis[0].uu;
const double uold = basis[0].uuold;
const double uoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = -k1*u*basis[1].uu*test;
f[1] = -k1*uold*basis[1].uuold*test;
f[2] = -k1*uoldold*basis[1].uuold*test;
//if(t_theta2_>.99)std::cout<<t_theta2_<<" "<<t_theta_<<" "<<dt_<<" "<<dtold_<<std::endl;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_b_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[1].uu;
const double uold = basis[1].uuold;
//const double uoldold = basis[1].uuoldold;
const double a = basis[0].uu;
const double aold = basis[0].uuold;
const double aoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = -k1*a*u*test;
f[1] = -k1*aold*uold*test;
f[2] = -k1*aoldold*basis[1].uuoldold*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_ab_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[2].uu;
const double uold = basis[2].uuold;
//const double uoldold = basis[1].uuoldold;
const double b = basis[1].uu;
const double bold = basis[1].uuold;
const double boldold = basis[1].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k2*b*basis[0].uu - k3*u)*test;
f[1] = (k2*bold*basis[0].uuold - k3*uold)*test;
f[2] = (k2*boldold*basis[0].uuoldold - k3*basis[2].uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_c_)
{
const double test = basis[1].phi[i];
//u, phi
const double u = basis[2].uu;
const double uold = basis[2].uuold;
//const double uoldold = basis[1].uuoldold;
const double a = basis[0].uu;
const double aold = basis[0].uuold;
const double aoldold = basis[0].uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = k1*a*basis[1].uu*test;
f[1] = k1*aold*basis[1].uuold*test;
f[2] = k1*aoldold*basis[1].uuoldold*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
INI_FUNC(init_a_)
{
return 1.;
}
INI_FUNC(init_b_)
{
return .5;
}
INI_FUNC(init_ab_)
{
return 0.;
}
INI_FUNC(init_c_)
{
return 0.;
}
}//namespace chem
namespace timeadapt
{
PPR_FUNC(d2udt2_)
{
const double uu = u[eqn_id];
const double uuold = uold[eqn_id];
const double uuoldold = uoldold[eqn_id];
const double duuold = (uuold-uuoldold)/dtold;
const double duu = (uu-uuold)/dt;
const double d2udt2 = (duu-duuold)/dt;
//const double ae = .5*dt*dt*d2udt2;
// double r = 0;
// r = abs(d2udt2/1.);
//if (uu*uu > 1.e-8) r = abs(d2udt2/uu);
//r = std::max(abs(d2udt2/uu),1.e-10);
//return sqrt(2.*tol*abs(uu)/abs(d2udt2));
//return abs(d2udt2/uu);
//std::cout<<r<<" "<<uu*uu<<" "<<d2udt2<<std::endl;
return .5*dt*dt*d2udt2;
}
PPR_FUNC(predictor_fe_)
{
const double uu = u[eqn_id];
//const double uuold = uold[eqn_id];
//const double uuoldold = uoldold[eqn_id];
const double uupred = gradu[eqn_id];//hack for now
//std::cout<<eqn_id<<" "<<uold[eqn_id]<<std::endl;
//std::cout<<eqn_id<<" "<<uu<<" "<<uupred<<" "<<uu - uupred<<std::endl;
return (uu - uupred);
}
PPR_FUNC(postproc1_)
{
const double uu = u[eqn_id];
const double x = xyz[0];
const double y = xyz[1];
const double pi = 3.141592653589793;
//d2udt2 = 4 E^(-2 \[Pi]^2 t) \[Pi]^4 Sin[\[Pi] x] Sin[\[Pi] y];
const double uex = exp(-2.*pi*pi*time)*sin(pi*x)*sin(pi*y);
//const double d2udt2ex = 4.*pi*pi*pi*pi*exp(-2.*pi*pi*time)*sin(pi*x)*sin(pi*y);
//return sqrt(2.*tol*abs(uu)/abs(d2udt2));
//return d2udt2;
//return abs(d2udt2ex/uex);
//return abs(d2udt2ex/1.);
return uu;
}
PPR_FUNC(postproc2_)
{
//const double uu = u[eqn_id];
const double x = xyz[0];
const double y = xyz[1];
const double pi = 3.141592653589793;
//d2udt2 = 4 E^(-2 \[Pi]^2 t) \[Pi]^4 Sin[\[Pi] x] Sin[\[Pi] y];
const double uex = exp(-2.*pi*pi*time)*sin(pi*x)*sin(pi*y);
//const double d2udt2ex = 4.*pi*pi*pi*pi*exp(-2.*pi*pi*time)*sin(pi*x)*sin(pi*y);
//return sqrt(2.*tol*abs(uu)/abs(d2udt2));
//return d2udt2;
//return abs(d2udt2ex/uex);
//return abs(d2udt2ex/1.);
const double uuoldold = gradu[eqn_id];//hack for now
return uuoldold;
}
PPR_FUNC(normu_)
{
const double uu = u[eqn_id];
return uu;
}
PPR_FUNC(dynamic_)
{
const double uu = u[eqn_id];
const double uuold = uold[eqn_id];
// std::cout<<uu<<" "<<uuold<<" "<<dt<<std::endl;
// return uu*dt/(uu-uuold);
return (uu-uuold)/dt/uu;
}
}//namespace timeadapt
double rand_phi_zero_(const double &phi, const double &random_number)
{
return 0.;
}
//furtado
double hp1_furtado_(const double &phi,const double &c)
{
double dH = 2.35e9;
double Tm = 1728.;
return -30.*dH/Tm*phi*phi*(1.-phi)*(1.-phi);
}
double hpp1_furtado_(const double &phi,const double &c)
{
double dH = 2.35e9;
double Tm = 1728.;
return -30.*dH/Tm* 2.* (1. -phi) *phi* (1. - 2. *phi) ;
}
double gp1_furtado_(const double &phi)
{
return 2.*phi*(1.-phi)*(1.-2.*phi);
}
double gpp1_furtado_(const double &phi)
{
return 2.*( 1. - 6.* phi + 6.* phi*phi);
}
double w_furtado_(const double &delta)
{
return .61e8;
}
double m_furtado_(const double &theta,const double &M,const double &eps)
{
//return 1./13.47;
return 1.;
}
double hp2_furtado_(const double &phi)
{
double dH = 2.35e9;
double rho = 0.37;
double Cp = 5.42e6;
//return dH/rho/Cp*30.*phi*phi*(1.-phi)*(1.-phi);
//return 1.*phi*phi*(1.-phi)*(1.-phi);
return 1.;
}
double rand_phi_furtado_(const double &phi, const double &random_number)
{
//double a = .025;
double a = 75.;
double r = 16.*a*phi*phi
*(1.-phi)*(1.-phi);
// double r = 256.*a*phi*phi*phi*phi
// *(1.-phi)*(1.-phi)*(1.-phi)*(1.-phi);
if( phi > 1. || phi < 0. ) r = 0;
return ((double)rand()/(RAND_MAX)*2.-1.)*r;
// return random_number*16.*r;
}
//karma
//karma has phi in [-1 +1]
double hp2_karma_(const double &phi)
{
//return 15./8./2.*(1.-2*phi*phi+phi*phi*phi*phi);//VF
return .5;//IVF
}
double w_karma_(const double &delta)
{
return 1.;
}
double gp1_karma_(const double &phi)
{
return phi*(1.-phi*phi);
}
double hp1_karma_(const double &phi,const double &c)
{
double lambda = 1.;
return -lambda* (1. -phi*phi) * (1. -phi*phi) ;
}
double hpp1_karma_(const double &phi,const double &c)//precon term
{
double dH = 2.35e9;
double Tm = 1728.;
//return -30.*dH/Tm* 2.* (1. -phi) *phi* (1. - 2. *phi) ;
return 0. ;
}
double gpp1_karma_(const double &phi)//precon term
{
//return 2.*( 1. - 6.* phi + 6.* phi*phi);
return 0.;
}
double m_karma_(const double &theta,const double &M,const double &eps)
{
double eps4 = eps;
double a_sbar = 1. - 3.* eps4;
double eps_prime = 4.*eps4/a_sbar;
double t0 = 1.;
double g = a_sbar*(1. + eps_prime * (pow(sin(theta),M)+pow(cos(theta),M)));
return t0*g*g;
}
double gs2_karma_( const double &theta, const double &M, const double &eps, const double &psi)
{
//double g = 1. + eps_ * (M_*cos(theta));
double W_0 = 1.;
double eps4 = eps;
double a_sbar = 1. - 3.* eps4;
double eps_prime = 4.*eps4/a_sbar;
double g = W_0*a_sbar*(1. + eps_prime * (pow(sin(theta),M)+pow(cos(theta),M)));
return g*g;
}
double dgs2_2dtheta_karma_(const double &theta, const double &M, const double &eps, const double &psi)
{
double W_0 = 1.;
double eps4 = eps;
double a_sbar = 1. - 3.* eps4;
double eps_prime = 4.*eps4/a_sbar;
double g = W_0*a_sbar*eps*(-4.*pow(cos(theta),3)*sin(theta) + 4.*cos(theta)*pow(sin(theta),3))*
(1. + eps*(pow(cos(theta),4) + pow(sin(theta),4)));
return g;
}
/*
@inproceedings{inproceedings,
author = {Cummins, Sharen and J Quirk, James and Kothe, Douglas},
year = {2002},
month = {11},
pages = {},
title = {An Exploration of the Phase Field Technique for Microstructure Solidification Modeling}
}
*/
namespace cummins
{
double delta_ = -9999.;
double m_cummins_(const double &theta,const double &M,const double &eps)
{
//double g = 1. + eps * (cos(M*(theta)));
double g = (4.*eps*(cos(theta)*cos(theta)*cos(theta)*cos(theta)
+ sin(theta)*sin(theta)*sin(theta)*sin(theta) ) -3.*eps +1. );
return g*g;
}
double hp2_cummins_(const double &phi)
{
return 1.;
}
RES_FUNC(residual_heat_)
{
//derivatives of the test function
double dtestdx = basis[eqn_id].dphidxi[i]*basis[eqn_id].dxidx
+basis[eqn_id].dphideta[i]*basis[eqn_id].detadx
+basis[eqn_id].dphidzta[i]*basis[eqn_id].dztadx;
double dtestdy = basis[eqn_id].dphidxi[i]*basis[eqn_id].dxidy
+basis[eqn_id].dphideta[i]*basis[eqn_id].detady
+basis[eqn_id].dphidzta[i]*basis[eqn_id].dztady;
double dtestdz = basis[eqn_id].dphidxi[i]*basis[eqn_id].dxidz
+basis[eqn_id].dphideta[i]*basis[eqn_id].detadz
+basis[eqn_id].dphidzta[i]*basis[eqn_id].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double phi = basis[1].uu;
double phiold = basis[1].uuold;
double D_ = 4.;
double ut = (u-uold)/dt_*test;
double divgradu = D_*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
// double divgradu_old = D_*(basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
// double divgradu = diffusivity_(*ubasis)*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
double divgradu_old = D_*(basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
double hp2 = hp2_cummins_(phi);
double phitu = -hp2*(phi-phiold)/dt_*test;
hp2 = hp2_cummins_(phiold);
double phitu_old = -hp2*(phiold-basis[1].uuoldold)/dt_*test;
return (ut + t_theta_*divgradu + (1.-t_theta_)*divgradu_old + t_theta_*phitu
+ (1.-t_theta_)*phitu_old);
}
double theta(const double &x,const double &y)
{
double small = 1e-9;
double pi = 3.141592653589793;
double t = 0.;
double sy = 1.;
if(y < 0.) sy = -1.;
double n = sy*sqrt(y*y);
//double n = y;
//std::cout<<y<<" "<<n<<std::endl;
// if(abs(x) < small && y > 0. ) t = pi/2.;
// else if(abs(x) < small && y < 0. ) t = 3.*pi/2.;
// else t= atan(n/x);
if(std::abs(x) < small && y > 0. ) t = pi/2.;
if(std::abs(x) < small && y < 0. ) t = 3.*pi/2.;
if(x > small && y >= 0.) t= atan(n/x);
if(x > small && y <0.) t= atan(n/x) + 2.*pi;
if(x < -small) t= atan(n/x)+ pi;
return t;
}
double gs_cummins_(const double &theta, const double &M, const double &eps, const double &psi)
{
double eps_0_ = 1.;
double g = eps_0_*(4.*eps*(cos(theta)*cos(theta)*cos(theta)*cos(theta)
+ sin(theta)*sin(theta)*sin(theta)*sin(theta)
*(1.-2.*sin(psi)*sin(psi)*cos(psi)*cos(psi))
) -3.*eps +1. );
return g;
}
double gs2_cummins_( const double &theta, const double &M, const double &eps, const double &psi)
{
double eps_0_ = 1.;
//double g = eps_0_*(1. + eps * (cos(M*theta)));
// double g = eps_0_*(4.*eps*(cos(theta)*cos(theta)*cos(theta)*cos(theta)
// + sin(theta)*sin(theta)*sin(theta)*sin(theta) ) -3.*eps +1. );
double g = gs_cummins_(theta,M,eps,psi);
return g*g;
}
double dgs2_2dtheta_cummins_(const double &theta, const double &M, const double &eps, const double &psi)
{
double eps_0_ = 1.;
//return -1.*eps_0_*(eps*M*(1. + eps*cos(M*(theta)))*sin(M*(theta)));
double g = gs_cummins_(theta,M,eps,psi);
//double dg = 4.* eps* (-4.*cos(theta)*cos(theta)*cos(theta)*sin(theta) + 4.* cos(theta)*sin(theta)*sin(theta)*sin(theta));
double dg = 4.* eps* (-4.*cos(theta)*cos(theta)*cos(theta)*sin(theta) +
4.* cos(theta)*sin(theta)*sin(theta)*sin(theta)*(1.-2.*cos(psi)*cos(psi)*sin(psi)*sin(psi)));
return g*dg;
// return eps_0_*4.*eps*(-4.*cos(theta)*cos(theta)*cos(theta)*sin(theta) + 4.*cos(theta)*sin(theta)*sin(theta)*sin(theta))
// *(1. - 3.*eps + 4.*eps*(cos(theta)*cos(theta)*cos(theta)*cos(theta)
// + sin(theta)*sin(theta)*sin(theta)*sin(theta)));
}
double dgs2_2dpsi_cummins_(const double &theta, const double &M, const double &eps, const double &psi)
{
//4 eps (-4 Cos[psi]^3 Sin[psi] + 4 Cos[psi] Sin[psi]^3) Sin[theta]^4
double g = gs_cummins_(theta,M,eps,psi);
double dg = 4.* eps* (-4.*cos(psi)*cos(psi)*cos(psi)*sin(psi) + 4.*cos(psi)*sin(psi)*sin(psi)*sin(psi))*sin(theta)*sin(theta)*sin(theta)*sin(theta);
return g*dg;
}
double w_cummins_(const double &delta)
{
return 1./delta/delta;
}
double gp1_cummins_(const double &phi)
{
return phi*(1.-phi)*(1.-2.*phi);
}
double hp1_cummins_(const double &phi,const double &c)
{
return -c*phi*phi*(1.-phi)*(1.-phi);
}
double hpp1_cummins_(const double &phi,const double &c)
{
return -c* 2.* (1. -phi) *phi* (1. - 2. *phi);
}
double gpp1_cummins_(const double &phi)
{
return 1. - 6.* phi + 6.* phi*phi;
}
RES_FUNC(residual_phase_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double phi = basis[1].uu;
double phiold = basis[1].uuold;
double eps_ = .05;
double M_= 4.;
double dphidx = basis[1].dudx;
double dphidy = basis[1].dudy;
double dphidz = basis[1].dudz;
double theta_0_ =0.;
double theta_ = theta(dphidx,dphidy)-theta_0_;
double psi_ = 0.;
double m = m_cummins_(theta_, M_, eps_);
double phit = m*(phi-phiold)/dt_*test;
double gs2 = gs2_cummins_(theta_, M_, eps_,0.);
double divgradphi = gs2*(dphidx*dtestdx + dphidy*dtestdy + dphidz*dtestdz);//(grad u,grad phi)
double dgdtheta = dgs2_2dtheta_cummins_(theta_, M_, eps_, 0.);
double dgdpsi = 0.;
double curlgrad = dgdtheta*(-dphidy*dtestdx + dphidx*dtestdy);//cn could be a wrong sign here!!!
//+dgdpsi*(-dphidz*dtestdx + dphidx*dtestdz);
double w = w_cummins_(delta_);//cn_delta
double gp1 = gp1_cummins_(phi);
double phidel2 = gp1*w*test;
double T_m_ = 1.55;
double T_inf_ = 1.;
double alpha_ = 191.82;
double hp1 = hp1_cummins_(phi,5.*alpha_/delta_);
double phidel = hp1*(T_m_ - u)*test;
double rhs = divgradphi + curlgrad + phidel2 + phidel;
dphidx = basis[1].duolddx;
dphidy = basis[1].duolddy;
dphidz = basis[1].duolddz;
theta_ = theta(dphidx,dphidy)-theta_0_;
//psi_ = psi(dphidx,dphidy,dphidz);
psi_ =0.;
gs2 = gs2_cummins_(theta_, M_, eps_,0.);
divgradphi = gs2*dphidx*dtestdx + gs2*dphidy*dtestdy + gs2*dphidz*dtestdz;//(grad u,grad phi)
dgdtheta = dgs2_2dtheta_cummins_(theta_, M_, eps_, 0.);
curlgrad = dgdtheta*(-dphidy*dtestdx + dphidx*dtestdy);
//+dgdpsi*(-dphidz*dtestdx + dphidx*dtestdz);
gp1 = gp1_cummins_(phiold);
phidel2 = gp1*w*basis[1].phi[i];
hp1 = hp1_cummins_(phiold,5.*alpha_/delta_);
phidel = hp1*(T_m_ - uold)*test;
double rhs_old = divgradphi + curlgrad + phidel2 + phidel;
return phit + t_theta_*rhs + (1.-t_theta_)*rhs_old;
}
PRE_FUNC(prec_heat_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double D_ = 4.;
double divgrad = D_*dbasisdx * dtestdx + D_*dbasisdy * dtestdy + D_*dbasisdz * dtestdz;
double u_t =test * basis[0].phi[j]/dt_;
return u_t + t_theta_*divgrad;
}
PRE_FUNC(prec_phase_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double dphidx = basis[1].dudx;
double dphidy = basis[1].dudy;
double dphidz = basis[1].dudz;
double eps_ = .05;
double M_= 4.;
double theta_0_ =0.;
double theta_ = theta(dphidx,dphidy)-theta_0_;
double m = m_cummins_(theta_, M_, eps_);
double phit = m*(basis[1].phi[j])/dt_*test;
double gs2 = gs2_cummins_(theta_, M_, eps_,0.);
double divgrad = gs2*dbasisdx * dtestdx + gs2*dbasisdy * dtestdy + gs2*dbasisdz * dtestdz;
double dg2 = dgs2_2dtheta_cummins_(theta_, M_, eps_,0.);
double curlgrad = -dg2*(dtestdy*dphidx -dtestdx*dphidy);
return phit + t_theta_*divgrad + t_theta_*curlgrad;
}
double R_cummins(const double &theta)
{
double R_0_ = .3;
double eps_ = .05;
double M_ = 4.;
return R_0_*(1. + eps_ * cos(M_*(theta)));
}
//double init_heat_(const double &x,
// const double &y,
// const double &z)
INI_FUNC(init_heat_)
{
double theta_0_ = 0.;
double t = theta(x,y) - theta_0_;
double r = R_cummins(t);
double T_m_ = 1.55;
double T_inf_ = 1.;
double val = 0.;
if(x*x+y*y+z*z < r*r){
val=T_m_;
}
else {
val=T_inf_;
}
return val;
}
INI_FUNC(init_heat_const_)
{
double T_inf_ = 1.;
return T_inf_;
}
INI_FUNC(init_phase_)
{
double theta_0_ = 0.;
double t = theta(x,y) - theta_0_;
double r = R_cummins(t);
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = 0.;
if(x*x+y*y+z*z < r*r){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
PARAM_FUNC(param_)
{
delta_ = plist->get<double>("delta");
}
}//cummins
INI_FUNC(init_zero_)
{
return 0.;
}
NBC_FUNC(nbc_zero_)
{
double phi = basis->phi[i];
return 0.*phi;
}
KOKKOS_INLINE_FUNCTION
DBC_FUNC(dbc_zero_)
{
return 0.;
}
NBC_FUNC(nbc_one_)
{
double phi = basis->phi[i];
return 1.*phi;
}
DBC_FUNC(dbc_one_)
{
return 1.;
}
DBC_FUNC(dbc_ten_)
{
return 10.*dbc_one_(x,
y,
z,
t);
}
NBC_FUNC(nbc_mone_)
{
double phi = basis->phi[i];
return -1.*phi;
}
DBC_FUNC(dbc_mone_)
{
return -1.;
}
INI_FUNC(init_neumann_test_)
{
double pi = 3.141592653589793;
return sin(pi*x);
}
namespace farzadi
{
//it appears the mm mesh is in um
// 1m = 1e3 mm
// 1m = 1e6 um
double pi = 3.141592653589793;
double theta_0_ = 0.;
double phi_sol_ = 1.;
double phi_liq_ = -1.;
double k_ =0.14;
double eps_ = .01;
double M_= 4.;
double lambda = 10.;
double c_inf = 3.;
double D= 6.267;
//double D_ = 3.e-9;//m^2/s
//double D_ = .003;//mm^2/s
double D_ = 3.e3;//um^2/s
//double D_ = D;
//double m = -2.6;
double tl = 925.2;//k
double ts = 877.3;//k
double G = .290900;//k/um
double R = 3000.;//um/s
double V = R;//um/s
double t0 = ts;
//double t0 = 900.;//k
double dt0 = tl-ts;
//double d0 = 5.e-9;//m
double d0 = 5.e-3;//um
//for the farzadiQuad1000x360mmr.e mesh...
double pp = 360.;
double ll = 40.;
double aa = 14.;
//double init_conc_farzadi_(const double &x,
// const double &y,
// const double &z)
PARAM_FUNC(param_)
{
pp = plist->get<double>("pp");
ll = plist->get<double>("ll");
aa = plist->get<double>("aa");
}
INI_FUNC(init_conc_farzadi_)
{
double val = -1.;
return val;
}
double ff(const double y)
{
return 2.+sin(y*aa*pi/pp);
}
//double init_phase_farzadi_(const double &x,
// const double &y,
// const double &z)
INI_FUNC(init_phase_farzadi_)
{
double val = phi_liq_;
double r = ll*(1.+ff(y)*ff(y/2.)*ff(y/4.));
//r=.9;
if(x < r){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
//return 1.;
}
INI_FUNC(init_phase_rand_farzadi_)
{
double val = phi_liq_;
int ri = rand()%(100);//random int between 0 and 100
double rd = (double)ri/ll;
double r = .5+rd*std::abs(sin(y*aa*pi/pp));
//r=.9;
if(x < r){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
//return 1.;
}
double tscale_(const double &x, const double &time)
{
//x and time come in as nondimensional quantities here...
double xx = d0*x;
double tt = d0*d0/D_*time;
double t = t0 + G*(xx-V*tt);
return (t-ts)/dt0;
}
RES_FUNC(residual_phase_farzadi_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double phi = basis[1].uu;
double phiold = basis[1].uuold;
double dphidx = basis[1].dudx;
double dphidy = basis[1].dudy;
//double theta_ = theta(basis[1].duolddx,basis[1].duolddy);
double theta_ = cummins::theta(basis[1].dudx,basis[1].dudy);
double m = (1+(1-k_)*u)*cummins::m_cummins_(theta_, M_, eps_);//cn we probably need u and uold here for CN...
//double m = m_cummins_(theta_, M_, eps_);//cn we probably need u and uold here for CN...
//double theta_old = theta(dphidx,dphidy);
//double mold = (1+(1-k_)*uold)*m_cummins_(theta_old, M_, eps_);
//double phit = (t_theta_*m+(1.-t_theta_)*mold)*(phi-phiold)/dt_*test;
//double phit = m*(phi-phiold)/dt_*test;
double gs2 = cummins::gs2_cummins_(theta_, M_, eps_,0.);
double divgradphi = gs2*(dphidx*dtestdx + dphidy*dtestdy);//(grad u,grad phi)
double phit = (1.+(1.-k_)*u)*gs2*(phi-phiold)/dt_*test;
double dgdtheta = cummins::dgs2_2dtheta_cummins_(theta_, M_, eps_, 0.);
double dgdpsi = 0.;
double curlgrad = dgdtheta*(-dphidy*dtestdx + dphidx*dtestdy);
double gp1 = -(phi - phi*phi*phi);
double phidel2 = gp1*test;
double x = basis[0].xx;
//double t = t0 + G*(x-R*time);
//double t_scale = (t-ts)/dt0;
double t_scale = tscale_(x,time);
double hp1 = lambda*(1. - phi*phi)*(1. - phi*phi)*(u+t_scale);
double phidel = hp1*test;
//phidel = 0.;
double rhs = divgradphi + curlgrad + phidel2 + phidel;
// dphidx = basis[1].duolddx;
// dphidy = basis[1].duolddy;
// theta_ = theta(dphidx,dphidy);
// gs2 = gs2_cummins_(theta_, M_, eps_,0.);
// divgradphi = gs2*dphidx*dtestdx + gs2*dphidy*dtestdy;//(grad u,grad phi)
// dgdtheta = dgs2_2dtheta_cummins_(theta_, M_, eps_, 0.);
// curlgrad = dgdtheta*(-dphidy*dtestdx + dphidx*dtestdy);
// gp1 = -(phiold-phiold*phiold*phiold);
// phidel2 = gp1*test;
// hp1 = lambda*(1.-phiold*phiold)*(1.-phiold*phiold)*(uold+t_scale);
// phidel = hp1*test;
// double rhs_old = divgradphi + curlgrad + phidel2 + phidel;
return phit + t_theta_*rhs;// + (1.-t_theta_)*rhs_old*0.;
}
RES_FUNC(residual_conc_farzadi_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double phi = basis[1].uu;
double phiold = basis[1].uuold;
double dphidx = basis[1].dudx;
double dphidy = basis[1].dudy;
double ut = (1.+k_)/2.*(u-uold)/dt_*test;
//ut = (u-uold)/dt_*test;
double divgradu = D*(1.-phi)/2.*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy);//(grad u,grad phi)
//divgradu = (basis[0].dudx*dtestdx + basis[0].dudy*dtestdy);
double divgradu_old = D*(1.-phiold)/2*(basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy);//(grad u,grad phi)
//j is antitrapping current
// j grad test here... j1*dtestdx + j2*dtestdy
// what if dphidx*dphidx + dphidy*dphidy = 0?
double norm = sqrt(dphidx*dphidx + dphidy*dphidy);
double small = 1.e-12;
double j_coef = 0.;
if (small < norm) {
j_coef = (1.+(1.-k_)*u)/sqrt(8.)/norm*(phi-phiold)/dt_;
}
//j_coef = 0.;
double j1 = j_coef*dphidx;
double j2 = j_coef*dphidy;
double divj = j1*dtestdx + j2*dtestdy;
double dphiolddx = basis[1].duolddx;
double dphiolddy = basis[1].duolddy;
norm = sqrt(dphidx*dphidx + dphidy*dphidy);
j_coef = 0.;
if (small < norm) {
j_coef = (1.+(1.-k_)*uold)/sqrt(8.)/norm*(phiold-basis[1].uuoldold)/dt_;
}
j1 = j_coef*dphidx;
j2 = j_coef*dphidy;
j_coef = 0.;
double divj_old = j1 *dtestdx + j2 *dtestdy;
double h = phi*(1.+(1.-k_)*u);
double hold = phiold*(1. + (1.-k_)*uold);
//double phitu = -.5*(h-hold)/dt_*test;
double phitu = -.5*(phi-phiold)/dt_*(1.+(1.-k_)*u)*test;
//phitu = 1.*test;
// h = hold;
// hold = basis[1].uuoldold*(1. + (1.-k_)*basis[0].uuoldold);
// double phitu_old = -.5*(h-hold)/dt_*test;
//return ut*0. + t_theta_*(divgradu + divj*0.) + (1.-t_theta_)*(divgradu_old + divj_old)*0. + t_theta_*phitu*0. + (1.-t_theta_)*phitu_old*0.;
return ut + t_theta_*divgradu + t_theta_*divj + t_theta_*phitu;
}
PRE_FUNC(prec_phase_farzadi_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[1].phi[i];
double dphidx = basis[1].dudx;
double dphidy = basis[1].dudy;
double dphidz = basis[1].dudz;
double u = basis[0].uu;
double phi = basis[1].uu;
double theta_ = cummins::theta(dphidx,dphidy)-theta_0_;
double gs2 = cummins::gs2_cummins_(theta_, M_, eps_,0.);
double m = (1.+(1.-k_)*0.*u)*gs2;
double phit = m*(basis[1].phi[j])/dt_*test;
//phit = (basis[1].phi[j])*test;
double divgrad = gs2*dbasisdx * dtestdx + gs2*dbasisdy * dtestdy;// + gs2*dbasisdz * dtestdz;
//double dg2 = cummins::dgs2_2dtheta_cummins_(theta_, M_, eps_,0.);
//double curlgrad = dg2*(-dtestdx*dphidy + dtestdy*dphidx );
//double t1 = (-1.+3.*phi*phi)*basis[1].phi[j]*test;
//double t2 = -4.*lambda*(u + 0.)*(-phi+phi*phi*phi)*basis[1].phi[j]*test;
//return phit + t_theta_*(divgrad + 0.*curlgrad + 0.*t1 + 0.*t2);
return phit + t_theta_*(divgrad);
}
PRE_FUNC(prec_conc_farzadi_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = D*(1.-basis[1].uu)/2.*(dbasisdx * dtestdx + dbasisdy * dtestdy);
//double dphidx = basis[1].dudx;
//double dphidy = basis[1].dudy;
//double norm = sqrt(dphidx*dphidx + dphidy*dphidy);
//double small = 1.e-12;
//double phi = basis[1].uu;
//double phiold = basis[1].uuold;
//double j_coef = 0.;
//if (small < norm) {
// j_coef = (1.+(1.-k_)* basis[0].phi[j])/sqrt(8.)/norm*(phi-phiold)/dt_;
//}
////j_coef = 0.;
//double j1 = j_coef*dphidx;
//double j2 = j_coef*dphidy;
//double divj = j1*dtestdx + j2*dtestdy;
double u_t =(1.+k_)/2.*test * basis[0].phi[j]/dt_;
//double phitu = -.5*(1.-k_)*basis[0].phi[j]*test*(phi-phiold)/dt_;
//return u_t + t_theta_*(divgrad + 0.*divj + 0.*phitu);
return u_t + t_theta_*(divgrad);
}
PPR_FUNC(postproc_c_)
{
double uu = u[0];
double phi = u[1];
return -c_inf*(1.+k_-phi+k_*phi)*(-1.-uu+k_*uu)/2./k_;
}
PPR_FUNC(postproc_t_)
{
// x is in nondimensional space, tscale_ takes in nondimensional and converts to um
double x = xyz[0];
return tscale_(x,time);
}
}//namespace farzadi
namespace robin_steadystate
{
RES_FUNC(residual_robin_test_)
{
//1-D robin bc test problem, steady state
// -d^2 u/dx^2 + a^2 u = 0
// u(x=0) = 0; grad u = b(1-u) | x=1
// u[x;b,a]=b cosh ( ax)/[b cosh(a)+a sinh(a)]
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
//double uold = basis[0].uuold;
double a =10.;
double au = a*a*u*test;
double divgradu = (basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
//double divgradu_old = (basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return divgradu + au;
}
PRE_FUNC(prec_robin_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz;
double a =10.;
double u_t =test * a*a*basis[0].phi[j];
return u_t + t_theta_*divgrad;
}
NBC_FUNC(nbc_robin_test_)
{
double test = basis->phi[i];
double u = basis[0].uu;
double b =1.;
return b*(1.-u)*test;
}
}//namespace robin_steadystate
namespace robin
{
// http://ramanujan.math.trinity.edu/rdaileda/teach/s12/m3357/lectures/lecture_2_28_short.pdf
// 1-D robin bc test problem, time dependent
// Solve D[u, t] - c^2 D[u, x, x] == 0
// u(0,t) == 0
// D[u, x] /. x -> L == -kappa u(t,L)
// => du/dx + kappa u = g = 0
// u(x,t) = a E^(-mu^2 t) Sin[mu x]
// mu solution to: Tan[mu L] + mu/kappa == 0 && Pi/2 < mu < 3 Pi/2
const double mu = 2.028757838110434;
const double a = 10.;
const double c = 1.;
const double L = 1.;
const double kappa = 1.;
RES_FUNC(residual_robin_test_)
{
//1-D robin bc test problem,
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
//double a =10.;
double ut = (u-uold)/dt_*test;
double divgradu = c*c*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
//double divgradu_old = (basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return ut + divgradu;
}
PRE_FUNC(prec_robin_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = c*c*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
//double a =10.;
double u_t = (basis[0].phi[j])/dt_*test;
return u_t + t_theta_*divgrad;
}
NBC_FUNC(nbc_robin_test_)
{
double test = basis->phi[i];
double u = basis[0].uu;
//du/dn + kappa u = g = 0 on L
//(du,dv) - <du/dn,v> = (f,v)
//(du,dv) - <g - kappa u,v> = (f,v)
//(du,dv) - < - kappa u,v> = (f,v)
// ^^^^^^^^^^^^^^ return this
return (-kappa*u)*test;
}
INI_FUNC(init_robin_test_)
{
return a*sin(mu*x);
}
}//namespace robin
namespace liniso
{
RES_FUNC(residual_liniso_x_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
//double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
strain[2] = basis[2].dudz;
strain[3] = basis[0].dudy + basis[1].dudx;
strain[4] = basis[1].dudz + basis[2].dudy;
strain[5] = basis[0].dudz + basis[2].dudx;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
//stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
//stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
stress[3] = c3*strain[3];
//stress[4] = c3*strain[4];
stress[5] = c3*strain[5];
double divgradu = stress[0]*dtestdx + stress[3]*dtestdy + stress[5]*dtestdz;//(grad u,grad phi)
return divgradu;
}
RES_FUNC(residual_liniso_y_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
//double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
strain[2] = basis[2].dudz;
strain[3] = basis[0].dudy + basis[1].dudx;
strain[4] = basis[1].dudz + basis[2].dudy;
strain[5] = basis[0].dudz + basis[2].dudx;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
//stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
//stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
stress[3] = c3*strain[3];
stress[4] = c3*strain[4];
//stress[5] = c3*strain[5];
double divgradu = stress[1]*dtestdy + stress[3]*dtestdx + stress[4]*dtestdz;//(grad u,grad phi)
return divgradu;
}
RES_FUNC(residual_liniso_z_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
//double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
strain[2] = basis[2].dudz;
strain[3] = basis[0].dudy + basis[1].dudx;
strain[4] = basis[1].dudz + basis[2].dudy;
strain[5] = basis[0].dudz + basis[2].dudx;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
//stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
//stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
//stress[3] = c3*strain[3];
stress[4] = c3*strain[4];
stress[5] = c3*strain[5];
double divgradu = stress[2]*dtestdz + stress[4]*dtestdy + stress[5]*dtestdx;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_liniso_x_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//strain[0] = basis[0].dudx;
//strain[1] = basis[1].dudy;
//strain[2] = basis[2].dudz;
//strain[3] = basis[0].dudy + basis[1].dudx;
//strain[4] = basis[1].dudz + basis[2].dudy;
//strain[5] = basis[0].dudz + basis[2].dudx;
//strain[0] = dbasisdx;
//strain[1] = dbasisdy;
//strain[2] = dbasisdz;
//strain[3] = dbasisdy + dbasisdx;
//strain[4] = dbasisdz + dbasisdy;
//strain[5] = dbasisdz + dbasisdx;
strain[0] = dbasisdx;
strain[1] = 0;
strain[2] = 0;
strain[3] = 0 + dbasisdy;
strain[4] = 0;
strain[5] = dbasisdz + 0;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
//stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
//stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
stress[3] = c3*strain[3];
//stress[4] = c3*strain[4];
stress[5] = c3*strain[5];
double divgradu = stress[0]*dtestdx + stress[3]*dtestdy + stress[5]*dtestdz;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_liniso_y_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//strain[0] = basis[0].dudx;
//strain[1] = basis[1].dudy;
//strain[2] = basis[2].dudz;
//strain[3] = basis[0].dudy + basis[1].dudx;
//strain[4] = basis[1].dudz + basis[2].dudy;
//strain[5] = basis[0].dudz + basis[2].dudx;
//strain[0] = dbasisdx;
//strain[1] = dbasisdy;
//strain[2] = dbasisdz;
//strain[3] = dbasisdy + dbasisdx;
//strain[4] = dbasisdz + dbasisdy;
//strain[5] = dbasisdz + dbasisdx;
strain[0] = 0;
strain[1] = dbasisdy;
strain[2] = 0;
strain[3] = 0 + dbasisdx;
strain[4] = dbasisdz + 0;
strain[5] = 0 + 0;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
//stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
//stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
stress[3] = c3*strain[3];
stress[4] = c3*strain[4];
//stress[5] = c3*strain[5];
double divgradu = stress[1]*dtestdy + stress[3]*dtestdx + stress[4]*dtestdz;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_liniso_z_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double E = 1e6;
double nu = .3;
double strain[6], stress[6];//x,y,z,yx,zy,zx
//strain[0] = basis[0].dudx;
//strain[1] = basis[1].dudy;
//strain[2] = basis[2].dudz;
//strain[3] = basis[0].dudy + basis[1].dudx;
//strain[4] = basis[1].dudz + basis[2].dudy;
//strain[5] = basis[0].dudz + basis[2].dudx;
//strain[0] = dbasisdx;
//strain[1] = dbasisdy;
//strain[2] = dbasisdz;
//strain[3] = dbasisdy + dbasisdx;
//strain[4] = dbasisdz + dbasisdy;
//strain[5] = dbasisdz + dbasisdx;
strain[0] = 0;
strain[1] = 0;
strain[2] = dbasisdz;
strain[3] = 0 + 0;
strain[4] = 0 + dbasisdy;
strain[5] = 0 + dbasisdx;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
//stress[0] = c1*strain[0] + c2*strain[1] + c2*strain[2];
//stress[1] = c2*strain[0] + c1*strain[1] + c2*strain[2];
stress[2] = c2*strain[0] + c2*strain[1] + c1*strain[2];
//stress[3] = c3*strain[3];
stress[4] = c3*strain[4];
stress[5] = c3*strain[5];
double divgradu = stress[2]*dtestdz + stress[4]*dtestdy + stress[5]*dtestdx;//(grad u,grad phi)
return divgradu;
}
RES_FUNC(residual_linisobodyforce_y_test_)
{
//this is taken from a test that had E=2e11; nu=.3 and body force -1e10 in the y direction;
//we reuse the test case that has E=1e6 and scale the body force accordingly by 5e-6
//test function
double test = basis[0].phi[i];
double bf = -1.e10*5.e-6;
double divgradu = residual_liniso_y_test_(basis,i,dt_,dt_,t_theta_,t_theta_,time,eqn_id) + bf*test;
return divgradu;
}
RES_FUNC(residual_linisoheat_x_test_)
{
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double gradu = basis[3].dudx;
double c = 1.e-6;
double alpha = 1.e-4;;
double E = 1.;
double divgradu = c*residual_liniso_x_test_(basis,i,dt_,dt_,t_theta_,t_theta_,time,eqn_id) - alpha*E*gradu*dtestdx;
return divgradu;
}
RES_FUNC(residual_linisoheat_y_test_)
{
//test function
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double gradu = basis[3].dudy;
double c = 1.e-6;
double alpha = 1.e-4;
double E = 1.;
double divgradu = c*residual_liniso_y_test_(basis,i,dt_,dt_,t_theta_,t_theta_,time,eqn_id) - alpha*E*gradu*dtestdy;
return divgradu;
}
RES_FUNC(residual_linisoheat_z_test_)
{
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double gradu = basis[3].dudz;
double c = 1.e-6;
double alpha = 1.e-4;
double E = 1.;
double divgradu = c*residual_liniso_z_test_(basis,i,dt_,dt_,t_theta_,t_theta_,time,eqn_id) - alpha*E*gradu*dtestdz;
return divgradu;
}
RES_FUNC(residual_divgrad_test_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
//double test = basis[3].phi[i];
//u, phi
//double u = basis[0].uu;
//double uold = basis[0].uuold;
double divgradu = (basis[3].dudx*dtestdx + basis[3].dudy*dtestdy + basis[3].dudz*dtestdz);//(grad u,grad phi)
//double divgradu_old = (basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return divgradu;
}
}//namespace liniso
namespace uehara
{
double L = 3.e3;//J/m^3
double m = 2.5e5;
double a = 10.;//m^4
double rho = 1.e3;//kg/m^3
double c = 5.e2;//J/kg/K
double k = 150.;//W/m/K
//double k = 1.5;//W/m/K
double r0 = 29.55;
double giga = 1.e+9;
double E = 200.*giga;//GPa
//double E = 200.*1.e9;//Pa
double nu = .3;
//plane stress
double c0 = E/(1.-nu*nu);
double c1 = c0;
double c2 = c0*nu;
double c3 = c0*(1.-nu)/2.;//always confused about the 2 here
//plane strain
// double c0 = E/(1.+nu)/(1.-2.*nu);
// double c1 = c0*(1.-nu);
// double c2 = c0*nu;
// double c3 = c0*(1.-2.*nu)/2.;
double alpha = 5.e-6;//1/K
//double alpha = 0.;//1/K
double beta = 1.5e-3;
//double beta = 0.;
//double init_heat_(const double &x,
// const double &y,
// const double &z)
INI_FUNC(init_heat_)
{
double val = 400.;
return val;
}
INI_FUNC(init_phase_)
{
//this is not exactly symmetric on the fine mesh
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = phi_sol_ ;
double dx = 1.e-2;
double r = r0*dx;
double r1 = (r0-1)*dx;
//if(y > r){
if( (x > r1 && y > r) ||(x > r && y > r1) ){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
INI_FUNC(init_phase_c_)
{
//this is not exactly symmetric on the fine mesh
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = phi_sol_ ;
double dx = 1.e-2;
double r = r0*dx;
double rr = sqrt(x*x+y*y);
//if(y > r){
if( rr > r0*sqrt(2.)*dx ){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
INI_FUNC(init_heat_seed_)
{
//this is not exactly symmetric on the fine mesh
double phi_sol_ = 300.;
double phi_liq_ = 400.;
double val = phi_sol_ ;
double dx = 1.e-2;
double r = r0*dx;
double r1 = (r0-1)*dx;
//if(y > r){
if( (x > r1 && y > r) ||(x > r && y > r1) ){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
INI_FUNC(init_heat_seed_c_)
{
//this is not exactly symmetric on the fine mesh
double phi_sol_ = 300.;
double phi_liq_ = 400.;
double val = phi_sol_ ;
double dx = 1.e-2;
double r = r0*dx;
double r1 = (r0-1)*dx;
double rr = sqrt(x*x+y*y);
//if(y > r){
if( rr > r0*sqrt(2.)*dx ){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
DBC_FUNC(dbc_)
{
return 300.;
}
double conv_bc_(const Basis *basis,
const int &i,
const double &dt_,
const double &t_theta_,
const double &time)
{
double test = basis->phi[i];
double u = basis->uu;
double uw = 300.;//K
double h =1.e4;//W/m^2/K
return h*(uw-u)*test/rho/c;
}
NBC_FUNC(nbc_stress_)
{
double test = basis->phi[i];
return -alpha*300.*test;
}
RES_FUNC(residual_phase_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double phi = basis[0].uu;
double phiold = basis[0].uuold;
double u = basis[1].uu;
//double uold = basis[1].uuold;
double dphidx = basis[0].dudx;
double dphidy = basis[0].dudy;
double dphidz = basis[0].dudz;
double b = 5.e-5;//m^3/J
//b = 5.e-7;//m^3/J
double f = 0.;
double um = 400.;//K
double phit = m*(phi-phiold)/dt_*test;
double divgradphi = a*(dphidx*dtestdx + dphidy*dtestdy + dphidz*dtestdz);//(grad u,grad test)
//double M = b*phi*(1. - phi)*(L*(um - u)/um + f);
double M = .66*150000000.*b*phi*(1. - phi)*(L*(um - u)/um + f);
//double g = -phi*(1. - phi)*(phi - .5 + M)*test;
double g = -(phi*(1. - phi)*(phi - .5)+phi*(1. - phi)*M)*test;
double rhs = divgradphi + g;
return (phit + rhs)/m;
}
RES_FUNC(residual_stress_x_dt_)
{
double strain[3];//x,y,yx
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_;
double stress = c1*strain[0] + c2*strain[1];
return stress;
}
RES_FUNC(residual_stress_y_dt_)
{
double strain[3];//x,y,z,yx,zy,zx
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_;
double stress = c2*strain[0] + c1*strain[1];
return stress;
}
RES_FUNC(residual_heat_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[1].phi[i];
//u, phi
double phi = basis[0].uu;
double phiold = basis[0].uuold;
double phioldold = basis[0].uuoldold;
double u = basis[1].uu;
double uold = basis[1].uuold;
double dudx = basis[1].dudx;
double dudy = basis[1].dudy;
//double dudz = basis[1].dudz;
double ut = rho*c*(u-uold)/dt_*test;
double divgradu = k*(dudx*dtestdx + dudy*dtestdy);
//double phitu = -30.*L*phi*phi*(1.-phi)*(1.-phi)*(phi-phioldold)/2./dt_*test;
double h = phi*phi*(1.-phi)*(1.-phi);
double phitu = -30.*L*h*(phi-phiold)/dt_*test;
//thermal term
double stress = test*alpha*u*(residual_stress_x_dt_(basis,
i, dt_, dt_, t_theta_,t_theta_,
time, eqn_id)
+residual_stress_y_dt_(basis,
i, dt_, dt_, t_theta_,t_theta_,
time, eqn_id));
double rhs = divgradu + phitu + stress;
return (ut + rhs)/rho/c;
}
RES_FUNC(residual_liniso_x_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,yx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//test function
double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
//double ut = (basis[1].uu - basis[1].uuoldold)/dt_/2;//thermal strain
double ut = (basis[1].uu - basis[1].uuold)/dt_;//thermal strain
double phi = basis[0].uu;
double h = phi*phi*(1.-phi)*(1.-phi);
//double hp = 2.*(1.-phi)*(1.-phi)*phi-2.*(1.-phi)*phi*phi;//2 (1 - x)^2 x - 2 (1 - x) x^2
// h' p_t p_x +h p_t_x
double strain_phi = 30.*beta*h*(phi-basis[0].uuold)/dt_;
// double strain_phi = 0.*2.*30.*beta*(c1+c2)*(hp*(phi-basis[0].uuold)/dt_*basis[0].dudx
// +h*(basis[0].dudx-basis[0].duolddx)/dt_
// )*test;
double ff = alpha*ut + strain_phi;
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_- ff;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_- ff;
strain[2] = (basis[2].dudy-basis[2].duolddy + basis[3].dudx-basis[3].duolddx)/dt_;// - alpha*ut - strain_phi;
stress[0] = c1*strain[0] + c2*strain[1];
// stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = (stress[0]*dtestdx + stress[2]*dtestdy)/E;//(grad u,grad phi)
//std::cout<<"residual_liniso_x_test_"<<std::endl;
return divgradu;
}
RES_FUNC(residual_liniso_y_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,z,yx,zy,zx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
//strain[0] = basis[2].dudx;
//strain[1] = basis[3].dudy;
//strain[2] = basis[2].dudy + basis[3].dudx;
//double ut = (basis[1].uu - basis[1].uuoldold)/dt_/2.;//thermal strain
double ut = (basis[1].uu - basis[1].uuold)/dt_;//thermal strain
double phi = basis[0].uu;
double h = phi*phi*(1.-phi)*(1.-phi);
//double hp = 2.*(1.-phi)*(1.-phi)*phi-2.*(1.-phi)*phi*phi;//2 (1 - x)^2 x - 2 (1 - x) x^2
double strain_phi = 30.*beta*h*(phi-basis[0].uuold)/dt_;
// double strain_phi = 0.*2.*30.*beta*(c1+c2)*(hp*(phi-basis[0].uuold)/dt_*basis[0].dudy
// +h*(basis[0].dudy-basis[0].duolddy)/dt_
// )*test;
double ff = alpha*ut + strain_phi;
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_- ff;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_- ff;
strain[2] = (basis[2].dudy-basis[2].duolddy + basis[3].dudx-basis[3].duolddx)/dt_;// - alpha*ut - strain_phi;
//stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = (stress[1]*dtestdy + stress[2]*dtestdx)/E;//(grad u,grad phi)
//std::cout<<"residual_liniso_y_test_"<<std::endl;
return divgradu;
}
RES_FUNC(residual_stress_x_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double phi = basis[0].uu;
double h = phi*phi*(1.-phi)*(1.-phi);
double phit = (phi - basis[0].uuold)/dt_;
double ut = (basis[1].uu - basis[1].uuold)/dt_;
double strain[2];
double stress = (basis[4].uu - basis[4].uuold)/dt_;//x,y,yx
//test function
double test = basis[0].phi[i];
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_- alpha*ut - 30.*h*phit;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_- alpha*ut - 30.*h*phit;
double sx = c1*strain[0] + c2*strain[1];
//std::cout<<strain[0]<<" "<<strain[1]<<" "<<sx<<" "<<stress - sx<<" "<<(stress - sx)*test<<" "<<(stress - sx)*test/E<<std::endl;
return (stress - sx)*test*dt_/E;
}
RES_FUNC(residual_stress_y_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double phi = basis[0].uu;
double h = phi*phi*(1.-phi)*(1.-phi);
double phit = (phi - basis[0].uuold)/dt_;
double ut = (basis[1].uu - basis[1].uuold)/dt_;
double strain[2];
double stress = (basis[5].uu - basis[5].uuold)/dt_;//x,y,yx
//test function
double test = basis[0].phi[i];
strain[0] = (basis[2].dudx-basis[2].duolddx)/dt_- alpha*ut - 30.*h*phit;
strain[1] = (basis[3].dudy-basis[3].duolddy)/dt_- alpha*ut - 30.*h*phit;
double sy = c2*strain[0] + c1*strain[1];
return (stress - sy)*test*dt_/E;//(grad u,grad phi)
}
RES_FUNC(residual_stress_xy_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
//double strain[2];
double stress = (basis[6].uu - basis[6].uuold)/dt_;
double test = basis[0].phi[i];
//strain[0] = basis[0].dudx;
//strain[1] = basis[1].dudy;
double strain = (basis[2].dudy-basis[2].duolddy + basis[3].dudx-basis[3].duolddx)/dt_;
//stress[0] = c1*strain[0] + c2*strain[1];
//stress[1] = c2*strain[0] + c1*strain[1];
double sxy = c3*strain;
return (stress - sxy)*test*dt_/E;//(grad u,grad phi)
}
PRE_FUNC(prec_phase_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double phit = m*(basis[0].phi[j])/dt_*test;
double divgrad = a*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
return (phit + t_theta_*divgrad)/m;
}
PRE_FUNC(prec_heat_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double stress = test*alpha*basis[1].phi[j]*(residual_stress_x_dt_(basis,
i, dt_, dt_, t_theta_,t_theta_,
0.,0)
+residual_stress_y_dt_(basis,
i, dt_, dt_, t_theta_,t_theta_,
0.,0));
double divgrad = k*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
double u_t =rho*c*basis[1].phi[j]/dt_*test;
return (u_t + t_theta_*divgrad + stress)/rho/c;
}
PRE_FUNC(prec_liniso_x_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double strain[3], stress[3];//x,y,z,yx,zy,zx
strain[0] = dbasisdx;
strain[1] = dbasisdy;
strain[2] = (dbasisdy + dbasisdx);
stress[0] = c1*strain[0] + c2*strain[1];
//stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = (stress[0]*dtestdx + stress[2]*dtestdy)/E/dt_;//(grad u,grad phi)
//double divgradu = (stress[0]*dtestdx + stress[2]*dtestdy)/E;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_liniso_y_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double strain[3], stress[3];//x,y,z,yx,zy,zx
strain[0] = dbasisdx;
strain[1] = dbasisdy;
strain[2] = (dbasisdy + dbasisdx);
//stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = (stress[1]*dtestdy + stress[2]*dtestdx)/E/dt_;//(grad u,grad phi)
//double divgradu = (stress[1]*dtestdy + stress[2]*dtestdx)/E;//(grad u,grad phi)
//std::cout<<divgradu<<std::endl;
return divgradu;
}
PRE_FUNC(prec_stress_test_)
{
double test = basis[0].phi[i];
return test * basis[0].phi[j]/dt_*dt_/E;
}
PPR_FUNC(postproc_stress_x_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[2];//x,y,z,yx,zy,zx
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
// strain[0] = gradu[0] - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
// strain[1] = gradu[3] - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
strain[0] = gradu[0] - alpha*u[1];// - 30.*beta*h*phi;//var 0 dx
strain[1] = gradu[4] - alpha*u[1];// - 30.*beta*h*phi;//var 1 dy
return c1*strain[0] + c2*strain[1];
}
PPR_FUNC(postproc_stress_xd_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[2];//x,y,z,yx,zy,zx
// double phi = u[0];
// if(phi < 0.) phi = 0.;
// if(phi > 1.) phi = 1.;
// double h = phi*phi*(1.-phi)*(1.-phi);
// strain[0] = gradu[0] - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
// strain[1] = gradu[3] - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
strain[0] = gradu[0];//var 0 dx
strain[1] = gradu[4];//var 1 dy
return c1*strain[0] + c2*strain[1];
}
PPR_FUNC(postproc_stress_y_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[2];//x,y,z,yx,zy,zx
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
// strain[0] = gradu[0] - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
// strain[1] = gradu[3] - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
strain[0] = gradu[0] - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
strain[1] = gradu[4] - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
return c2*strain[0] + c1*strain[1];
}
PPR_FUNC(postproc_stress_xy_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
double strain = gradu[1] + gradu[3] - alpha*u[1] - 30.*beta*h*phi;
return c3*strain;
}
PPR_FUNC(postproc_stress_eq_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[3], stress[3];//x,y,z,yx,zy,zx
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
strain[0] = gradu[0] - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
strain[1] = gradu[4] - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
strain[2] = gradu[1] + gradu[3];// - alpha*u[1] - 30.*beta*h*phi;
stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
// return sqrt(((stress[0]-stress[1])*(stress[0]-stress[1])
// + stress[0]*stress[0]
// + stress[1]*stress[1]
// + 6. *stress[2]*stress[2]
// )/2.);
return sqrt((stress[0]-stress[1])*(stress[0]-stress[1])
+ 3.*stress[2]*stress[2]
);
}
PPR_FUNC(postproc_stress_eqd_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[3], stress[3];//x,y,z,yx,zy,zx
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
strain[0] = gradu[0];// - alpha*u[1] - 30.*beta*h*phi;//var 0 dx
strain[1] = gradu[4];// - alpha*u[1] - 30.*beta*h*phi;//var 1 dy
strain[2] = gradu[1] + gradu[3];// + gradu[2];// - alpha*u[1] - 30.*beta*h*phi;
stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
// return sqrt(((stress[0]-stress[1])*(stress[0]-stress[1])
// + stress[0]*stress[0]
// + stress[1]*stress[1]
// + 6. *stress[2]*stress[2]
// )/2.);
return sqrt((stress[0]-stress[1])*(stress[0]-stress[1])
+ 3.*stress[2]*stress[2]
);
// return (stress[0]+stress[1])/2.
// +sqrt((stress[0]-stress[1])*(stress[0]-stress[1])/4.+stress[3]*stress[3]);
}
PPR_FUNC(postproc_phi_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double phi = u[0];
if(phi < 0.) phi = 0.;
if(phi > 1.) phi = 1.;
return phi;
}
PPR_FUNC(postproc_strain_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double phi = u[0];
double uu = u[1];
// if(phi < 0.) phi = 0.;
// if(phi > 1.) phi = 1.;
double h = phi*phi*(1.-phi)*(1.-phi);
return alpha*uu;// + 30.*beta*h*phi;
}
}//namespace uehara
namespace uehara2
{
INI_FUNC(init_phase_c_)
{
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = phi_sol_ ;
double r0 = uehara::r0;
double dx = 1.e-2;
double x0 = 15.*dx;
double r = .9*r0*dx/2.;
double rr = sqrt((x-x0)*(x-x0)+(y-x0)*(y-x0));
val=phi_liq_;
if( rr > r0*sqrt(2.)*dx/2. ){
val=phi_sol_;
}
else {
val=phi_liq_;
}
return val;
}
INI_FUNC(init_heat_)
{
double val = 300.;
return val;
}
RES_FUNC(residual_heat_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[1].phi[i];
//u, phi
double phi = basis[0].uu;
double phiold = basis[0].uuold;
double phioldold = basis[0].uuoldold;
double u = basis[1].uu;
double uold = basis[1].uuold;
double dudx = basis[1].dudx;
double dudy = basis[1].dudy;
//double dudz = basis[1].dudz;
double ut = uehara::rho*uehara::c*(u-uold)/dt_*test;
double divgradu = uehara::k*(dudx*dtestdx + dudy*dtestdy);
double h = phi*phi*(1.-phi)*(1.-phi);
//double phitu = -30.*1e12*uehara::L*h*(phi-phioldold)/2./dt_*test;
double phitu = -30.*uehara::L*h*(phi-phiold)/dt_*test;
//thermal term
double stress = test*uehara::alpha*u*(uehara::residual_stress_x_dt_(basis,
i, dt_, dt_, t_theta_, t_theta_,
time, eqn_id)
+uehara::residual_stress_y_dt_(basis,
i, dt_, dt_,t_theta_,t_theta_,
time, eqn_id));
double rhs = divgradu + phitu + stress;
return (ut + rhs)/uehara::rho/uehara::c;
}
}//namespace uehara2
namespace coupledstress
{
double E = 1e6;
double nu = .3;
//plane stress
// double c = E/(1.-nu*nu);
// double c1 = c;
// double c2 = c*nu;
// double c3 = c*(1.-nu)/2.;//always confused about the 2 here
//plane strain
double c = E/(1.+nu)/(1.-2.*nu);
double c1 = c*(1.-nu);
double c2 = c*nu;
double c3 = c*(1.-2.*nu)/2.;
RES_FUNC(residual_liniso_x_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,yx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//test function
//double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
strain[2] = basis[0].dudy + basis[1].dudx;
stress[0] = c1*strain[0] + c2*strain[1];
// stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = stress[0]*dtestdx + stress[2]*dtestdy;//(grad u,grad phi)
//std::cout<<"residual_liniso_x_test_"<<std::endl;
return divgradu;
}
RES_FUNC(residual_liniso_y_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,z,yx,zy,zx
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
strain[2] = basis[0].dudy + basis[1].dudx;
stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = stress[1]*dtestdy + stress[2]*dtestdx;//(grad u,grad phi)
//std::cout<<"residual_liniso_y_test_"<<std::endl;
return divgradu;
}
RES_FUNC(residual_stress_x_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,yx
//test function
double test = basis[0].phi[i];
//u, phi
double sx = basis[2].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
//strain[2] = basis[0].dudy + basis[1].dudx;
stress[0] = c1*strain[0] + c2*strain[1];
// stress[1] = c2*strain[0] + c1*strain[1];
//stress[2] = c3*strain[2];
return (sx - stress[0])*test;
}
RES_FUNC(residual_stress_y_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,z,yx,zy,zx
double test = basis[0].phi[i];
//u, phi
double sy = basis[3].uu;
strain[0] = basis[0].dudx;
strain[1] = basis[1].dudy;
//strain[2] = basis[0].dudy + basis[1].dudx;
//stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
//stress[2] = c3*strain[2];
return (sy - stress[1])*test;//(grad u,grad phi)
}
RES_FUNC(residual_stress_xy_test_)
{
//3-D isotropic x-displacement based solid mech, steady state
//strong form: sigma = stress eps = strain
// d^T sigma = d^T B D eps == 0
double strain[3], stress[3];//x,y,z,yx,zy,zx
double test = basis[0].phi[i];
//u, phi
double sxy = basis[4].uu;
//strain[0] = basis[0].dudx;
//strain[1] = basis[1].dudy;
strain[2] = basis[0].dudy + basis[1].dudx;
//stress[0] = c1*strain[0] + c2*strain[1];
//stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
return (sxy - stress[2])*test;//(grad u,grad phi)
}
PRE_FUNC(prec_liniso_x_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double strain[3], stress[3];//x,y,z,yx,zy,zx
strain[0] = dbasisdx;
strain[1] = dbasisdy;
strain[2] = dbasisdy + dbasisdx;
stress[0] = c1*strain[0] + c2*strain[1];
//stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = stress[0]*dtestdx + stress[2]*dtestdy;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_liniso_y_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double strain[3], stress[3];//x,y,z,yx,zy,zx
strain[0] = dbasisdx;
strain[1] = dbasisdy;
strain[2] = dbasisdy + dbasisdx;
//stress[0] = c1*strain[0] + c2*strain[1];
stress[1] = c2*strain[0] + c1*strain[1];
stress[2] = c3*strain[2];
double divgradu = stress[1]*dtestdy + stress[2]*dtestdx;//(grad u,grad phi)
return divgradu;
}
PRE_FUNC(prec_stress_test_)
{
double test = basis[0].phi[i];
return test * basis[0].phi[j];
}
PPR_FUNC(postproc_stress_x_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[2];//x,y,z,yx,zy,zx
strain[0] = gradu[0];//var 0 dx
strain[1] = gradu[4];//var 1 dy
return c1*strain[0] + c2*strain[1];
}
PPR_FUNC(postproc_stress_y_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain[2];//x,y,z,yx,zy,zx
strain[0] = gradu[0];//var 0 dx
strain[1] = gradu[4];//var 1 dy
return c2*strain[0] + c1*strain[1];
}
PPR_FUNC(postproc_stress_xy_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double strain = gradu[1] + gradu[3];
return c3*strain;
}
}//namespace coupledstress
namespace laplace
{
RES_FUNC(residual_heat_test_)
{
//u[x,y,t]=exp(-2 pi^2 t)sin(pi x)sin(pi y)
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
//double uold = basis[0].uuold;
//double ut = (u-uold)/dt_*test;
double divgradu = (basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
//double divgradu_old = (basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return divgradu - 8.*test;
}
}//namespace laplace
namespace cahnhilliard
{
//https://www.sciencedirect.com/science/article/pii/S0021999112007243
double M = 1.;
double Eps = 1.;
double alpha = 1.;//alpha >= 1
double pi = 3.141592653589793;
double fcoef_ = 0.;
double F(const double &x,const double &t)
{
// Sin(a*Pi*x)
// - M*(Power(a,2)*Power(Pi,2)*(1 + t)*Sin(a*Pi*x) - Power(a,4)*Ep*Power(Pi,4)*(1 + t)*Sin(a*Pi*x) +
// 6*Power(a,2)*Power(Pi,2)*Power(1 + t,3)*Power(Cos(a*Pi*x),2)*Sin(a*Pi*x) -
// 3*Power(a,2)*Power(Pi,2)*Power(1 + t,3)*Power(Sin(a*Pi*x),3))
double a = alpha;
return sin(a*pi*x)
- M*(std::pow(a,2)*std::pow(pi,2)*(1 + t)*sin(a*pi*x) - std::pow(a,4)*Eps*std::pow(pi,4)*(1 + t)*sin(a*pi*x) +
6*std::pow(a,2)*std::pow(pi,2)*std::pow(1 + t,3)*std::pow(cos(a*pi*x),2)*sin(a*pi*x) -
3*std::pow(a,2)*std::pow(pi,2)*std::pow(1 + t,3)*std::pow(sin(a*pi*x),3));
}
double fp(const double &u)
{
return u*u*u - u;
}
INI_FUNC(init_c_)
{
return sin(alpha*pi*x);
}
INI_FUNC(init_mu_)
{
//-Sin[a \[Pi] x] + a^2 \[Pi]^2 Sin[a \[Pi] x] + Sin[a \[Pi] x]^3
return -sin(alpha*pi*x) + alpha*alpha*pi*pi*sin(alpha*pi*x) + sin(alpha*pi*x)*sin(alpha*pi*x)*sin(alpha*pi*x);
}
RES_FUNC(residual_c_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
double c = basis[0].uu;
double cold = basis[0].uuold;
double mu = basis[1].uu;
double x = basis[0].xx;
double ct = (c - cold)/dt_*test;
double divgradmu = M*t_theta_*(basis[1].dudx*dtestdx + basis[1].dudy*dtestdy + basis[1].dudz*dtestdz)
+ M*(1.-t_theta_)*(basis[1].duolddx*dtestdx + basis[1].duolddy*dtestdy + basis[1].duolddz*dtestdz);
double f = t_theta_*fcoef_*F(x,time)*test + (1.-t_theta_)*fcoef_*F(x,time-dt_)*test;
return ct + divgradmu - f;
}
RES_FUNC(residual_mu_)
{
//derivatives of the test function
double dtestdx = basis[1].dphidxi[i]*basis[1].dxidx
+basis[1].dphideta[i]*basis[1].detadx
+basis[1].dphidzta[i]*basis[1].dztadx;
double dtestdy = basis[1].dphidxi[i]*basis[1].dxidy
+basis[1].dphideta[i]*basis[1].detady
+basis[1].dphidzta[i]*basis[1].dztady;
double dtestdz = basis[1].dphidxi[i]*basis[1].dxidz
+basis[1].dphideta[i]*basis[1].detadz
+basis[1].dphidzta[i]*basis[1].dztadz;
//test function
double test = basis[1].phi[i];
double c = basis[0].uu;
double mu = basis[1].uu;
double mut = mu*test;
double f = fp(c)*test;
double divgradc = Eps*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);
return mut - f - divgradc;
}
PARAM_FUNC(param_)
{
fcoef_ = plist->get<double>("fcoef");
}
}//namespace cahnhilliard
namespace quaternion
{
//see
//[1] LLNL-JRNL-409478 A Numerical Algorithm for the Solution of a Phase-Field Model of Polycrystalline Materials
//M. R. Dorr, J.-L. Fattebert, M. E. Wickett, J. F. Belak, P. E. A. Turchi (2008)
//[2] LLNL-JRNL-636233 Phase-field modeling of coring during solidification of Au-Ni alloy using quaternions and CALPHAD input
//J. L. Fattebert, M. E. Wickett, P. E. A. Turchi May 7, 2013
const double M = 10.;
const double H = 1.;
const double T = 1.;
const double D = 2.*H*T;
const double eps = .02;
const int N = 4;
void PI(const double *q, double *v){
double norm2 = 0.;
double dot = 0.;
for(int k = 0; k < N; k++){
norm2 = norm2 + q[k]*q[k];
dot = dot +q[k]*v[k];
}
for(int k = 0; k < N; k++){
v[k] = q[k]*dot/norm2;
}
}
void PIT(const double *q, double *v){
double norm2 = 0.;
double dot = 0.;
for(int k = 0; k < N; k++){
norm2 = norm2 + q[k]*q[k];
dot = dot +q[k]*v[k];
}
for(int k = 0; k < N; k++){
v[k] = v[k]-q[k]*dot/norm2;
}
}
//double pi = 3.141592653589793;
PARAM_FUNC(param_)
{
}
double dist(const double &x, const double &y, const double &z,
const double &x0, const double &y0, const double &z0,
const double &r)
{
const double c = (x-x0)*(x-x0) + (y-y0)*(y-y0) + (z-z0)*(z-z0);
return r-sqrt(c);
}
INI_FUNC(init_)
{
//return .001*r(x,eqn_id)*r(x,N-eqn_id)*(y,eqn_id)*r(y,N-eqn_id);
// srand((int)(1000*x));
// return ((rand() % 100)/50.-1.)*.001;
const double r = .1;
const double x0 = .5;
const double y0 = .5;
const double w = .1;//.025;
//g1 is the background grain
//g0 is black??
const double g0[4] = {-0.707106781186547,
-0.000000000000000,
0.707106781186548,
-0.000000000000000};
const double g1[4] = {0.460849109679818,
0.025097870693789,
0.596761014095944,
0.656402686655941};
const double g2[4] = {0.514408948531741,
0.574286304520035,
0.563215252388157,
0.297266300795322};
const double g3[4] = {0.389320954032683,
0.445278323410822,
0.064316533986652,
0.803753564786790};
const double scale = (g3[eqn_id]-g1[eqn_id])/2.;
const double shift = (g3[eqn_id]+g1[eqn_id])/2.;
double d = dist(x,y,z,x0,y0,0,r);
double val = shift + scale*tanh(d/sqrt(2.)/w);
return val;
}
RES_FUNC(residual_)
{
//derivatives of the test function
const double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
const double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
const double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
const double test = basis[0].phi[i];
const double u = basis[eqn_id].uu;
const double uold = basis[eqn_id].uuold;
double norm2 = 0.;
double normgrad = 0.;
double sumk = 0.;
for(int k = 0; k < N; k++){
norm2 = norm2 + basis[k].uu*basis[k].uu;
normgrad = normgrad + basis[k].dudx*basis[k].dudx + basis[k].dudy*basis[k].dudy + basis[k].dudz*basis[k].dudz;
sumk = sumk + basis[k].uu*(basis[k].dudx*dtestdx + basis[k].dudy*dtestdy + basis[k].dudz*dtestdz);
}
normgrad = sqrt(normgrad);
const double c = ((normgrad > .0001) ? eps+D/normgrad : eps);
sumk = -sumk*basis[eqn_id].uu*c/norm2;
const double divgradu = c*(basis[eqn_id].dudx*dtestdx + basis[eqn_id].dudy*dtestdy + basis[eqn_id].dudz*dtestdz);
return (u-uold)/dt_*test + M*(divgradu + sumk);
}
PRE_FUNC(prec_)
{
return 1;
}
PPR_FUNC(postproc_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double s =0.;
for(int j = 0; j < N; j++){
s = s + u[j]*u[j];
}
return s;
}
}//namespace quaternion
namespace grain
{
//see
//[1] Suwa et al, Mater. T. JIM., 44,11, (2003);
//[2] Krill et al, Acta Mater., 50,12, (2002);
double L = 1.;
double alpha = 1.;
double beta = 1.;
double gamma = 1.;
double kappa = 2.;
int N = 6;
double pi = 3.141592653589793;
double r(const double &x,const int &n){
return sin(64./512.*x*n*pi);
}
PARAM_FUNC(param_)
{
N = plist->get<int>("numgrain");
}
INI_FUNC(init_)
{
//return .001*r(x,eqn_id)*r(x,N-eqn_id)*(y,eqn_id)*r(y,N-eqn_id);
return ((rand() % 100)/50.-1.)*.001;
}
RES_FUNC(residual_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double test = basis[0].phi[i];
double u = basis[eqn_id].uu;
double uold = basis[eqn_id].uuold;
double divgradu = kappa*(basis[eqn_id].dudx*dtestdx + basis[eqn_id].dudy*dtestdy + basis[eqn_id].dudz*dtestdz);
double s = 0.;
for(int k = 0; k < N; k++){
s = s + basis[k].uu*basis[k].uu;
}
s = s - u*u;
return (u-uold)/dt_*test + L* ((-alpha*u + beta*u*u*u +2.*gamma*u*s)*test + divgradu);
}
PRE_FUNC(prec_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double u = basis[eqn_id].uu;
double test = basis[0].phi[i];
double divgrad = L*kappa*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
double u_t =test * basis[0].phi[j]/dt_;
double alphau = -test*L*alpha*basis[0].phi[j];
double betau = 3.*u*u*basis[0].phi[j]*test*L*beta;
double s = 0.;
for(int k = 0; k < N; k++){
s = s + basis[k].uu*basis[k].uu;
}
s = s - u*u;
double gammau = 2.*gamma*L*basis[0].phi[j]*s*test;
return u_t + divgrad + betau + gammau;// + alphau ;
}
PPR_FUNC(postproc_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double s =0.;
for(int j = 0; j < N; j++){
s = s + u[j]*u[j];
}
return s;
}
}//namespace grain
namespace periodic
{
RES_FUNC(residual_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double test = basis[0].phi[i];
double u = basis[0].uu;
double uold = basis[0].uuold;
double x = basis[0].xx;
double f = sin(11.*x);
double divgradu = basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz;
return (u-uold)/dt_*test + divgradu - f*test;
}
}//namespace periodic
namespace kundin
{
//double vf = 1e5;// J/mol-at / J/m^3
//double lf = 1.;//m/m length conversion
double lf = 1000.;//mm/m length conversion
double lf2 = lf*lf;
double lf3 = lf2*lf;
double W = 0.00000007*lf;//m
double dx = 0.000000032*lf; //m
double lx = dx*320.; //m
int N = 6;
double a_1 = sqrt(2.)/3.;
double a_2 = 1.175;
double sigma = 0.12/lf2;//J/m^2
double eps_4 = .05;
//is this the correct conversion? the paper is confusing
double x_fact = (1.e5)/lf3;// (J/mol-at/mf) should convert J/mol-at to J/m^3
double XA_L [6] = { 1.2*x_fact, 1.3*x_fact, .9*x_fact, 3.*x_fact, 3.*x_fact, 3.*x_fact };//J/mol-at/mf^2
double deltaA_SLT0 [6] = {.01645, .034356, -.0098313, -.0412, -.00545, .00005};//mf
double CAeq_ST0 [6] = {.20645, .219356, .0201687, .0098, .00355, .00505};//mf
double CAeq_LT0 [6] = {.19, .185, .03, .051, .009, .005};//mf
double kA_L [6] = {3.48, 1.48, 1.48, 2.48, 1.51, 11.21};
double mA_Sp [6] = {9118., 4365.8, -15257.4, -3640.8,-27522.9, 3700000.};//K/mf
double mA_Lp [6] = {2620., 2936., -10309., -1468.7,-18131.3, 330000.};//K/mf
double T0 = 1635.15;//K
//double T0 = 1243.;//K
//double T0 = 1362.;//C
double d_fact = (1.e-10)*lf2;
double DA_L [6] = {8.9843*d_fact, 9.0398*d_fact, 10.759*d_fact, 10.526*d_fact, 10.992*d_fact, 11.092*d_fact};//m^2/s
double q_fact = (1.e5)*lf;
double QA_L [6] = {5.615*q_fact,20.3*q_fact, .967*q_fact, 68.9*q_fact, .977*q_fact, .000123*q_fact};//(J/mol-at)/(J/m^3) s/m^2
double tau = 8.12e-8;//s
double Tdot [4] = {28745.6, 14372.8, 7186.39,3593.2};//K/s
//double lambda = 18.3;//J/(s m K) keep as meters
double a = 4.7e-6 * lf2;//m^2/s
//douple pi = 3.14159;
double df(const double p)
{
return 2.* (1. - p)*(1. - p)*p - 2.* (1. - p)*p*p;
}
double dg(const double p)
{
return p*p*p* (-15. + 12. *p) + 3 *p*p* (10. - 15.* p + 6 *p*p);
}
double CAeq_L(const int i,const double T){
return CAeq_LT0[i] + (T-T0)/mA_Lp[i];
}
double CAeq_S(const int i,const double T){
return CAeq_ST0[i] + (T-T0)/mA_Sp[i];
}
double deltaA_SL(const int i,const double T){
double k_S = 1./kA_L[i];
//return deltaA_SLT0[i] + (T0-T)*(1.-k_S)/mA_Lp[i];
return CAeq_S(i,T) - CAeq_L(i,T);
}
double temp(const double time, const double z){
double G_z = Tdot[0]/2./a*z;//K/m(mm)
//return T0 - Tdot[0]*time + G_z*z;
//return T0 +5.*(z- .1*time);
//return T0 - 1.e2*time+5.*z;
return T0 - 150.;
}
double deltaG_ch(const double * CA, const double p, const double T)
{
double s = 0.;
for (int i = 0; i < N; i++){
double CAeq = CAeq_S(i,T)*p + CAeq_L(i,T)*(1. - p);
double d = (p+(1.-p)*kA_L[i]);
s += XA_L[i]*deltaA_SL(i,T)*(CA[i]-CAeq)/d;
}
return s;
}
double fn (const double p){
return 16.*p*p*(1.-p)*(1.-p);
}
double XA_bar(const int i, const double p){
//this should be evaluated at p = .5
double XA_S = kA_L[i]*XA_L[i];
//double val = (1.-p)/XA_L[i] + p /XA_S;
double val = (1.-.5)/XA_L[i] + .5 /XA_S;
return 1./val;
}
double QA_L_(const int i,const double p,const double T){
return XA_bar(i,p)*deltaA_SL(i,T)*deltaA_SL(i,T)/DA_L[i];
}
double tau_(const double p,const double T){
double t =0.;
for (int i = 0; i < N; i++){
t += QA_L_(i,p,T);
}
t = t*a_1*a_2*W*W*W/sigma;
return t;
}
//double a_small = 5.e-3;// => px < 1e-9
double a_small = 5.e-9;// => px < 1e-9
inline const double a_s_(const double px, const double py, const double pz, const double ep){
// in 2d, equivalent to: a_s = 1 + ep cos 4 theta
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 1. + ep;
//return 1.-3.*ep + 4.*ep*(px2*px2 + py2*py2 + pz2*pz2)/norm4;
return 1.;
}
inline const double da_s_dpx(const double px, const double py, const double pz, const double ep){
// (16 ep x (-y^4 - z^4 + x^2 y^2 + x^2 z^2))/(x^2 + y^2 + z^2)^3
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return 16.*ep*px*(- py2*py2 - pz2*pz2 + px2*py2 + px2*pz2)/norm6;
return 0.;
}
inline const double da_s_dpy(const double px, const double py, const double pz, const double ep){
// -((16 ep y (x^4 - x^2 y^2 - y^2 z^2 + z^4))/(x^2 + y^2 + z^2)^3)
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return - 16.*ep*py*(px2*px2 + pz2*pz2 - px2*py2 - py2*pz2)/norm6;
return 0.;
}
inline const double da_s_dpz(const double px, const double py, const double pz, const double ep){
//-((16 ep z (x^4 + y^4 - x^2 z^2 - y^2 z^2))/(x^2 + y^2 + z^2)^3)
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return - 16.*ep*pz*(px2*px2 + py2*py2 - px2*pz2 - py2*pz2)/norm6;
return 0.;
}
RES_FUNC(phiresidual_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double test = basis[0].phi[i];
int phi_id = eqn_id;
double phi[2] = {basis[phi_id].uu, basis[phi_id].uuold};
double phi_x[2] = {basis[phi_id].dudx, basis[phi_id].duolddx};
double phi_y[2] = {basis[phi_id].dudy, basis[phi_id].duolddy};
double phi_z[2] = {basis[phi_id].dudz, basis[phi_id].duolddz};
double y = basis[phi_id].yy;
double a_s[2] = {a_s_(phi_x[0], phi_y[0], phi_z[0], eps_4),
a_s_(phi_x[1], phi_y[1], phi_z[1], eps_4)};
//a_s[0]=1;a_s[1]=1;
double a_spx[2] = {da_s_dpx(phi_x[0], phi_y[0], phi_z[0], eps_4),
da_s_dpx(phi_x[1], phi_y[1], phi_z[1], eps_4)};
double a_spy[2] = {da_s_dpy(phi_x[0], phi_y[0], phi_z[0], eps_4),
da_s_dpy(phi_x[1], phi_y[1], phi_z[1], eps_4)};
double a_spz[2] = {da_s_dpz(phi_x[0], phi_y[0], phi_z[0], eps_4),
da_s_dpz(phi_x[1], phi_y[1], phi_z[1], eps_4)};
tau = tau_(phi[0],temp(time,y));
tau=2.e-5;
//tau=tau/1000.;
double phit = (tau*phi[0]-tau*phi[1])/dt_*test;
double divgrad = t_theta_*W*W*a_s[0]*a_s[0]*(phi_x[0]*dtestdx + phi_y[0]*dtestdy + phi_z[0]*dtestdz)
+(1.-t_theta_)*W*W*a_s[1]*a_s[1]*(phi_x[1]*dtestdx + phi_y[1]*dtestdy + phi_z[1]*dtestdz);
double normphi2[2] = {phi_x[0]*phi_x[0] + phi_y[0]*phi_y[0] + phi_z[0]*phi_z[0],
phi_x[1]*phi_x[1] + phi_y[1]*phi_y[1] + phi_z[1]*phi_z[1]};
double curlgrad = t_theta_*W*W*normphi2[0]*a_s[0]*(a_spx[0]*dtestdx + a_spy[0]*dtestdy + a_spz[0]*dtestdz)
+(1.-t_theta_)*W*W*normphi2[1]*a_s[1]*(a_spx[1]*dtestdx + a_spy[1]*dtestdy + a_spz[1]*dtestdz);
double dfdp = (t_theta_*df(phi[0])+(1.-t_theta_)*df(phi[1]))*test;
double CA[6];
double deltaG_ch_[2];
for (int i = 0; i < N; i++) CA[i] = basis[i].uu;
double T = temp(time,y);
deltaG_ch_[0] = deltaG_ch(CA,phi[0],T);
for (int i = 0; i < N; i++) CA[i] = basis[i].uuold;
T = temp(time - dt_,y);
deltaG_ch_[1] = deltaG_ch(CA,phi[1],T);
double dgdp = -a_1*W/sigma*(t_theta_*dg(phi[0])*deltaG_ch_[0]
+(1.-t_theta_)*dg(phi[1])*deltaG_ch_[1])*test;
// if(phi[1] >0 && phi[1]<1)
// std::cout<<dgdp<<" "<<dfdp<<" "<<phi[1]<<std::endl;
return (phit + divgrad + curlgrad + dfdp + 10.*dgdp)/tau;// /tau/10.;
}
PRE_FUNC(phiprec_)
{
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
int phi_id = eqn_id;
double phi = basis[phi_id].uu;
double phi_x = basis[phi_id].dudx;
double phi_y = basis[phi_id].dudy;
double phi_z = basis[phi_id].dudz;
//tau = tau_(phi,temp(0.));
tau = 2.e-5;
double phit = tau*basis[phi_id].phi[j]/dt_*test;
double a_s = a_s_(phi_x, phi_y, phi_z, eps_4);
double divgrad = t_theta_*W*W*a_s*a_s*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
return (phit + t_theta_*divgrad)/tau;// /tau/10.;
}
RES_FUNC(cresidual_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double test = basis[0].phi[i];
double y = basis[eqn_id].yy;
double CA[2] = {basis[eqn_id].uu,
basis[eqn_id].uuold};
double CA_x[2] = {basis[eqn_id].dudx,
basis[eqn_id].duolddx};
double CA_y[2] = {basis[eqn_id].dudy,
basis[eqn_id].duolddy};
double CA_z[2] = {basis[eqn_id].dudz,
basis[eqn_id].duolddz};
double phi[2] = {basis[6].uu,
basis[6].uuold};
double phi_x[2] = {basis[6].dudx,
basis[6].duolddx};
double phi_y[2] = {basis[6].dudy,
basis[6].duolddy};
double phi_z[2] = {basis[6].dudz,
basis[6].duolddz};
double T[2] = {temp(time,y),
temp(time-dt_,y)};
double D_L = DA_L[eqn_id];
//double D_S = 0.;
double D_S = D_L;
double k_L =kA_L[eqn_id];
double CAt = (CA[0] - CA[1])/dt_*test;
// double CAeq[2] = {CAeq_S(eqn_id,T)*phi[0] + CAeq_L(eqn_id,T)*(1.- phi[0]),
// CAeq_S(eqn_id,T)*phi[1] + CAeq_L(eqn_id,T)*(1.- phi[1])};
double CAeq_x[2] = {CAeq_S(eqn_id,T[0])*phi_x[0] + CAeq_L(eqn_id,T[0])*(- phi_x[0]),
CAeq_S(eqn_id,T[1])*phi_x[1] + CAeq_L(eqn_id,T[1])*(- phi_x[1])};
double CAeq_y[2] = {CAeq_S(eqn_id,T[0])*phi_y[0] + CAeq_L(eqn_id,T[0])*(- phi_y[0]),
CAeq_S(eqn_id,T[1])*phi_y[1] + CAeq_L(eqn_id,T[1])*(- phi_y[1])};
double CAeq_z[2] = {CAeq_S(eqn_id,T[0])*phi_z[0] + CAeq_L(eqn_id,T[0])*(- phi_z[0]),
CAeq_S(eqn_id,T[1])*phi_z[1] + CAeq_L(eqn_id,T[1])*(- phi_z[1])};
double CA_xd[2] = {CA_x[0] - CAeq_x[0],
CA_x[1] - CAeq_x[1]};
double CA_yd[2] = {CA_y[0] - CAeq_y[0],
CA_y[1] - CAeq_y[1]};
double CA_zd[2] = {CA_z[0] - CAeq_z[0],
CA_z[1] - CAeq_z[1]};
//the denominator *should* be inside the gradient operator
//however, most implementations factor it out like this
double coef[2] = {(D_S*phi[0] + D_L*(1.-phi[0])*k_L)/(phi[0] + (1. - phi[0])*k_L),
(D_S*phi[1] + D_L*(1.-phi[1])*k_L)/(phi[1] + (1. - phi[1])*k_L)};
// double coef[2] = {D_L,
// D_L};
double divgrad = t_theta_*coef[0]*(CA_xd[0]*dtestdx + CA_yd[0]*dtestdy + CA_zd[0]*dtestdz)
+(1.-t_theta_)*coef[1]*(CA_xd[1]*dtestdx + CA_yd[1]*dtestdy + CA_zd[1]*dtestdz);
double delta_SL[2] = {deltaA_SL(eqn_id,T[0]),
deltaA_SL(eqn_id,T[1])};
double normphi[2] = {sqrt(phi_x[0]*phi_x[0] + phi_y[0]*phi_y[0] + phi_z[0]*phi_z[0]),
sqrt(phi_x[1]*phi_x[1] + phi_y[1]*phi_y[1] + phi_z[0]*phi_z[1])};
double small = 1.e-12;
double coef2[2] = {0.,0.};
if (normphi[0] > small) coef2[0] = W/sqrt(2.)*delta_SL[0]*(phi[0] - phi[1])/dt_/normphi[0];
if (normphi[1] > small) coef2[1] = W/sqrt(2.)*delta_SL[1]*(phi[1] - basis[6].uuoldold)/dt_/normphi[1];
double trap = t_theta_*coef2[0]*(phi_x[0]*dtestdx + phi_y[0]*dtestdy + phi_z[0]*dtestdz)
+ (1. - t_theta_)*coef2[1]*(phi_x[1]*dtestdx + phi_y[1]*dtestdy + phi_z[1]*dtestdz);
//std::cout<<CAt<<" "<<divgrad<<" : "
//std::cout<<CA<<" "<<CAold<<" "<<CA-CAold<<" "<<eqn_id<<" "<<basis[eqn_id].uu<<std::endl;
return (CAt + divgrad + 0.*trap);
//return CA[0]-CAeq_ST0[eqn_id];
}
PRE_FUNC(cprec_)
{
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[eqn_id].dphidxi[j]*basis[eqn_id].dxidx
+basis[eqn_id].dphideta[j]*basis[eqn_id].detadx
+basis[eqn_id].dphidzta[j]*basis[eqn_id].dztadx;
double dbasisdy = basis[eqn_id].dphidxi[j]*basis[eqn_id].dxidy
+basis[eqn_id].dphideta[j]*basis[eqn_id].detady
+basis[eqn_id].dphidzta[j]*basis[eqn_id].dztady;
double dbasisdz = basis[eqn_id].dphidxi[j]*basis[eqn_id].dxidz
+basis[eqn_id].dphideta[j]*basis[eqn_id].detadz
+basis[eqn_id].dphidzta[j]*basis[eqn_id].dztadz;
double test = basis[0].phi[i];
double CAt = basis[eqn_id].phi[j]/dt_*test;
double CA = basis[eqn_id].phi[j];
double CA_x = dbasisdx;
double CA_y = dbasisdy;
double CA_z = dbasisdz;
double phi = basis[6].uu;
double phi_x = basis[6].dudx;
double phi_y = basis[6].dudy;
double phi_z = basis[6].dudz;
//double T = temp(0.);
double D_L = DA_L[eqn_id];
double k_L = kA_L[eqn_id];
double den = (phi + (1. - phi)*k_L);
double den_x = phi_x - k_L*phi_x;
double den_y = phi_y - k_L*phi_y;
double den_z = phi_z - k_L*phi_z;
double num = CA;
double num_x = CA_x;
double num_y = CA_y;
double num_z = CA_z;
double CA_xd = (num_x*den - num*den_x)/den/den;
double CA_yd = (num_y*den - num*den_y)/den/den;
double CA_zd = (num_z*den - num*den_z)/den/den;
double D_S = 0.;
//double D_S = D_L;
double coef = (D_S*phi + D_L*(1.-phi)*k_L)/den;
double divgrad = coef*(CA_x*dtestdx + CA_y*dtestdy + CA_z*dtestdz);
return (CAt + t_theta_*divgrad);
}
double init(const double x)
{
double pi = 3.141592653589793;
double val = lx/7.*sin(7.*pi*x/lx);
return 10.*(std::abs(val)-.0005);
}
INI_FUNC(cinit_)
{
double val = CAeq_LT0[eqn_id];
if(y < init(x)) val=CAeq_ST0[eqn_id];
//std::cout<<eqn_id<<" "<<val<<std::endl;
return val;
}
DBC_FUNC(dbc0_)
{
return CAeq_LT0[0];
}
DBC_FUNC(dbc1_)
{
return CAeq_LT0[1];
}
DBC_FUNC(dbc2_)
{
return CAeq_LT0[2];
}
DBC_FUNC(dbc3_)
{
return CAeq_LT0[3];
}
DBC_FUNC(dbc4_)
{
return CAeq_LT0[4];
}
DBC_FUNC(dbc5_)
{
return CAeq_LT0[5];
}
INI_FUNC(phiinit_)
{
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = phi_liq_;
if(y < init(x)) val=phi_sol_;
return val;
}
PPR_FUNC(postproc_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double y = xyz[1];
return temp(time,y);
}
}//namespace kundin
namespace truchas
{
// time is ms space is mm
double rho_ = 7.57e-3; // g/mm^3 density
double cp_ = 750.65; // (g-mm^2/ms^2)/g-K specific heat
//we can interp this as in truchas
double k_ = .0213; //(g-mm^2/ms^3)/mm-K thermal diffusivity
double l_ = 2.1754e5; //g-mm^2/ms^2/g latent heat
double w_ = 2.4;
//double eps_ = .001;// anisotropy strength
double eps_ = 000547723;
double m_ = .002149;// K ms/mm
//double t_m_ = 1678.;
double t_m_ = 1450.;
double zmin_ = -.036;
double dz_ = .0002;
double get_k_liq_(const double temp){
double c1 = 8.92e-3;
double c2 = 1.474e-5;
double r =273;
return c1+c2*(temp-r);
//return k_;
}
double get_k_sol_(const double temp){
double c1 = 12.3e-3;
double c2 = 1.472e-5;
double r =273;
return c1+c2*(temp-r);
//return k_;
}
RES_FUNC(residual_heat_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
double u = basis[0].uu;
double uold = basis[0].uuold;
double ut = rho_*cp_*(u-uold)/dt_*test;
double divgradu = get_k_liq_(basis[0].uu)*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy + basis[0].dudz*dtestdz);//(grad u,grad phi)
//double divgradu_old = k_*(basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy + basis[0].duolddz*dtestdz);//(grad u,grad phi)
return (ut + t_theta_*divgradu);// /rho_/cp_;// + (1.-t_theta_)*divgradu_old;
}
PRE_FUNC(prec_heat_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = get_k_liq_(basis[0].uu)*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
double u_t =rho_*cp_*test * basis[0].phi[j]/dt_;
return (u_t + t_theta_*divgrad);// /rho_/cp_;;
}
RES_FUNC(residual_phase_)
{
//derivatives of the test function
double dtestdx = basis[1].dphidxi[i]*basis[1].dxidx
+basis[1].dphideta[i]*basis[1].detadx
+basis[1].dphidzta[i]*basis[1].dztadx;
double dtestdy = basis[1].dphidxi[i]*basis[1].dxidy
+basis[1].dphideta[i]*basis[1].detady
+basis[1].dphidzta[i]*basis[1].dztady;
double dtestdz = basis[1].dphidxi[i]*basis[1].dxidz
+basis[1].dphideta[i]*basis[1].detadz
+basis[1].dphidzta[i]*basis[1].dztadz;
//test function
double test = basis[1].phi[i];
//u, phi
double u = basis[1].uu;
double uold = basis[1].uuold;
double ut = (u-uold)/dt_*test;
double divgradu = m_*eps_*eps_*(basis[1].dudx*dtestdx + basis[1].dudy*dtestdy + basis[1].dudz*dtestdz);//(grad u,grad phi)
double g = 2.*m_*w_*u*(1.-u)*(1.-2.*u);
double p = 30.*m_*l_*(t_m_-basis[0].uu)/t_m_*u*u*(1.-u)*(1.-u);
return (ut + t_theta_*divgradu+ t_theta_*g + t_theta_*p)/eps_/eps_/m_;
}
PRE_FUNC(prec_phase_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[1].dphidxi[i]*basis[1].dxidx
+basis[1].dphideta[i]*basis[1].detadx
+basis[1].dphidzta[i]*basis[1].dztadx;
double dtestdy = basis[1].dphidxi[i]*basis[1].dxidy
+basis[1].dphideta[i]*basis[1].detady
+basis[1].dphidzta[i]*basis[1].dztady;
double dtestdz = basis[1].dphidxi[i]*basis[1].dxidz
+basis[1].dphideta[i]*basis[1].detadz
+basis[1].dphidzta[i]*basis[1].dztadz;
double dbasisdx = basis[1].dphidxi[j]*basis[1].dxidx
+basis[1].dphideta[j]*basis[1].detadx
+basis[1].dphidzta[j]*basis[1].dztadx;
double dbasisdy = basis[1].dphidxi[j]*basis[1].dxidy
+basis[1].dphideta[j]*basis[1].detady
+basis[1].dphidzta[j]*basis[1].dztady;
double dbasisdz = basis[1].dphidxi[j]*basis[1].dxidz
+basis[1].dphideta[j]*basis[1].detadz
+basis[1].dphidzta[j]*basis[1].dztadz;
double test = basis[1].phi[i];
double divgrad = m_*eps_*eps_*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
double u_t = test * basis[1].phi[j]/dt_;
return (u_t + t_theta_*divgrad)/eps_/eps_/m_;
}
INI_FUNC(init_phase_)
{
double phi_sol_ = 1.;
double phi_liq_ = 0.;
double val = phi_liq_;
double c = 1.5;//1.1;
if ( z < zmin_ + c*dz_) {
val = ((rand() % 100)/50.-1.)*1.5;
if (val < 0.) val =0.;
if (val > 1.) val =1.;
}
return val;
}
}//namespace truchas
namespace rotate
{
//t0 is rotation in x-y plane (wrt to z axis) only
//there is no derivative coded at this time
//note that to rotate around the x or y axis, is more complicated;
//requiring a rotation matrix in cartesian coordinates to be applied
const double a_sr_(const double px, const double py, const double pz, const double ep, const double t0){
// in 2d, equivalent to: a_s = 1 + ep cos 4 (theta - t0)
double nn = sqrt(px*px + py*py + pz*pz );
double small = 5.e-3;// => px < 1e-9
//double small = a_small;
if( nn < small*small ) return 1. + ep;
double xx = px/nn;
double yy = py/nn;
double zz = pz/nn;
double aa = .75 + (xx*xx*xx*xx + yy*yy*yy*yy -.75)*cos(4.*t0) + (xx*xx*xx*yy-yy*yy*yy*xx)*sin(4.*t0);
return 1.-3.*ep + 4.*ep*(aa + zz*zz*zz*zz);
}
const double da_sr_dpx(const double px, const double py, const double pz, const double ep, const double t0){
return 0.;
}
}//namespace rotate
//double a_small = 5.e-3;// => px < 1e-9
namespace takaki {
double a_small = 5.e-9;// => px < 1e-9
const double umperm_ = 1.e6; //1e6 um = 1 m
const double ep4_=.02;
const double w0_ = .9375; //um
const double T0_ = 931.2; //K
const double G_ = .2; //K/um
const double Vp_ = 50.; //um/s
const double tau0_ =1.;
const double c0_ = .00245; //atm frac
const double m_ = -620; //K/atm frac
const double k_ = .14; //atm frac
double lT_ = -m_*(1.- k_)*c0_/(k_*G_); //should be um
double gamma_ = .24e-6/umperm_;// K/m -> K/um
//double d0_ = k_*gamma_/(-m_*(1.-k_)*c0_);
double d0_ = 1.3e-2;//um
const double a1_ = 0.88388;
double lambdastar_ = a1_*w0_/d0_;
//const double abar_ = 1.;
const double Dl_ = (3.e-9)*umperm_*umperm_; //m^2/s -> um^2/s
//const double Ds_ = (2.e-12)*umperm_*umperm_; //m^2/s -> um^2/s
const double Ds_ = Dl_;
double a_ = (1.-k_*Ds_/Dl_)/2./std::sqrt(2.);
double dfdp(const double p){
return -p + p*p*p;
}
double dgdp(const double p){
return (1.-p*p)*(1.-p*p);
}
double q(const double p){
return (k_*Ds_+Dl_+(k_*Ds_-Dl_)*p)/2./Dl_;;
}
//see anisotropy_new.nb
//rotation about z axis or x-y plane
const double rpx_z(const double px, const double py, const double pz, const double tz){
double c = cos(tz);
double s = sin(tz);
return c*px + s*py;
}
const double drpx_zdpx(const double px, const double py, const double pz, const double tz){
return cos(tz);
}
const double rpy_z(const double px, const double py, const double pz, const double tz){
double c = cos(tz);
double s = sin(tz);
return -s*px + c*py;
}
const double drpy_zdpy(const double px, const double py, const double pz, const double tz){
return cos(tz);
}
const double rpz_z(const double px, const double py, const double pz, const double tz){
return pz;
}
const double drpz_zdpz(const double px, const double py, const double pz, const double tz){
return 1.;
}
//full 3d rotation about z axis, tz, y axis, ty, and x axis, tx
const double rpx_f(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
double cy = cos(ty);
double cz = cos(tz);
double sy = sin(ty);
double sz = sin(tz);
return cy*cz*px + cy*sz*py + sy*pz;
}
const double drpx_fdpx(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
return rpx_f(1.,0.,0.,tz,ty,tx);
}
const double rpy_f(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
double cx = cos(tx);
double cy = cos(ty);
double cz = cos(tz);
double sx = sin(tx);
double sy = sin(ty);
double sz = sin(tz);
return (-cz*sx*sy - cx*sz)*px + (cx*cz-sx*sy*sz)*py + cy*sx*pz;
}
const double drpy_fdpy(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
return rpy_f(0.,1.,0.,tz,ty,tx);
}
const double rpz_f(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
double cx = cos(tx);
double cy = cos(ty);
double cz = cos(tz);
double sx = sin(tx);
double sy = sin(ty);
double sz = sin(tz);
return (-cx*cz*sy + sx*sz)*px + (-cz*sx - cx*sy*sz)*py + cx*cy*pz;
}
const double drpz_fdpz(const double px, const double py, const double pz, const double tz, const double ty, const double tx){
return rpz_f(0.,0.,1.,tz,ty,tx);
}
const double a_s_(const double px, const double py, const double pz, const double ep){
// in 2d, equivalent to: a_s = 1 + ep cos 4 theta
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 1. + ep;
//return 1.-3.*ep + 4.*ep*(px2*px2 + py2*py2 + pz2*pz2)/norm4;
return 1.;
}
const double da_s_dpx(const double px, const double py, const double pz, const double ep){
// (16 ep x (-y^4 - z^4 + x^2 y^2 + x^2 z^2))/(x^2 + y^2 + z^2)^3
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return 16.*ep*px*(- py2*py2 - pz2*pz2 + px2*py2 + px2*pz2)/norm6;
return 0.;
}
const double da_s_dpy(const double px, const double py, const double pz, const double ep){
// -((16 ep y (x^4 - x^2 y^2 - y^2 z^2 + z^4))/(x^2 + y^2 + z^2)^3)
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return - 16.*ep*py*(px2*px2 + pz2*pz2 - px2*py2 - py2*pz2)/norm6;
return 0.;
}
const double da_s_dpz(const double px, const double py, const double pz, const double ep){
//-((16 ep z (x^4 + y^4 - x^2 z^2 - y^2 z^2))/(x^2 + y^2 + z^2)^3)
double px2 = px*px;
double py2 = py*py;
double pz2 = pz*pz;
double norm4 = (px2 + py2 + pz2 )*(px2 + py2 + pz2 );
double norm6 = norm4*(px2 + py2 + pz2 );
//double small = 5.e-3;// => px < 1e-9
if( norm4 < a_small ) return 0.;
//return - 16.*ep*pz*(px2*px2 + py2*py2 - px2*pz2 - py2*pz2)/norm6;
return 0.;
}
const double w_(const double px, const double py, const double pz, const double ep){
double a2 = a_s_(px, py, pz, ep);
return w0_*a2*a2;
}
const double dw_dpx(const double px, const double py, const double pz, const double ep){
return 2.*w0_*a_s_(px, py, pz, ep)*da_s_dpx(px, py, pz, ep);
}
const double dw_dpy(const double px, const double py, const double pz, const double ep){
return 2.*w0_*a_s_(px, py, pz, ep)*da_s_dpy(px, py, pz, ep);
}
const double dw_dpz(const double px, const double py, const double pz, const double ep){
return 2.*w0_*a_s_(px, py, pz, ep)*da_s_dpz(px, py, pz, ep);
}
double temp(const double time, const double y){
return T0_ + G_*(y-Vp_*time);
}
double uprime(const double time, const double y){
return (y-Vp_*time)/lT_;
}
const double tau_(const double px, const double py, const double pz, const double ep){
double a2 = a_s_(px, py, pz, ep);
return tau0_*a2*a2;
}
INI_FUNC(init_conc_)
{
//return c0_;//cn should be u0
return 0.;
}
INI_FUNC(init_phase_)
{
double dx = .75;
double lfo = 230.*dx;
double luo = 300.*dx;
double val = -1.;
double r2 = x*x + y*y;
double rr2 =.75*.75*dx*dx;
if(r2 < rr2 ){
val=1.;
}
r2 = (x - lfo)*(x - lfo) + y*y;
if(r2 < rr2 ){
val=1.;
}
r2 = (x - (lfo+luo))*(x - (lfo+luo)) + y*y;
if(r2 < rr2 ){
val=1.;
}
return val;
}
RES_FUNC(residual_conc_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//test function
double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
double u = basis[0].uuold;
//double uold = basis[0].uuold;
double uold = basis[0].uuoldold;
//double phi = basis[1].uu;
double phi = basis[1].uuold;
//double phiold = basis[1].uuold;
double phiold = basis[1].uuoldold;
//double dphidx = basis[1].dudx;
double dphidx = basis[1].duolddx;
//double dphidy = basis[1].dudy;
double dphidy = basis[1].duolddy;
double dtc = (1.+k_-(1.-k_)*phi)/2.;
//double ut = dtc*(u-uold)/dt_*test;
double ut = dtc*(basis[0].uu-basis[0].uuold)/dt_*test;
//ut = (u-uold)/dt_*test;
double divgradu = Dl_*q(phi)*(basis[0].dudx*dtestdx + basis[0].dudy*dtestdy);//(grad u,grad phi)
//double divgradu_old = D*(1.-phiold)/2*(basis[0].duolddx*dtestdx + basis[0].duolddy*dtestdy);//(grad u,grad phi)
//j is antitrapping current
// j grad test here... j1*dtestdx + j2*dtestdy
// what if dphidx*dphidx + dphidy*dphidy = 0?
double norm = sqrt(dphidx*dphidx + dphidy*dphidy);
double small = 1.e-12;
double j_coef = 0.;
if (small < norm) {
j_coef = a_*w0_*(1.+(1.-k_)*u)/norm*(phi-phiold)/dt_;
}
//j_coef = 0.;
double j1 = j_coef*dphidx;
double j2 = j_coef*dphidy;
double divj = j1*dtestdx + j2*dtestdy;
double phitu = -.5*(phi-phiold)/dt_*(1.+(1.-k_)*u)*test;
//phitu = 1.*test;
// h = hold;
// hold = basis[1].uuoldold*(1. + (1.-k_)*basis[0].uuoldold);
// double phitu_old = -.5*(h-hold)/dt_*test;
//return ut*0. + t_theta_*(divgradu + divj*0.) + (1.-t_theta_)*(divgradu_old + divj_old)*0. + t_theta_*phitu*0. + (1.-t_theta_)*phitu_old*0.;
//std::cout<<"u: "<<ut<<" "<< t_theta_*divgradu <<" "<< 0.*t_theta_*divj <<" "<< t_theta_*phitu<<" : "<<dtc<<std::endl;
return (ut + t_theta_*divgradu + 0.*t_theta_*divj + t_theta_*phitu)/dtc*dt_;
}
RES_FUNC(residual_phase_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
//test function
double test = basis[0].phi[i];
//u, phi
//double u = basis[0].uu;
double u = basis[0].uuold;
//double uold = basis[0].uuold;
double uold = basis[0].uuoldold;
//double phi = basis[1].uu;
double phi = basis[1].uuold;
//double phiold = basis[1].uuold;
double phiold = basis[1].uuoldold;
//double dphidx = basis[1].dudx;
double dphidx = basis[1].duolddx;
//double dphidy = basis[1].dudy;
double dphidy = basis[1].duolddy;
double y = basis[0].yy;
double up = uprime(y,time);
double dtc = tau_(dphidx,dphidy,0.,ep4_)*(1.-(1.-k_)*up);
//double phit = dtc*(phi-phiold)/dt_*test;
double phit = dtc*(basis[1].uu-basis[1].uuold)/dt_*test;
double w = w_(dphidx,dphidy,0.,ep4_);
double divgrad = w*w*(dphidx*dtestdx + dphidy*dtestdy);//(grad u,grad phi)
double norm2 = dphidx*dphidx + dphidy*dphidy;
double curlgrad = w*norm2*(dw_dpx(dphidx,dphidy,0.,ep4_)*dtestdx + dw_dpy(dphidx,dphidy,0.,ep4_)*dtestdy);
double df = dfdp(phi)*test;
double dg = lambdastar_*dgdp(phi)*(u + up)*test;
//std::cout<<"phi: "<<phit <<" "<< divgrad <<" "<< curlgrad <<" "<< df <<" "<<dg<<" "<<d0_<<" : "<<dtc<<std::endl;
return (phit + t_theta_*(divgrad + curlgrad + df +dg))/dtc*dt_;
}
}//namespace takaki
namespace allencahn {
double kappa = 0.0004;
const double pi = 3.141592653589793;
const double A1 = 0.0075;
const double B1 = 8.0*pi;
const double A2 = 0.03;
const double B2 = 22.0*pi;
const double C2 = 0.0625*pi;
PARAM_FUNC(param_)
{
//kappa = plist->get<double>("kappa");
}
double alpha(double t, double x) {
double alpha_result;
alpha_result = A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25;
return alpha_result;
}
double eta(double a, double y) {
double eta_result;
eta_result = -1.0L/2.0L*tanh((1.0L/2.0L)*sqrt(2)*(-a + y)/sqrt(kappa)) + 1.0L/2.0L;
return eta_result;
}
double eta0(double a, double y) {
double eta0_result;
eta0_result = -1.0L/2.0L*tanh((1.0L/2.0L)*sqrt(2)*(-a + y)/sqrt(kappa)) + 1.0L/2.0L;
return eta0_result;
}
double dadt(double t, double x) {
double dadt_result;
dadt_result = A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t);
return dadt_result;
}
double dadx(double t, double x) {
double dadx_result;
dadx_result = A1*B1*t*cos(B1*x) + A2*B2*cos(B2*x + C2*t);
return dadx_result;
}
double d2adx2(double t, double x) {
double d2adx2_result;
d2adx2_result = -A1*pow(B1, 2)*t*sin(B1*x) - A2*pow(B2, 2)*sin(B2*x + C2*t);
return d2adx2_result;
}
double source(double a, double t, double x, double y) {
double source_result;
source_result = (1.0L/4.0L)*(-pow(tanh((1.0L/2.0L)*sqrt(2)*(-a + y)/sqrt(kappa)), 2) + 1)*(-2*sqrt(kappa)*pow(A1*B1*t*cos(B1*x) + A2*B2*cos(B2*x + C2*t), 2)*tanh((1.0L/2.0L)*sqrt(2)*(-a + y)/sqrt(kappa)) - sqrt(2)*kappa*(-A1*pow(B1, 2)*t*sin(B1*x) - A2*pow(B2, 2)*sin(B2*x + C2*t)) + sqrt(2)*(A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t)))/sqrt(kappa);
return source_result;
}
RES_FUNC(residual_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
//test function
double test = basis[0].phi[i];
double u[2] = {basis[0].uu, basis[0].uuold};
double u_x[2] = {basis[0].dudx, basis[0].duolddx};
double u_y[2] = {basis[0].dudy, basis[0].duolddy};
double ut = (u[0]-u[1])/dt_*test;
double divgrad = t_theta_*kappa*(u_x[0]*dtestdx + u_y[0]*dtestdy)
+(1.-t_theta_)*kappa*(u_x[1]*dtestdx + u_y[1]*dtestdy);
double fp = (-t_theta_*4.*u[0]*(u[0]-1.)*(u[0]-.5)
-(1.-t_theta_)*4.*u[1]*(u[1]-1.)*(u[1]-.5))*test;
double x = basis[0].xx;
double y = basis[0].yy;
double t[2] = {time, time - dt_};
double a[2] = {alpha(t[0],x),alpha(t[1],x)};
double s = (-t_theta_*source(a[0],t[0],x,y)
-(1.-t_theta_)*source(a[1],t[1],x,y))*test;
return ut + divgrad + fp + s;
}
PRE_FUNC(prec_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double u_t = test * basis[0].phi[j]/dt_;
double divgrad = t_theta_*kappa*(dbasisdx * dtestdx + dbasisdy * dtestdy);
return (u_t + divgrad);
}
INI_FUNC(init_)
{
double a = alpha(0.,x);
double val = eta0(a,y);
return val;
}
PPR_FUNC(postproc_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double x = xyz[0];
double y = xyz[1];
double a = alpha(time,x);
double val = eta(a,y);
return val;
}
PPR_FUNC(postproc_error)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
// x is in nondimensional space, tscale_ takes in nondimensional and converts to um
double x = xyz[0];
double y = xyz[1];
double a = alpha(time,x);
double val = (u[0]-eta(a,y));
//double val = (u[0]-eta(a,y))*(u[0]-eta(a,y));
return val;
}
}//namespace allencahn
namespace pfhub2 {
int N_ = 1;
int eqn_off_ =1;
const double c0_ = .5;
const double eps_ = .05;
const double eps_eta_ = .1;
const double psi_ = 1.5;
const double rho_ = std::sqrt(2.);
const double c_alpha_ = .3;
const double c_beta_ = .7;
const double alpha_ = 5.;
const double k_c_ = 0.;//3.
const double k_eta_ = 3.;
const double M_ = 5.;
const double L_ = 5.;
const double w_ = 1.;
double c_a[2] = {0., 0.};
double c_b[2] = {0., 0.};
PARAM_FUNC(param_)
{
N_ = plist->get<int>("N");
eqn_off_ = plist->get<int>("OFFSET");
}
double f_alpha(const double c){
return rho_*rho_*(c - c_alpha_)*(c - c_alpha_);
}
double df_alphadc(const double c){
return 2.*rho_*rho_*(c - c_alpha_);
}
double f_beta(const double c){
return rho_*rho_*(c_beta_ - c)*(c_beta_ - c);
}
double df_betadc(const double c){
return -2.*rho_*rho_*(c_beta_ - c);
}
double d2fdc2(){
return 2.*rho_*rho_;
}
double h(const double *eta){
double val = 0.;
for (int i = 0; i < N_; i++){
val += eta[i]*eta[i]*eta[i]*(6.*eta[i]*eta[i] - 15.*eta[i] + 10.);
}
return val;
}
//double dhdeta(const double *eta, const int eqn_id){
double dhdeta(const double eta){
//return 30.*eta[eqn_id]*eta[eqn_id] - 60.*eta[eqn_id]*eta[eqn_id]*eta[eqn_id] + 30.*eta[eqn_id]*eta[eqn_id]*eta[eqn_id]*eta[eqn_id];
return 30.*eta*eta - 60.*eta*eta*eta + 30.*eta*eta*eta*eta;
}
// double d2hdeta2(const double *eta, const int eqn_id){
// return 60.*eta[eqn_id] - 180.*eta[eqn_id]*eta[eqn_id] + 120.*eta[eqn_id]*eta[eqn_id]*eta[eqn_id];
// }
// double g(const double *eta){
// double aval =0.;
// for (int i = 0; i < N_; i++){
// aval += eta[i]*eta[i];
// }
// double val = 0.;
// for (int i = 0; i < N_; i++){
// val += eta[i]*eta[i]*(1.-eta[i])*(1.-eta[i]) + alpha_*eta[i]*eta[i]*aval
// - alpha_*eta[i]*eta[i]*eta[i]*eta[i];
// }
// return val;
// }
double dgdeta(const double *eta, const int eqn_id){
double aval =0.;
for (int i = 0; i < N_; i++){
aval += eta[i]*eta[i];
}
aval = aval - eta[eqn_id]* eta[eqn_id];
return 2.*eta[eqn_id]*(1. - eta[eqn_id])*(1. - eta[eqn_id])
- 2.* eta[eqn_id]* eta[eqn_id]* (1. - eta[eqn_id])
+ 4.*alpha_*eta[eqn_id] *aval;
}
// double d2gdeta2(const double *eta, const int eqn_id){
// double aval =0.;
// for (int i = 0; i < N_; i++){
// aval += eta[i]*eta[i];
// }
// return 2. - 12.*eta[eqn_id] + 12.*eta[eqn_id]*eta[eqn_id] + alpha_*4.*aval - 4.*alpha_*eta[eqn_id]*eta[eqn_id];
// }
//void solve_kks(double &c_a, double &c_b, const double c, double phi)//const double phi
void solve_kks(const double c, double *phi)//const double phi
{
double delta_c_a = 0.;
double delta_c_b = 0.;
const int max_iter = 20;
const double tol = 1.e-8;
const double hh = h(phi);
//c_a[0] = (1.-hh)*c;
c_a[0] = c - hh*(c_beta_ - c_alpha_);
//c_b[0]=hh*c;
c_b[0]= c - (1.-hh)*(c_beta_ - c_alpha_);
//std::cout<<"-1"<<" "<<delta_c_b<<" "<<delta_c_a<<" "<<c_b[0]<<" "<<c_a[0]<<" "<<hh*c_b[0] + (1.- hh)*c_a[0]<<" "<<c<<std::endl;
for(int i = 0; i < max_iter; i++){
double det = hh*d2fdc2() + (1.-hh)*d2fdc2();//-fa''*h+(1-h)*fb''
double f1 = hh*c_b[0] + (1.- hh)*c_a[0] - c;
double f2 = df_betadc(c_b[0]) - df_alphadc(c_a[0]);
delta_c_b = (-d2fdc2()*f1 - (1-hh)*f2)/det;//-fa''f*1-(1-h)*f2
delta_c_a = (-d2fdc2()*f1 + hh*f2)/det;//-fb''*f1+h*f2
c_b[0] = delta_c_b + c_b[0];
c_a[0] = delta_c_a + c_a[0];
//std::cout<<i<<" "<<delta_c_b<<" "<<delta_c_a<<" "<<c_b[0]<<" "<<c_a[0]<<" "<<hh*c_b[0] + (1.- hh)*c_a[0]<<" "<<c<<std::endl;
if(delta_c_a*delta_c_a+delta_c_b*delta_c_b < tol*tol) return;
}
std::cout<<"################################### solve_kks falied to converge with delta_c_a*delta_c_a+delta_c_b*delta_c_b = "
<<delta_c_a*delta_c_a+delta_c_b*delta_c_b<<" ###################################"<<std::endl;
//if(delta_c_a*delta_c_a+delta_c_b*delta_c_b > 0) exit(0);
exit(0);
return;
}
void solve_kks_exact(const double c, double *phi)//const double phi
{
const double hh = h(phi);
//c_a[0] = (1.-hh)*c;
c_a[0] = (-c +(c_beta_ + c_alpha_)*hh)/(-1.+2.*hh);
//c_b[0]=hh*c;
c_b[0]= (c +(c_beta_ + c_alpha_)*(hh-1.))/(-1.+2.*hh);
return;
}
void solve_kks(const double c, double *phi, double &ca, double &cb)//const double phi
{
double delta_c_a = 0.;
double delta_c_b = 0.;
const int max_iter = 20;
const double tol = 1.e-8;
const double hh = h(phi);
//c_a[0] = (1.-hh)*c;
ca = 0.;//c - hh*(c_beta_ - c_alpha_);
//c_b[0]=hh*c;
cb = 0.;//c - (1.-hh)*(c_beta_ - c_alpha_);
//solve:
// f1 = hh*cb + (1.- hh)*ca - c = 0
// f2 = df_betadc(cb) - df_alphadc(ca) = 0
// F'*delta_c = - F
// delta_c = F'^-1 *(-F)
// delta_c = cnew - cold
// c = [cb ca]^T
// F'= [ h 1-h ]
// [d2fdc2() -d2fdc2()]
// F'^-1 = 1/det [-d2fdc2() -(1-h)]
// [-d2fdc2() h ]
// det = -h d2fdc2() -(1-h)d2fdc2() = -d2fdc2()
for(int i = 0; i < max_iter; i++){
//const double det = hh*d2fdc2() + (1.-hh)*d2fdc2();
const double det = -d2fdc2();
const double f1 = hh*cb + (1.- hh)*ca - c;
const double f2 = df_betadc(cb) - df_alphadc(ca);
delta_c_b = (-d2fdc2()*(-f1) - (1-hh)*(-f2))/det;
delta_c_a = (-d2fdc2()*(-f1) + hh*(-f2))/det;
cb = delta_c_b + cb;
ca = delta_c_a + ca;
//std::cout<<i<<" "<<delta_c_b<<" "<<delta_c_a<<" "<<c_b[0]<<" "<<c_a[0]<<" "<<hh*c_b[0] + (1.- hh)*c_a[0]<<" "<<c<<std::endl;
if(delta_c_a*delta_c_a+delta_c_b*delta_c_b < tol*tol) return;
}
// std::cout<<"################################### solve_kks falied to converge with delta_c_a*delta_c_a+delta_c_b*delta_c_b = "
// <<delta_c_a*delta_c_a+delta_c_b*delta_c_b<<" ###################################"<<std::endl;
exit(0);
return;
}
RES_FUNC(residual_c_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
//double dtestdz = basis[0].dphidz[i];
//test function
double test = basis[0].phi[i];
//u, phi
double c[2] = {basis[0].uu, basis[0].uuold};
double dcdx[2] = {basis[0].dudx, basis[0].duolddx};
double dcdy[2] = {basis[0].dudy, basis[0].duolddy};
double dhdx[2] = {0., 0.};
double dhdy[2] = {0., 0.};
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
dhdx[0] += dhdeta(basis[kk_off].uu)*basis[kk_off].dudx;
dhdx[1] += dhdeta(basis[kk_off].uuold)*basis[kk_off].duolddx;
dhdy[0] += dhdeta(basis[kk_off].uu)*basis[kk_off].dudy;
dhdy[1] += dhdeta(basis[kk_off].uuold)*basis[kk_off].duolddy;
}
double ct = (c[0]-c[1])/dt_*test;
double DfDc[2] = {df_betadc(c[0])-df_alphadc(c[0]),
df_betadc(c[1])-df_alphadc(c[1])};
double D2fDc2 = d2fdc2();
double dfdx[2] = {DfDc[0]*dhdx[0] + D2fDc2*dcdx[0],
DfDc[1]*dhdx[1] + D2fDc2*dcdx[1]};
double dfdy[2] = {DfDc[0]*dhdy[0] + D2fDc2*dcdy[0],
DfDc[1]*dhdy[1] + D2fDc2*dcdy[1]};
double divgradc[2] = {M_*(dfdx[0]*dtestdx + dfdy[0]*dtestdy),
M_*(dfdx[1]*dtestdx + dfdy[1]*dtestdy)};
return ct + t_theta_*divgradc[0] + (1.-t_theta_)*divgradc[1];
}
PRE_FUNC(prec_c_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
double dtestdz = basis[0].dphidz[i];
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz;
double u_t =test * basis[0].phi[j]/dt_;
double D2fDc2 = d2fdc2();
return u_t + t_theta_*M_*D2fDc2*divgrad;
}
RES_FUNC(residual_eta_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
//double dtestdz = basis[0].dphidz[i];
//test function
double test = basis[eqn_id].phi[i];
//u, phi
double c[2] = {basis[0].uu, basis[0].uuold};
double eta[2] = {basis[eqn_id].uu, basis[eqn_id].uuold};
double detadx[2] = {basis[eqn_id].dudx, basis[eqn_id].duolddx};
double detady[2] = {basis[eqn_id].dudy, basis[eqn_id].duolddy};
double eta_array[N_];
double eta_array_old[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
eta_array_old[kk] = basis[kk_off].uuold;
}
double etat = (eta[0]-eta[1])/dt_*test;
double F[2] = {f_beta(c[0])-f_alpha(c[0]),
f_beta(c[1])-f_alpha(c[1])};
int k = eqn_id - eqn_off_;
double dfdeta[2] = {L_*(F[0]*dhdeta(eta[0]) + w_*dgdeta(eta_array,k))*test,
L_*(F[1]*dhdeta(eta[1]) + w_*dgdeta(eta_array_old,k))*test};
double divgradeta[2] = {L_*k_eta_*(detadx[0]*dtestdx + detady[0]*dtestdy),
L_*k_eta_*(detadx[1]*dtestdx + detady[1]*dtestdy)};//(grad u,grad phi)
return etat + t_theta_*divgradeta[0] + t_theta_*dfdeta[0] + (1.-t_theta_)*divgradeta[1] + (1.-t_theta_)*dfdeta[1];
}
PRE_FUNC(prec_eta_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
double dtestdz = basis[0].dphidz[i];
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double test = basis[0].phi[i];
double divgrad = dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz;
double u_t =test * basis[0].phi[j]/dt_;
const double eta = basis[eqn_id].uu;
const double g1 = (2. - 12.*eta + 12.*eta*eta)*basis[eqn_id].phi[j]*test;
return u_t + t_theta_*L_*k_eta_*divgrad + t_theta_*L_*g1;
}
RES_FUNC(residual_c_kks_)
{
//derivatives of the test function
double dtestdx = basis[0].dphidx[i];
double dtestdy = basis[0].dphidy[i];
//double dtestdz = basis[0].dphidz[i];
//test function
double test = basis[0].phi[i];
//u, phi
double c[2] = {basis[0].uu, basis[0].uuold};
double dcdx[2] = {basis[0].dudx, basis[0].duolddx};
double dcdy[2] = {basis[0].dudy, basis[0].duolddy};
double dhdx[2] = {0., 0.};
double dhdy[2] = {0., 0.};
double eta_array[N_];
double eta_array_old[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
dhdx[0] += dhdeta(basis[kk_off].uu)*basis[kk_off].dudx;
dhdx[1] += dhdeta(basis[kk_off].uuold)*basis[kk_off].duolddx;
dhdy[0] += dhdeta(basis[kk_off].uu)*basis[kk_off].dudy;
dhdy[1] += dhdeta(basis[kk_off].uuold)*basis[kk_off].duolddy;
eta_array[kk] = basis[kk_off].uu;
eta_array_old[kk] = basis[kk_off].uuold;
}
double ct = (c[0]-c[1])/dt_*test;
double ca,cb;
solve_kks(c[0],eta_array,ca,cb);
//kks paper
double dfdx[2] = {dcdx[0] + dhdeta(eta_array[0])*(ca-cb)*basis[1].dudx,0.};
double dfdy[2] = {dcdy[0] + dhdeta(eta_array[0])*(ca-cb)*basis[1].dudy,0.};
double divgradc[2] = {M_*(dfdx[0]*dtestdx + dfdy[0]*dtestdy),
M_*(dfdx[1]*dtestdx + dfdy[1]*dtestdy)};
return ct + t_theta_*divgradc[0] + 0.*(1.-t_theta_)*divgradc[1];
}
RES_FUNC(residual_eta_kks_)
{
//derivatives of the test function
double dtestdx = basis[eqn_id].dphidx[i];
double dtestdy = basis[eqn_id].dphidy[i];
//double dtestdz = basis[0].dphidz[i];
//test function
double test = basis[eqn_id].phi[i];
//u, phi
double c[2] = {basis[0].uu, basis[0].uuold};
double eta[2] = {basis[eqn_id].uu, basis[eqn_id].uuold};
double detadx[2] = {basis[eqn_id].dudx, basis[eqn_id].duolddx};
double detady[2] = {basis[eqn_id].dudy, basis[eqn_id].duolddy};
double eta_array[N_];
double eta_array_old[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
eta_array_old[kk] = basis[kk_off].uuold;
}
double ca,cb;
solve_kks(c[0],eta_array,ca,cb);
double etat = (eta[0]-eta[1])/dt_*test;
double F[2] = {f_beta(cb)-f_alpha(ca) - (cb - ca)*df_alphadc(ca),
f_beta(c_b[1])-f_alpha(c_a[1]) - (c_b[1] - c_a[1])*df_betadc(c_b[1])};
const int k = eqn_id - eqn_off_;
double dfdeta[2] = {L_*(F[0]*dhdeta(eta_array[0]) + w_*dgdeta(eta_array,k) )*test,
L_*(F[1]*dhdeta(eta_array_old[0]) + w_*dgdeta(eta_array_old,k))*test};
double divgradeta[2] = {L_*k_eta_*(detadx[0]*dtestdx + detady[0]*dtestdy),
L_*k_eta_*(detadx[1]*dtestdx + detady[1]*dtestdy)};//(grad u,grad phi)
return etat + t_theta_*divgradeta[0] + t_theta_*dfdeta[0] + 0.*(1.-t_theta_)*divgradeta[1] + 0.*(1.-t_theta_)*dfdeta[1];
}
INI_FUNC(init_c_)
{
return c0_ + eps_*(cos(0.105*x)*cos(0.11*y)
+ cos(0.13*x)*cos(0.087*y)*cos(0.13*x)*cos(0.087*y)
+ cos(0.025*x-0.15*y)*cos(0.07*x-0.02*y)
);
}
INI_FUNC(init_eta_)
{
const double i = (double)(eqn_id - eqn_off_ + 1);
return eps_eta_*std::pow(cos((0.01*i)*x-4.)*cos((0.007+0.01*i)*y)
+ cos((0.11+0.01*i)*x)*cos((0.11+0.01*i)*y)
+ psi_*std::pow(cos((0.046+0.001*i)*x+(0.0405+0.001*i)*y)
*cos((0.031+0.001*i)*x-(0.004+0.001*i)*y),2
),2
);
}
RES_FUNC(residual_c_alpha_g_)
{
//globally coupled global kks equation
double test = basis[eqn_id].phi[i];
double c = basis[0].uu;
double ca = basis[1].uu;
double cb = basis[2].uu;
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
}
return (h(eta_array)*cb + (1.- h(eta_array))*ca - c)*test;
}
RES_FUNC(residual_c_beta_g_)
{
//globally coupled global kks equation
double test = basis[eqn_id].phi[i];
double ca = basis[1].uu;
double cb = basis[2].uu;
return (df_betadc(cb) - df_alphadc(ca))*test;
}
PRE_FUNC(prec_c_alpha_)
{
double test = basis[0].phi[i];
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
}
return (1.-h(eta_array)) * basis[eqn_id].phi[j]*test;
//return basis[eqn_id].phi[j]*test;
}
RES_FUNC(residual_c_alpha_l_)
{
//globally coupled local kks equation
double test = basis[eqn_id].phi[i];
double cc = basis[0].uu;
double ca = basis[1].uu;
//double cb = basis[2].uu;
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
}
solve_kks(cc,eta_array);
//solve_kks_exact(cc,eta_array);
const double val = ca-c_a[0];
// const double hh = h(eta_array);
// const double val = (-1.+2.*hh)*ca-(-cc +(c_beta_ + c_alpha_)*hh);
return val*test;
}
RES_FUNC(residual_c_beta_l_)
{
//globally coupled local kks equation
double test = basis[eqn_id].phi[i];
double cc = basis[0].uu;
//double ca = basis[1].uu;
double cb = basis[2].uu;
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off].uu;
}
solve_kks(cc,eta_array);
//solve_kks_exact(cc,eta_array);
const double val = cb-c_b[0];
// const double hh = h(eta_array);
// const double val = (-1.+2.*hh)*cb-(cc +(c_beta_ + c_alpha_)*(hh-1.));
// std::cout<<val<<" "<<val*test<<std::endl;
return val*test;
}
PRE_FUNC(prec_c_beta_)
{
double test = basis[eqn_id].phi[i];
double c_b = basis[eqn_id].phi[j];
//return df_betadc(c_b)*c_b*test;
return c_b*test;
}
INI_FUNC(init_c_alpha_)
{
double c = init_c_(x,y,z,0);
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = init_eta_(x,y,z,kk_off);
}
return c-h(eta_array)*(c_beta_ - c_alpha_);
}
INI_FUNC(init_c_beta_)
{
double c = init_c_(x,y,z,0);
double eta_array[N_];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = init_eta_(x,y,z,kk_off);
}
return c+(1-h(eta_array))*(c_beta_ - c_alpha_);
}
PPR_FUNC(postproc_c_b_)
{
//cn will need eta_array here...
double cc = u[0];
double phi = u[eqn_off_];
solve_kks(cc,&phi);
//solve_kks_exact(cc,&phi);
return c_b[0];
}
PPR_FUNC(postproc_c_a_)
{
//cn will need eta_array here...
double cc = u[0];
double phi = u[eqn_off_];
solve_kks(cc,&phi);
//solve_kks_exact(cc,&phi);
return c_a[0];
}
PPR_FUNC(postproc_h_)
{
//cn will need eta_array here...
//double cc = u[0];
double phi = u[eqn_off_];
return h(&phi);
}
PPR_FUNC(postproc_c_)
{
//cn will need eta_array here...
double cc = u[0];
double phi = u[eqn_off_];
solve_kks(cc,&phi);
//solve_kks_exact(cc,&phi);
return (1.-h(&phi))*c_a[0]+h(&phi)*c_b[0];
}
}//namespace pfhub2
namespace cerium{
//https://iopscience.iop.org/article/10.1088/2053-1591/ac1c32
//units are in J, mm, s
//note that 10^6 kJ/m^3 in figure 2 is J/mm^3
//free energy density f_m = f_p(c) = = 4 (c - .5)^2 - 1
//f_m'(c) = 8 (c - 1/2)
// = 2 am (c - bm)
//f_h(c) = 30 (c - 2/3)^2 - 8
//f_h'(c) = 60 (c - 2/3)
// = 2 ah (c - bh)
//assume ordering is p, h, m; c; displacement
const double am = 4.;// J/mm^3
const double bm = .5;// mole fraction H
const double cm = 1.;
const double ah = 30.;// J/mm^3
const double bh = 2./3.;// mole fraction H
const double ch = 8.;
const double m = 4.6e-3;// mm^3/J/s
// const double M[3][3] = {
// {0.,m,m},
// {m,0.,m},
// {m,m,0.}
// };
const double es = 3.9e-5;// J/mm
// const double e2[3][3] = {
// {0.,es,es},
// {es,0.,es},
// {es,es,0}
// };
const double h = 1.85e2;// J/mm^3
// const double H[3][3] = {
// {0.,h,h},
// {h,0.,h},
// {h,h,0.}
// };
const double D[3] = {1.e-5,3.5e-5,3.5e-5};// mm^2/s
const double e0 = .2;
const double E = 3.4e3;// J/mm^3
const double nu = .24;
double dG[3][3] = {
{0.,0.,0.},
{0.,0.,0.},
{0.,0.,0.}
};
//solve eqn 5
void solve_kks(const double cc, //c
const double pp, //phi_p
const double ph, //phi_h
const double pm, //phi_m
double &cp,
double &ch,
double &cm)
{
const double d = am*ph + ah*pm + ah*pp;
cp = -(-ah*cc + ah*bh*ph - am*bm*ph)/d;
ch = -(-am*cc - ah*bh*pm + am*bm*pm - ah*bh*pp + am*bm*pp)/d;
cm = -(-ah*cc + ah*bh*ph - am*bm*ph)/d;
}
const double fm(const int c)
{
return am*(c-bm)*(c-bm)-cm;
}
const double fp(const int c)
{
return fm(c);
}
const double fh(const int c)
{
return ah*(c-bh)*(c-bh)-ch;
}
const double dfm(const int c)
{
return 2.*am*(c-bm);
}
const double dfp(const int c)
{
return dfm(c);
}
const double dfh(const int c)
{
return 2.*ah*(c-bh);
}
//g10 = ghp = -gph
const double g10(const double ch,const double cp)
{
return fh(ch) - fp(cp) - .5*(dfh(ch) + dfp(cp))*(ch - cp);
}
//g20 = gmp = - gpm
const double g20(const double cm, const double cp)
{
return fm(cm) - fp(cp) - .5*(dfm(cm) + dfp(cp))*(cm - cp);
}
//g21 = gmh = -ghm
const double g21(const double cm, const double ch)
{
return fm(cm) - fh(ch) - .5*(dfm(cm) + dfh(ch))*(cm - ch);
}
//note that there is a difference in the lapace terms by a factor of 2
//depending on summation; see cerium.nb
RES_FUNC(residual_p_)
{
const double ut = (basis[eqn_id].uu-basis[eqn_id].uuold)/dt_*basis[eqn_id].phi[i];
const double p[3] = {basis[0].uu, basis[1].uu, basis[2].uu};
const double lp[3] = {-(basis[0].dudx*basis[eqn_id].dphidx[i]
+ basis[0].dudy*basis[eqn_id].dphidy[i]
+ basis[0].dudz*basis[eqn_id].dphidz[i]),
-(basis[1].dudx*basis[eqn_id].dphidx[i]
+ basis[1].dudy*basis[eqn_id].dphidy[i]
+ basis[1].dudz*basis[eqn_id].dphidz[i]),
-(basis[2].dudx*basis[eqn_id].dphidx[i]
+ basis[2].dudy*basis[eqn_id].dphidy[i]
+ basis[2].dudz*basis[eqn_id].dphidz[i])};
double c[3] = {0.,0.,0.};
solve_kks(basis[3].uu, //c
p[0], //phi_p
p[1], //phi_h
p[2], //phi_m
c[0],
c[1],
c[2]);
dG[1][0] = g10(c[1],c[0]);
dG[2][0] = g20(c[2],c[0]);
const double rhs = (2.*es*m*lp[0])/3. - (es*m*lp[1])/3. - (es*m*lp[2])/3.
- 6.*m*dG[1][0]*p[0]*p[1]*basis[eqn_id].phi[i]
+ h*m*pow(p[0],2)*p[1]*basis[eqn_id].phi[i]
- h*m*p[0]*pow(p[1],2)*basis[eqn_id].phi[i]
- 6.*m*dG[2][0]*p[0]*p[2]*basis[eqn_id].phi[i]
+ h*m*pow(p[0],2)*p[2]*basis[eqn_id].phi[i]
- h*m*p[0]*pow(p[2],2)*basis[eqn_id].phi[i];
return ut-rhs;
}
RES_FUNC(residual_h_)
{
const double ut = (basis[eqn_id].uu-basis[eqn_id].uuold)/dt_*basis[eqn_id].phi[i];
const double p[3] = {basis[0].uu, basis[1].uu, basis[2].uu};
const double lp[3] = {-(basis[0].dudx*basis[eqn_id].dphidx[i]
+ basis[0].dudy*basis[eqn_id].dphidy[i]
+ basis[0].dudz*basis[eqn_id].dphidz[i]),
-(basis[1].dudx*basis[eqn_id].dphidx[i]
+ basis[1].dudy*basis[eqn_id].dphidy[i]
+ basis[1].dudz*basis[eqn_id].dphidz[i]),
-(basis[2].dudx*basis[eqn_id].dphidx[i]
+ basis[2].dudy*basis[eqn_id].dphidy[i]
+ basis[2].dudz*basis[eqn_id].dphidz[i])};
double c[3] = {0.,0.,0.};
solve_kks(basis[3].uu, //c
p[0], //phi_p
p[1], //phi_h
p[2], //phi_m
c[0],
c[1],
c[2]);
dG[0][1] = -g10(c[1],c[0]);
dG[2][1] = g21(c[2],c[1]);
const double rhs = -(es*m*lp[0])/3. + (2.*es*m*lp[1])/3. - (es*m*lp[2])/3.
- 6.*m*dG[0][1]*p[0]*p[1]*basis[eqn_id].phi[i]
- h*m*pow(p[0],2)*p[1]*basis[eqn_id].phi[i]
+ h*m*p[0]*pow(p[1],2)*basis[eqn_id].phi[i]
- 6.*m*dG[2][1]*p[1]*p[2]*basis[eqn_id].phi[i]
+ h*m*pow(p[1],2)*p[2]*basis[eqn_id].phi[i]
- h*m*p[1]*pow(p[2],2)*basis[eqn_id].phi[i];
return ut-rhs;
}
RES_FUNC(residual_m_)
{
const double ut = (basis[eqn_id].uu-basis[eqn_id].uuold)/dt_*basis[eqn_id].phi[i];
const double p[3] = {basis[0].uu, basis[1].uu, basis[2].uu};
const double lp[3] = {-(basis[0].dudx*basis[eqn_id].dphidx[i]
+ basis[0].dudy*basis[eqn_id].dphidy[i]
+ basis[0].dudz*basis[eqn_id].dphidz[i]),
-(basis[1].dudx*basis[eqn_id].dphidx[i]
+ basis[1].dudy*basis[eqn_id].dphidy[i]
+ basis[1].dudz*basis[eqn_id].dphidz[i]),
-(basis[2].dudx*basis[eqn_id].dphidx[i]
+ basis[2].dudy*basis[eqn_id].dphidy[i]
+ basis[2].dudz*basis[eqn_id].dphidz[i])};
double c[3] = {0.,0.,0.};
solve_kks(basis[3].uu, //c
p[0], //phi_p
p[1], //phi_h
p[2], //phi_m
c[0],
c[1],
c[2]);
dG[0][2] = g20(c[2],c[0]);
dG[1][2] = -g21(c[2],c[1]);
const double rhs = -(es*m*lp[0])/3. - (es*m*lp[1])/3. + (2.*es*m*lp[2])/3.
- 6.*m*dG[0][2]*p[0]*p[2]*basis[eqn_id].phi[i]
- h*m*pow(p[0],2)*p[2]*basis[eqn_id].phi[i]
- 6.*m*dG[1][2]*p[1]*p[2]*basis[eqn_id].phi[i]
- h*m*pow(p[1],2)*p[2]*basis[eqn_id].phi[i]
+ h*m*p[0]*pow(p[2],2)*basis[eqn_id].phi[i]
+ h*m*p[1]*pow(p[2],2)*basis[eqn_id].phi[i];
return ut-rhs;
}
RES_FUNC(residual_c_)
{
const double ut = (basis[eqn_id].uu-basis[eqn_id].uuold)/dt_*basis[eqn_id].phi[i];
const double p[3] = {basis[0].uu, basis[1].uu, basis[2].uu};
double c[3] = {0.,0.,0.};
solve_kks(basis[3].uu, //c
p[0], //phi_p
p[1], //phi_h
p[2], //phi_m
c[0],
c[1],
c[2]);
//the trouble is how to get gradient of c[0],c[1],c[2]
//the kks paper has a solution
const double rhs =0.;
return ut-rhs;
}
}//namespace cerium
// #define RES_FUNC_TPETRA(NAME) double NAME(const GPUBasis * const * basis,
#define RES_FUNC_TPETRA(NAME) double NAME(GPUBasis * basis[], \
const int &i,\
const double &dt_,\
const double &dtold_,\
const double &t_theta_,\
const double &t_theta2_,\
const double &time,\
const int &eqn_id, \
const double &vol, \
const double &rand)
#define PRE_FUNC_TPETRA(NAME) double NAME(const GPUBasis *basis, \
const int &i,\
const int &j,\
const double &dt_,\
const double &t_theta_,\
const int &eqn_id)
#define NBC_FUNC_TPETRA(NAME) double NAME(const GPUBasis *basis,\
const int &i,\
const double &dt_,\
const double &dtold_,\
const double &t_theta_,\
const double &t_theta2_,\
const double &time)
namespace tpetra{//we can just put the KOKKOS... around the other dbc_zero_ later...
namespace heat{
TUSAS_DEVICE
double k_d = 1.;
TUSAS_DEVICE
double rho_d = 1.;
TUSAS_DEVICE
double cp_d = 1.;
TUSAS_DEVICE
double tau0_d = 1.;
TUSAS_DEVICE
double W0_d = 1.;
TUSAS_DEVICE
double deltau_d = 1.;
TUSAS_DEVICE
double uref_d = 0.;
double k_h = 1.;
double rho_h = 1.;
double cp_h = 1.;
double tau0_h = 1.;
double W0_h = 1.;
double deltau_h = 1.;
double uref_h = 0.;
//KOKKOS_INLINE_FUNCTION
DBC_FUNC(dbc_zero_)
{
return 0.;
}
//KOKKOS_INLINE_FUNCTION
INI_FUNC(init_heat_test_)
{
const double pi = 3.141592653589793;
return sin(pi*x)*sin(pi*y);
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_heat_test_)
{
//right now, it is probably best to handle nondimensionalization of temperature via:
// theta = (T-T_s)/(T_l-T_s) external to this module by multiplication of (T_l-T_s)=delta T
const double ut = rho_d*cp_d/tau0_d*deltau_d*(basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*basis[eqn_id]->phi[i];
const double f[3] = {k_d/W0_d/W0_d*deltau_d*(basis[eqn_id]->dudx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->dudy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->dudz*basis[eqn_id]->dphidz[i]),
k_d/W0_d/W0_d*deltau_d*(basis[eqn_id]->duolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duolddz*basis[eqn_id]->dphidz[i]),
k_d/W0_d/W0_d*deltau_d*(basis[eqn_id]->duoldolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duoldolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duoldolddz*basis[eqn_id]->dphidz[i])};
//std::cout<<std::scientific<<f[0]<<std::endl<<std::defaultfloat;
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_heat_test_dp_)) = residual_heat_test_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_heat_test_)
{
return rho_d*cp_d/tau0_d*deltau_d*basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i]
+ t_theta_*k_d/W0_d/W0_d*deltau_d*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_heat_test_dp_)) = prec_heat_test_;
PARAM_FUNC(param_)
{
double kk = plist->get<double>("k_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(k_d,&kk,sizeof(double));
#else
k_d = kk;
#endif
k_h = kk;
double rho = plist->get<double>("rho_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(rho_d,&rho,sizeof(double));
#else
rho_d = rho;
#endif
rho_h = rho;
double cp = plist->get<double>("cp_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(cp_d,&cp,sizeof(double));
#else
cp_d = cp;
#endif
cp_h = cp;
double tau0 = plist->get<double>("tau0_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(tau0_d,&tau0,sizeof(double));
#else
tau0_d = tau0;
#endif
tau0_h = tau0;
double W0 = plist->get<double>("W0_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(W0_d,&W0,sizeof(double));
#else
W0_d = W0;
#endif
W0_h = W0;
double deltau = plist->get<double>("deltau_",1.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(deltau_d,&deltau,sizeof(double));
#else
deltau_d = deltau;
#endif
deltau_h = deltau;
double uref = plist->get<double>("uref_",0.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(uref_d,&uref,sizeof(double));
#else
uref_d = uref;
#endif
uref_h = uref;
}
PPR_FUNC(postproc_)
{
//exact solution is: u[x,y,t]=exp(-2 pi^2 k t)sin(pi x)sin(pi y)
const double uu = u[0];
const double x = xyz[0];
const double y = xyz[1];
const double pi = 3.141592653589793;
const double s= exp(-2.*k_h*pi*pi*time)*sin(pi*x)*sin(pi*y);
return s-uu;
}
}//namespace heat
// the above solution is also a solution to the nonlinear problem:
// u_t - div ( u grad u) + 2 pi^2 (1-u) + u_x^2 + u_y^2
// we replace u_x^2 + u_y^2 with a forcing term f2(x,y,t)
KOKKOS_INLINE_FUNCTION
double f1(const double &u)
{
const double pi = 3.141592653589793;
return 2.*pi*pi*u*(1.-u);
}
KOKKOS_INLINE_FUNCTION
double f2(const double &x, const double &y, const double &t)
{
const double pi = 3.141592653589793;
const double pix = pi*x;
const double piy = pi*y;
const double pi2 = pi*pi;
return exp(-4.*pi2*t)*pi2*(cos(piy)*cos(piy)*sin(pix)*sin(pix) + cos(pix)*cos(pix)*sin(piy)*sin(piy));
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_nlheatimr_test_)
{
const double u_m = t_theta_*basis[eqn_id]->uu + (1. - t_theta_)*basis[eqn_id]->uuold;
const double dudx_m = t_theta_*basis[eqn_id]->dudx + (1. - t_theta_)*basis[eqn_id]->duolddx;
const double dudy_m = t_theta_*basis[eqn_id]->dudy + (1. - t_theta_)*basis[eqn_id]->duolddy;
const double dudz_m = t_theta_*basis[eqn_id]->dudz + (1. - t_theta_)*basis[eqn_id]->duolddz;
const double t_m = time + t_theta_*dt_;
const double x = basis[0]->xx;
const double y = basis[0]->yy;
const double divgrad = u_m*(dudx_m*basis[eqn_id]->dphidx[i]
+ dudy_m*basis[eqn_id]->dphidy[i]
+ dudz_m*basis[eqn_id]->dphidz[i]);
return (basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*basis[eqn_id]->phi[i]
+ divgrad
+ f1(u_m)*basis[eqn_id]->phi[i]
+ f2(x,y,t_m)*basis[eqn_id]->phi[i];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_nlheatimr_test_dp_)) = residual_nlheatimr_test_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_nlheatcn_test_)
{
const double u[2] = {basis[eqn_id]->uu, basis[eqn_id]->uuold};
const double dudx[2] = {basis[eqn_id]->dudx, basis[eqn_id]->duolddx};
const double dudy[2] = {basis[eqn_id]->dudy, basis[eqn_id]->duolddy};
const double dudz[2] = {basis[eqn_id]->dudz, basis[eqn_id]->duolddz};
//const double dudz_m = t_theta_*basis[eqn_id].dudz + (1. - t_theta_)*basis[eqn_id].duolddz;
const double t[2] = {time, time+dt_};
const double x = basis[0]->xx;
const double y = basis[0]->yy;
const double divgrad = t_theta_*
u[0]*(dudx[0]*basis[eqn_id]->dphidx[i]
+ dudy[0]*basis[eqn_id]->dphidy[i]
+ dudz[0]*basis[eqn_id]->dphidz[i])
+ (1. - t_theta_)*
u[1]*(dudx[1]*basis[eqn_id]->dphidx[i]
+ dudy[1]*basis[eqn_id]->dphidy[i]
+ dudz[1]*basis[eqn_id]->dphidz[i]);
return (basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*basis[eqn_id]->phi[i]
+ divgrad
+ (t_theta_*f1(u[0])
+ (1. - t_theta_)*f1(u[1]))*basis[eqn_id]->phi[i]
+ (t_theta_*f2(x,y,t[0])
+ (1. - t_theta_)*f2(x,y,t[1]))*basis[eqn_id]->phi[i];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_nlheatcn_test_dp_)) = residual_nlheatcn_test_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_nlheatcn_test_)
{
return basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i]
+ t_theta_*basis[eqn_id].uu
*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_nlheatcn_test_dp_)) = prec_nlheatcn_test_;
//}//namespace heat
namespace localprojection
{
RES_FUNC_TPETRA(residual_u1_)
{
const double test = basis[eqn_id]->phi[i];
//std::cout<<basis[0]->uu*basis[0]->uu+basis[1]->uu*basis[1]->uu<<std::endl;
const double u2[3] = {basis[1]->uu, basis[1]->uuold, basis[1]->uuoldold};
const double f[3] = {u2[0]*test,
u2[1]*test,
u2[2]*test};
const double ut = (basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*test;
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC_TPETRA(residual_u2_)
{
const double test = basis[eqn_id]->phi[i];
const double u1[3] = {basis[0]->uu, basis[0]->uuold, basis[0]->uuoldold};
const double f[3] = {-u1[0]*test,
-u1[1]*test,
-u1[2]*test};
const double ut = (basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*test;
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
INI_FUNC(init_u1_)
{
return 1.;
}
INI_FUNC(init_u2_)
{
return 0.;
}
PPR_FUNC(postproc_u1_)
{
return cos(time);
}
PPR_FUNC(postproc_u2_)
{
return sin(time);
}
PPR_FUNC(postproc_norm_)
{
return sqrt(u[0]*u[0]+u[1]*u[1])-1.;
}
PPR_FUNC(postproc_u1err_)
{
return cos(time)-u[0];
}
PPR_FUNC(postproc_u2err_)
{
return sin(time)-u[1];
}
}//namespace localprojection
namespace farzadi3d
{
TUSAS_DEVICE
double absphi = 0.9997; //1.
//double absphi = 0.999999; //1.
TUSAS_DEVICE
double k = 0.14;
TUSAS_DEVICE //0.5
double eps = 0.0;
TUSAS_DEVICE
double lambda = 10.;
TUSAS_DEVICE
double D_liquid = 3.e-9; //1.e-11 //m^2/s
TUSAS_DEVICE
double m = -2.6;
TUSAS_DEVICE //-2.6 100.
double c_inf = 3.; //1.
TUSAS_DEVICE
double G = 3.e5;
TUSAS_DEVICE //k/m
double R = 0.003;
// TUSAS_DEVICE //m/s
// double V = 0.003;
TUSAS_DEVICE //m/s
double d0 = 5.e-9; //4.e-9 //m
// parameters to scale dimensional quantities
TUSAS_DEVICE
double delta_T0 = 47.9143;
TUSAS_DEVICE
double w0 = 5.65675e-8;
TUSAS_DEVICE
double tau0 = 6.68455e-6;
// TUSAS_DEVICE
// double Vp0 = .354508;
TUSAS_DEVICE
double l_T0 = 2823.43;
TUSAS_DEVICE
double D_liquid_ = 6.267;
TUSAS_DEVICE
double dT = 0.0;
// TUSAS_DEVICE
double base_height = 15.;
// TUSAS_DEVICE
double amplitude = 0.2;
//circle or sphere parameters
double r = 0.5;
double x0 = 20.0;
double y0 = 20.0;
double z0 = 20.0;
int C = 0;
double t_activate_farzadi = 0.0;
PARAM_FUNC(param_)
{
double k_p = plist->get<double>("k", 0.14);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(k,&k_p,sizeof(double));
#else
k = k_p;
#endif
double eps_p = plist->get<double>("eps", 0.0);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(eps,&eps_p,sizeof(double));
#else
eps = eps_p;
#endif
double lambda_p = plist->get<double>("lambda", 10.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(lambda,&lambda_p,sizeof(double));
#else
lambda = lambda_p;
#endif
double d0_p = plist->get<double>("d0", 5.e-9);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(d0,&d0_p,sizeof(double));
#else
d0 = d0_p;
#endif
double D_liquid_p = plist->get<double>("D_liquid", 3.e-9);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(D_liquid,&D_liquid_p,sizeof(double));
#else
D_liquid = D_liquid_p;
#endif
double m_p = plist->get<double>("m", -2.6);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(m,&m_p,sizeof(double));
#else
m = m_p;
#endif
double c_inf_p = plist->get<double>("c_inf", 3.);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(c_inf,&c_inf_p,sizeof(double));
#else
c_inf = c_inf_p;
#endif
double G_p = plist->get<double>("G", 3.e5);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(G,&G_p,sizeof(double));
#else
G = G_p;
#endif
double R_p = plist->get<double>("R", 0.003);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(R,&R_p,sizeof(double));
#else
R = R_p;
#endif
// added dT here
double dT_p = plist->get<double>("dT", 0.0);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(dT,&dT_p,sizeof(double));
#else
dT = dT_p;
#endif
double base_height_p = plist->get<double>("base_height", 15.);
// #ifdef TUSAS_HAVE_CUDA
// cudaMemcpyToSymbol(base_height,&base_height_p,sizeof(double));
// #else
base_height = base_height_p;
// #endif
double amplitude_p = plist->get<double>("amplitude", 0.2);
// #ifdef TUSAS_HAVE_CUDA
// cudaMemcpyToSymbol(amplitude,&litude_p,sizeof(double));
// #else
amplitude = amplitude_p;
// #endif
int C_p = plist->get<int>("C", 0);
C = C_p;
// circle or sphere parameters
double r_p = plist->get<double>("r", 0.5);
r = r_p;
double x0_p = plist->get<double>("x0", 20.0);
x0 = x0_p;
double y0_p = plist->get<double>("y0", 20.0);
y0 = y0_p;
double z0_p = plist->get<double>("z0", 20.0);
z0 = z0_p;
//double absphi_p = plist->get<double>("absphi", absphi);
//the calculated values need local vars to work....
//calculated values
double w0_p = lambda_p*d0_p/0.8839;
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(w0,&w0_p,sizeof(double));
#else
w0 = w0_p;
#endif
double tau0_p = (lambda_p*0.6267*w0_p*w0_p)/D_liquid_p;
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(tau0,&tau0_p,sizeof(double));
#else
tau0 = tau0_p;
#endif
// double V_p = R_p;
// #ifdef TUSAS_HAVE_CUDA
// cudaMemcpyToSymbol(V,&V_p,sizeof(double));
// #else
// V = V_p;
// #endif
// double Vp0_p = V_p*tau0_p/w0_p;
// #ifdef TUSAS_HAVE_CUDA
// cudaMemcpyToSymbol(Vp0,&Vp0_p,sizeof(double));
// #else
// Vp0 = Vp0_p;
// #endif
double delta_T0_p = abs(m_p)*c_inf_p*(1.-k_p)/k_p;
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(delta_T0,&delta_T0_p,sizeof(double));
#else
delta_T0 = delta_T0_p;
#endif
double l_T0_p = delta_T0_p/G_p;
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(l_T0,&l_T0_p,sizeof(double));
#else
l_T0 = l_T0_p;
#endif
double D_liquid__p = D_liquid_p*tau0_p/(w0_p*w0_p);
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(D_liquid_,&D_liquid__p,sizeof(double));
#else
D_liquid_ = D_liquid__p;
#endif
t_activate_farzadi = plist->get<double>("t_activate_farzadi", 0.0);
//std::cout<<l_T0<<" "<<G<<" "<<Vp0<<" "<<tau0<<" "<<w0<<std::endl;
}
//see tpetra::pfhub3 for a possibly better implementation of a,ap
KOKKOS_INLINE_FUNCTION
double a(const double &p,const double &px,const double &py,const double &pz, const double ep)
{
double val = 1. + ep;
val = (p*p < farzadi3d::absphi)&&(p*p > 1.-farzadi3d::absphi) ? (1.-3.*ep)*(1.+4.*ep/(1.-3.*ep)*
(px*px*px*px+py*py*py*py+pz*pz*pz*pz)/(px*px+py*py+pz*pz)/(px*px+py*py+pz*pz))
: 1. + ep;
// if(val!=val) std::cout<<farzadi3d::absphi<<" "<<1.-farzadi3d::absphi<<" "<<p*p<<" "<<px*px+py*py+pz*pz<<" "<<val<<" "<<
// (1.-3.*ep)*(1.+4.*ep/(1.-3.*ep)*
// (px*px*px*px+py*py*py*py+pz*pz*pz*pz)/(px*px+py*py+pz*pz)/(px*px+py*py+pz*pz))<<std::endl;
return val;
}
KOKKOS_INLINE_FUNCTION
double ap(const double &p,const double &px,const double &py,const double &pz,const double &pd, const double ep)
{
return (p*p < farzadi3d::absphi)&&(p*p > 1.-farzadi3d::absphi) ? 4.*ep*
(4.*pd*pd*pd*(px*px+py*py+pz*pz)-4.*pd*(px*px*px*px+py*py*py*py+pz*pz*pz*pz))
/(px*px+py*py+pz*pz)/(px*px+py*py+pz*pz)/(px*px+py*py+pz*pz)
: 0.;
}
//the current ordering in set_test_case is conc (u), phase (phi)
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_conc_farzadi_)
{
//right now, if explicit, we will have some problems with time derivates below
const double dtestdx = basis[eqn_id]->dphidx[i];
const double dtestdy = basis[eqn_id]->dphidy[i];
const double dtestdz = basis[eqn_id]->dphidz[i];
const double test = basis[eqn_id]->phi[i];
const double u[3] = {basis[eqn_id]->uu,basis[eqn_id]->uuold,basis[eqn_id]->uuoldold};
const int phi_id = eqn_id+1;
const double phi[3] = {basis[phi_id]->uu,basis[phi_id]->uuold,basis[phi_id]->uuoldold};
const double dphidx[3] = {basis[phi_id]->dudx,basis[phi_id]->duolddx,basis[phi_id]->duoldolddx};
const double dphidy[3] = {basis[phi_id]->dudy,basis[phi_id]->duolddy,basis[phi_id]->duoldolddy};
const double dphidz[3] = {basis[phi_id]->dudz,basis[phi_id]->duolddz,basis[phi_id]->duoldolddz};
const double ut = (1.+k)/2.*(u[0]-u[1])/dt_*test;
const double divgradu[3] = {D_liquid_*(1.-phi[0])/2.*(basis[eqn_id]->dudx*dtestdx + basis[eqn_id]->dudy*dtestdy + basis[eqn_id]->dudz*dtestdz),
D_liquid_*(1.-phi[1])/2.*(basis[eqn_id]->duolddx*dtestdx + basis[eqn_id]->duolddy*dtestdy + basis[eqn_id]->duolddz*dtestdz),
D_liquid_*(1.-phi[2])/2.*(basis[eqn_id]->duoldolddx*dtestdx + basis[eqn_id]->duoldolddy*dtestdy + basis[eqn_id]->duoldolddz*dtestdz)};//(grad u,grad phi)
const double normd[3] = {(phi[0]*phi[0] < absphi)&&(phi[0]*phi[0] > 0.) ? 1./sqrt(dphidx[0]*dphidx[0] + dphidy[0]*dphidy[0] + dphidz[0]*dphidz[0]) : 0.,
(phi[1]*phi[1] < absphi)&&(phi[1]*phi[1] > 0.) ? 1./sqrt(dphidx[1]*dphidx[1] + dphidy[1]*dphidy[1] + dphidz[1]*dphidz[1]) : 0.,
(phi[2]*phi[2] < absphi)&&(phi[2]*phi[2] > 0.) ? 1./sqrt(dphidx[2]*dphidx[2] + dphidy[2]*dphidy[2] + dphidz[2]*dphidz[2]) : 0.}; //cn lim grad phi/|grad phi| may -> 1 here?
//we need to double check these terms with temporal derivatives....
const double phit = (phi[0]-phi[1])/dt_;
const double j_coef[3] = {(1.+(1.-k)*u[0])/sqrt(8.)*normd[0]*phit,
(1.+(1.-k)*u[1])/sqrt(8.)*normd[1]*phit,
(1.+(1.-k)*u[2])/sqrt(8.)*normd[2]*phit};
const double divj[3] = {j_coef[0]*(dphidx[0]*dtestdx + dphidy[0]*dtestdy + dphidz[0]*dtestdz),
j_coef[1]*(dphidx[1]*dtestdx + dphidy[1]*dtestdy + dphidz[1]*dtestdz),
j_coef[2]*(dphidx[2]*dtestdx + dphidy[2]*dtestdy + dphidz[2]*dtestdz)};
double phitu[3] = {-.5*phit*(1.+(1.-k)*u[0])*test,
-.5*phit*(1.+(1.-k)*u[1])*test,
-.5*phit*(1.+(1.-k)*u[2])*test};
//double val = ut + t_theta_*divgradu + t_theta_*divj + t_theta_*phitu;
//printf("%lf\n",val);
const double f[3] = {divgradu[0] + divj[0] + phitu[0],
divgradu[1] + divj[1] + phitu[1],
divgradu[2] + divj[2] + phitu[2]};
return (ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]));
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_conc_farzadi_dp_)) = residual_conc_farzadi_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phase_farzadi_)
{
//derivatives of the test function
const double dtestdx = basis[eqn_id]->dphidx[i];
const double dtestdy = basis[eqn_id]->dphidy[i];
const double dtestdz = basis[eqn_id]->dphidz[i];
//test function
const double test = basis[eqn_id]->phi[i];
//u, phi
const int u_id = eqn_id-1;
const double u[3] = {basis[u_id]->uu,basis[u_id]->uuold,basis[u_id]->uuoldold};
const double phi[3] = {basis[eqn_id]->uu,basis[eqn_id]->uuold,basis[eqn_id]->uuoldold};
const double dphidx[3] = {basis[eqn_id]->dudx,basis[eqn_id]->duolddx,basis[eqn_id]->duoldolddx};
const double dphidy[3] = {basis[eqn_id]->dudy,basis[eqn_id]->duolddy,basis[eqn_id]->duoldolddy};
const double dphidz[3] = {basis[eqn_id]->dudz,basis[eqn_id]->duolddz,basis[eqn_id]->duoldolddz};
const double as[3] = {a(phi[0],dphidx[0],dphidy[0],dphidz[0],eps),
a(phi[1],dphidx[1],dphidy[1],dphidz[1],eps),
a(phi[2],dphidx[2],dphidy[2],dphidz[2],eps)};
const double divgradphi[3] = {as[0]*as[0]*(dphidx[0]*dtestdx + dphidy[0]*dtestdy + dphidz[0]*dtestdz),
as[1]*as[1]*(dphidx[1]*dtestdx + dphidy[1]*dtestdy + dphidz[1]*dtestdz),
as[2]*as[2]*(dphidx[2]*dtestdx + dphidy[2]*dtestdy + dphidz[2]*dtestdz)};//(grad u,grad phi)
const double mob[3] = {(1.+(1.-k)*u[0])*as[0]*as[0],(1.+(1.-k)*u[1])*as[1]*as[1],(1.+(1.-k)*u[2])*as[2]*as[2]};
const double phit = (phi[0]-phi[1])/dt_*test;
//double curlgrad = -dgdtheta*dphidy*dtestdx + dgdtheta*dphidx*dtestdy;
const double curlgrad[3] = {as[0]*(dphidx[0]*dphidx[0] + dphidy[0]*dphidy[0] + dphidz[0]*dphidz[0])
*(ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidx[0],eps)*dtestdx
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidy[0],eps)*dtestdy
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidz[0],eps)*dtestdz),
as[1]*(dphidx[1]*dphidx[1] + dphidy[1]*dphidy[1] + dphidz[1]*dphidz[1])
*(ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidx[1],eps)*dtestdx
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidy[1],eps)*dtestdy
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidz[1],eps)*dtestdz),
as[2]*(dphidx[2]*dphidx[2] + dphidy[2]*dphidy[2] + dphidz[2]*dphidz[2])
*(ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidx[2],eps)*dtestdx
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidy[2],eps)*dtestdy
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidz[2],eps)*dtestdz)};
const double gp1[3] = {-(phi[0] - phi[0]*phi[0]*phi[0])*test,
-(phi[1] - phi[1]*phi[1]*phi[1])*test,
-(phi[2] - phi[2]*phi[2]*phi[2])*test};
//note in paper eq 39 has g3 different
//here (as implemented) our g3 = lambda*(1. - phi[0]*phi[0])*(1. - phi[0]*phi[0])
//matches farzadi eq 10
const double hp1u[3] = {lambda*(1. - phi[0]*phi[0])*(1. - phi[0]*phi[0])*(u[0])*test,
lambda*(1. - phi[1]*phi[1])*(1. - phi[1]*phi[1])*(u[1])*test,
lambda*(1. - phi[2]*phi[2])*(1. - phi[2]*phi[2])*(u[2])*test};
const double f[3] = {(divgradphi[0] + curlgrad[0] + gp1[0] + hp1u[0])/mob[0],
(divgradphi[1] + curlgrad[1] + gp1[1] + hp1u[1])/mob[1],
(divgradphi[2] + curlgrad[2] + gp1[2] + hp1u[2])/mob[2]};
const double val = phit
+ (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
return mob[0]*val;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_farzadi_dp_)) = residual_phase_farzadi_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phase_farzadi_uncoupled_)
{
//test function
const double test = basis[eqn_id]->phi[i];
//u, phi
const int u_id = eqn_id-1;
const double u[3] = {basis[u_id]->uu,basis[u_id]->uuold,basis[u_id]->uuoldold};
const double phi[3] = {basis[eqn_id]->uu,basis[eqn_id]->uuold,basis[eqn_id]->uuoldold};
const double dphidx[3] = {basis[eqn_id]->dudx,basis[eqn_id]->duolddx,basis[eqn_id]->duoldolddx};
const double dphidy[3] = {basis[eqn_id]->dudy,basis[eqn_id]->duolddy,basis[eqn_id]->duoldolddy};
const double dphidz[3] = {basis[eqn_id]->dudz,basis[eqn_id]->duolddz,basis[eqn_id]->duoldolddz};
const double as[3] = {a(phi[0],dphidx[0],dphidy[0],dphidz[0],eps),
a(phi[1],dphidx[1],dphidy[1],dphidz[1],eps),
a(phi[2],dphidx[2],dphidy[2],dphidz[2],eps)};
const double mob[3] = {(1.+(1.-k)*u[0])*as[0]*as[0],(1.+(1.-k)*u[1])*as[1]*as[1],(1.+(1.-k)*u[2])*as[2]*as[2]};
const double x = basis[eqn_id]->xx;
// frozen temperature approximation: linear pulling of the temperature field
const double xx = x*w0;
//cn this should probablly be: (time+dt_)*tau
const double tt[3] = {(time+dt_)*tau0,time*tau0,(time-dtold_)*tau0};
const double g4[3] = {((dT < 0.001) ? G*(xx-R*tt[0])/delta_T0 : dT),
((dT < 0.001) ? G*(xx-R*tt[1])/delta_T0 : dT),
((dT < 0.001) ? G*(xx-R*tt[2])/delta_T0 : dT)};
const double hp1g4[3] = {lambda*(1. - phi[0]*phi[0])*(1. - phi[0]*phi[0])*(g4[0])*test,
lambda*(1. - phi[1]*phi[1])*(1. - phi[1]*phi[1])*(g4[1])*test,
lambda*(1. - phi[2]*phi[2])*(1. - phi[2]*phi[2])*(g4[2])*test};
const double val = tpetra::farzadi3d::residual_phase_farzadi_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double rv = val/mob[0]
+ (1.-t_theta2_)*t_theta_*hp1g4[0]/mob[0]
+ (1.-t_theta2_)*(1.-t_theta_)*hp1g4[1]/mob[1]
+.5*t_theta2_*((2.+dt_/dtold_)*hp1g4[1]/mob[1]-dt_/dtold_*hp1g4[2]/mob[2]);
return mob[0]*rv;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_farzadi_uncoupled_dp_)) = residual_phase_farzadi_uncoupled_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phase_farzadi_coupled_)
{
//test function
const double test = basis[eqn_id]->phi[i];
//u, phi
const int u_id = eqn_id-1;
const int theta_id = eqn_id+1;
const double u[3] = {basis[u_id]->uu,basis[u_id]->uuold,basis[u_id]->uuoldold};
const double phi[3] = {basis[eqn_id]->uu,basis[eqn_id]->uuold,basis[eqn_id]->uuoldold};
const double dphidx[3] = {basis[eqn_id]->dudx,basis[eqn_id]->duolddx,basis[eqn_id]->duoldolddx};
const double dphidy[3] = {basis[eqn_id]->dudy,basis[eqn_id]->duolddy,basis[eqn_id]->duoldolddy};
const double dphidz[3] = {basis[eqn_id]->dudz,basis[eqn_id]->duolddz,basis[eqn_id]->duoldolddz};
const double as[3] = {a(phi[0],dphidx[0],dphidy[0],dphidz[0],eps),
a(phi[1],dphidx[1],dphidy[1],dphidz[1],eps),
a(phi[2],dphidx[2],dphidy[2],dphidz[2],eps)};
const double mob[3] = {(1.+(1.-k)*u[0])*as[0]*as[0],(1.+(1.-k)*u[1])*as[1]*as[1],(1.+(1.-k)*u[2])*as[2]*as[2]};
const double theta[3] = {basis[theta_id]->uu,basis[theta_id]->uuold,basis[theta_id]->uuoldold};
const double g4[3] = {theta[0],theta[1],theta[2]};
const double hp1g4[3] = {lambda*(1. - phi[0]*phi[0])*(1. - phi[0]*phi[0])*(g4[0])*test,
lambda*(1. - phi[1]*phi[1])*(1. - phi[1]*phi[1])*(g4[1])*test,
lambda*(1. - phi[2]*phi[2])*(1. - phi[2]*phi[2])*(g4[2])*test};
const double val = tpetra::farzadi3d::residual_phase_farzadi_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double rv = val/mob[0]
+ (1.-t_theta2_)*t_theta_*hp1g4[0]/mob[0]
+ (1.-t_theta2_)*(1.-t_theta_)*hp1g4[1]/mob[1]
+.5*t_theta2_*((2.+dt_/dtold_)*hp1g4[1]/mob[1]-dt_/dtold_*hp1g4[2]/mob[2]);
return mob[0]*rv;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_farzadi_coupled_dp_)) = residual_phase_farzadi_coupled_;
RES_FUNC_TPETRA(residual_conc_farzadi_activated_)
{
const double val = tpetra::farzadi3d::residual_conc_farzadi_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double u[2] = {basis[eqn_id]->uu,basis[eqn_id]->uuold};
// Coefficient to turn Farzadi evolution off until a specified time
const double delta = 1.0e12;
const double sigmoid_var = delta * (time-t_activate_farzadi/tau0);
const double sigmoid = 0.5 * (1.0 + sigmoid_var / (std::sqrt(1.0 + sigmoid_var*sigmoid_var)));
//std::cout<<val * sigmoid + (u[1]-u[0]) * (1.0 - sigmoid)*basis[eqn_id]->phi[i]<<std::endl;
return val * sigmoid + (u[1]-u[0]) * (1.0 - sigmoid)*basis[eqn_id]->phi[i];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_conc_farzadi_activated_dp_)) = residual_conc_farzadi_activated_;
RES_FUNC_TPETRA(residual_phase_farzadi_coupled_activated_)
{
const double val = tpetra::farzadi3d::residual_phase_farzadi_coupled_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double phi[2] = {basis[eqn_id]->uu,basis[eqn_id]->uuold};
// Coefficient to turn Farzadi evolution off until a specified time
const double delta = 1.0e12;
const double sigmoid_var = delta * (time-t_activate_farzadi/tau0);
const double sigmoid = 0.5 * (1.0 + sigmoid_var / (std::sqrt(1.0 + sigmoid_var*sigmoid_var)));
return val * sigmoid + (phi[1]-phi[0]) * (1.0 - sigmoid)*basis[eqn_id]->phi[i];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_farzadi_coupled_activated_dp_)) = residual_phase_farzadi_coupled_activated_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_conc_farzadi_)
{
const double dtestdx = basis[eqn_id].dphidx[i];
const double dtestdy = basis[eqn_id].dphidy[i];
const double dtestdz = basis[eqn_id].dphidz[i];
const double dbasisdx = basis[eqn_id].dphidx[j];
const double dbasisdy = basis[eqn_id].dphidy[j];
const double dbasisdz = basis[eqn_id].dphidz[j];
const double test = basis[0].phi[i];
const double divgrad = D_liquid_*(1.-basis[1].uu)/2.*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
const double u_t =(1.+k)/2.*test * basis[0].phi[j]/dt_;
return u_t + t_theta_*(divgrad);
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_phase_farzadi_)
{
const double dtestdx = basis[eqn_id].dphidx[i];
const double dtestdy = basis[eqn_id].dphidy[i];
const double dtestdz = basis[eqn_id].dphidz[i];
const double dbasisdx = basis[eqn_id].dphidx[j];
const double dbasisdy = basis[eqn_id].dphidy[j];
const double dbasisdz = basis[eqn_id].dphidz[j];
const double test = basis[1].phi[i];
const double dphidx = basis[1].dudx;
const double dphidy = basis[1].dudy;
const double dphidz = basis[1].dudz;
const double u = basis[0].uu;
const double phi = basis[1].uu;
const double as = a(phi,dphidx,dphidy,dphidz,eps);
const double m = (1.+(1.-k)*u)*as*as;
const double phit = (basis[1].phi[j])/dt_*test;
const double divgrad = as*as*(dbasisdx*dtestdx + dbasisdy*dtestdy + dbasisdz*dtestdz);
return (phit + t_theta_*(divgrad)/m)*m;
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_phase_farzadi_dp_)) = prec_phase_farzadi_;
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_conc_farzadi_dp_)) = prec_conc_farzadi_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_conc_farzadi_exp_)
{
//this is the explicit case with explicit phit
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
const double dtestdz = basis[0]->dphidz[i];
const double test = basis[0]->phi[i];
const double u[2] = {basis[0]->uu,basis[0]->uuold};
const double phi[2] = {basis[1]->uu,basis[1]->uuold};
const double dphidx[2] = {basis[1]->dudx,basis[1]->duolddx};
const double dphidy[2] = {basis[1]->dudy,basis[1]->duolddy};
const double dphidz[2] = {basis[1]->dudz,basis[1]->duolddz};
const double ut = (1.+k)/2.*(u[0]-u[1])/dt_*test;
const double divgradu[2] = {D_liquid_*(1.-phi[0])/2.*(basis[0]->dudx*dtestdx + basis[0]->dudy*dtestdy + basis[0]->dudz*dtestdz),
D_liquid_*(1.-phi[1])/2.*(basis[0]->duolddx*dtestdx + basis[0]->duolddy*dtestdy + basis[0]->duolddz*dtestdz)};//(grad u,grad phi)
const double normd[2] = {(phi[0]*phi[0] < absphi)&&(phi[0]*phi[0] > 0.) ? 1./sqrt(dphidx[0]*dphidx[0] + dphidy[0]*dphidy[0] + dphidz[0]*dphidz[0]) : 0.,
(phi[1]*phi[1] < absphi)&&(phi[1]*phi[1] > 0.) ? 1./sqrt(dphidx[1]*dphidx[1] + dphidy[1]*dphidy[1] + dphidz[1]*dphidz[1]) : 0.}; //cn lim grad phi/|grad phi| may -> 1 here?
const double phit = (phi[0]-phi[1])/dt_;
const double j_coef[2] = {(1.+(1.-k)*u[0])/sqrt(8.)*normd[0]*phit,
(1.+(1.-k)*u[1])/sqrt(8.)*normd[1]*phit};
const double divj[2] = {j_coef[0]*(dphidx[0]*dtestdx + dphidy[0]*dtestdy + dphidz[0]*dtestdz),
j_coef[1]*(dphidx[1]*dtestdx + dphidy[1]*dtestdy + dphidz[1]*dtestdz)};
double phitu[2] = {-.5*phit*(1.+(1.-k)*u[0])*test,
-.5*phit*(1.+(1.-k)*u[1])*test};
//double val = ut + t_theta_*divgradu + t_theta_*divj + t_theta_*phitu;
//printf("%lf\n",val);
return ut + t_theta_*(divgradu[0] + divj[0] + phitu[0]) + (1.-t_theta_)*(divgradu[1] + divj[1] + phitu[1]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_conc_farzadi_exp_dp_)) = residual_conc_farzadi_exp_;
INI_FUNC(init_phase_farzadi_)
{
double h = base_height + amplitude*((double)rand()/(RAND_MAX));
double c = (x-x0)*(x-x0) + (y-y0)*(y-y0) + (z-z0)*(z-z0);
return (C == 0) ? (tanh((h-x)/sqrt(2.))) : ((c < r*r) ? 1. : -1.);
}
INI_FUNC(init_phase_farzadi_test_)
{
const double pp = 36.;
const double ll = .2;
const double aa = 9.;
const double pi = 3.141592653589793;
double r = ll*(1.+(2.+sin(y*aa*pi/pp))
*(2.+sin(y*aa*pi/pp/2.))
*(2.+sin(y*aa*pi/pp/4.)));
double val = -1.;
if(x < r) val = 1.;
return val;
}
INI_FUNC(init_conc_farzadi_)
{
return -1.;
}
PPR_FUNC(postproc_c_)
{
// return the physical concentration
const double uu = u[0];
const double phi = u[1];
return -c_inf*(1.+k-phi+k*phi)*(-1.-uu+k*uu)/2./k;
}
PPR_FUNC(postproc_t_)
{
// return the physical temperature in K here
double x = xyz[0];
double xx = x*w0;
double tt = time*tau0;
//return ((dT < 0.001) ? 877.3 + (xx-R*tt)/l_T0*delta_T0 : 877.3);
return ((dT < 0.001) ? 877.3 + G*(xx-R*tt) : 877.3);
}
}//namespace farzadi3d
namespace noise
{
KOKKOS_INLINE_FUNCTION
double noise_(const double rand)
{
return 20.*rand;
}
}//namespace noise
namespace pfhub3
{
const double R_ = 8.;// 8.;
TUSAS_DEVICE
double smalld_ = 0.;
TUSAS_DEVICE
const double delta_ = -.3;//-.3;
TUSAS_DEVICE
const double D_ = 10.;
TUSAS_DEVICE
const double eps_ = .05;
TUSAS_DEVICE
const double tau0_ = 1.;
TUSAS_DEVICE
const double W_ = 1.;
TUSAS_DEVICE
const double lambda_ = D_*tau0_/.6267/W_/W_;
PARAM_FUNC(param_)
{
//we will need to propgate this to device
double smalld_p = plist->get<double>("smalld", smalld_);
smalld_ = smalld_p;
}
KOKKOS_INLINE_FUNCTION
double a(const double &p,const double &px,const double &py,const double &pz, const double ep)
{
double val = 1. + ep;
const double d = (px*px+py*py+pz*pz)*(px*px+py*py+pz*pz);
val = (d > smalld_) ? (1.-3.*ep)*(1.+4.*ep/(1.-3.*ep)*(px*px*px*px+py*py*py*py+pz*pz*pz*pz)/d)
: 1. + ep;
//older version produced nicer dendrite
// const double d = (px*px+py*py+pz*pz)*(px*px+py*py+pz*pz);
// val = (d > smalld_) ? (1.-3.*ep)*(1.+4.*ep/(1.-3.*ep)*(px*px*px*px+py*py*py*py+pz*pz*pz*pz)/d)
// : 1. + ep;
return val;
}
KOKKOS_INLINE_FUNCTION
double ap(const double &p,const double &px,const double &py,const double &pz,const double &pd, const double ep)
{
//older version produced nicer dendrite
// const double d = (px*px+py*py+pz*pz)*(px*px+py*py+pz*pz);
// return (d > smalld_) ? 4.*ep*
// (4.*pd*pd*pd*(px*px+py*py+pz*pz)-4.*pd*(px*px*px*px+py*py*py*py+pz*pz*pz*pz))
// /(px*px+py*py+pz*pz)/d
// : 0.;
const double d = (px*px+py*py+pz*pz)*(px*px+py*py+pz*pz);
return (d > smalld_) ? 4.*ep*
(4.*pd*pd*pd*(px*px+py*py+pz*pz)-4.*pd*(px*px*px*px+py*py*py*py+pz*pz*pz*pz))
/((px*px+py*py+pz*pz)*d)
: 0.;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_heat_pfhub3_)
{
const double ut = (basis[eqn_id]->uu-basis[eqn_id]->uuold)/dt_*basis[eqn_id]->phi[i];
double divgradu[3] = {D_*(basis[eqn_id]->dudx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->dudy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->dudz*basis[eqn_id]->dphidz[i]),
D_*(basis[eqn_id]->duolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duolddz*basis[eqn_id]->dphidz[i]),
D_*(basis[eqn_id]->duoldolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duoldolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duoldolddz*basis[eqn_id]->dphidz[i])};
const double phit[2] = {.5*(basis[1]->uu-basis[1]->uuold)/dt_*basis[0]->phi[i],
.5*(basis[1]->uuold-basis[1]->uuoldold)/dt_*basis[0]->phi[i]};
double f[3];
f[0] = -divgradu[0] + phit[0];
f[1] = -divgradu[1] + phit[1];
f[2] = -divgradu[2] + phit[1];
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_heat_pfhub3_dp_)) = residual_heat_pfhub3_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phase_pfhub3_)
{
const double test = basis[eqn_id]->phi[i];
const double dtestdx = basis[eqn_id]->dphidx[i];
const double dtestdy = basis[eqn_id]->dphidy[i];
const double dtestdz = basis[eqn_id]->dphidz[i];
const double phi[3] = {basis[eqn_id]->uu,basis[eqn_id]->uuold,basis[eqn_id]->uuoldold};
const double dphidx[3] = {basis[eqn_id]->dudx,basis[eqn_id]->duolddx,basis[eqn_id]->duoldolddx};
const double dphidy[3] = {basis[eqn_id]->dudy,basis[eqn_id]->duolddy,basis[eqn_id]->duoldolddy};
const double dphidz[3] = {basis[eqn_id]->dudz,basis[eqn_id]->duolddz,basis[eqn_id]->duoldolddz};
const double as[3] = {a(phi[0],
dphidx[0],
dphidy[0],
dphidz[0],
eps_),
a(phi[1],
dphidx[1],
dphidy[1],
dphidz[1],
eps_),
a(phi[2],
dphidx[2],
dphidy[2],
dphidz[2],
eps_)};
const double tau[3] = {tau0_*as[0]*as[0],tau0_*as[1]*as[1],tau0_*as[2]*as[2]};
const double phit = (phi[0]-phi[1])/dt_*test;
const double w[3] = {W_*as[0],W_*as[1],W_*as[2]};
// const double divgradphi[3] = {w[0]*w[0]*(dphidx[0]*dtestdx
// + dphidy[0]*dtestdy
// + dphidz[0]*dtestdz),
// w[1]*w[1]*(dphidx[1]*dtestdx
// + dphidy[1]*dtestdy
// + dphidz[1]*dtestdz),
// w[2]*w[2]*(dphidx[2]*dtestdx
// + dphidy[2]*dtestdy
// + dphidz[2]*dtestdz)};
const double divgradphi[3] = {W_*W_*(dphidx[0]*dtestdx
+ dphidy[0]*dtestdy
+ dphidz[0]*dtestdz),
W_*W_*(dphidx[1]*dtestdx
+ dphidy[1]*dtestdy
+ dphidz[1]*dtestdz),
W_*W_*(dphidx[2]*dtestdx
+ dphidy[2]*dtestdy
+ dphidz[2]*dtestdz)};
const double wp[3] = {W_*(ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidx[0],eps_)*dtestdx
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidy[0],eps_)*dtestdy
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidz[0],eps_)*dtestdz),
W_*(ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidx[1],eps_)*dtestdx
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidy[1],eps_)*dtestdy
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidz[1],eps_)*dtestdz),
W_*(ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidx[2],eps_)*dtestdx
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidy[2],eps_)*dtestdy
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidz[2],eps_)*dtestdz)};
const double curlgrad[3] = {w[0]*(dphidx[0]*dphidx[0] + dphidy[0]*dphidy[0] + dphidz[0]*dphidz[0])*wp[0],
w[1]*(dphidx[1]*dphidx[1] + dphidy[1]*dphidy[1] + dphidz[1]*dphidz[1])*wp[1],
w[2]*(dphidx[2]*dphidx[2] + dphidy[2]*dphidy[2] + dphidz[2]*dphidz[2])*wp[2]};
const double g[3] = {((phi[0]-lambda_*basis[0]->uu*(1.-phi[0]*phi[0]))*(1.-phi[0]*phi[0]))*test,
((phi[1]-lambda_*basis[0]->uuold*(1.-phi[1]*phi[1]))*(1.-phi[1]*phi[1]))*test,
((phi[2]-lambda_*basis[0]->uuoldold*(1.-phi[2]*phi[2]))*(1.-phi[2]*phi[2]))*test};
double f[3];
f[0] = -(divgradphi[0]/tau0_+curlgrad[0]/tau[0]-g[0]/tau[0]);
f[1] = -(divgradphi[1]/tau0_+curlgrad[1]/tau[1]-g[1]/tau[1]);
f[2] = -(divgradphi[2]/tau0_+curlgrad[2]/tau[2]-g[2]/tau[2]);
return phit - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC_TPETRA(residual_phase_pfhub3_noise_)
{
double val = residual_phase_pfhub3_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double phi[1] ={ basis[eqn_id]->uu};
const double g = (1.-phi[0]*phi[0])*(1.-phi[0]*phi[0]);
double noise[3] = {g*tpetra::noise::noise_(rand)*basis[eqn_id]->phi[i],0.*basis[eqn_id]->phi[i],0.*basis[eqn_id]->phi[i]};
double rv = (val + (1.-t_theta2_)*t_theta_*noise[0]
+ (1.-t_theta2_)*(1.-t_theta_)*noise[1]
+.5*t_theta2_*((2.+dt_/dtold_)*noise[1]-dt_/dtold_*noise[2]));
return rv;
}
RES_FUNC(residual_heat_pfhub3_n_)
{
const double ut = (basis[eqn_id].uu-basis[eqn_id].uuold)/dt_*basis[eqn_id].phi[i];
const double divgradu[3] = {D_*(basis[eqn_id].dudx*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dudy*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dudz*basis[eqn_id].dphidz[i]),
D_*(basis[eqn_id].duolddx*basis[eqn_id].dphidx[i]
+ basis[eqn_id].duolddy*basis[eqn_id].dphidy[i]
+ basis[eqn_id].duolddz*basis[eqn_id].dphidz[i]),
D_*(basis[eqn_id].duoldolddx*basis[eqn_id].dphidx[i]
+ basis[eqn_id].duoldolddy*basis[eqn_id].dphidy[i]
+ basis[eqn_id].duoldolddz*basis[eqn_id].dphidz[i])};
const double phit[2] = {.5*(basis[1].uu-basis[1].uuold)/dt_*basis[0].phi[i],
.5*(basis[1].uuold-basis[1].uuoldold)/dt_*basis[0].phi[i]};
double f[3];
f[0] = -divgradu[0] + phit[0];
f[1] = -divgradu[1] + phit[1];
f[2] = -divgradu[2] + phit[1];
// std::cout<<ut
// + t_theta_*divgradu[0] + (1. - t_theta_)*divgradu[1]
// - t_theta_*phit<<std::endl
// return ut - t_theta_*f[0]
// - (1.-t_theta_)*f[1];
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC(residual_phase_pfhub3_n_)
{
const double test = basis[eqn_id].phi[i];
const double dtestdx = basis[eqn_id].dphidx[i];
const double dtestdy = basis[eqn_id].dphidy[i];
const double dtestdz = basis[eqn_id].dphidz[i];
const double phi[3] = {basis[eqn_id].uu,basis[eqn_id].uuold,basis[eqn_id].uuoldold};
const double dphidx[3] = {basis[eqn_id].dudx,basis[eqn_id].duolddx,basis[eqn_id].duoldolddx};
const double dphidy[3] = {basis[eqn_id].dudy,basis[eqn_id].duolddy,basis[eqn_id].duoldolddy};
const double dphidz[3] = {basis[eqn_id].dudz,basis[eqn_id].duolddz,basis[eqn_id].duoldolddz};
const double as[3] = {a(phi[0],
dphidx[0],
dphidy[0],
dphidz[0],
eps_),
a(phi[1],
dphidx[1],
dphidy[1],
dphidz[1],
eps_),
a(phi[2],
dphidx[2],
dphidy[2],
dphidz[2],
eps_)};
const double tau[3] = {tau0_*as[0]*as[0],tau0_*as[1]*as[1],tau0_*as[2]*as[2]};
// if(tau[0]!= tau[0]) std::cout<<tau[0]<<" "<<as[0]<<" "
// <<dphidx[0]<<" "<<dphidy[0]<<" "<<dphidz[0]
// <<" "<<phi[0]<<" "<<phi[0]*phi[0]<<std::endl;
const double phit = (phi[0]-phi[1])/dt_*test;
const double w[3] = {W_*as[0],W_*as[1],W_*as[2]};
// const double divgradphi[3] = {w[0]*w[0]*(dphidx[0]*dtestdx
// + dphidy[0]*dtestdy
// + dphidz[0]*dtestdz),
// w[1]*w[1]*(dphidx[1]*dtestdx
// + dphidy[1]*dtestdy
// + dphidz[1]*dtestdz),
// w[2]*w[2]*(dphidx[2]*dtestdx
// + dphidy[2]*dtestdy
// + dphidz[2]*dtestdz)};
const double divgradphi[3] = {W_*W_*(dphidx[0]*dtestdx
+ dphidy[0]*dtestdy
+ dphidz[0]*dtestdz),
W_*W_*(dphidx[1]*dtestdx
+ dphidy[1]*dtestdy
+ dphidz[1]*dtestdz),
W_*W_*(dphidx[2]*dtestdx
+ dphidy[2]*dtestdy
+ dphidz[2]*dtestdz)};
const double wp[3] = {W_*(ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidx[0],eps_)*dtestdx
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidy[0],eps_)*dtestdy
+ ap(phi[0],dphidx[0],dphidy[0],dphidz[0],dphidz[0],eps_)*dtestdz),
W_*(ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidx[1],eps_)*dtestdx
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidy[1],eps_)*dtestdy
+ ap(phi[1],dphidx[1],dphidy[1],dphidz[1],dphidz[1],eps_)*dtestdz),
W_*(ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidx[2],eps_)*dtestdx
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidy[2],eps_)*dtestdy
+ ap(phi[2],dphidx[2],dphidy[2],dphidz[2],dphidz[2],eps_)*dtestdz)};
const double curlgrad[3] = {w[0]*(dphidx[0]*dphidx[0] + dphidy[0]*dphidy[0] + dphidz[0]*dphidz[0])*wp[0],
w[1]*(dphidx[1]*dphidx[1] + dphidy[1]*dphidy[1] + dphidz[1]*dphidz[1])*wp[1],
w[2]*(dphidx[2]*dphidx[2] + dphidy[2]*dphidy[2] + dphidz[2]*dphidz[2])*wp[2]};
const double g[3] = {((phi[0]-lambda_*basis[0].uu*(1.-phi[0]*phi[0]))*(1.-phi[0]*phi[0]))*test,
((phi[1]-lambda_*basis[0].uuold*(1.-phi[1]*phi[1]))*(1.-phi[1]*phi[1]))*test,
((phi[2]-lambda_*basis[0].uuoldold*(1.-phi[2]*phi[2]))*(1.-phi[2]*phi[2]))*test};
// if(tau[0]!= tau[0]) std::cout<<tau[0]<<" "<<as[0]<<" "
// <<dphidx[0]<<" "<<dphidy[0]<<" "<<dphidz[0]
// <<" "<<phi[0]<<" "<<phi[0]*phi[0]<<" "<<g[0]<<" "<<divgradphi[0]
// <<" "<<curlgrad[0]<<std::endl;
double f[3];
f[0] = -(divgradphi[0]/tau0_+curlgrad[0]/tau[0]-g[0]/tau[0]);
f[1] = -(divgradphi[1]/tau0_+curlgrad[1]/tau[1]-g[1]/tau[1]);
f[2] = -(divgradphi[2]/tau0_+curlgrad[2]/tau[2]-g[2]/tau[2]);
// return phit - t_theta_*f[0]
// - (1.-t_theta_)*f[1];
return phit - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_pfhub3_dp_)) = residual_phase_pfhub3_;
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_phase_pfhub3_noise_dp_)) = residual_phase_pfhub3_noise_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_heat_pfhub3_)
{
const double ut = basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double divgradu = D_*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return ut + t_theta_*divgradu;
}
PRE_FUNC(prec_heat_pfhub3_n_)
{
const double ut = basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double divgradu = D_*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return ut + t_theta_*divgradu;
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_heat_pfhub3_dp_)) = prec_heat_pfhub3_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_phase_pfhub3_)
{
const double test = basis[eqn_id].phi[i];
const double dtestdx = basis[eqn_id].dphidx[i];
const double dtestdy = basis[eqn_id].dphidy[i];
const double dtestdz = basis[eqn_id].dphidz[i];
const double phi = basis[eqn_id].uu;
const double phit = basis[eqn_id].phi[j]/dt_*test;
// const double as = a(phi,
// basis[eqn_id].dudx,
// basis[eqn_id].dudy,
// basis[eqn_id].dudz,
// eps_);
const double tau = tau0_;//*as*as;
const double divgradphi = W_*W_*(basis[eqn_id].dphidx[j]*dtestdx
+ basis[eqn_id].dphidy[j]*dtestdy
+ basis[eqn_id].dphidz[j]*dtestdz);
return phit
+ t_theta_*divgradphi/tau;
}
PRE_FUNC(prec_phase_pfhub3_n_)
{
const double test = basis[eqn_id].phi[i];
const double dtestdx = basis[eqn_id].dphidx[i];
const double dtestdy = basis[eqn_id].dphidy[i];
const double dtestdz = basis[eqn_id].dphidz[i];
const double phi = basis[eqn_id].uu;
const double phit = basis[eqn_id].phi[j]/dt_*test;
// const double as = tpetra::farzadi3d::a(phi,
// basis[eqn_id].dudx,
// basis[eqn_id].dudy,
// basis[eqn_id].dudz,
// eps_);
// const double tau = tau0_*as*as;
const double tau = tau0_;
// const double divgradphi = W_*as*W_*as*(basis[eqn_id].dphidx[j]*dtestdx
// + basis[eqn_id].dphidy[j]*dtestdy
// + basis[eqn_id].dphidz[j]*dtestdz);
const double divgradphi = W_*W_*(basis[eqn_id].dphidx[j]*dtestdx
+ basis[eqn_id].dphidy[j]*dtestdy
+ basis[eqn_id].dphidz[j]*dtestdz);
return phit
+ t_theta_*divgradphi/tau;
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_phase_pfhub3_dp_)) = prec_phase_pfhub3_;
INI_FUNC(init_heat_pfhub3_)
{
return delta_;
}
INI_FUNC(init_phase_pfhub3_)
{
double val = -1.;
const double r = sqrt(x*x+y*y+z*z);
//if(x*x+y*y+z*z < R_*R_) val = 1.;
//see https://aip.scitation.org/doi/pdf/10.1063/1.5142353
//we should have a general function for this
//val = tanh((R_-r)/(sqrt(8.)*W_));
val = tanh((R_-r)/(sqrt(2.)*W_));
//should probably be:
//val = -tanh( (x*x+y*y+z*z - R_*R_)/(sqrt(2.)*W_) );
return val;
}
}//namespace pfhub3
namespace pfhub2
{
TUSAS_DEVICE
const int N_MAX = 1;
TUSAS_DEVICE
int N_ = 1;
TUSAS_DEVICE
int eqn_off_ = 2;
TUSAS_DEVICE
int ci_ = 0;
TUSAS_DEVICE
int mui_ = 1;
TUSAS_DEVICE
const double c0_ = .5;
TUSAS_DEVICE
const double eps_ = .05;
TUSAS_DEVICE
const double eps_eta_ = .1;
TUSAS_DEVICE
const double psi_ = 1.5;
TUSAS_DEVICE
const double rho_ = 1.414213562373095;//std::sqrt(2.);
TUSAS_DEVICE
const double c_alpha_ = .3;
TUSAS_DEVICE
const double c_beta_ = .7;
TUSAS_DEVICE
const double alpha_ = 5.;
TUSAS_DEVICE
//const double k_c_ = 3.;
const double k_c_ = 0.0;
TUSAS_DEVICE
const double k_eta_ = 3.;
TUSAS_DEVICE
const double M_ = 5.;
TUSAS_DEVICE
const double L_ = 5.;
TUSAS_DEVICE
const double w_ = 1.;
// double c_a[2] = {0., 0.};
// double c_b[2] = {0., 0.};
PARAM_FUNC(param_)
{
int N_p = plist->get<int>("N");
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(N_,&N_p,sizeof(int));
#else
N_ = N_p;
#endif
int eqn_off_p = plist->get<int>("OFFSET");
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(eqn_off_,&eqn_off_p,sizeof(int));
#else
eqn_off_ = eqn_off_p;
#endif
}
PARAM_FUNC(param_trans_)
{
int N_p = plist->get<int>("N");
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(N_,&N_p,sizeof(int));
#else
N_ = N_p;
#endif
int eqn_off_p = plist->get<int>("OFFSET");
#ifdef TUSAS_HAVE_CUDA
cudaMemcpyToSymbol(eqn_off_,&eqn_off_p,sizeof(int));
#else
eqn_off_ = eqn_off_p;
#endif
ci_ = 1;
mui_ = 0;
}
KOKKOS_INLINE_FUNCTION
double dhdeta(const double eta)
{
//return 30.*eta[eqn_id]*eta[eqn_id] - 60.*eta[eqn_id]*eta[eqn_id]*eta[eqn_id] + 30.*eta[eqn_id]*eta[eqn_id]*eta[eqn_id]*eta[eqn_id];
return 30.*eta*eta - 60.*eta*eta*eta + 30.*eta*eta*eta*eta;
}
KOKKOS_INLINE_FUNCTION
double h(const double *eta)
{
double val = 0.;
for (int i = 0; i < N_; i++){
val += eta[i]*eta[i]*eta[i]*(6.*eta[i]*eta[i] - 15.*eta[i] + 10.);
}
return val;
}
KOKKOS_INLINE_FUNCTION
double d2fdc2()
{
return 2.*rho_*rho_;
}
KOKKOS_INLINE_FUNCTION
double df_alphadc(const double c)
{
return 2.*rho_*rho_*(c - c_alpha_);
}
KOKKOS_INLINE_FUNCTION
double df_betadc(const double c)
{
return -2.*rho_*rho_*(c_beta_ - c);
}
KOKKOS_INLINE_FUNCTION
void solve_kks(const double c, double *phi, double &ca, double &cb)//const double phi
{
double delta_c_a = 0.;
double delta_c_b = 0.;
const int max_iter = 20;
const double tol = 1.e-8;
const double hh = h(phi);
//c_a[0] = (1.-hh)*c;
ca = c - hh*(c_beta_ - c_alpha_);
//c_b[0]=hh*c;
cb = c - (1.-hh)*(c_beta_ - c_alpha_);
//std::cout<<"-1"<<" "<<delta_c_b<<" "<<delta_c_a<<" "<<c_b[0]<<" "<<c_a[0]<<" "<<hh*c_b[0] + (1.- hh)*c_a[0]<<" "<<c<<std::endl;
for(int i = 0; i < max_iter; i++){
const double det = hh*d2fdc2() + (1.-hh)*d2fdc2();
const double f1 = hh*cb + (1.- hh)*ca - c;
const double f2 = df_betadc(cb) - df_alphadc(ca);
delta_c_b = (-d2fdc2()*f1 - (1-hh)*f2)/det;
delta_c_a = (-d2fdc2()*f1 + hh*f2)/det;
cb = delta_c_b + cb;
ca = delta_c_a + ca;
//std::cout<<i<<" "<<delta_c_b<<" "<<delta_c_a<<" "<<c_b[0]<<" "<<c_a[0]<<" "<<hh*c_b[0] + (1.- hh)*c_a[0]<<" "<<c<<std::endl;
if(delta_c_a*delta_c_a+delta_c_b*delta_c_b < tol*tol) return;
}
// std::cout<<"################################### solve_kks falied to converge with delta_c_a*delta_c_a+delta_c_b*delta_c_b = "
// <<delta_c_a*delta_c_a+delta_c_b*delta_c_b<<" ###################################"<<std::endl;
exit(0);
return;
}
KOKKOS_INLINE_FUNCTION
double f_alpha(const double c)
{
return rho_*rho_*(c - c_alpha_)*(c - c_alpha_);
}
KOKKOS_INLINE_FUNCTION
double f_beta(const double c)
{
return rho_*rho_*(c_beta_ - c)*(c_beta_ - c);
}
KOKKOS_INLINE_FUNCTION
double dgdeta(const double *eta, const int eqn_id){
double aval =0.;
for (int i = 0; i < N_; i++){
aval += eta[i]*eta[i];
}
aval = aval - eta[eqn_id]* eta[eqn_id];
return 2.*eta[eqn_id]*(1. - eta[eqn_id])*(1. - eta[eqn_id])
- 2.* eta[eqn_id]* eta[eqn_id]* (1. - eta[eqn_id])
+ 4.*alpha_*eta[eqn_id] *aval;
}
KOKKOS_INLINE_FUNCTION
double dfdc(const double c, const double *eta)
{
const double hh = h(eta);
return df_alphadc(c)*(1.-hh)+df_betadc(c)*hh;
}
KOKKOS_INLINE_FUNCTION
double dfdeta(const double c, const double eta)
{
//this does not include the w g' term
//dh(eta1,eta2)/deta1 is a function of eta1 only
const double dh_deta = dhdeta(eta);
return f_alpha(c)*(-dh_deta)+f_beta(c)*dh_deta;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_c_)
{
// c_t + M grad mu grad test
const double ut = (basis[ci_]->uu-basis[ci_]->uuold)/dt_*basis[eqn_id]->phi[i];
//M_ divgrad mu
const double f[3] = {M_*(basis[mui_]->dudx*basis[eqn_id]->dphidx[i]
+ basis[mui_]->dudy*basis[eqn_id]->dphidy[i]
+ basis[mui_]->dudz*basis[eqn_id]->dphidz[i]),
M_*(basis[mui_]->duolddx*basis[eqn_id]->dphidx[i]
+ basis[mui_]->duolddy*basis[eqn_id]->dphidy[i]
+ basis[mui_]->duolddz*basis[eqn_id]->dphidz[i]),
M_*(basis[mui_]->duoldolddx*basis[eqn_id]->dphidx[i]
+ basis[mui_]->duoldolddy*basis[eqn_id]->dphidy[i]
+ basis[mui_]->duoldolddz*basis[eqn_id]->dphidz[i])};
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_c_dp_)) = residual_c_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_c_kks_)
{
//derivatives of the test function
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
//double dtestdz = basis[0]->dphidz[i];
//test function
const double test = basis[0]->phi[i];
//u, phi
const double c[2] = {basis[0]->uu, basis[0]->uuold};
const double dcdx[2] = {basis[0]->dudx, basis[0]->duolddx};
const double dcdy[2] = {basis[0]->dudy, basis[0]->duolddy};
double dhdx[2] = {0., 0.};
double dhdy[2] = {0., 0.};
double c_a[2] = {0., 0.};
double c_b[2] = {0., 0.};
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
dhdx[0] += dhdeta(basis[kk_off]->uu)*basis[kk_off]->dudx;
dhdx[1] += dhdeta(basis[kk_off]->uuold)*basis[kk_off]->duolddx;
dhdy[0] += dhdeta(basis[kk_off]->uu)*basis[kk_off]->dudy;
dhdy[1] += dhdeta(basis[kk_off]->uuold)*basis[kk_off]->duolddy;
}
const double ct = (c[0]-c[1])/dt_*test;
double eta_array[N_MAX];
double eta_array_old[N_MAX];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off]->uu;
eta_array_old[kk] = basis[kk_off]->uuold;
}
solve_kks(c[0],eta_array,c_a[0],c_b[0]);
const double DfDc[2] = {-c_b[0] + c_a[0],
-c_b[1] + c_a[1]};
const double D2fDc2 = 1.;
//double D2fDc2 = 1.*d2fdc2();
const double dfdx[2] = {DfDc[0]*dhdx[0] + D2fDc2*dcdx[0],
DfDc[1]*dhdx[1] + D2fDc2*dcdx[1]};
const double dfdy[2] = {DfDc[0]*dhdy[0] + D2fDc2*dcdy[0],
DfDc[1]*dhdy[1] + D2fDc2*dcdy[1]};
const double divgradc[2] = {M_*(dfdx[0]*dtestdx + dfdy[0]*dtestdy),
M_*(dfdx[1]*dtestdx + dfdy[1]*dtestdy)};
return ct + t_theta_*divgradc[0] + (1.-t_theta_)*divgradc[1];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_c_kks_dp_)) = residual_c_kks_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_eta_)
{
//test function
const double test = basis[eqn_id]->phi[i];
//u, phi
const double c[3] = {basis[ci_]->uu, basis[ci_]->uuold, basis[ci_]->uuoldold};
const double eta[3] = {basis[eqn_id]->uu, basis[eqn_id]->uuold, basis[eqn_id]->uuoldold};
const double divgradeta[3] = {L_*k_eta_*(basis[eqn_id]->dudx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->dudy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->dudz*basis[eqn_id]->dphidz[i]),
L_*k_eta_*(basis[eqn_id]->duolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duolddz*basis[eqn_id]->dphidz[i]),
L_*k_eta_*(basis[eqn_id]->duoldolddx*basis[eqn_id]->dphidx[i]
+ basis[eqn_id]->duoldolddy*basis[eqn_id]->dphidy[i]
+ basis[eqn_id]->duoldolddz*basis[eqn_id]->dphidz[i])};
double eta_array[N_MAX];
double eta_array_old[N_MAX];
double eta_array_oldold[N_MAX];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off]->uu;
eta_array_old[kk] = basis[kk_off]->uuold;
eta_array_oldold[kk] = basis[kk_off]->uuoldold;
}
const int k = eqn_id - eqn_off_;
const double df_deta[3] = {L_*(dfdeta(c[0],eta[0]) + w_*dgdeta(eta_array,k))*test,
L_*(dfdeta(c[1],eta[1]) + w_*dgdeta(eta_array_old,k))*test,
L_*(dfdeta(c[2],eta[2]) + w_*dgdeta(eta_array_oldold,k))*test};
const double f[3] = {df_deta[0] + divgradeta[0],
df_deta[1] + divgradeta[1],
df_deta[2] + divgradeta[2]};
const double ut = (eta[0]-eta[1])/dt_*test;
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_eta_dp_)) = residual_eta_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_eta_kks_)
{
//derivatives of the test function
const double dtestdx = basis[eqn_id]->dphidx[i];
const double dtestdy = basis[eqn_id]->dphidy[i];
//double dtestdz = basis[0].dphidz[i];
//test function
const double test = basis[eqn_id]->phi[i];
//u, phi
const double c[2] = {basis[0]->uu, basis[0]->uuold};
const double eta[2] = {basis[eqn_id]->uu, basis[eqn_id]->uuold};
const double detadx[2] = {basis[eqn_id]->dudx, basis[eqn_id]->duolddx};
const double detady[2] = {basis[eqn_id]->dudy, basis[eqn_id]->duolddy};
double c_a[2] = {0., 0.};
double c_b[2] = {0., 0.};
double eta_array[N_MAX];
double eta_array_old[N_MAX];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off]->uu;
eta_array_old[kk] = basis[kk_off]->uuold;
}
solve_kks(c[0],eta_array,c_a[0],c_b[0]);
const double etat = (eta[0]-eta[1])/dt_*test;
const double F[2] = {f_beta(c_b[0]) - f_alpha(c_a[0])
- (c_b[0] - c_a[0])*df_betadc(c_b[0]),
f_beta(c_b[1]) - f_alpha(c_a[1])
- (c_b[1] - c_a[1])*df_betadc(c_b[1])};
const int k = eqn_id - eqn_off_;
const double dfdeta[2] = {L_*(F[0]*dhdeta(eta[0])
+ w_*dgdeta(eta_array,k) )*test,
L_*(F[1]*dhdeta(eta[1])
+ w_*dgdeta(eta_array_old,k))*test};
const double divgradeta[2] = {L_*k_eta_
*(detadx[0]*dtestdx + detady[0]*dtestdy),
L_*k_eta_
*(detadx[1]*dtestdx + detady[1]*dtestdy)};//(grad u,grad phi)
return etat + t_theta_*divgradeta[0] + t_theta_*dfdeta[0] + (1.-t_theta_)*divgradeta[1] + (1.-t_theta_)*dfdeta[1];
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_eta_kks_dp_)) = residual_eta_kks_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_mu_)
{
//-mu + df/dc +div c grad test
const double c = basis[ci_]->uu;
const double mu = basis[mui_]->uu;
//const double eta = basis[2]->uu;
const double test = basis[eqn_id]->phi[i];
const double divgradc = k_c_*(basis[ci_]->dudx*basis[eqn_id]->dphidx[i]
+ basis[ci_]->dudy*basis[eqn_id]->dphidy[i]
+ basis[ci_]->dudz*basis[eqn_id]->dphidz[i]);
double eta_array[N_MAX];
for( int kk = 0; kk < N_; kk++){
int kk_off = kk + eqn_off_;
eta_array[kk] = basis[kk_off]->uu;
};
const double df_dc = dfdc(c,eta_array)*test;
//return dt_*(-mu*test + df_dc + divgradc);
return -mu*test + df_dc + divgradc;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_mu_dp_)) = residual_mu_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_c_)
{
//const int ci = 1;
//const int mui = 0;
const double D = k_c_;
const double test = basis[eqn_id].phi[i];
//const double u_t =test * basis[eqn_id].phi[j]/dt_;
const double divgrad = D*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
const double d2 = d2fdc2()*basis[eqn_id].phi[j]*test;
return divgrad + d2;
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_mu_)
{
const double D = M_;
//const double test = basis[eqn_id].phi[i];
//const double u_t =test * basis[eqn_id].phi[j]/dt_;
const double divgrad = D*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return divgrad;
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_eta_)
{
const double ut = basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double divgrad = L_*k_eta_*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
// const double eta = basis[eqn_id].uu;
// const double c = basis[0].uu;
// const double g1 = L_*(2. - 12.*eta + 12.*eta*eta)*basis[eqn_id].phi[j]*basis[eqn_id].phi[i];
// const double h1 = L_*(-f_alpha(c)+f_beta(c))*(60.*eta-180.*eta*eta+120.*eta*eta*eta)*basis[eqn_id].phi[j]*basis[eqn_id].phi[i];
return ut + t_theta_*divgrad;// + t_theta_*(g1+h1);
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_ut_)
{
const double test = basis[eqn_id].phi[i];
const double u_t =test * basis[eqn_id].phi[j]/dt_;
return u_t;
}
PPR_FUNC(postproc_c_a_)
{
//cn will need eta_array here...
const double cc = u[0];
double phi = u[2];
double c_a = 0.;
double c_b = 0.;
solve_kks(cc,&phi,c_a,c_b);
return c_a;
}
PPR_FUNC(postproc_c_b_)
{
//cn will need eta_array here...
const double cc = u[0];
double phi = u[2];
double c_a = 0.;
double c_b = 0.;
solve_kks(cc,&phi,c_a,c_b);
return c_b;
}
INI_FUNC(init_mu_)
{
//this will need the eta_array version
const double c = ::pfhub2::init_c_(x,y,z,eqn_id);
const double eta = ::pfhub2::init_eta_(x,y,z,2);
return dfdc(c,&eta);
// return 0.;
}
INI_FUNC(init_eta_)
{
return ::pfhub2::init_eta_(x,y,z,eqn_id-1);
}
}//namespace pfhub2
namespace cahnhilliard
{
//this has an mms described at:
//https://www.sciencedirect.com/science/article/pii/S0021999112007243
//residual_*_ is a traditional formulation for [c mu] with
//R_c = c_t - divgrad mu
//R_mu = -mu + df/dc - divgrad c
//residual_*_trans_ utilizes a transformation as [mu c] with
//R_mu = c_t - divgrad mu
//R_c = -mu + df/dc - divgrad c
//that puts the elliptic terms on the diagonal, with better solver convergence and
//potential for preconditioning
//the transformation is inspired by:
//https://web.archive.org/web/20220201192736id_/https://publikationen.bibliothek.kit.edu/1000141249/136305383
//https://www.sciencedirect.com/science/article/pii/S037704271930319X
//right now, the preconditioner can probably be improved by scaling c by dt
double M = 1.;
double Eps = 1.;
double alpha = 1.;//alpha >= 1
double pi = 3.141592653589793;
double fcoef_ = 0.;
double F(const double &x,const double &t)
{
// Sin(a*Pi*x)
// - M*(Power(a,2)*Power(Pi,2)*(1 + t)*Sin(a*Pi*x) - Power(a,4)*Ep*Power(Pi,4)*(1 + t)*Sin(a*Pi*x) +
// 6*Power(a,2)*Power(Pi,2)*Power(1 + t,3)*Power(Cos(a*Pi*x),2)*Sin(a*Pi*x) -
// 3*Power(a,2)*Power(Pi,2)*Power(1 + t,3)*Power(Sin(a*Pi*x),3))
double a = alpha;
return sin(a*pi*x)
- M*(std::pow(a,2)*std::pow(pi,2)*(1 + t)*sin(a*pi*x) - std::pow(a,4)*Eps*std::pow(pi,4)*(1 + t)*sin(a*pi*x) +
6*std::pow(a,2)*std::pow(pi,2)*std::pow(1 + t,3)*std::pow(cos(a*pi*x),2)*sin(a*pi*x) -
3*std::pow(a,2)*std::pow(pi,2)*std::pow(1 + t,3)*std::pow(sin(a*pi*x),3));
}
double fp(const double &u)
{
return u*u*u - u;
}
INI_FUNC(init_c_)
{
return sin(alpha*pi*x);
}
INI_FUNC(init_mu_)
{
//-Sin[a \[Pi] x] + a^2 \[Pi]^2 Sin[a \[Pi] x] + Sin[a \[Pi] x]^3
return -sin(alpha*pi*x) + alpha*alpha*pi*pi*sin(alpha*pi*x) + sin(alpha*pi*x)*sin(alpha*pi*x)*sin(alpha*pi*x);
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_c_)
{
//derivatives of the test function
double dtestdx = basis[0]->dphidx[i];
double dtestdy = basis[0]->dphidy[i];
double dtestdz = basis[0]->dphidz[i];
//test function
double test = basis[0]->phi[i];
double c = basis[0]->uu;
double cold = basis[0]->uuold;
double mu = basis[1]->uu;
double x = basis[0]->xx;
double ct = (c - cold)/dt_*test;
double divgradmu = M*t_theta_*(basis[1]->dudx*dtestdx + basis[1]->dudy*dtestdy + basis[1]->dudz*dtestdz)
+ M*(1.-t_theta_)*(basis[1]->duolddx*dtestdx + basis[1]->duolddy*dtestdy + basis[1]->duolddz*dtestdz);
double f = t_theta_*fcoef_*F(x,time)*test + (1.-t_theta_)*fcoef_*F(x,time-dt_)*test;
return ct + divgradmu - f;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_mu_)
{
//derivatives of the test function
double dtestdx = basis[0]->dphidx[i];
double dtestdy = basis[0]->dphidy[i];
double dtestdz = basis[0]->dphidz[i];
//test function
double test = basis[1]->phi[i];
double c = basis[0]->uu;
double mu = basis[1]->uu;
double mut = mu*test;
double f = fp(c)*test;
double divgradc = Eps*(basis[0]->dudx*dtestdx + basis[0]->dudy*dtestdy + basis[0]->dudz*dtestdz);
return -mut + f + divgradc;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_mu_trans_)
{
//derivatives of the test function
double dtestdx = basis[0]->dphidx[i];
double dtestdy = basis[0]->dphidy[i];
double dtestdz = basis[0]->dphidz[i];
//test function
double test = basis[0]->phi[i];
double c = basis[1]->uu;
double cold = basis[1]->uuold;
//double mu = basis[1]->uu;
double x = basis[0]->xx;
double ct = (c - cold)/dt_*test;
double divgradmu = M*t_theta_*(basis[0]->dudx*dtestdx + basis[0]->dudy*dtestdy + basis[0]->dudz*dtestdz)
+ M*(1.-t_theta_)*(basis[0]->duolddx*dtestdx + basis[0]->duolddy*dtestdy + basis[0]->duolddz*dtestdz);
double f = t_theta_*fcoef_*F(x,time)*test + (1.-t_theta_)*fcoef_*F(x,time-dt_)*test;
return ct + divgradmu - f;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_c_trans_)
{
//derivatives of the test function
double dtestdx = basis[0]->dphidx[i];
double dtestdy = basis[0]->dphidy[i];
double dtestdz = basis[0]->dphidz[i];
//test function
double test = basis[1]->phi[i];
double c = basis[1]->uu;
double mu = basis[0]->uu;
double mut = mu*test;
double f = fp(c)*test;
double divgradc = Eps*(basis[1]->dudx*dtestdx + basis[1]->dudy*dtestdy + basis[1]->dudz*dtestdz);
return -mut + f + divgradc;
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_mu_trans_)
{
const double divgradmu = M*t_theta_*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return divgradmu;
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_c_trans_)
{
const double divgradc = Eps*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return divgradc;
}
PARAM_FUNC(param_)
{
fcoef_ = plist->get<double>("fcoef");
}
}//namespace cahnhilliard
namespace robin
{
// http://ramanujan.math.trinity.edu/rdaileda/teach/s12/m3357/lectures/lecture_2_28_short.pdf
// 1-D robin bc test problem, time dependent
// Solve D[u, t] - c^2 D[u, x, x] == 0
// u(0,t) == 0
// D[u, x] /. x -> L == -kappa u(t,L)
// => du/dx + kappa u = g = 0
// u(x,t) = a E^(-mu^2 t) Sin[mu x]
// mu solution to: Tan[mu L] + mu/kappa == 0 && Pi/2 < mu < 3 Pi/2
const double mu = 2.028757838110434;
const double a = 10.;
const double c = 1.;
const double L = 1.;
const double kappa = 1.;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_robin_test_)
{
//1-D robin bc test problem,
//derivatives of the test function
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
const double dtestdz = basis[0]->dphidz[i];
//test function
const double test = basis[0]->phi[i];
//u, phi
const double u = basis[0]->uu;
const double uold = basis[0]->uuold;
//double a =10.;
const double ut = (u-uold)/dt_*test;
const double f[3] = {c*c*(basis[0]->dudx*dtestdx + basis[0]->dudy*dtestdy + basis[0]->dudz*dtestdz),
c*c*(basis[0]->duolddx*dtestdx + basis[0]->duolddy*dtestdy + basis[0]->duolddz*dtestdz),
c*c*(basis[0]->duoldolddx*dtestdx + basis[0]->duoldolddy*dtestdy + basis[0]->duoldolddz*dtestdz)};
return ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_robin_test_dp_)) = residual_robin_test_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_robin_test_)
{
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
const double dtestdx = basis[0].dphidx[i];
const double dtestdy = basis[0].dphidy[i];
const double dtestdz = basis[0].dphidz[i];
const double dbasisdx = basis[0].dphidx[j];
const double dbasisdy = basis[0].dphidy[j];
const double dbasisdz = basis[0].dphidz[j];
const double test = basis[0].phi[i];
const double divgrad = c*c*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
//double a =10.;
const double u_t = (basis[0].phi[j])/dt_*test;
return u_t + t_theta_*divgrad;
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_robin_test_dp_)) = prec_robin_test_;
NBC_FUNC_TPETRA(nbc_robin_test_)
{
const double test = basis[0].phi[i];
//du/dn + kappa u = g = 0 on L
//(du,dv) - <du/dn,v> = (f,v)
//(du,dv) - <g - kappa u,v> = (f,v)
//(du,dv) - < - kappa u,v> = (f,v)
// ^^^^^^^^^^^^^^ return this
const double f[3] = {-kappa*basis[0].uu*test,
-kappa*basis[0].uuold*test,
-kappa*basis[0].uuoldold*test};
return (1.-t_theta2_)*t_theta_*f[0]
+(1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
INI_FUNC(init_robin_test_)
{
return a*sin(mu*x);
}
PPR_FUNC(postproc_robin_)
{
const double uu = u[0];
const double x = xyz[0];
//const double y = xyz[1];
//const double z = xyz[2];
const double s= a*exp(-mu*mu*time)*sin(mu*x);//c?
return s-uu;
}
}//namespace robin
namespace autocatalytic4
{
//https://documen.site/download/math-3795-lecture-18-numerical-solution-of-ordinary-differential-equations-goals_pdf#
//https://media.gradebuddy.com/documents/2449908/0c88cf76-7605-4aec-b2ad-513ddbebefec.pdf
const double k1 = .0001;
const double k2 = 1.;
const double k3 = .0008;
RES_FUNC_TPETRA(residual_a_)
{
const double test = basis[0]->phi[i];
//u, phi
const double u = basis[0]->uu;
const double uold = basis[0]->uuold;
const double uoldold = basis[0]->uuoldold;
const double ut = (u-uold)/dt_*test;
//std::cout<<ut<<" "<<dt_<<" "<<time<<std::endl;
double f[3];
f[0] = (-k1*u - k2*u*basis[1]->uu)*test;
f[1] = (-k1*uold - k2*u*basis[1]->uuold)*test;
f[2] = (-k1*uoldold - k2*u*basis[1]->uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC_TPETRA(residual_b_)
{
const double test = basis[1]->phi[i];
//u, phi
const double u = basis[1]->uu;
const double uold = basis[1]->uuold;
//const double uoldold = basis[1]->uuoldold;
const double a = basis[0]->uu;
const double aold = basis[0]->uuold;
const double aoldold = basis[0]->uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k1*a - k2*a*u + 2.*k3*basis[2]->uu)*test;
f[1] = (k1*aold - k2*aold*uold + 2.*k3*basis[2]->uuold)*test;
f[2] = (k1*aoldold - k2*aoldold*basis[1]->uuoldold + 2.*k3*basis[2]->uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC_TPETRA(residual_ab_)
{
const double test = basis[1]->phi[i];
//u, phi
const double u = basis[2]->uu;
const double uold = basis[2]->uuold;
//const double uoldold = basis[1]->uuoldold;
const double b = basis[1]->uu;
const double bold = basis[1]->uuold;
const double boldold = basis[1]->uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k2*b*basis[0]->uu - k3*u)*test;
f[1] = (k2*bold*basis[0]->uuold - k3*uold)*test;
f[2] = (k2*boldold*basis[0]->uuoldold - k3*basis[2]->uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
RES_FUNC_TPETRA(residual_c_)
{
const double test = basis[1]->phi[i];
//u, phi
const double u = basis[3]->uu;
const double uold = basis[3]->uuold;
//const double uoldold = basis[1]->uuoldold;
const double a = basis[0]->uu;
const double aold = basis[0]->uuold;
const double aoldold = basis[0]->uuoldold;
const double ut = (u-uold)/dt_*test;
double f[3];
f[0] = (k1*a + k3*basis[2]->uu)*test;
f[1] = (k1*aold + k3*basis[2]->uuold)*test;
f[2] = (k1*aoldold + k3*basis[2]->uuoldold)*test;
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
}//namespace autocatalytic4
namespace timeonly
{
const double pi = 3.141592653589793;
//const double lambda = 10.;//pi*pi;
const double lambda = pi*pi;
const double ff(const double &u)
{
return -lambda*u;
}
RES_FUNC_TPETRA(residual_test_)
{
//test function
const double test = basis[0]->phi[i];
//u, phi
const double u[3] = {basis[0]->uu,basis[0]->uuold,basis[0]->uuoldold};
const double ut = (u[0]-u[1])/dt_*test;
const double f[3] = {ff(u[0])*test,ff(u[1])*test,ff(u[2])*test};
return ut - (1.-t_theta2_)*t_theta_*f[0]
- (1.-t_theta2_)*(1.-t_theta_)*f[1]
-.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
}//namespace timeonly
namespace radconvbc
{
double h = 50.;
double ep = .7;
double sigma = 5.67037e-9;
double ti = 323.;
double tau0_h = 1.;
double W0_h = 1.;
double deltau_h = 1.;
double uref_h = 0.;
double scaling_constant = 1.0;
DBC_FUNC(dbc_)
{
return 1173.;
}
NBC_FUNC_TPETRA(nbc_)
{
//https://reference.wolfram.com/language/PDEModels/tutorial/HeatTransfer/HeatTransfer.html#2048120463
//h(t-ti)+\ep\sigma(t^4-ti^4) = -g(t)
//du/dn = g
//return g*test here
//std::cout<<h<<" "<<ep<<" "<<sigma<<" "<<ti<<std::endl;
const double test = basis[0].phi[i];
const double u = deltau_h*basis[0].uu+uref_h; // T=deltau_h*theta+uref_h
const double uold = deltau_h*basis[0].uuold+uref_h;
const double uoldold = deltau_h*basis[0].uuoldold+uref_h;
#if 1
const double f[3] = {(h*(ti-u)+ep*sigma*(ti*ti*ti*ti-u*u*u*u))*test,
(h*(ti-uold)+ep*sigma*(ti*ti*ti*ti-uold*uold*uold*uold))*test,
(h*(ti-uoldold)+ep*sigma*(ti*ti*ti*ti-uoldold*uoldold*uoldold*uoldold))*test};
#else
const double c = h+4.*ep*sigma*ti*ti*ti;
const double f[3] = {(c*(ti-u))*test,
(c*(ti-uold))*test,
(c*(ti-uoldold))*test};
#endif
const double coef = deltau_h / W0_h;
//std::cout<<f[0]<<" "<<f[1]<<" "<<f[2]<<std::endl;
const double rv = (1.-t_theta2_)*t_theta_*f[0]
+(1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
return f[0] * coef * scaling_constant;
}
INI_FUNC(init_heat_)
{
return 1173.;
}
PARAM_FUNC(param_)
{
h = plist->get<double>("h_",50.);
ep = plist->get<double>("ep_",.7);
sigma = plist->get<double>("sigma_",5.67037e-9);
ti = plist->get<double>("ti_",323.);
deltau_h = plist->get<double>("deltau_",1.);
uref_h = plist->get<double>("uref_",0.);
W0_h = plist->get<double>("W0_",1.);
scaling_constant = plist->get<double>("scaling_constant_",1.);
// std::cout<<"tpetra::radconvbc::param_:"<<std::endl
// <<" h = "<<h<<std::endl
// <<" ep = "<<ep<<std::endl
// <<" sigma = "<<sigma<<std::endl
// <<" ti = "<<ti<<std::endl<<std::endl;
}
}//namespace radconvbc
namespace goldak{
TUSAS_DEVICE
const double pi_d = 3.141592653589793;
double te = 1641.;
double tl = 1706.;
double Lf = 2.95e5;
TUSAS_DEVICE
double dfldu_mushy_d = tpetra::heat::rho_d*Lf/(tl-te);//fl=(t-te)/(tl-te);
TUSAS_DEVICE
double eta_d = 0.3;
TUSAS_DEVICE
double P_d = 50.;
TUSAS_DEVICE
double s_d = 2.;
TUSAS_DEVICE
double r_d = .00005;
TUSAS_DEVICE
double d_d = .00001;
TUSAS_DEVICE
double gamma_d = 0.886227;
TUSAS_DEVICE
double x0_d = 0.;
TUSAS_DEVICE
double y0_d = 0.;
TUSAS_DEVICE
double z0_d = 0.;
TUSAS_DEVICE
double t_hold_d = 0.005;
TUSAS_DEVICE
double t_decay_d = 0.01;
TUSAS_DEVICE
double tau0_d = 1.;
TUSAS_DEVICE
double W0_d = 1.;
TUSAS_DEVICE
double t0_d = 300.;
TUSAS_DEVICE
double scaling_constant_d = 1.;
KOKKOS_INLINE_FUNCTION
void dfldt_uncoupled(GPUBasis * basis[], const int index, const double dt_, const double dtold_, double *a)
{
//the latent heat term is zero outside of the mushy region (ie outside Te < T < Tl)
//we need device versions of deltau_h,uref_h
const double coef = 1./tau0_d;
const double tt[3] = {tpetra::heat::deltau_h*basis[index]->uu+tpetra::heat::uref_h,
tpetra::heat::deltau_h*basis[index]->uuold+tpetra::heat::uref_h,
tpetra::heat::deltau_h*basis[index]->uuoldold+tpetra::heat::uref_h};
const double dfldu_d[3] = {((tt[0] > te) && (tt[0] < tl)) ? coef*dfldu_mushy_d : 0.0,
((tt[1] > te) && (tt[1] < tl)) ? coef*dfldu_mushy_d : 0.0,
((tt[2] > te) && (tt[2] < tl)) ? coef*dfldu_mushy_d : 0.0};
a[0] = ((1. + dt_/dtold_)*(dfldu_d[0]*basis[index]->uu-dfldu_d[1]*basis[index]->uuold)/dt_
-dt_/dtold_*(dfldu_d[0]*basis[index]->uu-dfldu_d[2]*basis[index]->uuoldold)/(dt_+dtold_)
);
a[1] = (dtold_/dt_/(dt_+dtold_)*(dfldu_d[0]*basis[index]->uu)
-(dtold_-dt_)/dt_/dtold_*(dfldu_d[1]*basis[index]->uuold)
-dt_/dtold_/(dt_+dtold_)*(dfldu_d[2]*basis[index]->uuoldold)
);
a[2] = (-(1.+dtold_/dt_)*(dfldu_d[2]*basis[index]->uuoldold-dfldu_d[1]*basis[index]->uuold)/dtold_
+dtold_/dt_*(dfldu_d[2]*basis[index]->uuoldold-dfldu_d[0]*basis[index]->uu)/(dtold_+dt_)
);
return;
}
KOKKOS_INLINE_FUNCTION
void dfldt_coupled(GPUBasis * basis[], const int index, const double dt_, const double dtold_, double *a)
{
const double coef = tpetra::heat::rho_d*tpetra::goldak::Lf/tau0_d;
const double dfldu_d[3] = {-.5*coef,-.5*coef,-.5*coef};
a[0] = ((1. + dt_/dtold_)*(dfldu_d[0]*basis[index]->uu-dfldu_d[1]*basis[index]->uuold)/dt_
-dt_/dtold_*(dfldu_d[0]*basis[index]->uu-dfldu_d[2]*basis[index]->uuoldold)/(dt_+dtold_)
);
a[1] = (dtold_/dt_/(dt_+dtold_)*(dfldu_d[0]*basis[index]->uu)
-(dtold_-dt_)/dt_/dtold_*(dfldu_d[1]*basis[index]->uuold)
-dt_/dtold_/(dt_+dtold_)*(dfldu_d[2]*basis[index]->uuoldold)
);
a[2] = (-(1.+dtold_/dt_)*(dfldu_d[2]*basis[index]->uuoldold-dfldu_d[1]*basis[index]->uuold)/dtold_
+dtold_/dt_*(dfldu_d[2]*basis[index]->uuoldold-dfldu_d[0]*basis[index]->uu)/(dtold_+dt_)
);
return;
}
KOKKOS_INLINE_FUNCTION
const double P(const double t)
{
// t is nondimensional
// t_hold, t_decay, and tt are dimensional
const double t_hold = t_hold_d;
const double t_decay = t_decay_d;
const double tt = t*tau0_d;
return (tt < t_hold) ? P_d :
((tt<t_hold+t_decay) ? P_d*((t_hold+t_decay)-tt)/(t_decay)
:0.);
}
KOKKOS_INLINE_FUNCTION
const double qdot(const double &x, const double &y, const double &z, const double &t)
{
// x, y, z, and t are nondimensional values
// r, d, and p and dimensional
// Qdot as a whole has dimensions, but that's ok since it's written in terms of non-dimensional (x,y,z,t)
const double p = P(t);
const double r = r_d;
const double d = d_d;
//s_d = 2 below; we can simplify this expression 5.19615=3^1.5
const double coef = eta_d*p*5.19615/r/r/d/gamma_d/pi_d;
const double exparg = ((W0_d*x-x0_d)*(W0_d*x-x0_d)+(W0_d*y-y0_d)*(W0_d*y-y0_d))/r/r+(W0_d*z-z0_d)*(W0_d*z-z0_d)/d/d;
const double f = exp( -3.* exparg );
return coef*f;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_test_)
{
//u_t,v + grad u,grad v - qdot,v = 0
double val = tpetra::heat::residual_heat_test_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
const double qd[3] = {-qdot(basis[eqn_id]->xx,basis[eqn_id]->yy,basis[eqn_id]->zz,time)*basis[eqn_id]->phi[i],
-qdot(basis[eqn_id]->xx,basis[eqn_id]->yy,basis[eqn_id]->zz,time-dt_)*basis[eqn_id]->phi[i],
-qdot(basis[eqn_id]->xx,basis[eqn_id]->yy,basis[eqn_id]->zz,time-dt_-dtold_)*basis[eqn_id]->phi[i]};
const double rv = (val
+ (1.-t_theta2_)*t_theta_*qd[0]
+ (1.-t_theta2_)*(1.-t_theta_)*qd[1]
+.5*t_theta2_*((2.+dt_/dtold_)*qd[1]-dt_/dtold_*qd[2]));
return rv;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_test_dp_)) = residual_test_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_uncoupled_test_)
{
//u_t,v + grad u,grad v + dfldt,v - qdot,v = 0
double val = tpetra::goldak::residual_test_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
double dfldu_d[3];
dfldt_uncoupled(basis,eqn_id,dt_,dtold_,dfldu_d);
const double dfldt[3] = {dfldu_d[0]*basis[eqn_id]->phi[i],
dfldu_d[1]*basis[eqn_id]->phi[i],
dfldu_d[2]*basis[eqn_id]->phi[i]};
const double rv = (val
+ (1.-t_theta2_)*t_theta_*dfldt[0]
+ (1.-t_theta2_)*(1.-t_theta_)*dfldt[1]
+.5*t_theta2_*((2.+dt_/dtold_)*dfldt[1]-dt_/dtold_*dfldt[2]));
return rv * scaling_constant_d;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_uncoupled_test_dp_)) = residual_uncoupled_test_;
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_coupled_test_)
{
//u_t,v + grad u,grad v + dfldt,v - qdot,v = 0
double val = tpetra::goldak::residual_test_dp_(basis,
i,
dt_,
dtold_,
t_theta_,
t_theta2_,
time,
eqn_id,
vol,
rand);
int phi_index = 1;
double dfldu_d[3];
dfldt_coupled(basis,phi_index,dt_,dtold_,dfldu_d);
const double dfldt[3] = {dfldu_d[0]*basis[eqn_id]->phi[i],
dfldu_d[1]*basis[eqn_id]->phi[i],
dfldu_d[2]*basis[eqn_id]->phi[i]};
const double rv = (val
+ (1.-t_theta2_)*t_theta_*dfldt[0]
+ (1.-t_theta2_)*(1.-t_theta_)*dfldt[1]
+.5*t_theta2_*((2.+dt_/dtold_)*dfldt[1]-dt_/dtold_*dfldt[2]));
return rv * scaling_constant_d;
}
TUSAS_DEVICE
RES_FUNC_TPETRA((*residual_coupled_test_dp_)) = residual_coupled_test_;
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(prec_test_)
{
const double val = tpetra::heat::prec_heat_test_dp_(basis,
i,
j,
dt_,
t_theta_,
eqn_id);
return val * scaling_constant_d;
}
TUSAS_DEVICE
PRE_FUNC_TPETRA((*prec_test_dp_)) = prec_test_;
INI_FUNC(init_heat_)
{
const double t_preheat = t0_d;
const double val = (t_preheat-tpetra::heat::uref_h)/tpetra::heat::deltau_h;
return val;
}
DBC_FUNC(dbc_)
{
// The assumption here is that the desired Dirichlet BC is the initial temperature,
// that may not be true in the future.
const double t_preheat = t0_d;
const double val = (t_preheat-tpetra::heat::uref_h)/tpetra::heat::deltau_h;
return val;
}
PPR_FUNC(postproc_qdot_)
{
const double x = xyz[0];
const double y = xyz[1];
const double z = xyz[2];
return qdot(x,y,z,time);
}
PPR_FUNC(postproc_u_)
{
return u[0]*tpetra::heat::deltau_h + tpetra::heat::uref_h;
}
PARAM_FUNC(param_)
{
//we need to set h, ep, sigma, ti in radconv params as follows:
//h = 100 W/(m2*K)
//ep = .3
//sigma = 5.6704 x 10-5 g s^-3 K^-4
//ti = 300 K
//we need to set rho_*, k_* and cp_* in heat params
//and also *maybe* figure out a way to distinguish between k_lig and k_sol
//when phasefield is coupled
//rho_* = 8.9 g/cm^3
//kliq = 90 W/(m*K)
//ksol = 90 W/(m*K)
//cpliq = 0.44 J/(g*K)
//cpsol = 0.44 J/(g*K)
//here we need the rest..
//and pull fro xml
//te = 1635.;// K
te = plist->get<double>("te_",1641.);
//tl = 1706.;// K
tl = plist->get<double>("tl_",1706.);
//Lf = 17.2;// kJ/mol
Lf = plist->get<double>("Lf_",2.95e5);
//eta_d = 0.3;//dimensionless
eta_d = plist->get<double>("eta_",0.3);
//P_d = 50.;// W
P_d = plist->get<double>("P_",50.);
//s_d = 2.;//dimensionless
s_d = plist->get<double>("s_",2.);
//r_d = .005;// 50 um
r_d = plist->get<double>("r_",.00005);
//d_d = .001;// 10 um
d_d = plist->get<double>("d_",.00001);
//gamma_d = is gamma function
//gamma(3/s):
//gamma(3/2) = sqrt(pi)/2
gamma_d = plist->get<double>("gamma_",0.886227);
x0_d = plist->get<double>("x0_",0.);
y0_d = plist->get<double>("y0_",0.);
z0_d = plist->get<double>("z0_",0.);
t_hold_d = plist->get<double>("t_hold_",0.005);
t_decay_d = plist->get<double>("t_decay_",0.01);
tau0_d = plist->get<double>("tau0_",1.);
W0_d = plist->get<double>("W0_",1.);
t0_d = plist->get<double>("t0_",300.);
dfldu_mushy_d = tpetra::heat::rho_d*Lf/(tl-te); //fl=(t-te)/(tl-te);
scaling_constant_d = plist->get<double>("scaling_constant_",1.);
}
}//namespace goldak
namespace fullycoupled
{
double hemisphere_IC_rad = 1.0;
double hemispherical_IC_x0 = 0.0;
double hemispherical_IC_y0 = 0.0;
double hemispherical_IC_z0 = 0.0;
bool hemispherical_IC = false;
INI_FUNC(init_conc_farzadi_)
{
return -1.;
}
INI_FUNC(init_phase_farzadi_)
{
if (hemispherical_IC){
const double w0 = tpetra::farzadi3d::w0;
const double dist = std::sqrt( (x-hemispherical_IC_x0/w0)*(x-hemispherical_IC_x0/w0)
+ (y-hemispherical_IC_y0/w0)*(y-hemispherical_IC_y0/w0)
+ (z-hemispherical_IC_z0/w0)*(z-hemispherical_IC_z0/w0));
const double r = hemisphere_IC_rad/w0 + tpetra::farzadi3d::amplitude*((double)rand()/(RAND_MAX));
return std::tanh( (dist-r)/std::sqrt(2.));
}
else {
double h = tpetra::farzadi3d::base_height + tpetra::farzadi3d::amplitude*((double)rand()/(RAND_MAX));
return std::tanh((h-z)/std::sqrt(2.));
double c = (x-tpetra::farzadi3d::x0)*(x-tpetra::farzadi3d::x0) + (y-tpetra::farzadi3d::y0)*(y-tpetra::farzadi3d::y0) + (z-tpetra::farzadi3d::z0)*(z-tpetra::farzadi3d::z0);
return ((tpetra::farzadi3d::C == 0) ? (tanh((h-z)/sqrt(2.))) : (c < tpetra::farzadi3d::r*tpetra::farzadi3d::r) ? 1. : -1.);
}
}
INI_FUNC(init_heat_)
{
const double t_preheat = tpetra::goldak::t0_d;
const double val = (t_preheat-tpetra::heat::uref_h)/tpetra::heat::deltau_h;
return val;
}
DBC_FUNC(dbc_)
{
// The assumption here is that the desired Dirichlet BC is the initial temperature,
// that may not be true in the future.
const double t_preheat = tpetra::goldak::t0_d;
const double val = (t_preheat-tpetra::heat::uref_h)/tpetra::heat::deltau_h;
return val;
}
PPR_FUNC(postproc_t_)
{
// return the physical temperature in K here
const double theta = u[2];
return theta * tpetra::heat::deltau_h + tpetra::heat::uref_h;
}
PARAM_FUNC(param_)
{
hemispherical_IC = plist->get<bool>("hemispherical_IC", false);
hemisphere_IC_rad = plist->get<double>("hemisphere_IC_rad", 1.0);
hemispherical_IC_x0 = plist->get<double>("hemispherical_IC_x0", 0.0);
hemispherical_IC_y0 = plist->get<double>("hemispherical_IC_y0", 0.0);
hemispherical_IC_z0 = plist->get<double>("hemispherical_IC_z0", 0.0);
}
}//namespace fullycoupled
namespace quaternion
{
//see
//[1] LLNL-JRNL-409478 A Numerical Algorithm for the Solution of a Phase-Field Model of Polycrystalline Materials
//M. R. Dorr, J.-L. Fattebert, M. E. Wickett, J. F. Belak, P. E. A. Turchi (2008)
//[2] LLNL-JRNL-636233 Phase-field modeling of coring during solidification of Au-Ni alloy using quaternions and CALPHAD input
//J. L. Fattebert, M. E. Wickett, P. E. A. Turchi May 7, 2013
const double beta = 1.e-10;
const double r0 = .064;
const double halfdx = .001;
const double Mq = 1.;//1/sec/pJ
const double Mphi = 1.;//1/sec/pJ
//const double Mmax = .64;//1/sec/pJ
//const double Mmin= 1.e-6;
const double Dmax = 1000.;
//const double Dmin = 1.e-6;
const double epq = .0477;//(pJ/um)^1/2
//const double epq = .0;//(pJ/um)^1/2
const double epphi = .083852;//(pJ/um)^1/2
// const double L = 2.e9;//J/m^3 =======>
const double L = 2000.;//pJ/um^3
const double omega = 31.25;//pJ/um^3
const double H = .884e-3;//pJ/K/um^2
//const double T = 1000.;//K
const double T = 1000.;//K
const double Tm = 1025.;//K
const int N = 4;
const double pi = 3.141592653589793;
const double dist(const double &x, const double &y, const double &z,
const double &x0, const double &y0, const double &z0,
const double &r)
{
const double c = (x-x0)*(x-x0) + (y-y0)*(y-y0) + (z-z0)*(z-z0);
return r-sqrt(c);
}
#if 0
const double getphi(const double &x, const double &y, const double &z,
const double &x0, const double &y0, const double &z0,
const double &r, const double &t)
{
double rnew = r + t*.003125*1.e5;
double d = dist(x,y,z,x0,y0,0,rnew);
const double scale = (1-0)/2.;
const double shift = (1+0)/2.;
double val = shift + scale*tanh(d/sqrt(2.)/.01);
return val;
}
#endif
const double p(const double &phi)
{
return phi*phi;
}
const double pp(const double &phi)
{
return 2.*phi;
}
const double h(const double &phi)
{
return phi*phi*phi*(10.-15.*phi+6.*phi*phi);
}
const double hp(const double &phi)
{
return 3.*phi*phi*(10.-15.*phi+6.*phi*phi)+phi*phi*phi*(-15.+12.*phi);
}
const double g(const double &phi)
{
return 16.*phi*phi*(1.-phi)*(1.-phi);
}
const double gp(const double &phi)
{
return 32.*phi*(1.-3.*phi+2.*phi*phi);
}
const double norm( const double &u1, const double &u2, const double &u3, const double &u4)
{
return sqrt(u1*u1+u2*u2+u3*u3+u4*u4);
}
const double normsquared( const double &u1, const double &u2, const double &u3, const double &u4)
{
return u1*u1+u2*u2+u3*u3+u4*u4;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_)
{
//derivatives of the test function
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
const double dtestdz = basis[0]->dphidz[i];
//test function
const double test = basis[0]->phi[i];
//u, phi
const double u = basis[eqn_id]->uu;
const double uold = basis[eqn_id]->uuold;
const double phi[3] = {basis[4]->uu,basis[4]->uuold,basis[4]->uuoldold};
const double m[3] = {1.-h(phi[0]),1.-h(phi[1]),1.-h(phi[2])};
double M[3] = {m[0]*(Mq+1e-6)+1e-6,m[1]*(Mq+1e-6)+1e-6,m[2]*(Mq+1e-6)+1e-6};
//double M[3] = {Mq,Mq,Mq};
//we need norm grad q here
//grad q is nonzero only within interfaces
double normgradq[3] = {0.,0.,0.};
for(int k = 0; k < N; k++){
normgradq[0] = normgradq[0] + basis[k]->dudx*basis[k]->dudx + basis[k]->dudy*basis[k]->dudy + basis[k]->dudz*basis[k]->dudz;
normgradq[1] = normgradq[1] + basis[k]->duolddx*basis[k]->duolddx + basis[k]->duolddy*basis[k]->duolddy + basis[k]->duolddz*basis[k]->duolddz;
normgradq[2] = normgradq[2] + basis[k]->duoldolddx*basis[k]->duoldolddx + basis[k]->duoldolddy*basis[k]->duoldolddy + basis[k]->duoldolddz*basis[k]->duoldolddz;
}
//std::cout<<normgradq[0]<<std::endl;
//const double betal = beta;
double b2 = beta*beta;
normgradq[0] = sqrt(b2 + normgradq[0]);
normgradq[1] = sqrt(b2 + normgradq[1]);
normgradq[2] = sqrt(b2 + normgradq[2]);
//const double ep[3] = {epq*epq,epq*epq,epq*epq};
const double ep[3] = {epq*epq*p(phi[0]),epq*epq*p(phi[1]),epq*epq*p(phi[2])};
double Dq[3] = {2.*T*H*p(phi[0]),2.*T*H*p(phi[1]),2.*T*H*p(phi[2])};
double pfu[3] = {0., 0., 0.};
double normq[3] = {0., 0., 0.};
for(int k = 0; k < N; k++){
pfu[0] = pfu[0] + basis[k]->uu*(basis[k]->dudx*dtestdx + basis[k]->dudy*dtestdy + basis[k]->dudz*dtestdz);
pfu[1] = pfu[1] + basis[k]->uuold*(basis[k]->duolddx*dtestdx + basis[k]->duolddy*dtestdy + basis[k]->duolddz*dtestdz);
pfu[2] = pfu[2] + basis[k]->uuoldold*(basis[k]->duoldolddx*dtestdx + basis[k]->duoldolddy*dtestdy + basis[k]->duoldolddz*dtestdz);
normq[0] = normq[0] + basis[k]->uu*basis[k]->uu;
normq[1] = normq[1] + basis[k]->uuold*basis[k]->uuold;
normq[2] = normq[2] + basis[k]->uuoldold*basis[k]->uuoldold;
}
b2 = beta*beta;
normq[0] = (normq[0] > b2 ) ? normq[0] : b2;
normq[1] = (normq[1] > b2 ) ? normq[1] : b2;
normq[2] = (normq[2] > b2 ) ? normq[2] : b2;
//DD is the diffusion term ep^ p + 2 H T p/normgradq
//const double DD[3] = {ep[0]*normgradq[0]+Dq[0],ep[1]*normgradq[1]+Dq[1],ep[2]*normgradq[2]+Dq[2]};
const double DD[3] = {ep[0]+Dq[0]/normgradq[0],ep[1]+Dq[1]/normgradq[1],ep[2]+Dq[2]/normgradq[2]};
//const double ut = normgradq[1]*(u-uold)/dt_*test;
const double ut = (u-uold)/dt_*test;
pfu[0] = -pfu[0]*u*M[0]*DD[0]/normq[0];
pfu[1] = -pfu[1]*uold*M[1]*DD[1]/normq[1];
pfu[2] = -pfu[2]*basis[eqn_id]->uuoldold*M[2]*DD[2]/normq[2];
if(pfu[0] != pfu[0]) exit(0);
if(pfu[1] != pfu[1]) exit(0);
if(pfu[2] != pfu[2]) exit(0);
const double divgradu[3] = {M[0]*DD[0]*(basis[eqn_id]->dudx*dtestdx + basis[eqn_id]->dudy*dtestdy + basis[eqn_id]->dudz*dtestdz),
M[1]*DD[1]*(basis[eqn_id]->duolddx*dtestdx + basis[eqn_id]->duolddy*dtestdy + basis[eqn_id]->duolddz*dtestdz),
M[2]*DD[2]*(basis[eqn_id]->duoldolddx*dtestdx + basis[eqn_id]->duoldolddy*dtestdy + basis[eqn_id]->duoldolddz*dtestdz)};
const double a = 1.;
const double f[3] = {divgradu[0]+a*pfu[0], divgradu[1]+a*pfu[1], divgradu[2]+a*pfu[2]};
double val= (ut + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]))/1.;//*normgradq[0];
// if(val!=val){
// std::cout<<divgradu[0]<<" "<<divgradu[1]<<" "<<divgradu[2]<<std::endl;
// }
// std::cout<<val<<" "<<i<<std::endl;
//val = 0.;
return val;
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(precon_)
{
const double phi = basis[4].uu;
double Dq = 2.*T*H*p(phi);
double m = 1.-h(phi);
double M = m*Mq;
//double M = Mq;
const double ep = epq*epq*p(phi);
double normgradq = 0.;
for(int k = 0; k < N; k++){
normgradq = normgradq + basis[k].dudx*basis[k].dudx + basis[k].dudy*basis[k].dudy + basis[k].dudz*basis[k].dudz;
}
const double betal = beta;
const double b2 = betal*betal;
normgradq = sqrt(b2 + normgradq);
Dq = Dq/normgradq;
//const double DD = ep*normgradq+Dq;
const double DD = ep+Dq;
//const double ut = normgradq*basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double ut = basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double divgradu = M*DD*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
return (ut + t_theta_*divgradu)/10.;
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phi_)
{
//derivatives of the test function
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
const double dtestdz = basis[0]->dphidz[i];
//test function
const double test = basis[0]->phi[i];
//u, phi
const double phi[3] = {basis[eqn_id]->uu, basis[eqn_id]->uuold, basis[eqn_id]->uuoldold};
const double phit = (phi[0]-phi[1])/dt_*test;
const double normq[3] = {sqrt(basis[0]->uu*basis[0]->uu+basis[1]->uu*basis[1]->uu+basis[2]->uu*basis[2]->uu+basis[3]->uu*basis[3]->uu),
sqrt(basis[0]->uuold*basis[0]->uuold+basis[1]->uuold*basis[1]->uuold+basis[2]->uuold*basis[2]->uuold+basis[3]->uuold*basis[3]->uuold),
sqrt(basis[0]->uuoldold*basis[0]->uuoldold+basis[1]->uuoldold*basis[1]->uuoldold+basis[2]->uuoldold*basis[2]->uuoldold+basis[3]->uuoldold*basis[3]->uuoldold)};
#if 0
//this shows that even though qold has norm 1 at nodes, it does not necessarily have norm 1 at guass pts
//what does this do to grad qold at guass pts?
if(t_theta_ < 1.){
if(normq[1] < 1.)
std::cout<<normq[0]<<" "<<norm(basis[0]->uu,basis[1]->uu,basis[2]->uu,basis[3]->uu)<<" "
<<normq[1]<<" "<<norm(basis[0]->uuold,basis[1]->uuold,basis[2]->uuold,basis[3]->uuold)<<std::endl;
}
#endif
//M eps^2 grad phi rrad test
const double divgradu[3] = {Mphi*epphi*epphi*(basis[eqn_id]->dudx*dtestdx + basis[eqn_id]->dudy*dtestdy + basis[eqn_id]->dudz*dtestdz),
Mphi*epphi*epphi*(basis[eqn_id]->duolddx*dtestdx + basis[eqn_id]->duolddy*dtestdy + basis[eqn_id]->duolddz*dtestdz),
Mphi*epphi*epphi*(basis[eqn_id]->duoldolddx*dtestdx + basis[eqn_id]->duoldolddy*dtestdy + basis[eqn_id]->duoldolddz*dtestdz)};
const double ww[3] = {Mphi*gp(phi[0])*test,
Mphi*gp(phi[1])*test,
Mphi*gp(phi[2])*test};
double normgradq[3] = {0.,0.,0.};
for(int k = 0; k < N; k++){
normgradq[0] = normgradq[0] + basis[k]->dudx*basis[k]->dudx + basis[k]->dudy*basis[k]->dudy + basis[k]->dudz*basis[k]->dudz;
normgradq[1] = normgradq[1] + basis[k]->duolddx*basis[k]->duolddx + basis[k]->duolddy*basis[k]->duolddy + basis[k]->duolddz*basis[k]->duolddz;
normgradq[2] = normgradq[2] + basis[k]->duoldolddx*basis[k]->duoldolddx + basis[k]->duoldolddy*basis[k]->duoldolddy + basis[k]->duoldolddz*basis[k]->duoldolddz;
}
const double betal = 0.*beta;
const double b2 = betal*betal;
normgradq[0] = sqrt(b2 + normgradq[0]);//(normgradq[0] > b2) ? sqrt(normgradq[0]) : betal;
normgradq[1] = sqrt(b2 + normgradq[1]);//(normgradq[1] > b2) ? sqrt(normgradq[1]) : betal;
normgradq[2] = sqrt(b2 + normgradq[2]);//(normgradq[2] > b2) ? sqrt(normgradq[2]) : betal;
//coupling term
const double pq[3] = {Mphi*2.*H*T*pp(phi[0])*normgradq[0]*test,
Mphi*2.*H*T*pp(phi[1])*normgradq[1]*test,
Mphi*2.*H*T*pp(phi[2])*normgradq[2]*test};
const double hh[3] = {(Mphi*hp(phi[0])*L*(T-Tm)/Tm*test),
(Mphi*hp(phi[1])*L*(T-Tm)/Tm*test),
(Mphi*hp(phi[2])*L*(T-Tm)/Tm*test)};
const double epqq[3] = {0.,0.,0.};
// const double epqq[3] = {Mphi*epq*epq*phi[0]*normgradq[0]*normgradq[0]*test,
// Mphi*epq*epq*phi[1]*normgradq[1]*normgradq[1]*test,
// Mphi*epq*epq*phi[2]*normgradq[2]*normgradq[2]*test};
const double f[3] = {divgradu[0] + ww[0] + pq[0] + hh[0] + epqq[0],
divgradu[1] + ww[1] + pq[1] + hh[1] + epqq[1],
divgradu[2] + ww[2] + pq[2] + hh[2] + epqq[2]};
return phit + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_phase_)
{
//derivatives of the test function
const double dtestdx = basis[0]->dphidx[i];
const double dtestdy = basis[0]->dphidy[i];
const double dtestdz = basis[0]->dphidz[i];
//test function
const double test = basis[0]->phi[i];
//u, phi
const double phi[3] = {basis[eqn_id]->uu, basis[eqn_id]->uuold, basis[eqn_id]->uuoldold};
const double phit = (phi[0]-phi[1])/dt_*test;
//M eps^2 grad phi rrad test
const double divgradu[3] = {Mphi*epphi*epphi*(basis[eqn_id]->dudx*dtestdx + basis[eqn_id]->dudy*dtestdy + basis[eqn_id]->dudz*dtestdz),
Mphi*epphi*epphi*(basis[eqn_id]->duolddx*dtestdx + basis[eqn_id]->duolddy*dtestdy + basis[eqn_id]->duolddz*dtestdz),
Mphi*epphi*epphi*(basis[eqn_id]->duoldolddx*dtestdx + basis[eqn_id]->duoldolddy*dtestdy + basis[eqn_id]->duoldolddz*dtestdz)};
const double ww[3] = {Mphi*gp(phi[0])*test,
Mphi*gp(phi[1])*test,
Mphi*gp(phi[2])*test};
//double normgradq[3] = {0.,0.,0.};
double normgradq[3] = {1.,1.,1.};
//coupling term
const double pq[3] = {Mphi*2.*H*T*pp(phi[0])*normgradq[0]*test,
Mphi*2.*H*T*pp(phi[1])*normgradq[1]*test,
Mphi*2.*H*T*pp(phi[2])*normgradq[2]*test};
const double hh[3] = {(Mphi*hp(phi[0])*L*(T-Tm)/Tm*test),
(Mphi*hp(phi[1])*L*(T-Tm)/Tm*test),
(Mphi*hp(phi[2])*L*(T-Tm)/Tm*test)};
const double epqq[3] = {0.,0.,0.};
// const double epqq[3] = {Mphi*epq*epq*phi[0]*normgradq[0]*normgradq[0]*test,
// Mphi*epq*epq*phi[1]*normgradq[1]*normgradq[1]*test,
// Mphi*epq*epq*phi[2]*normgradq[2]*normgradq[2]*test};
const double f[3] = {divgradu[0] + ww[0] + pq[0] + hh[0] + epqq[0],
divgradu[1] + ww[1] + pq[1] + hh[1] + epqq[1],
divgradu[2] + ww[2] + pq[2] + hh[2] + epqq[2]};
return phit + (1.-t_theta2_)*t_theta_*f[0]
+ (1.-t_theta2_)*(1.-t_theta_)*f[1]
+.5*t_theta2_*((2.+dt_/dtold_)*f[1]-dt_/dtold_*f[2]);
}
KOKKOS_INLINE_FUNCTION
PRE_FUNC_TPETRA(precon_phi_)
{
const double phit = basis[eqn_id].phi[j]/dt_*basis[eqn_id].phi[i];
const double divgradphi = Mphi*epphi*epphi*(basis[eqn_id].dphidx[j]*basis[eqn_id].dphidx[i]
+ basis[eqn_id].dphidy[j]*basis[eqn_id].dphidy[i]
+ basis[eqn_id].dphidz[j]*basis[eqn_id].dphidz[i]);
const double ww = Mphi*16.*omega*(1.-2.*basis[eqn_id].uu)*basis[eqn_id].phi[j]*basis[eqn_id].phi[i];
return phit + t_theta_*(divgradphi + ww);
}
//q0 is -.5 lower right
INI_FUNC(initq0_)
{
double val = .0;
const double s = .001;
const double den = sqrt(2)*s;
val = .5*(1.+tanh((r0-x)/den)+tanh((y-r0)/den));
if (val > .5) val = .5;
return val;
}
INI_FUNC(initq0s_)
{
double val = .5;
const double s = r0 + halfdx;
if (x > s && y < s) val = -.5;
return val;
}
//q1 is -.5 in upper right
INI_FUNC(initq1_)
{
double val = .0;//.5
const double s = .001;
const double den = sqrt(2)*s;
//if (x > r0 && y > r0 ) val = -.5;
val = .5*(1.+tanh((r0-x)/den)+tanh((r0-y)/den));
if (val > .5) val = .5;
return val;
}
INI_FUNC(initq1s_)
{
double val = .5;
const double s = r0 + halfdx;
if (x > s && y > s) val = -.5;
return val;
}
//q2 and q3 are .5 everywhere
INI_FUNC(initq2_)
{
return 0.5;
}
INI_FUNC(initq3_)
{
return 0.5;
}
INI_FUNC(initphi_)
{
double val = 0.;
const double x0 = 0.;
const double x1 = .128;
const double s = .001;
const double den = sqrt(2)*s;
//if( x*x + y*y <= r0*r0 ) val = 1.;
val = .5*(tanh((r0-sqrt(x*x + y*y))/den) + 1.);
//if( (x-x1)*(x-x1) + y*y <= r0*r0 ) val = 1.;
val += .5*(tanh((r0-sqrt((x-x1)*(x-x1) + y*y))/den) + 1.);
//if( (x-x1)*(x-x1) + (y-x1)*(y-x1) <= r0*r0 ) val = 1.;
val += .5*(tanh((r0-sqrt((x-x1)*(x-x1) + (y-x1)*(y-x1)))/den) + 1.);
//if( x*x + (y-x1)*(y-x1) <= r0*r0 ) val = 1.;
val += .5*(tanh((r0-sqrt(x*x + (y-x1)*(y-x1)))/den) + 1.);
return val;
}
INI_FUNC(init_)
{
//this will be a function of eqn_id...
const double r = .2;
const double x0 = .5;
const double y0 = .5;
const double w = .01;//.025;
//g1 is the background grain
//g0 is black??
const double g0[4] = {-0.707106781186547,
-0.000000000000000,
0.707106781186548,
-0.000000000000000};
const double g1[4] = {0.460849109679818,
0.025097870693789,
0.596761014095944,
0.656402686655941};
const double g2[4] = {0.659622270251558,
0.314355942642574,
0.581479198986258,
-0.357716008950928};
const double g3[4] = {0.610985843880283,
-0.625504969359875,
-0.474932634235629,
-0.099392277476709};
double scale = (g2[eqn_id]-g1[eqn_id])/2.;
double shift = (g2[eqn_id]+g1[eqn_id])/2.;
double d = dist(x,y,z,x0,y0,0,r);
double val = shift + scale*tanh(d/sqrt(2.)/w);
return val;
}
//https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
//atan2 returns [-pi,pi]
//asin returns [-pi/2,pi/2]
//paraview expects [0,1] for an rgb value
//https://discourse.paraview.org/t/coloring-surface-by-predefined-rgb-values/6011/6
//so should we shift and scale each of these here?
//Also the page seems different today, 4-12-23
//And our convention to normalize via:
// return (s+pi)/2./pi;
//so that each angle is between 0 and 1 can be used as RGB coloring
//Also, with the example, q=[.5 -.5 .5 .5] and roundoff, etc
//produces arguments to atan2 with near +/- 0, producing oscillations
//we need to fix this
//ie small chages in q lead to large changes in euler angle
#if 0
EulerAngles ToEulerAngles(Quaternion q) {
EulerAngles angles;
// roll (x-axis rotation)
double sinr_cosp = 2 * (q.w * q.x + q.y * q.z);
double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y);
angles.roll = std::atan2(sinr_cosp, cosr_cosp);
// pitch (y-axis rotation)
double sinp = std::sqrt(1 + 2 * (q.w * q.y - q.x * q.z));
double cosp = std::sqrt(1 - 2 * (q.w * q.y - q.x * q.z));
angles.pitch = 2 * std::atan2(sinp, cosp) - M_PI / 2;
// yaw (z-axis rotation)
double siny_cosp = 2 * (q.w * q.z + q.x * q.y);
double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z);
angles.yaw = std::atan2(siny_cosp, cosy_cosp);
return angles;
}
#endif
PPR_FUNC(postproc_ea0_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
// w x y z
double sinr_cosp = 2. * (u[0] * u[1] + u[2] * u[3]);
// x x y y
double cosr_cosp = 1. - 2. * (u[1] * u[1] + u[2] * u[2]);
double s = std::atan2(sinr_cosp, cosr_cosp);
return (s+pi)/2./pi;
//return s;
}
PPR_FUNC(postproc_ea1_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
// w y z x
double sinp = 2 * (u[0] * u[2] - u[3] * u[1]);
double s = 0.;
if (std::abs(sinp) >= 1.){
//if (std::abs(sinp) >= .95){
s = std::copysign(pi / 2., sinp); // use 90 degrees if out of range
}else{
s = std::asin(sinp);
}
return (s+pi/2.)/pi;
//return s;
}
PPR_FUNC(postproc_ea2_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
// w z x y
double siny_cosp = 2. * (u[0] * u[3] + u[1] * u[2]);
// y y z z
double cosy_cosp = 1. - 2. * (u[2] * u[2] + u[3] * u[3]);
double s = std::atan2(siny_cosp, cosy_cosp);
return (s+pi)/2./pi;
//return s;
}
//a possible alternative to euler angles is to just consider the quaternion as rgba color
//there may be visualization ttols that allow for this, although doesn't seem easy in
//paraview
//rgba can be converted to rgb via the following, assuming some background color BGColor,
//and all values normalized in [0 1]:
// Source => Target = (BGColor + Source) =
// Target.R = ((1 - Source.A) * BGColor.R) + (Source.A * Source.R)
// Target.G = ((1 - Source.A) * BGColor.G) + (Source.A * Source.G)
// Target.B = ((1 - Source.A) * BGColor.B) + (Source.A * Source.B)
//
//note that in our example problem, q0 and q1 can have values in [-.5 .5]
//but paraview does not seem to care about negative values
PPR_FUNC(postproc_rgb_r_)
{
return (1.-u[3])*0.+u[3]*u[0];
}
PPR_FUNC(postproc_rgb_g_)
{
return (1.-u[3])*0.+u[3]*u[1];
}
PPR_FUNC(postproc_rgb_b_)
{
return (1.-u[3])*0.+u[3]*u[2];
}
PPR_FUNC(postproc_normqold_)
{
return uold[0]*uold[0]+uold[1]*uold[1]+uold[2]*uold[2]+uold[3]*uold[3];
}
PPR_FUNC(postproc_normq_)
{
return u[0]*u[0]+u[1]*u[1]+u[2]*u[2]+u[3]*u[3];
}
PPR_FUNC(postproc_d_)
{
double phi=u[4];
return 2*H*T*p(phi);
}
PPR_FUNC(postproc_qdotqt_)
{
double s = 0.;
for(int k = 0; k < 4; k++) s = s + u[k]*(u[k]-uold[k])/dt;
return s;
}
PPR_FUNC(postproc_normgradq_)
{
double s = 0.;
for(int k = 0; k < 12; k++) s = s + gradu[k]*gradu[k];
return s;
}
PPR_FUNC(postproc_qdotqold_)
{
double s = 0.;
for(int k = 0; k < 4; k++) s = s + u[k]*uold[k];
return s;
}
PPR_FUNC(postproc_normphi_)
{
double s = u[4]*u[4];
return s;
}
}//namespace quaternion
namespace grain
{
//see
//[1] Suwa et al, Mater. T. JIM., 44,11, (2003);
//[2] Krill et al, Acta Mater., 50,12, (2002);
double L = 1.;
double alpha = 1.;
double beta = 1.;
double gamma = 1.;
double kappa = 2.;
int N = 6;
double pi = 3.141592653589793;
double r(const double &x,const int &n){
return sin(64./512.*x*n*pi);
}
PARAM_FUNC(param_)
{
N = plist->get<int>("numgrain");
}
KOKKOS_INLINE_FUNCTION
RES_FUNC_TPETRA(residual_)
{
//derivatives of the test function
double dtestdx = basis[0]->dphidx[i];
double dtestdy = basis[0]->dphidy[i];
double dtestdz = basis[0]->dphidz[i];
double test = basis[0]->phi[i];
double u = basis[eqn_id]->uu;
double uold = basis[eqn_id]->uuold;
double divgradu = kappa*(basis[eqn_id]->dudx*dtestdx + basis[eqn_id]->dudy*dtestdy + basis[eqn_id]->dudz*dtestdz);
double s = 0.;
for(int k = 0; k < N; k++){
s = s + basis[k]->uu*basis[k]->uu;
}
s = s - u*u;
return (u-uold)/dt_*test + L* ((-alpha*u + beta*u*u*u +2.*gamma*u*s)*test + divgradu);
}
PRE_FUNC(prec_)
{
#if 0
//cn probably want to move each of these operations inside of getbasis
//derivatives of the test function
double dtestdx = basis[0].dphidxi[i]*basis[0].dxidx
+basis[0].dphideta[i]*basis[0].detadx
+basis[0].dphidzta[i]*basis[0].dztadx;
double dtestdy = basis[0].dphidxi[i]*basis[0].dxidy
+basis[0].dphideta[i]*basis[0].detady
+basis[0].dphidzta[i]*basis[0].dztady;
double dtestdz = basis[0].dphidxi[i]*basis[0].dxidz
+basis[0].dphideta[i]*basis[0].detadz
+basis[0].dphidzta[i]*basis[0].dztadz;
double dbasisdx = basis[0].dphidxi[j]*basis[0].dxidx
+basis[0].dphideta[j]*basis[0].detadx
+basis[0].dphidzta[j]*basis[0].dztadx;
double dbasisdy = basis[0].dphidxi[j]*basis[0].dxidy
+basis[0].dphideta[j]*basis[0].detady
+basis[0].dphidzta[j]*basis[0].dztady;
double dbasisdz = basis[0].dphidxi[j]*basis[0].dxidz
+basis[0].dphideta[j]*basis[0].detadz
+basis[0].dphidzta[j]*basis[0].dztadz;
double u = basis[eqn_id].uu;
double test = basis[0].phi[i];
double divgrad = L*kappa*(dbasisdx * dtestdx + dbasisdy * dtestdy + dbasisdz * dtestdz);
double u_t =test * basis[0].phi[j]/dt_;
double alphau = -test*L*alpha*basis[0].phi[j];
double betau = 3.*u*u*basis[0].phi[j]*test*L*beta;
double s = 0.;
for(int k = 0; k < N; k++){
s = s + basis[k].uu*basis[k].uu;
}
s = s - u*u;
double gammau = 2.*gamma*L*basis[0].phi[j]*s*test;
return u_t + divgrad + betau + gammau;// + alphau ;
#endif
return 1.;
}
PPR_FUNC(postproc_)
{
//u is u0,u1,...
//gradu is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz...
double s =0.;
for(int j = 0; j < N; j++){
s = s + u[j]*u[j];
}
return s;
}
}//namespace grain
namespace random
{
RES_FUNC_TPETRA(residual_test_)
{
//test function
const double test = basis[0]->phi[i];
//printf("%d %le \n",i,rand);
return (basis[0]->uu - rand)*test;
}
}//namespace random
NBC_FUNC_TPETRA(nbc_one_)
{
double phi = basis->phi[i];
return 1.*phi;
}
}//namespace tpetra
#endif
|
//---------------------------------------------------------------------------
#ifndef ParseTreeH
#define ParseTreeH
//---------------------------------------------------------------------------
#include "IParseEngine.h"
#include "ISourceData.h"
class ParseTree;
class ClassMember;
class ParseTreeNode
{
friend ParseTree;
private:
//必备数据
IParseEngine * m_Engine;
IClassManager * m_ClassManager;
IClassMember * m_ClassMember;
//解析用数据
char * m_lpData; //完整数据
int m_Len; //完整数据长度
int m_CurPos;
int m_ParseLen;
String m_ParseResult;
int m_bParsed; //是否解析过
int m_Key;
void ParseCurNode();
//构建树的数据
AList<ParseTreeNode> m_ParseTreeNodes;
AList<ClassMember> m_NodesExtData; //数组创建的附加节点, 无用, 回收垃圾
ParseTreeNode * m_Prev;
ParseTreeNode * m_Next;
ParseTreeNode * m_Parent;
ParseTreeNode * FindArrayVarPre(String arrayVar); //[动态数组]向前找到变量内容
void SetParseData(char *lpData, int Len, int pos);
void BalanceChildTreeCount(int curCount);
void SetClassMember(IClassMember * member){m_ClassMember = member;}
protected:
void SetPrev(ParseTreeNode *prev);
void SetNext(ParseTreeNode *next);
void SetParent(ParseTreeNode *parent);
ParseTreeNode * AddChild(IClassMember * classMember);
public:
ParseTreeNode(IParseEngine * engine, IClassMember * classMember, IClassManager * classManager);
~ParseTreeNode();
IClassMember * GetClassMember(){return m_ClassMember;}
//叶子节点使用, 解析数据
String GetParseResult();
int GetParseLen();
int GetCurPos(){return m_CurPos;}
void Clear();
//树形控制
int GetChildCount(){return m_ParseTreeNodes.Count();}
ParseTreeNode * GetChild(int index){return m_ParseTreeNodes[index];}
ParseTreeNode * GetPrev(){return m_Prev;}
ParseTreeNode * GetNext(){return m_Next;}
ParseTreeNode * GetParent(){return m_Parent;}
//解析控制
void UnPackData(char *lpData, int Len, int& pos, int Key=0);
void Parse();
bool IsNeedParse();
//界面控制
String GetTreeText();
void SetExNodeName();
};
/////////////////////////////////////////////////////////////////////////////
class ParseTree
{
private:
IParseEngine * m_Engine;
IClassManager * m_ClassManager;
IClassData * m_ClassData;
TTreeNodes * m_TreeNodes;
char * m_lpData;
int m_Len;
int m_CurPos;
int m_Key;
//解析
int m_bUnpacked; //是否已经展开过
int m_bParsed; //是否已经解析过
//树的数据
AList<ParseTreeNode> m_ParseTreeNodes;
String GetStructText();
void SetView();
void RefreshTreeText(TTreeNode * curNode);
void AddUnVisibleNode(TTreeNode * parent, ParseTreeNode * parentData, int type);//0: 父为结构体 1:普通
public:
ParseTree(IParseEngine * engine, IClassManager * classManager);
~ParseTree();
//初始化
void BindClass(IClassData * curClass);
void SetParseData(char * lpData, int Len, int Key=0);
void UnPackData(int pos, int needRefresh = 0); //第一步: 展开数据, 分配每个数据的解析位置, 计算总长度
void ParseData(); //第二步: 解析数据
int GetSize();
int GetCurPos(){return m_CurPos;}
//树视图
void BindView(TTreeNodes * curTreeNodes);
void ViewCurNode(ParseTreeNode * parseTreeNode, TTreeNode * treeNode);
void RefreshViewText();
IClassData * GetClassData();
IClassManager *GetClassManager();
//导出数据
ParseTreeNode * GetParseTreeNode(int index){return m_ParseTreeNodes[index];}
int GetParseTreeNodeCount(){return m_ParseTreeNodes.Count();}
};
#endif
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "COOP_GameInstance.h"
#include "UObject/ConstructorHelpers.h"
#include "Blueprint/UserWidget.h"
#include "Interfaces/OnlineSessionInterface.h"
#include "OnlineSessionSettings.h"
#include "COOP_GameMode_Base.h"
#include "MenuSystem/COOP_MainMenu.h"
#include "MenuSystem/MenuWidget.h"
#include "MenuSystem/COOP_PauseMenu.h"
const FName CURRENT_SESSION = NAME_GameSession; /*TEXT("Game");*/
UCOOP_GameInstance::UCOOP_GameInstance(const FObjectInitializer& ObjectInitializer)
{
ConstructorHelpers::FClassFinder<UUserWidget> MainMenuWBPClass(TEXT("/Game/Blueprints/UI/WBP_MainMenu"));
if (!ensure(MainMenuWBPClass.Class != nullptr)) return;
MainMenuClass = MainMenuWBPClass.Class;
ConstructorHelpers::FClassFinder<UUserWidget> PauseMenuWBPClass(TEXT("/Game/Blueprints/UI/WBP_PauseMenu"));
if (!ensure(PauseMenuWBPClass.Class != nullptr)) return;
PauseMenuClass = PauseMenuWBPClass.Class;
SessionSettings.bIsLANMatch = true;
SessionSettings.NumPublicConnections = 1;
SessionSettings.bShouldAdvertise = true;
SessionSettings.bIsDedicated = false;
SessionSettings.bUsesPresence = true;
}
void UCOOP_GameInstance::Init()
{
IOnlineSubsystem* Subsystem = IOnlineSubsystem::Get();
if (Subsystem != nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("Subsystem name is: %s"), *Subsystem->GetSubsystemName().ToString());
SessionInterface = Subsystem->GetSessionInterface();
if (SessionInterface.IsValid())
{
UE_LOG(LogTemp, Warning, TEXT("Session found"));
SessionInterface->OnCreateSessionCompleteDelegates.AddUObject(this, &UCOOP_GameInstance::OnCreateNewSessionComplete);
SessionInterface->OnFindSessionsCompleteDelegates.AddUObject(this, &UCOOP_GameInstance::OnFindSessionsComplete);
SessionInterface->OnJoinSessionCompleteDelegates.AddUObject(this, &UCOOP_GameInstance::OnJoinSessionComplete);
//SessionInterface->OnSessionFailureDelegates.AddUObject(this, &UCOOP_GameInstance::OnSessionLost);
//SessionInterface->OnDestroySessionCompleteDelegates.AddUObject(this, &UCOOP_GameInstance::OnDestroySessionsComplete);
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("No Subsystem found!"));
}
}
void UCOOP_GameInstance::HostGame()
{
if (SessionInterface.IsValid())
{
if (SessionInterface->GetNamedSession(CURRENT_SESSION) != nullptr)
{
SessionInterface->DestroySession(CURRENT_SESSION);
UE_LOG(LogTemp, Error, TEXT("Session DELETED!"));
}
/*@TODO: Set a proper settings menu =========
//==========================================*/
ACOOP_GameMode_Base* CurrentGameMode = Cast<ACOOP_GameMode_Base>(GetWorld()->GetAuthGameMode());
if (CurrentGameMode)
{
SessionSettings = CurrentGameMode->GameSessionSettings;
}
/*SessionSettings.bIsLANMatch = true;
SessionSettings.NumPublicConnections = 4;
SessionSettings.bShouldAdvertise = true;
SessionSettings.bIsDedicated = false;
SessionSettings.bUsesPresence = true;*/
SessionInterface->CreateSession(0, CURRENT_SESSION, SessionSettings);
}
}
void UCOOP_GameInstance::OnCreateNewSessionComplete(FName SessionName, bool Success)
{
if (Success)
{
UE_LOG(LogTemp, Warning, TEXT("HOSTING GAME"));
if (MainMenu != nullptr)
{
MainMenu->Teardown();
}
GetWorld()->ServerTravel("/Game/Maps/Lobby?listen");
}
}
void UCOOP_GameInstance::FindNewSessions()
{
SessionSearch = MakeShareable(new FOnlineSessionSearch());
if (SessionSearch.IsValid())
{
SessionSearch->MaxSearchResults = 100;
SessionSearch->bIsLanQuery = true;
SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals);
UE_LOG(LogTemp, Warning, TEXT("Finding sessions!"));
SessionInterface->FindSessions(0, SessionSearch.ToSharedRef());
}
}
void UCOOP_GameInstance::OnFindSessionsComplete(bool Success)
{
auto& SessionSearchResults = SessionSearch->SearchResults;
int32 NumPlayersSlots = 0;
int32 NumMaxPlayers = 0;
if (SessionSearchResults.Num() > 0)
{
TArray<FString> ServerList;
for (int32 i = 0; i < SessionSearchResults.Num(); i++)
{
ServerList.AddUnique(*SessionSearchResults[i].GetSessionIdStr());
NumMaxPlayers = SessionSearchResults[i].Session.SessionSettings.NumPublicConnections;
NumPlayersSlots = NumMaxPlayers - SessionSearchResults[i].Session.NumOpenPublicConnections;
FString ServerUserName = SessionSearchResults[i].Session.OwningUserName;
MainMenu->AddEntityToServerList(ServerList, NumPlayersSlots, NumMaxPlayers, ServerUserName);
UE_LOG(LogTemp, Warning, TEXT("Available session id: %s"), *SessionSearchResults[i].GetSessionIdStr());
}
}
UE_LOG(LogTemp, Warning, TEXT("Session search complete!"));
}
void UCOOP_GameInstance::JoinGame(int32 ServerIndex)
{
UE_LOG(LogTemp, Warning, TEXT("Joinging Server with index %i"), ServerIndex);
if(!SessionInterface.IsValid()) return;
if (!SessionSearch.IsValid()) return;
if (MainMenu != nullptr)
{
MainMenu->Teardown();
}
SessionInterface->JoinSession(0, CURRENT_SESSION, SessionSearch->SearchResults[ServerIndex]);
}
void UCOOP_GameInstance::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
{
if (!SessionInterface.IsValid()) return;
FString ServerToJoin;
if (!SessionInterface->GetResolvedConnectString(SessionName, ServerToJoin))
{
UE_LOG(LogTemp, Error, TEXT("ConnectString and/ServerToJoin are not valid"));
return;
}
APlayerController* PlayerController = GetFirstLocalPlayerController();
if(!ensure(PlayerController != nullptr)) return;
PlayerController->ClientTravel(ServerToJoin, ETravelType::TRAVEL_Absolute);
}
void UCOOP_GameInstance::OnDestroySessionsComplete()
{
ClientTravelToLevel(MainMenuLevel);
}
void UCOOP_GameInstance::LoadMenu()
{
if (MainMenuClass == nullptr) { return; }
MainMenu = CreateWidget<UCOOP_MainMenu>(this, MainMenuClass);
if (MainMenu != nullptr)
{
MainMenu->Setup();
MainMenu->SetMenuInterface(this);
}
}
void UCOOP_GameInstance::LoadPauseMenu()
{
if (PauseMenuClass == nullptr) { return; }
PauseMenu = CreateWidget<UCOOP_PauseMenu>(this, PauseMenuClass);
if (PauseMenu != nullptr)
{
PauseMenu->Setup();
PauseMenu->SetMenuInterface(this);
}
}
void UCOOP_GameInstance::ClientTravelToLevel(const FString& LevelToTravel)
{
APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
if (PlayerController == nullptr) { return; }
PlayerController->ClientTravel(*LevelToTravel, ETravelType::TRAVEL_Absolute);
}
void UCOOP_GameInstance::OnSessionLost()
{
SessionInterface->DestroySession(CURRENT_SESSION);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/tempbuf.h"
#include "modules/encodings/encoders/outputconverter.h"
#include "modules/encodings/utility/charsetnames.h"
#include "modules/pi/OpFont.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/layout/box/box.h"
#include "modules/layout/box/blockbox.h"
#include "modules/layout/box/inline.h"
#include "modules/layout/box/tables.h"
#include "modules/layout/content/content.h"
#include "modules/layout/traverse/traverse.h"
#include "modules/layout/cascade.h"
#include "modules/layout/layout.h"
#include "modules/layout/layout_workplace.h"
#include "modules/logdoc/attr_val.h"
#include "modules/probetools/probepoints.h"
#include "modules/logdoc/src/textdata.h"
#include "modules/logdoc/logdoc_util.h"
#include "modules/logdoc/cssprop_storage.h"
#include "modules/logdoc/xml_ev.h"
#include "modules/logdoc/xmlevents.h"
#include "modules/logdoc/complex_attr.h"
#include "modules/logdoc/src/attribute.h"
#include "modules/logdoc/src/textdata.h"
#include "modules/logdoc/datasrcelm.h"
#include "modules/logdoc/src/xml.h"
#include "modules/logdoc/html5parser.h"
#include "modules/logdoc/elementref.h"
#include "modules/logdoc/stringtokenlist_attribute.h"
#include "modules/logdoc/source_position_attr.h"
#include "modules/url/url_api.h"
#include "modules/url/url2.h"
#include "modules/logdoc/urlimgcontprov.h"
#include "modules/logdoc/helistelm.h"
#include "modules/dom/domevents.h"
#include "modules/formats/argsplit.h"
#include "modules/forms/form.h"
#include "modules/forms/formvaluelistener.h"
#include "modules/forms/formvalueradiocheck.h"
#include "modules/forms/formvaluetext.h"
#include "modules/forms/formvaluetextarea.h"
#include "modules/forms/formvaluelist.h"
#include "modules/forms/formmanager.h"
#include "modules/forms/webforms2number.h"
#include "modules/forms/webforms2support.h"
#include "modules/display/VisDevListeners.h"
#include "modules/olddebug/timing.h"
#include "modules/debug/debug.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/viewers/viewers.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/locale/locale-enum.h"
#include "modules/logdoc/htm_lex.h"
#include "modules/logdoc/logdoc_constants.h"
#include "modules/logdoc/htm_ldoc.h"
#include "modules/logdoc/html5parser.h"
#include "modules/logdoc/src/html5/html5tokenwrapper.h"
#include "modules/logdoc/html5namemapper.h"
#include "modules/style/css.h"
#include "modules/style/css_media.h"
#include "modules/style/css_dom.h"
#include "modules/style/css_property_list.h"
#include "modules/style/css_style_attribute.h"
#include "modules/style/css_svgfont.h"
#include "modules/style/css_viewport_meta.h"
#include "modules/display/vis_dev.h"
#include "modules/display/styl_man.h"
#include "modules/forms/piforms.h"
#include "modules/forms/formsenum.h"
#include "modules/forms/formvalue.h"
#include "modules/doc/frm_doc.h"
#include "modules/doc/html_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/util/handy.h"
#include "modules/util/htmlify.h"
#include "modules/security_manager/include/security_manager.h"
#include "modules/media/media.h"
#include "modules/ecmascript/ecmascript.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esthread.h"
#include "modules/ecmascript_utils/esterm.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/dom/domenvironment.h"
#include "modules/dom/domutils.h"
#include "modules/wand/wandmanager.h"
#include "modules/windowcommander/src/TransferManagerDownload.h"
#ifdef DOCUMENT_EDIT_SUPPORT
# include "modules/documentedit/OpDocumentEdit.h"
#endif // DOCUMENT_EDIT_SUPPORT
#ifdef PICTOGRAM_SUPPORT
# include "modules/logdoc/src/picturlconverter.h"
#endif // PICTOGRAM_SUPPORT
#ifdef QUICK
# ifdef _KIOSK_MANAGER_
# include "adjunct/quick/managers/KioskManager.h"
# endif // _KIOSK_MANAGER_
# include "adjunct/quick/hotlist/HotlistManager.h"
# include "adjunct/quick/windows/BrowserDesktopWindow.h"
#endif // QUICK
#ifdef SVG_SUPPORT
# include "modules/svg/svg_workplace.h"
# include "modules/svg/SVGManager.h"
# include "modules/svg/SVGContext.h"
#endif // SVG_SUPPORT
#ifdef JS_PLUGIN_SUPPORT
# include "modules/jsplugins/src/js_plugin_context.h"
# include "modules/jsplugins/src/js_plugin_object.h"
#endif // JS_PLUGIN_SUPPORT
#ifdef MEDIA_HTML_SUPPORT
# include "modules/media/mediaelement.h"
# include "modules/media/mediatrack.h"
#endif // MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
# include "modules/libvega/src/canvas/canvas.h"
#endif // CANVAS_SUPPORT
#ifdef ENCODINGS_HAVE_TABLE_DRIVEN
# include "modules/encodings/tablemanager/optablemanager.h"
#endif
#ifdef _WML_SUPPORT_
# include "modules/logdoc/wml.h"
# include "modules/windowcommander/src/WindowCommander.h"
#endif // _WML_SUPPORT_
#ifdef ARIA_ATTRIBUTES_SUPPORT
# include "modules/logdoc/ariaenum.h"
#endif // ARIA_ATTRIBUTES_SUPPORT
#ifdef M2_SUPPORT
# include "modules/logdoc/omfenum.h"
#endif // M2_SUPPORT
#include "modules/logdoc/xmlenum.h"
#include "modules/xmlutils/xmldocumentinfo.h"
#include "modules/xmlutils/xmlnames.h"
#include "modules/xmlparser/xmldoctype.h"
#ifdef XSLT_SUPPORT
# include "modules/xslt/xslt.h"
# include "modules/logdoc/src/xsltsupport.h"
#endif // XSLT_SUPPORT
#ifdef _SPAT_NAV_SUPPORT_
# include "modules/spatial_navigation/handler_api.h"
#endif // _SPAT_NAV_SUPPORT_
#ifdef SKINNABLE_AREA_ELEMENT
#include "modules/skin/OpSkinManager.h"
#endif //SKINNABLE_AREA_ELEMENT
#ifdef VEGA_OPPAINTER_SUPPORT
#include "modules/libgogi/pi_impl/mde_opview.h"
#include "modules/libgogi/pi_impl/mde_widget.h"
#endif // VEGA_OPPAINTER_SUPPORT
#define WHITESPACE_L UNI_L(" \t\n\f\r")
#ifdef DRAG_SUPPORT
#include "modules/logdoc/dropzone_attribute.h"
#include "modules/dragdrop/dragdrop_manager.h"
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
#include "modules/dragdrop/clipboard_manager.h"
#endif // USE_OP_CLIPBOARD
#ifdef _DEBUG
static void CheckIsFormValueType(HTML_Element* he)
{
if (he->GetNsType() == NS_HTML)
{
switch (he->Type())
{
case HE_TEXTAREA:
case HE_OUTPUT:
# if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_)
case HE_KEYGEN:
# endif
case HE_INPUT:
case HE_SELECT:
case HE_BUTTON:
return;
}
}
OP_ASSERT(FALSE);
}
# define CHECK_IS_FORM_VALUE_TYPE(he) CheckIsFormValueType(he)
#else // !_DEBUG
# define CHECK_IS_FORM_VALUE_TYPE(he)
#endif // _DEBUG
#if defined(SELFTEST) || defined(_DEBUG)
BOOL HTML_Element::ElementHasFormValue()
{
return GetSpecialAttr(ATTR_FORM_VALUE, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_LOGDOC) != 0;
}
# endif // SELFTEST || _DEBUG
class MediaAttr : public ComplexAttr
{
private:
CSS_MediaObject* m_media_object;
OpString m_original_string;
MediaAttr() : m_media_object(NULL) {}
public:
static MediaAttr* Create(const uni_char* string, unsigned int string_len)
{
MediaAttr* media_attr = OP_NEW(MediaAttr, ());
if (!media_attr ||
OpStatus::IsError(media_attr->m_original_string.Set(string, string_len)) ||
(media_attr->m_media_object = OP_NEW(CSS_MediaObject, ())) == NULL ||
OpStatus::IsError(media_attr->m_media_object->SetMediaText(string, string_len, TRUE)))
{
OP_DELETE(media_attr);
return NULL;
}
return media_attr;
}
static MediaAttr* Create(CSS_MediaObject* media_object)
{
MediaAttr* media_attr = OP_NEW(MediaAttr, ());
if (!media_attr)
return NULL;
media_attr->m_media_object = media_object;
return media_attr;
}
CSS_MediaObject* GetMediaObject() { return m_media_object; }
virtual ~MediaAttr() { OP_DELETE(m_media_object); }
/// Used to check the types of complex attr. SHOULD be implemented
/// by all subclasses and all must match a unique value.
///\param[in] type A unique type value.
// virtual BOOL IsA(int type) { return type == T_UNKNOWN; }
/// Used to clone HTML Elements. Returning OpStatus::ERR_NOT_SUPPORTED here
/// will prevent the attribute from being cloned with the html element.
///\param[out] copy_to A pointer to an new'ed instance of the same object with the same content.
virtual OP_STATUS CreateCopy(ComplexAttr **copy_to);
/// Used to get a string representation of the attribute. The string
/// value of the attribute must be appended to the buffer. Need not
/// be implemented.
///\param[in] buffer A TempBuffer that the serialized version of the obejct will be appended to.
virtual OP_STATUS ToString(TempBuffer *buffer);
};
/* virtual */
OP_STATUS MediaAttr::CreateCopy(ComplexAttr **copy_to)
{
*copy_to = MediaAttr::Create(m_original_string.CStr(), m_original_string.Length());
return *copy_to ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
/* virtual */
OP_STATUS MediaAttr::ToString(TempBuffer *buffer)
{
if (!m_original_string.IsEmpty())
{
return buffer->Append(m_original_string.CStr());
}
TRAPD(status, m_media_object->GetMediaStringL(buffer));
RETURN_IF_ERROR(status);
if (!buffer->GetStorage())
status = buffer->Append(""); // So that we get "" and not NULL
return status;
}
CSS_MediaObject* HTML_Element::GetLinkStyleMediaObject() const
{
ComplexAttr* complex_attr = static_cast<ComplexAttr*>(GetAttr(ATTR_MEDIA, ITEM_TYPE_COMPLEX, NULL));
if (!complex_attr)
return NULL;
return static_cast<MediaAttr*>(complex_attr)->GetMediaObject();
}
void HTML_Element::SetLinkStyleMediaObject(CSS_MediaObject* media_object)
{
MediaAttr* attr = MediaAttr::Create(media_object);
// No way to signal OOM . :-(
if (attr)
{
SetAttr(ATTR_MEDIA, ITEM_TYPE_COMPLEX, attr, TRUE);
}
}
URL HTML_Element::GetLinkOriginURL()
{
if (DataSrc* src_head = GetDataSrc())
if (!src_head->GetOrigin().IsEmpty())
return src_head->GetOrigin();
if (URL* source = GetLinkURL())
{
URL origin(*source), target(source->GetAttribute(URL::KMovedToURL, URL::KNoRedirect));
while (!target.IsEmpty() && target.Type() != URL_JAVASCRIPT && target.Type() != URL_DATA)
{
origin = target;
target = target.GetAttribute(URL::KMovedToURL, URL::KNoRedirect);
}
return origin;
}
else
{
URL empty;
return empty;
}
}
void
HTML_Element::RemoveLayoutBox(FramesDocument* doc, BOOL clean_references)
{
OP_PROBE7(OP_PROBE_HTML_ELEMENT_REMOVELAYOUTBOX);
OP_ASSERT(layout_box);
FormObject* form_object = GetFormObject();
// Any form data must be moved from the widget to the
// the FormValue object, but don't look at elements
// HE_INSERTED_BY_LAYOUT since those have FormObject pointers, but none that
// logdoc/forms should know of. If we look at those we
// will Unexternalize a FormObject to the wrong FormValue
if (form_object && GetInserted() != HE_INSERTED_BY_LAYOUT)
{
// Optimization: avoid transferring form data from the
// widget to the html element if we are being deleted
if (!(doc && doc->IsBeingDeleted()))
{
// No form object unless there is a FormValue
GetFormValue()->Unexternalize(form_object);
}
if (doc && doc->IsReflowing())
layout_box->StoreFormObject();
}
if (doc)
{
if (clean_references && IsReferenced())
CleanReferences(doc);
#ifndef HAS_NOTEXTSELECTION
doc->RemoveLayoutCacheFromSelection(this);
#endif
OP_ASSERT(doc->GetLogicalDocument() && doc->GetLogicalDocument()->GetLayoutWorkplace());
doc->GetLogicalDocument()->GetLayoutWorkplace()->LayoutBoxRemoved(this);
#ifdef ACCESS_KEYS_SUPPORT
doc->GetHLDocProfile()->RemoveAccessKey(this, TRUE);
#endif // ACCESS_KEYS_SUPPORT
}
for (HTML_Element* child = FirstChild(); child; child = child->Suc())
if (child->GetLayoutBox())
child->RemoveLayoutBox(doc);
OP_DELETE(layout_box);
layout_box = NULL;
}
#ifdef CSS_SCROLLBARS_SUPPORT
void HTML_Element::GetScrollbarColor(ScrollbarColors* colors)
{
// Run through propertys and set the colors.
CSS_property_list* cp = GetCSS_Style();
if (cp)
{
CSS_decl* cd = cp->GetFirstDecl();
while(cd)
{
switch(cd->GetProperty())
{
case CSS_PROPERTY_scrollbar_base_color:
case CSS_PROPERTY_scrollbar_face_color:
case CSS_PROPERTY_scrollbar_arrow_color:
case CSS_PROPERTY_scrollbar_track_color:
case CSS_PROPERTY_scrollbar_shadow_color:
case CSS_PROPERTY_scrollbar_3dlight_color:
case CSS_PROPERTY_scrollbar_highlight_color:
case CSS_PROPERTY_scrollbar_darkshadow_color:
{
long col = HTM_Lex::GetColValByIndex(cd->LongValue());
switch(cd->GetProperty())
{
case CSS_PROPERTY_scrollbar_base_color: colors->SetBase(col); break;
case CSS_PROPERTY_scrollbar_face_color: colors->SetFace(col); break;
case CSS_PROPERTY_scrollbar_arrow_color: colors->SetArrow(col); break;
case CSS_PROPERTY_scrollbar_track_color: colors->SetTrack(col); break;
case CSS_PROPERTY_scrollbar_shadow_color: colors->SetShadow(col); break;
case CSS_PROPERTY_scrollbar_3dlight_color: colors->SetLight(col); break;
case CSS_PROPERTY_scrollbar_highlight_color: colors->SetHighlight(col); break;
case CSS_PROPERTY_scrollbar_darkshadow_color: colors->SetDarkShadow(col); break;
};
}
break;
};
cd = cd->Suc();
}
}
}
#endif // CSS_SCROLLBARS_SUPPORT
void HTML_Element::SetCheckForPseudo(unsigned int pseudo_bits)
{
if (!GetIsPseudoElement())
{
if (pseudo_bits & CSS_PSEUDO_CLASS_FIRST_LETTER)
packed2.has_first_letter = 1;
if (pseudo_bits & CSS_PSEUDO_CLASS_FIRST_LINE)
packed2.has_first_line = 1;
if (pseudo_bits & CSS_PSEUDO_CLASS_AFTER)
packed2.has_after = 1;
if (pseudo_bits & CSS_PSEUDO_CLASS_BEFORE)
packed2.has_before = 1;
}
if (pseudo_bits & (CSS_PSEUDO_CLASS_HOVER | CSS_PSEUDO_CLASS_VISITED |
CSS_PSEUDO_CLASS_LINK | CSS_PSEUDO_CLASS_FOCUS |
CSS_PSEUDO_CLASS_ACTIVE | CSS_PSEUDO_CLASS__O_PREFOCUS |
CSS_PSEUDO_CLASS_DEFAULT | CSS_PSEUDO_CLASS_INVALID |
CSS_PSEUDO_CLASS_VALID | CSS_PSEUDO_CLASS_IN_RANGE |
CSS_PSEUDO_CLASS_OUT_OF_RANGE | CSS_PSEUDO_CLASS_REQUIRED |
CSS_PSEUDO_CLASS_OPTIONAL | CSS_PSEUDO_CLASS_READ_ONLY |
CSS_PSEUDO_CLASS_READ_WRITE | CSS_PSEUDO_CLASS_ENABLED |
CSS_PSEUDO_CLASS_DISABLED | CSS_PSEUDO_CLASS_CHECKED |
CSS_PSEUDO_CLASS_INDETERMINATE))
packed2.check_dynamic = 1;
}
void HTML_Element::ResetCheckForPseudoElm()
{
packed2.has_first_letter = 0;
packed2.has_first_line = 0;
packed2.has_after = 0;
packed2.has_before = 0;
}
void HTML_Element::SetCurrentDynamicPseudoClass( unsigned int flags )
{
packed2.hovered = (flags & CSS_PSEUDO_CLASS_HOVER) ? 1 : 0;
packed2.focused = (flags & CSS_PSEUDO_CLASS_FOCUS) ? 1 : 0;
packed2.activated = (flags & CSS_PSEUDO_CLASS_ACTIVE)? 1 : 0;
if (flags & (CSS_PSEUDO_CLASS_INVALID | CSS_PSEUDO_CLASS_VALID |
CSS_PSEUDO_CLASS_DEFAULT |
CSS_PSEUDO_CLASS_IN_RANGE | CSS_PSEUDO_CLASS_OUT_OF_RANGE |
CSS_PSEUDO_CLASS_READ_WRITE | CSS_PSEUDO_CLASS_READ_ONLY |
CSS_PSEUDO_CLASS_REQUIRED | CSS_PSEUDO_CLASS_OPTIONAL |
CSS_PSEUDO_CLASS_DISABLED | CSS_PSEUDO_CLASS_ENABLED |
CSS_PSEUDO_CLASS_CHECKED /*| CSS_PSEUDO_CLASS_INDETERMINATE */
))
{
OP_ASSERT(IsFormElement()); // Maybe we have to do if (IsFormElement())...
// but none of these flags should be set otherwise and if it is a
// form element then at least one of the flags should be
// set (either CSS_PSEUDO_CLASS_INVALID or CSS_PSEUDO_CLASS_VALID)
FormValue* form_value = GetFormValue();
form_value->SetMarkedPseudoClasses(flags);
}
}
unsigned int HTML_Element::GetCurrentDynamicPseudoClass()
{
unsigned int flags = 0;
if (IsHovered())
flags |= CSS_PSEUDO_CLASS_HOVER;
if (IsFocused())
flags |= CSS_PSEUDO_CLASS_FOCUS;
if (IsActivated())
flags |= CSS_PSEUDO_CLASS_ACTIVE;
if (IsPreFocused())
flags |= CSS_PSEUDO_CLASS__O_PREFOCUS;
if (IsFormElement())
{
FormValue* form_value = GetFormValue();
flags |= form_value->GetMarkedPseudoClasses();
}
return flags;
}
BOOL HTML_Element::IsDefaultFormElement(FramesDocument* frames_doc)
{
if (frames_doc->current_default_formelement == this)
{
return TRUE;
}
if(frames_doc->current_default_formelement ||
!frames_doc->current_focused_formobject ||
frames_doc->current_focused_formobject->GetHTML_Element() != this)
{
// default form element is somewhere else
return FALSE;
}
// Focused button will behave as "default button"
OP_ASSERT(GetNsType() == NS_HTML);
BOOL is_button_type = Type() == HE_BUTTON || Type() == HE_INPUT;
if (is_button_type)
{
InputType inp_type = GetInputType();
is_button_type =
inp_type == INPUT_BUTTON || inp_type == INPUT_RESET ||
inp_type == INPUT_SUBMIT;
}
return is_button_type;
}
void HTML_Element::MarkImagesDirty(FramesDocument* doc)
{
if (GetIsListMarkerPseudoElement())
{
/* Currently there is no effective way to check whether particular list marker
is an image marker. We can only limit the situation where we have to mark extra dirty.
An that is a must if the content type might be unsuitable after the change. */
if ((doc->GetShowImages() && !(GetLayoutBox() && GetLayoutBox()->GetBulletContent()))
|| (!doc->GetShowImages() && GetLayoutBox() && GetLayoutBox()->GetBulletContent()))
MarkExtraDirty(doc);
else
MarkDirty(doc);
return;
}
if (GetLayoutBox())
{
BOOL is_image_content = GetLayoutBox()->IsContentImage();
#ifdef SVG_SUPPORT
BOOL is_svg_content = (GetLayoutBox()->GetContent() && GetLayoutBox()->GetContent()->GetSVGContent());
if (is_svg_content && IsMatchingType(Markup::SVGE_SVG, NS_SVG) && !doc->GetShowImages())
{
DocumentManager* docman = doc->GetDocManager();
if(docman)
{
FramesDocElm* fdelm = docman->GetFrame();
if(fdelm)
{
if(fdelm->IsInlineFrame())
{
HTML_Element* parent_elm = fdelm->GetHtmlElement();
if(parent_elm && parent_elm->IsMatchingType(HE_OBJECT, NS_HTML))
{
// If it was an <embed> then don't do anything.
// If we say don't render, then we need to disable plugins
// that may render the same content. An SVG plugin would
// render the image as soon as we say we don't handle it natively.
if (!(parent_elm->GetInserted() == HE_INSERTED_BY_LAYOUT &&
parent_elm->Parent() &&
parent_elm->Parent()->IsMatchingType(HE_EMBED, NS_HTML)))
{
parent_elm->MarkExtraDirty(doc);
}
}
}
}
}
}
else
#endif // SVG_SUPPORT
if (is_image_content && IsMatchingType(HE_OBJECT, NS_HTML) && !doc->GetShowImages())
MarkExtraDirty(doc);
else
if (is_image_content || GetLayoutBox()->IsContentEmbed())
{
if (HasAttr(ATTR_USEMAP))
MarkExtraDirty(doc);
#ifdef SVG_SUPPORT
BOOL svgHandledNatively = FALSE;
if(GetLayoutBox()->IsContentEmbed() && doc->GetShowImages())
{
URL* url = GetEMBED_URL(doc->GetLogicalDocument());
if(url && url->ContentType() == URL_SVG_CONTENT)
{
HTML_ElementType elm_type;
OP_BOOLEAN resolve_status = GetResolvedObjectType(url, elm_type, doc->GetLogicalDocument());
if(resolve_status == OpBoolean::IS_TRUE && elm_type == HE_IFRAME)
{
MarkExtraDirty(doc);
svgHandledNatively = TRUE;
}
}
}
if(!svgHandledNatively)
#endif // SVG_SUPPORT
MarkDirty(doc);
}
else
if (IsMatchingType(HE_OBJECT, NS_HTML) && doc->GetShowImages())
{
URL* inline_url = GetUrlAttr(ATTR_DATA, NS_IDX_HTML, doc->GetLogicalDocument());
if (inline_url)
{
HTML_ElementType element_type;
OP_BOOLEAN resolve_status = GetResolvedObjectType(inline_url, element_type, doc->GetLogicalDocument());
if (resolve_status == OpBoolean::IS_FALSE ||
(resolve_status == OpBoolean::IS_TRUE &&
(element_type == HE_IMG
#ifdef SVG_SUPPORT
|| (inline_url->ContentType() == URL_SVG_CONTENT && element_type == HE_IFRAME)
#endif // SVG_SUPPORT
)))
MarkExtraDirty(doc);
}
}
else if (HasAttr(ATTR_USEMAP))
{
MarkExtraDirty(doc);
}
else
for (HTML_Element* he = FirstChild(); he; he = he->Suc())
he->MarkImagesDirty(doc);
}
}
void
HTML_Element::Remove(const DocumentContext &context, BOOL going_to_delete /* = FALSE */)
{
#ifdef DEBUG
if (context.logdoc && context.logdoc->GetLayoutWorkplace())
{
OP_ASSERT(!context.logdoc->GetLayoutWorkplace()->IsReflowing());
}
#endif
#ifdef NS4P_COMPONENT_PLUGINS
if (context.logdoc && context.logdoc->GetLayoutWorkplace())
if (context.logdoc->GetLayoutWorkplace()->IsReflowing() || context.logdoc->GetLayoutWorkplace()->IsTraversing())
return;
#endif // NS4P_COMPONENT_PLUGINS
if (GetNsType() == NS_HTML)
{
// FIXME: This could should move to HandleDocumentTreeChange or OutSafe
switch (Type())
{
case HE_OPTION:
{
for (HTML_Element *parent = Parent(); parent; parent = parent->Parent())
if (parent->Type() == HE_SELECT)
{
if (parent->GetLayoutBox())
parent->GetLayoutBox()->RemoveOption(this);
break;
}
}
break;
case HE_OPTGROUP:
{
for (HTML_Element *parent = Parent(); parent; parent = parent->Parent())
if (parent->Type() == HE_SELECT)
{
if (parent->GetLayoutBox())
parent->GetLayoutBox()->RemoveOptionGroup(this);
break;
}
}
break;
default:
break;
}
} // end NS_HTML
HTML_Element* parent = Parent();
FramesDocument *frames_doc = context.frames_doc;
BOOL in_document = FALSE;
if (frames_doc)
{
#ifdef DOM_FULLSCREEN_MODE
if (frames_doc->GetFullscreenElement() != NULL &&
(frames_doc->GetFullscreenElement() == this || IsAncestorOf(frames_doc->GetFullscreenElement())))
frames_doc->DOMExitFullscreen(NULL);
#endif // DOM_FULLSCREEN_MODE
if (LogicalDocument* logdoc = context.logdoc)
{
if (parent && logdoc->GetRoot())
{
in_document = logdoc->GetRoot()->IsAncestorOf(parent);
if (in_document)
{
if (parent->GetInserted() == HE_INSERTED_BY_LAYOUT)
parent->MarkExtraDirty(frames_doc);
else
{
if (GetLayoutBox())
/* Removing this element may cause two anonymous layout boxes (table
objects or flex items), one preceding and one succeeding this
element, to be joined into one anonymous table object. Search for a
preceding anonymous table object, and if we find one, mark it extra
dirty, and the layout engine will take care of the rest. */
for (HTML_Element* sibling = Pred(); sibling; sibling = sibling->Pred())
{
/* Find the nearest sibling layout box. Skip extra dirty boxes; we
cannot tell what they will become after reflow (maybe they have
become display:none, for instance). */
if (sibling->GetLayoutBox() && !sibling->IsExtraDirty())
{
if (sibling->GetInserted() == HE_INSERTED_BY_LAYOUT &&
sibling->GetLayoutBox()->IsAnonymousWrapper())
sibling->MarkExtraDirty(context.frames_doc);
break;
}
}
#ifdef SVG_SUPPORT
// SVG size isn't affected by their children and the
// internal invalidation is done in HandleDocumentTreeChange
if (!parent->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
#endif // SVG_SUPPORT
parent->MarkDirty(frames_doc, TRUE, TRUE);
}
int sibling_subtrees = logdoc->GetHLDocProfile()->GetCssSuccessiveAdjacent();
if (sibling_subtrees < INT_MAX && context.hld_profile->GetCSSCollection()->MatchFirstChild() && IsFirstChild())
/* If the element removed was first-child, its sibling (if any) now becomes
first-child. Must recalculate its properties, and all siblings of it that may be
affected by this change. */
++ sibling_subtrees;
MarkPropsDirty(frames_doc, sibling_subtrees);
}
}
logdoc->RemoveFromParseState(this);
}
}
OutSafe(context, going_to_delete);
if (in_document)
{
#ifdef XML_EVENTS_SUPPORT
for (XML_Events_Registration *registration = frames_doc->GetFirstXMLEventsRegistration();
registration;
registration = (XML_Events_Registration *) registration->Suc())
{
if (OpStatus::IsMemoryError(registration->HandleElementRemovedFromDocument(frames_doc, this)))
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
#endif // XML_EVENTS_SUPPORT
ES_Thread* thread = context.environment ? context.environment->GetCurrentScriptThread() : NULL;
if (OpStatus::IsMemoryError(HandleDocumentTreeChange(context, parent, this, thread, FALSE)))
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
void
HTML_Element::DisableContent(FramesDocument* doc)
{
BOOL is_leaving_page = doc->IsUndisplaying();
// Disable this subtree
HTML_Element* stop = (HTML_Element*)NextSibling();
for (HTML_Element *current = this; current != stop; current = (HTML_Element*)current->Next())
{
if (current->layout_box)
current->layout_box->DisableContent(doc);
if (is_leaving_page && current->Type() == HE_INPUT && current->GetInputType() == INPUT_PASSWORD)
{
// We don't want to leave any passwords in the history
current->GetFormValue()->SetValueFromText(current, NULL);
}
}
}
OP_STATUS
HTML_Element::EnableContent(FramesDocument* doc)
{
if (layout_box)
if (layout_box->EnableContent(doc) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
for (HTML_Element* he = FirstChild(); he; he = he->Suc())
if (he->EnableContent(doc) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
int
HTML_Element::GetTextContentLength()
{
int len = 0;
if (Type() == HE_TEXT)
{
return data.text->GetTextLen();
}
else
for (HTML_Element* element = FirstChild(); element; element = element->Suc())
{
if (!element->GetIsFirstLetterPseudoElement())
len += element->GetTextContentLength();
}
return len;
}
int
HTML_Element::GetTextContent(uni_char* buf, int buf_len)
{
if (buf_len < 1)
return 0;
int len = 0;
if (Type() == HE_TEXT)
{
const uni_char* text = LocalContent();
if (text)
{
len = uni_strlen(text);
if (len >= buf_len)
len = buf_len - 1;
uni_strncpy(buf, text, len);
buf[len] = '\0';
}
}
else if (!IsScriptElement())
{
for (HTML_Element* element = FirstChild(); element; element = element->Suc())
{
if (!element->GetIsFirstLetterPseudoElement())
len += element->GetTextContent(buf + len, buf_len - len);
}
}
return len;
}
Box*
HTML_Element::GetInnerBox(int x, int y, FramesDocument* doc, BOOL text_boxes /* = TRUE */)
{
if (layout_box)
{
IntersectionObject intersection(doc, LayoutCoord(x), LayoutCoord(y), text_boxes);
intersection.Traverse(this);
return intersection.GetInnerBox();
}
else
return NULL;
}
FormObject*
HTML_Element::GetFormObject()
{
return layout_box ? layout_box->GetFormObject() : GetFormObjectBackup();
}
FormValue*
HTML_Element::GetFormValue()
{
CHECK_IS_FORM_VALUE_TYPE(this);
FormValue* form_value = static_cast<FormValue*>(GetSpecialAttr(ATTR_FORM_VALUE,
ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_LOGDOC));
OP_ASSERT(form_value); // Nobody should call GetFormValue unless they
// know it's a form thing and then there should
// always be an ATTR_FORM_VALUE. If it's
// missing it's a bug that should be fixed
return form_value;
}
void
HTML_Element::ReplaceFormValue(FormValue* value)
{
SetSpecialAttr(ATTR_FORM_VALUE, ITEM_TYPE_COMPLEX, value, TRUE, SpecialNs::NS_LOGDOC);
if (layout_box)
if (FormObject *formobject = GetFormObject())
value->Externalize(formobject);
}
OP_STATUS
HTML_Element::ConstructFormValue(HLDocProfile *hld_profile, FormValue*& value)
{
CHECK_IS_FORM_VALUE_TYPE(this);
// It can exist if someone has changed type attribute so that we
// have to recreate the FormValue.
// OP_ASSERT(!ElementHasFormValue()); // Not already set
RETURN_IF_ERROR(FormValue::ConstructFormValue(this, hld_profile, value));
OP_ASSERT(value);
return OpStatus::OK;
}
void
HTML_Element::RemoveCachedTextInfo(FramesDocument* doc)
{
if (layout_box)
if (layout_box->RemoveCachedInfo() && doc)
MarkDirty(doc);
for (HTML_Element* child = FirstChild(); child; child = child->Suc())
child->RemoveCachedTextInfo(doc);
}
void
HTML_Element::ERA_LayoutModeChanged(FramesDocument* doc, BOOL apply_doc_styles_changed, BOOL support_float, BOOL column_strategy_changed)
{
OP_ASSERT(doc->GetDocRoot() == this);
doc->GetLogicalDocument()->GetLayoutWorkplace()->ERA_LayoutModeChanged(apply_doc_styles_changed, support_float, column_strategy_changed);
}
OP_STATUS
HTML_Element::LoadAllCSS(const DocumentContext& context)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_LOADALLCSS);
OP_STATUS status = OpStatus::OK;
if (IsStyleElement())
{
if (!GetCSS())
status = LoadStyle(context, FALSE);
}
else
for (HTML_Element* he = FirstChild(); status != OpStatus::ERR_NO_MEMORY && he; he = he->Suc())
status = he->LoadAllCSS(context);
return status;
}
BOOL HTML_Element::HasWhiteSpaceOnly()
{
if (Type() == HE_TEXTGROUP)
{
for (HTML_Element *child = FirstChild(); child; child = child->Suc())
if (!child->HasWhiteSpaceOnly())
return FALSE;
}
else
{
const uni_char* txt = LocalContent();
if (txt)
{
while (*txt)
{
if (*txt != ' ' && !uni_iscntrl(*txt))
return FALSE;
txt++;
}
}
}
return TRUE;
}
BOOL HTML_Element::CanUseTextCursor()
{
#ifdef SVG_SUPPORT
if(GetNsType() == NS_SVG)
return (g_svg_manager->IsTextContentElement(this) && g_svg_manager->IsVisible(this));
else
#endif //SVG_SUPPORT
{
return (layout_box && layout_box->IsTextBox());
}
}
const uni_char*
HTML_Element::TextContent() const
{
return Type() == HE_BR ? UNI_L("\n") : LocalContent();
}
#ifdef _WML_SUPPORT_
const uni_char* HTML_Element::GetWmlName() const
{
const uni_char* name_str = GetStringAttr(WA_NAME, NS_IDX_WML);
if (name_str)
return name_str;
else
return GetName();
}
const uni_char* HTML_Element::GetWmlValue() const
{
const uni_char* val_str = GetStringAttr(WA_VALUE, NS_IDX_WML);
if (val_str)
return val_str;
else
return GetValue();
}
#endif //_WML_SUPPORT_
HTML_Element* HTML_Element::GetAnchorTags(FramesDocument *document/*=NULL*/)
{
HTML_Element* helm = this;
while (helm)
{
if (helm->GetAnchor_HRef(document))
return helm;
helm = helm->ParentActualStyle();
}
return NULL;
}
HTML_Element* HTML_Element::GetA_Tag()
{
HTML_Element* h = this;
do
{
if (h->IsMatchingType(HE_A, NS_HTML))
break;
h = h->ParentActualStyle();
}
while (h);
return h;
}
// returns a pointer to start of refresh url, or null pointer if no url specified.
const uni_char* ParseRefreshUrl(const uni_char* buf, int &refresh_url_len, short &refresh_int)
{
// https://bugzilla.mozilla.org/show_bug.cgi?id=170021 has a decent
// summary of what Mozilla implements. Follow it here (which is
// what WebKit also does.)
#define FIND_CHAR(ptr, ch) { while (*ptr && *ptr != ch) ptr++; }
#define SKIP_SPACES(ptr) { while (uni_isspace(*ptr)) ptr++; }
refresh_url_len = 0;
refresh_int = uni_atoi(buf);
const uni_char* tmp = buf;
while (*tmp && *tmp != ';' && *tmp != ',' && !uni_isspace(*tmp))
tmp++;
SKIP_SPACES(tmp);
if(*tmp == ';' || *tmp == ',')
tmp++;
SKIP_SPACES(tmp);
if(uni_strni_eq(tmp, "URL", 3))
{
tmp+=3;
SKIP_SPACES(tmp);
if (*tmp == '=')
tmp++;
else
return NULL;
SKIP_SPACES(tmp);
}
refresh_url_len = uni_strlen(tmp);
while (refresh_url_len > 0 && uni_isspace(tmp[refresh_url_len-1]))
refresh_url_len--;
return tmp;
}
const uni_char *GetInputTypeString(InputType type)
{
switch(type)
{
case INPUT_TEXT:
return UNI_L("text");
case INPUT_CHECKBOX:
return UNI_L("checkbox");
case INPUT_RADIO:
return UNI_L("radio");
case INPUT_SUBMIT:
return UNI_L("submit");
case INPUT_RESET:
return UNI_L("reset");
case INPUT_HIDDEN:
return UNI_L("hidden");
case INPUT_IMAGE:
return UNI_L("image");
case INPUT_PASSWORD:
return UNI_L("password");
case INPUT_BUTTON:
return UNI_L("button");
case INPUT_FILE:
return UNI_L("file");
case INPUT_URI:
return UNI_L("url");
case INPUT_DATE:
return UNI_L("date");
case INPUT_WEEK:
return UNI_L("week");
case INPUT_TIME:
return UNI_L("time");
case INPUT_EMAIL:
return UNI_L("email");
case INPUT_NUMBER:
return UNI_L("number");
case INPUT_RANGE:
return UNI_L("range");
case INPUT_MONTH:
return UNI_L("month");
case INPUT_DATETIME:
return UNI_L("datetime");
case INPUT_DATETIME_LOCAL:
return UNI_L("datetime-local");
case INPUT_COLOR:
return UNI_L("color");
case INPUT_SEARCH:
return UNI_L("search");
case INPUT_TEL:
return UNI_L("tel");
case INPUT_TEXTAREA:
break;
}
return NULL;
}
const uni_char *GetDirectionString(short value)
{
switch(value)
{
case ATTR_VALUE_up: return UNI_L("up");
case ATTR_VALUE_down: return UNI_L("down");
case ATTR_VALUE_left: return UNI_L("left");
case ATTR_VALUE_right: return UNI_L("right");
}
return NULL;
}
const uni_char *GetLiTypeString(short value)
{
switch(value)
{
case CSS_VALUE_lower_greek:
return UNI_L("lower_greek");
case CSS_VALUE_armenian:
return UNI_L("armenian");
case CSS_VALUE_georgian:
return UNI_L("georgian");
case CSS_VALUE_disc:
return UNI_L("disc");
case CSS_VALUE_square:
return UNI_L("square");
case CSS_VALUE_circle:
return UNI_L("circle");
case CSS_VALUE_lower_alpha:
case CSS_VALUE_lower_latin:
return UNI_L("a");
case CSS_VALUE_upper_alpha:
case CSS_VALUE_upper_latin:
return UNI_L("A");
case CSS_VALUE_lower_roman:
return UNI_L("i");
case CSS_VALUE_upper_roman:
return UNI_L("I");
// case CSS_VALUE_decimal_leading_zero:
// case CSS_VALUE_hebrew:
// case CSS_VALUE_cjk_ideographic:
// case CSS_VALUE_hiragana:
// case CSS_VALUE_katakana:
// case CSS_VALUE_hiragana_iroha:
// case CSS_VALUE_katakana_iroha:
case CSS_VALUE_decimal:
default:
return UNI_L("1");
}
}
/**
* A short text with an unterminated entity that should be decoded.
*/
OP_STATUS HTML_Element::ConstructUnterminatedText(const uni_char* text, unsigned text_len)
{
OP_ASSERT(text_len <= SplitTextLen || !"Use AppendText/SetText if you are going to insert long text chunks");
css_properties = NULL;
layout_box = NULL;
packed1_init = 0;
packed2_init = 0;
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
SetNsIdx(NS_IDX_DEFAULT);
g_ns_manager->GetElementAt(NS_IDX_DEFAULT)->IncRefCount();
SetType(HE_TEXT);
data.text = NEW_TextData(());
if( ! data.text || data.text->Construct(text, text_len, TRUE, FALSE, TRUE) == OpStatus::ERR_NO_MEMORY )
{
DELETE_TextData(data.text);
data.text = NULL;
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
/* static */
HTML_Element* HTML_Element::CreateText(HLDocProfile* hld_profile, const uni_char* text, unsigned text_len, BOOL resolve_entities, BOOL is_cdata, BOOL expand_wml_vars)
{
OP_ASSERT(!expand_wml_vars || hld_profile || !"Can't expand wml variables without an hld_profile");
// Create empty text node and then add the text to it. AppendText does all the complicated stuff
HTML_Element *new_elm = NEW_HTML_Element();
if (new_elm &&
(OpStatus::IsMemoryError(new_elm->Construct((const uni_char*)NULL, 0, resolve_entities, is_cdata)) ||
OpStatus::IsMemoryError(new_elm->AppendText(hld_profile, text, text_len, resolve_entities, is_cdata, expand_wml_vars))))
{
DELETE_HTML_Element(new_elm);
new_elm = NULL;
}
return new_elm;
}
OP_STATUS HTML_Element::AppendText(HLDocProfile* hld_profile, const uni_char* text, unsigned text_len, BOOL resolve_entities, BOOL is_cdata, BOOL expand_wml_vars, BOOL is_foster_parented)
{
OP_ASSERT(IsText() && !(Parent() && Parent()->IsText()));
HTML_Element* group = Type() == HE_TEXTGROUP ? this : NULL;
HTML_Element* last_text = group ? LastLeaf() : this;
OP_ASSERT(!group || group->GetIsCDATA() == is_cdata || !"Adding cdata to a non cdata text or the opposite");
OP_ASSERT(!last_text || last_text->Type() != HE_TEXT || !last_text->data.text || last_text->data.text->GetIsCDATA() == is_cdata || !"Adding cdata to a non cdata text or the opposite");
TempBuffer temp_buffer; // Only needed if we have previous data
// that will have to be put in front of the new buffer or for wml variable substitution
if (resolve_entities &&
last_text && last_text->Type() == HE_TEXT &&
last_text->data.text &&
last_text->data.text->IsUnterminatedEntity())
{
OP_ASSERT(group);
// See if the new text will make it more terminated. This should seldom run so it shouldn't matter that it's a little expensive
RETURN_IF_ERROR(temp_buffer.Append(last_text->data.text->GetUnresolvedEntity()));
RETURN_IF_ERROR(temp_buffer.Append(text, text_len));
HTML_Element* unterminated_elm = last_text;
last_text = last_text->Pred();
if (hld_profile)
{
/* We need to make sure that the element is removed from the cascade. */
unterminated_elm->Remove(hld_profile->GetFramesDocument());
/* Although ::Remove already called ::Clean, we need the return value to
determine if we can really Free the element. */
if (unterminated_elm->Clean(hld_profile->GetFramesDocument()))
{
unterminated_elm->Free(hld_profile->GetFramesDocument());
}
}
else
{
unterminated_elm->Out();
DELETE_HTML_Element(unterminated_elm);
}
text = temp_buffer.GetStorage();
text_len = temp_buffer.Length();
}
if (text_len == 0 && Type() == HE_TEXT && !data.text)
{
// Newly created element with NULL TextData -> make it non-null even though we have no string
TextData* textdata = NEW_TextData(());
if (!textdata ||
OpStatus::IsError(textdata->Construct(NULL, 0, FALSE, is_cdata, FALSE)))
{
DELETE_TextData(textdata);
return OpStatus::ERR_NO_MEMORY;
}
data.text = textdata;
return OpStatus::OK;
}
BOOL need_group = FALSE; // Assume the best
while (text_len > 0)
{
if (need_group)
{
// Need to convert the text to a textgroup to fit the new text
OP_ASSERT(!group);
OP_ASSERT(last_text == this);
need_group = FALSE;
HTML_Element *new_elm = NEW_HTML_Element();
if (!new_elm ||
OpStatus::IsMemoryError(new_elm->Construct((const uni_char*)NULL, 0, resolve_entities, is_cdata)))
{
if (new_elm)
{
DELETE_HTML_Element(new_elm);
}
return OpStatus::ERR_NO_MEMORY;
}
// Move the text to the child
DELETE_TextData(new_elm->data.text);
new_elm->data.text = last_text->data.text;
last_text->data.text = NULL;
last_text->SetType(HE_TEXTGROUP);
group = last_text;
new_elm->Under(group);
#ifdef DELAYED_SCRIPT_EXECUTION
if (hld_profile && hld_profile->ESIsParsingAhead() && is_foster_parented)
RETURN_IF_ERROR(hld_profile->ESAddFosterParentedElement(new_elm));
#endif // DELAYED_SCRIPT_EXECUTION
new_elm->SetInserted(GetInserted());
if (hld_profile)
hld_profile->GetFramesDocument()->OnTextConvertedToTextGroup(group);
last_text = new_elm;
if (is_cdata)
{
group->SetSpecialBoolAttr(ATTR_CDATA, TRUE, SpecialNs::NS_LOGDOC);
}
if (hld_profile)
{
group->MarkExtraDirty(hld_profile->GetFramesDocument());
}
OP_ASSERT(group);
}
#if defined _WML_SUPPORT_
if (expand_wml_vars)
{
OP_ASSERT(hld_profile);
if (hld_profile && WML_Context::NeedSubstitution(text, text_len))
{
if (!group)
{
need_group = TRUE;
continue;
}
AutoTempBuffer subst_buf;
// add just a little bit more space than the original
RETURN_IF_ERROR(subst_buf->Expand(text_len + 64));
uni_char *subst_txt = subst_buf->GetStorage();
unsigned int subst_len = hld_profile->WMLGetContext()
->SubstituteVars(text, text_len, subst_txt, subst_buf->GetCapacity());
OP_STATUS status = OpStatus::OK;
// Store the original value in an attribute so that we can redo the substitution
uni_char *content = UniSetNewStrN(text, text_len);
if (!content ||
group->SetSpecialAttr(ATTR_TEXT_CONTENT, ITEM_TYPE_STRING, (void*)content, TRUE, SpecialNs::NS_LOGDOC) == -1)
{
OP_DELETEA(content);
status = OpStatus::ERR_NO_MEMORY;
}
else
{
temp_buffer.Clear();
status = temp_buffer.Append(subst_txt, subst_len);
}
RETURN_IF_ERROR(status);
text = temp_buffer.GetStorage();
text_len = temp_buffer.Length();
if (text_len == 0)
{
if (last_text && last_text->Type() == HE_TEXT && !last_text->data.text)
{
// Need to make it non-null. Coming from CreateText it's our job to
// do that.
TextData* textdata = NEW_TextData(());
if (!textdata ||
OpStatus::IsError(textdata->Construct(NULL, 0, FALSE, is_cdata, FALSE)))
{
DELETE_TextData(textdata);
return OpStatus::ERR_NO_MEMORY;
}
last_text->data.text = textdata;
}
break;
}
}
expand_wml_vars = FALSE;
}
#endif // _WML_SUPPORT_
#if 0 // FIXME :Optimization not yet implemented.
if (!group && last_text)
{
// Here we might be able to reuse the existing HE_TEXT instead of creating a new one
// Can just append to the existing text element, but if the first half is processed and the second half is not, this becomes messy
....
...
return OpStatus::OK;
}
#endif // 0
unsigned len_for_this = MIN(SplitTextLen, text_len);
// Don't cut an entity in two if it can be avoided;
if (resolve_entities)
{
uni_char *buf_p = const_cast<uni_char*>(text+len_for_this);
if (HTM_Lex::ScanBackIfEscapeChar(text, &buf_p, text_len > len_for_this))
{
if (text == buf_p)
{
if (!group)
{
need_group = TRUE;
continue;
}
OP_ASSERT(group);
// The unterminated entity was all there was. Put it in a special text node.
HTML_Element *new_elm;
if (last_text && last_text->Type() == HE_TEXT && !last_text->data.text)
{
// (Re)use the empty HE_TEXT we got from CreateText
new_elm = last_text;
}
else
{
new_elm = NEW_HTML_Element();
}
if (!new_elm ||
OpStatus::IsMemoryError(new_elm->ConstructUnterminatedText(text, len_for_this)))
{
if (new_elm &&
new_elm != last_text &&
new_elm->Clean(hld_profile->GetFramesDocument()))
new_elm->Free(hld_profile->GetFramesDocument());
hld_profile->SetIsOutOfMemory(TRUE);
return OpStatus::ERR_NO_MEMORY;
}
if (new_elm != last_text)
{
new_elm->Under(group);
HE_InsertType inserted = GetInserted();
#ifdef DELAYED_SCRIPT_EXECUTION
if (hld_profile && hld_profile->ESIsParsingAhead())
{
inserted = HE_INSERTED_BY_PARSE_AHEAD;
if (is_foster_parented)
RETURN_IF_ERROR(hld_profile->ESAddFosterParentedElement(new_elm));
}
#endif // DELAYED_SCRIPT_EXECUTION
new_elm->SetInserted(inserted);
}
return OpStatus::OK;
}
len_for_this = buf_p - text;
}
}
// Need a new element (or more)
OP_ASSERT(len_for_this > 0);
if (last_text && last_text->Type() == HE_TEXT &&
(!last_text->data.text ||
(last_text->data.text->GetTextLen() == 0 &&
!last_text->data.text->IsUnterminatedEntity())))
{
// Just insert the data into the existing node
TextData* textdata = NEW_TextData(());
if (!textdata ||
OpStatus::IsError(textdata->Construct(text, len_for_this, resolve_entities, is_cdata, FALSE)))
{
DELETE_TextData(textdata);
return OpStatus::ERR_NO_MEMORY;
}
DELETE_TextData(last_text->data.text);
last_text->data.text = textdata;
}
else if (!group)
{
need_group = TRUE;
continue;
}
else
{
HTML_Element *new_elm = NEW_HTML_Element();
if (!new_elm ||
OpStatus::IsMemoryError(new_elm->Construct(text, len_for_this, resolve_entities, is_cdata)))
{
if (new_elm)
{
DELETE_HTML_Element(new_elm);
}
return OpStatus::ERR_NO_MEMORY;
}
new_elm->Under(group);
HE_InsertType inserted = GetInserted();
#ifdef DELAYED_SCRIPT_EXECUTION
if (hld_profile && hld_profile->ESIsParsingAhead())
{
inserted = HE_INSERTED_BY_PARSE_AHEAD;
if (is_foster_parented)
RETURN_IF_ERROR(hld_profile->ESAddFosterParentedElement(new_elm));
}
#endif // DELAYED_SCRIPT_EXECUTION
new_elm->SetInserted(inserted);
if (hld_profile)
new_elm->MarkExtraDirty(hld_profile->GetFramesDocument());
}
text += len_for_this;
text_len -= len_for_this;
}
#ifdef _DEBUG
HTML_Element* stop = static_cast<HTML_Element*>(NextSibling());
HTML_Element* it = this;
while (it != stop)
{
if (it->Type() == HE_TEXT)
{
OP_ASSERT(it->data.text);
}
it = it->Next();
}
#endif // _DEBUG
return OpStatus::OK;
}
const uni_char* GetMetaValue(const uni_char* &tmp, UINT &len, BOOL &end_found)
{
const uni_char* val = 0;
end_found = FALSE;
const uni_char* current = tmp; // avoid writing back to tmp all the time
while (uni_isspace(*current))
current++;
if (*current == '=')
{
uni_char quote_char;
current++;
while (uni_isspace(*current))
current++;
quote_char = (*current == '"' || *current == '\'') ? *current++ : 0;
val = current;
while (*current)
{
if (quote_char)
{
if (quote_char == *current)
break;
}
else
{
if (*current == ',' || *current == ';')
break;
}
current++;
}
len = current - val;
if (*current)
{
if (quote_char)
{
current++;
while (*current && *current != ',' && *current != ';')
current++;
}
end_found = (*current == ',');
if (*current)
current++;
}
else if (quote_char)
{
val = NULL;
len = 0;
}
}
tmp = current;
return val;
}
void HTML_Element::HandleMetaRefresh(HLDocProfile* hld_profile, const uni_char* content)
{
/*
* This section parses the http-equiv refresh meta content attribute
* The attribute has somewhat the following aspect:
* content="xx;url=yyy"
* where xx is a number, and yyy is an url.
* yyy CAN be quoted both with quotes or apostrophes. Check CORE-17731
* All tokens can be padded with whitespace
*
* */
while(*(content) && uni_isspace(*(content)))
content++;
if (uni_isdigit(*(content)) || *content == '.')
{
short refresh_sec;
int refresh_url_len;
URL refresh_url;
const uni_char* refresh_tmp = ParseRefreshUrl(content, refresh_url_len, refresh_sec);
#ifdef GADGET_SUPPORT
// If both url and gadget, the command is ignored.
if(refresh_tmp && hld_profile->GetFramesDocument()->GetWindow()->GetGadget() != NULL)
refresh_sec = -1;
else
#endif //GADGET_SUPPORT
if (refresh_tmp && *refresh_tmp)
{
AutoTempBuffer tmp_buf;
if (OpStatus::IsMemoryError(tmp_buf.GetBuf()->Append(refresh_tmp, refresh_url_len)))
hld_profile->SetIsOutOfMemory(TRUE);
else
{
uni_char* uni_val_tmp = tmp_buf.GetBuf()->GetStorage();
int copy_len = refresh_url_len;
RemoveTabs(uni_val_tmp);
/*
* The following if block and loop handle the case of the URL being quoted around
*/
uni_char c_url_quoter = uni_val_tmp[0];
if (c_url_quoter == '\'' || c_url_quoter == '"')
{
uni_val_tmp++;
copy_len--;
int index = 0;
while (index < copy_len)
{
if (uni_val_tmp[index] == c_url_quoter)
{
uni_val_tmp[index] = 0;
break;
}
index++;
}
}
uni_char *tmp = uni_val_tmp;
uni_char *rel_start = 0;
while (*tmp != '\0' && *tmp != '#')
tmp++;
if (*tmp == '#')
{
*tmp = '\0';
rel_start = tmp+1;
}
if (rel_start == uni_val_tmp + 1) // only an anchor within the local page
refresh_url = g_url_api->GetURL(*hld_profile->GetURL(), uni_val_tmp, rel_start);
else if (hld_profile->BaseURL())
refresh_url = g_url_api->GetURL(*hld_profile->BaseURL(), uni_val_tmp, rel_start);
else
refresh_url = g_url_api->GetURL(uni_val_tmp, rel_start);
}
}
// Use this refresh URL if the timeout is valid and is
// smaller or equal to the previously refresh set URL,
// or if it is the first set refresh URL.
short prev_refresh_sec = hld_profile->GetRefreshSeconds();
if (refresh_sec >= 0 && (prev_refresh_sec < 0 || refresh_sec <= prev_refresh_sec))
hld_profile->SetRefreshURL(&refresh_url, refresh_sec);
}
}
// returns FALSE if we find that we have used wrong character set
// This function used to be called CheckHttpEquiv, but it now checks more than that (stighal, 2002-08-29)
BOOL HTML_Element::CheckMetaElement(const DocumentContext& context, HTML_Element* parent_elm, BOOL added)
{
const uni_char* content = GetStringAttr(ATTR_CONTENT);
const uni_char* name = GetStringAttr(ATTR_NAME);
HLDocProfile* hld_profile = context.hld_profile;
#ifdef CSS_VIEWPORT_SUPPORT
if (name && uni_stri_eq(name, "VIEWPORT"))
{
CSSCollection* coll = hld_profile->GetCSSCollection();
if (added && content)
{
CSS_ViewportMeta* viewport_meta = GetViewportMeta(context, TRUE);
if (viewport_meta)
{
viewport_meta->ParseContent(content);
coll->AddCollectionElement(viewport_meta);
}
}
else
coll->RemoveCollectionElement(this);
return TRUE;
}
#endif // CSS_VIEWPORT_SUPPORT
if (!added || !content)
return TRUE;
BOOL rc = TRUE;
if (name && uni_stri_eq(name, "DESCRIPTION"))
{
if (OpStatus::IsMemoryError(hld_profile->SetDescription(content)))
hld_profile->SetIsOutOfMemory(TRUE);
// go on and see if there's any other interesting attribute on the element
}
const uni_char* http_equiv = GetStringAttr(ATTR_HTTP_EQUIV);
if (http_equiv)
{
if (uni_stri_eq(http_equiv, "SET-COOKIE"))
{
uni_char *unitempcookie = NULL;
if (UniSetStr(unitempcookie, content) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
else
{
char *tempcookie=(char*) unitempcookie;
make_singlebyte_in_place(tempcookie);
URL* OP_MEMORY_VAR url = hld_profile->GetURL();
if(url->GetAttribute(URL::KHaveServerName))
{
#ifdef OOM_SAFE_API
TRAPD(op_err, urlManager->HandleSingleCookieL(url->GetRep(), tempcookie, tempcookie, 0));
if (OpStatus::IsMemoryError(op_err))
hld_profile->SetIsOutOfMemory(TRUE);
#else
TRAPD(op_err, g_url_api->HandleSingleCookieL(*url, tempcookie, tempcookie, 0)); // FIXME: OOM
if (OpStatus::IsMemoryError(op_err))
hld_profile->SetIsOutOfMemory(TRUE);
#endif //OOM_SAFE_API
}
}
OP_DELETEA(unitempcookie);
}
else
if(!hld_profile->IsXml() && uni_stri_eq(http_equiv, "CONTENT-TYPE") && parent_elm)
{
ParameterList type;
uni_char* uni_val_tmp = (uni_char*)g_memory_manager->GetTempBuf();
int val_max_len = UNICODE_DOWNSIZE(g_memory_manager->GetTempBufLen());
int copy_len = uni_strlen(content);
if (copy_len >= val_max_len)
copy_len = val_max_len - 1;
uni_strncpy(uni_val_tmp, content, copy_len);
uni_val_tmp[copy_len] = 0;
char* val_tmp=(char*) uni_val_tmp;
make_singlebyte_in_place(val_tmp);
if (type.SetValue(val_tmp,PARAM_SEP_SEMICOLON) == OpStatus::ERR_NO_MEMORY)
{
hld_profile->SetIsOutOfMemory(TRUE);
}
else
{
Parameters *element = type.GetParameter("charset", PARAMETER_ASSIGNED_ONLY, type.First());
if(element)
{
// Workaround for PGO crash on Windows - see DSK-279424
OpString8 charset;
// Character set name given in this META tag
if (OpStatus::IsMemoryError(charset.Set(element->Value())))
hld_profile->SetIsOutOfMemory(TRUE);
// We have a dilemma here, since we have now found a <META> tag
// defining which encoding we should use, but we may already
// be decoding the document as if it was another encoding.
//
// There are six cases to consider:
//
// 0. We can read the document and the tag says that it is
// an incompatible encoding (such as utf-16 instead of
// iso-8859-1) [see Bug#49311]
// => return TRUE (=ok)
//
// 1. The HTTP header contained a charset identifier, or we saw
// a meta http-equiv defining charset the last run, or one
// was already seen in this document
// => return TRUE (=ok)
//
// 2. The user has defined an override using View|Encoding
// => Set KMIME_CharSet and return TRUE (=ok)
//
// 3. The current character decoder has the same character
// set that is defined here
// => Set KMIME_CharSet and return TRUE (=ok)
//
// 4. The current character decoder has a different character
// set than is defined here, and the defined one is known
// => Set KMIME_CharSet and return FALSE (=refresh)
//
// 5. The current character decoder has a different character
// set than is defined here, but we do not know about it
// => Set MIME_CharSet and return TRUE (=ok)
// Character set from HTTP header (or last <meta> found)
const char *http_charset =
hld_profile->GetURL()->GetAttribute(URL::KMIME_CharSet, TRUE).CStr();
// User override from View|Encoding
const char *override = g_pcdisplay->GetForceEncoding();
if (override && strni_eq(override, "AUTODETECT-", 11))
override = NULL;
// The name that GetCharacterSet would return if
// this character set is known. If it was not found,
// we get a NULL Pointer.
OpString8 found;
// Workaround for PGO crash on Windows - see DSK-279424
if (charset.HasContent() &&
OpStatus::IsMemoryError(found.Set(g_charsetManager->GetCanonicalCharsetName(charset.CStr()))))
hld_profile->SetIsOutOfMemory(TRUE);
// Currently used decoder's character set
URL_DataDescriptor *my_dd = NULL;
FramesDocument* tFrm = hld_profile->GetFramesDocument();
if (tFrm)
my_dd = tFrm->Get_URL_DataDescriptor();
const char *current = NULL;
if (my_dd)
current = my_dd->GetCharacterSet();
else // temp crashfix. will look into what is wrong, when the testpage is up again. (bug 50811) (emil)
current = "utf-16";
if ((current && (0 == op_strncmp(current, "utf-16", 6))) ||
(found.HasContent() && (0 == found.Compare("utf-16", 6))))
{
// CASE 0: META tag might not be telling the truth
found.Empty();
charset.Empty();
rc = TRUE;
}
else if (http_charset)
{
// CASE 1: HTTP header have charset
rc = TRUE;
}
else if (override && *override)
{
// CASE 2: User defined override
rc = TRUE;
if (charset.HasContent())
{
// Remember this anyway, since the next access to
// the URL might not be overridden
if (OpStatus::IsMemoryError(hld_profile->GetURL()->SetAttribute(URL::KMIME_CharSet, charset)))
hld_profile->SetIsOutOfMemory(TRUE);
if (hld_profile->SetCharacterSet(charset.CStr()) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
}
}
else
{
// CASE 3-5
if(my_dd)
my_dd->StopGuessingCharset();
if (current)
{
if (found.HasContent())
{
// CASE 3-4
if (found.CompareI(current) == 0)
{
// CASE 3: Using the correct decoder already
rc = TRUE;
if (OpStatus::IsMemoryError(hld_profile->GetURL()->SetAttribute(URL::KMIME_CharSet, found)))
hld_profile->SetIsOutOfMemory(TRUE);
if (hld_profile->SetCharacterSet(found.CStr()) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
}
else
{
// CASE 4: Switching character set
rc = FALSE;
if (OpStatus::IsMemoryError(hld_profile->GetURL()->SetAttribute(URL::KMIME_CharSet, found)))
hld_profile->SetIsOutOfMemory(TRUE);
if (hld_profile->SetCharacterSet(found.CStr()) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
}
}
else
{
// CASE 5: Wrong charset, but unknown
rc = TRUE;
if (OpStatus::IsMemoryError(hld_profile->GetURL()->SetAttribute(URL::KMIME_CharSet, charset)))
hld_profile->SetIsOutOfMemory(TRUE);
if (hld_profile->SetCharacterSet(NULL) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
}
}
}
}
}
}
else
if (uni_stri_eq(http_equiv, "LINK") && parent_elm)
{
const uni_char* val_tmp = content;
while (*val_tmp && !hld_profile->GetIsOutOfMemory())
{
while (uni_isspace(*val_tmp))
val_tmp++;
if (*val_tmp != '<')
return TRUE;
val_tmp++;
const uni_char* tmp = uni_strchr(val_tmp, '>');
if (!tmp)
return TRUE;
HtmlAttrEntry ha_list[5];
int i = 0;
ha_list[i].ns_idx = NS_IDX_DEFAULT;
ha_list[i].attr = ATTR_HREF;
ha_list[i].value = val_tmp;
ha_list[i++].value_len = tmp - val_tmp;
tmp++;
if (*tmp == ';')
{
BOOL type_done = FALSE;
BOOL rel_done = FALSE;
BOOL media_done = FALSE;
tmp++;
while (*tmp)
{
BOOL is_type = FALSE;
BOOL is_rel = FALSE;
BOOL is_media = FALSE;
tmp++;
while (uni_isspace(*tmp))
tmp++;
if (uni_strni_eq(tmp, "TYPE", 4))
{
tmp += 4;
is_type = TRUE;
}
else if (uni_strni_eq(tmp, "REL", 3))
{
tmp += 3;
is_rel = TRUE;
}
else if (uni_strni_eq(tmp, "MEDIA", 5))
{
tmp += 5;
is_media = TRUE;
}
else
{
break;
}
BOOL end_found;
UINT tval_len = 0;
const uni_char* tval = GetMetaValue(tmp, tval_len, end_found);
if (is_type)
{
if (type_done)
break;
else
{
ha_list[i].ns_idx = NS_IDX_DEFAULT;
ha_list[i].attr = ATTR_TYPE;
ha_list[i].value = tval;
ha_list[i++].value_len = tval_len;
}
}
else if (is_media)
{
if (media_done)
break;
else
{
ha_list[i].ns_idx = NS_IDX_DEFAULT;
ha_list[i].attr = ATTR_MEDIA;
ha_list[i].value = tval;
ha_list[i++].value_len = tval_len;
}
}
else if (is_rel)
{
if (rel_done)
break;
else
{
ha_list[i].ns_idx = NS_IDX_DEFAULT;
ha_list[i].attr = ATTR_REL;
ha_list[i].value = tval;
ha_list[i++].value_len = tval_len;
}
}
if (end_found)
break;
}
}
ha_list[i].attr = ATTR_NULL;
HTML_Element* new_elm = NEW_HTML_Element();
if( new_elm && OpStatus::ERR_NO_MEMORY != new_elm->Construct(hld_profile, NS_IDX_HTML, HE_LINK, ha_list, HE_INSERTED_BY_CSS_IMPORT) )
{
new_elm->Under(parent_elm);
if (OpStatus::IsMemoryError(hld_profile->HandleLink(new_elm)))
hld_profile->SetIsOutOfMemory(TRUE);
}
else
{
DELETE_HTML_Element(new_elm);
hld_profile->SetIsOutOfMemory(TRUE);
}
val_tmp = tmp;
}
}
else if (uni_stri_eq(http_equiv, "EXPIRES"))
{
URL *url = hld_profile->GetURL();
if(url && uni_strlen(content) > 0)
{
uni_char *uni_content = NULL;
if (UniSetStr(uni_content, content) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
else if (uni_content)
{
char *temp_content=(char*) uni_content;
make_singlebyte_in_place(temp_content);
url->SetAttribute(URL::KHTTPExpires,temp_content);
OP_DELETEA(uni_content);
}
}
}
else if (uni_stri_eq(http_equiv, "PRAGMA"))
{
URL *url = hld_profile->GetURL();
if(url && uni_strlen(content) > 0)
{
uni_char *uni_content = NULL;
if (UniSetStr(uni_content, content) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
else if (uni_content)
{
char *temp_content=(char*) uni_content;
make_singlebyte_in_place(temp_content);
url->SetAttribute(URL::KHTTPPragma,temp_content);
OP_DELETEA(uni_content);
}
}
}
else if (uni_stri_eq(http_equiv, "CACHE-CONTROL"))
{
URL *url = hld_profile->GetURL();
if(url && *content)
{
uni_char *uni_content = NULL;
if (UniSetStr(uni_content, content) == OpStatus::ERR_NO_MEMORY)
hld_profile->SetIsOutOfMemory(TRUE);
else if (uni_content)
{
char *temp_content=(char*) uni_content;
make_singlebyte_in_place(temp_content);
url->SetAttribute(URL::KHTTPCacheControl, temp_content);
OP_DELETEA(uni_content);
}
}
}
else if (uni_stri_eq(http_equiv, "REFRESH")
&& (!hld_profile->GetFramesDocument()->GetWindow()->IsMailOrNewsfeedWindow()
&& hld_profile->GetURL()->Type() != URL_ATTACHMENT))
{
if (GetInserted() != HE_INSERTED_BY_PARSE_AHEAD)
HandleMetaRefresh(hld_profile, content);
}
#ifdef DNS_PREFETCHING
else if (uni_stri_eq(http_equiv, "x-dns-prefetch-control"))
{
if (uni_stri_eq(content, "on"))
hld_profile->GetLogicalDocument()->SetDNSPrefetchControl(TRUE);
else if (uni_stri_eq(content, "off"))
hld_profile->GetLogicalDocument()->SetDNSPrefetchControl(FALSE);
}
#endif // DNS_PREFETCHING
#if 0 // It seems as if MSIE8 didn't include support for this in META and since supporting this in META has problems (it's too late to prevent parsing and execution when we come here) I'll disable it for now but leave it in to make it easy to enable again.
else if (uni_stri_eq(http_equiv, "x-frame-options")) // Click-jacking protection
{
// From the spec:
// * The META tag SHOULD appear in the document <HEAD>, but MAY appear
// anywhere in the document due to liberal HTML5 rules.
// * The name and value are NOT case-sensitive.
// * Only the first valid X-FRAME-OPTIONS directive is respected
// The third item will be ignored for now which means that a same-origin
// followed by a deny might be blocked when it should not.
FramesDocument* doc = hld_profile->GetFramesDocument();
if (doc->GetParentDoc() != NULL)
{
// In a frame. Is that bad? Time to check what the document has
// stipulated
// The HTTP header takes precedence
OpString8 frame_options;
doc->GetURL().GetAttribute(URL::KHTTPFrameOptions, frame_options);
if (frame_options.IsEmpty())
{
// Note that very similar code also exists in DocumantManager::HandleByOpera
// where the HTTP header is taken care of
BOOL allow = TRUE;
if (uni_stri_eq(content, "deny"))
allow = FALSE;
else if (uni_stri_eq(content, "sameorigin"))
{
URL top_doc_url = doc->GetWindow()->DocManager()->GetCurrentDoc()->GetURL();
if (!doc->GetURL().SameServer(top_doc_url))
allow = FALSE;
}
if (!allow)
{
// Go away!
// We should replace ourselves with a warning page immediately somehow
doc->GetDocManager()->StopLoading(FALSE);
rc = FALSE;
doc->GetDocManager()->GenerateAndShowClickJackingBlock(doc->GetURL());
}
}
}
}
#endif // 0 - Removed support for anti-clickjacking in META
}
return rc;
}
#ifdef LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
int html_elm_balance = 0;
struct HTML_Exo
{
HTML_Element *elt;
HTML_Exo *next;
};
HTML_Exo *all_html_elements = NULL;
#endif // LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
HTML_Element::~HTML_Element()
{
OP_ASSERT(!GetESElement());
#ifdef SVG_SUPPORT
DestroySVGContext();
#endif
if (IsFormElement())
DestroyFormObjectBackup();
DetachChildren();
LocalClean();
#ifdef DISPLAY_CLICKINFO_SUPPORT
if (MouseListener::GetClickInfo().GetImageElement() == this)
MouseListener::GetClickInfo().Reset();
#endif // DISPLAY_CLICKINFO_SUPPORT
#ifdef LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
html_elm_balance--;
HTML_Exo *p, *q;
for ( p=all_html_elements, q=0 ; p != 0 && p->elt != this ; q=p, p=p->next )
;
OP_ASSERT( p != 0 );
if (q == 0)
all_html_elements = p->next;
else
q->next = p->next;
OP_DELETE(p);
#endif // LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
OP_ASSERT(!Parent());
OP_ASSERT(!m_first_ref);
}
void HTML_Element::LocalClean()
{
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
if(Type() == HE_TEXT) // HE_TEXT is the same in all namespacse
{
DELETE_TextData(data.text);
data.text = NULL;
}
else
{
if (data.attrs)
{
REPORT_MEMMAN_DEC(GetAttrSize() * sizeof(AttrItem));
DELETE_HTML_Attributes(data.attrs);
data.attrs = NULL;
}
}
}
int GetAlignValue(BYTE align_val, BOOL allow_middle, BOOL allow_justify)
{
switch (align_val)
{
case ATTR_VALUE_center:
return CSS_VALUE_center;
case ATTR_VALUE_left:
return CSS_VALUE_left;
case ATTR_VALUE_right:
return CSS_VALUE_right;
case ATTR_VALUE_bottom:
return CSS_VALUE_bottom;
case ATTR_VALUE_justify:
if (allow_justify)
return CSS_VALUE_justify;
else
return 0;
case ATTR_VALUE_middle:
if (allow_middle)
return CSS_VALUE_center;
else
return 0;
default:
return 0;
}
}
void SetNumAttrVal(HTML_ElementType type, short attr, BYTE val, void* &value)
{
value = 0;
switch (attr)
{
#ifdef SUPPORT_TEXT_DIRECTION
case ATTR_DIR:
if (val == ATTR_VALUE_ltr)
value = (void*)CSS_VALUE_ltr;
else if (val == ATTR_VALUE_rtl)
value = (void*)CSS_VALUE_rtl;
break;
#endif // SUPPORT_TEXT_DIRECTION
case ATTR_SHAPE:
if (val == ATTR_VALUE_circle || val == ATTR_VALUE_circ)
value = (void*)AREA_SHAPE_CIRCLE;
else if (val == ATTR_VALUE_polygon || val == ATTR_VALUE_poly)
value = (void*)AREA_SHAPE_POLYGON;
else if (val == ATTR_VALUE_default)
value = (void*)AREA_SHAPE_DEFAULT;
else
value = (void*)AREA_SHAPE_RECT;
break;
case ATTR_ALIGN:
switch (type)
{
case HE_IMG:
case HE_EMBED:
case HE_APPLET:
case HE_OBJECT:
#ifdef MEDIA_HTML_SUPPORT
case HE_AUDIO:
case HE_VIDEO:
#endif // MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
case HE_CANVAS:
#endif
case HE_METER:
case HE_PROGRESS:
case HE_IFRAME:
case HE_INPUT:
case HE_CAPTION:
case HE_LEGEND:
if (val == ATTR_VALUE_top)
value = (void*) CSS_VALUE_top;
else if (val == ATTR_VALUE_left)
value = (void*) CSS_VALUE_left;
else if (val == ATTR_VALUE_right)
value = (void*) CSS_VALUE_right;
else if (val == ATTR_VALUE_center)
value = (void*) CSS_VALUE_center;
else if (val == ATTR_VALUE_middle || val == ATTR_VALUE_absmiddle)
{
if (type != HE_CAPTION)
value = (void*) CSS_VALUE_middle;
}
else if (val == ATTR_VALUE_absbottom)
value = (void*) CSS_VALUE_text_bottom;
else
value = (void*) CSS_VALUE_bottom;
break;
case HE_HR:
if (val == ATTR_VALUE_right)
value = (void*) CSS_VALUE_right;
else if (val == ATTR_VALUE_left)
value = (void*) CSS_VALUE_left;
else if (val == ATTR_VALUE_center)
value = (void*) CSS_VALUE_center;
break;
default:
BOOL is_row_or_cell_or_group = (type == HE_TR || type == HE_TD || type == HE_TH || type == HE_TBODY || type == HE_TFOOT || type == HE_THEAD); //TBODY etc see bug 83880
BOOL is_h_or_p_div = (type == HE_P || type == HE_DIV || (type >= HE_H1 && type <= HE_H6));
value = INT_TO_PTR(GetAlignValue(val, is_row_or_cell_or_group, is_row_or_cell_or_group || is_h_or_p_div || type == HE_COL || type == HE_COLGROUP));
if (is_h_or_p_div && value == 0)
value = (void*)CSS_VALUE_left;
break;
}
break;
case ATTR_VALIGN:
if (val == ATTR_VALUE_top)
value = (void*) CSS_VALUE_top;
else if (val == ATTR_VALUE_middle || val == ATTR_VALUE_center)
value = (void*) CSS_VALUE_middle;
else if (val == ATTR_VALUE_bottom)
value = (void*) CSS_VALUE_bottom;
else if (val == ATTR_VALUE_baseline)
value = (void*) CSS_VALUE_baseline;
else
value = (void*) 0;
break;
case ATTR_CLEAR:
if (val == ATTR_VALUE_left)
value = (void*) CLEAR_LEFT;
else if (val == ATTR_VALUE_right)
value = (void*) CLEAR_RIGHT;
else if (val == ATTR_VALUE_all || val == ATTR_VALUE_both)
value = (void*) CLEAR_ALL;
else
value = (void*) CLEAR_NONE;
break;
case ATTR_TYPE:
if (type == HE_INPUT || type == HE_BUTTON)
{
if (ATTR_is_inputtype_val(val))
{
// Magic. The enum InputType and ATTR_VALUE_... table must be in sync
InputType inp_type = (enum InputType) (val - ATTR_VALUE_text + INPUT_TEXT);
if (type == HE_BUTTON)
{
// Set value to default value if it's a bad or unknown value
if (inp_type != INPUT_BUTTON && inp_type != INPUT_RESET)
inp_type = INPUT_SUBMIT;
}
value = (void*) inp_type;
}
else // different defaults for HE_INPUT and HE_BUTTON
value = (void*) (type == HE_INPUT ? INPUT_TEXT : INPUT_SUBMIT);
}
else
{
if (val == ATTR_VALUE_disc)
value = (void*) LIST_TYPE_DISC;
else if (val == ATTR_VALUE_square)
value = (void*) LIST_TYPE_SQUARE;
else if (val == ATTR_VALUE_circle)
value = (void*) LIST_TYPE_CIRCLE;
else
value = (void*) LIST_TYPE_NULL;
}
break;
case ATTR_SCROLLING:
if (val == ATTR_VALUE_yes)
value = (void*) SCROLLING_YES;
else if (val == ATTR_VALUE_no)
value = (void*) SCROLLING_NO;
else
value = (void*) SCROLLING_AUTO;
break;
case ATTR_METHOD:
case ATTR_FORMMETHOD:
if (val == ATTR_VALUE_post)
value = (void*) HTTP_METHOD_POST;
else
value = (void*) HTTP_METHOD_GET;
break;
case ATTR_DIRECTION:
switch (val)
{
case ATTR_VALUE_up:
case ATTR_VALUE_down:
case ATTR_VALUE_left:
case ATTR_VALUE_right:
value = INT_TO_PTR(val);
break;
}
break;
case ATTR_BEHAVIOR:
switch (val)
{
case ATTR_VALUE_slide:
case ATTR_VALUE_scroll:
case ATTR_VALUE_alternate:
value = INT_TO_PTR(val);
break;
}
break;
default:
break;
}
}
PrivateAttrs*
AddPrivateAttr(HLDocProfile* hld_profile, HTML_ElementType type, int plen, HtmlAttrEntry* ha_list)
{
#if defined(_APPLET_2_EMBED_)
plen += 2; // RL 2000-01-09: Adds 2 to the length to make space for java_DOCBASE and java_CODEBASE
#endif
PrivateAttrs* pa = NEW_PrivateAttrs((plen)); // FIXME:REPORT_MEMMAN-KILSMO
// OOM check
if (!pa)
{
hld_profile->SetIsOutOfMemory(TRUE);
return NULL;
}
if (OpStatus::IsMemoryError(pa->ProcessAttributes(hld_profile, type, ha_list)))
hld_profile->SetIsOutOfMemory(TRUE);
return pa;
}
void
HTML_Element::ReplaceAttrLocal(int i, short attr, ItemType item_type, void* value, int ns_idx/*=NS_IDX_HTML*/, BOOL need_free/*=FALSE*/, BOOL is_special/*=FALSE*/, BOOL is_id/*=FALSE*/, BOOL is_specified/*=TRUE*/, BOOL is_event/*=FALSE*/)
{
if (data.attrs[i].GetAttr() != ATTR_NULL)
data.attrs[i].Clean();
data.attrs[i].Set(attr, item_type, value, ns_idx, need_free, is_special, is_id, is_specified, is_event);
if (!is_special && attr == Markup::HA_CLASS)
{
NS_Type ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (ns == NS_HTML || ns == NS_SVG)
SetHasClass();
}
}
void
HTML_Element::SetAttrLocal(int i, short attr, ItemType item_type, void* value, int ns_idx/*=NS_IDX_HTML*/, BOOL need_free/*=FALSE*/, BOOL is_special/*=FALSE*/, BOOL is_id/*=FALSE*/, BOOL is_specified/*=TRUE*/, BOOL is_event/*=FALSE*/)
{
data.attrs[i].Set(attr, item_type, value, ns_idx, need_free, is_special, is_id, is_specified, is_event);
if (!is_special && attr == Markup::HA_CLASS)
{
NS_Type ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (ns == NS_HTML || ns == NS_SVG)
SetHasClass();
}
}
int
HTML_Element::SetAttrCommon(int i, short attr, ItemType item_type, void* val, BOOL need_free, int ns_idx, BOOL is_special, BOOL is_id, BOOL is_specified, BOOL is_event)
{
OP_ASSERT(Type() != Markup::HTE_TEXT);
if (i >= 0)
{
ReplaceAttrLocal(i, attr, item_type, val, ns_idx, need_free, is_special, is_id, is_specified, is_event);
return i;
}
int attr_size = GetAttrSize();
i = attr_size;
// check if there is empty entries - always at the end
while (i > 0 && GetAttrItem(i - 1) == ATTR_NULL)
i--;
if (i >= 0 && i < attr_size)
{
ReplaceAttrLocal(i, attr, item_type, val, ns_idx, need_free, is_special, is_id, is_specified, is_event);
return i;
}
// create new entry
int new_len = attr_size + 2; // one extra
AttrItem* new_attrs = NEW_HTML_Attributes((new_len));
// OOM check
if (new_attrs)
{
// need to decrease ns reference count on all attributes overwritten
// by the memcpy below
for (int j = 0; j < attr_size; j++)
if (!new_attrs[j].IsSpecial())
g_ns_manager->GetElementAt(new_attrs[j].GetNsIdx())->DecRefCountA();
op_memcpy(new_attrs, data.attrs, attr_size * sizeof(AttrItem));
// need to set NeedFree to false so that the destructor called from DELETE_HTML_Attributes
// a few lines down, doesn't delete the contents of the attributes
for (int j = 0; j < attr_size; j++)
{
if (!new_attrs[j].IsSpecial())
g_ns_manager->GetElementAt(new_attrs[j].GetNsIdx())->IncRefCountA();
data.attrs[j].SetNeedFree(FALSE);
}
SetAttrSize(new_len);
DELETE_HTML_Attributes(data.attrs);
data.attrs = new_attrs;
// set new attr value
SetAttrLocal(attr_size, attr, item_type, val, ns_idx, need_free, is_special, is_id, is_specified, is_event);
// reset extra entry
SetAttrLocal(attr_size + 1, ATTR_NULL, ITEM_TYPE_BOOL, NULL, NS_IDX_DEFAULT, FALSE, TRUE);
REPORT_MEMMAN_INC((new_len - attr_size) * sizeof(AttrItem));
return attr_size;
}
return -1;
}
/*inline*/ int
HTML_Element::GetResolvedAttrNs(int i) const
{
int idx = data.attrs[i].GetNsIdx();
if (idx != NS_IDX_DEFAULT)
return idx;
else
return GetNsIdx();
}
BOOL
HTML_Element::IsStyleElement()
{
NS_Type ns = GetNsType();
return Type() == Markup::HTE_STYLE && (ns == NS_HTML || ns == NS_SVG);
}
BOOL
HTML_Element::IsScriptElement()
{
NS_Type ns = GetNsType();
return Type() == Markup::HTE_SCRIPT && (ns == NS_HTML || ns == NS_SVG);
}
BOOL
HTML_Element::IsLinkElement()
{
if (IsMatchingType(HE_LINK, NS_HTML))
return TRUE;
if (Type() == HE_PROCINST)
{
const uni_char* target = GetStringAttr(ATTR_TARGET);
if(target && uni_str_eq(target, "xml-stylesheet"))
return TRUE;
}
return FALSE;
}
BOOL
HTML_Element::IsCssImport()
{
HTML_Element* parent_elm = Parent();
return (GetInserted() == HE_INSERTED_BY_CSS_IMPORT && parent_elm && (parent_elm->IsStyleElement() || parent_elm->IsLinkElement()));
}
BOOL
HTML_Element::IsFocusable(FramesDocument *document)
{
// This method determines what is focusable on a
// page. Elements that this returns TRUE for can
// be focused with mousedown, can have the :focus
// pseudo class and has a working focus() method
// in DOM.
if (IsText())
return FALSE;
if (GetAnchor_HRef(document) || IsFormElement())
return TRUE;
if (IsMatchingType(HE_AREA, NS_HTML) && HasAttr(ATTR_HREF))
return TRUE;
#ifdef DOCUMENT_EDIT_SUPPORT
// We don't allow any elements outside of body to be focusable.
if (IsContentEditable(FALSE))
return TRUE;
#endif // DOCUMENT_EDIT_SUPPORT
// If the author explicitly has said that he wants a
// certain element to be involved in keyboard
// navigation, then we should enable :focus on it.
if (GetNsType() == NS_HTML && HasNumAttr(ATTR_TABINDEX))
return TRUE;
#ifdef SVG_SUPPORT
if(g_svg_manager->IsFocusableElement(document, this))
return TRUE;
#endif // SVG_SUPPORT
return FALSE;
}
HTML_Element::HTML_Element() : DocTree()
, exo_object(NULL)
, m_first_ref(NULL)
, css_properties(NULL)
{
packed1_init = 0;
packed2_init = 0;
data.attrs = NULL;
layout_box = NULL;
#ifdef SVG_SUPPORT
svg_context = NULL;
#endif // SVG_SUPPORT
g_ns_manager->GetElementAt(GetNsIdx())->IncRefCount();
#ifdef LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
html_elm_balance++;
HTML_Exo *p = OP_NEW(HTML_Exo, ());
if (p)
{
p->elt = this;
p->next = all_html_elements;
all_html_elements = p;
}
#endif // LOGDOC_EXPENSIVE_ELEMENT_DEBUGGING
}
OP_STATUS HTML_Element::Construct(HLDocProfile* hld_profile, HTML_Element* he, BOOL skip_events, BOOL force_html)
{
css_properties = NULL;
layout_box = NULL;
packed1_init = 0;
packed2_init = 0;
int elmtype = he->Type();
int new_ns = he->GetNsIdx();
if (force_html && new_ns != NS_IDX_HTML && he->GetTagName())
{
if (he->GetNsType() == NS_HTML)
new_ns = NS_IDX_HTML;
else
{
elmtype = HTM_Lex::GetElementType(he->GetTagName(), NS_HTML, FALSE);
HtmlAttrEntry *attrs = htmLex->GetAttrArray();
int attr_index = 0, attr_count = he->GetAttrSize();
if (elmtype == HE_UNKNOWN)
{
attrs[0].attr = ATTR_XML_NAME;
attrs[0].is_id = FALSE;
attrs[0].is_special = TRUE;
attrs[0].is_specified = FALSE;
LogdocXmlName *old_name = (LogdocXmlName*)he->GetSpecialAttr(ATTR_XML_NAME, ITEM_TYPE_COMPLEX, (void*)NULL, SpecialNs::NS_LOGDOC);
attrs[0].value = (uni_char*)old_name;
attrs[0].value_len = 0;
++attr_index;
}
attrs[attr_index].attr = ATTR_NULL;
for (int i = 0; i < attr_count && attr_index < HtmlAttrEntriesMax; i++)
if (!he->GetAttrIsSpecial(i) && he->GetAttrItem(i) == ATTR_XML)
{
const uni_char *value = (const uni_char *) he->GetValueItem(i);
attrs[attr_index].attr = HTM_Lex::GetAttrType(value, NS_HTML, FALSE);
attrs[attr_index].ns_idx = NS_IDX_HTML;
attrs[attr_index].is_id = attrs[attr_index].attr == ATTR_ID;
attrs[attr_index].is_specified = he->GetAttrIsSpecified(i);
attrs[attr_index].is_special = FALSE;
attrs[attr_index].value = value + uni_strlen(value) + 1;
attrs[attr_index].value_len = uni_strlen(attrs[attr_index].value);
attrs[attr_index].name = value;
attrs[attr_index].name_len = uni_strlen(value);
attrs[++attr_index].attr = ATTR_NULL;
}
return Construct(hld_profile, NS_IDX_HTML, (HTML_ElementType) elmtype, attrs);
}
}
SetType((HTML_ElementType) elmtype);
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
SetNsIdx(new_ns);
g_ns_manager->GetElementAt(new_ns)->IncRefCount();
if (Type() == HE_TEXT)
{
if (he->Content())
{
data.text = NEW_TextData(());
if (! data.text || data.text->Construct(he->GetTextData()) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
}
}
else
{
int attr_count = he->GetAttrSize();
int insert_count = 0;
packed1.inserted = he->GetInserted();
if (attr_count)
{
data.attrs = NEW_HTML_Attributes((attr_count));
// OOM check
if (!data.attrs)
return OpStatus::ERR_NO_MEMORY;
REPORT_MEMMAN_INC(attr_count * sizeof(AttrItem));
}
else
data.attrs = NULL;
SetAttrSize(attr_count);
for (OP_MEMORY_VAR int i = 0; i < attr_count; i++)
{
ItemType item_type = he->GetItemType(i);
void* OP_MEMORY_VAR value = he->GetValueItem(i);
short attr = he->GetAttrItem(i);
int attr_ns = he->GetAttrNs(i);
BOOL attr_is_special = he->GetAttrIsSpecial(i);
BOOL attr_is_id = he->GetAttrIsId(i);
BOOL attr_is_specified = he->GetAttrIsSpecified(i);
BOOL attr_is_event = he->GetAttrIsEvent(i);
if (attr)
{
switch (item_type)
{
case ITEM_TYPE_BOOL:
case ITEM_TYPE_NUM:
if (attr_is_special)
{
// Must not copy numbers that are really pointers
if (attr_ns == SpecialNs::NS_LOGDOC && attr == ATTR_FORMOBJECT_BACKUP)
continue;
// Must not reuse other forms' form nr or we'll get really confused
if (attr_ns == SpecialNs::NS_LOGDOC && attr == ATTR_JS_ELM_IDX)
continue;
#if defined SVG_SUPPORT
// This is a meta attribute that would lie if it was copied
if(attr_ns == SpecialNs::NS_SVG && attr == Markup::SVGA_SHADOW_TREE_BUILT)
continue;
#endif // SVG_SUPPORT
}
break;
case ITEM_TYPE_NUM_AND_STRING:
{
OP_ASSERT(value);
uni_char* string_part = reinterpret_cast<uni_char*>(static_cast<char*>(value)+sizeof(INTPTR));
size_t len = sizeof(INTPTR)+sizeof(uni_char)*(uni_strlen(string_part)+1);
char* new_value = OP_NEWA(char, len);
if (!new_value)
{
value = NULL;
item_type = ITEM_TYPE_STRING;
hld_profile->SetIsOutOfMemory(TRUE);
}
else
{
op_memcpy(new_value, value, len);
value = new_value;
}
}
break;
case ITEM_TYPE_STRING:
if (value)
{
const uni_char *xml_value = NULL;
int xml_value_len = 0;
const uni_char *str = (const uni_char *) value;
int str_len = uni_strlen(str);
if (attr == ATTR_XML)
{
xml_value = (const uni_char *) str + str_len + 1;
if (xml_value)
xml_value_len = uni_strlen(xml_value);
}
if (attr == ATTR_XML)
{
value = OP_NEWA(uni_char, str_len + xml_value_len + 2); // FIXME:REPORT_MEMMAN-KILSMO
if (value)
{
uni_strncpy((uni_char*)value, str, str_len);
((uni_char*)value)[str_len] = '\0';
if (xml_value_len)
uni_strncpy((uni_char*)value + str_len + 1, xml_value, xml_value_len);
((uni_char*)value)[str_len + xml_value_len + 1] = '\0';
}
}
else
value = (void*) UniSetNewStrN(str, str_len); // FIXME:REPORT_MEMMAN-KILSMO
if (!value)
hld_profile->SetIsOutOfMemory(TRUE);
}
break;
case ITEM_TYPE_URL:
if (value)
{
value = OP_NEW(URL, (*((URL*) value)));
if (!value)
hld_profile->SetIsOutOfMemory(TRUE);
}
break;
case ITEM_TYPE_URL_AND_STRING:
{
OP_ASSERT(value);
UrlAndStringAttr *url_attr = static_cast<UrlAndStringAttr*>(value);
UrlAndStringAttr *new_attr;
const uni_char *url_string = url_attr->GetString();
OP_STATUS oom = UrlAndStringAttr::Create(url_string, url_attr->GetStringLength(), new_attr);
if (OpStatus::IsSuccess(oom))
{
if (url_attr->GetResolvedUrl())
{
oom = new_attr->SetResolvedUrl(url_attr->GetResolvedUrl());
if (OpStatus::IsMemoryError(oom))
{
UrlAndStringAttr::Destroy(new_attr);
value = NULL;
item_type = ITEM_TYPE_URL_AND_STRING;
hld_profile->SetIsOutOfMemory(TRUE);
}
else
value = static_cast<void*>(new_attr);
}
else
value = static_cast<void*>(new_attr);
}
else
{
value = NULL;
item_type = ITEM_TYPE_URL_AND_STRING;
hld_profile->SetIsOutOfMemory(TRUE);
}
}
break;
case ITEM_TYPE_COORDS_ATTR:
if (value)
{
CoordsAttr* new_value;
OP_STATUS status = ((CoordsAttr*)value)->CreateCopy(&new_value);
if (OpStatus::IsError(status))
hld_profile->SetIsOutOfMemory(TRUE);
else
value = (void*)new_value;
}
break;
case ITEM_TYPE_PRIVATE_ATTRS:
if (value)
{
PrivateAttrs* attrs = (PrivateAttrs*)value;
value = attrs->GetCopy(attrs->GetLength());
if (!value)
hld_profile->SetIsOutOfMemory(TRUE);
}
break;
case ITEM_TYPE_COMPLEX:
if (value)
{
ComplexAttr *new_value;
OP_STATUS status = static_cast<ComplexAttr*>(value)->CreateCopy(&new_value);
if (status == OpStatus::ERR_NOT_SUPPORTED)
{
// This attribute shouldn't be copied.
continue;
}
// The attribute might be required and the failure to create it might
// leave the element in a inconsistent state causing crashes
// later. Better to abort immediately.
RETURN_IF_ERROR(status);
OP_ASSERT(new_value);
value = (void*)new_value;
}
break;
default:
continue;
}
}
if (hld_profile->GetIsOutOfMemory())
return OpStatus::ERR_NO_MEMORY;
SetAttrLocal(insert_count++, attr, item_type, value, attr_ns, item_type != ITEM_TYPE_BOOL && item_type != ITEM_TYPE_NUM, attr_is_special, attr_is_id, attr_is_specified, attr_is_event);
// When cloning form elements we need to clone the form value
if (attr_is_special && attr_ns == SpecialNs::NS_LOGDOC && attr == ATTR_FORM_VALUE)
{
FormValue* newformvalue = (FormValue*) value;
if (he->GetFormValue()->GetType() == FormValue::VALUE_RADIOCHECK)
{
FormValueRadioCheck* new_radiovalue = FormValueRadioCheck::GetAs(newformvalue);
FormValueRadioCheck* old_radiovalue = FormValueRadioCheck::GetAs(he->GetFormValue());
new_radiovalue->SetIsChecked(this, old_radiovalue->IsChecked(he), NULL, FALSE);
}
else
{
// Clone the value unless it's already stored in an attribute or somewhere else
FormValue* oldformvalue = he->GetFormValue();
if (oldformvalue->HasMeaningfulTextRepresentation() &&
oldformvalue->GetType() != FormValue::VALUE_OUTPUT &&
oldformvalue->GetType() != FormValue::VALUE_NO_OWN_VALUE)
{
OpString text;
oldformvalue->GetValueAsText(he, text);
newformvalue->SetValueFromText(this, text.CStr());
}
}
}
}
for (int j = insert_count; j < attr_count; j++)
{
SetAttrLocal(j, ATTR_NULL, ITEM_TYPE_BOOL, NULL, NS_IDX_DEFAULT, FALSE, TRUE);
}
}
#if defined(SVG_SUPPORT)
if (IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
SVGContext* ctx = g_svg_manager->CreateDocumentContext(this, hld_profile->GetLogicalDocument());
if (!ctx)
return OpStatus::ERR_NO_MEMORY;
}
#endif // SVG_SUPPORT
if (IsFormElement())
{
FormValue* form_value = GetFormValue();
form_value->SetMarkedPseudoClasses(form_value->CalculateFormPseudoClasses(hld_profile->GetFramesDocument(), this));
}
return OpStatus::OK;
}
static int GetNumberOfExtraAttributesForType(HTML_ElementType type, NS_Type ns, HLDocProfile *hld_profile, HtmlAttrEntry* ha_list)
{
if (ns == NS_HTML)
{
switch (type)
{
case HE_FORM: // one extra for ATTR_JS_ELM_IDX
case HE_LABEL: // 1 extra for ATTR_JS_FORM_IDX
case HE_LEGEND: // 1 extra for ATTR_JS_FORM_IDX
case HE_FIELDSET: // 1 extra for ATTR_JS_FORM_IDX
case HE_PROGRESS:
case HE_METER:
#ifdef CANVAS_SUPPORT
case HE_CANVAS:
#endif // CANVAS_SUPPORT
#ifdef MEDIA_HTML_SUPPORT
case Markup::HTE_TRACK:
#endif // MEDIA_HTML_SUPPORT
return 1;
case HE_IMG:
if (hld_profile->GetCurrentForm())
return 1;
break;
case HE_OBJECT:
{
int attr_count = 2; // one extra for ATTR_PRIVATE/ATTR_VALUE
#ifdef PICTOGRAM_SUPPORT
if (ha_list)
{
while (ha_list->attr != Markup::HA_NULL)
{
if (ha_list->attr == Markup::HA_DATA)
{
if (ha_list->value_len > 7 && uni_strni_eq(ha_list->value, "PICT://", 7))
attr_count++; // one extra for ATTR_LOCALSRC_URL
break;
}
ha_list++;
}
}
#endif // PICTOGRAM_SUPPORT
return attr_count;
}
case HE_EMBED: // one extra for ATTR_PRIVATE/ATTR_VALUE
case HE_APPLET: // one extra for ATTR_PRIVATE/ATTR_VALUE
case HE_SCRIPT:
case HE_OUTPUT:
#ifdef MEDIA_HTML_SUPPORT
case HE_AUDIO:
case HE_VIDEO:
#endif //MEDIA_HTML_SUPPORT
return 2;
case HE_BUTTON:
case HE_INPUT:
case HE_TEXTAREA:
case HE_SELECT:
#if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_)
case HE_KEYGEN:
#endif
case HE_STYLE:
return 3; // three extra for ATTR_JS_ELM_IDX, ATTR_FORM_VALUE and ATTR_JS_FORM_IDX (the JS attrs are set later in InsertElement)
case HE_PROCINST:
case HE_LINK:
return 4;
}
}
#ifdef SVG_SUPPORT
else if (ns == NS_SVG)
{
switch (type)
{
case Markup::SVGE_SCRIPT:
return 2;
case Markup::SVGE_STYLE:
return 3;
}
}
#endif // SVG_SUPPORT
#if defined PICTOGRAM_SUPPORT && defined _WML_SUPPORT_
else if (ns == NS_WML)
{
int attr_count = 0;
if (ha_list)
{
while (ha_list->attr != Markup::HA_NULL)
{
if (ha_list->attr == Markup::WMLA_LOCALSRC)
{
if (ha_list->value_len > 7 && uni_strni_eq(ha_list->value, "PICT://", 7))
attr_count++; // one extra for ATTR_LOCALSRC_URL
break;
}
ha_list++;
}
}
return attr_count;
}
#endif // PICTOGRAM_SUPPORT && _WML_SUPPORT_
return 0;
}
OP_STATUS HTML_Element::SetExtraAttributesForType(unsigned &attr_i, NS_Type ns_type, HtmlAttrEntry *ha_list, int attr_count, HLDocProfile *hld_profile)
{
HTML_ElementType type = Type();
OP_STATUS ret_stat = OpStatus::OK;
if (ns_type == NS_HTML)
{
switch (type)
{
case HE_PROCINST:
{
const uni_char* target = GetStringAttr(ATTR_TARGET, NS_IDX_HTML);
if (!target || !uni_str_eq(target, "xml-stylesheet"))
break;
}
// fall through
case HE_STYLE:
case HE_LINK:
SetAttrLocal(attr_i++, ATTR_CSS, ITEM_TYPE_CSS, (void*)0, SpecialNs::NS_LOGDOC, TRUE, TRUE);
// fall through
case HE_SCRIPT:
// link, script and style tag need some special attributes
ret_stat = SetSrcListAttr(attr_i++, NULL);
break;
case HE_EMBED:
case HE_APPLET:
case HE_OBJECT:
if (ha_list)
{
// add private attrs
int plen = attr_count - 1; // not including this
PrivateAttrs* pa = AddPrivateAttr(hld_profile, type, plen, ha_list);
// OOM check
if (!pa)
return OpStatus::ERR_NO_MEMORY;
SetAttrLocal(attr_i++, ATTR_PRIVATE, ITEM_TYPE_PRIVATE_ATTRS, pa, SpecialNs::NS_LOGDOC, TRUE, TRUE);
SetAttrLocal(attr_i++, ATTR_JS_ELM_IDX, ITEM_TYPE_NUM, INT_TO_PTR(hld_profile->GetNewEmbedElmNumber()), SpecialNs::NS_LOGDOC, FALSE, TRUE);
}
break;
#ifdef MEDIA_HTML_SUPPORT
case HE_AUDIO:
case HE_VIDEO:
if (GetInserted() < HE_INSERTED_FIRST_HIDDEN_BY_ACTUAL)
{
RETURN_IF_ERROR(ConstructMediaElement(attr_i++));
SetAttrLocal(attr_i++, Markup::MEDA_MEDIA_ATTR_IDX, ITEM_TYPE_NUM, INT_TO_PTR(Markup::MEDA_COMPLEX_MEDIA_ELEMENT), SpecialNs::NS_MEDIA, FALSE, TRUE);
}
break;
case Markup::HTE_TRACK:
if (GetInserted() < HE_INSERTED_FIRST_HIDDEN_BY_ACTUAL)
{
TrackElement* track_elm = OP_NEW(TrackElement, ());
if (!track_elm)
return OpStatus::ERR_NO_MEMORY;
SetAttrLocal(attr_i++, Markup::MEDA_COMPLEX_TRACK_ELEMENT, ITEM_TYPE_COMPLEX, track_elm, SpecialNs::NS_MEDIA, TRUE, TRUE);
}
break;
#endif // MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
case HE_CANVAS:
if (GetInserted() < HE_INSERTED_FIRST_HIDDEN_BY_ACTUAL &&
hld_profile->GetESEnabled()
&& g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::CanvasEnabled,
*hld_profile->GetURL()))
{
Canvas* value = OP_NEW(Canvas, ());
if (!value)
return OpStatus::ERR_NO_MEMORY;
SetAttrLocal(attr_i++, Markup::VEGAA_CANVAS, ITEM_TYPE_COMPLEX,
value, SpecialNs::NS_OGP, TRUE, TRUE);
}
break;
#endif // CANVAS_SUPPORT
// Insert form values if that kind of element
case HE_TEXTAREA:
case HE_OUTPUT:
#if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_)
case HE_KEYGEN:
#endif
case HE_INPUT:
case HE_SELECT:
case HE_BUTTON:
CHECK_IS_FORM_VALUE_TYPE(this);
{
FormValue* value;
RETURN_IF_ERROR(ConstructFormValue(hld_profile, value));
SetAttrLocal(attr_i++, ATTR_FORM_VALUE, ITEM_TYPE_COMPLEX,
value, SpecialNs::NS_LOGDOC, TRUE, TRUE);
}
break;
}
} // end if (ns == NS_HTML)
#if defined(SVG_SUPPORT)
else if (ns_type == NS_SVG)
{
switch (type)
{
case Markup::SVGE_STYLE:
SetAttrLocal(attr_i++, ATTR_CSS, ITEM_TYPE_CSS, 0, SpecialNs::NS_LOGDOC, TRUE, TRUE);
// fall through
case Markup::SVGE_SCRIPT:
// link, script and style tag need some special attributes
ret_stat = SetSrcListAttr(attr_i++, 0);
break;
}
}
#endif // SVG_SUPPORT
return ret_stat;
}
OP_STATUS
HTML_Element::Construct(HLDocProfile* hld_profile, int ns_idx,
HTML_ElementType type, HtmlAttrEntry* ha_list,
HE_InsertType inserted/*=HE_NOT_INSERTED*/,
BOOL decode_entities_in_attributes /*= FALSE*/)
{
css_properties = NULL;
layout_box = NULL;
packed1_init = 0;
packed2_init = 0;
SetType(type);
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
SetNsIdx(ns_idx);
g_ns_manager->GetElementAt(ns_idx)->IncRefCount();
NS_Type ns_type = g_ns_manager->GetNsTypeAt(ns_idx);
unsigned attr_count = 0;
unsigned attr_i = 0;
if (inserted != HE_NOT_INSERTED)
{
SetInserted(inserted);
attr_count++;
}
if (ha_list)
{
#if defined XML_EVENTS_SUPPORT
BOOL has_xml_events_attributes = FALSE;
#endif // XML_EVENTS_SUPPORT
while (ha_list[attr_i].attr != ATTR_NULL)
{
if (!ha_list[attr_i].is_special)
{
switch (g_ns_manager->GetNsTypeAt(ResolveNsIdx(ha_list[attr_i].ns_idx)))
{
case NS_HTML:
{
if (ha_list[attr_i].attr == ATTR_FACE) // one extra for font number
attr_count++;
#ifdef PICTOGRAM_SUPPORT
else if (type == HE_OBJECT && ha_list[attr_i].attr == ATTR_DATA
&& ha_list[attr_i].value_len > 7 && uni_strni_eq(ha_list[attr_i].value, "PICT://", 7))
{
attr_count++;
}
#endif // PICTOGRAM_SUPPORT
}
break;
#ifdef PICTOGRAM_SUPPORT
case NS_WML:
if (ha_list[attr_i].attr == WA_LOCALSRC)
attr_count++;
break;
#endif // PICTOGRAM_SUPPORT
#ifdef XML_EVENTS_SUPPORT
case NS_EVENT:
has_xml_events_attributes = TRUE;
hld_profile->GetFramesDocument()->SetHasXMLEvents();
break;
#endif // XML_EVENTS_SUPPORT
}
}
attr_i++;
attr_count++;
}
#if defined XML_EVENTS_SUPPORT
if (has_xml_events_attributes)
attr_count++; // one extra for ATTR_XML_EVENTS_REGISTRATION
#endif // XML_EVENTS_SUPPORT
}
attr_count += GetNumberOfExtraAttributesForType(type, ns_type, hld_profile, ha_list);
if (attr_count)
{
data.attrs = NEW_HTML_Attributes((attr_count));
if (!data.attrs)
{
hld_profile->SetIsOutOfMemory(TRUE);
return OpStatus::ERR_NO_MEMORY;
}
SetAttrSize(attr_count);
REPORT_MEMMAN_INC(attr_count * sizeof(AttrItem));
}
else
data.attrs = NULL;
void* value;
ItemType item_type;
attr_i = 0;
if (ha_list)
{
BOOL replace_escapes = Markup::IsRealElement(Type()) && decode_entities_in_attributes;
for (int i=0; ha_list[i].attr != ATTR_NULL; i++)
{
item_type = ITEM_TYPE_UNDEFINED;
value = 0;
HtmlAttrEntry* hae = &ha_list[i];
BOOL need_free = TRUE;
BOOL is_event = FALSE;
const uni_char* orig_hae_value = hae->value;
UINT orig_hae_value_len = hae->value_len;
// If we allocate a new buffer for
BOOL may_steal_hae_value = FALSE;
if (replace_escapes && hae->value_len > 0)
{
OP_BOOLEAN replaced = ReplaceAttributeEntities(hae);
if (OpStatus::IsError(replaced))
goto oom_err;
if (replaced == OpBoolean::IS_TRUE)
may_steal_hae_value = TRUE; // Now we own hae->value
}
OP_STATUS status = ConstructAttrVal(hld_profile, hae, may_steal_hae_value, value, item_type, need_free, is_event, ha_list, &attr_i);
if (may_steal_hae_value)
{
OP_DELETEA(const_cast<uni_char*>(hae->value));
hae->value = orig_hae_value;
hae->value_len = orig_hae_value_len;
}
if (OpStatus::IsMemoryError(status))
goto oom_err;
if (item_type != ITEM_TYPE_UNDEFINED)
SetAttrLocal(attr_i++, hae->attr, item_type, value, hae->ns_idx, need_free, hae->is_special, hae->is_id, hae->is_specified, is_event);
}
}
if (OpStatus::IsMemoryError(SetExtraAttributesForType(attr_i, ns_type, ha_list, attr_count, hld_profile)))
goto oom_err;
OP_ASSERT(attr_i <= attr_count);
// reset unidentified attrs
while (attr_i < attr_count)
{
SetAttrLocal(attr_i, ATTR_NULL, ITEM_TYPE_BOOL, NULL, NS_IDX_DEFAULT, FALSE, TRUE);
attr_i++;
}
#if defined(JS_PLUGIN_SUPPORT)
if (type == HE_OBJECT)
RETURN_IF_MEMORY_ERROR(SetupJsPluginIfRequested(GetStringAttr(ATTR_TYPE), hld_profile));
#endif // JS_PLUGIN_SUPPORT
#if defined(SVG_SUPPORT)
if (ns_type == NS_SVG && type == Markup::SVGE_SVG)
{
SVGContext* ctx = g_svg_manager->CreateDocumentContext(this, hld_profile->GetLogicalDocument());
if (!ctx)
goto oom_err;
}
#endif // SVG_SUPPORT
return OpStatus::OK;
oom_err:
hld_profile->SetIsOutOfMemory(TRUE);
return OpStatus::ERR_NO_MEMORY;
}
#if defined(JS_PLUGIN_SUPPORT)
OP_STATUS HTML_Element::SetupJsPluginIfRequested(const uni_char* type_attr, HLDocProfile* hld_profile)
{
if (type_attr)
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
RETURN_IF_ERROR(frames_doc->ConstructDOMEnvironment());
DOM_Environment *environment = frames_doc->GetDOMEnvironment();
if (environment && environment->IsEnabled())
if (JS_Plugin_Context *ctx = environment->GetJSPluginContext())
if (ctx->HasObjectHandler(type_attr, NULL))
{
ES_Runtime *runtime = environment->GetRuntime();
DOM_Object *node;
RETURN_IF_ERROR(environment->ConstructNode(node, this));
return ctx->HandleObject(type_attr, this, runtime, ES_Runtime::GetHostObject(runtime->GetGlobalObjectAsPlainObject()));
}
}
return OpStatus::ERR;
}
#endif
OP_STATUS HTML_Element::Construct(HLDocProfile* hld_profile, const uni_char* ttxt, unsigned int text_len)
{
return Construct(ttxt, text_len, FALSE, FALSE);
}
OP_STATUS
HTML_Element::Construct(const uni_char* ttxt, unsigned int text_len, BOOL resolve_entities, BOOL is_cdata)
{
OP_ASSERT(text_len <= SplitTextLen || !"Use AppendText/SetText if you are going to insert long text chunks, or rather use them anyway");
css_properties = NULL;
layout_box = NULL;
packed1_init = 0;
packed2_init = 0;
packed2.props_clean = 1;
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
SetNsIdx(NS_IDX_DEFAULT);
g_ns_manager->GetElementAt(NS_IDX_DEFAULT)->IncRefCount();
SetType(HE_TEXT);
// Avoid allocating a TextData if we're going to work more on it anyway,
// which is signaled by a NULL ttxt.
if (ttxt)
{
data.text = NEW_TextData(());
if( ! data.text || data.text->Construct(ttxt, text_len, resolve_entities, is_cdata, FALSE) == OpStatus::ERR_NO_MEMORY )
{
DELETE_TextData(data.text);
data.text = NULL;
return OpStatus::ERR_NO_MEMORY;
}
}
else
data.text = NULL;
return OpStatus::OK;
}
static OP_STATUS CreateStyleAttribute(const uni_char* str, size_t str_len, URL* base_url, HLDocProfile* hld_profile, void*& value, ItemType& item_type)
{
CSS_property_list* list = NULL;
if (str_len > 0 && hld_profile)
{
CSS_PARSE_STATUS stat;
list = CSS::LoadHtmlStyleAttr(str, str_len, base_url ? *base_url : URL(), hld_profile, stat);
if (OpStatus::IsMemoryError(stat))
return stat;
}
value = (void*) NULL;
if (str)
{
uni_char* string = UniSetNewStrN(str, str_len);
if (list)
{
if (string)
{
StyleAttribute* style_attr = OP_NEW(StyleAttribute, (string, list));
value = static_cast<void*>(style_attr);
}
if (!value)
{
OP_DELETEA(string);
list->Unref();
return OpStatus::ERR_NO_MEMORY;
}
item_type = ITEM_TYPE_COMPLEX;
}
else
{
value = static_cast<void*>(string);
item_type = ITEM_TYPE_STRING;
}
}
return OpStatus::OK;
}
OP_STATUS
ClassAttribute::Construct(const OpVector<ReferencedHTMLClass>& classes)
{
UINT32 count = classes.GetCount();
OP_ASSERT(count > 0);
ReferencedHTMLClass** class_list = OP_NEWA(ReferencedHTMLClass*, count+1);
if (class_list)
{
class_list[count] = NULL;
while (count--)
class_list[count] = classes.Get(count);
SetClassList(class_list);
return OpStatus::OK;
}
else
return OpStatus::ERR_NO_MEMORY;
}
/* virtual */
ClassAttribute::~ClassAttribute()
{
if (IsSingleClass())
{
if (m_class)
m_class->UnRef();
}
else
{
ReferencedHTMLClass** cur = GetClassList();
while (*cur)
{
(*cur)->UnRef();
cur++;
}
OP_DELETEA(GetClassList());
}
OP_DELETEA(m_string);
}
/* virtual */ OP_STATUS
ClassAttribute::CreateCopy(ComplexAttr **copy_to)
{
ReferencedHTMLClass* single_class = NULL;
ReferencedHTMLClass** new_class_list = NULL;
uni_char* string = UniSetNewStr(m_string);
if (!string)
return OpStatus::ERR_NO_MEMORY;
if (IsSingleClass())
single_class = m_class;
else
{
ReferencedHTMLClass** class_list = GetClassList();
unsigned int i = 0;
while (*class_list++)
i++;
new_class_list = OP_NEWA(ReferencedHTMLClass*, i+1);
if (!new_class_list)
{
OP_DELETEA(string);
return OpStatus::ERR_NO_MEMORY;
}
}
ClassAttribute* copy = OP_NEW(ClassAttribute, (string, m_class));
if (!copy)
{
OP_DELETEA(string);
OP_DELETEA(new_class_list);
return OpStatus::ERR_NO_MEMORY;
}
if (single_class)
single_class->Ref();
else
if (new_class_list)
{
copy->SetClassList(new_class_list);
ReferencedHTMLClass** class_list = GetClassList();
while ((*new_class_list = *class_list++))
(*new_class_list++)->Ref();
}
*copy_to = copy;
return OpStatus::OK;
}
/* virtual */ BOOL
ClassAttribute::MoveToOtherDocument(FramesDocument *old_document, FramesDocument *new_document)
{
if (!new_document)
return FALSE;
LogicalDocument* logdoc = new_document->GetLogicalDocument();
if (!logdoc)
return FALSE;
if (IsSingleClass())
{
if (m_class)
{
uni_char* new_str = UniSetNewStr(m_class->GetString());
if (!new_str)
return FALSE;
ReferencedHTMLClass* new_ref = logdoc->GetClassReference(new_str);
if (new_ref)
{
m_class->UnRef();
m_class = new_ref;
}
else
return FALSE;
}
}
else
{
ReferencedHTMLClass** class_list = GetClassList();
while (*class_list)
{
uni_char* new_str = UniSetNewStr((*class_list)->GetString());
if (!new_str)
return FALSE;
ReferencedHTMLClass* new_ref = logdoc->GetClassReference(new_str);
if (new_ref)
{
(*class_list)->UnRef();
*class_list++ = new_ref;
}
else
return FALSE;
}
}
return TRUE;
}
OP_STATUS
StringTokenListAttribute::SetValue(const uni_char* attr_str_in, size_t length)
{
OP_ASSERT(attr_str_in);
RETURN_IF_ERROR(m_string.Set(attr_str_in, length));
m_list.DeleteAll();
// Decompose string into tokens.
const uni_char* attr_str = m_string.CStr();
while (*attr_str)
{
// Skip whitespace.
attr_str += uni_strspn(attr_str, WHITESPACE_L);
// Find size of next token.
if (size_t token_len = uni_strcspn(attr_str, WHITESPACE_L))
{
OpString* new_token = OP_NEW(OpString, ());
if (!new_token || OpStatus::IsMemoryError(new_token->Set(attr_str, token_len)))
{
OP_DELETE(new_token);
return OpStatus::ERR_NO_MEMORY;
}
RETURN_IF_ERROR(m_list.Add(new_token));
// Skip this token.
attr_str += token_len;
// Continue populating collection from next token.
}
}
return OpStatus::OK;
}
/* virtual */ OP_STATUS
StringTokenListAttribute::CreateCopy(ComplexAttr **copy_to)
{
OpAutoPtr<StringTokenListAttribute> ap_copy(OP_NEW(StringTokenListAttribute, ()));
RETURN_OOM_IF_NULL(ap_copy.get());
RETURN_IF_ERROR(ap_copy->m_string.Set(m_string));
for (UINT32 i_token = 0; i_token < m_list.GetCount(); i_token++)
{
OpAutoPtr<OpString> new_token(OP_NEW(OpString, ()));
RETURN_OOM_IF_NULL(new_token.get());
RETURN_IF_ERROR(new_token->Set(m_list.Get(i_token)->CStr()));
RETURN_IF_ERROR(ap_copy->m_list.Add(new_token.release()));
}
*copy_to = ap_copy.release();
return OpStatus::OK;
}
OP_STATUS
StringTokenListAttribute::Add(const uni_char* token_to_add)
{
OP_ASSERT(token_to_add);
OP_ASSERT(token_to_add[0] != ' ');
if (Contains(token_to_add))
// No need to add, it's already there.
return OpStatus::OK;
// Add to list.
OpAutoPtr<OpString> str_token_to_add(OP_NEW(OpString, ()));
RETURN_IF_ERROR(str_token_to_add->Set(token_to_add));
RETURN_IF_ERROR(m_list.Add(str_token_to_add.release()));
// Add to underlying string.
TempBuffer *buffer = g_opera->logdoc_module.GetTempBuffer();
OP_STATUS status = buffer->Append(m_string.CStr());
if (OpStatus::IsSuccess(status))
status = StringTokenListAttribute::AppendWithSpace(buffer, token_to_add);
if (OpStatus::IsSuccess(status))
status = m_string.Set(buffer->GetStorage());
g_opera->logdoc_module.ReleaseTempBuffer(buffer);
return status;
}
OP_STATUS
StringTokenListAttribute::Remove(const uni_char* token_to_remove)
{
OP_ASSERT(token_to_remove);
OP_ASSERT(token_to_remove[0] != ' ');
BOOL did_remove = FALSE;
// Remove from list.
for (int i = m_list.GetCount() - 1; i >= 0; i--)
if (uni_str_eq(m_list.Get(i)->CStr(), token_to_remove))
{
m_list.Delete(i);
did_remove = TRUE;
}
// Remove from underlying string.
if (did_remove)
{
OP_STATUS status = OpStatus::OK;
const uni_char* attr_str = m_string.CStr();
const uni_char* copy_start = attr_str;
const uni_char* copy_end = attr_str;
unsigned int to_remove_len = uni_strlen(token_to_remove);
TempBuffer* buffer = g_opera->logdoc_module.GetTempBuffer();
while (*attr_str)
{
// Skip whitespace.
attr_str += uni_strspn(attr_str, WHITESPACE_L);
// Find size of next token.
if (size_t token_len = uni_strcspn(attr_str, WHITESPACE_L))
{
if (uni_strncmp(attr_str, token_to_remove, MAX(token_len, to_remove_len)) == 0)
{
// Copy what we have so far.
if (OpStatus::IsError(status = StringTokenListAttribute::AppendWithSpace(buffer, copy_start, copy_end - copy_start)))
break;
// Skip this occurence of to_remove.
attr_str += token_len;
// skip whitespace
attr_str += uni_strspn(attr_str, WHITESPACE_L);
// Continue copying from next token.
copy_start = copy_end = attr_str;
}
else
{
// Keep this token, will copy later.
attr_str += token_len;
copy_end = attr_str;
}
}
}
// Now append what remains.
if (status == OpStatus::OK)
status = StringTokenListAttribute::AppendWithSpace(buffer, copy_start, attr_str - copy_start);
if (status == OpStatus::OK)
status = m_string.Set(buffer->GetStorage() ? buffer->GetStorage() : UNI_L(""));
g_opera->logdoc_module.ReleaseTempBuffer(buffer);
return status;
}
else
// There's nothing to remove.
return OpStatus::OK;
}
static StringTokenListAttribute*
CreateStringTokenListAttribute(const uni_char* attr_str, size_t str_len)
{
if (!attr_str)
{
attr_str = UNI_L("");
str_len = 0;
}
// Create complex attribute.
StringTokenListAttribute* stl = OP_NEW(StringTokenListAttribute, ());
if (!stl || OpStatus::IsError(stl->SetValue(attr_str, str_len)))
{
OP_DELETE(stl);
return NULL;
}
return stl;
}
static OP_STATUS CreateBackgroundAttribute(const uni_char* str, size_t str_len, void*& value, ItemType& item_type)
{
/* Fake background style by rewriting it as a css property. The reason for this is that layout
need a stable CSS_decl, tied to the element.
When background images is stored as a list in the cascade (as it must be for multiple
background images to work), the only current viable choice is to keep a pointer to the css
declaration directly (CSS_decl). When the declaration comes from a HTML attribute, the
declarations are usually shared (allocated statically) and only stable during property
reload, i.e. pointers to them can not be stored in the cascade. Storing the background
attribute as a StyleAttribute lets us have a pointer to a stable CSS_decl in the cascade. */
CSS_property_list* prop_list = OP_NEW(CSS_property_list, ());
if (!prop_list)
return OpStatus::ERR_NO_MEMORY;
else
{
prop_list->Ref();
CSS_generic_value gen_arr;
gen_arr.value_type = CSS_FUNCTION_URL;
gen_arr.value.string = UniSetNewStrN(str_len ? str : UNI_L(""), str_len);
if (!gen_arr.value.string)
{
prop_list->Unref();
return OpStatus::ERR_NO_MEMORY;
}
/* AddDeclL will make a copy of the string. We'll re-use the allocated string for the
ToString representation of StyleAttribute. */
TRAPD(status, prop_list->AddDeclL(CSS_PROPERTY_background_image, &gen_arr, 1, 1, FALSE, CSS_decl::ORIGIN_AUTHOR));
if (OpStatus::IsError(status))
{
OP_DELETEA(gen_arr.value.string);
prop_list->Unref();
return status;
}
else
{
value = OP_NEW(StyleAttribute, (gen_arr.value.string, prop_list));
if (!value)
{
OP_DELETEA(gen_arr.value.string);
prop_list->Unref();
return OpStatus::ERR_NO_MEMORY;
}
}
}
item_type = ITEM_TYPE_COMPLEX;
return OpStatus::OK;
}
#if defined IMODE_EXTENSIONS
void
AddTelUrlAttributes(const uni_char *&value_str, UINT &value_len, HtmlAttrEntry* ha_list)
{
// tel/mail-urls:
// initially this iMode thingie resides here
// Should maybe be moved to HandleEvent. But then we need to know and
// all attributes that we should parse (which, according to spec, we
// shall not assume)
if( !ha_list )
return;
if ((value_len > 4 && uni_strni_eq(value_str, "TEL:", 4))
|| (value_len > 5 && uni_strni_eq(value_str, "MAIL:", 5))
|| (value_len > 5 && uni_strni_eq(value_str, "VTEL:", 5)))
{
uni_char* tmp_buf = (uni_char*)g_memory_manager->GetTempBuf();
UINT buf_len = g_memory_manager->GetTempBufLen();
if (value_len + 1 <= buf_len)
{
if (value_len)
uni_strncpy(tmp_buf, value_str, value_len);
BOOL first_attr = TRUE;
for (int i = 0; ha_list[i].attr != ATTR_NULL; i++)
{
HtmlAttrEntry* current_hae = &ha_list[i];
if (ha_list[i].attr != ATTR_HREF
# ifdef TEL_EXCLUDE_CORE_ATTRS
&& ha_list[i].attr != ATTR_CLASS
&& ha_list[i].attr != ATTR_ID
&& ha_list[i].attr != ATTR_STYLE
&& ha_list[i].attr != ATTR_TITLE
&& ha_list[i].attr != ATTR_LANG
&& ha_list[i].attr != ATTR_DIR
# endif // TEL_EXCLUDE_CORE_ATTRS
&& !ha_list[i].is_special)
{
// avoid buffer overrun
if (value_len + current_hae->value_len + current_hae->name_len + 4 > buf_len)
break;
if (first_attr)
tmp_buf[value_len] = '?';
else
tmp_buf[value_len] = '&';
value_len++;
first_attr = FALSE;
if (current_hae->name_len)
{
uni_strncpy(tmp_buf + value_len, current_hae->name, current_hae->name_len);
value_len += current_hae->name_len;
tmp_buf[value_len++] = '=';
if (current_hae->value_len)
{
uni_strncpy(tmp_buf + value_len, current_hae->value, current_hae->value_len);
value_len += current_hae->value_len;
}
}
}
}
tmp_buf[value_len] = '\0';
value_str = tmp_buf;
}
}
}
#endif // IMODE_EXTENSIONS
BOOL HTML_Element::IsSameAttrValue(int index, const uni_char* name, const uni_char* value)
{
void *old_attr_value = GetValueItem(index);
BOOL is_same_value = FALSE;
switch (GetItemType(index))
{
case ITEM_TYPE_BOOL:
case ITEM_TYPE_NUM:
{
uni_char buf[25]; /* ARRAY OK 2009-05-07 stighal */
#ifdef DEBUG_ENABLE_OPASSERT
buf[24] = 0xabcd; // To catch too long keywords
#endif // DEBUG_ENABLE_OPASSERT
int ns_idx = GetAttrNs(index);
int resolved_ns_idx = ResolveNsIdx(ns_idx);
NS_Type attr_ns = g_ns_manager->GetNsTypeAt(resolved_ns_idx);
const uni_char* generated_value = GenerateStringValueFromNumAttr(GetAttrItem(index), attr_ns, old_attr_value, buf, HE_UNKNOWN);
OP_ASSERT(buf[24] == 0xabcd);
is_same_value = generated_value && uni_str_eq(generated_value, value);
}
break;
case ITEM_TYPE_STRING:
if (GetAttrItem(index) == ATTR_XML)
{
const uni_char* old_name_value = static_cast<const uni_char *>(old_attr_value);
// Verify same attribute name
OP_ASSERT(GetNsIdx() != NS_IDX_HTML ? uni_str_eq(name, old_name_value) : uni_stri_eq(name, old_name_value));
int value_offset = uni_strlen(name) + 1;
is_same_value = uni_str_eq(value, old_name_value+value_offset);
}
else
is_same_value = uni_str_eq(static_cast<const uni_char *>(old_attr_value), value);
break;
case ITEM_TYPE_URL_AND_STRING:
if (Type() == HE_SCRIPT || Type() == HE_OBJECT)
{
UrlAndStringAttr *old_attr = static_cast<UrlAndStringAttr*>(old_attr_value);
is_same_value = old_attr->GetString() && uni_str_eq(old_attr->GetString(), value);
}
break;
case ITEM_TYPE_COMPLEX:
ComplexAttr *old_complex_attr = static_cast<ComplexAttr*>(old_attr_value);
if (old_complex_attr)
{
TempBuffer old_attr_buf;
if (OpStatus::IsSuccess(old_complex_attr->ToString(&old_attr_buf)))
{
const uni_char *old_attr_string = old_attr_buf.GetStorage();
is_same_value = old_attr_string && uni_str_eq(old_attr_string, value);
}
}
break;
}
return is_same_value;
}
OP_STATUS HTML_Element::GetInnerTextOrImgAlt(TempBuffer& title_buffer, const uni_char*& alt_text)
{
for (HTML_Element *iter = this, *stop = this->NextSiblingActual(); iter != stop;)
{
NS_Type helm_ns_type = iter->GetNsType();
if (iter->Type() == HE_TEXT)
{
RETURN_IF_ERROR(title_buffer.Append(iter->TextContent()));
}
else if (helm_ns_type == NS_HTML)
{
switch (iter->Type())
{
case HE_IMG:
if (iter->GetIMG_Alt())
{
alt_text = iter->GetIMG_Alt();
}
break;
case HE_SELECT:
case HE_TEXTAREA:
case HE_SCRIPT:
case HE_STYLE:
iter = iter->NextSiblingActual();
continue;
}
}
iter = iter->NextActual();
}
return OpStatus::OK;
}
/**
* This either makes a copy of hae->value or sets hae->value
* to NULL and then returns the original hae->value or,
* if hae->value_len is 0, returns empty_string.
*
* @returns The string as void* to make it easier to use in ConstructAttrVal or NULL if there was an OOM.
*/
static void* StealOrCopyString(HtmlAttrEntry* hae, BOOL may_steal_hae_value, const uni_char* empty_string)
{
OP_ASSERT(empty_string && !*empty_string);
UINT hae_value_len = hae->value_len;
void* value;
if (hae_value_len)
{
if (may_steal_hae_value)
{
value = (void*)hae->value;
hae->value = NULL; // Signal that it has been stolen
}
else
value = (void*) UniSetNewStrN(hae->value, hae_value_len);
}
else
value = (void*)empty_string;
return value;
}
OP_STATUS HTML_Element::ConstructAttrVal(HLDocProfile* hld_profile,
HtmlAttrEntry* hae,
BOOL may_steal_hae_value,
void*& value,
ItemType& item_type,
BOOL& need_free,
BOOL& is_event,
HtmlAttrEntry* ha_list,
unsigned *attr_index)
{
OP_PROBE8(OP_PROBE_HTML_ELEMENT_CONSTRUCTATTRVAL);
OP_ASSERT(!may_steal_hae_value || hae->value && uni_strlen(hae->value) == hae->value_len);
OP_STATUS ret_stat = OpStatus::OK;
short attr = hae->attr;
URL* base_url = hld_profile ? hld_profile->BaseURL() : NULL;
item_type = ITEM_TYPE_UNDEFINED;
value = NULL;
is_event = FALSE;
const uni_char* empty_string = UNI_L("");
if (hae->is_special)
{
if (hae->ns_idx == SpecialNs::NS_LOGDOC)
{
if (hae->attr == ATTR_XML_NAME)
{
if (hae->value)
{
LogdocXmlName *new_name = OP_NEW(LogdocXmlName, ());
if (new_name)
{
ret_stat = new_name->SetName((LogdocXmlName*)hae->value);
item_type = ITEM_TYPE_COMPLEX;
need_free = TRUE;
value = (void*)new_name;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
else if (hae->attr == ATTR_TEXT_CONTENT ||
hae->attr == ATTR_PUB_ID ||
hae->attr == ATTR_SYS_ID)
{
if (hae->value_len > 0)
{
value = (void*) UniSetNewStrN(hae->value, hae->value_len); // FIXME:REPORT_MEMMAN-KILSMO
need_free = TRUE;
}
else
{
value = (void*)empty_string;
need_free = FALSE;
}
if (value)
item_type = ITEM_TYPE_STRING;
else if (hae->value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else if (hae->attr == ATTR_LOGDOC)
{
item_type = ITEM_TYPE_COMPLEX;
need_free = FALSE;
value = const_cast<uni_char*>(hae->value);
}
else if (hae->attr == ATTR_ALTERNATE)
{
if (hae->value_len == 3 && uni_strncmp(hae->value, "yes", 3) == 0)
{
value = INT_TO_PTR(TRUE);
item_type = ITEM_TYPE_BOOL;
}
}
else
{
OP_ASSERT(!"Unknown special attribute in the logdoc/lexer namespace");
}
}
return ret_stat;
}
NS_Type attr_ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(hae->ns_idx));
switch (attr_ns)
{
case NS_HTML:
{
switch (hae->attr)
{
case ATTR_FACE:
if (hae->value && hld_profile)
{
#ifdef FONTSWITCHING
short font_num = GetFirstFontNumber(hae->value, hae->value_len, hld_profile->GetPreferredScript());
#else //FONTSWITCHING
short font_num = GetFirstFontNumber(hae->value, hae->value_len, WritingSystem::Unknown);
#endif // FONTSWITCHING
value = INT_TO_PTR(font_num);
item_type = ITEM_TYPE_NUM;
}
break;
case ATTR_NOWRAP:
// 06/11/97: Removed since it is not supported on <TABLE> by HTML 3.2 or Netscape
if (Type() == HE_TABLE)
break;
case ATTR_ISMAP:
case ATTR_NOHREF:
case ATTR_HIDDEN:
case ATTR_ITEMSCOPE:
case ATTR_NOSHADE:
case ATTR_NORESIZE:
case ATTR_CHECKED:
case ATTR_SELECTED:
case ATTR_READONLY:
case ATTR_MULTIPLE:
case ATTR_COMPACT:
case ATTR_DISABLED:
case ATTR_DEFER:
case ATTR_DECLARE:
case ATTR_AUTOPLAY:
case ATTR_CONTROLS:
case ATTR_MUTED:
case ATTR_PUBDATE:
case Markup::HA_DEFAULT:
case ATTR_REQUIRED:
case ATTR_AUTOFOCUS:
case ATTR_NOVALIDATE:
case ATTR_FORMNOVALIDATE:
case Markup::HA_REVERSED:
{
// Normally the presence of the hidden attribute means that it's hidden, but it seems
// we have supported hidden=false on plugins in the past so we might need to continue
// supporting it.
item_type = ITEM_TYPE_BOOL;
if (attr == ATTR_MULTIPLE ||
(attr == ATTR_HIDDEN && (IsMatchingType(HE_EMBED, NS_HTML) || IsMatchingType(HE_OBJECT, NS_HTML))))
value = INT_TO_PTR(ATTR_GetKeyword(hae->value, hae->value_len) != ATTR_VALUE_false);
else
value = INT_TO_PTR(TRUE);
}
break;
case ATTR_FRAMEBORDER:
value = INT_TO_PTR(hae->value_len==1 && *hae->value == '1');
item_type = ITEM_TYPE_BOOL;
break;
case ATTR_COLOR:
value = INT_TO_PTR(GetColorVal(hae->value, hae->value_len, TRUE));
item_type = ITEM_TYPE_NUM;
break;
case ATTR_LOOP:
value = INT_TO_PTR(SetLoop(hae->value, hae->value_len));
item_type = ITEM_TYPE_NUM;
break;
case ATTR_WIDTH:
case ATTR_HEIGHT:
case ATTR_HSPACE:
case ATTR_VSPACE:
case ATTR_BORDER:
case ATTR_SPAN:
case ATTR_COLSPAN:
case ATTR_ROWSPAN:
case ATTR_CELLPADDING:
case ATTR_CELLSPACING:
case ATTR_CHAROFF:
case ATTR_TOPMARGIN:
case ATTR_LEFTMARGIN:
case ATTR_RIGHTMARGIN:
case ATTR_BOTTOMMARGIN:
case ATTR_MARGINWIDTH:
case ATTR_MARGINHEIGHT:
case ATTR_FRAMESPACING:
case ATTR_MAXLENGTH:
case ATTR_SCROLLAMOUNT:
case ATTR_SCROLLDELAY:
{
// Need a null terminated string for uni_atoi. Hadn't it been for that we could
// have removed this string copy
uni_char *tmp = (uni_char*)g_memory_manager->GetTempBuf();
unsigned int tlen = (UNICODE_DOWNSIZE(g_memory_manager->GetTempBufLen()) <= hae->value_len) ? UNICODE_DOWNSIZE(g_memory_manager->GetTempBufLen())-1 : hae->value_len;
if (tlen)
uni_strncpy(tmp, hae->value, tlen);
tmp[tlen] = '\0';
int val = 0;
while (*tmp && uni_isspace(*tmp))
tmp++;
BOOL store_as_string = FALSE;
if (*tmp && (uni_isdigit(*tmp) || *tmp == '-' || *tmp == '+'))
val = uni_atoi(tmp);
else if (attr == ATTR_BORDER)
val = Type() == HE_TABLE ? 1 : 0;
else
store_as_string = TRUE;
#ifdef CANVAS_SUPPORT
if (val <= 0 && Type() == HE_CANVAS)
store_as_string = TRUE;
#endif // CANVAS_SUPPORT
if (store_as_string)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
if (val < 0)
val = 0;
switch (attr)
{
case ATTR_WIDTH:
case ATTR_HEIGHT:
case ATTR_CHAROFF:
{
for (UINT k=0; k<tlen; k++)
{
if (tmp[k] == '%')
{
val = -val; // mark as percent
break;
}
}
}
break;
case ATTR_VSPACE:
case ATTR_HSPACE:
if (val > 253)
val = 253;
break;
case ATTR_SPAN:
case ATTR_COLSPAN:
if (val > 1000) // MSIE limit!
val = 1;
break;
case ATTR_ROWSPAN:
if (val > SHRT_MAX)
val = SHRT_MAX; // Opera layout engine limit!
break;
}
value = INT_TO_PTR(val);
item_type = ITEM_TYPE_NUM;
}
}
break;
case ATTR_SIZE:
if (hae->value && hae->value_len)
{
item_type = ITEM_TYPE_NUM;
if (Type() == HE_FONT)
{
int len = hae->value_len;
const uni_char* tmp = hae->value;
BOOL pos = *tmp == '+';
BOOL neg = *tmp == '-';
if (pos || neg)
{
tmp++;
len--;
}
if (len)
{
int fsize = uni_atoi(tmp);
if (pos)
fsize += 3;
else if (neg)
fsize = 3 - fsize;
if (fsize > 7)
fsize = 7;
else if (fsize < 1)
fsize = 1;
value = INT_TO_PTR(fsize);
}
}
else
{
uni_char* end_ptr;
int parsed_number = uni_strtol(hae->value, &end_ptr, 10);
// We only accept numbers at the start of the value
// and only if they're followed by something that isn't a
// letter. This is compatible with MSIE. Mozilla is weird.
if (end_ptr != hae->value && (end_ptr == hae->value + hae->value_len || !uni_isalpha(*end_ptr)))
value = INT_TO_PTR(parsed_number);
else
{
// Store as a string
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
}
else
{
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_TABINDEX:
{
long tabindex;
if (SetTabIndexAttr(hae->value, hae->value_len, this, tabindex))
{
item_type = ITEM_TYPE_NUM;
value = (void*)tabindex;
}
else
{
// Store as a string
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
break;
case ATTR_SHAPE:
case ATTR_ALIGN:
case ATTR_VALIGN:
case ATTR_CLEAR:
case ATTR_METHOD:
case ATTR_FORMMETHOD:
case ATTR_SCROLLING:
case ATTR_DIRECTION:
case ATTR_BEHAVIOR:
case ATTR_DIR:
#ifdef _WML_SUPPORT_
if (hld_profile && hld_profile->IsWml() && Type() == HE_TABLE)
{
item_type = ITEM_TYPE_STRING;
if (hae->value_len)
{
value = (void*) SetStringAttr(hae->value, hae->value_len, FALSE);
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
value = (void*)empty_string;
}
else
#endif // _WML_SUPPORT_
{
item_type = ITEM_TYPE_NUM;
if (hae->value && hae->value_len)
{
BYTE val = ATTR_GetKeyword(hae->value, hae->value_len);
SetNumAttrVal(Type(), attr, val, value);
}
else
{
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
}
break;
case ATTR_SPELLCHECK:
{
SPC_ATTR_STATE spellcheck_state = IsMatchingType(HE_INPUT, NS_HTML) ? SPC_DISABLE_DEFAULT : SPC_ENABLE_DEFAULT;
if (hae->value && hae->value_len)
{
if (uni_strni_eq(hae->value, "true", hae->value_len))
spellcheck_state = SPC_ENABLE;
else if (uni_strni_eq(hae->value, "false", hae->value_len))
spellcheck_state = SPC_DISABLE;
}
else
spellcheck_state = SPC_ENABLE;
value = INT_TO_PTR(spellcheck_state);
item_type = ITEM_TYPE_NUM;
}
break;
case ATTR_FRAME:
case ATTR_RULES:
if (hae->value && hae->value_len)
{
value = INT_TO_PTR(ATTR_GetKeyword(hae->value, hae->value_len));
if (value != NULL)
item_type = ITEM_TYPE_NUM;
}
if (item_type != ITEM_TYPE_NUM)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
case ATTR_COORDS:
if (hae->value_len)
{
// Parse the numbers in the string into an array of ints.
int coords_len = 0;
int *tmp_coords = (int*) g_memory_manager->GetTempBuf2k();
int max_coords_len = g_memory_manager->GetTempBuf2kLen() / sizeof(int);
// This is an approximation of the HTML5 algorithm for parsing lists of numbers:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#rules-for-parsing-a-list-of-integers
const uni_char *tmp = hae->value;
const uni_char* end = hae->value + hae->value_len;
while (tmp < end)
{
// Skip initial trash
const uni_char* start_number_p = tmp;
while (tmp < end && !uni_isdigit(*tmp))
tmp++;
BOOL negated = FALSE;
if (tmp > start_number_p && *(tmp-1) == '-')
negated = TRUE;
int current_number = 0;
while (tmp < end && uni_isdigit(*tmp))
{
current_number = current_number * 10 + *tmp - '0';
tmp++;
}
// Spec says:
//BOOL is_acceptable_number_terminator =
// *tmp <= 0x1f || // control codes
// *tmp >= 0x21 && *tmp <= 0x2b || // the special chars you get from shift+digit on a us keyboard
// *tmp >= 0x2d && *tmp <= 0x2f || // - . and /
// *tmp == 0x3a || // colon
// *tmp >= 0x3c && *tmp <= 0x40 || // <, >, =, ?, @
// *tmp >= 0x5b && *tmp <= 0x60 || // [ ] ^ _
// *tmp >= 0x7b && *tmp <= 0x7f;
BOOL is_acceptable_number_terminator = *tmp <= 0x7f && !op_isalnum(*tmp);
if (tmp < end && is_acceptable_number_terminator)
{
// Skip all to the next seperator (yes, this is weird, but see HTML5, i.e. MSIE)
while (tmp < end && *tmp != ' ' && *tmp != ',' && *tmp != ';')
tmp++;
}
if (tmp < end && *tmp != ' ' && *tmp != ',' && *tmp != ';')
{
// Trailing garbage on the number. Abort the parsing
tmp = end;
}
else
{
if (negated)
current_number = -current_number; // These will be set to 0 below but I tried to keep this block generic in case we want to reuse it.
tmp_coords[coords_len++] = current_number;
if (tmp < end)
tmp++;
if (coords_len >= max_coords_len)
break;
}
}
// end generic number list parser
if (coords_len)
{
CoordsAttr* ca = NEW_CoordsAttr((coords_len)); // FIXME:REPORT_MEMMAN-KILSMO
// OOM check
if (ca && OpStatus::IsSuccess(ca->SetOriginalString(hae->value, hae->value_len)))
{
int* coords = ca->GetCoords();
for (int i = 0; i < coords_len; i++)
{
if (tmp_coords[i] < 0)
coords[i] = 0;
else
coords[i] = tmp_coords[i];
}
value = (void*)ca;
item_type = ITEM_TYPE_COORDS_ATTR;
}
else
{
OP_DELETE(ca);
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
}
else
{
value = (void*)empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_START:
if (hae->value && hae->value_len)
switch (Type())
{
case HE_OL:
{
const uni_char* start_str = hae->value;
while (uni_isspace(*start_str) && ((UINT)(start_str - hae->value)) < hae->value_len)
start_str++;
long start = uni_strtol(start_str, NULL, 10, NULL);
/* Check if start wasn't a valid number. */
if (((UINT)(start_str - hae->value)) == hae->value_len || start == 0 && *start_str != '0')
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
value = INT_TO_PTR(start);
item_type = ITEM_TYPE_NUM;
}
}
break;
default:
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_BACKGROUND:
ret_stat = CreateBackgroundAttribute(hae->value, hae->value_len, value, item_type);
break;
case ATTR_CODEBASE:
case ATTR_CITE:
case ATTR_DATA:
case ATTR_SRC:
case ATTR_LONGDESC:
case ATTR_HREF:
case ATTR_DYNSRC:
case ATTR_USEMAP:
case ATTR_ACTION:
case ATTR_FORMACTION:
case ATTR_POSTER:
case ATTR_MANIFEST:
if (hae->value_len)
{
const uni_char *value_str = hae->value;
UINT value_len = hae->value_len;
#ifdef PICTOGRAM_SUPPORT
if (hae->attr == ATTR_DATA && Type() == HE_OBJECT)
{
if (value_len > 7 && uni_strni_eq(value_str, "PICT://", 7))
{
OpString local_url_str;
ret_stat = PictUrlConverter::GetLocalUrl(value_str, value_len, local_url_str);
if (OpStatus::IsSuccess(ret_stat) && !local_url_str.IsEmpty())
{
value = (void*) SetUrlAttr(local_url_str.CStr(), local_url_str.Length(), base_url, hld_profile, FALSE, TRUE);
if (value)
{
if (attr_index)
SetAttrLocal((*attr_index)++, ATTR_LOCALSRC_URL, ITEM_TYPE_URL, value, SpecialNs::NS_LOGDOC, TRUE, TRUE);
else
SetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, value, TRUE, SpecialNs::NS_LOGDOC);
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsMemoryError(ret_stat))
break;
}
}
}
#endif // PICTOGRAM_SUPPORT
#if defined IMODE_EXTENSIONS
if (Type() == HE_A)
AddTelUrlAttributes(value_str, value_len, ha_list);
#endif // IMODE_EXTENSIONS
// FIXME: Don't modify attributes here, do it when they are used (relates to the ATTR_DATA case that strips whitespace)
if (attr == ATTR_DATA)
{
value_str = SetStringAttr(value_str, value_len, TRUE);
if (!value_str)
{
ret_stat = OpStatus::ERR_NO_MEMORY;
break;
}
}
UrlAndStringAttr *url_attr;
ret_stat = UrlAndStringAttr::Create(value_str, value_len, url_attr);
if (attr == ATTR_DATA)
OP_DELETEA(value_str);
if (OpStatus::IsSuccess(ret_stat))
{
value = static_cast<void*>(url_attr);
item_type = ITEM_TYPE_URL_AND_STRING;
}
}
else
{
UrlAndStringAttr *url_attr;
ret_stat = UrlAndStringAttr::Create(UNI_L(""), 0, url_attr);
if (OpStatus::IsSuccess(ret_stat))
{
value = static_cast<void*>(url_attr);
item_type = ITEM_TYPE_URL_AND_STRING;
}
}
break;
case ATTR_TYPE:
if (hae->value && hae->value_len)
{
HTML_ElementType type = Type();
if (GetNsType() == NS_HTML &&
(type == HE_INPUT ||
type == HE_BUTTON ||
type == HE_LI ||
type == HE_UL ||
type == HE_OL ||
type == HE_MENU || // Kyocera extension
type == HE_DIR)) // Kyocera extension
{
item_type = ITEM_TYPE_NUM;
if (type != HE_INPUT && type != HE_BUTTON && hae->value_len == 1)
{
value = (void*) LIST_TYPE_NULL;
if (*(hae->value) == 'a')
value = (void*) LIST_TYPE_LOWER_ALPHA;
else if (*(hae->value) == 'A')
value = (void*) LIST_TYPE_UPPER_ALPHA;
else if (*(hae->value) == 'i')
value = (void*) LIST_TYPE_LOWER_ROMAN;
else if (*(hae->value) == 'I')
value = (void*) LIST_TYPE_UPPER_ROMAN;
else if (*(hae->value) == '1') // || *(hae->value) == 'n' || *(hae->value) == 'N')
value = (void*) LIST_TYPE_NUMBER;
}
else
{
BYTE val = ATTR_GetKeyword(hae->value, hae->value_len);
SetNumAttrVal(type, attr, val, value);
}
}
else
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
else
{
// Empty type attributes for stylesheets is not the same as none
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_BGPROPERTIES:
if (hae->value_len == 5 && uni_strni_eq(hae->value, "FIXED", 5))
{
value = INT_TO_PTR(TRUE);
item_type = ITEM_TYPE_BOOL;
}
break;
case ATTR_BGCOLOR:
case ATTR_TEXT:
case ATTR_LINK:
case ATTR_VLINK:
case ATTR_ALINK:
if (hae->value_len)
{
value = (void*)GetColorVal(hae->value, hae->value_len, TRUE);
item_type = ITEM_TYPE_NUM;
}
else
{
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_ID:
case ATTR_VALUE:
case ATTR_ROWS:
case ATTR_COLS:
case ATTR_CONTENT:
#ifdef CORS_SUPPORT
case Markup::HA_CROSSORIGIN:
#endif // CORS_SUPPORT
if (hae->value)
{
HTML_ElementType type = Type();
if ((
#ifdef _WML_SUPPORT_
GetNsType() != NS_WML &&
#endif //_WML_SUPPORT
attr == ATTR_VALUE && type != HE_PARAM
&& type != HE_INPUT && type != HE_SELECT
&& type != HE_TEXTAREA && type != HE_OPTION
&& type != HE_BUTTON && type != HE_UNKNOWN
&& type != HE_A) ||
((attr == ATTR_ROWS || attr == ATTR_COLS) && (type == HE_INPUT || type == HE_TEXTAREA)))
{
if (IsNumericAttributeFloat(attr))
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
if (hae->value_len)
value = INT_TO_PTR(uni_atoi(hae->value));
item_type = ITEM_TYPE_NUM;
}
}
else if (attr == ATTR_CONTENT && type == HE_COMMENT)
{
uni_char *val_buffer = OP_NEWA(uni_char, hae->value_len + 1);
if (val_buffer)
{
op_memcpy(val_buffer, hae->value, UNICODE_SIZE(hae->value_len));
val_buffer[hae->value_len] = 0;
value = (void*) val_buffer;
item_type = ITEM_TYPE_STRING;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else if (!(type == HE_FRAMESET && hae->value_len == 0 && (attr == ATTR_COLS || attr == ATTR_ROWS)))
{
// FIXME: Remove special cases that are historic with no obvious reason and probably fixed the right way long ago
// and use StealOrCopy string like the rest.
value = (void*) SetStringAttr(hae->value, hae->value_len, type == HE_EMBED && attr == ATTR_PLUGINSPACE);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
if (attr == ATTR_ID)
hae->is_id = TRUE;
}
}
else
{
value = (void*)empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case ATTR_MEDIA:
{
MediaAttr* media_attr = MediaAttr::Create(hae->value, hae->value_len);
if (media_attr)
{
item_type = ITEM_TYPE_COMPLEX;
value = media_attr;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
case ATTR_TITLE:
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
break;
case ATTR_ALT:
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
break;
}
case ATTR_STYLE:
ret_stat = CreateStyleAttribute(hae->value, hae->value_len, base_url, hld_profile, value, item_type);
break;
case ATTR_CLASS:
if (hld_profile)
{
ClassAttribute* class_attr = hld_profile->GetLogicalDocument()->CreateClassAttribute(hae->value, hae->value_len);
if (class_attr)
{
value = static_cast<void*>(class_attr);
item_type = ITEM_TYPE_COMPLEX;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
case ATTR_ITEMPROP:
case ATTR_ITEMREF:
{
StringTokenListAttribute* stl = CreateStringTokenListAttribute(hae->value, hae->value_len);
if (stl)
{
value = static_cast<void*>(stl);
item_type = ITEM_TYPE_COMPLEX;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
#ifdef DRAG_SUPPORT
case Markup::HA_DROPZONE:
{
DropzoneAttribute* dropzone = DropzoneAttribute::Create(hae->value, hae->value_len);
if (dropzone)
{
value = static_cast<void*>(dropzone);
item_type = ITEM_TYPE_COMPLEX;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
#endif // DRAG_SUPPORT
case ATTR_ONLOAD:
case ATTR_ONUNLOAD:
case ATTR_ONBLUR:
case ATTR_ONFOCUS:
case ATTR_ONFOCUSIN:
case ATTR_ONFOCUSOUT:
case ATTR_ONERROR:
case ATTR_ONSUBMIT:
case ATTR_ONCHANGE:
case ATTR_ONCLICK:
case ATTR_ONDBLCLICK:
case ATTR_ONKEYDOWN:
case ATTR_ONKEYPRESS:
case ATTR_ONKEYUP:
case ATTR_ONMOUSEOVER:
case ATTR_ONMOUSEENTER:
case ATTR_ONMOUSEOUT:
case ATTR_ONMOUSELEAVE:
case ATTR_ONMOUSEMOVE:
case ATTR_ONMOUSEUP:
case ATTR_ONMOUSEDOWN:
case ATTR_ONMOUSEWHEEL:
case ATTR_ONRESET:
case ATTR_ONSELECT:
case ATTR_ONRESIZE:
case ATTR_ONSCROLL:
case ATTR_ONHASHCHANGE:
case ATTR_ONINPUT:
case ATTR_ONFORMINPUT:
case ATTR_ONINVALID:
case ATTR_ONFORMCHANGE:
# ifdef MEDIA_HTML_SUPPORT
case ATTR_ONLOADSTART:
case ATTR_ONPROGRESS:
case ATTR_ONSUSPEND:
case ATTR_ONSTALLED:
case ATTR_ONLOADEND:
case ATTR_ONEMPTIED:
case ATTR_ONPLAY:
case ATTR_ONPAUSE:
case ATTR_ONLOADEDMETADATA:
case ATTR_ONLOADEDDATA:
case ATTR_ONWAITING:
case ATTR_ONPLAYING:
case ATTR_ONSEEKING:
case ATTR_ONSEEKED:
case ATTR_ONTIMEUPDATE:
case ATTR_ONENDED:
case ATTR_ONCANPLAY:
case ATTR_ONCANPLAYTHROUGH:
case ATTR_ONRATECHANGE:
case ATTR_ONDURATIONCHANGE:
case ATTR_ONVOLUMECHANGE:
case Markup::HA_ONCUECHANGE:
# endif
#ifdef CLIENTSIDE_STORAGE_SUPPORT
case ATTR_ONSTORAGE:
#endif // CLIENTSIDE_STORAGE_SUPPORT
# ifdef TOUCH_EVENTS_SUPPORT
case ATTR_ONTOUCHSTART:
case ATTR_ONTOUCHMOVE:
case ATTR_ONTOUCHEND:
case ATTR_ONTOUCHCANCEL:
# endif // TOUCH_EVENTS_SUPPORT
case ATTR_ONCONTEXTMENU:
case ATTR_ONPOPSTATE:
#ifdef PAGED_MEDIA_SUPPORT
case Markup::HA_ONPAGECHANGE:
#endif // PAGED_MEDIA_SUPPORT
#ifdef DRAG_SUPPORT
case Markup::HA_ONDRAG:
case Markup::HA_ONDRAGOVER:
case Markup::HA_ONDRAGENTER:
case Markup::HA_ONDRAGLEAVE:
case Markup::HA_ONDRAGSTART:
case Markup::HA_ONDRAGEND:
case Markup::HA_ONDROP:
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
case Markup::HA_ONCOPY:
case Markup::HA_ONCUT:
case Markup::HA_ONPASTE:
#endif // USE_OP_CLIPBOARD
// If we come from the parser, only add the event handler if this is the
// first attribute for that event type. Using "!attr_index" to check if
// we come from somewhere other than the parser is probably not perfect.
if (!HasAttr(hae->attr) || !attr_index)
{
DOM_EventType event = GetEventType(hae->attr, hae->ns_idx);
is_event = TRUE;
if (hld_profile)
{
hld_profile->GetLogicalDocument()->AddEventHandler(event);
if (exo_object)
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
if (OpStatus::IsMemoryError(SetEventHandler(frames_doc, event, hae->value, hae->value_len)))
{
ret_stat = OpStatus::ERR_NO_MEMORY;
break;
}
}
}
item_type = ITEM_TYPE_STRING;
if (hae->value_len)
{
value = (void*) UniSetNewStrN(hae->value, hae->value_len); // FIXME:REPORT_MEMMAN-KILSMO
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
value = (void*) empty_string;
}
break;
default:
// Unknown attribute, store as name/value string pair. If we end up here
// for a known attribute it's a bug that will cause the attribute to
// become semi-invisible.
if (attr < Markup::HA_LAST) // name can be looked up, store value as string
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
break;
}
else
{
OP_ASSERT(hae->attr == ATTR_XML);
hae->attr = ATTR_XML;
}
break;
}
}
break;
#ifdef _WML_SUPPORT_
case NS_WML:
{
if (hld_profile)
{
hld_profile->WMLInit();
}
switch(hae->attr)
{
case WA_EMPTYOK:
case WA_ORDERED:
case WA_OPTIONAL:
case WA_NEWCONTEXT:
case WA_SENDREFERER:
// values "1" and "true" (case insensitive) are interpreted as TRUE, otherwise FALSE
if ((hae->value_len == 1 && *hae->value == '1')
|| (hae->value_len == 4 && uni_strni_eq(hae->value, "TRUE", 4)))
value = (void*)1;
else
value = (void*)0;
item_type = ITEM_TYPE_BOOL;
break;
case WA_METHOD:
if (hae->value_len == 4 && uni_strni_eq(hae->value, "POST", 4))
value = (void*)HTTP_METHOD_POST;
else
value = (void*)HTTP_METHOD_GET;
item_type = ITEM_TYPE_NUM;
break;
case WA_MODE:
if (hae->value_len == 6 && uni_strni_eq(hae->value, "NOWRAP", 6))
value = (void*)WATTR_VALUE_nowrap;
else
value = (void*)WATTR_VALUE_wrap;
item_type = ITEM_TYPE_NUM;
break;
case WA_TABINDEX:
{
long tabindex;
if (SetTabIndexAttr(hae->value, hae->value_len, this, tabindex))
{
item_type = ITEM_TYPE_NUM;
value = (void*)tabindex;
}
else
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
break;
case WA_CACHE_CONTROL:
if (hae->value_len == 8 && uni_strni_eq(hae->value, "NO-CACHE", 8))
value = (void*)WATTR_VALUE_nocache;
else
value = (void*)WATTR_VALUE_cache;
item_type = ITEM_TYPE_NUM;
break;
case WA_LOCALSRC:
if (hae->value)
{
#ifdef PICTOGRAM_SUPPORT
if (hae->value_len > 7 && uni_strni_eq(hae->value, "PICT://", 7))
{
OpString local_url_str;
ret_stat = PictUrlConverter::GetLocalUrl(hae->value, hae->value_len, local_url_str);
if (OpStatus::IsSuccess(ret_stat) && !local_url_str.IsEmpty())
{
value = (void*) SetUrlAttr(local_url_str.CStr(), local_url_str.Length(), base_url, hld_profile, FALSE, TRUE);
if (value)
{
if (attr_index)
SetAttrLocal((*attr_index)++, ATTR_LOCALSRC_URL, ITEM_TYPE_URL, value, SpecialNs::NS_LOGDOC, TRUE, TRUE);
else
SetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, value, TRUE, SpecialNs::NS_LOGDOC);
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
#endif // PICTOGRAM_SUPPORT
value = (void*) SetStringAttr(hae->value, hae->value_len, FALSE);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
value = (void*) empty_string;
item_type = ITEM_TYPE_STRING;
}
break;
case WA_ID:
case WA_HREF:
case WA_TYPE:
case WA_NAME:
case WA_PATH:
case WA_CLASS:
case WA_TITLE:
case WA_VALUE:
case WA_LABEL:
case WA_INAME:
case WA_FORUA:
case WA_DOMAIN:
case WA_FORMAT:
case WA_IVALUE:
case WA_ENCTYPE:
case WA_ACCESSKEY:
case WA_ACCEPT_CHARSET:
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
else if (hae->value_len)
{
#ifdef IMODE_EXTENSIONS
const uni_char *value_str = (const uni_char*)value;
UINT value_len = hae->value_len;
if (hae->attr == WA_HREF)
AddTelUrlAttributes(value_str, value_len, ha_list);
#endif // IMODE_EXTENSIONS
hae->is_id = hae->attr == WA_ID;
}
break;
case WA_ONPICK:
case WA_ONTIMER:
case WA_ONENTERFORWARD:
case WA_ONENTERBACKWARD:
{
if (hld_profile)
{
hld_profile->WMLInit();
}
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
case ATTR_XML:
// do nothing
break;
default:
if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
hae->attr = ATTR_XML;
break;
}
}
break;
#endif // _WML_SUPPORT_
#ifdef SVG_SUPPORT
case NS_SVG:
// attributes for unknown elements should be stored with full name and value
if(hae->attr != Markup::HA_XML && hld_profile)
{
if(Type() == HE_UNKNOWN)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
DOM_EventType event = DOM_EVENT_NONE;
switch(hae->attr)
{
case Markup::SVGA_CONTENTSCRIPTTYPE:
case Markup::SVGA_CONTENTSTYLETYPE:
case Markup::SVGA_ID:
{
value =
(void*) SetStringAttrUTF8Escaped(hae->value, hae->value_len, hld_profile);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
if(hae->attr == Markup::SVGA_ID)
{
hae->is_id = TRUE;
}
}
break;
case Markup::SVGA_TYPE:
{
Markup::Type type = Type();
if (type == Markup::SVGE_SCRIPT ||
type == Markup::SVGE_STYLE ||
type == Markup::SVGE_VIDEO ||
type == Markup::SVGE_AUDIO ||
type == Markup::SVGE_HANDLER)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
ret_stat = g_svg_manager->ParseAttribute(this, frames_doc,
hae->attr, NS_IDX_SVG, hae->value,
hae->value_len, &value, item_type);
}
}
break;
case Markup::SVGA_STYLE:
ret_stat = CreateStyleAttribute(hae->value, hae->value_len, base_url, hld_profile, value, item_type);
break;
#ifdef DRAG_SUPPORT
case Markup::SVGA_DRAGGABLE:
{
value = (void*) SetStringAttr(hae->value, hae->value_len, FALSE);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
case Markup::SVGA_DROPZONE:
{
DropzoneAttribute* dropzone = DropzoneAttribute::Create(hae->value, hae->value_len);
if (dropzone)
{
value = static_cast<void*>(dropzone);
item_type = ITEM_TYPE_COMPLEX;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
break;
#endif // DRAG_SUPPORT
#ifdef SVG_DOM
case Markup::SVGA_ONFOCUSIN:
event = DOMFOCUSIN;
break;
case Markup::SVGA_ONFOCUSOUT:
event = DOMFOCUSOUT;
break;
case Markup::SVGA_ONACTIVATE:
event = DOMACTIVATE;
break;
case Markup::SVGA_ONCLICK:
event = ONCLICK;
break;
case Markup::SVGA_ONMOUSEDOWN:
event = ONMOUSEDOWN;
break;
case Markup::SVGA_ONMOUSEUP:
event = ONMOUSEUP;
break;
case Markup::SVGA_ONMOUSEOVER:
event = ONMOUSEOVER;
break;
case Markup::SVGA_ONMOUSEENTER:
event = ONMOUSEENTER;
break;
case Markup::SVGA_ONMOUSEMOVE:
event = ONMOUSEMOVE;
break;
case Markup::SVGA_ONMOUSEOUT:
event = ONMOUSEOUT;
break;
case Markup::SVGA_ONMOUSELEAVE:
event = ONMOUSELEAVE;
break;
case Markup::SVGA_ONUNLOAD:
event = SVGUNLOAD;
break;
case Markup::SVGA_ONLOAD:
event = SVGLOAD;
break;
case Markup::SVGA_ONABORT:
event = SVGABORT;
break;
case Markup::SVGA_ONERROR:
event = SVGERROR;
break;
case Markup::SVGA_ONRESIZE:
event = SVGRESIZE;
break;
case Markup::SVGA_ONSCROLL:
event = SVGSCROLL;
break;
case Markup::SVGA_ONZOOM:
event = SVGZOOM;
break;
case Markup::SVGA_ONBEGIN:
event = BEGINEVENT;
break;
case Markup::SVGA_ONEND:
event = ENDEVENT;
break;
case Markup::SVGA_ONREPEAT:
event = REPEATEVENT;
break;
#ifdef TOUCH_EVENTS_SUPPORT
case Markup::SVGA_ONTOUCHSTART:
event = TOUCHSTART;
break;
case Markup::SVGA_ONTOUCHMOVE:
event = TOUCHMOVE;
break;
case Markup::SVGA_ONTOUCHEND:
event = TOUCHEND;
break;
case Markup::SVGA_ONTOUCHCANCEL:
event = TOUCHCANCEL;
break;
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
case Markup::SVGA_ONDRAG:
event = ONDRAG;
break;
case Markup::SVGA_ONDRAGOVER:
event = ONDRAGOVER;
break;
case Markup::SVGA_ONDRAGENTER:
event = ONDRAGENTER;
break;
case Markup::SVGA_ONDRAGLEAVE:
event = ONDRAGLEAVE;
break;
case Markup::SVGA_ONDRAGSTART:
event = ONDRAGSTART;
break;
case Markup::SVGA_ONDRAGEND:
event = ONDRAGEND;
break;
case Markup::SVGA_ONDROP:
event = ONDROP;
break;
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
case Markup::SVGA_ONCOPY:
event = ONCOPY;
break;
case Markup::SVGA_ONCUT:
event = ONCUT;
break;
case Markup::SVGA_ONPASTE:
event = ONPASTE;
break;
#endif // USE_OP_CLIPBOARD
#endif // SVG_DOM
default:
ret_stat = g_svg_manager->ParseAttribute(this, frames_doc,
hae->attr, NS_IDX_SVG, hae->value,
hae->value_len, &value, item_type);
break;
}
if(event != DOM_EVENT_NONE)
{
is_event = TRUE;
hld_profile->GetLogicalDocument()->AddEventHandler(event);
if (exo_object)
ret_stat = SetEventHandler(frames_doc, event, hae->value, hae->value_len);
value = (void*) UniSetNewStrN(hae->value, hae->value_len); // FIXME:REPORT_MEMMAN-KILSMO
if (value)
item_type = ITEM_TYPE_STRING;
else if( hae->value ) // only out of memory if a value was supposed to be copied
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
}
else
hae->attr = ATTR_XML;
break;
#endif // SVG_SUPPORT
#ifdef XLINK_SUPPORT
case NS_XLINK:
{
if (hae->attr == Markup::XLINKA_HREF)
{
if (hld_profile && hae->value)
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
ret_stat = g_svg_manager->ParseAttribute(this, frames_doc,
(Markup::AttrType)hae->attr, NS_IDX_XLINK,
hae->value, hae->value_len, &value, item_type);
}
else
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
else if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
break;
#endif // XLINK_SUPPORT
#ifdef XML_EVENTS_SUPPORT
case NS_EVENT:
{
if (hld_profile)
{
// Replace escapes, except for XML documents where that's already been done
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
}
break;
#endif // XML_EVENTS_SUPPORT
case NS_XML:
switch (hae->attr)
{
case XMLA_ID:
case XMLA_LANG:
case XMLA_BASE:
{
value =
(void*) SetStringAttrUTF8Escaped(hae->value, hae->value_len, hld_profile);
if (value)
item_type = ITEM_TYPE_STRING;
else
ret_stat = OpStatus::ERR_NO_MEMORY;
hae->is_id = hae->attr == XMLA_ID;
}
break;
case XMLA_SPACE:
{
item_type = ITEM_TYPE_BOOL;
if (hae->value_len == 8 && uni_strni_eq(hae->value, "PRESERVE", hae->value_len))
value = INT_TO_PTR(TRUE);
else
value = INT_TO_PTR(FALSE);
}
break;
default:
if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
hae->attr = ATTR_XML;
break;
}
break;
#ifdef ARIA_ATTRIBUTES_SUPPORT
case NS_ARIA:
if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
hae->attr = ATTR_XML;
break;
#endif // ARIA_ATTRIBUTES_SUPPORT
#ifdef MATHML_ELEMENT_CODES
case NS_MATHML:
if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
hae->attr = ATTR_XML;
break;
#endif // MATHML_ELEMENT_CODES
default:
if (hae->attr < Markup::HA_LAST)
{
value = StealOrCopyString(hae, may_steal_hae_value, empty_string);
item_type = ITEM_TYPE_STRING;
if (!value)
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
hae->attr = ATTR_XML;
break;
}
// The ATTR_XML code must be the same in all namespace
if (hae->attr == ATTR_XML)
{
value = OP_NEWA(uni_char, hae->name_len + hae->value_len + 2); // FIXME:REPORT_MEMMAN-KILSMO
if (value)
{
// Copy the attribute name to the value string
if (hae->name_len)
uni_strncpy((uni_char*)value, hae->name, hae->name_len);
((uni_char*)value)[hae->name_len] = '\0';
// Copy the attribute value to the value string
uni_char* val_start = (uni_char*)value + hae->name_len + 1;
if (hae->value_len > 0)
uni_strncpy(val_start, hae->value, hae->value_len);
val_start[hae->value_len] = '\0';
item_type = ITEM_TYPE_STRING;
}
else
ret_stat = OpStatus::ERR_NO_MEMORY;
}
if (item_type == ITEM_TYPE_NUM || item_type == ITEM_TYPE_BOOL)
{
BOOL store_string = TRUE;
#if 1 // optimization (save memory by spending some CPU here)
if (item_type == ITEM_TYPE_NUM)
{
uni_char buf[25]; /* ARRAY OK 2009-05-07 stighal */
#ifdef DEBUG_ENABLE_OPASSERT
buf[24] = 0xabcd; // To catch too long keywords
#endif // DEBUG_ENABLE_OPASSERT
const uni_char* generated_value = GenerateStringValueFromNumAttr(attr, attr_ns, value, buf, HE_UNKNOWN);
OP_ASSERT(buf[24] == 0xabcd);
if (generated_value && hae->value_len == uni_strlen(generated_value) && uni_strncmp(hae->value, generated_value, hae->value_len) == 0)
{
// We can recreate this string exactly with op_ltoa so we'll save some memory and an allocation.
store_string = FALSE;
}
}
#endif // 1
if (store_string)
{
char* value_with_string = OP_NEWA(char, sizeof(INTPTR) + sizeof(uni_char)*(hae->value_len+1));
if (!value_with_string)
{
// This is not critical so we could go on with just the number, but we'll not do that.
ret_stat = OpStatus::ERR_NO_MEMORY;
}
else
{
uni_char* string_part = reinterpret_cast<uni_char*>(value_with_string + sizeof(INTPTR));
if (hae->value_len)
uni_strncpy(string_part, hae->value, hae->value_len);
string_part[hae->value_len] = '\0';
INTPTR* num_part = reinterpret_cast<INTPTR*>(value_with_string);
*num_part = reinterpret_cast<INTPTR>(value);
item_type = ITEM_TYPE_NUM_AND_STRING;
value = value_with_string;
}
}
}
need_free = item_type != ITEM_TYPE_NUM && item_type != ITEM_TYPE_BOOL
&& !(item_type == ITEM_TYPE_STRING
&& static_cast<uni_char*>(value) == empty_string);
return ret_stat;
}
BOOL HTML_Element::GetIsCDATA() const
{
if (Type() == HE_TEXT)
return data.text->GetIsCDATA();
else if (Type() == HE_TEXTGROUP)
return GetSpecialBoolAttr(ATTR_CDATA, SpecialNs::NS_LOGDOC);
else
return FALSE;
}
short HTML_Element::GetAttrCount() const
{
int count = 0, size = GetAttrSize();
for (int i = 0; i < size; i++)
{
if (!GetAttrIsSpecial(i))
count++;
}
return count;
}
const uni_char* HTML_Element::GetXmlAttr(const uni_char* attr_name, BOOL case_sensitive)
{
int idx = FindAttrIndex(ATTR_XML, attr_name, NS_IDX_ANY_NAMESPACE, case_sensitive);
if ((idx != ATTR_NOT_FOUND) && (GetItemType(idx) == ITEM_TYPE_STRING))
{
const uni_char* str_value = (const uni_char*)GetValueItem(idx);
if (str_value)
{
if (uni_stricmp(str_value, attr_name) == 0)
return str_value + uni_strlen(str_value) + 1;
}
}
return NULL;
}
BOOL HTML_Element::HasNumAttr(short attr, int ns_idx/* = NS_IDX_HTML*/) const
{
OP_ASSERT(attr != ATTR_XML);
int idx = FindAttrIndex(attr, NULL, ns_idx, FALSE);
if (idx != ATTR_NOT_FOUND)
{
ItemType item_type = GetItemType(idx);
return item_type == ITEM_TYPE_BOOL ||
item_type == ITEM_TYPE_NUM ||
item_type == ITEM_TYPE_NUM_AND_STRING;
}
return FALSE;
}
BOOL HTML_Element::HasAttr(short attr, int ns_idx/*=NS_IDX_HTML*/) const
{
if (attr != ATTR_XML && FindAttrIndex(attr, NULL, ns_idx, FALSE) != ATTR_NOT_FOUND)
return TRUE;
return FALSE;
}
BOOL HTML_Element::HasSpecialAttr(short attr, SpecialNs::Ns ns) const
{
if (FindSpecialAttrIndex(attr, ns) != ATTR_NOT_FOUND)
return TRUE;
return FALSE;
}
void* HTML_Element::GetAttrByIndex(int idx, ItemType item_type, void* def_value) const
{
if (idx > ATTR_NOT_FOUND)
{
if (GetItemType(idx) == item_type)
{
if (GetAttrItem(idx) == ATTR_XML)
{
uni_char* str_value = (uni_char*)GetValueItem(idx);
if (str_value)
return str_value + uni_strlen(str_value) + 1;
}
return GetValueItem(idx);
}
else if (GetItemType(idx) == ITEM_TYPE_NUM_AND_STRING)
{
if (item_type == ITEM_TYPE_NUM || item_type == ITEM_TYPE_BOOL)
return INT_TO_PTR(*static_cast<INTPTR*>(GetValueItem(idx)));
else if (item_type == ITEM_TYPE_STRING)
return static_cast<char*>(GetValueItem(idx))+sizeof(INTPTR);
}
else if (GetItemType(idx) == ITEM_TYPE_URL_AND_STRING)
{
if (item_type == ITEM_TYPE_URL)
return static_cast<UrlAndStringAttr*>(GetValueItem(idx))->GetResolvedUrl();
else if (item_type == ITEM_TYPE_STRING)
return static_cast<UrlAndStringAttr*>(GetValueItem(idx))->GetString();
}
}
return def_value;
}
const uni_char*
HTML_Element::GetMicrodataItemValue(TempBuffer& buffer, FramesDocument* frm_doc)
{
int attr = Markup::HA_NULL;
switch (Type())
{
case Markup::HTE_AUDIO:
case Markup::HTE_EMBED:
case Markup::HTE_IFRAME:
case Markup::HTE_IMG:
case Markup::HTE_SOURCE:
//case Markup::HTE_TRACK:
case Markup::HTE_VIDEO:
attr = Markup::HA_SRC;
break;
case Markup::HTE_A:
case Markup::HTE_AREA:
case Markup::HTE_LINK:
attr = Markup::HA_HREF;
break;
case Markup::HTE_OBJECT:
attr = Markup::HA_DATA;
break;
case Markup::HTE_META:
return GetStringAttr(Markup::HA_CONTENT);
case Markup::HTE_TIME:
if (HasAttr(Markup::HA_DATETIME))
return GetStringAttr(Markup::HA_DATETIME);
// else fall through
default:
OP_ASSERT(frm_doc->GetDOMEnvironment());
return DOMGetContentsString(frm_doc->GetDOMEnvironment(), &buffer);
}
if (attr != Markup::HA_NULL)
if (URL* url = GetUrlAttr(attr, NS_IDX_HTML, frm_doc->GetLogicalDocument()))
return url->GetAttribute(URL::KUniName_With_Fragment_Escaped).CStr();
return NULL;
}
BOOL
HTML_Element::IsToplevelMicrodataItem() const
{
if (GetBoolAttr(Markup::HA_ITEMSCOPE) && (!GetItemPropAttribute() || GetItemPropAttribute()->GetTokenCount() == 0))
return TRUE;
return FALSE;
}
void* HTML_Element::GetAttr(short attr, ItemType item_type, void* def_value, int ns_idx/*=NS_IDX_HTML*/) const
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_GETATTR);
OP_ASSERT(item_type != ITEM_TYPE_NUM_AND_STRING); // Internal type, please don't expose past this level
int idx = FindAttrIndex(attr, NULL, ns_idx, FALSE);
return GetAttrByIndex(idx, item_type, def_value);
}
int HTML_Element::SetAttr(short attr, ItemType item_type, void* val, BOOL need_free/*=FALSE*/, int ns_idx/*=NS_IDX_HTML*/, BOOL strict_ns/*=FALSE*/, BOOL is_id/*=FALSE*/, BOOL is_specified/*=TRUE*/, BOOL is_event/*=FALSE*/, int at_known_index /*= -1*/, BOOL case_sensitive/*=FALSE*/)
{
OP_ASSERT(need_free == FALSE || need_free == TRUE || !"Are the arguments messed up again, and the namespace used at this position?");
int i;
if (at_known_index >= 0)
i = at_known_index;
else
i = FindAttrIndex(attr, attr == ATTR_XML ? (const uni_char *) val : NULL, ns_idx, case_sensitive, strict_ns);
return SetAttrCommon(i, attr, item_type, val, need_free, ns_idx, FALSE, is_id, is_specified, is_event);
}
void* HTML_Element::GetSpecialAttr(Markup::AttrType attr, ItemType item_type, void* def_value, SpecialNs::Ns ns) const
{
OP_PROBE7(OP_PROBE_HTML_ELEMENT_GETSPECIALATTR);
OP_ASSERT(item_type != ITEM_TYPE_NUM_AND_STRING); // Internal type, please don't expose past this level
OP_ASSERT(item_type != ITEM_TYPE_URL_AND_STRING && item_type != ITEM_TYPE_NUM_AND_STRING);
int idx = FindSpecialAttrIndex(attr, ns);
if (idx > ATTR_NOT_FOUND && GetItemType(idx) == item_type)
return GetValueItem(idx);
return def_value;
}
int HTML_Element::SetSpecialAttr(Markup::AttrType attr, ItemType item_type, void* val, BOOL need_free, SpecialNs::Ns ns)
{
OP_ASSERT(need_free == FALSE || need_free == TRUE || !"Are the arguments messed up again, and the namespace used at this position?");
int i = FindSpecialAttrIndex(attr, ns);
return SetAttrCommon(i, attr, item_type, val, need_free, ns, TRUE, FALSE, FALSE, FALSE);
}
ElementRef* HTML_Element::GetFirstReferenceOfType(ElementRef::ElementRefType type)
{
ElementRef *iter = m_first_ref;
while (iter && !iter->IsA(type))
iter = iter->NextRef();
return iter;
}
BOOL HTML_Element::SetAttrValue(const uni_char* attr, const uni_char* value, BOOL create)
{
// must check for attr == ATTR_XML and search using string-functions
if (!create && !GetAttrValue(attr))
return FALSE;
int attr_len = uni_strlen(attr);
int value_len = uni_strlen(value);
uni_char* new_value = OP_NEWA(uni_char, attr_len+value_len+2); // FIXME:REPORT_MEMMAN-KILSMO
if (new_value)
{
uni_strcpy(new_value, attr);
uni_strcpy(new_value + attr_len + 1, value);
SetAttr(ATTR_XML, ITEM_TYPE_STRING, (void*)new_value, TRUE);
return TRUE;
}
else
return FALSE;
}
int HTML_Element::ResolveNameNs(const uni_char *prefix, unsigned prefix_length, const uni_char *name) const
{
for (int index = 0, length = GetAttrSize(); index < length; ++index)
{
Markup::AttrType attr_item = GetAttrItem(index);
if (GetAttrIsSpecial(index))
continue;
int resolved_attr_ns = GetResolvedAttrNs(index);
const uni_char *attr_name;
NS_Type ns_type = g_ns_manager->GetNsTypeAt(resolved_attr_ns);
if (attr_item == ATTR_XML)
attr_name = static_cast<const uni_char *>(GetValueItem(index));
else
{
attr_name = HTM_Lex::GetAttributeString(attr_item, ns_type);
if (!attr_name)
continue;
}
const uni_char *ns_prefix = g_ns_manager->GetPrefixAt(resolved_attr_ns);
if (prefix_length > 0 && ns_prefix && uni_strlen(ns_prefix) == prefix_length && uni_strncmp(ns_prefix, prefix, prefix_length) == 0 && uni_str_eq(name, attr_name))
return resolved_attr_ns;
else if (prefix_length > 0 && uni_strncmp(attr_name, prefix, prefix_length) == 0 && attr_name[prefix_length] == ':' && uni_str_eq(attr_name + prefix_length + 1, name))
return NS_IDX_DEFAULT;
else if (ns_type == NS_XMLNS && prefix_length == 0 && !*ns_prefix && uni_str_eq(attr_name, name))
return resolved_attr_ns;
}
return NS_IDX_DEFAULT;
}
int HTML_Element::FindAttrIndexNs(int attr, const uni_char *name, int ns_idx, BOOL case_sensitive, BOOL strict_ns) const
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_FINDATTR);
OP_ASSERT(!(attr != ATTR_XML && ns_idx == NS_IDX_ANY_NAMESPACE));
OP_ASSERT(attr != ATTR_XML || name);
if (!strict_ns)
ns_idx = ResolveNsIdx(ns_idx);
BOOL any_namespace;
NS_Type ns_type;
int name_length;
if (attr == ATTR_XML)
{
any_namespace = ns_idx == NS_IDX_ANY_NAMESPACE;
name_length = uni_strlen(name);
if (!any_namespace)
{
ns_type = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (name_length)
attr = htmLex->GetAttrType(name, name_length, ns_type, case_sensitive);
}
else
ns_type = NS_NONE;
}
else
{
any_namespace = FALSE;
ns_type = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
name_length = 0; // Won't be used, but the compiler might warn about it being used initialized anyway.
}
const uni_char *uri;
if (!any_namespace && (strict_ns || ns_type == NS_USER))
uri = g_ns_manager->GetElementAt(ns_idx)->GetUri();
else
uri = NULL;
for (int index = 0, length = GetAttrSize(); index < length; ++index)
{
/* This function is called a lot, so we want to do the comparison
most likely to fail first, to make the loop as tight as possible. */
Markup::AttrType attr_item = GetAttrItem(index);
if (attr != attr_item)
{
// Textual comparison instead?
if (attr != ATTR_XML) // no
continue;
}
if (GetAttrIsSpecial(index))
continue;
int resolved_attr_ns = GetResolvedAttrNs(index);
if (attr == ATTR_XML)
{
OP_ASSERT(name);
const uni_char *attr_name;
if (attr_item == ATTR_XML)
attr_name = (const uni_char *) GetValueItem(index);
else
{
attr_name = HTM_Lex::GetAttributeString(attr_item, g_ns_manager->GetNsTypeAt(resolved_attr_ns));
if (!attr_name)
continue;
}
if (case_sensitive ? uni_strcmp(name, attr_name) : uni_stricmp(name, attr_name))
continue;
}
int attr_ns = GetAttrNs(index);
if (!any_namespace && (strict_ns ? attr_ns != ns_idx : resolved_attr_ns != ns_idx))
{
if (g_ns_manager->GetNsTypeAt(resolved_attr_ns) != ns_type)
continue;
if (strict_ns || ns_type == NS_USER)
if (uni_strcmp(uri, g_ns_manager->GetElementAt(attr_ns)->GetUri()))
continue;
}
return index;
}
return -1;
}
int HTML_Element::FindHtmlAttrIndex(int attr, const uni_char *name) const
{
OP_ASSERT(attr != ATTR_XML || name);
if (attr == ATTR_XML)
attr = htmLex->GetAttrType(name, NS_HTML, FALSE);
for (int index = 0, length = GetAttrSize(); index < length; ++index)
{
/* This function is called a lot, so we want to do the comparison
most likely to fail first, to make the loop as tight as possible. */
int attr_item = GetAttrItem(index);
if (attr != attr_item)
continue;
if (GetAttrIsSpecial(index))
continue;
int resolved_attr_ns = GetResolvedAttrNs(index);
if (attr == ATTR_XML)
{
OP_ASSERT(name);
const uni_char *attr_name = (const uni_char *) GetValueItem(index);
if (uni_stricmp(name, attr_name))
continue;
}
if (resolved_attr_ns != NS_IDX_HTML && g_ns_manager->GetNsTypeAt(resolved_attr_ns) != NS_HTML)
continue;
return index;
}
return -1;
}
int HTML_Element::FindSpecialAttrIndex(int attr, SpecialNs::Ns ns_idx) const
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_FINDSPECIALATTRINDEX);
for (int index = 0, length = GetAttrSize(); index < length; ++index)
{
if (attr != GetAttrItem(index) || !GetAttrIsSpecial(index) || GetAttrNs(index) != ns_idx)
continue;
return index;
}
return -1;
}
void HTML_Element::LocalCleanAttr(int i)
{
data.attrs[i].Clean();
}
extern const uni_char* CSS_GetKeywordString(short val);
#include "modules/logdoc/src/htm_elm_maps.inl"
const uni_char * GetColorString(COLORREF value)
{
/* When a named color arrives in Opera (either via a
HTML-attribute or CSS) an index is stored in the color-table.
To check if your color value is such an index, and it with
CSS_COLOR_KEYWORD_TYPE_index */
if (value & CSS_COLOR_KEYWORD_TYPE_x_color)
return HTM_Lex::GetColNameByIndex(value & CSS_COLOR_KEYWORD_TYPE_index);
else
{
uni_char* number = (uni_char*)g_memory_manager->GetTempBuf();
HTM_Lex::GetRGBStringFromVal(value, number, TRUE);
return number;
}
}
static BOOL IsLengthAttribute(HTML_ElementType for_element_type, short attr);
const uni_char* HTML_Element::GenerateStringValueFromNumAttr(int attr, NS_Type ns_type, void* value, uni_char* buf, HTML_ElementType for_element_type) const
{
short num_value = (short) (INTPTR) value;
if (ns_type == NS_HTML)
switch (attr)
{
case ATTR_ALIGN:
case ATTR_VALIGN:
return CSS_GetKeywordString(num_value);
case ATTR_METHOD:
case ATTR_FORMMETHOD:
return (num_value >= HTTP_METHOD_GET && num_value <= HTTP_METHOD_PUT) ? MethodNameMap[num_value - HTTP_METHOD_GET] : NULL;
case ATTR_TYPE:
if ((Type() == HE_INPUT || Type() == HE_BUTTON) && GetNsType() == NS_HTML)
return GetInputTypeString((InputType)(INTPTR)value);
else if (((Type() == HE_LI && Parent() && Parent()->Type() == HE_OL) || (Type() == HE_OL)) && GetNsType() == NS_HTML)
return GetLiTypeString((short)(INTPTR)value);
else
return CSS_GetKeywordString(num_value);
case ATTR_SHAPE:
return (num_value >= AREA_SHAPE_DEFAULT && num_value <= AREA_SHAPE_POLYGON) ? ShapeNameMap[num_value - AREA_SHAPE_DEFAULT] : NULL;
case ATTR_DIRECTION:
return GetDirectionString(num_value);
case ATTR_BEHAVIOR:
return (num_value >= ATTR_VALUE_slide && num_value <= ATTR_VALUE_alternate) ? BehaviorNameMap[num_value - ATTR_VALUE_slide] : NULL;
case ATTR_CLEAR:
return (num_value >= CLEAR_NONE && num_value <= CLEAR_ALL) ? ClearNameMap[num_value - CLEAR_NONE] : NULL;
case ATTR_SCROLLING:
return (num_value >= SCROLLING_NO && num_value <= SCROLLING_AUTO) ? ScrollNameMap[num_value - SCROLLING_NO] : ScrollNameMap[SCROLLING_AUTO];
case ATTR_FRAME:
return (num_value >= ATTR_VALUE_box && num_value <= ATTR_VALUE_border) ? FrameValueNameMap[num_value - ATTR_VALUE_box] : NULL;
case ATTR_RULES:
if (num_value == ATTR_VALUE_all)
return RulesNameMap[ATTR_VALUE_groups - ATTR_VALUE_none + 1];
else if (num_value >= ATTR_VALUE_none && num_value <= ATTR_VALUE_groups)
return RulesNameMap[num_value - ATTR_VALUE_none];
else
return NULL;
#ifdef SUPPORT_TEXT_DIRECTION
case ATTR_DIR:
return (num_value == CSS_VALUE_ltr || num_value == CSS_VALUE_rtl) ? DirNameMap[num_value - CSS_VALUE_ltr] : NULL;
#endif
case ATTR_ALINK:
case ATTR_LINK:
case ATTR_TEXT:
case ATTR_VLINK:
case ATTR_COLOR:
case ATTR_BGCOLOR:
return GetColorString((COLORREF) (INTPTR) value);
case ATTR_WIDTH:
case ATTR_HEIGHT:
case ATTR_CHAROFF:
{
uni_char* number = buf;
BOOL convPercent = for_element_type == HE_ANY || for_element_type != HE_UNKNOWN && IsLengthAttribute(for_element_type, attr);
uni_ltoa((convPercent ? (int)op_abs((INTPTR)value) : (INTPTR)value), number, 10);
if (convPercent && ((INTPTR)value) < 0)
uni_strcat(number, UNI_L("%"));
return number;
}
case ATTR_SPELLCHECK:
if (num_value == SPC_DISABLE)
uni_strcpy(buf, UNI_L("false"));
else if (num_value == SPC_ENABLE)
uni_strcpy(buf, UNI_L("true"));
else
return NULL;
return buf;
}
return uni_ltoa(reinterpret_cast<INTPTR>(value), buf, 10);
}
const uni_char * HTML_Element::GetAttrValueValue(int i, short attr, HTML_ElementType for_element_type, TempBuffer *buffer/*=NULL*/) const
{
void* value = GetValueItem(i);
NS_Type ns = g_ns_manager->GetNsTypeAt(GetResolvedAttrNs(i));
switch (GetItemType(i))
{
case ITEM_TYPE_BOOL:
// FIXME: All the code below might be useless after the addition of ITEM_TYPE_NUM_AND_STRING
if (ns == NS_HTML && attr == ATTR_FRAMEBORDER)
return (value) ? UNI_L("1") : UNI_L("0");
else if (ns == NS_XML && attr == XMLA_SPACE)
return (value) ? UNI_L("preserve") : UNI_L("default");
else
return (value) ? UNI_L("true") : UNI_L("false");
case ITEM_TYPE_NUM:
return GenerateStringValueFromNumAttr(attr, ns, value, (uni_char*)g_memory_manager->GetTempBuf(), for_element_type);
case ITEM_TYPE_NUM_AND_STRING:
{
OP_ASSERT(value);
uni_char* string_part = reinterpret_cast<uni_char*>(static_cast<char*>(value)+sizeof(INTPTR));
return string_part;
}
case ITEM_TYPE_STRING:
if (attr == ATTR_XML)
return (const uni_char*) value + uni_strlen((const uni_char*)value) + 1;
else
return (const uni_char*) value;
case ITEM_TYPE_URL:
if (value)
return ((URL*)value)->GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI).CStr();
break;
case ITEM_TYPE_URL_AND_STRING:
{
OP_ASSERT(value);
return static_cast<UrlAndStringAttr*>(value)->GetString();
}
case ITEM_TYPE_COORDS_ATTR:
if(value)
{
CoordsAttr *ca = (CoordsAttr *)value;
return ca->GetOriginalString();
}
break;
case ITEM_TYPE_COMPLEX:
if (value && buffer)
{
buffer->Clear();
if(OpStatus::IsSuccess(((ComplexAttr*)value)->ToString(buffer)))
{
return buffer->GetStorage();
}
}
break;
default:
return NULL;
}
return NULL;
}
const uni_char* HTML_Element::GetAttrValue(short attr, int ns_idx, HTML_ElementType for_element_type, BOOL strict_ns, TempBuffer *buffer, int known_index)
{
int idx = known_index >= 0 ? known_index : FindAttrIndex(attr, NULL, ns_idx, FALSE, strict_ns);
if (idx > ATTR_NOT_FOUND)
return GetAttrValueValue(idx, attr, for_element_type, buffer);
return NULL;
}
const uni_char* HTML_Element::GetAttrValue(const uni_char* attr_name, int ns_idx, HTML_ElementType for_element_type, TempBuffer *buffer, int known_index)
{
short attr = ATTR_XML;
NS_Type ns_type = ns_idx == NS_IDX_ANY_NAMESPACE ? NS_USER : g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (ns_type != NS_USER && Type() != HE_UNKNOWN)
attr = (short)htmLex->GetAttrType(attr_name, ns_type);
int idx = known_index >= 0 ? known_index : FindAttrIndex(attr, attr_name, ns_idx, FALSE);
if (idx != ATTR_NOT_FOUND)
{
if (GetAttrItem(idx) == ATTR_XML)
{
const uni_char* str_value = (const uni_char*)GetValueItem(idx);
if (str_value)
return str_value + uni_strlen(str_value) + 1;
}
else
return GetAttrValueValue(idx, GetAttrItem(idx), for_element_type, buffer);
}
return NULL;
}
BOOL HTML_Element::IsInsideUnclosedFormElement()
{
HTML_Element* elm = this;
while (elm)
{
if (elm->IsMatchingType(HE_FORM, NS_HTML))
{
if (elm->GetEndTagFound())
return FALSE; // Inside _closed_ form element
return TRUE;
}
// This is where MSIE and Mozilla differs. MSIE doesn't search
// up through tables and other "special" elements.
if (elm->GetNsType() == NS_HTML)
{
HTML_ElementType parent_type = elm->Type();
if (parent_type == HE_TABLE ||
parent_type == HE_BUTTON ||
parent_type == HE_SELECT ||
parent_type == HE_DATALIST ||
parent_type == HE_APPLET ||
parent_type == HE_OBJECT)
{
return FALSE;
}
}
elm = elm->Parent();
}
return FALSE;
}
BOOL HTML_Element::InsideLIList() const
{
for (HTML_Element *p = Parent(); p; p = p->Parent())
switch (p->Type())
{
case HE_OL:
case HE_UL:
case HE_MENU:
case HE_DIR:
return TRUE;
}
return FALSE;
}
BOOL HTML_Element::InsideDLList() const
{
for (HTML_Element *p = Parent(); p; p = p->Parent())
if (p->Type() == HE_DL)
return TRUE;
return FALSE;
}
const uni_char*
HTML_Element::LocalContent() const
{
return (Type() == HE_TEXT && data.text) ? data.text->GetText() : NULL;
}
short
HTML_Element::LocalContentLength() const
{
return (Type() == HE_TEXT && data.text) ? data.text->GetTextLen() : 0;
}
void HTML_Element::MakeIsindex(HLDocProfile* hld_profile, const uni_char* prompt)
{
HTML_Element* he = NEW_HTML_Element();
// OOM check
if (!he || he->Construct(hld_profile, NS_IDX_HTML, HE_HR, NULL) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(he);
hld_profile->SetIsOutOfMemory(TRUE);
return;
}
he->Under(this);
OP_STATUS err;
OpString use_prompt;
if (prompt)
{
err = use_prompt.Set(prompt);
}
else
{
TRAP(err, g_languageManager->GetStringL(Str::SI_ISINDEX_TEXT, use_prompt));
}
if (OpStatus::IsMemoryError(err))
hld_profile->SetIsOutOfMemory(TRUE);
he = HTML_Element::CreateText(use_prompt.CStr(), use_prompt.Length(), TRUE, FALSE, FALSE);
if (!he)
{
hld_profile->SetIsOutOfMemory(TRUE);
return;
}
he->Under(this);
he = NEW_HTML_Element();
// OOM check
if (!he || OpStatus::ERR_NO_MEMORY == he->Construct(hld_profile, NS_IDX_HTML, HE_BR, NULL))
{
DELETE_HTML_Element(he);
hld_profile->SetIsOutOfMemory(TRUE);
return;
}
he->Under(this);
const uni_char* const inp_str1 = UNI_L("text");
const uni_char* const inp_str2 = UNI_L("20");
HtmlAttrEntry attr_array[3]; /* ARRAY OK 2010-09-17 fs */
attr_array[0].attr = ATTR_TYPE;
attr_array[0].value = inp_str1;
attr_array[0].value_len = uni_strlen(inp_str1);
attr_array[1].attr = ATTR_SIZE;
attr_array[1].value = inp_str2;
attr_array[1].value_len = uni_strlen(inp_str2);
attr_array[2].attr = ATTR_NULL;
he = NEW_HTML_Element();
// OOM check
if (!he || OpStatus::ERR_NO_MEMORY == he->Construct(hld_profile, NS_IDX_HTML, HE_INPUT, attr_array))
{
DELETE_HTML_Element(he);
hld_profile->SetIsOutOfMemory(TRUE);
return;
}
he->Under(this);
he = NEW_HTML_Element();
// OOM check
if (he && OpStatus::ERR_NO_MEMORY != he->Construct(hld_profile, NS_IDX_HTML, HE_HR, NULL))
he->Under(this);
else
{
DELETE_HTML_Element(he);
hld_profile->SetIsOutOfMemory(TRUE);
}
}
void
HTML_Element::DeleteTextData()
{
OP_DELETE(data.text);
data.text = NULL;
}
void HTML_Element::EmptySrcListAttr()
{
if (DataSrc* head = GetDataSrc())
head->DeleteAll();
}
OP_STATUS HTML_Element::SetTextInternal(FramesDocument* doc, const uni_char *txt, unsigned int txt_len)
{
OP_ASSERT(IsText());
// First remove the current text
TextData* fallback_textdata = NULL;
if (Type() == HE_TEXTGROUP)
{
if (doc && doc->GetDocRoot() && doc->GetDocRoot()->IsAncestorOf(this))
MarkDirty(doc);
while (HTML_Element* child = FirstChild())
{
child->OutSafe(doc, TRUE);
if (child->Clean(doc))
child->Free(doc);
}
}
else
{
fallback_textdata = data.text;
data.text = NULL;
}
// Add the new text
HLDocProfile* hld_profile = doc ? doc->GetHLDocProfile() : NULL;
OP_STATUS status = AppendText(hld_profile, txt, txt_len, FALSE, FALSE, FALSE);
// Make sure we don't have a NULL data.text in case of oom
if (OpStatus::IsError(status) && Type() == HE_TEXT && !data.text)
{
data.text = fallback_textdata;
}
else
{
DELETE_TextData(fallback_textdata);
}
return status;
}
OP_STATUS HTML_Element::SetSrcListAttr(int idx, DataSrc* dupl_head)
{
DataSrc* head = OP_NEW(DataSrc, ());
if (!head)
return OpStatus::ERR_NO_MEMORY;
SetAttrLocal(idx, ATTR_SRC_LIST, ITEM_TYPE_COMPLEX, static_cast<void*>(head), SpecialNs::NS_LOGDOC, TRUE, TRUE);
if (dupl_head && head)
{
DataSrcElm* sse = dupl_head->First();
URL origin = dupl_head->GetOrigin();
while (sse)
{
if (sse->GetSrc())
RETURN_IF_ERROR(head->AddSrc(sse->GetSrc(), sse->GetSrcLen(), origin));
sse = sse->Suc();
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::AddToSrcListAttr(const uni_char* src, int src_len, URL origin)
{
if (DataSrc* head = GetDataSrc())
return head->AddSrc(src, src_len, origin);
else
return OpStatus::ERR_NO_MEMORY;
}
void HTML_Element::RemoveCSS(const DocumentContext& context)
{
RemoveImportedStyleElements(context);
if (context.hld_profile)
context.hld_profile->GetCSSCollection()->RemoveCollectionElement(this);
RemoveSpecialAttribute(ATTR_CSS, SpecialNs::NS_LOGDOC);
}
OP_STATUS HTML_Element::LoadStyle(const DocumentContext& context, BOOL user_defined)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_LOADSTYLE);
if (IsStyleElement() || IsLinkElement())
{
// Remove old stylesheet.
RemoveCSS(context);
// Create DataSrc from inline style elements (HE_STYLE, Markup::SVGE_STYLE)
if (IsStyleElement())
RETURN_IF_ERROR(CreateSrcListFromChildren());
#ifdef USER_JAVASCRIPT
// BeforeCSS and AfterCSS events are generated for linked stylesheets because
// their contents might not be accessible due to cross origin restrictions,
// parse errors or proprietary will be parsed out and therefore not represented
// by the CSSOM. The style loading logic already expects stylesheets to be loaded
// asynchronously so waiting a bit more to run an event listener is trivial.
// <style> elements are not supported because their contents are easily accessible
// in the DOM, the raw contents are just the text nodes, and because supporting
// them would require the styles' loading logic for inline <style> elements to
// be async, which would add some small lag due to event queueing and running
// the ecmascript chunk before handling the CSS.
if (IsLinkElement() && context.hld_profile && DOM_Environment::IsEnabled(context.frames_doc, TRUE))
{
// Creation of the DOM environment will fail if scripts are off. Deal with it gracefully.
RETURN_IF_MEMORY_ERROR(context.frames_doc->ConstructDOMEnvironment());
if (DOM_Environment *environment = context.frames_doc->GetDOMEnvironment())
{
// Run the script immediately since any other thread can be blocked waiting for the style.
ES_Thread* current_thread = context.frames_doc->GetESScheduler()->GetCurrentThread();
OP_BOOLEAN handled_by_userjs = environment->HandleCSS(this, current_thread);
if (handled_by_userjs != OpBoolean::IS_FALSE)
return OpStatus::IsError(handled_by_userjs) ? handled_by_userjs : OpStatus::OK;
}
}
#endif // USER_JAVASCRIPT
DataSrc* src_head = GetDataSrc();
if (!src_head)
return OpStatus::ERR_NO_MEMORY;
URL* base_url_ptr = 0, base_url;
if (IsLinkElement())
base_url_ptr = GetLinkURL(context.logdoc);
else
if (context.hld_profile)
base_url_ptr = context.hld_profile->BaseURL();
if (base_url_ptr)
base_url = *base_url_ptr;
BOOL suspicious_origin = FALSE;
// HE_STYLE/Markup::SVGE_STYLE are local so they are ok, and loads
// outside the document (hld_profile == NULL) is for user.css
// and they are always ok as well.
if (!IsStyleElement() && context.hld_profile)
{
suspicious_origin = TRUE;
URL css_origin = src_head->GetOrigin();
OP_ASSERT(!css_origin.IsEmpty());
if (!css_origin.IsEmpty())
{
URLContentType content_type = css_origin.ContentType();
if (content_type == URL_CSS_CONTENT) // If the server says it's CSS, then it's always ok.
suspicious_origin = FALSE;
else
{
// Try to mark CSS from suspicious sources to make stealing
// content by loading as CSS harder.
if (css_origin.Type() == URL_DATA ||
css_origin.Type() == URL_JAVASCRIPT ||
g_secman_instance->OriginCheck(context.frames_doc, css_origin))
suspicious_origin = FALSE;
}
base_url = css_origin;
}
}
CSS* css = OP_NEW(CSS, (this, base_url, user_defined));
if (!css)
return OpStatus::ERR_NO_MEMORY;
if (!context.hld_profile || context.hld_profile->IsXml())
css->SetXml();
BOOL is_ssr = context.frames_doc && context.frames_doc->GetWindow()->GetLayoutMode() == LAYOUT_SSR;
BOOL store_css = !is_ssr || (context.hld_profile->GetCSSMode() == CSS_FULL && context.hld_profile->HasMediaStyle(CSS_MEDIA_TYPE_HANDHELD));
CSS_PARSE_STATUS stat = OpStatus::OK;
// If the source is not empty, parse into a CSS stylesheet object.
if (!src_head->IsEmpty())
{
unsigned line_no_start = 1, line_character_start = 0;
if (SourcePositionAttr* pos_attr = static_cast<SourcePositionAttr*>(GetSpecialAttr(ATTR_SOURCE_POSITION, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_LOGDOC)))
{
line_no_start = pos_attr->GetLineNumber();
line_character_start = pos_attr->GetLinePosition();
}
if (!suspicious_origin)
{
stat = css->Load(context.hld_profile, src_head, line_no_start, line_character_start);
if (OpStatus::IsMemoryError(stat))
{
RemoveImportedStyleElements(context);
store_css = FALSE;
}
}
else
store_css = FALSE;
}
if (store_css && SetSpecialAttr(ATTR_CSS, ITEM_TYPE_CSS, css, TRUE, SpecialNs::NS_LOGDOC) >= 0)
{
if (context.hld_profile)
{
context.hld_profile->AddCSS(css);
#ifdef USER_JAVASCRIPT
if (IsLinkElement())
if (DOM_Environment *environment = context.frames_doc->GetDOMEnvironment())
stat = environment->HandleCSSFinished(this, context.hld_profile->GetESLoadManager()->GetInterruptedThread(this));
#endif // USER_JAVASCRIPT
}
}
else
OP_DELETE(css);
// For inline style elements, discard the DataSrc we created in the beginning of this method.
if (IsStyleElement())
src_head->DeleteAll();
if (stat == OpStatus::ERR_NO_MEMORY)
return stat;
}
return OpStatus::OK;
}
void HTML_Element::RemoveImportedStyleElements(const DocumentContext& context)
{
HTML_Element* child = FirstChild();
while (child)
{
HTML_Element* next_child = child->Suc();
if (child->GetInserted() == HE_INSERTED_BY_CSS_IMPORT)
{
child->OutSafe(context);
if (child->Clean(context))
child->Free(context);
}
child = next_child;
}
}
#ifdef USE_HTML_PARSER_FOR_XML
inline void StripCDATA(uni_char*& content, int& content_len)
{
// Remove the CDATA stuff before and after
while (content_len > 0 && uni_isspace(*content))
++content, --content_len;
BOOL is_cdata = FALSE;
if (content_len > 9 && uni_strni_eq(content, "<![CDATA[", 9))
{
is_cdata = TRUE;
content += 9, content_len -= 9;
}
while (content_len > 0 && uni_isspace(content[content_len - 1]))
content_len--;
if (is_cdata && uni_strni_eq(content + content_len - 3, "]]>", 3))
content_len -= 3;
}
#endif // USE_HTML_PARSER_FOR_XML
OP_STATUS HTML_Element::CreateSrcListFromChildren()
{
EmptySrcListAttr();
HTML_Element *iter = FirstChild(), *stop = (HTML_Element *) NextSibling();
if (iter == stop)
RETURN_IF_ERROR(AddToSrcListAttr(UNI_L(""), 0, URL()));
else
{
while (iter && iter != stop)
{
switch (iter->Type())
{
case HE_TEXT:
{
uni_char* content = iter->GetTextData()->GetText();
int content_len = iter->GetTextData()->GetTextLen();
#ifdef USE_HTML_PARSER_FOR_XML
StripCDATA(content, content_len);
#endif // USE_HTML_PARSER_FOR_XML
RETURN_IF_ERROR(AddToSrcListAttr(content, content_len, URL()));
}
/* fall through */
case HE_TEXTGROUP:
iter = (HTML_Element *) iter->Next();
break;
default:
iter = (HTML_Element *) iter->NextSibling();
}
}
}
return OpStatus::OK;
}
BOOL HTML_Element::ShowAltText()
{
OP_ASSERT(Type() == HE_IMG || Type() == HE_INPUT || Type() == HE_OBJECT || Type() == HE_EMBED);
HEListElm* hle = GetHEListElm(FALSE);
if (hle)
{
Image img = hle->GetImage();
if (img.Width() && img.Height())
// Size can be determined; reflow
return FALSE;
}
return TRUE;
}
# if defined(SVG_SUPPORT)
static const uni_char* GetStringAttrFromSVGRoot(HTML_Element* elm, Markup::AttrType attr)
{
HTML_Element* parent = elm->Parent();
while(parent)
{
if(parent->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
break;
}
else if(Markup::IsRealElement(parent->Type()))
{
// crossing namespace border not allowed
parent = NULL;
break;
}
parent = parent->Parent();
}
if(parent)
{
return parent->GetStringAttr(attr, NS_IDX_SVG);
}
return NULL;
}
#endif // SVG_SUPPORT
OP_STATUS HTML_Element::ProcessCSS(HLDocProfile *hld_profile)
{
LogicalDocument* logdoc = hld_profile->GetLogicalDocument();
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
LayoutMode layout_mode = hld_profile->GetFramesDocument()->GetWindow()->GetLayoutMode();
BOOL is_smallscreen = layout_mode == LAYOUT_SSR || layout_mode == LAYOUT_CSSR;
CSS_MediaObject* media_obj = GetLinkStyleMediaObject();
short link_style_media = media_obj ? media_obj->GetMediaTypes() : 0;
#if defined(SVG_SUPPORT)
const uni_char *type = NULL;
if(GetNsType() != NS_SVG)
{
type = GetStringAttr(ATTR_TYPE, NS_IDX_HTML);
}
else
{
type = GetStringAttr(Markup::SVGA_TYPE, NS_IDX_SVG);
if(!type)
{
type = GetStringAttrFromSVGRoot(this, Markup::SVGA_CONTENTSTYLETYPE);
}
}
#else
const uni_char *type = GetStringAttr(ATTR_TYPE, NS_IDX_HTML);
#endif // SVG_SUPPORT
// Only read stylesheets that match text/css or has no explicit type.
// HTML 5 also specifies that charset and unknown parameters causes it to
// be an unsupported style sheet, hence only a type of exactly "text/css"
// is supported
if (!type || (uni_stri_eq(type, "text/css")))
{
HTML_Element::DocumentContext context(logdoc);
if ((is_smallscreen
&& ((hld_profile->GetCSSMode() == CSS_FULL && hld_profile->HasMediaStyle(CSS_MEDIA_TYPE_HANDHELD))))
|| (layout_mode != LAYOUT_SSR
&& g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_profile->GetCSSMode(),
PrefsCollectionDisplay::EnableAuthorCSS), *hld_profile->GetURL()))
|| hld_profile->GetFramesDocument()->GetWindow()->IsCustomWindow())
{
status = LoadStyle(context, FALSE);
}
else if (is_smallscreen && hld_profile->GetCSSMode() == CSS_FULL)
{
status = LoadStyle(context, FALSE);
if (status == OpStatus::OK)
{
if (hld_profile->HasMediaStyle(CSS_MEDIA_TYPE_HANDHELD) || (link_style_media & CSS_MEDIA_TYPE_HANDHELD))
{
hld_profile->SetHasMediaStyle(CSS_MEDIA_TYPE_HANDHELD);
// Q: Is this thing really needed? Shouldn't CSS::Added be called in LoadAllCSS(), also for this element?
// A: I don't know, but not necessarily. Perhaps this is what makes reloading default props for elements
// whose default style is different in SSR and handheld mode, but are not affected by any stylesheets, work?
// Let's keep CHANGED_PROPS for now, at least.
hld_profile->GetCSSCollection()->StyleChanged(CSSCollection::CHANGED_PROPS);
status = hld_profile->LoadAllCSS();
}
else
hld_profile->SetUnloadedCSS(TRUE);
}
}
hld_profile->SetHasMediaStyle(link_style_media);
}
return status;
}
HTML_Element::DocumentContext::DocumentContext(FramesDocument *frames_doc)
: frames_doc(frames_doc)
, logdoc(frames_doc ? frames_doc->GetLogicalDocument() : NULL)
, hld_profile(logdoc ? logdoc->GetHLDocProfile() : NULL)
, environment(frames_doc ? frames_doc->GetDOMEnvironment() : NULL)
{
}
HTML_Element::DocumentContext::DocumentContext(LogicalDocument *logdoc)
: frames_doc(logdoc ? logdoc->GetFramesDocument() : NULL)
, logdoc(logdoc)
, hld_profile(logdoc ? logdoc->GetHLDocProfile() : NULL)
, environment(frames_doc ? frames_doc->GetDOMEnvironment() : NULL)
{
}
HTML_Element::DocumentContext::DocumentContext(DOM_Environment *environment)
: frames_doc(environment ? environment->GetFramesDocument() : NULL)
, logdoc(frames_doc ? frames_doc->GetLogicalDocument() : NULL)
, hld_profile(logdoc ? logdoc->GetHLDocProfile() : NULL)
, environment(environment)
{
}
#if defined SEARCH_MATCHES_ALL && !defined HAS_NO_SEARCHTEXT
void HTML_Element::CleanSearchHit(FramesDocument *frm_doc)
{
if (frm_doc)
{
if (HTML_Document* html_doc = frm_doc->GetHtmlDocument())
{
HTML_Element* stop_elm = static_cast<HTML_Element*>(NextSibling());
for (HTML_Element* iter = this; iter && iter != stop_elm; iter = iter->Next())
{
html_doc->RemoveElementFromSearchHit(iter);
}
}
}
}
#endif // SEARCH_MATCHES_ALL && !HAS_NO_SEARCHTEXT
BOOL HTML_Element::Clean(const DocumentContext &context, BOOL going_to_delete/*=TRUE*/)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_CLEAN);
BOOL keep = FALSE;
CleanLocal(context);
if (m_first_ref)
{
// Head of list for the processed refs. The refs are taken out of the
// element list as they are processed to avoid problems with finding
// the next ref if other refs are removed from the list as a
// side-effect of the processing.
AutoNullElementRef placeholder;
while (m_first_ref)
{
// The first ref left will be the next to process.
ElementRef *current_ref = m_first_ref;
m_first_ref = current_ref->NextRef();
// Move the current ref out of the active list.
current_ref->DetachAndMoveAfter(&placeholder);
if (going_to_delete)
current_ref->OnDelete(context.frames_doc);
else
current_ref->OnRemove(context.frames_doc);
}
// Put the references that has not been reset back.
m_first_ref = placeholder.NextRef();
}
LogicalDocument *logdoc = context.logdoc;
if (!Parent() && logdoc && logdoc->GetRoot() == this)
if (context.environment)
if (context.environment->GetDocument())
keep = TRUE;
HTML_Element* c = FirstChild();
while (c)
{
if (!c->Clean(context, going_to_delete))
keep = TRUE;
c = c->Suc();
}
return exo_object == NULL && !keep;
}
void HTML_Element::FreeLayout(const DocumentContext &context)
{
HTML_Element* elm = this;
HTML_Element* stop = static_cast<HTML_Element*>(NextSibling());
while (elm != stop)
{
FreeLayoutLocal(context.frames_doc);
elm = elm->Next();
}
}
void HTML_Element::FreeLayoutLocal(FramesDocument* doc)
{
OP_PROBE7(OP_PROBE_HTML_ELEMENT_FREELAYOUTLOCAL);
if (css_properties)
{
DELETE_CSS_PROPERTIES(this);
}
if (layout_box)
RemoveLayoutBox(doc, TRUE);
if (doc)
{
if (!doc->IsBeingDeleted())
{
SetCurrentDynamicPseudoClass(0);
}
#ifdef SVG_SUPPORT
else
DestroySVGContext();
#endif // SVG_SUPPORT
#ifdef _SPAT_NAV_SUPPORT_
Window* window = doc->GetWindow();
if (window && window->GetSnHandler())
window->GetSnHandler()->ElementDestroyed(this);
#endif // _SPAT_NAV_SUPPORT_
}
}
void HTML_Element::CleanLocal(const DocumentContext &context)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_CLEANLOCAL);
FramesDocument* doc = context.frames_doc;
FreeLayoutLocal(doc);
/* FreeLayoutLocal needs to be called before FlushInlineElement, because
FlushInlineElement will remove the FramesDocElm that belongs to an iframe
and IFrameContent::Disable uses the FramesDocElm object. */
if (doc)
{
#ifdef DOCUMENT_EDIT_SUPPORT
if (doc->GetDocumentEdit())
{
OpDocumentEdit* de = doc->GetDocumentEdit();
de->OnElementDeleted(this);
}
#endif // DOCUMENT_EDIT_SUPPORT
if (!doc->IsBeingDeleted())
{
if (IsReferenced())
CleanReferences(doc);
if (!IsText())
doc->FlushAsyncInlineElements(this);
}
#ifdef DRAG_SUPPORT
g_drag_manager->OnElementRemove(this);
#endif // DRAG_SUPPORT
if (context.hld_profile)
{
if ((IsStyleElement() || IsLinkElement()) && GetCSS())
RemoveCSS(context);
#ifdef SVG_SUPPORT
else if (IsMatchingType(Markup::SVGE_FONT, NS_SVG) || IsMatchingType(Markup::SVGE_FONT_FACE, NS_SVG))
{
CSS_SvgFont* svg_font = static_cast<CSS_SvgFont*>(context.hld_profile->GetCSSCollection()->RemoveCollectionElement(this));
OP_DELETE(svg_font);
}
#endif // SVG_SUPPORT
else if (IsMatchingType(HE_META, NS_HTML))
CheckMetaElement(context, ParentActual(), FALSE);
}
}
// Must make sure that the formobject is removed because if the
// document is deleted it will keep a dangling pointer to it
if (IsFormElement())
DestroyFormObjectBackup();
#ifdef XML_EVENTS_SUPPORT
if (!doc || doc->HasXMLEvents())
{
// This attribute contains pointers to the document so it needs
// to be removed when the element is disconnected from the document
RemoveSpecialAttribute(ATTR_XML_EVENTS_REGISTRATION, SpecialNs::NS_LOGDOC);
}
#endif // XML_EVENTS_SUPPORT
if (Type() == HE_DOC_ROOT)
{
// Remove cached pointer to logdoc. It might disappear while we stay alive
RemoveSpecialAttribute(ATTR_LOGDOC, SpecialNs::NS_LOGDOC);
}
}
void HTML_Element::Free(const DocumentContext &context)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_FREE);
HTML_Element* c = FirstChild();
while (c)
{
HTML_Element *tmp_elm = c->Suc();
c->Out();
c->Free(context);
c = tmp_elm;
}
#ifdef DEBUG
// Only KeepAliveElementRefs should continue to reference an element which has been called Free() on
for (ElementRef* ref = m_first_ref; ref; ref = ref->NextRef())
OP_ASSERT(ref->IsA(ElementRef::KEEP_ALIVE));
#endif
if (!m_first_ref) // KeepAliveElementRef keeps the element alive as long as the ref exist
DELETE_HTML_Element(this);
}
BOOL HTML_Element::Clean(int *ptr)
{
OP_ASSERT(ptr == NULL);
return Clean(static_cast<FramesDocument *>(NULL));
}
void HTML_Element::Free(int *ptr)
{
OP_ASSERT(ptr == NULL);
Free(static_cast<FramesDocument *>(NULL));
}
OP_STATUS HTML_Element::DeepClone(HLDocProfile *hld_profile, HTML_Element *src_elm, BOOL force_html)
{
OP_ASSERT(src_elm->GetInserted() < HE_INSERTED_FIRST_HIDDEN_BY_ACTUAL || src_elm->GetInserted() == HE_INSERTED_BY_IME);
HTML_Element *child = src_elm->FirstChildActual();
while( child )
{
HTML_Element *new_elm = NEW_HTML_Element();
if( ! new_elm || new_elm->Construct(hld_profile, child, FALSE, force_html) == OpStatus::ERR_NO_MEMORY )
{
DELETE_HTML_Element(new_elm);
return OpStatus::ERR_NO_MEMORY;
}
if( new_elm->DeepClone(hld_profile, child, force_html) == OpStatus::ERR_NO_MEMORY )
{
new_elm->Free(hld_profile->GetFramesDocument());
return OpStatus::ERR_NO_MEMORY;
}
new_elm->SetInserted(HE_INSERTED_BY_DOM);
new_elm->SetEndTagFound(child->GetEndTagFound());
new_elm->Under(this);
child = child->SucActual();
}
return OpStatus::OK;
}
OP_STATUS
HTML_Element::AppendEntireContentAsString(TempBuffer *tmp_buf, BOOL text_only, BOOL include_this, BOOL is_xml/*=FALSE*/)
{
return HTML5Parser::SerializeTree(this, tmp_buf, HTML5Parser::SerializeTreeOptions().IsXml(is_xml).TextOnly(text_only).IncludeRoot(include_this));
}
void
HTML_Element::AppendEntireContentAsStringL(TempBuffer *tmp_buf, BOOL text_only, BOOL include_this, HTML_Element *root/*=NULL*/, BOOL is_xml/*=FALSE*/)
{
HTML5Parser::SerializeTreeL(this, tmp_buf, HTML5Parser::SerializeTreeOptions().IsXml(is_xml).TextOnly(text_only).IncludeRoot(include_this));
}
void HTML_Element::CleanReferences(FramesDocument *frm_doc)
{
OP_PROBE7(OP_PROBE_HTML_ELEMENT_CLEANREFS);
OP_ASSERT(IsReferenced()); // Expensive function, don't call if not needed
if (frm_doc)
frm_doc->CleanReferencesToElement(this);
SetReferenced(FALSE);
}
HTML_Element* HTML_Element::GetNamedElm(const uni_char* name)
{
if (!name)
return NULL;
const uni_char* element_name = NULL;
switch (Type())
{
case HE_A:
element_name = GetA_Name();
break;
case HE_MAP:
element_name = GetMAP_Name();
break;
default:
/* element_name = GetStringAttr(ATTR_NAME); */
break;
}
if (element_name && (uni_strcmp(element_name, name) == 0))
return this;
const uni_char* id = GetId();
if (id && (uni_strcmp(id, name) == 0))
return this;
// 05/11/97: changed search direction. This routine is used to find "map" with given name.
// Netscape always use the last of two with identical names.
for (HTML_Element* he = LastChildActual(); he; he = he->PredActual())
{
HTML_Element* a_elm = he->GetNamedElm(name);
if (a_elm)
return a_elm;
}
return NULL;
}
HTML_Element* HTML_Element::GetElmById(const uni_char* name)
{
HTML_Element* elm = this;
do
{
const uni_char* id = elm->GetId();
if (id && (uni_strcmp(id, name) == 0))
return elm;
elm = elm->NextActual();
} while (elm);
return NULL;
}
HTML_Element* HTML_Element::FindFirstContainedFormElm()
{
if( (Type() == HE_INPUT || Type() == HE_SELECT || Type() == HE_BUTTON || Type() == HE_ISINDEX || Type() == HE_TEXTAREA || Type() == HE_OPTGROUP) && g_ns_manager->GetNsTypeAt(GetNsIdx()) == NS_HTML)
return this;
for (HTML_Element* he = FirstChildActual(); he; he = he->SucActual())
{
HTML_Element* a_elm = he->FindFirstContainedFormElm();
if (a_elm)
return a_elm;
}
return NULL;
}
HTML_Element* HTML_Element::GetMAP_Elm(const uni_char* name)
{
if (Type() == HE_MAP)
{
const uni_char *elm_name = GetMAP_Name();
// changed to case insensitive because of bug 83236
if (elm_name && (uni_stricmp(elm_name, name) == 0))
return this;
const uni_char *id = GetId();
if (id && (uni_stricmp(id, name) == 0))
return this;
}
for (HTML_Element *he = FirstChildActual(); he; he = he->SucActual())
{
HTML_Element *map_elm = he->GetMAP_Elm(name);
if (map_elm)
return map_elm;
}
return NULL;
}
OP_STATUS HTML_Element::InitESObject(ES_Runtime* runtime, BOOL statically_allocated)
{
if (FramesDocument *frames_doc = runtime->GetFramesDocument())
if (DOM_Environment *environment = frames_doc->GetDOMEnvironment())
{
DOM_Object *node;
RETURN_IF_ERROR(environment->ConstructNode(node, this));
return OpStatus::OK;
}
return OpStatus::ERR;
}
const uni_char* HTML_Element::GetAnchor_HRef(FramesDocument *doc)
{
if (IsMatchingType(HE_A, NS_HTML))
return GetA_HRef(doc);
#ifdef _WML_SUPPORT_
if (doc && doc->GetDocManager()->WMLHasWML())
{
WML_Context* wc = doc->GetDocManager()->WMLGetContext();
if (wc)
{
URL ret_url = wc->GetWmlUrl(this);
return ret_url.IsEmpty() ? NULL : ret_url.GetAttribute(URL::KUniName).CStr();
}
}
#endif //_WML_SUPPORT_
#ifdef SVG_SUPPORT
if (IsMatchingType(Markup::SVGE_A, NS_SVG))
{
URL* url = g_svg_manager->GetXLinkURL(this, &doc->GetURL());
if (url)
{
return url->GetAttribute(URL::KUniName).CStr();
}
}
#endif // SVG_SUPPORT
if (URL *css_link = (URL*)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, (void*)NULL, SpecialNs::NS_LOGDOC))
if (css_link->Type() != URL_JAVASCRIPT)
return css_link->GetAttribute(URL::KUniName_Username_Password_Hidden).CStr();
return NULL;
}
const uni_char* HTML_Element::GetA_HRef(FramesDocument *doc, BOOL insert_password/*= FALSE*/)
{
if (Type() == HE_A)
{
#ifdef _WML_SUPPORT_
if (doc && doc->GetDocManager()->WMLHasWML())
{
WML_Context* wc = doc->GetDocManager()->WMLGetContext();
if (wc)
{
URL ret_url = wc->GetWmlUrl((HTML_Element*)this);
return ret_url.GetAttribute(insert_password ? URL::KUniName_Username_Password_NOT_FOR_UI : URL::KUniName).CStr();
}
}
#endif // _WML_SUPPORT_
return GetStringAttr(ATTR_HREF);
}
return NULL;
}
const char* HTML_Element::GetA_HRefWithRel(FramesDocument *doc)
{
if (Type() == HE_A)
{
#ifdef _WML_SUPPORT_
if (doc && doc->GetDocManager()->WMLHasWML())
{
WML_Context* wc = doc->GetDocManager()->WMLGetContext();
if (wc)
{
URL ret_url = wc->GetWmlUrl((HTML_Element*)this);
return ret_url.GetAttribute(URL::KName_With_Fragment, TRUE).CStr();
}
}
#endif // _WML_SUPPORT_
URL* url = GetUrlAttr(ATTR_HREF, NS_IDX_HTML, doc ? doc->GetLogicalDocument() : NULL);
if (url)
return url->GetAttribute(URL::KName_With_Fragment, TRUE).CStr();
}
return NULL;
}
const char* HTML_Element::GetA_HRefRel(LogicalDocument *logdoc/*=NULL*/)
{
if (Type() == HE_A)
{
URL* url = GetUrlAttr(ATTR_HREF, NS_IDX_HTML, logdoc);
if (url)
return url->RelName();
}
return 0;
}
URL HTML_Element::GetAnchor_URL(HTML_Document *doc)
{
OP_ASSERT(doc);
return GetAnchor_URL(doc->GetFramesDocument());
}
URL HTML_Element::GetAnchor_URL(FramesDocument *doc)
{
OP_ASSERT(doc);
#ifdef _WML_SUPPORT_
if (doc->GetDocManager()->WMLHasWML())
{
WML_Context* wc = doc->GetDocManager()->WMLGetContext();
if (wc)
{
URL ret_url = wc->GetWmlUrl(this);
if (!ret_url.IsEmpty())
return ret_url;
}
}
#endif //_WML_SUPPORT_
if (URL *css_link = (URL*)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, (void*)NULL, SpecialNs::NS_LOGDOC))
{
if (css_link->Type() != URL_JAVASCRIPT)
return *css_link;
}
else if (GetNsType() == NS_HTML &&
(Type() == HE_A || Type() == HE_LINK || Type() == HE_AREA))
{
URL* tmp_url = GetUrlAttr(ATTR_HREF, NS_IDX_HTML, doc->GetLogicalDocument());
if (tmp_url)
return *tmp_url;
}
#ifdef SVG_SUPPORT
else if (IsMatchingType(Markup::SVGE_A, NS_SVG))
{
URL root_url = doc->GetURL();
URL* retval = g_svg_manager->GetXLinkURL(this, &root_url);
if(retval)
return *retval;
}
#endif // SVG_SUPPORT
return URL();
}
OP_STATUS HTML_Element::GetAnchor_URL(FramesDocument *doc, OpString& url)
{
URL target = GetAnchor_URL(doc);
const uni_char* url_local = target.GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden).CStr();
if (!url_local)
url_local = UNI_L("");
return url.Set(url_local);
}
OP_STATUS HTML_Element::GetURLAndTitle(FramesDocument *doc, OpString& url, OpString& title)
{
RETURN_IF_ERROR(GetAnchor_URL(doc, url));
TempBuffer title_buffer;
const uni_char* title_local;
if (IsMatchingType(HE_AREA, NS_HTML))
{
RETURN_IF_ERROR(title_buffer.Append(GetStringAttr(ATTR_TITLE)));
title_local = title_buffer.GetStorage();
}
else
{
const uni_char* alt_text = NULL;
RETURN_IF_ERROR(GetInnerTextOrImgAlt(title_buffer, alt_text));
uni_char* ptr = title_buffer.GetStorage();
if (ptr)
while (uni_isspace(*ptr)) ++ptr;
if ((!ptr || uni_strlen(ptr) == 0) && alt_text)
title_local = alt_text;
else
title_local = ptr;
}
if (!title_local)
title_local = UNI_L("");
return title.Set(title_local);
}
CSSValue HTML_Element::GetListType() const
{
HTML_ElementType type = Type();
CSSValue ltype = (CSSValue)GetNumAttr(ATTR_TYPE, NS_IDX_HTML, LIST_TYPE_NULL);
switch (type)
{
case HE_LI:
return (ltype == LIST_TYPE_NULL) && (NULL != Parent()) ? (CSSValue)Parent()->GetListType() : ltype;
case HE_UL:
case HE_MENU:
return ltype == LIST_TYPE_NULL ? LIST_TYPE_DISC : ltype;
case HE_OL:
return ltype == LIST_TYPE_NULL ? LIST_TYPE_NUMBER : ltype;
}
return ltype;
}
int HTML_Element::GetEMBED_PrivateAttrs(uni_char** &argn, uni_char** &argv) const
{
argn = 0;
argv = 0;
PrivateAttrs* pa = (PrivateAttrs*)GetSpecialAttr(ATTR_PRIVATE, ITEM_TYPE_PRIVATE_ATTRS, (void*)0, SpecialNs::NS_LOGDOC);
if (pa)
{
argn = pa->GetNames();
argv = pa->GetValues();
return pa->GetLength();
}
return 0;
}
BOOL HTML_Element::GetMapUrl(VisualDevice* vd, int x, int y, const HTML_Element* img_element, URL* murl, LogicalDocument *logdoc/*=NULL*/)
{
//if (Type() == HE_AREA)
{
BOOL hit = FALSE;
int shape = GetAREA_Shape();
CoordsAttr* ca = (CoordsAttr*)GetAttr(ATTR_COORDS, ITEM_TYPE_COORDS_ATTR, (void*)0);
if (ca)
{
int coords_len = ca->GetLength();
int* coords = ca->GetCoords();
int width_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_WIDTH_SCALE, SpecialNs::NS_LAYOUT, 1000));
int height_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_HEIGHT_SCALE, SpecialNs::NS_LAYOUT, 1000));
POINT pt;
pt.x = x*1000/width_scale;
pt.y = y*1000/height_scale;
switch (shape)
{
case AREA_SHAPE_RECT:
if (coords_len >= 4)
{
int minx, maxx, miny, maxy;
if(coords[0] > coords[2])
{
minx = coords[2];
maxx = coords[0];
}
else
{
minx = coords[0];
maxx = coords[2];
}
if(coords[1] > coords[3])
{
miny = coords[3];
maxy = coords[1];
}
else
{
miny = coords[1];
maxy = coords[3];
}
hit = (pt.x >= minx &&
pt.x <= maxx &&
pt.y >= miny &&
pt.y <= maxy);
}
break;
case AREA_SHAPE_CIRCLE:
if (coords_len >= 3)
hit = vd->InEllipse(coords, pt.x, pt.y);
break;
case AREA_SHAPE_POLYGON:
if (coords_len >= 2)
hit = vd->InPolygon(coords, coords_len / 2, pt.x, pt.y);
break;
}
}
if (hit)
{
if (murl)
if (!GetAREA_NoHRef())
{
URL* url = NULL;
url = GetUrlAttr(ATTR_HREF, NS_IDX_HTML, logdoc);
if (url)
*murl = *url;
}
return TRUE;
}
}
return FALSE;
}
void HTML_Element::InvertRegionBorder(VisualDevice* vd, int xpos, int ypos, int width, int height, int bsize, RECT* region_rect, BOOL clear, HTML_Element* img_element)
{
int shape = GetAREA_Shape();
int coords_len = 0;
int* coords = NULL;
int tmpcoords[4];
xpos -= vd->GetRenderingViewX();
ypos -= vd->GetRenderingViewY();
if (shape == AREA_SHAPE_DEFAULT)
{
//default shape is 'rect', with the full image as coordinates.
coords_len = 4;
coords = tmpcoords;
coords[0] = 0;
coords[1] = 0;
coords[2] = width;
coords[3] = height;
shape = AREA_SHAPE_RECT;
}
else if (CoordsAttr* ca = (CoordsAttr*)GetAttr(ATTR_COORDS, ITEM_TYPE_COORDS_ATTR, (void*)0))
{
coords_len = ca->GetLength();
coords = ca->GetCoords();
}
if (coords_len)
{
int width_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_WIDTH_SCALE, SpecialNs::NS_LAYOUT, 1000));
int height_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_HEIGHT_SCALE, SpecialNs::NS_LAYOUT, 1000));
switch (shape)
{
case AREA_SHAPE_RECT:
if (coords_len >= 4)
{
int x, y, w, h;
x = xpos + MIN(coords[0]*width_scale/1000, width);
y = ypos + MIN(coords[1]*height_scale/1000, height);
w = MIN((coords[2] - coords[0])*width_scale/1000, MAX(width - coords[0]*width_scale/1000, 0));
h = MIN((coords[3] - coords[1])*height_scale/1000, MAX(height - coords[1]*height_scale/1000, 0));
if (region_rect)
{
region_rect->left = x;
region_rect->top = y;
region_rect->right = x + w;
region_rect->bottom = y + h;
}
else
{
OpRect drawRect(x, y, w, h);
vd->painter->InvertBorderRect(vd->OffsetToContainer(vd->ScaleToScreen(drawRect)), bsize);
}
}
break;
case AREA_SHAPE_CIRCLE:
if (coords_len >= 3)
{
int radius_scale = MIN(width_scale, height_scale);
int radius = coords[2]*radius_scale/1000;
if (region_rect)
{
region_rect->left = xpos + coords[0]*width_scale/1000 - radius + 1;
region_rect->top = ypos + coords[1]*height_scale/1000 - radius + 1;
region_rect->right = region_rect->left + 2*radius;
region_rect->bottom = region_rect->top + 2*radius;
}
else
{
OpRect drawRect(xpos + coords[0]*width_scale/1000 - radius + 1,
ypos + coords[1]*height_scale/1000 - radius + 1,
2*radius,
2*radius);
vd->painter->InvertBorderEllipse(vd->OffsetToContainer(vd->ScaleToScreen(drawRect)), bsize);
}
}
break;
case AREA_SHAPE_POLYGON:
if (coords_len >= 2)
{
if (region_rect)
{
int max_x = 0;
int max_y = 0;
int numpoints = coords_len / 2;
for (int i = 0; i < numpoints; i++)
{
max_x = MAX(max_x, coords[i * 2]*width_scale/1000);
max_y = MAX(max_y, coords[i * 2 + 1]*height_scale/1000);
}
region_rect->left = xpos;
region_rect->top = ypos;
region_rect->right = xpos + max_x;
region_rect->bottom = ypos + max_y;
}
else
{
int numpoints = coords_len / 2;
OpPoint* points = OP_NEWA(OpPoint, numpoints);
if (!points)
return; //FIXME:OOM7 - Can't propagate the OOM error
for(int i=0; i < numpoints; i++)
{
points[i].Set(xpos + coords[i*2]*width_scale/1000,
ypos + coords[i*2 + 1]*height_scale/1000);
points[i] = vd->OffsetToContainer(vd->ScaleToScreen(points[i]));
}
vd->painter->InvertBorderPolygon(points, numpoints, bsize);
OP_DELETEA(points);
}
}
break;
}
}
}
#ifdef SKINNABLE_AREA_ELEMENT
void HTML_Element::DrawRegionBorder(VisualDevice* vd, int xpos, int ypos, int width, int height, int bsize, RECT* region_rect, BOOL clear, HTML_Element* img_element)
{
int shape = GetAREA_Shape();
int coords_len = 0;
int* coords = NULL;
int tmpcoords[4];
xpos -= vd->GetRenderingViewX();
ypos -= vd->GetRenderingViewY();
if (shape == AREA_SHAPE_DEFAULT)
{
//default shape is 'rect', with the full image as coordinates.
coords_len = 4;
coords = tmpcoords;
coords[0] = 0;
coords[1] = 0;
coords[2] = width;
coords[3] = height;
shape = AREA_SHAPE_RECT;
}
else if (CoordsAttr* ca = (CoordsAttr*)GetAttr(ATTR_COORDS, ITEM_TYPE_COORDS_ATTR, (void*)0))
{
coords_len = ca->GetLength();
coords = ca->GetCoords();
}
if (coords_len)
{
int width_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_WIDTH_SCALE, 1000, SpecialNs::NS_LAYOUT));
int height_scale = static_cast<int>(img_element->GetSpecialNumAttr(Markup::LAYOUTA_IMAGEMAP_HEIGHT_SCALE, 1000, SpecialNs::NS_LAYOUT));
switch (shape)
{
case AREA_SHAPE_RECT:
if (coords_len >= 4)
{
int x, y, w, h;
x = xpos + MIN(coords[0]*width_scale/1000, width);
y = ypos + MIN(coords[1]*height_scale/1000, height);
w = MIN((coords[2] - coords[0])*width_scale/1000, MAX(width - coords[0]*width_scale/1000, 0));
h = MIN((coords[3] - coords[1])*height_scale/1000, MAX(height - coords[1]*height_scale/1000, 0));
if (region_rect)
{
region_rect->left = x;
region_rect->top = y;
region_rect->right = x + w;
region_rect->bottom = y + h;
}
else
{
OpRect drawRect(x, y, w, h);
OpSkinElement* skin_elm_area = g_skin_manager->GetSkinElement(UNI_L("Active Area Element"));
UINT32 outline_color = 0;
UINT32 outline_width = 2;
if (skin_elm_area)
{
skin_elm_area->GetOutlineColor(&outline_color, 0);
skin_elm_area->GetOutlineWidth(&outline_width, 0);
}
vd->painter->SetColor(outline_color);
vd->painter->DrawRect(vd->OffsetToContainer(vd->ScaleToScreen(drawRect)), outline_width);
}
}
break;
case AREA_SHAPE_CIRCLE:
if (coords_len >= 3)
{
int radius_scale = MIN(width_scale, height_scale);
int radius = coords[2]*radius_scale/1000;
if (region_rect)
{
region_rect->left = xpos + coords[0]*width_scale/1000 - radius + 1;
region_rect->top = ypos + coords[1]*height_scale/1000 - radius + 1;
region_rect->right = region_rect->left + 2*radius;
region_rect->bottom = region_rect->top + 2*radius;
}
else
{
OpRect drawRect(xpos + coords[0]*width_scale/1000 - radius + 1,
ypos + coords[1]*height_scale/1000 - radius + 1,
2*radius,
2*radius);
OpSkinElement* skin_elm_area = g_skin_manager->GetSkinElement(UNI_L("Active Area Element"));
UINT32 outline_color = 0;
UINT32 outline_width = 2;
if (skin_elm_area)
{
skin_elm_area->GetOutlineColor(&outline_color, 0);
skin_elm_area->GetOutlineWidth(&outline_width, 0);
}
vd->painter->SetColor(outline_color);
vd->painter->DrawEllipse(vd->OffsetToContainer(vd->ScaleToScreen(drawRect)), outline_width);
}
}
break;
case AREA_SHAPE_POLYGON:
if (coords_len >= 2)
{
if (region_rect)
{
int max_x = 0;
int max_y = 0;
int numpoints = coords_len / 2;
for (int i = 0; i < numpoints; i++)
{
max_x = MAX(max_x, coords[i * 2]*width_scale/1000);
max_y = MAX(max_y, coords[i * 2 + 1]*height_scale/1000);
}
region_rect->left = xpos;
region_rect->top = ypos;
region_rect->right = xpos + max_x;
region_rect->bottom = ypos + max_y;
}
else
{
int numpoints = coords_len / 2;
OpPoint* points = OP_NEWA(OpPoint, numpoints);
if (!points)
return; //FIXME:OOM7 - Can't propagate the OOM error
for(int i=0; i < numpoints; i++)
{
points[i].Set(xpos + coords[i*2]*width_scale/1000,
ypos + coords[i*2 + 1]*height_scale/1000);
points[i] = vd->OffsetToContainer(vd->ScaleToScreen(points[i]));
}
OpSkinElement* skin_elm_area = g_skin_manager->GetSkinElement(UNI_L("Active Area Element"));
UINT32 outline_color = 0;
UINT32 outline_width = 2;
if (skin_elm_area)
{
skin_elm_area->GetOutlineColor(&outline_color, 0);
skin_elm_area->GetOutlineWidth(&outline_width, 0);
}
vd->painter->SetColor(outline_color);
vd->painter->DrawPolygon(points, numpoints, outline_width);
OP_DELETEA(points);
}
}
break;
}
}
}
#endif //SKINNABLE_AREA_ELEMENT
URL* HTML_Element::GetEMBED_URL(LogicalDocument *logdoc/*=NULL*/)
{
if (Type() == HE_EMBED)
return GetUrlAttr(ATTR_SRC, NS_IDX_HTML, logdoc);
else
return NULL;
}
URL HTML_Element::GetImageURL(BOOL follow_redirect/*=TRUE*/, LogicalDocument *logdoc/*=NULL*/)
{
short attr = ATTR_NULL;
if (GetNsType() == NS_HTML)
{
HTML_ElementType type = Type();
switch (type)
{
case HE_IMG:
#ifdef PICTOGRAM_SUPPORT
{
URL *local_url = (URL*)GetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC);
if (local_url)
{
local_url->SetAttribute(URL::KIsGeneratedByOpera, TRUE);
return *local_url;
}
}
#endif // PICTOGRAM_SUPPORT
// fall through
case Markup::HTE_INPUT:
case Markup::HTE_EMBED:
attr = Markup::HA_SRC;
break;
#ifdef MEDIA_HTML_SUPPORT
case HE_VIDEO:
attr = ATTR_POSTER;
break;
#endif // MEDIA_HTML_SUPPORT
case HE_OBJECT:
{
#ifdef PICTOGRAM_SUPPORT
URL *local_url = (URL*)GetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC);
if (local_url)
{
local_url->SetAttribute(URL::KIsGeneratedByOpera, TRUE);
return *local_url;
}
#endif // PICTOGRAM_SUPPORT
#ifdef JS_PLUGIN_ATVEF_VISUAL
JS_Plugin_Object *obj_p = NULL;
OP_BOOLEAN is_jsplugin = IsJSPluginObject(logdoc->GetHLDocProfile(), &obj_p);
if (is_jsplugin == OpBoolean::IS_TRUE)
{
// Does this jsplugin want an ATVEF visual representation?
ES_Object *esobj = DOM_Utils::GetJSPluginObject(GetESElement());
if (obj_p->IsAtvefVisualPlugin() && esobj != NULL)
{
// Get the JS_Plugin_HTMLObjectElement_Object that correspond to
// the OBJECT tag. This is not the same as the obj_p we just
// retrieved...
EcmaScript_Object *ecmascriptobject =
ES_Runtime::GetHostObject(esobj);
OP_ASSERT(ecmascriptobject->IsA(ES_HOSTOBJECT_JSPLUGIN));
JS_Plugin_Object *jsobject =
static_cast<JS_Plugin_Object *>(ecmascriptobject);
// Check that we actually did request visualization when
// instantiating this object.
if (jsobject->IsAtvefVisualPlugin())
{
// Create an internal tv: URL so that we can set up a listener
// that can filter on this particular object only (this is done
// in GetResolvedObjectType()).
uni_char tv_url_string[sizeof (void *) * 2 + 9]; /* ARRAY OK 2010-01-18 peter */
uni_snprintf(tv_url_string, ARRAY_SIZE(tv_url_string), UNI_L("tv:///%p"),
reinterpret_cast<void *>(jsobject));
return g_url_api->GetURL(tv_url_string);
}
}
}
else if (OpStatus::IsMemoryError(is_jsplugin))
{
g_memory_manager->RaiseCondition(is_jsplugin);
return URL();
}
#endif
attr = ATTR_DATA;
}
break;
case HE_TABLE:
case HE_TD:
case HE_TH:
case HE_BODY:
attr = ATTR_BACKGROUND;
break;
default:
break;
}
}
if (attr == ATTR_NULL)
return URL();
else if (attr == ATTR_BACKGROUND)
{
StyleAttribute* style_attr = (StyleAttribute *)GetAttr(ATTR_BACKGROUND, ITEM_TYPE_COMPLEX, (void *)0);
if (style_attr && style_attr->GetProperties()->GetFirstDecl())
{
CSS_decl *bg_images_cp = style_attr->GetProperties()->GetFirstDecl();
OP_ASSERT(bg_images_cp->GenArrayValue() && bg_images_cp->ArrayValueLen() == 1);
const uni_char *url_str = bg_images_cp->GenArrayValue()[0].GetString();
return url_str ? g_url_api->GetURL(url_str) : URL();
}
else
return URL();
}
if (URL *tmp_url = GetUrlAttr(attr, NS_IDX_HTML, logdoc))
{
if (!follow_redirect)
return *tmp_url;
URL target_url = tmp_url->GetAttribute(URL::KMovedToURL, TRUE);
return !target_url.IsEmpty() ? target_url : *tmp_url;
}
return URL();
}
OP_STATUS HTML_Element::SetCSS_Style(CSS_property_list* prop_list)
{
StyleAttribute* style = OP_NEW(StyleAttribute, (NULL, prop_list));
if (!style)
{
return OpStatus::ERR_NO_MEMORY;
}
int res;
#ifdef SVG_SUPPORT
if(GetNsType() == NS_SVG)
{
res = SetAttr(Markup::SVGA_STYLE, ITEM_TYPE_COMPLEX, static_cast<void*>(style), TRUE, NS_IDX_SVG);
}
else
#endif // SVG_SUPPORT
{
res = SetAttr(ATTR_STYLE, ITEM_TYPE_COMPLEX, static_cast<void*>(style), TRUE);
}
if (res == -1)
{
prop_list->Ref(); // Take back the reference we gave to |style|
OP_DELETE(style);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
StyleAttribute*
HTML_Element::GetStyleAttribute()
{
# if defined(SVG_SUPPORT)
if (GetNsType() == NS_SVG)
return static_cast<StyleAttribute*>(GetAttr(Markup::SVGA_STYLE, ITEM_TYPE_COMPLEX, (void*)0, NS_IDX_SVG));
else
# endif // SVG_SUPPORT
return static_cast<StyleAttribute*>(GetAttr(ATTR_STYLE, ITEM_TYPE_COMPLEX, (void*)0));
}
CSS_property_list*
HTML_Element::GetCSS_Style()
{
StyleAttribute* style_attr = GetStyleAttribute();
return style_attr ? style_attr->GetProperties() : NULL;
}
OP_STATUS
HTML_Element::EnsureCSS_Style()
{
if (!GetCSS_Style())
{
CSS_property_list *prop_list = OP_NEW(CSS_property_list, ());
RETURN_OOM_IF_NULL(prop_list);
prop_list->Ref();
if (OpStatus::IsMemoryError(SetCSS_Style(prop_list)))
{
prop_list->Unref();
return OpStatus::ERR_NO_MEMORY;
}
}
return OpStatus::OK;
}
OP_STATUS
HTML_Element::SetStyleDecl(CSSProperty property, float value, CSSValueType val_type)
{
if (StyleAttribute *style_attr = GetStyleAttribute())
style_attr->SetIsModified();
RETURN_IF_ERROR(EnsureCSS_Style());
CSS_property_list *prop_list = GetCSS_Style();
CSS_number_decl *decl = OP_NEW(CSS_number_decl, (property, value, val_type));
RETURN_OOM_IF_NULL(decl);
prop_list->ReplaceDecl(decl, TRUE, CSS_decl::ORIGIN_AUTHOR);
return OpStatus::OK;
}
OP_STATUS
HTML_Element::ApplyStyle(HLDocProfile* hld_profile)
{
return hld_profile->GetLayoutWorkplace()->ApplyPropertyChanges(this, 0, FALSE, Markup::HA_STYLE);
}
const uni_char* HTML_Element::GetId() const
{
BOOL is_svg = (GetNsType() == NS_SVG);
const uni_char* id = NULL;
for (int index = 0, length = GetAttrSize(); index < length; ++index)
{
if (GetAttrIsId(index) && GetItemType(index) == ITEM_TYPE_STRING)
{
id = GetAttrValueString(index);
if(!is_svg || (is_svg && GetAttrNs(index) == NS_IDX_XML))
break;
}
}
return id;
}
OP_STATUS HTML_Element::SetText(const DocumentContext &context, const uni_char *txt, unsigned int txt_len,
HTML_Element::ValueModificationType modification_type /* = MODIFICATION_REPLACING_ALL */,
unsigned offset /* = 0 */, unsigned length1 /* = 0 */, unsigned length2 /* = 0 */)
{
FramesDocument *doc = context.frames_doc;
#if defined(DOCUMENT_EDIT_SUPPORT)
if(doc && doc->GetDocumentEdit())
doc->GetDocumentEdit()->OnTextChange(this);
#endif
if (doc)
doc->BeforeTextDataChange(this);
OP_STATUS status = SetTextInternal(doc, txt, txt_len);
if (OpStatus::IsError(status))
{
if (doc)
doc->AbortedTextDataChange(this);
return status;
}
if (doc && doc->GetDocRoot() && doc->GetDocRoot()->IsAncestorOf(this))
{
#ifdef DOCUMENT_EDIT_SUPPORT
if(doc->GetDocumentEdit())
doc->GetDocumentEdit()->OnTextChanged(this);
#endif
if (layout_box)
{
layout_box->RemoveCachedInfo();
#ifndef HAS_NOTEXTSELECTION
doc->RemoveLayoutCacheFromSelection(this);
#endif // !HAS_NOTEXTSELECTION
}
MarkDirty(doc);
DOM_Environment *environment = context.environment;
ES_Thread* thread = environment ? environment->GetCurrentScriptThread() : NULL;
if (HTML_Element *parent = ParentActual())
status = parent->HandleCharacterDataChange(doc, thread, TRUE);
}
if (doc)
doc->TextDataChange(this, modification_type, offset, length1, length2);
if (context.environment)
{
OP_STATUS status2 = context.environment->ElementCharacterDataChanged(this, modification_type, offset, length1, length2);
if (OpStatus::IsError(status2))
status = status2;
}
return status;
}
OP_STATUS
HTML_Element::SetTextOfNumerationListItemMarker(FramesDocument* doc, const uni_char *txt, unsigned int txt_len)
{
// Two asserts ensuring that this is a text element of a numeration list item marker.
OP_ASSERT(GetInserted() == HE_INSERTED_BY_LAYOUT);
OP_ASSERT(Parent() && Parent()->GetIsListMarkerPseudoElement());
RETURN_IF_ERROR(SetTextInternal(doc, txt, txt_len));
/* Numeration string length is currently strictly limited by the layout engine (a lot below 32k).
So any conversion to HE_TEXTGROUP cannot occur after setting the new text data. */
OP_ASSERT(Type() == HE_TEXT);
if (layout_box)
layout_box->RemoveCachedInfo();
return OpStatus::OK;
}
BOOL GetFramesetRowColSpecVal(const uni_char* spec, int i, int& val, int& type)
{
const uni_char* str = spec;
for (int j=i; j>0 && str; j--)
{
str = uni_strchr(str, ',');
if (str)
str++;
}
if (!str)
return FALSE;
while (*str && uni_isspace(*str))
str++;
if (*str == '*' || *str == ',')
{
// Empty values should be treated as 1*
val = 1;
type = FRAMESET_RELATIVE_SIZED;
return TRUE;
}
else if (uni_isdigit(*str))
{
val = uni_atoi(str);
while (uni_isdigit(*str))
str++;
if (*str == '.')
{
str++;
while (uni_isdigit(*str))
str++;
}
while (uni_isspace(*str))
str++;
if (*str == '*')
type = FRAMESET_RELATIVE_SIZED;
else if (*str == '%')
type = FRAMESET_PERCENTAGE_SIZED;
else
type = FRAMESET_ABSOLUTE_SIZED;
return TRUE;
}
else if (uni_strchr(str, ','))
{
// garbage, but not garbage at the end. Treat as 0
val = 0;
type = FRAMESET_ABSOLUTE_SIZED;
return TRUE;
}
else
return FALSE;
}
BOOL HTML_Element::GetFramesetRow(int i, int& val, int& tpe) const
{
if (Type() == HE_FRAMESET)
{
const uni_char* spec = GetStringAttr(ATTR_ROWS);
if (spec)
return GetFramesetRowColSpecVal(spec, i, val, tpe);
}
return FALSE;
}
BOOL HTML_Element::GetFramesetCol(int i, int& val, int& tpe) const
{
if (Type() == HE_FRAMESET)
{
const uni_char* spec = GetStringAttr(ATTR_COLS);
if (spec)
return GetFramesetRowColSpecVal(spec, i, val, tpe);
}
return FALSE;
}
int HTML_Element::GetFramesetRowCount() const
{
int rows = 0;
if (Type() == HE_FRAMESET)
{
int j, type;
for (;GetFramesetRow(rows, j, type);rows++){}
}
return rows;
}
int HTML_Element::GetFramesetColCount() const
{
int cols = 0;
if (Type() == HE_FRAMESET)
{
int j, type;
for (;GetFramesetCol(cols, j, type);cols++){}
}
return cols;
}
OP_STATUS HTML_Element::GetOptionText(TempBuffer *buffer)
{
OP_ASSERT(IsMatchingType(HE_OPTION, NS_HTML) || IsMatchingType(HE_OPTGROUP, NS_HTML));
int len = GetTextContentLength();
RETURN_IF_ERROR(buffer->Expand(len + 1));
uni_char *storage = buffer->GetStorage();
GetTextContent(storage, len + 1);
buffer->SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
uni_char *source = storage, *target = storage;
BOOL insert_space = FALSE;
while (*source)
{
if (uni_isspace(*source))
{
if (uni_isnbsp(*source))
*target++ = ' ';
else
insert_space = TRUE;
}
else
{
if (insert_space && target != storage)
*target++ = ' ';
*target++ = *source;
insert_space = FALSE;
}
++source;
}
*target = 0;
return OpStatus::OK;
}
BOOL HTML_Element::IsIncludedInSelect(HTML_Element* select)
{
OP_ASSERT(select && select->IsMatchingType(HE_SELECT, NS_HTML));
OP_ASSERT(select->IsAncestorOf(this));
if (!IsMatchingType(HE_OPTION, NS_HTML) && !IsMatchingType(HE_OPTGROUP, NS_HTML))
return FALSE;
HTML_Element* parent = Parent();
while (parent != select)
{
if (!parent->IsMatchingType(HE_OPTGROUP, NS_HTML))
return FALSE;
parent = parent->Parent();
}
return TRUE;
}
int HTML_Element::GetFormNr(FramesDocument* frames_doc /* = NULL */) const
{
if (Type() == HE_FORM)
return static_cast<int>(GetSpecialNumAttr(ATTR_JS_ELM_IDX, SpecialNs::NS_LOGDOC, -1));
else if (Type() == HE_ISINDEX || (Parent() && Parent()->Type() == HE_ISINDEX))
return 0; // quick hack to make ISINDEX work (this is no problem if the page is normal and only has one isindex and no other form elements)
else
{
// The form element may be disassociated with the form
const uni_char* form_specified = FormManager::GetFormIdString(const_cast<HTML_Element*>(this));
if (form_specified)
{
HTML_Element* form_elm = FormManager::FindElementFromIdString(frames_doc, const_cast<HTML_Element*>(this), form_specified);
if (form_elm)
return form_elm->GetFormNr();
return -1;
}
int formnr = static_cast<int>(GetSpecialNumAttr(ATTR_JS_FORM_IDX, SpecialNs::NS_LOGDOC, -1));
if (GetInserted() == HE_INSERTED_BY_DOM)
{
// Elements inserted by DOM don't know which form they belong to so we need to check.
formnr = -1;
HTML_Element* he = ParentActual();
while (he)
{
if (he->GetNsType() == NS_HTML && he->Type() == HE_FORM)
{
formnr = he->GetFormNr();
break;
}
he = he->ParentActual();
}
}
return formnr;
}
}
long HTML_Element::GetFormElmNr() const
{
int elm_nr = GetElmNr();
int form_nr = GetFormNr();
return MAKELONG((int)elm_nr, (int)form_nr);
}
int HTML_Element::GetSize() const
{
int size = (int)GetNumAttr(ATTR_SIZE);
if (Type() == HE_INPUT)
{
if (size <= 0)
{
switch (GetInputType())
{
case INPUT_TEL:
case INPUT_SEARCH:
case INPUT_URI:
case INPUT_EMAIL:
case INPUT_TEXT:
case INPUT_PASSWORD:
size = 20; //15;
break;
case INPUT_DATE:
size = 20; // XXX MAX_SIZE;
break;
case INPUT_WEEK:
size = 8;
break;
case INPUT_TIME:
size = 21;
break;
case INPUT_NUMBER:
case INPUT_RANGE:
size = 12;
break;
case INPUT_MONTH:
size = 5;
break;
case INPUT_DATETIME:
size = 50;
break;
case INPUT_DATETIME_LOCAL:
size = 48;
break;
case INPUT_COLOR:
size = 10;
break;
}
}
}
else if (Type() == HE_SELECT)
{
if (size < 1 && GetMultiple())
size = 4;
else
if (size < 1)
size = 1;
}
return size;
}
HTML_Element* HTML_Element::GetFirstElm(HTML_ElementType tpe, NS_Type ns/*=NS_HTML*/)
{
if (IsMatchingType(tpe, ns))
return this;
HTML_Element* the = 0;
HTML_Element* he = FirstChildActual();
while (he && !the)
{
the = he->GetFirstElm(tpe, ns);
he = he->SucActual();
}
return the;
}
int HTML_Element::GetElmNumber(HTML_Element* he, BOOL& found)
{
if (he == this)
{
found = TRUE;
return 1;
}
int count = 1;
HTML_Element* che = FirstChildActual();
found = FALSE;
while (che && !found)
{
count += che->GetElmNumber(he, found);
che = che->SucActual();
}
return count;
}
HTML_Element* HTML_Element::GetElmNumber(int elm_nr, int &i)
{
i++;
if (elm_nr == i)
return this;
HTML_Element* he = 0;
HTML_Element* che = FirstChildActual();
while (che && !he)
{
he = che->GetElmNumber(elm_nr, i);
che = che->SucActual();
}
return he;
}
BOOL HTML_Element::IsDisabled(FramesDocument* frames_doc)
{
// In WF2 fieldset may disable anything within it
return FormValidator::IsInheritedDisabled(this);
}
BOOL HTML_Element::HasContent()
{
HTML_ElementType type = Type();
if (type == HE_IMG || type == HE_HR || type == HE_INPUT || type == HE_SELECT ||
#if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_)
type == HE_KEYGEN ||
#endif
#ifdef _PLUGIN_SUPPORT_
type == HE_EMBED ||
#endif
type == HE_TEXTAREA)
return TRUE;
else if (type == HE_TEXT)
{
const uni_char* txt = LocalContent();
if (!txt)
return FALSE;
while (*txt && uni_isspace(*txt))
txt++;
return (*txt != '\0');
}
HTML_Element* he = FirstChild();
BOOL ret = FALSE;
while (he && !ret)
{
ret = he->HasContent();
he = he->Suc();
}
return ret;
}
BOOL HTML_Element::IsPartOf(HTML_ElementType tpe) const
{
HTML_Element* p = ParentActual();
while (p)
{
if (p->Type() == tpe)
return TRUE;
p = p->ParentActual();
}
return FALSE;
}
HTML_Element* HTML_Element::GetTitle()
{
if (IsMatchingType(HE_TITLE, NS_HTML))
return this;
#ifdef SVG_SUPPORT
else if(IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
HTML_Element* title = FirstChildActual();
while(title)
{
if(title->IsMatchingType(Markup::SVGE_TITLE, NS_SVG))
return title;
title = title->NextSiblingActual();
}
return 0;
}
#endif // SVG_SUPPORT
else
{
HTML_Element* elm = FirstChildActual();
HTML_Element* title;
while (elm)
{
title = elm->GetTitle();
if (title)
return title;
elm = elm->SucActual();
}
return 0;
}
}
const uni_char*
HTML_Element::GetCurrentLanguage()
{
const uni_char *ret_val;
if ((ret_val = GetStringAttr(XMLA_LANG, NS_IDX_XML)) != NULL)
return ret_val;
if ((ret_val = GetStringAttr(ATTR_LANG)) != NULL)
return ret_val;
if (Parent())
return Parent()->GetCurrentLanguage();
else
return NULL;
}
URL* HTML_Element::GetScriptURL(URL& root_url, LogicalDocument *logdoc/*=NULL*/)
{
URL *original_src_url = static_cast<URL*>(GetSpecialAttr(Markup::LOGA_ORIGINAL_SRC, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC));
if (original_src_url)
return original_src_url;
#ifdef SVG_DOM
if (IsMatchingType(Markup::SVGE_SCRIPT, NS_SVG))
return g_svg_manager->GetXLinkURL(this, &root_url);
#endif // SVG_DOM
return GetUrlAttr(ATTR_SRC, NS_IDX_HTML, logdoc);
}
OP_BOOLEAN HTML_Element::HandleScriptElement(HLDocProfile* hld_profile, ES_Thread *thread, BOOL register_first, BOOL is_inline_script, unsigned stream_position)
{
/* Script parsed in innerHTML/outerHTML. Will be handled when inserted into the
document instead. */
if (!hld_profile->GetHandleScript())
return OpBoolean::IS_FALSE;
URL* url = GetScriptURL(*hld_profile->GetURL(), hld_profile->GetLogicalDocument());
BOOL is_external = url && url->Type() != URL_NULL_TYPE;
// Don't execute completely empty scripts. They might execute later if the content is changed.
if (!is_external && !FirstChildActualStyle())
return OpBoolean::IS_FALSE;
#ifdef DELAYED_SCRIPT_EXECUTION
if (!hld_profile->ESDelayScripts())
#endif // DELAYED_SCRIPT_EXECUTION
{
RETURN_IF_ERROR(hld_profile->GetFramesDocument()->ConstructDOMEnvironment());
if (register_first)
RETURN_IF_ERROR(hld_profile->GetESLoadManager()->RegisterScript(this, is_external, is_inline_script, thread));
}
#ifdef DELAYED_SCRIPT_EXECUTION
if (hld_profile->ESDelayScripts() && !HasAttr(ATTR_DECLARE))
RETURN_IF_ERROR(hld_profile->ESAddScriptElement(this, stream_position, !is_external));
#endif // DELAYED_SCRIPT_EXECUTION
if (is_external)
{
int handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
if ((handled & SCRIPT_HANDLED_LOADED) == 0)
{
BOOL already_loaded = FALSE;
#ifdef DELAYED_SCRIPT_EXECUTION
OP_BOOLEAN result = FetchExternalScript(hld_profile, thread, &already_loaded, !hld_profile->ESIsExecutingDelayedScript() || !hld_profile->ESIsFirstDelayedScript(this));
if (hld_profile->ESDelayScripts())
if (result == OpBoolean::IS_TRUE)
{
if (already_loaded)
RETURN_IF_ERROR(hld_profile->ESSetScriptElementReady(this));
return OpBoolean::IS_FALSE;
}
else
{
OP_STATUS status = hld_profile->ESCancelScriptElement(this);
if (OpStatus::IsMemoryError(status))
return status;
}
#else // DELAYED_SCRIPT_EXECUTION
OP_BOOLEAN result = FetchExternalScript(hld_profile, thread, &already_loaded);
#endif // DELAYED_SCRIPT_EXECUTION
if (!already_loaded)
return result;
else if ((GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC) & SCRIPT_HANDLED_LOADED) == 0)
return LoadExternalScript(hld_profile);
else
return OpBoolean::IS_TRUE;
}
}
#ifdef DELAYED_SCRIPT_EXECUTION
if (hld_profile->ESDelayScripts())
return OpBoolean::IS_FALSE;
else
#endif // DELAYED_SCRIPT_EXECUTION
return LoadScript(hld_profile);
}
void HTML_Element::CancelScriptElement(HLDocProfile* hld_profile)
{
hld_profile->GetESLoadManager()->CancelInlineScript(this);
}
#if defined(USER_JAVASCRIPT) && defined(_PLUGIN_SUPPORT_)
OP_BOOLEAN HTML_Element::PluginInitializedElement(HLDocProfile* hld_profile)
{
OP_ASSERT(hld_profile->GetFramesDocument());
RETURN_IF_ERROR(hld_profile->GetFramesDocument()->ConstructDOMEnvironment());
return hld_profile->GetFramesDocument()->GetDOMEnvironment()->PluginInitializedElement(this);
}
#endif // USER_JAVASCRIPT && _PLUGIN_SUPPORT_
BOOL HTML_Element::IsScriptSupported(FramesDocument* frames_doc)
{
BOOL script_supported = frames_doc->GetDOMEnvironment()->IsEnabled();
if (script_supported)
{
const uni_char* type = NULL;
const uni_char* language = NULL;
#if defined(SVG_SUPPORT)
if(GetNsType() == NS_SVG)
{
type = GetStringAttr(Markup::SVGA_TYPE, NS_IDX_SVG);
if(!type)
{
type = GetStringAttrFromSVGRoot(this, Markup::SVGA_CONTENTSCRIPTTYPE);
}
}
else
#endif // SVG_SUPPORT
{
type = GetStringAttr(ATTR_TYPE);
language = GetStringAttr(ATTR_LANGUAGE);
}
script_supported = g_ecmaManager->IsScriptSupported(type, language);
}
return script_supported;
}
OP_BOOLEAN HTML_Element::LoadScript(HLDocProfile* hld_profile)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_LOADSCRIPT1);
FramesDocument* frames_doc = hld_profile->GetFramesDocument();
ES_LoadManager *load_manager = hld_profile->GetESLoadManager();
OP_STATUS status = frames_doc->ConstructDOMEnvironment();
if (OpStatus::IsError(status))
{
if (status == OpStatus::ERR)
OpStatus::Ignore(load_manager->CancelInlineScript(this));
return status;
}
BOOL script_supported = IsScriptSupported(frames_doc), script_skipped = FALSE;
/* <script declare="declare"> means that this script should only be executed
when activated by an event. */
if (HasAttr(ATTR_DECLARE))
script_skipped = TRUE;
#ifdef USER_JAVASCRIPT
if (script_supported && !script_skipped)
{
OP_BOOLEAN handled_by_userjs = frames_doc->GetDOMEnvironment()->HandleScriptElement(this, hld_profile->GetESLoadManager()->GetInterruptedThread(this));
if (handled_by_userjs != OpBoolean::IS_FALSE)
return handled_by_userjs;
}
#endif // USER_JAVASCRIPT
if (script_supported)
{
/* If the script tag comes from an innerHTML, outerHTML or insertAdjacentHTML,
it needs to be supported or there will be crashes if the script calls
document.write. It's unclear exactly when and how such scripts would be
executed anyway. */
if (!hld_profile->GetHandleScript())
script_supported = FALSE;
}
if (!script_supported)
{
hld_profile->ESSetScriptNotSupported(TRUE);
script_skipped = TRUE;
}
if (script_skipped)
{
RETURN_IF_ERROR(load_manager->CancelInlineScript(this));
return OpBoolean::IS_FALSE;
}
hld_profile->ESSetScriptNotSupported(FALSE);
ES_ProgramText *program_array = NULL;
int program_array_length = 0;
status = ConstructESProgramText(program_array, program_array_length, *hld_profile->GetURL(), hld_profile->GetLogicalDocument());
if (OpStatus::IsError(status))
{
OpStatus::Ignore(load_manager->CancelInlineScript(this));
if (OpStatus::IsMemoryError(status))
hld_profile->SetIsOutOfMemory(TRUE);
return status;
}
OP_BOOLEAN result;
long handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
if (program_array_length > 0)
{
result = load_manager->SetScript(this, program_array, program_array_length, (handled & SCRIPT_HANDLED_CROSS_ORIGIN) != 0);
if (result == OpBoolean::IS_TRUE)
{
handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
SetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, handled | SCRIPT_HANDLED_EXECUTED, SpecialNs::NS_LOGDOC);
}
else
OpStatus::Ignore(frames_doc->HandleEvent(ONLOAD, NULL, this, SHIFTKEY_NONE, 0, NULL));
}
else
{
OpStatus::Ignore(frames_doc->HandleEvent(ONLOAD, NULL, this, SHIFTKEY_NONE, 0, NULL));
OP_STATUS status = load_manager->CancelInlineScript(this);
if (OpStatus::IsSuccess(status))
result = OpBoolean::IS_FALSE;
else
result = status;
}
OP_DELETEA(program_array);
return result;
}
OP_BOOLEAN
HTML_Element::FetchExternalScript(HLDocProfile* hld_profile, ES_Thread *thread, BOOL *already_loaded, BOOL load_inline)
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
#ifdef USER_JAVASCRIPT
#ifdef DELAYED_SCRIPT_EXECUTION
if (!hld_profile->ESDelayScripts())
#endif // DELAYED_SCRIPT_EXECUTION
{
OP_STATUS status = frames_doc->ConstructDOMEnvironment();
RETURN_IF_MEMORY_ERROR(status);
if (OpStatus::IsError(status))
{
hld_profile->GetESLoadManager()->CancelInlineScript(this);
return status;
}
OP_BOOLEAN handled_by_userjs = frames_doc->GetDOMEnvironment()->HandleExternalScriptElement(this, hld_profile->GetESLoadManager()->GetInterruptedThread(this));
if (handled_by_userjs != OpBoolean::IS_FALSE)
return handled_by_userjs;
}
#endif // USER_JAVASCRIPT
#ifdef LOGDOC_GETSCRIPTLIST
RETURN_IF_ERROR(hld_profile->AddScript(this));
#endif // LOGDOC_GETSCRIPTLIST
URL* url = GetScriptURL(*hld_profile->GetURL(), hld_profile->GetLogicalDocument());
OP_ASSERT(url && url->Type() != URL_NULL_TYPE);
OP_LOAD_INLINE_STATUS load_stat;
if (load_inline)
{
LoadInlineOptions options;
if (frames_doc->GetDocManager()->MustReloadScripts()
#ifdef DELAYED_SCRIPT_EXECUTION
/* With DSE we may get here twice: the first time when parsing ahead and
the second when executing the script. Force reload only for the first case
otherwise we'll get NSL.
*/
&& !hld_profile->ESIsExecutingDelayedScript()
#endif // DELAYED_SCRIPT_EXECUTION
)
options.ReloadConditionally();
load_stat = frames_doc->LoadInline(url, this, SCRIPT_INLINE, options);
}
else
load_stat = LoadInlineStatus::USE_LOADED;
if (load_stat == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
if (HasAttr(ATTR_DECLARE))
// The script should not be executed during loading.
return OpBoolean::IS_FALSE;
else if ((load_stat == LoadInlineStatus::LOADING_CANCELLED || load_stat == LoadInlineStatus::USE_LOADED) && url->Status(TRUE) == URL_LOADED)
{
if (already_loaded)
{
*already_loaded = TRUE;
return OpBoolean::IS_TRUE;
}
else if ((GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC) & SCRIPT_HANDLED_LOADED) == 0)
return LoadExternalScript(hld_profile);
else
return OpBoolean::IS_TRUE;
}
else if (load_stat == LoadInlineStatus::LOADING_REFUSED || load_stat == LoadInlineStatus::LOADING_CANCELLED)
{
#ifdef OPERA_CONSOLE
RETURN_IF_MEMORY_ERROR(LogicalDocument::PostConsoleMsg(url,
Str::S_ES_LOADING_LINKED_SCRIPT_FAILED,
OpConsoleEngine::EcmaScript, OpConsoleEngine::Error, GetLogicalDocument()));
#endif // OPERA_CONSOLE
// The script will not be loaded, for whatever reason, so continue parsing.
hld_profile->GetESLoadManager()->CancelInlineScript(this);
return OpBoolean::IS_FALSE;
}
else if (!load_inline)
{
// We expected the inline to be loaded already; if it wasn't, we
// can't block here.
hld_profile->GetESLoadManager()->CancelInlineScript(this);
return OpBoolean::IS_FALSE;
}
else
// Default: block parsing progress waiting for the script to load.
return OpBoolean::IS_TRUE;
}
OP_BOOLEAN
HTML_Element::LoadExternalScript(HLDocProfile* hld_profile)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_LOADEXTERNALSCRIPT1);
FramesDocument* frames_doc = hld_profile->GetFramesDocument();
LogicalDocument *logdoc = hld_profile->GetLogicalDocument();
RETURN_IF_ERROR(frames_doc->ConstructDOMEnvironment());
if (!frames_doc->GetDOMEnvironment()->IsEnabled())
{
RETURN_IF_ERROR(hld_profile->GetESLoadManager()->CancelInlineScript(this));
return OpBoolean::IS_FALSE;
}
URL* url = GetScriptURL(*hld_profile->GetURL(), logdoc);
#ifdef _DEBUG
OP_NEW_DBG("LoadExternalScript", "html5");
if (Debug::DoDebugging("html5"))
{
OpString dbg_url_str;
url->GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI, dbg_url_str, TRUE);
OP_DBG((UNI_L("Loaded external (%s)"), dbg_url_str.CStr()));
}
#endif // _DEBUG
DataSrc *src_head = GetDataSrc();
OP_BOOLEAN result = OpBoolean::IS_FALSE; OpStatus::Ignore(result);
HEListElm* helm = GetHEListElmForInline(SCRIPT_INLINE);
if (helm)
helm->SetHandled();
URL target_url = url->GetAttribute(URL::KMovedToURL, TRUE);
if (target_url.IsEmpty())
target_url = *url;
OP_MEMORY_VAR uint32 http_response = HTTP_OK;
if (target_url.Type() == URL_HTTP || target_url.Type() == URL_HTTPS)
http_response = target_url.GetAttribute(URL::KHTTP_Response_Code, TRUE);
src_head->DeleteAll();
#ifdef CORS_SUPPORT
if (HasAttr(Markup::HA_CROSSORIGIN))
{
if (!helm->IsCrossOriginAllowed())
{
hld_profile->GetESLoadManager()->ReportScriptError(this, UNI_L("Error loading script."));
CancelScriptElement(hld_profile);
#ifdef DELAYED_SCRIPT_EXECUTION
hld_profile->ESCancelScriptElement(this);
#endif // DELAYED_SCRIPT_EXECUTION
SendEvent(ONERROR, frames_doc);
return result;
}
else
{
long handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
SetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, handled | SCRIPT_HANDLED_CROSS_ORIGIN, SpecialNs::NS_LOGDOC);
}
}
#endif // CORS_SUPPORT
BOOL is_cancelled = FALSE;
if (http_response == HTTP_OK || http_response == HTTP_NOT_MODIFIED)
{
URL_DataDescriptor* url_data_desc;
unsigned short int parent_charset_id = helm ? GetSuggestedCharsetId(this, hld_profile, helm->GetLoadInlineElm()) : 0;
g_charsetManager->IncrementCharsetIDReference(parent_charset_id);
if (helm && OpStatus::IsSuccess(result = helm->CreateURLDataDescriptor(url_data_desc, NULL, URL::KFollowRedirect, FALSE, TRUE, frames_doc->GetWindow(), URL_X_JAVASCRIPT, 0, FALSE, parent_charset_id)))
{
BOOL more = TRUE;
unsigned long data_size;
while (more)
{
#ifdef OOM_SAFE_API
TRAP(result, data_size = url_data_desc->RetrieveDataL(more));
if (OpStatus::IsError(result))
break;
#else // OOM_SAFE_API
data_size = url_data_desc->RetrieveData(more);
#endif // OOM_SAFE_API
uni_char* data_buf = (uni_char *) url_data_desc->GetBuffer();
if (!data_buf || !data_size)
break;
if (OpStatus::IsError(result = src_head->AddSrc(data_buf, UNICODE_DOWNSIZE(data_size), *url)))
break;
url_data_desc->ConsumeData(data_size);
}
OP_DELETE(url_data_desc);
}
else
{
CancelScriptElement(hld_profile);
#ifdef DELAYED_SCRIPT_EXECUTION
hld_profile->ESCancelScriptElement(this);
#endif // DELAYED_SCRIPT_EXECUTION
is_cancelled = TRUE;
}
g_charsetManager->DecrementCharsetIDReference(parent_charset_id);
}
else if (http_response >= 400)
{
hld_profile->GetESLoadManager()->CancelInlineScript(this);
#ifdef DELAYED_SCRIPT_EXECUTION
hld_profile->ESCancelScriptElement(this);
#endif // DELAYED_SCRIPT_EXECUTION
is_cancelled = TRUE;
/* Note: load error not reported at the toplevel error handler, but to the
console only. Do not want to expose that result beyond the script element's
onerror handler, but as a compatibility note, Gecko always reports it. */
#ifdef OPERA_CONSOLE
RETURN_IF_MEMORY_ERROR(LogicalDocument::PostConsoleMsg(url,
Str::S_ES_LOADING_LINKED_SCRIPT_FAILED,
OpConsoleEngine::EcmaScript, OpConsoleEngine::Error, GetLogicalDocument()));
#endif // OPERA_CONSOLE
/* To prevent duplicate error events, report 'error' via the inline's element, if possible. */
if (helm)
helm->SendOnError();
else
SendEvent(ONERROR, frames_doc);
}
long handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
SetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, handled | SCRIPT_HANDLED_LOADED, SpecialNs::NS_LOGDOC);
if (!OpStatus::IsMemoryError(result) && http_response < 400)
{
BOOL parser_blocking = !is_cancelled && logdoc->GetParser();
if (logdoc->IsXml())
parser_blocking = FALSE;
if (parser_blocking)
{
result = logdoc->GetParser()->GetTreeBuilder()->ExternalScriptReady(this);
}
if (!OpStatus::IsMemoryError(result))
result = HandleScriptElement(hld_profile);
}
if (OpStatus::IsMemoryError(result))
{
hld_profile->SetIsOutOfMemory(TRUE);
src_head->DeleteAll();
}
return result;
}
OP_STATUS
HTML_Element::ConstructESProgramText(ES_ProgramText *&program_array, int &program_array_length, URL& root_url, LogicalDocument *logdoc/*=NULL*/)
{
BOOL is_external = FALSE;
if (URL* url = GetScriptURL(root_url, logdoc))
if (!url->IsEmpty())
is_external = TRUE;
if (is_external)
{
DataSrc* src_head = GetDataSrc();
program_array_length = src_head->GetDataSrcElmCount();
if (program_array_length > 0)
{
program_array = OP_NEWA(ES_ProgramText, program_array_length);
if (program_array)
{
ES_ProgramText *program_array_ptr = program_array;
DataSrcElm *src_elm = src_head->First();
while (src_elm)
{
program_array_ptr->program_text = src_elm->GetSrc();
program_array_ptr->program_text_length = src_elm->GetSrcLen();
++program_array_ptr;
src_elm = src_elm->Suc();
}
}
else
return OpStatus::ERR_NO_MEMORY;
}
}
else
{
HTML_Element *elm;
program_array = 0;
program_array_length = 0;
elm = (HTML_Element *) NextActual();
while (elm && IsAncestorOf(elm))
{
if (elm->Type() == HE_TEXT && elm->LocalContent())
++program_array_length;
elm = (HTML_Element *) elm->NextActual();
}
if (program_array_length)
{
ES_ProgramText *program_array_ptr = program_array = OP_NEWA(ES_ProgramText, program_array_length); // FIXME:REPORT_MEMMAN-KILSMO
if (!program_array)
return OpStatus::ERR_NO_MEMORY;
elm = (HTML_Element *) NextActual();
while (elm && IsAncestorOf(elm))
{
if (elm->Type() == HE_TEXT && elm->LocalContent())
{
program_array_ptr->program_text = elm->LocalContent();
program_array_ptr->program_text_length = elm->LocalContentLength();
++program_array_ptr;
}
elm = (HTML_Element *) elm->NextActual();
}
}
}
/* Strip trailing HTML comment stuff (-->).
A comment end is stripped by shortening the script text. It is stripped
back to the first line break unless it's commented out by a '//' or '<--', in
which case nothing is changed and we let the ecmascript engine ignore it
the ordinary way. */
if (program_array_length > 0)
{
int text_length = program_array[program_array_length - 1].program_text_length;
const uni_char* last = program_array[program_array_length - 1].program_text + text_length - 1;
while (text_length > 0 && uni_isspace(*last))
--last, --text_length;
if (text_length >= 3 && uni_strni_eq(last - 2, "-->", 3))
{
last -= 3;
text_length -= 3;
// Look for a // or <!-- on the line to see if this is already commented out
// the ordinary way. Else strip it completely
while (TRUE)
{
if (text_length == 0 || *last == '\n' || *last == '\r')
{
// Strip the line (MSIE compatibility, WebKit and Mozilla doesn't do this)
program_array[program_array_length - 1].program_text_length = text_length;
break;
}
if ((text_length >= 2 && last[0] == '/' && last[-1] == '/') ||
(text_length >= 4 && last[0] == '-' && last[-1] == '-' && last[-2] == '!' && last[-3] == '<'))
{
// the end comment is already commented out so don't strip the line
break;
}
--last, --text_length;
}
}
}
return OpStatus::OK;
}
void HTML_Element::CleanupScriptSource()
{
if (DataSrc* src = GetDataSrc())
src->DeleteAll();
}
void HTML_Element::StealScriptSource(DataSrc* other)
{
if (DataSrc* src = GetDataSrc())
src->MoveTo(other);
}
OP_STATUS HTML_Element::SetEventHandler(FramesDocument *frames_doc, DOM_EventType event, const uni_char *value, int value_length)
{
RETURN_IF_ERROR(frames_doc->ConstructDOMEnvironment());
DOM_Environment *environment = frames_doc->GetDOMEnvironment();
if (environment && environment->IsEnabled())
{
if (!exo_object)
{
/* Calling ConstructNode when there is already a node is typically
safe, but this function is typically indirectly called from
ConstructNode itself, and there is an OP_ASSERT there that gets
confused if we it gets called recursively like that. */
DOM_Object *node;
RETURN_IF_ERROR(environment->ConstructNode(node, this));
}
OP_STATUS status = environment->SetEventHandler(exo_object, event, value, value_length);
return status;
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::ClearEventHandler(DOM_Environment *environment, DOM_EventType event)
{
OP_ASSERT(environment);
if (exo_object)
{
if (environment->IsEnabled())
{
return environment->ClearEventHandler(exo_object, event);
}
}
return OpStatus::OK;
}
OP_STATUS
HTML_Element::EnableEventHandlers(FramesDocument *doc)
{
return OpStatus::OK;
}
BOOL
HTML_Element::HasEventHandler(FramesDocument *frames_doc, DOM_EventType event, HTML_Element* referencing_elm, HTML_Element** handling_elm, ES_EventPhase phase)
{
if (frames_doc)
{
if (!GetESElement() && HasEventHandlerAttribute(frames_doc, event))
{
if (handling_elm)
*handling_elm = this;
return TRUE;
}
if (DOM_Environment *dom_environment = frames_doc->GetDOMEnvironment())
return dom_environment->HasEventHandler(this, event, handling_elm);
else if (Parent()) // Assume that the event will bubble so ask parent
return Parent()->HasEventHandler(frames_doc, event, referencing_elm, handling_elm, phase);
}
return FALSE;
}
#ifdef _WML_SUPPORT_
void
DoWmlSelection(HTML_Element *select_elm, HTML_Element *option_elm, FramesDocument *frames_doc, BOOL user_initiated)
{
if (!select_elm)
{
if (option_elm)
{
select_elm = option_elm->Parent();
while (select_elm)
{
if (select_elm->IsMatchingType(HE_SELECT, NS_HTML))
break;
select_elm = select_elm->Parent();
}
}
if (!select_elm)
return;
}
// Need to update the WML Variables.
WML_Context *wc = frames_doc->GetDocManager()->WMLGetContext();
wc->UpdateWmlSelection(select_elm, FALSE);
FormValueList* form_value_list = FormValueList::GetAs(select_elm->GetFormValue());
if (HTML_Element* option_he = form_value_list->GetFirstSelectedOption(select_elm))
{
// checks if we should navigate somewhere
BOOL noop = TRUE;
WMLNewTaskElm *tmp_task = wc->GetTaskByElement(option_he);
if (tmp_task && wc->PerformTask(tmp_task, noop, user_initiated, WEVT_ONPICK) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
#endif // _WML_SUPPORT_
/**
* Some elements expect focus and blur elements when interacted with.
* This identifies those and returns that element, or NULL
* if there is no such element involved.
*/
static HTML_Element* GetFocusBlurElement(FramesDocument* frames_doc, HTML_Element* elm)
{
HTML_Element* focusable_element = elm;
// Using the same definition of focusable as the script method HTMLElement::focus and the
// CSS pseudo class :focused (or is it :focus ?)
while (focusable_element && !focusable_element->IsFocusable(frames_doc))
{
focusable_element = focusable_element->Parent();
}
return focusable_element;
}
void
HTML_Element::GetCaretCoordinate(FramesDocument* frames_doc, int& caret_doc_x, int& caret_doc_y,
int& caret_offset_x, int& caret_offset_y)
{
BOOL found_doc_coords = FALSE;
#ifdef DOCUMENT_EDIT_SUPPORT
if (OpDocumentEdit *de = frames_doc->GetDocumentEdit())
{
if (de->GetEditableContainer(this))
{
OpPoint doc_caret_point = frames_doc->GetCaretPainter()->GetCaretPosInDocument();
caret_doc_x = doc_caret_point.x;
caret_doc_y = doc_caret_point.y;
found_doc_coords = TRUE;
}
}
#endif // DOCUMENT_EDIT_SUPPORT
if (!found_doc_coords)
{
if (FormObject* form_obj = GetFormObject())
{
if (!form_obj->GetCaretPosInDocument(&caret_doc_x, &caret_doc_y))
{
// Not the caret, but closer than (0,0)
AffinePos doc_pos;
form_obj->GetPosInDocument(&doc_pos);
OpPoint doc_pt = doc_pos.GetTranslation();
caret_doc_x = doc_pt.x;
caret_doc_y = doc_pt.y;
}
found_doc_coords = TRUE;
}
}
RECT rect;
BOOL status = frames_doc->GetLogicalDocument()->GetBoxRect(this, BOUNDING_BOX, rect);
if (status)
{
if (!found_doc_coords)
{
// In the middle of the box for no specific reason except symmetry.
caret_doc_x = (rect.left + rect.right) / 2;
caret_doc_y = (rect.top + rect.bottom) / 2;
}
caret_offset_x = caret_doc_x - rect.left;
caret_offset_y = caret_doc_y - rect.top;
}
else
{
if (!found_doc_coords)
{
// So, no idea where we are. Upper left corner will have to do
caret_doc_x = 0;
caret_doc_y = 0;
}
caret_offset_x = 0;
caret_offset_y = 0;
}
}
#ifndef NO_SAVE_SUPPORT
/**
* Trigger "Save image as" depending on modifiers.
*
* Ctrl+Alt+Click on img should result in triggering action. As legacy
* feature, we also support Ctrl+Click on <img> that is not an anchor.
*
* SVG inside <img> and <object> is also supported.
*
* @param modifiers key modifiers pressed
* @param frames_doc FramesDocument to which this event was dispatched
* @param target HTML_Element which received the event
*
* @returns TRUE if download was triggered
* FALSE if there was nothing saved
*/
static BOOL HandleSaveImage(ShiftKeyState modifiers, FramesDocument *frames_doc, HTML_Element *target)
{
# ifdef _KIOSK_MANAGER_
if (KioskManager::GetInstance()->GetNoSave())
return FALSE;
# endif
OP_ASSERT(frames_doc);
OP_ASSERT(target);
# ifdef SVG_SUPPORT
# define IS_MATCHING_SVG_ELEMENT target->IsMatchingType(Markup::SVGE_SVG, NS_SVG)
# else
# define IS_MATCHING_SVG_ELEMENT FALSE
#endif // SVG_SUPPORT
OP_ASSERT(target->IsMatchingType(HE_IMG, NS_HTML) ||
target->IsMatchingType(HE_EMBED, NS_HTML) ||
target->IsMatchingType(HE_OBJECT, NS_HTML) ||
target->IsMatchingType(HE_APPLET, NS_HTML) ||
IS_MATCHING_SVG_ELEMENT);
#undef IS_MATCHING_SVG_ELEMENT
if (!(modifiers & SHIFTKEY_CTRL))
return FALSE;
URL image_url;
# ifdef SVG_SUPPORT
if (target->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
// SVG inside iframe ?
if (frames_doc->GetParentDoc() &&
target->ParentActual()->Type() == HE_DOC_ROOT)
{
image_url = frames_doc->GetURL();
}
else
return FALSE;
}
else
# endif // SVG_SUPPORT
{
// If <img> is wrapped by link, expect also alt modifier.
HTML_Element *parent = target;
while ((parent = parent->ParentActual()) != NULL)
if (parent->IsAnchorElement(frames_doc))
{
if (!(modifiers & SHIFTKEY_ALT))
return FALSE;
break;
}
image_url = target->GetImageURL(TRUE, frames_doc->GetLogicalDocument());
HEListElm *hle = target->GetHEListElm(FALSE);
BOOL is_valid_image = (hle && !hle->GetImage().IsFailed()) ||
# ifdef SVG_SUPPORT
(!image_url.IsEmpty() && image_url.ContentType() == URL_SVG_CONTENT) ||
# endif
(!image_url.IsEmpty() && image_url.GetAttribute(URL::KIsImage, TRUE));
if (!is_valid_image)
return FALSE;
}
WindowCommander *wic = frames_doc->GetWindow()->GetWindowCommander();
# ifdef WIC_USE_DOWNLOAD_CALLBACK
ViewActionFlag view_action_flag;
view_action_flag.Set(ViewActionFlag::SAVE_AS);
TransferManagerDownloadCallback *download_callback = OP_NEW(TransferManagerDownloadCallback, (frames_doc->GetDocManager(), image_url, NULL, view_action_flag));
if (download_callback)
{
wic->GetDocumentListener()->OnDownloadRequest(wic, download_callback);
download_callback->Execute();
}
else
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
# else
OpString str_image_url, suggested_name;
OpString8 mime_type;
OP_STATUS status;
TRAP(status, image_url.GetAttributeL(URL::KSuggestedFileName_L, suggested_name));
if (OpStatus::IsSuccess(status) &&
OpStatus::IsSuccess(status = image_url.GetAttribute(URL::KUniName, str_image_url)) &&
OpStatus::IsSuccess(status = image_url.GetAttribute(URL::KHTTP_ContentType, mime_type)))
{
wic->GetDocumentListener()->OnDownloadRequest(wic, str_image_url.CStr(), suggested_name.CStr(), mime_type.CStr(), image_url.GetContentSize(), OpDocumentListener::SAVE, NULL);
}
else if (OpStatus::IsMemoryError(status))
frames_doc->GetWindow()->RaiseCondition(status);
# endif // WIC_USE_DOWNLOAD_CALLBACK
return TRUE;
}
#endif // NO_SAVE_SUPPORT
BOOL
HTML_Element::IsWidgetWithCaret()
{
if (IsMatchingType(Markup::HTE_INPUT, NS_HTML))
{
InputType input_type = GetInputType();
return input_type == INPUT_TEXT ||
#ifdef WEBFORMS2_SUPPORT
input_type == INPUT_NUMBER || input_type == INPUT_URI ||
input_type == INPUT_TEL || input_type == INPUT_EMAIL ||
input_type == INPUT_SEARCH || input_type == INPUT_TIME ||
#endif // WEBFORMS2_SUPPORT
input_type == INPUT_PASSWORD;
}
return IsMatchingType(Markup::HTE_TEXTAREA, NS_HTML);
}
#ifdef DRAG_SUPPORT
static BOOL IsDateTimeWidget(HTML_Element* elm)
{
if (elm->IsMatchingType(Markup::HTE_INPUT, NS_HTML))
{
InputType input_type = elm->GetInputType();
return input_type == INPUT_DATETIME || input_type == INPUT_DATETIME_LOCAL;
}
return FALSE;
}
BOOL
HTML_Element::IsWidgetWithDraggableSelection()
{
BOOL is_widget_with_caret = IsWidgetWithCaret();
BOOL is_passwd_widget = (IsMatchingType(Markup::HTE_INPUT, NS_HTML) &&
GetInputType() == INPUT_PASSWORD);
return (is_widget_with_caret || IsDateTimeWidget(this)) && !is_passwd_widget;
}
BOOL
HTML_Element::IsWidgetAcceptingDrop()
{
return IsWidgetWithCaret() || IsDateTimeWidget(this);
}
#endif // DRAG_SUPPORT
#if defined MEDIA_SUPPORT || defined MEDIA_HTML_SUPPORT
/**
* Handles several events on a Media element.
* @returns TRUE if the event produced side effects and therefore should be considered handled.
*/
static BOOL HandleMediaElementEvent(DOM_EventType event, FramesDocument* frames_doc,HTML_Element *current_target, const HTML_Element::HandleEventOptions& options)
{
switch(event)
{
case ONMOUSEDOWN:
case ONMOUSEUP:
case ONMOUSEOVER:
case ONMOUSEMOVE:
case ONMOUSEOUT:
{
switch(current_target->Type())
{
#ifdef MEDIA_SUPPORT
case HE_EMBED:
case HE_OBJECT:
case HE_APPLET:
{
if (Media* media = current_target->GetMedia())
media->OnMouseEvent(event, EXTRACT_MOUSE_BUTTON(options.sequence_count_and_button_or_key_or_delta), options.offset_x, options.offset_y);
break;
}
#endif // MEDIA_SUPPORT
#ifdef MEDIA_HTML_SUPPORT
case HE_VIDEO:
case HE_AUDIO:
{
if (MediaElement* media_element = current_target->GetMediaElement())
media_element->OnMouseEvent(event, EXTRACT_MOUSE_BUTTON(options.sequence_count_and_button_or_key_or_delta), options.offset_x, options.offset_y);
break;
}
#endif // MEDIA_HTML_SUPPORT
}
break;
}
#ifdef DOM_FULLSCREEN_MODE
case ONDBLCLICK:
if (options.cancelled || current_target->Type() != HE_VIDEO)
break;
// Fancy: make double click switch between fullscreen and non-fullscreen just like media players.
if (frames_doc->GetFullscreenElement() == current_target)
{
frames_doc->DOMExitFullscreen(NULL);
return TRUE;
}
else if (frames_doc->GetFullscreenElement() == NULL)
return OpStatus::IsSuccess(frames_doc->DOMRequestFullscreen(current_target, NULL, TRUE));
break;
#endif //DOM_FULLSCREEN_MODE
}
return FALSE;
}
#endif // defined MEDIA_SUPPORT || defined MEDIA_HTML_SUPPORT
BOOL
HTML_Element::HandleEvent(DOM_EventType event, FramesDocument* frames_doc, HTML_Element* target,
const HandleEventOptions& options, HTML_Element* imagemap /* = NULL */, HTML_Element** event_bubbling_path /* = NULL */, int event_bubbling_path_len /* = -1 */)
{
HTML_Element* related_target = options.related_target;
int offset_x = options.offset_x;
int offset_y = options.offset_y;
int document_x = options.document_x;
int document_y = options.document_y;
int sequence_count_and_button_or_key_or_delta = options.sequence_count_and_button_or_key_or_delta;
ShiftKeyState modifiers = options.modifiers;
BOOL cancelled = options.cancelled;
BOOL synthetic = options.synthetic;
ES_Thread* thread = options.thread;
#ifdef TOUCH_EVENTS_SUPPORT
int radius = options.radius;
# ifdef DOC_RETURN_TOUCH_EVENT_TO_SENDER
void* user_data = options.user_data;
# endif // DOC_RETURN_TOUCH_EVENT_TO_SENDER
#endif // TOUCH_EVENTS_SUPPORT
unsigned int id = options.id;
if (!frames_doc->GetHLDocProfile())
{
// This happens when an event is delayed for script processing
// and the document is removed in the meantime. When the
// script is removed, it will send the events that should have
// been sent earlier.
return FALSE;
}
#ifdef DRAG_SUPPORT
if ((event == ONDRAGSTART || event == ONDRAG || event == ONDRAGENTER || event == ONDRAGOVER ||
event == ONDRAGLEAVE || event == ONDROP || event == ONDRAGEND) && !g_drag_manager->IsDragging())
{
// This happens when an event thread is blocked by e.g. an alert
// and d'n'd has to be finished in a meanwhile.
return FALSE;
}
#endif // DRAG_SUPPORT
if (synthetic &&
(event == ONKEYDOWN || event == ONKEYUP || event == ONKEYPRESS ||
event == ONMOUSEDOWN || event == ONMOUSEUP || event == ONMOUSEMOVE ||
event == ONDBLCLICK ||
event == ONMOUSEOVER || event == ONMOUSEOUT ||
event == ONMOUSEENTER || event == ONMOUSELEAVE ||
event == ONMOUSEWHEELH || event == ONMOUSEWHEELV ||
#ifdef TOUCH_EVENTS_SUPPORT
event == TOUCHSTART || event == TOUCHMOVE || event == TOUCHEND || event == TOUCHCANCEL ||
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
event == ONDRAGSTART || event == ONDRAG || event == ONDRAGENTER || event == ONDRAGOVER ||
event == ONDRAGLEAVE || event == ONDROP || event == ONDRAGEND ||
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
event == ONCOPY || event == ONCUT || event == ONPASTE ||
#endif // USE_OP_CLIPBOARD
event == ONCONTEXTMENU))
{
return FALSE;
}
BOOL handled = FALSE;
if (target == this)
{
#ifdef DRAG_SUPPORT
/* Let the drag manager know about mouse down/up because
cancelling ONMOUSEDOWN must prevent the drag from starting. */
if (event == ONMOUSEDOWN)
g_drag_manager->OnMouseDownDefaultAction(frames_doc, target, cancelled);
#endif // DRAG_SUPPORT
frames_doc->HandleEventFinished(event, target);
/* We may want to ignore 'cancelled'. */
if (event == ONKEYDOWN || event == ONKEYUP || event == ONKEYPRESS)
{
OpKey::Code key = static_cast<OpKey::Code>(sequence_count_and_button_or_key_or_delta);
#ifdef OP_KEY_CONTEXT_MENU_ENABLED
// Generate a context menu if the user pressed the context menu
// key regardless of if scripts tried to concel the key event
// or not.
if (event == ONKEYPRESS && key == OP_KEY_CONTEXT_MENU)
{
int caret_doc_x;
int caret_doc_y;
int caret_offset_x;
int caret_offset_y;
GetCaretCoordinate(frames_doc, caret_doc_x, caret_doc_y, caret_offset_x, caret_offset_y);
frames_doc->HandleMouseEvent(ONCONTEXTMENU,
related_target, target, imagemap,
caret_offset_x, caret_offset_y,
caret_doc_x, caret_doc_y,
modifiers,
sequence_count_and_button_or_key_or_delta,
NULL, FALSE, FALSE,
NULL, NULL,
TRUE);
return TRUE;
}
#endif // OP_KEY_CONTEXT_MENU_ENABLED
// Reset the "block keypress event" flag if keypress/keyup is handled.
if ((event == ONKEYPRESS || event == ONKEYUP) && frames_doc->GetWindow()->HasRecentlyCancelledKeyDown(key))
frames_doc->GetWindow()->SetRecentlyCancelledKeyDown(OP_KEY_INVALID);
if (!cancelled)
{
if (event == ONKEYDOWN || event == ONKEYUP || event == ONKEYPRESS)
{
// While scripts handled the key events, the keyboard focus might have moved
// so we have to be careful sending the events to the right receiver.
// This is both a security issue (redirecting key events to file input fields)
// and a correctness issue (having enter ending up in a wand
// dialog, closing it; see bug 278731)
OpInputContext* document_context = frames_doc->GetVisualDevice();
OpInputContext* current_context = g_input_manager->GetKeyboardInputContext();
if (!current_context)
return FALSE; // The focused element has disappeared so let us ignore the event.
if (current_context != document_context &&
!current_context->IsChildInputContextOf(document_context))
{
// Focus seemed to have moved far away, just ignore the event (not optimal)
return FALSE;
}
const uni_char *key_value = reinterpret_cast<const uni_char *>(reinterpret_cast<INTPTR>(options.user_data));
switch (event)
{
case ONKEYDOWN:
g_input_manager->InvokeKeyDown(key, key_value, options.key_event_data, modifiers, FALSE, OpKey::LOCATION_STANDARD, FALSE);
return TRUE;
case ONKEYUP:
g_input_manager->InvokeKeyUp(key, key_value, options.key_event_data, modifiers, FALSE, OpKey::LOCATION_STANDARD, FALSE);
return TRUE;
case ONKEYPRESS:
g_input_manager->InvokeKeyPressed(key, key_value, modifiers, FALSE, FALSE);
return TRUE;
default:
break;
}
}
}
}
#ifndef MOUSELESS
if (!cancelled && (event == ONMOUSEWHEELH || event == ONMOUSEWHEELV))
{
BOOL vertical = event == ONMOUSEWHEELV;
int& delta = sequence_count_and_button_or_key_or_delta;
// The scroll command should go to the scrollable
// thing that is under the mouse cursor
OpInputContext* target_input_context = frames_doc->GetVisualDevice();
// Se if we have a scrollable container as parent of the inner_box
HTML_Element* h_elm = this;
BOOL invoke_action = TRUE;
while(h_elm && invoke_action)
{
if (h_elm->GetLayoutBox())
{
FormObject *form_object = h_elm->GetFormObject();
if( form_object )
{
// Scrollable forms should stop bubbling the wheel up in the hierarchy, even if it didn't scroll now (might have hit the bottom/top).
if (form_object->OnMouseWheel(OpPoint(document_x, document_y), delta, vertical))
invoke_action = FALSE;
}
if (ScrollableArea* sc = h_elm->GetLayoutBox()->GetScrollable())
{
target_input_context = sc;
break;
}
}
h_elm = h_elm->ParentActual();
}
if (invoke_action)
{
g_input_manager->InvokeAction(delta < 0 ?
(vertical ? OpInputAction::ACTION_SCROLL_UP : OpInputAction::ACTION_SCROLL_LEFT) :
(vertical ? OpInputAction::ACTION_SCROLL_DOWN : OpInputAction::ACTION_SCROLL_RIGHT),
op_abs(delta), 0, target_input_context, NULL, TRUE, OpInputAction::METHOD_MOUSE);
}
}
#endif // MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
if (event == TOUCHSTART || event == TOUCHMOVE || event == TOUCHEND || event == TOUCHCANCEL)
{
#ifdef DOC_TOUCH_SMARTPHONE_COMPATIBILITY
// CORE-37279: Safari/iPhone ignores preventdefault on text area and text input elements.
if (FormManager::IsFormElement(this) && GetFormValue()->IsUserEditableText(this))
cancelled = FALSE;
#endif // DOC_TOUCH_SMARTPHONE_COMPATIBILITY
BOOL primary_touch = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta) == 0;
BOOL mouse_simulation_handled = false;
BOOL want_click = EXTRACT_CLICK_INDICATOR(sequence_count_and_button_or_key_or_delta);
#ifdef DOC_RETURN_TOUCH_EVENT_TO_SENDER
mouse_simulation_handled = frames_doc->SignalTouchEventProcessed(user_data, cancelled);
#endif // DOC_RETURN_TOUCH_EVENT_TO_SENDER
if (want_click && !cancelled && primary_touch && !mouse_simulation_handled && frames_doc->GetHtmlDocument())
SimulateMouse(frames_doc->GetHtmlDocument(), event, document_x, document_y, radius, modifiers);
}
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DOCUMENT_EDIT_SUPPORT
if (frames_doc->GetDocumentEdit())
{
OpDocumentEdit *doc_edit = frames_doc->GetDocumentEdit();
if(event == ONMOUSEDOWN && doc_edit->m_layout_modifier.IsLayoutModifiable(this))
{
doc_edit->HandleMouseEvent(this, event, document_x, document_y, EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta));
}
}
#endif // DOCUMENT_EDIT_SUPPORT
}
#ifdef DOCUMENT_EDIT_SUPPORT
BOOL target_at_layout_modifier = frames_doc->GetDocumentEdit() && frames_doc->GetDocumentEdit()->m_layout_modifier.m_helm == target;
if(target_at_layout_modifier
#ifdef DRAG_SUPPORT
&& event != ONDRAGSTART && event != ONDRAG && event != ONDRAGENTER && event != ONDRAGOVER && event != ONDROP
#endif // DRAG_SUPPORT
)
cancelled = TRUE;
#endif // DOCUMENT_EDIT_SUPPORT
BOOL shift_pressed = (modifiers & SHIFTKEY_SHIFT) == SHIFTKEY_SHIFT;
BOOL control_pressed = (modifiers & SHIFTKEY_CTRL) == SHIFTKEY_CTRL;
BOOL is_link = FALSE;
NS_Type ns = GetNsType();
#define MOUSEOVERURL_THREAD , thread
#define HANDLEEVENT_THREAD , thread
#ifdef ON_DEMAND_PLUGIN
// Allow enabling of on-demand plugins even if event is cancelled
if (!synthetic && layout_box && GetNsType() == NS_HTML
&& (Type() == HE_OBJECT || Type() == HE_EMBED || Type() == HE_APPLET)
&& IsPluginPlaceholder() && !GetNS4Plugin())
{
static_cast<PluginPlaceholderContent*>(layout_box->GetContent())->HandleMouseEvent(frames_doc, event);
}
#endif // ON_DEMAND_PLUGIN
/* It would be possible to do more sophisticated things with the 'cancelled'
and 'synthetic' flags. Synthetic events might be a security risk. */
switch (event)
{
case ONMOUSEDOWN:
break;
case ONMOUSEUP:
/* Our only default action is to arm an element (mousedown) or fire a
click event (mouseup on the active element). MSIE does nothing
special when mousedown/mouseup is cancelled, so if we do, click will
not work on some pages that mindlessly cancel all mousedown/mouseup
events. */
if (target == this && !synthetic)
{
switch(EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta))
{
#ifndef HAS_NOTEXTSELECTION
case MOUSE_BUTTON_1: // left mouse button
// Move the end point of the selection here, cancelled events should end the
// selection anyway, but synthetic events shouldn't.
{
#ifdef DRAG_SUPPORT
BOOL is_selecting = frames_doc->GetSelectingText();
#endif // DRAG_SUPPORT
frames_doc->EndSelectionIfSelecting(document_x, document_y);
#ifdef DRAG_SUPPORT
// Don't clear the selection if we're clicking on something
// that are likely to start a script (either via a javascript
// url or via an event listener) that might ask for current
// selection.
HTML_Element* hovered = this;
while (hovered && hovered->IsText())
{
hovered = hovered->ParentActual();
}
BOOL may_clear = !hovered ||
!(hovered->Type() == Markup::HTE_A || hovered->Type() == Markup::HTE_IMG ||
FormManager::IsButton(hovered) ||
hovered->Type() == Markup::HTE_INPUT && hovered->GetInputType() == INPUT_IMAGE);
int sequence_count = EXTRACT_SEQUENCE_COUNT(sequence_count_and_button_or_key_or_delta);
HTML_Document* html_doc = frames_doc->GetHtmlDocument();
if (may_clear && html_doc && html_doc->HasSelectedText() && this == frames_doc->GetActiveHTMLElement() &&
frames_doc->GetMouseUpMayBeClick() && !frames_doc->GetWasSelectingText() &&
sequence_count == 1 && !shift_pressed && !is_selecting)
frames_doc->ClearDocumentSelection(FALSE, TRUE);
#endif // DRAG_SUPPORT
}
break;
#endif // HAS_NOTEXTSELECTION
case MOUSE_BUTTON_2: // right mouse button
{
BOOL might_be_interpreted_as_click = EXTRACT_CLICK_INDICATOR(sequence_count_and_button_or_key_or_delta);
if (might_be_interpreted_as_click)
{
if (frames_doc->HandleMouseEvent(ONCONTEXTMENU,
related_target, target, imagemap,
offset_x, offset_y,
document_x, document_y,
modifiers,
sequence_count_and_button_or_key_or_delta) == OpStatus::ERR_NO_MEMORY)
{
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
break;
}
default:
break;
}
}
break;
case ONCLICK:
if (IsMatchingType(HE_INPUT, NS_HTML))
{
FormValue* value = GetFormValue();
if (value->GetType() == FormValue::VALUE_RADIOCHECK)
{
FormValueRadioCheck* radiocheck = FormValueRadioCheck::GetAs(value);
BOOL is_changed = radiocheck->RestoreStateAfterOnClick(this, cancelled);
if (is_changed)
{
OP_ASSERT(!cancelled);
OP_STATUS status = FormValueListener::HandleValueChanged(frames_doc, this, TRUE, !synthetic, thread);
if (OpStatus::IsMemoryError(status))
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
FormObject *form_object = GetFormObject();
if (form_object && form_object->GetInputType() == INPUT_FILE && !cancelled)
if ((thread && thread->IsUserRequested() && !thread->HasOpenedFileUploadDialog()) ||
(!thread && !synthetic))
{
static_cast<FileUploadObject*>(form_object)->Click(thread);
if (thread)
thread->SetHasOpenedFileUploadDialog();
}
}
if (cancelled)
goto replay_mouse_actions;
break;
/* HandleOnDrag*() functions below take care of everything what is needed to be done on a drag'n'drop event e.g.
the cursor change or moving the the next event (replaying next event). This is why we may return right after calling them. */
#ifdef DRAG_SUPPORT
case ONDRAGSTART:
g_drag_manager->HandleOnDragStartEvent(cancelled);
return TRUE;
case ONDRAGOVER:
g_drag_manager->HandleOnDragOverEvent(frames_doc->GetHtmlDocument(), document_x, document_y, offset_x, offset_y, cancelled);
return TRUE;
case ONDRAGENTER:
g_drag_manager->HandleOnDragEnterEvent(this, frames_doc->GetHtmlDocument(), document_x, document_y, offset_x, offset_y, modifiers, cancelled);
return TRUE;
case ONDRAG:
g_drag_manager->HandleOnDragEvent(frames_doc->GetHtmlDocument(), document_x, document_y, offset_x, offset_y, modifiers, cancelled);
return TRUE;
case ONDROP:
g_drag_manager->HandleOnDropEvent(frames_doc->GetHtmlDocument(), document_x, document_y, offset_x, offset_y, modifiers, cancelled);
return TRUE;
case ONDRAGLEAVE:
g_drag_manager->HandleOnDragLeaveEvent(this, frames_doc->GetHtmlDocument());
return TRUE;
case ONDRAGEND:
g_drag_manager->HandleOnDragEndEvent(frames_doc->GetHtmlDocument());
return TRUE;
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
case ONCUT:
case ONCOPY:
case ONPASTE:
g_clipboard_manager->HandleClipboardEventDefaultAction(event, cancelled, id);
return TRUE;
#endif // USE_OP_CLIPBOARD
default:
if (cancelled)
goto replay_mouse_actions;
}
if (event == ONMOUSEOVER || event == ONCLICK || event == ONMOUSEMOVE)
{
URL* url = (URL *)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, (void*)NULL, SpecialNs::NS_LOGDOC);
if (url && url->Type() != URL_JAVASCRIPT)
{
if (frames_doc->MouseOverURL(*url, NULL, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
is_link = TRUE;
goto cursor_check;
}
}
#ifndef MOUSELESS
else if (event == ONMOUSEUP)
{
HTML_Document* html_doc = frames_doc->GetHtmlDocument();
FormObject* form_object = GetFormObject();
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
UINT8 nclicks = EXTRACT_SEQUENCE_COUNT(sequence_count_and_button_or_key_or_delta);
if (html_doc->GetCapturedWidgetElement())
{
if (form_object)
{
// This will position cursors and activate checkboxes and radio buttons.
form_object->OnMouseUp(OpPoint(document_x, document_y), button, nclicks);
}
html_doc->SetCapturedWidgetElement(NULL);
}
if (g_widget_globals->captured_widget)
{
OP_ASSERT(button == current_mouse_button);
AffinePos widget_pos = g_widget_globals->captured_widget->GetPosInDocument();
OpPoint point(document_x, document_y);
widget_pos.ApplyInverse(point);
g_widget_globals->captured_widget->GenerateOnMouseUp(point, button, nclicks);
}
}
#endif // MOUSELESS
if (GetIsPseudoElement())
{
if (Parent())
handled = Parent()->HandleEvent(event, frames_doc, target, options, imagemap, event_bubbling_path, event_bubbling_path_len);
goto cursor_check;
}
if (target == this)
{
BOOL is_capturing_element = FALSE;
#ifdef SVG_SUPPORT
BOOL is_svg_element = FALSE;
#endif // SVG_SUPPORT
HTML_Element *form_element = this;
/* Check if this element or any of its ancestors is a form
element. The only relevant descendant of a form element is
OPTION and OPTGROUP. */
while (form_element)
{
#ifdef SVG_SUPPORT
if (form_element->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
// SVG rootcontainers are OpInputContexts, the focus has already been set on it
is_svg_element = TRUE;
break;
}
else
#endif // SVG_SUPPORT
if (form_element->GetFormObject() &&
(form_element->GetNsType() == NS_HTML &&
(form_element->Type() == HE_INPUT ||
form_element->Type() == HE_TEXTAREA ||
form_element->Type() == HE_SELECT
#ifdef _SSL_SUPPORT_
|| form_element->Type() == HE_KEYGEN
#endif
)))
{
is_capturing_element = TRUE;
break;
}
else
form_element = form_element->Parent();
}
if (event == ONMOUSEDOWN)
{
HTML_Document *html_document = frames_doc->GetHtmlDocument();
if (!cancelled)
{
BOOL set_focus_on_visdev = !is_capturing_element
#ifdef SVG_SUPPORT
&& !is_svg_element
#endif // SVG_SUPPORT
#ifdef _PLUGIN_SUPPORT_
&& GetNS4Plugin() == 0
#endif // _PLUGIN_SUPPORT_
;
if (!target->IsMatchingType(HE_BUTTON, NS_HTML))
frames_doc->GetVisualDevice()->SetDrawFocusRect(FALSE);
BOOL is_editable_root = FALSE;
#ifdef DOCUMENT_EDIT_SUPPORT
if (frames_doc->GetDocumentEdit() && frames_doc->GetDocumentEdit()->GetEditableContainer(target))
is_editable_root = TRUE;
#endif // DOCUMENT_EDIT_SUPPORT
if (target->IsMatchingType(HE_BUTTON, NS_HTML) && !target->IsDisabled(frames_doc) && !target->GetUnselectable() && !is_editable_root)
{
if (html_document && frames_doc->GetDocRoot()->IsAncestorOf(target))
html_document->FocusElement(target, HTML_Document::FOCUS_ORIGIN_MOUSE, FALSE);
}
else if (is_capturing_element && !is_editable_root)
{
// These handle their own focus
}
else if (target->IsMatchingType(HE_OPTION, NS_HTML) && !is_editable_root)
{
// HE_OPTION mousedowns are generated by the form code and we must not interfere with dropdown focus
}
else
{
// Set the real inputmanager focus to the body, but also send a
// fake focus event to certain elements that expect such and
// record them in HTML_Document as the focused element. This
// includes HE_A, HE_AREA and HE_IMG.
HTML_Element* focus_blur_element = GetFocusBlurElement(frames_doc, this);
if (html_document && html_document->GetFocusedElement() != focus_blur_element)
{
html_document->SetFocusedElement(focus_blur_element, FALSE);
if (focus_blur_element)
{
frames_doc->HandleEvent(ONFOCUS,
html_document->GetHoverReferencingHTMLElement(),
focus_blur_element,
modifiers);
}
}
FOCUS_REASON focus_reason = synthetic ? FOCUS_REASON_OTHER : FOCUS_REASON_MOUSE;
#ifdef DOCUMENT_EDIT_SUPPORT
HTML_Element* docedit_elm_to_focus = NULL;
if (OpDocumentEdit* docedit = frames_doc->GetDocumentEdit())
{
if (docedit->GetEditableContainer(target))
docedit_elm_to_focus = target;
else if (LogicalDocument* logdoc = frames_doc->GetLogicalDocument())
{
// Let clicks outside the <body> also focus <body> if <body> is editable since
// anything else would be confusing for the user.
HTML_Element* body = logdoc->GetBodyElm();
if (body && target->IsAncestorOf(body) && docedit->GetEditableContainer(body))
docedit_elm_to_focus = body;
}
}
if (docedit_elm_to_focus)
frames_doc->GetDocumentEdit()->FocusEditableRoot(docedit_elm_to_focus, focus_reason);
else
#endif // DOCUMENT_EDIT_SUPPORT
if (set_focus_on_visdev)
{
if (OpInputContext* input_context = Content::FindInputContext(target))
input_context->SetFocus(focus_reason);
else
frames_doc->GetVisualDevice()->SetFocus(focus_reason);
}
}
// Remove the default-look from the defaultbutton.
FormObject::ResetDefaultButton(frames_doc);
} // !cancelled
if (is_capturing_element)
{
FormObject* form_object = form_element->GetFormObject();
// The mouse down event used to be sent from the
// widget to the HE_OPTION for listboxes and
// this was to prevent infinite event loops. Now
// that only happens for listboxes inside dropdowns
// where the mouse event never went through
// the document initially.
if (!(form_element->IsMatchingType(HE_SELECT, NS_HTML) &&
form_object &&
!static_cast<SelectionObject*>(form_object)->IsListbox() &&
target->IsMatchingType(HE_OPTION, NS_HTML)))
{
html_document->SetCapturedWidgetElement(form_element);
#ifndef MOUSELESS
unsigned sequence_count = EXTRACT_SEQUENCE_COUNT(sequence_count_and_button_or_key_or_delta);
OP_ASSERT(sequence_count >= 1);
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
form_object->OnMouseDown(OpPoint(document_x, document_y), button, sequence_count, cancelled);
#endif // !MOUSELESS
}
}
}
else if (event == ONCONTEXTMENU)
frames_doc->InitiateContextMenu(this, offset_x, offset_y, document_x, document_y, options.has_keyboard_origin);
if (layout_box)
layout_box->HandleEvent(frames_doc, event, offset_x, offset_y);
}
if (ns == NS_HTML)
{
HTML_ElementType type = Type();
switch (type)
{
#ifdef _PLUGIN_SUPPORT_
case HE_EMBED:
case HE_OBJECT:
case HE_APPLET:
{
OpNS4Plugin* plugin = GetNS4Plugin();
if (!plugin)
{
// No plug-in object; divert to layout module for handling of alternate content.
if (layout_box && layout_box->IsContentEmbed())
((EmbedContent*) layout_box->GetContent())->HandleMouseEvent(frames_doc->GetWindow(), event);
#ifdef MEDIA_SUPPORT
handled = HandleMediaElementEvent(event, frames_doc, this, options);
if (handled)
goto cursor_check;
#endif //MEDIA_SUPPORT
#ifndef NO_SAVE_SUPPORT
if (!cancelled && event == ONCLICK)
{
handled = HandleSaveImage(modifiers, frames_doc, this);
if (handled)
goto cursor_check;
}
#endif // NO_SAVE_SUPPORT
break;
}
# ifdef _WINDOWLESS_PLUGIN_SUPPORT_
VisualDevice* vd = frames_doc->GetVisualDevice();
if (plugin->IsWindowless())
{
// The coordinate for handleevent should be in raw pixels relative to the OpView.
OpPoint point(document_x - vd->GetRenderingViewX(), document_y - vd->GetRenderingViewY());
point = vd->ScaleToScreen(point);
int button_or_key_or_delta = sequence_count_and_button_or_key_or_delta;
if (event == ONMOUSEUP || event == ONMOUSEDOWN || event == ONCLICK || event == ONDBLCLICK)
{
button_or_key_or_delta = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
}
plugin->HandleEvent(event, point, button_or_key_or_delta, modifiers);
/* Document might be collapsing under our feet if it was deleted before
event returned from plugin (when context menu blocked it for example).
We will try to escape immediately to prevent further code from running. */
if (frames_doc->IsBeingDeleted())
return TRUE;
}
#ifdef VEGA_OPPAINTER_SUPPORT
if (vd->GetOpView())
((MDE_OpView*)vd->GetOpView())->GetMDEWidget()->m_screen->ReleaseMouseCapture();
#endif // VEGA_OPPAINTER_SUPPORT
# endif // _WINDOWLESS_PLUGIN_SUPPORT_
break;
}
#endif // _PLUGIN_SUPPORT_
case HE_AREA:
switch (event)
{
case ONMOUSEOVER:
case ONMOUSEMOVE:
case ONCLICK:
{
/* Pretty ugly hack to not load a new page if the current document
has been replaced using document.write. (jl@opera.com) */
if (event == ONCLICK && frames_doc->GetESScheduler() && !frames_doc->GetESScheduler()->TestTerminatingAction(ES_OpenURLAction::FINAL, ES_OpenURLAction::CONDITIONAL))
goto cursor_check;
URL* url = GetAREA_URL(frames_doc->GetLogicalDocument());
if (!url)
break;
else
{
const uni_char* win_name = GetAREA_Target();
if (!win_name || !*win_name)
win_name = GetCurrentBaseTarget(this);
if (frames_doc->MouseOverURL(*url, win_name, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
is_link = TRUE;
}
goto cursor_check;
}
#ifdef WIC_MIDCLICK_SUPPORT
case ONMOUSEDOWN:
case ONMOUSEUP:
{
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3)
{
if (URL *url = GetAREA_URL(frames_doc->GetLogicalDocument()))
frames_doc->HandleMidClick(this, offset_x, offset_y, document_x, document_y, modifiers, event == ONMOUSEDOWN);
goto cursor_check;
}
}
break;
#endif // WIC_MIDCLICK_SUPPORT
default:
break;
}
break;
case HE_A:
switch (event)
{
case ONMOUSEOVER:
case ONMOUSEMOVE:
case ONCLICK:
{
/* Pretty ugly hack to not load a new page if the current document
has been replaced using document.write. (jl@opera.com) */
if (event == ONCLICK && frames_doc->GetESScheduler() && !frames_doc->GetESScheduler()->TestTerminatingAction(ES_OpenURLAction::FINAL, ES_OpenURLAction::CONDITIONAL))
goto cursor_check;
URL url = GetAnchor_URL(frames_doc); // will substitute if it's a WML docuemnt
if (url.IsEmpty())
break;
#ifdef DOCUMENT_EDIT_SUPPORT
if (event == ONCLICK && frames_doc->GetDocumentEdit() && frames_doc->GetDocumentEdit()->GetEditableContainer(this))
break;
#endif // DOCUMENT_EDIT_SUPPORT
is_link = TRUE;
#ifdef WIC_USE_ANCHOR_SPECIAL
// Let the platform code abort user link clicks, but don't tell them
// about synthetic clicks since that would allow scripts to trigger
// ui actions.
if (!synthetic && event == ONCLICK)
{
const uni_char *rel_str = GetStringAttr(ATTR_REL);
const uni_char *ttl_str = GetStringAttr(ATTR_TITLE);
OpString urlnamerel_str;
OpString urlname_str;
OP_STATUS set_stat;
do
{
set_stat = url.GetAttribute(URL::KUniName_With_Fragment, urlnamerel_str, TRUE);
if (OpStatus::IsMemoryError(set_stat))
break;
set_stat = url.GetAttribute(URL::KUniName, urlname_str, TRUE);
if (OpStatus::IsMemoryError(set_stat))
break;
}
while (0);
if (set_stat != OpStatus::OK)
{
frames_doc->GetWindow()->RaiseCondition(set_stat);
goto cursor_check;
}
const OpDocumentListener::AnchorSpecialInfo anchor_info(rel_str, ttl_str, urlnamerel_str.CStr(), urlname_str.CStr());
if (WindowCommander *wc = frames_doc->GetWindow()->GetWindowCommander())
{
if (wc->GetDocumentListener()->OnAnchorSpecial(wc, anchor_info))
goto cursor_check;
}
}
#endif // !WIC_USE_ANCHOR_SPECIAL
#ifdef IMODE_EXTENSIONS
// utn support
const uni_char *attr_value = GetAttrValue(UNI_L("UTN"));
if( attr_value && uni_stri_eq(attr_value, "TRUE"))
url.SetUseUtn(TRUE);
#endif //IMODE_EXTENSIONS
const uni_char* win_name = GetA_Target();
if (!win_name || !*win_name)
win_name = GetCurrentBaseTarget(this);
#ifdef _WML_SUPPORT_
if (event == ONCLICK && frames_doc->GetDocManager())
{
if (WML_Context *wc = frames_doc->GetDocManager()->WMLGetContext())
wc->SetStatusOn(WS_GO);
}
#endif // _WML_SUPPORT_
if (frames_doc->MouseOverURL(url, win_name, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
goto cursor_check;
}
#ifdef WIC_MIDCLICK_SUPPORT
case ONMOUSEDOWN:
case ONMOUSEUP:
{
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3)
{
URL url(GetAnchor_URL(frames_doc));
if (!url.IsEmpty())
frames_doc->HandleMidClick(this, offset_x, offset_y, document_x, document_y, modifiers, event == ONMOUSEDOWN);
goto cursor_check;
}
}
break;
#endif // WIC_MIDCLICK_SUPPORT
default:
break;
}
break;
case HE_IMG:
#ifndef MOUSELESS
if (IsMap())
{
switch (event)
{
case ONMOUSEOVER:
case ONCLICK:
case ONMOUSEMOVE:
#ifdef WIC_MIDCLICK_SUPPORT
case ONMOUSEDOWN:
case ONMOUSEUP:
#endif // WIC_MIDCLICK_SUPPORT
{
HTML_Element* a_elm = GetA_Tag();
if (a_elm)
{
/* Pretty ugly hack to not load a new page if the current document
has been replaced using document.write. (jl@opera.com) */
if (event == ONCLICK && frames_doc->GetESScheduler() && !frames_doc->GetESScheduler()->TestTerminatingAction(ES_OpenURLAction::FINAL, ES_OpenURLAction::CONDITIONAL))
goto cursor_check;
const uni_char* win_name = a_elm->GetA_Target();
if (!win_name || !*win_name)
win_name = GetCurrentBaseTarget(a_elm);
const uni_char* href = a_elm->GetA_HRef(frames_doc, TRUE);
if (!href)
goto cursor_check;
int count = uni_strlen(href);
uni_char *buffer = OP_NEWA(uni_char, count + sizeof(long) * 3 + sizeof(int) * 3 + 5);
if (!buffer)
{
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
goto cursor_check;
}
uni_sprintf(buffer, UNI_L("%s?%d,%ld"), href, offset_x, offset_y);
URL url(ResolveUrl(buffer, frames_doc->GetLogicalDocument(), ATTR_HREF));
OP_DELETEA(buffer);
#ifdef WIC_MIDCLICK_SUPPORT
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3
&& (event == ONMOUSEDOWN || event == ONMOUSEUP)
&& !url.IsEmpty())
{
frames_doc->HandleMidClick(this, offset_x, offset_y, document_x, document_y, modifiers, event == ONMOUSEDOWN);
}
else
#endif // WIC_MIDCLICK_SUPPORT
if (frames_doc->MouseOverURL(url, win_name, event == ONMOUSEMOVE ? ONMOUSEOVER : event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
is_link = TRUE;
if (event == ONCLICK)
goto cursor_check;
}
}
break;
default:
break;
}
}
#ifndef NO_SAVE_SUPPORT
else // HE_IMG
{
if (!cancelled && event == ONCLICK)
{
handled = HandleSaveImage(modifiers, frames_doc, this);
if (handled)
goto cursor_check;
}
}
#endif // NO_SAVE_SUPPORT
#endif // !MOUSELESS
break;
case HE_BUTTON:
case HE_INPUT:
case HE_TEXTAREA:
{
#ifdef _X11_SELECTION_POLICY_
if (event == ONMOUSEDOWN || event == ONMOUSEUP)
{
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3)
goto cursor_check;
}
#endif // _X11_SELECTION_POLICY_
if (event == ONFORMCHANGE || event == ONFORMINPUT)
{
// This is an event that is sent to all elements in the form and it
// has no default action so we don't want to do anything at all when it
// happens. Not even call FindFormElm (that is O(n) which makes
// OnFormChange O(n^2) if we call it).
break;
}
if (event == ONCLICK && IsDisabled(frames_doc))
{
break;
}
#ifdef DOCUMENT_EDIT_SUPPORT
if (event == ONCLICK && frames_doc->GetDocumentEdit() && frames_doc->GetDocumentEdit()->GetEditableContainer(this))
break;
#endif // DOCUMENT_EDIT_SUPPORT
HTML_Element* form_element = FormManager::FindFormElm(frames_doc, this);
if (form_element)
{
InputType inp_type = GetInputType();
switch (inp_type)
{
case INPUT_SUBMIT:
case INPUT_IMAGE:
switch (event)
{
case ONCLICK:
{
OP_STATUS status = FormManager::HandleSubmitButtonClick(frames_doc, form_element,
this, offset_x, offset_y, document_x, document_y,
sequence_count_and_button_or_key_or_delta, modifiers, thread);
if (OpStatus::IsMemoryError(status))
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
goto cursor_check;
#ifndef MOUSELESS
case ONMOUSEOVER:
case ONMOUSEMOVE:
{
URL& url = frames_doc->GetURL();
URL moved_url = url.GetAttribute(URL::KMovedToURL, TRUE);
Form form(!moved_url.IsEmpty() ? moved_url : url, form_element, target, offset_x, offset_y);
URL form_url;
OP_STATUS status = form.GetDisplayURL(form_url, frames_doc);
if (status == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
else
{
if (frames_doc->MouseOverURL(form_url, NULL, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetHLDocProfile()->SetIsOutOfMemory(TRUE);
if (GetInputType() != INPUT_SUBMIT)
is_link = TRUE;
}
goto cursor_check;
}
#endif // !MOUSELESS
default:
break;
}
break;
case INPUT_RESET:
if (event == ONCLICK)
{
if (frames_doc->HandleEvent(ONRESET, this, form_element, modifiers) == OpStatus::ERR_NO_MEMORY)
{
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
break;
// XXX Shouldn't INPUT_FILE be included in this?
case INPUT_PASSWORD:
case INPUT_TEXT:
case INPUT_URI:
case INPUT_DATE:
case INPUT_WEEK:
case INPUT_TIME:
case INPUT_EMAIL:
case INPUT_NUMBER:
case INPUT_RANGE:
case INPUT_MONTH:
case INPUT_DATETIME:
case INPUT_DATETIME_LOCAL:
case INPUT_COLOR:
case INPUT_TEL:
case INPUT_SEARCH:
break;
default:
break;
}
if (event == ONCHANGE || event == ONINPUT)
{
// The default action of a change event should be to
// send the formchange event to all elements in the form
// The default action of a input event should be to
// send the forminput event to all elements in the form
// XXX The OnINPUT event?
if (form_element->Type() == HE_FORM) // Not for HE_ISINDEX
{
// Don't send formchange/forminput for changes in an output element
if (!target || target->Type() != HE_OUTPUT)
{
FormValidator form_validator(frames_doc); // XXX Split the FormValidator class
if (event == ONCHANGE)
{
form_validator.DispatchFormChange(form_element);
}
else
{
OP_ASSERT(event == ONINPUT);
form_validator.DispatchFormInput(form_element);
}
}
}
}
}
if (event == ONINVALID)
{
// The first oninvalid message for a form submission
// causes an error message to be displayed
FormValidator form_validator(frames_doc);
form_validator.MaybeDisplayErrorMessage(this);
}
}
break;
#ifdef _WML_SUPPORT_
case HE_SELECT:
case HE_OPTION:
#ifdef _X11_SELECTION_POLICY_
if (type == HE_SELECT && (event == ONMOUSEDOWN || event == ONMOUSEUP))
{
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3)
goto cursor_check;
}
#endif // _X11_SELECTION_POLICY_
if (type == HE_SELECT && event == ONCHANGE ||
type == HE_OPTION && event == ONCLICK)
{
if (frames_doc && frames_doc->GetDocManager() && frames_doc->GetDocManager()->WMLHasWML())
{
BOOL user_initiated = !synthetic;
if (thread)
user_initiated = thread->GetInfo().is_user_requested;
if (type == HE_SELECT)
DoWmlSelection(this, NULL, frames_doc, user_initiated);
else
{
OP_ASSERT(type == HE_OPTION);
DoWmlSelection(NULL, this, frames_doc, user_initiated);
}
}
}
#endif // _WML_SUPPORT_
if (event == ONINVALID)
{
// The first oninvalid message for a form submission
// causes an error message to be displayed
FormValidator form_validator(frames_doc);
form_validator.MaybeDisplayErrorMessage(this);
}
break;
case HE_ISINDEX:
case HE_FORM:
if (event == ONSUBMIT || event == ONRESET)
{
OP_STATUS status;
if (event == ONRESET)
{
status = FormManager::ResetForm(frames_doc, this);
}
else // event == ONSUBMIT
{
ES_Thread* submit_thread = synthetic ? thread : NULL;
status = FormManager::SubmitForm(frames_doc, this, related_target,
offset_x, offset_y, submit_thread, synthetic, modifiers);
if (OpStatus::IsSuccess(status))
{
is_link = TRUE;
}
}
if (OpStatus::IsMemoryError(status))
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
goto cursor_check;
}
break;
case HE_LABEL:
// Clicks on labels should simulate a click on the form element for simple form controls.
if (event == ONCLICK &&
!target->IsMatchingType(HE_OPTION, NS_HTML) && !target->IsFormElement())
{
HTML_Element *form_elm;
const uni_char *for_id = GetAttrValue(ATTR_FOR);
if (for_id)
{
// find the form element this label belongs to (or the root node if not inside a form)
form_elm = this;
HTML_Element* parent = ParentActual();
while (parent && !form_elm->IsMatchingType(HE_FORM, NS_HTML))
{
form_elm = parent;
parent = parent->ParentActual();
}
form_elm = form_elm->GetElmById(for_id);
}
else
form_elm = FindFirstContainedFormElm();
if (form_elm && form_elm->IsFormElement())
{
if (form_elm->Type() == HE_INPUT || form_elm->Type() == HE_BUTTON || form_elm->Type() == HE_TEXTAREA || form_elm->Type() == HE_SELECT)
{
// A click on a label will act as an alternate way to click in the form element
if (frames_doc->GetHtmlDocument())
frames_doc->GetHtmlDocument()->ScrollToElement(form_elm, SCROLL_ALIGN_CENTER, FALSE, VIEWPORT_CHANGE_REASON_FORM_FOCUS);
FormObject* form_object = form_elm->GetFormObject();
if (form_object)
{
form_object->SetFocus(synthetic ? FOCUS_REASON_OTHER : FOCUS_REASON_MOUSE);
form_object->Click(thread);
}
else if (!form_elm->IsDisabled(frames_doc))
{
FormValue* form_value = form_elm->GetFormValue();
FormValueRadioCheck* radiocheck = NULL;
if (form_value->GetType() == FormValue::VALUE_RADIOCHECK)
{
// A hidden checkbox/radio button.
radiocheck = FormValueRadioCheck::GetAs(form_value);
radiocheck->SaveStateBeforeOnClick(form_elm);
}
// These have no FormObjects (could be because of no layout - display: none style).
frames_doc->HandleMouseEvent(ONCLICK,
NULL, form_elm, NULL,
0, 0, // x and y relative to the element
0, 0, // x and y relative to the document
0, // keystate
MAKE_SEQUENCE_COUNT_AND_BUTTON(1, MOUSE_BUTTON_1),
thread);
// Generated click event can't toggle checkboxes that have no layout.
if (radiocheck)
{
BOOL new_state;
if (form_elm->GetInputType() == INPUT_CHECKBOX)
new_state = !radiocheck->IsChecked(form_elm);
else
new_state = TRUE;
radiocheck->SetIsChecked(form_elm, new_state, frames_doc, TRUE, thread);
FormValueListener::HandleValueChanged(frames_doc, form_elm, !synthetic, !synthetic, thread);
}
}
}
}
}
break;
#ifdef MEDIA_HTML_SUPPORT
case HE_AUDIO:
case HE_VIDEO:
handled = HandleMediaElementEvent(event, frames_doc, this, options);
if (handled)
goto cursor_check;
break;
#endif // MEDIA_HTML_SUPPORT
default:
break;
}
}
#ifdef M2_SUPPORT
else if (ns == NS_OMF)
{
HTML_ElementType type = Type();
switch (type)
{
case OE_ITEM:
case OE_SHOWHEADERS:
if (event == ONMOUSEOVER || event == ONCLICK)
{
URL* url = (URL*)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC);
if (url && url->Type() != URL_JAVASCRIPT)
{
if (frames_doc->MouseOverURL(*url, NULL, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
is_link = TRUE;
goto cursor_check;
}
}
break;
}
}
#endif // M2_SUPPORT
#ifdef _WML_SUPPORT_
else if (ns == NS_WML)
{
WML_ElementType type = (WML_ElementType) Type();
WML_Context *wc = frames_doc->GetDocManager()->WMLGetContext();
OP_ASSERT( wc ); // could we get here without a context? /pw
if (!wc)
goto cursor_check;
switch(type)
{
case WE_ANCHOR:
case WE_DO:
{
WMLNewTaskElm *wml_task = wc->GetTaskByElement(this);
switch (event)
{
case ONCLICK:
{
// setting the temporary task if a link is clicked
if (wc->SetActiveTask(wml_task) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
// this one should fall through
case ONMOUSEMOVE:
case ONMOUSEOVER:
{
UINT32 action = 0;
URL url = wc->GetWmlUrl(wml_task ? wml_task->GetHElm() : this, &action);
if (url.IsEmpty())
break;
is_link = TRUE;
if (event == ONCLICK)
{
if ((action & WS_GO) != 0)
{
// Validate the form a final time before allowing
// the submit so that we catch fields that doesn't
// validate even before a user accesses them.
if (!FormManager::ValidateWMLForm(frames_doc))
break;
}
if (action & WS_GO)
wc->SetStatusOn(action);
else if (action & WS_REFRESH)
{
wc->SetStatusOn(action);
frames_doc->GetDocManager()
->GetMessageHandler()
->PostMessage(MSG_WML_REFRESH, frames_doc->GetURL().Id(TRUE), TRUE);
goto cursor_check;
}
else if (action & WS_ENTERBACK)
{
wc->SetStatusOn(WS_ENTERBACK);
frames_doc->GetWindow()
->GetMessageHandler()
->PostMessage(MSG_HISTORY_BACK, frames_doc->GetURL().Id(TRUE), 0);
goto cursor_check;
}
}
if (frames_doc->MouseOverURL(url, NULL, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
goto cursor_check;
}
default:
break;
}
}
break;
}
}
#endif // _WML_SUPPORT_
#ifdef SVG_SUPPORT
else if (ns == NS_SVG)
{
#ifndef NO_SAVE_SUPPORT
if (!cancelled && event == ONCLICK && IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
handled = HandleSaveImage(modifiers, frames_doc, this);
if (handled)
goto cursor_check;
}
#endif // NO_SAVE_SUPPORT
if (event == ONCLICK || event == ONMOUSEOVER || event == ONMOUSEMOVE)
{
URL *url = NULL;
const uni_char* window_target = NULL;
OP_BOOLEAN status = g_svg_manager->NavigateToElement(this, frames_doc, &url, event, event == ONCLICK ? &window_target : NULL);
if (status == OpBoolean::IS_TRUE && url != NULL)
{
if (!url->IsEmpty())
{
is_link = TRUE;
if (frames_doc->MouseOverURL(*url, window_target, event, shift_pressed, control_pressed MOUSEOVERURL_THREAD, this) == OpStatus::ERR_NO_MEMORY)
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
goto cursor_check;
}
}
if (OpStatus::IsMemoryError(status))
frames_doc->GetWindow()->RaiseCondition(status);
}
}
#endif // SVG_SUPPORT
HTML_Element* parent;
if (IsMatchingType(HE_MAP, NS_HTML) && imagemap)
{
// When parent is a map and an imagemap is supplied, event
// propagation is redirected to the imagemap.
parent = imagemap;
imagemap = NULL;
}
else
{
// path len == -1 - means 'find it yourself'
if (event_bubbling_path_len == -1)
parent = ParentActualStyle();
else if (event_bubbling_path_len > 0) // go to the next element
{
parent = *event_bubbling_path;
++event_bubbling_path;
--event_bubbling_path_len;
}
else // the path ended
parent = NULL;
}
if (parent)
handled = parent->HandleEvent(event, frames_doc, target, options, imagemap, event_bubbling_path, event_bubbling_path_len);
#ifndef MOUSELESS
else
{
MouseButton button = EXTRACT_MOUSE_BUTTON(sequence_count_and_button_or_key_or_delta);
if (button == MOUSE_BUTTON_3)
{
#ifdef WIC_MIDCLICK_SUPPORT
if (event == ONMOUSEDOWN || event == ONMOUSEUP)
{
URL url;
frames_doc->HandleMidClick(this, offset_x, offset_y, document_x, document_y, modifiers, event == ONMOUSEDOWN);
}
#endif // WIC_MIDCLICK_SUPPORT
}
else switch (event)
{
case ONMOUSEUP:
{
#if !defined HAS_NOTEXTSELECTION && defined _X11_SELECTION_POLICY_
// This section has to be done outside the 'target == active' test below as they
// may very well not be identical when finishing a selection
if (button == MOUSE_BUTTON_1)
{
if (frames_doc->HasSelectedText() && frames_doc->GetWasSelectingText())
frames_doc->CopySelectedTextToMouseSelection();
}
#endif // !defined HAS_NOTEXTSELECTION && defined _X11_SELECTION_POLICY_
HTML_Element* active = frames_doc->GetActiveHTMLElement();
frames_doc->SetActiveHTMLElement(NULL);
if (target == active &&
!target->IsDisabled(frames_doc) && button == MOUSE_BUTTON_1)
{
/* Don't generate a ONCLICK if there is selected text.
This is to make it possible to select text in a link
without also clicking the link. */
# ifndef HAS_NOTEXTSELECTION
BOOL selected_text = frames_doc->HasSelectedText() && frames_doc->GetWasSelectingText();
# ifdef SVG_SUPPORT
BOOL svg_has_selected_text = FALSE;
if(!selected_text && active->GetNsType() == NS_SVG)
{
SVGWorkplace* svg_workplace = frames_doc->GetLogicalDocument()->GetSVGWorkplace();
svg_has_selected_text = svg_workplace->HasSelectedText();
selected_text = svg_has_selected_text;
}
# endif // SVG_SUPPORT
# ifdef GRAB_AND_SCROLL
if (frames_doc->GetWindow()->GetScrollIsPan())
selected_text = FALSE; //ignore selected text here
# endif // GRAB_AND_SCROLL
BOOL might_be_interpreted_as_click = EXTRACT_CLICK_INDICATOR(sequence_count_and_button_or_key_or_delta);
if (!might_be_interpreted_as_click && frames_doc->GetMouseUpMayBeClick())
might_be_interpreted_as_click = TRUE;
BOOL send_onclick_event = FALSE;
if (might_be_interpreted_as_click)
{
send_onclick_event = !selected_text ||
(!frames_doc->HasSelectedText()
# ifdef SVG_SUPPORT
&& !svg_has_selected_text
# endif // SVG_SUPPORT
) ||
modifiers != 0;
}
frames_doc->SetSelectingText(FALSE);
if (send_onclick_event)
# endif
{
DOM_EventType type = ONCLICK;
send_click_event:
if (frames_doc->HandleMouseEvent(type,
related_target, target, imagemap,
offset_x, offset_y,
document_x, document_y,
modifiers,
sequence_count_and_button_or_key_or_delta) == OpStatus::ERR_NO_MEMORY)
{
frames_doc->GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
else if (type == ONCLICK)
{
int sequence_count = EXTRACT_SEQUENCE_COUNT(sequence_count_and_button_or_key_or_delta);
if (sequence_count == 2)
{
type = ONDBLCLICK;
goto send_click_event;
}
}
}
}
}
break;
case ONMOUSEDOWN:
#ifndef HAS_NOTEXTSELECTION
if (button == MOUSE_BUTTON_1
&& !cancelled
&& frames_doc->GetHtmlDocument()
&& !frames_doc->GetHtmlDocument()->GetCapturedWidgetElement()
&& !OpWidget::hooked_widget
&& !target->IsMatchingType(HE_OPTION, NS_HTML)
#ifdef DOCUMENT_EDIT_SUPPORT
&& !target_at_layout_modifier
#endif // DOCUMENT_EDIT_SUPPORT
)
{
int sequence_count = EXTRACT_SEQUENCE_COUNT(sequence_count_and_button_or_key_or_delta);
if (shift_pressed)
{
if (sequence_count == 1 && frames_doc->GetSelectedTextLen())
{
frames_doc->MoveSelectionFocusPoint(document_x, document_y, FALSE);
frames_doc->SetSelectingText(TRUE);
}
#ifdef DOCUMENT_EDIT_SUPPORT
else if (sequence_count == 1 && frames_doc->GetDocumentEdit())
{
OpDocumentEdit *de = frames_doc->GetDocumentEdit();
if (de->GetEditableContainer(target))
{
OpPoint p = frames_doc->GetCaretPainter()->GetCaretPosInDocument();
if (OpStatus::IsSuccess(frames_doc->StartSelection(p.x, p.y)))
frames_doc->MoveSelectionFocusPoint(document_x, document_y, FALSE);
}
}
#endif
}
else
{
// The selection should be expanded after the second mousedown.
if (sequence_count == 2)
{
frames_doc->ExpandSelection(TEXT_SELECTION_WORD);
frames_doc->SetSelectingText(FALSE);
}
else if(sequence_count == 1)
{
// Remove all search hits
frames_doc->GetTopDocument()->RemoveSearchHits();
frames_doc->MaybeStartTextSelection(document_x, document_y);
}
}
}
#endif // HAS_NOTEXTSELECTION
frames_doc->SetActiveHTMLElement(target);
break;
case ONDBLCLICK:
#ifndef HAS_NOTEXTSELECTION
# ifdef LOGDOC_HOTCLICK
# ifdef _X11_SELECTION_POLICY_
frames_doc->CopySelectedTextToMouseSelection();
# endif // _X11_SELECTION_POLICY_
#ifdef DOCUMENT_EDIT_SUPPORT
// No hotclick menu if we clicked in a editable element
if (!(frames_doc->GetDocumentEdit() && frames_doc->GetDocumentEdit()->GetEditableContainer(target)))
#endif // DOCUMENT_EDIT_SUPPORT
{
VisualDevice* vis_dev = frames_doc->GetVisualDevice();
CoreView* view = vis_dev->GetView();
if (view)
ShowHotclickMenu(vis_dev, frames_doc->GetWindow(), view, frames_doc->GetDocManager(), frames_doc, TRUE);
}
# endif // LOGDOC_HOTCLICK
#endif // HAS_NOTEXTSELECTION
break;
case ONMOUSEOVER:
{
if (g_pcdoc->GetIntegerPref(PrefsCollectionDoc::DisplayLinkTitle))
{
const uni_char* string = NULL;
#ifdef SVG_SUPPORT
OpString title_owner;
#endif // SVG_SUPPORT
HTML_Element* elm = target;
while (elm && !string)
{
if (elm->GetNsType() == NS_HTML)
string = elm->GetStringAttr(ATTR_TITLE);
#ifdef SVG_SUPPORT
else if (elm->GetNsType() == NS_SVG)
{
g_svg_manager->GetToolTip(elm, title_owner);
string = title_owner.CStr();
}
#endif // SVG_SUPPORT
elm = elm->Parent();
}
if (string)
frames_doc->GetWindow()->DisplayLinkInformation(NULL, ST_ATITLE, string);
}
}
break;
default:
break;
}
}
#endif // !MOUSELESS
cursor_check:
#ifndef MOUSELESS
if (event == ONMOUSEOVER || event == ONMOUSEMOVE || event == ONMOUSEOUT)
{
Window* cur_win = frames_doc->GetWindow();
if (Type() == Markup::HTE_DOC_ROOT &&
!(frames_doc->GetHtmlDocument() && frames_doc->GetHtmlDocument()->GetCapturedWidgetElement()))
{
/* Set cursor auto when we reach doc root */
cur_win->SetPendingCursor(CURSOR_AUTO);
}
else
{
BOOL has_cursor_settings;
FormObject* form_object = GetFormObject();
# ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
has_cursor_settings = HasCursorSettings(); // never any layout box for svg elements
else
# endif
has_cursor_settings = HasCursorSettings() && GetLayoutBox();
if (has_cursor_settings)
{
# ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
cur_win->SetPendingCursor(g_svg_manager->GetCursorForElement(this));
else
# endif // SVG
cur_win->SetPendingCursor(GetCursorType());
}
else if (is_link)
{
cur_win->SetPendingCursor(CURSOR_CUR_POINTER);
}
else if (event == ONMOUSEMOVE && form_object)
{
form_object->OnSetCursor(OpPoint(document_x, document_y));
}
/* Set the default arrow cursor here so that we could avoid the text cursor on
* boxes inside labels or buttons.
*/
else if (cur_win->GetPendingCursor() == CURSOR_AUTO
&& (IsMatchingType(HE_LABEL, NS_HTML) || IsMatchingType(HE_BUTTON, NS_HTML)))
{
cur_win->SetPendingCursor(CURSOR_DEFAULT_ARROW);
}
if (this == target)
{
# ifdef DOCUMENT_EDIT_SUPPORT
CursorType de_cursor = CURSOR_AUTO;
if (OpDocumentEdit *de = frames_doc->GetDocumentEdit())
de_cursor = de->GetCursorType(target, document_x, document_y);
/* Note: If we want to use any specific cursor from parents
* check for pending cursor and then only set the cursor
*/
if (de_cursor != CURSOR_AUTO)
cur_win->SetPendingCursor(de_cursor);
else
# endif // DOCUMENT_EDIT_SUPPORT
if (cur_win->GetPendingCursor() == CURSOR_AUTO && CanUseTextCursor())
cur_win->SetPendingCursor(CURSOR_TEXT);
/* Form objects would have already set a cursor, so
* apply the pending cursor if not a FormObject.
* If cursor style is specified then force that style (CORE-43297)
* Note: plugins can force a cursor change so in
* such cases we should not override it.
*/
if (has_cursor_settings || !form_object
#ifdef _PLUGIN_SUPPORT_
&& !GetNS4Plugin()
#endif // _PLUGIN_SUPPORT_
)
cur_win->CommitPendingCursor();
}
}
}
#endif // MOUSELESS
replay_mouse_actions:
; // empty statement to silence compiler
#ifndef MOUSELESS
if (this == target)
{
switch (event)
{
case ONMOUSEDOWN:
case ONMOUSEUP:
case ONMOUSEMOVE:
case ONMOUSEOVER:
case ONMOUSEENTER:
case ONMOUSEOUT:
case ONMOUSELEAVE:
case ONMOUSEWHEELH:
case ONMOUSEWHEELV:
#ifdef TOUCH_EVENTS_SUPPORT
case TOUCHSTART:
case TOUCHMOVE:
case TOUCHEND:
case TOUCHCANCEL:
#endif // TOUCH_EVENTS_SUPPORT
if (HTML_Document *html_doc = frames_doc->GetHtmlDocument())
/* This may trigger recursive calls to this function. */
html_doc->ReplayRecordedMouseActions();
break;
}
}
#endif // !MOUSELESS
return handled;
}
#ifdef TOUCH_EVENTS_SUPPORT
void HTML_Element::SimulateMouse(HTML_Document* doc, DOM_EventType event, int x, int y, int radius, ShiftKeyState modifiers)
{
int sequence_count_and_button = MAKE_SEQUENCE_COUNT_AND_BUTTON(1, MOUSE_BUTTON_1);
BOOL shift = !!(modifiers & SHIFTKEY_SHIFT);
BOOL ctrl = !!(modifiers & SHIFTKEY_CTRL);
BOOL alt = !!(modifiers & SHIFTKEY_ALT);
#ifndef DOC_TOUCH_SMARTPHONE_COMPATIBILITY
/*
* Our default behaviour is to map touch events directly to mouse events,
* facilitating normal desktop interactivity.
*/
DOM_EventType sequence[3] = { DOM_EVENT_NONE, DOM_EVENT_NONE, DOM_EVENT_NONE }; /* ARRAY OK 2010-07-26 terjes */
switch (event)
{
case TOUCHSTART:
/* Move pointer and implicitly generate ONMOUSE{OUT,OVER}. */
sequence[0] = ONMOUSEMOVE;
sequence[1] = ONMOUSEDOWN;
break;
case TOUCHMOVE:
sequence[0] = ONMOUSEMOVE;
break;
case TOUCHEND:
sequence[0] = ONMOUSEUP;
break;
};
for (int i = 0; sequence[i] != DOM_EVENT_NONE; i++)
doc->MouseAction(sequence[i], x, y, doc->GetFramesDocument()->GetVisualViewX(), doc->GetFramesDocument()->GetVisualViewY(), sequence_count_and_button, shift, ctrl, alt, FALSE, TRUE, radius);
#else // !DOC_TOUCH_SMARTPHONE_COMPATIBILITY
/*
* As we are aiming for behaviour consistent with other smartphones, generate
* the entire sequence of mouse events on TOUCHEND.
*/
if (event == TOUCHEND)
{
/*
* We should consider cancelling this sequence if the mouseover/mousemove
* events lead to document changes. This would theoretically allow menus
* such as the one currently in effect on opera.com.
*
* (Cancelling the sequence is easily done by filtering all recorded events
* with the 'simulated' flag set.)
*/
DOM_EventType sequence[] = { ONMOUSEMOVE, ONMOUSEDOWN, ONMOUSEUP, DOM_EVENT_NONE };
for (int i = 0; sequence[i] != DOM_EVENT_NONE; i++)
doc->MouseAction(sequence[i], x, y, sequence_count_and_button, shift, ctrl, alt, FALSE, TRUE, radius);
}
#endif // DOC_TOUCH_SMARTPHONE_COMPATIBILITY
}
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
void HTML_Element::UpdateCursor(FramesDocument *frames_doc)
{
BOOL has_cursor_settings;
HTML_Element *parent = this;
while (parent)
{
if (parent->IsLink(frames_doc))
break;
# ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
has_cursor_settings = parent->HasCursorSettings(); // never any layout box for svg elements
else
# endif
has_cursor_settings = parent->HasCursorSettings() && GetLayoutBox();
if (has_cursor_settings)
{
CursorType new_cursor;
# ifdef SVG_SUPPORT
if (parent->GetNsType() == NS_SVG)
new_cursor = g_svg_manager->GetCursorForElement(parent);
else
# endif // SVG
new_cursor = parent->GetCursorType();
/* Only set if the current cursor and new_cursor are different */
frames_doc->GetWindow()->SetCursor(new_cursor, TRUE);
return;
}
parent = parent->Parent();
}
}
BOOL HTML_Element::IsLink(FramesDocument *frames_doc)
{
if (GetNsType() == NS_HTML)
{
if (Type() == HE_IMG && GetA_Tag())
return TRUE;
if (Type() == HE_A && !GetAnchor_URL(frames_doc).IsEmpty())
return TRUE;
if (Type() == HE_AREA && GetAREA_URL(frames_doc->GetLogicalDocument()))
return TRUE;
if (Type() == HE_INPUT && GetInputType() == INPUT_IMAGE && FormManager::FindFormElm(frames_doc, this))
return TRUE;
}
if (URL *css_link = (URL*)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, (void*)NULL, SpecialNs::NS_LOGDOC))
if (css_link->Type() != URL_JAVASCRIPT)
return TRUE;
#ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
{
URL *url = NULL;
OP_BOOLEAN status = g_svg_manager->NavigateToElement(this, frames_doc, &url, ONMOUSEOVER, NULL);
if (status == OpBoolean::IS_TRUE && url != NULL && !url->IsEmpty())
return TRUE;
}
#endif // SVG_SUPPORT
#ifdef _WML_SUPPORT_
if (GetNsType() == NS_WML)
{
WML_ElementType type = (WML_ElementType) Type();
WML_Context *wc = frames_doc->GetDocManager()->WMLGetContext();
WMLNewTaskElm *wml_task = wc->GetTaskByElement(this);
if (!wc || !wml_task)
return FALSE;
if (type == WE_ANCHOR || type == WE_DO)
{
UINT32 action = 0;
URL url = wc->GetWmlUrl(wml_task->GetHElm(), &action);
if (!url.IsEmpty())
return TRUE;
}
}
#endif //_WML_SUPPORT_
#ifdef M2_SUPPORT
if (GetNsType() == NS_OMF)
{
if (Type() == OE_ITEM || Type() == OE_SHOWHEADERS)
if (URL *css_link = (URL*)GetSpecialAttr(ATTR_CSS_LINK, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC))
if (css_link->Type() != URL_JAVASCRIPT)
return TRUE;
}
#endif // M2_SUPPORT
return FALSE;
}
#endif // !MOUSELESS
HTML_Element*
HTML_Element::GetNextLinkElementInMap(BOOL forward, HTML_Element* map_element)
{
HTML_Element* next;
if (map_element == this)
next = forward ? FirstChildActual() : LastChildActual();
else
next = forward ? NextActual() : PrevActual();
if (next && map_element != next && map_element->IsAncestorOf(next))
{
if (next->IsMatchingType(HE_A, NS_HTML) || next->IsMatchingType(HE_AREA, NS_HTML))
return next;
else
return next->GetNextLinkElementInMap(forward, map_element);
}
return NULL;
}
HTML_Element* HTML_Element::GetAncestorMapElm()
{
HTML_Element* map_elm = ParentActual();
while (map_elm && !map_elm->IsMatchingType(HE_MAP, NS_HTML))
map_elm = map_elm->ParentActual();
return map_elm;
}
HTML_Element*
HTML_Element::GetLinkElement(VisualDevice* vd, int rel_x, int rel_y,
const HTML_Element* img_element,
HTML_Element* &default_element,
LogicalDocument *logdoc/*=NULL*/)
{
if (Type() == HE_A || Type() == HE_AREA)
{
if (GetMapUrl(vd, rel_x, rel_y, img_element, NULL, logdoc))
return this;
else if (GetAREA_Shape() == AREA_SHAPE_DEFAULT)
default_element = this;
}
HTML_Element* link_element = NULL;
for (HTML_Element* child = FirstChildActual(); child && !link_element; child = child->SucActual())
link_element = child->GetLinkElement(vd, rel_x, rel_y, img_element, default_element, logdoc);
return link_element;
}
/**
* Get element linked to from an usemap image based on coordinates. If the alt text is
* shown, the linked element is based on the href of the clicked element that was
* INSERTED_BY_LAYOUT to act as an alt link.
*
* @param frames_doc
* @param rel_x
* @param rel_y
* @param clicked_element Corresponding alt text link that was clicked.
*
*/
HTML_Element*
HTML_Element::GetLinkedElement(FramesDocument* frames_doc,
int rel_x, int rel_y, HTML_Element* clicked_alt_text_element)
{
if(GetNsType() == NS_HTML)
{
switch (Type())
{
case HE_INPUT:
case HE_IMG:
case HE_OBJECT:
{
URL* usemap_url = NULL;
if(Type() == HE_INPUT || Type() == HE_OBJECT)
usemap_url = GetUrlAttr(ATTR_USEMAP, NS_IDX_HTML, frames_doc->GetLogicalDocument());
else
usemap_url = GetIMG_UsemapURL(frames_doc->GetLogicalDocument());
if (usemap_url && !usemap_url->IsEmpty())
{
HTML_Element* map_elm = NULL;
LogicalDocument* logdoc = frames_doc->GetLogicalDocument();
if (logdoc)
{
const uni_char* rel_name = usemap_url->UniRelName();
if (rel_name && logdoc->GetRoot())
map_elm = logdoc->GetRoot()->GetMAP_Elm(rel_name);
}
if (map_elm)
{
HTML_Element* link_element = NULL;
if (!GetLayoutBox() || !GetLayoutBox()->IsContentImage())
{
// We are showing the alt text.
if (!clicked_alt_text_element)
return NULL;
const uni_char* elm_url = NULL;
HTML_Element* elm_iter = clicked_alt_text_element;
while (elm_iter)
{
if ((elm_url = elm_iter->GetA_HRef(frames_doc)) != NULL)
break;
elm_iter = elm_iter->Parent(); // Not ParentActual we want to be INSERTED_BY_LAYOUT
}
if (!elm_url)
return NULL;
HTML_Element* link_element = map_elm->GetNextLinkElementInMap(TRUE, map_elm);
while (link_element)
{
const uni_char* link_element_href = link_element->GetStringAttr(ATTR_HREF);
if (link_element_href && uni_strcmp(elm_url, link_element_href) == 0)
return link_element;
link_element = link_element->GetNextLinkElementInMap(TRUE, map_elm);
}
}
else
{
HTML_Element* default_element = NULL;
link_element = map_elm->GetLinkElement(frames_doc->GetVisualDevice(), rel_x, rel_y, this, default_element, logdoc);
if (!link_element)
link_element = default_element;
}
return link_element;
}
}
}
break;
default:
break;
}
}
return NULL;
}
#ifdef _WML_SUPPORT_
OP_STATUS HTML_Element::WMLInit(DocumentManager *doc_man)
{
WML_ElementType w_type = (WML_ElementType)Type();
NS_Type ns = GetNsType();
WML_Context *context = doc_man->WMLGetContext();
if (!context)
{
doc_man->WMLInit();
context = doc_man->WMLGetContext();
if (!context)
return OpStatus::ERR_NO_MEMORY;
}
if (ns != NS_WML)
{
if (ns != NS_HTML)
return OpStatus::OK;
switch (Type())
{
case HE_HTML:
case HE_BODY:
if (HasAttr(WA_ONTIMER, NS_IDX_WML))
{
if (OpStatus::IsMemoryError(context->SetEventHandler(WEVT_ONTIMER, context->NewTask(this))))
return OpStatus::ERR_NO_MEMORY;
}
else if (HasAttr(WA_ONENTERFORWARD, NS_IDX_WML))
{
if (OpStatus::IsMemoryError(context->SetEventHandler(WEVT_ONENTERFORWARD, context->NewTask(this))))
return OpStatus::ERR_NO_MEMORY;
}
else if (HasAttr(WA_ONENTERBACKWARD, NS_IDX_WML))
{
if (OpStatus::IsMemoryError(context->SetEventHandler(WEVT_ONENTERBACKWARD, context->NewTask(this))))
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
case HE_OPTION:
if (HasAttr(WA_ONPICK, NS_IDX_WML))
return context->SetTaskByElement(context->NewTask(this), this);
break;
default:
return OpStatus::OK;
}
}
HTML_Element *parent = Parent();
WMLNewTaskElm *tmp_task = NULL;
const uni_char *value = doc_man->GetCurrentURL().UniRelName();
const uni_char *extra_value = NULL;
if (w_type == WE_CARD)
{
extra_value = GetId();
if (!extra_value)
extra_value = UNI_L("");
BOOL matches_target = value ? uni_str_eq(value, extra_value) : context->IsSet(WS_FIRSTCARD);
if (matches_target || context->IsSet(WS_FIRSTCARD))
{
if (matches_target)
{
if (context->GetPendingCurrentCard())
context->ScrapTmpCurrentCard();
context->SetStatusOn(WS_INRIGHTCARD);
}
else
{
RETURN_IF_MEMORY_ERROR(context->PushTmpCurrentCard());
}
context->SetPendingCurrentCard(this);
}
else
return OpStatus::OK;
}
else if (!context->IsSet(WS_FIRSTCARD) && ! context->IsSet(WS_INRIGHTCARD)) // check if the element is within the valid card
return OpStatus::OK;
/****************************************
* do element specific tasks
****************************************/
switch (w_type)
{
case WE_PREV: // fall through
case WE_REFRESH: // fall through
case WE_GO:
case WE_NOOP:
{
WML_ElementType e_type = (WML_ElementType) parent->Type();
if (e_type == WE_ANCHOR
|| e_type == WE_ONEVENT
|| e_type == WE_DO)
{
tmp_task = context->GetTaskByElement(parent);
if (context->SetTaskByElement(tmp_task, this) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
}
}
break;
case WE_ONEVENT:
{
value = GetStringAttr(WA_TYPE, NS_IDX_WML);
WML_EventType e_type = WML_Lex::GetEventType(value);
if (e_type == WEVT_ONPICK && parent->IsMatchingType(HE_OPTION, NS_HTML))
{
tmp_task = context->GetTaskByElement(parent); // if exists, use the task of the OPTION element
if (!tmp_task)
{
tmp_task = context->NewTask(this);
if (context->SetTaskByElement(tmp_task, parent) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
}
}
else if ((e_type == WEVT_ONTIMER
|| e_type == WEVT_ONENTERFORWARD
|| e_type == WEVT_ONENTERBACKWARD)
&&
(parent->IsMatchingType(WE_CARD, NS_WML)
|| parent->IsMatchingType(WE_TEMPLATE, NS_WML)
|| parent->IsMatchingType(HE_BODY, NS_HTML)))
{
tmp_task = context->NewTask(this);
if (context->SetTaskByElement(tmp_task, this) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
if (context->SetEventHandler(e_type, tmp_task) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
}
}
break;
case WE_DO:
case WE_ANCHOR:
return context->SetTaskByElement(context->NewTask(this), this);
case WE_CARD:
if (GetBoolAttr(WA_NEWCONTEXT, NS_IDX_WML))
{
RETURN_IF_MEMORY_ERROR(context->SetNewContext());
}
// fall through
case WE_TEMPLATE:
value = GetAttrValue(WA_ONENTERFORWARD, NS_IDX_WML);
if (value && context->SetEventHandler(WEVT_ONENTERFORWARD, context->NewTask(this)) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
value = GetAttrValue(WA_ONENTERBACKWARD, NS_IDX_WML);
if (value && context->SetEventHandler(WEVT_ONENTERBACKWARD, context->NewTask(this)) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
value = GetAttrValue(WA_ONTIMER, NS_IDX_WML);
if (value && context->SetEventHandler(WEVT_ONTIMER, context->NewTask(this)) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
break;
case WE_ACCESS:
{
URL url = doc_man->GetCurrentDoc()->GetRefURL().url;
value = GetStringAttr(WA_DOMAIN, NS_IDX_WML);
if (value)
{
ServerName *host = (ServerName *) url.GetAttribute(URL::KServerName, (void*)NULL);
ServerName *domain = g_url_api->GetServerName(value, TRUE);
if(!host || !domain || host->GetCommonDomain(domain) != domain)
{
context->SetStatusOn(WS_NOACCESS);
break;
}
}
extra_value = GetStringAttr(WA_PATH, NS_IDX_WML);
if (extra_value)
{
#ifdef OOM_SAFE_API
TRAPD(op_err, value = url.GetAttributeL(URL::KUniPath));
if (OpStatus::IsError(op_err) || !value )
value = UNI_L("");
#else
if (! (value = url.GetAttribute(URL::KUniPath, TRUE).CStr()))
value = UNI_L("");
#endif //OOM_SAFE_API
unsigned int i = 0;
unsigned int j = uni_strlen(extra_value);
if (uni_strlen(value) >= j)
{
while (i < j && value[i] == extra_value[i])
i++;
if (i != j || (value[i] != '/' && (i == 0 || extra_value[i - 1] != '/')))
context->SetStatusOn(WS_NOACCESS);
}
else
context->SetStatusOn(WS_NOACCESS);
}
}
break;
case WE_TIMER:
value = GetWmlName();
extra_value = GetWmlValue();
if (extra_value)
{
#ifdef WML_SHORTEN_SHORT_DELAYS
if( uni_atoi(extra_value) < 20 )
extra_value = UNI_L("1");
else
break;
#endif // WML_SHORTEN_SHORT_DELAYS
return context->SetTimer(value, extra_value);
}
break;
default:
break;
}
return OpStatus::OK;
}
#endif // _WML_SUPPORT_
LogicalDocument*
HTML_Element::GetLogicalDocument() const
{
const HTML_Element *parent = this;
while (parent && parent->Type() != HE_DOC_ROOT)
parent = parent->Parent();
if(!parent)
return NULL;
ComplexAttr *attr = (ComplexAttr*) parent->GetSpecialAttr(ATTR_LOGDOC,
ITEM_TYPE_COMPLEX, (void*)NULL, SpecialNs::NS_LOGDOC);
OP_ASSERT(!attr || attr->IsA(ComplexAttr::T_LOGDOC));
return (LogicalDocument*)attr;
}
#ifdef _DEBUG
const uni_char *InsStr(HE_InsertType type)
{
switch(type)
{
case HE_NOT_INSERTED: return UNI_L("HE_NOT_INSERTED");
case HE_INSERTED_BY_DOM: return UNI_L("HE_INSERTED_BY_DOM");
case HE_INSERTED_BY_PARSE_AHEAD: return UNI_L("HE_INSERTED_BY_PARSE_AHEAD");
case HE_INSERTED_BY_LAYOUT: return UNI_L("HE_INSERTED_BY_LAYOUT");
case HE_INSERTED_BY_CSS_IMPORT: return UNI_L("HE_INSERTED_BY_CSS_IMPORT");
#ifdef SVG_SUPPORT
case HE_INSERTED_BY_SVG: return UNI_L("HE_INSERTED_BY_SVG");
#endif
};
return UNI_L("");
}
void HTML_Element::DumpDebugTree(int level)
{
#ifdef WIN32
if (level == 0)
OutputDebugString(UNI_L("\n---------------------\n"));
#endif // WIN32
uni_char line[2000]; /* ARRAY OK 2009-05-07 stighal */
if (level > 1000)
level = 1000;
for(int i = 0; i < level; i++)
line[i] = ' ';
const uni_char* tmptypename = HTM_Lex::GetTagString(Type());
if (Type() == HE_TEXT)
tmptypename = UNI_L("TEXT");
else if (!tmptypename)
tmptypename = UNI_L("UNKNOWN");
if (Type() == HE_TEXT)
uni_snprintf(&line[level], 2000 - level, UNI_L("%s %p: \"%s\" %s\n"), tmptypename, this, TextContent(), InsStr(GetInserted()));
else
uni_snprintf(&line[level], 2000 - level, UNI_L("%s %p %s\n"), tmptypename, this, InsStr(GetInserted()));
#ifdef WIN32
OutputDebugString(line);
#endif // WIN32
HTML_Element* tmp = FirstChild();
while(tmp)
{
tmp->DumpDebugTree(level + 2);
tmp = (HTML_Element*) tmp->Suc();
}
}
#endif
#define DOM_LOWERCASE_NAME(name, name_length) \
AutoTempBuffer lowercase_buf; \
if (!case_sensitive && name_length) \
{ \
RETURN_IF_MEMORY_ERROR(lowercase_buf->Expand(name_length + 1)); \
for (const uni_char *c = name; *c; c++) \
lowercase_buf->Append(uni_tolower(*c)); \
lowercase_buf->SetCachedLengthPolicy(TempBuffer::UNTRUSTED); \
lowercase_buf->Append(static_cast<uni_char>(0)); \
name = lowercase_buf->GetStorage(); \
}
OP_STATUS HTML_Element::SetAttribute(const DocumentContext &context, Markup::AttrType attr, const uni_char *name, int ns_idx, const uni_char *value, unsigned value_length, ES_Thread *thread, BOOL case_sensitive, BOOL is_id, BOOL is_specified)
{
/* Either ATTR_XML and a name, or not ATTR_XML and no name. */
OP_ASSERT((attr == ATTR_XML) == (name != NULL));
LogicalDocument *logdoc = context.logdoc;
HLDocProfile *hld_profile = context.hld_profile;
unsigned name_length = name ? uni_strlen(name) : 0;
DOM_LOWERCASE_NAME(name, name_length);
int index;
if (ns_idx == NS_IDX_HTML)
index = FindHtmlAttrIndex(attr, name);
else
index = FindAttrIndex(attr, name, ns_idx, case_sensitive, TRUE);
if (index != -1)
{
/* We shouldn't find another attribute type unless attr == ATTR_XML. */
OP_ASSERT(attr == ATTR_XML || attr == GetAttrItem(index));
attr = GetAttrItem(index);
ns_idx = GetAttrNs(index);
}
else
{
if (ns_idx == NS_IDX_ANY_NAMESPACE)
ns_idx = NS_IDX_DEFAULT;
if (attr == ATTR_XML)
attr = htmLex->GetAttrType(name, name_length, g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx)), case_sensitive);
}
int resolved_ns_idx = ResolveNsIdx(ns_idx);
BOOL is_same_value = index != -1 && IsSameAttrValue(index, name, value);
OP_STATUS status = BeforeAttributeChange(context, thread, index, attr, resolved_ns_idx, is_same_value);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsError(status))
// Script was not allowed to change the attribute.
return OpStatus::OK;
// If it's the same value then we don't need to set it at all, except if the
// old value was owned by someone else (ITEM_TYPE_NUM and ITEM_TYPE_BOOL is
// never owned by someone else).
if (!is_same_value || GetItemType(index) != ITEM_TYPE_NUM && GetItemType(index) != ITEM_TYPE_BOOL && !GetItemFree(index))
{
HtmlAttrEntry entry;
entry.attr = attr;
entry.is_id = is_id;
entry.is_specified = is_specified;
entry.ns_idx = ns_idx;
entry.value = value;
entry.value_len = value_length;
entry.name = name;
entry.name_len = name_length;
void *attr_value;
ItemType attr_item_type;
BOOL attr_need_free;
BOOL attr_is_event;
RETURN_IF_ERROR(ConstructAttrVal(hld_profile, &entry, FALSE, attr_value, attr_item_type, attr_need_free, attr_is_event));
if (attr_item_type != ITEM_TYPE_UNDEFINED || index != -1)
{
if (index != -1 && GetAttrIsEvent(index) && logdoc)
/* ConstructAttrVal will have called AddEventHandler, so if we're overwriting
an existing event handler attribute, we should remove one as well. */
logdoc->RemoveEventHandler(GetEventType(attr, ns_idx));
if (attr_item_type != ITEM_TYPE_UNDEFINED)
if (index != -1)
ReplaceAttrLocal(index, entry.attr, attr_item_type, attr_value, ns_idx, attr_need_free, FALSE, entry.is_id, entry.is_specified, attr_is_event);
else
index = SetAttr(entry.attr, attr_item_type, attr_value, attr_need_free, ns_idx, TRUE, entry.is_id, entry.is_specified, attr_is_event, -1, case_sensitive);
else
RemoveAttrAtIdx(index);
if (hld_profile && GetNsType() == NS_HTML)
{
// FIXME: Move to HandleAttributeChange (unless it needs to run before ApplyPropertyChanges).
HTML_ElementType type = Type();
if (type == HE_OBJECT || type == HE_EMBED || type == HE_APPLET)
{
if (PrivateAttrs *pa = (PrivateAttrs*)GetSpecialAttr(ATTR_PRIVATE, ITEM_TYPE_PRIVATE_ATTRS, (void*)NULL, SpecialNs::NS_LOGDOC))
{
if (!entry.name && entry.attr)
{
entry.name = HTM_Lex::GetAttributeString(static_cast<Markup::AttrType>(entry.attr), NS_HTML);
entry.name_len = uni_strlen(entry.name);
}
RETURN_IF_MEMORY_ERROR(pa->SetAttribute(hld_profile, Type(), entry));
}
}
}
// Only called for changed attributes
status = HandleAttributeChange(context, thread, index, static_cast<Markup::AttrType>(entry.attr), ns_idx);
}
}
// Must always be called if BeforeAttributeChange was called
OP_STATUS status2 = AfterAttributeChange(context, thread, index, attr, ns_idx, is_same_value);
return OpStatus::IsError(status) ? status : status2;
}
#ifdef DOCUMENT_EDIT_SUPPORT
OP_STATUS HTML_Element::SetStringHtmlAttribute(FramesDocument *frames_doc, ES_Thread *thread, Markup::AttrType attr, const uni_char *value)
{
// This function uses NS_IDX_DEFAULT in a way that assumes this is an HTML element.
OP_ASSERT(GetNsType() == NS_HTML);
return SetAttribute(frames_doc, attr, NULL, NS_IDX_DEFAULT, value, uni_strlen(value), thread, FALSE, attr == ATTR_ID);
}
OP_STATUS HTML_Element::EnableContentEditable(FramesDocument* frames_doc)
{
OP_ASSERT(IsContentEditable());
// Avoid setting focus to the editable element
g_input_manager->LockKeyboardInputContext(TRUE);
OP_STATUS oom = frames_doc->SetEditable(FramesDocument::CONTENTEDITABLE);
g_input_manager->LockKeyboardInputContext(FALSE);
if (OpStatus::IsError(oom))
return oom;
if (frames_doc->GetDocumentEdit())
{
HTML_Element *body = frames_doc->GetDocumentEdit()->GetBody();
if (body)
{
if (this->IsAncestorOf(body))
frames_doc->GetDocumentEdit()->InitEditableRoot(body);
else
frames_doc->GetDocumentEdit()->InitEditableRoot(this);
}
}
return OpStatus::OK;
}
void HTML_Element::DisableContentEditable(FramesDocument *frames_doc)
{
if (frames_doc->GetDocumentEdit())
frames_doc->GetDocumentEdit()->UninitEditableRoot(this);
if (!frames_doc->GetDesignMode())
{
// If no element is editable anymore, we can disable editing in this document.
BOOL has_editable_content = FALSE;
HTML_Element* elm = frames_doc->GetDocRoot();
while(elm)
{
if (elm->IsContentEditable())
{
has_editable_content = TRUE;
break;
}
elm = elm->Next();
}
if (!has_editable_content)
frames_doc->SetEditable(FramesDocument::CONTENTEDITABLE_OFF);
}
}
#endif // DOCUMENT_EDIT_SUPPORT
static BOOL IsLengthAttribute(HTML_ElementType type, short attr)
{
if (attr == ATTR_WIDTH)
return (type == HE_HR || type == HE_OBJECT || type == HE_APPLET || type == HE_TABLE ||
type == HE_COLGROUP || type == HE_COL || type == HE_TR || type == HE_TD || type == HE_TH || type == HE_IFRAME || type == HE_VIDEO);
else if (attr == ATTR_HEIGHT)
return type == HE_OBJECT || type == HE_APPLET || type == HE_TR || type == HE_TD || type == HE_TH || type == HE_IFRAME || type == HE_VIDEO;
else if (attr == ATTR_HSPACE || attr == ATTR_VSPACE)
return type == HE_OBJECT || type == HE_APPLET;
else if (attr == ATTR_BORDER || attr == ATTR_CELLPADDING || attr == ATTR_CELLSPACING)
return type == HE_TABLE;
else if (attr == ATTR_CHAROFF)
return (type == HE_COLGROUP || type == HE_COL || type == HE_THEAD || type == HE_TFOOT || type == HE_TBODY ||
type == HE_TR || type == HE_TD || type == HE_TH);
else
return FALSE;
}
static BOOL IsUrlAttribute(HTML_ElementType type, short attr)
{
if (attr == ATTR_HREF)
return type == HE_A || type == HE_AREA || type == HE_BASE || type == HE_LINK;
else if (attr == ATTR_SRC)
return type == HE_INPUT || type == HE_IMG || type == HE_SCRIPT || type == HE_FRAME || type == HE_IFRAME || type == HE_AUDIO || type == HE_VIDEO || type == HE_SOURCE || type == HE_EMBED || type == Markup::HTE_TRACK;
else if (attr == ATTR_DATA)
return type == HE_OBJECT;
else if (attr == ATTR_CITE)
return type == HE_BLOCKQUOTE || type == HE_Q || type == HE_DEL || type == HE_INS;
else if (attr == ATTR_LONGDESC)
return type == HE_IMG || type == HE_FRAME || type == HE_IFRAME;
else if (attr == ATTR_CODEBASE)
return type == HE_OBJECT || type == HE_APPLET;
else if (attr == ATTR_POSTER)
return type == HE_VIDEO;
else if (attr == ATTR_ITEMID)
return TRUE;
else if (attr == ATTR_MANIFEST)
return type == HE_HTML;
else if (attr == ATTR_ACTION)
return type == HE_FORM;
else
return FALSE;
}
int HTML_Element::GetAttributeCount()
{
if (!Markup::IsRealElement(Type()))
return 0;
return GetAttrCount();
}
OP_STATUS HTML_Element::GetAttributeName(FramesDocument *frames_doc, int index, TempBuffer *buffer, const uni_char *&name, int &ns_idx, BOOL *specified, BOOL *id)
{
int attr_index = 0;
while (index >= 0 && attr_index < GetAttrSize())
{
if (!GetAttrIsSpecial(attr_index++))
--index;
}
--attr_index;
OP_STATUS status = OpStatus::OK;
if (index >= 0)
{
// There wasn't that many attributes
name = NULL;
ns_idx = NS_IDX_DEFAULT;
}
else
{
Markup::AttrType item = GetAttrItem(attr_index);
if (item != ATTR_XML)
name = HTM_Lex::GetAttributeString(item, g_ns_manager->GetNsTypeAt(GetResolvedAttrNs(attr_index)));
else
name = (const uni_char *) GetValueItem(attr_index);
ns_idx = GetAttrNs(attr_index);
if (specified)
*specified = GetAttrIsSpecified(attr_index);
if (id)
*id = GetAttrIsId(attr_index);
}
return status;
}
const uni_char *HTML_Element::GetAttribute(FramesDocument *frames_doc, int attr, const uni_char *name, int ns_idx, BOOL case_sensitive, TempBuffer *buffer, BOOL resolve_urls, int at_known_index)
{
int index = at_known_index;
if (index == -1)
if (ns_idx == NS_IDX_HTML)
index = FindHtmlAttrIndex(attr, name);
else
index = FindAttrIndex(attr, name, ns_idx, case_sensitive, FALSE);
const uni_char *value = NULL;
if (index != -1)
{
if (attr == ATTR_XML)
attr = GetAttrItem(index);
ns_idx = GetResolvedAttrNs(index);
BOOL is_html = g_ns_manager->GetNsTypeAt(ns_idx) == NS_HTML;
if (attr != ATTR_XML && is_html)
{
const uni_char *value = GetAttrValue(attr, NS_IDX_HTML, Type(), FALSE, buffer, index);
if (value)
{
if (resolve_urls)
{
LogicalDocument* logdoc = frames_doc ? frames_doc->GetLogicalDocument() : NULL;
if (IsUrlAttribute(Type(), attr))
{
URL *href_url = GetUrlAttr(attr, NS_IDX_HTML, logdoc);
return href_url ? href_url->GetAttribute(URL::KUniName_With_Fragment_Escaped).CStr() : NULL;
}
else if (attr == ATTR_BACKGROUND && Type() == HE_BODY)
{
// Stored as a StyleAttribute, so GetUrlAttr() will not work.
URL bg_url = ResolveUrl(value, logdoc, ATTR_BACKGROUND);
OpString bg_url_str;
if (!bg_url.IsEmpty() &&
OpStatus::IsSuccess(bg_url.GetAttribute(URL::KUniName_With_Fragment_Escaped, bg_url_str)))
{
buffer->Clear();
OpStatus::Ignore(buffer->Append(bg_url_str));
value = buffer->GetStorage();
}
}
}
return value;
}
}
else
{
if (attr != ATTR_XML)
attr = ATTR_ID; // arbitrary attribute that will cause no conversion in GetAttrValueValue.
value = GetAttrValueValue(index, attr, HE_ANY, buffer);
}
}
return value;
}
BOOL HTML_Element::HasAttribute(const uni_char* attr_name, int ns_idx)
{
Markup::AttrType attr = Markup::HA_XML;
NS_Type ns_type = ns_idx == NS_IDX_ANY_NAMESPACE ? NS_USER : g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (ns_type != NS_USER && Type() != Markup::HTE_UNKNOWN)
attr = HTM_Lex::GetAttrType(attr_name, ns_type, FALSE);
return FindAttrIndex(attr, attr_name, ns_idx, FALSE) != ATTR_NOT_FOUND;
}
BOOL
HTML_Element::AreAttributesEqual(short attr, ItemType attr_item_type, void *left, void *right)
{
BOOL is_same_value = FALSE;
switch (attr_item_type)
{
case ITEM_TYPE_BOOL:
is_same_value = !right == !left;
break;
case ITEM_TYPE_NUM:
is_same_value = (long) right == (long) left;
break;
case ITEM_TYPE_NUM_AND_STRING:
is_same_value = *static_cast<INTPTR*>(left) == *static_cast<INTPTR*>(right) &&
uni_str_eq(reinterpret_cast<uni_char*>(static_cast<char*>(left) + sizeof(INTPTR)), reinterpret_cast<uni_char*>(static_cast<char*>(right) + sizeof(INTPTR)));
break;
case ITEM_TYPE_STRING:
if (attr == ATTR_XML)
{
const uni_char* new_name_value = static_cast<const uni_char *>(right);
const uni_char* old_name_value = static_cast<const uni_char *>(left);
int value_offset = uni_strlen(new_name_value) + 1;
OP_ASSERT(uni_stricmp(new_name_value, old_name_value)==0); // Same attribute name
is_same_value = uni_str_eq(new_name_value + value_offset, old_name_value + value_offset);
}
else
is_same_value = uni_str_eq(static_cast<const uni_char *>(right), static_cast<const uni_char *>(left));
break;
case ITEM_TYPE_URL_AND_STRING:
{
UrlAndStringAttr *old_attr = static_cast<UrlAndStringAttr*>(left);
UrlAndStringAttr *new_attr = static_cast<UrlAndStringAttr*>(right);
if (old_attr->GetString() && new_attr->GetString())
is_same_value = uni_str_eq(old_attr->GetString(), new_attr->GetString());
}
break;
case ITEM_TYPE_COMPLEX:
{
ComplexAttr* left_complex_attr = static_cast<ComplexAttr*>(left);
ComplexAttr* right_complex_attr = static_cast<ComplexAttr*>(right);
if (!left_complex_attr || !right_complex_attr)
is_same_value = left_complex_attr == right_complex_attr;
else
is_same_value = right_complex_attr->Equals(left_complex_attr);
}
break;
}
return is_same_value;
}
// Search for the parent of the option, first among the
// option parents and then optionally in another tree, that's
// supposed to be the previous parents of the option.
static HTML_Element* FindOptionParent(HTML_Element* option, HTML_Element* parent_tree = NULL)
{
OP_ASSERT(option->IsMatchingType(HE_OPTION, NS_HTML) || option->IsMatchingType(HE_OPTGROUP, NS_HTML));
HTML_Element* parent = option;
for (;;)
{
parent = parent->Parent();
if (!parent)
{
if (parent_tree)
{
parent = parent_tree;
parent_tree = NULL;
}
else
{
break;
}
}
BOOL is_option_parent =
parent->IsMatchingType(HE_SELECT, NS_HTML) ||
parent->IsMatchingType(HE_DATALIST, NS_HTML);
if (is_option_parent)
{
break;
}
}
return parent;
}
OP_STATUS HTML_Element::HandleDocumentTreeChange(const DocumentContext &context, HTML_Element *parent, HTML_Element *child, ES_Thread *thread, BOOL added)
{
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
HLDocProfile *hld_profile = context.hld_profile;
DOM_Environment *environment = context.environment;
BOOL chardata_changed = FALSE;
OpVector<HTML_Element> changed_radio_buttons;
HTML_Element *iter = child, *stop = (HTML_Element *) child->NextSibling();
while (iter != stop)
{
BOOL skip_children = FALSE;
if (iter->IsText() || iter->Type() == HE_COMMENT)
{
chardata_changed = TRUE;
#ifdef DISPLAY_WRITINGSYSTEM_HEURISTIC
// analyze text to detect writing system
if (added && hld_profile)
hld_profile->AnalyzeText(iter);
#endif // DISPLAY_WRITINGSYSTEM_HEURISTIC
}
else if (iter->IsScriptElement())
{
skip_children = TRUE;
if (added)
{
int handled = iter->GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
/* Script already executed?. */
BOOL handle_script_element = (handled & SCRIPT_HANDLED_EXECUTED) == 0;
if (handle_script_element && environment)
{
#ifdef USER_JAVASCRIPT
if (environment->IsHandlingScriptElement(this))
handle_script_element = FALSE;
else
#endif // USER_JAVASCRIPT
if (environment->SkipScriptElements())
handle_script_element = FALSE;
}
if (handle_script_element)
RETURN_IF_ERROR(iter->HandleScriptElement(hld_profile, thread, TRUE, FALSE));
}
else if (hld_profile)
{
// This will abort the script if it should be aborted, otherwise do nothing.
// If it's an external script that hasn't loaded, we will have killed the
// inline load so in that case it's essential that CancelInlineScript
// does something or we will wait forever.
RETURN_IF_ERROR(hld_profile->GetESLoadManager()->CancelInlineScript(iter));
}
}
else if (iter->IsStyleElement())
{
if (hld_profile)
{
if (!added)
iter->RemoveCSS(context);
else
RETURN_IF_ERROR(iter->LoadStyle(context, FALSE));
}
}
else if (iter->GetNsType() == NS_HTML)
{
if (added)
{
#ifdef DOCUMENT_EDIT_SUPPORT
if (iter->IsContentEditable())
RETURN_IF_ERROR(iter->EnableContentEditable(frames_doc));
else
#endif // DOCUMENT_EDIT_SUPPORT
{
if (iter->IsFormElement())
{
FormValue* form_value = iter->GetFormValue();
form_value->SetMarkedPseudoClasses(form_value->CalculateFormPseudoClasses(frames_doc, iter));
#if defined(WAND_SUPPORT) && defined(PREFILLED_FORM_WAND_SUPPORT)
if (iter->IsMatchingType(HE_INPUT, NS_HTML))
{
if (g_wand_manager->HasMatch(frames_doc, iter))
{
if (thread)
frames_doc->AddPendingWandElement(iter, thread->GetRunningRootThread());
else
{
frames_doc->SetHasWandMatches(TRUE);
g_wand_manager->InsertWandDataInDocument(frames_doc, iter, NO);
}
}
}
#endif // defined(WAND_SUPPORT) && defined(PREFILLED_FORM_WAND_SUPPORT)
}
}
}
#ifdef ACCESS_KEYS_SUPPORT
if (hld_profile && iter->HasAttr(Markup::HA_ACCESSKEY))
{
const uni_char *key = iter->GetAccesskey();
if (key)
if (added)
hld_profile->AddAccessKey(key, iter);
else
hld_profile->RemoveAccessKey(key, iter);
}
#endif // ACCESS_KEYS_SUPPORT
switch (iter->Type())
{
case HE_TITLE:
RETURN_IF_ERROR(iter->HandleCharacterDataChange(context, thread, added));
skip_children = TRUE;
break;
case HE_BODY:
if (hld_profile && parent->IsMatchingType(HE_HTML, NS_HTML))
if (added)
{
if (!hld_profile->GetBodyElm() || iter->Precedes(hld_profile->GetBodyElm()))
hld_profile->SetBodyElm(iter);
}
else if (iter == hld_profile->GetBodyElm())
hld_profile->ResetBodyElm();
break;
case HE_PROCINST:
case HE_LINK:
if (hld_profile && iter->IsLinkElement())
if (added)
RETURN_IF_ERROR(hld_profile->HandleLink(iter));
else
{
RETURN_IF_ERROR(frames_doc->CleanInline(iter));
hld_profile->RemoveLink(iter);
}
break;
case HE_IFRAME:
if (added)
{
RETURN_IF_MEMORY_ERROR(hld_profile->HandleNewIFrameElementInTree(iter, thread));
skip_children = TRUE;
}
else
{
// Removed an iframe.
OP_STATUS onloadstatus;
if (thread)
onloadstatus = frames_doc->ScheduleAsyncOnloadCheck(thread);
else
onloadstatus = FramesDocument::CheckOnLoad(frames_doc, NULL);
if (OpStatus::IsError(onloadstatus))
return OpStatus::ERR_NO_MEMORY;
}
break;
case HE_OPTION:
case HE_OPTGROUP:
{
HTML_Element* select = FindOptionParent(iter, parent);
if (select && select->IsMatchingType(HE_SELECT, NS_HTML))
{
FormValueList* formvalue = FormValueList::GetAs(select->GetFormValue());
formvalue->HandleOptionListChanged(frames_doc, select, iter, added);
}
}
break;
case HE_INPUT:
if (added && // removals are handled earlier, in OutSafe
iter->GetInputType() == INPUT_RADIO)
{
OpStatus::Ignore(changed_radio_buttons.Add(iter)); // We want to continue processing changes even if this fails
}
break;
case HE_BASE:
if (URL *url = iter->GetUrlAttr(ATTR_HREF, NS_IDX_HTML, logdoc))
hld_profile->SetBaseURL(url, iter->GetStringAttr(ATTR_HREF, NS_IDX_HTML));
break;
#if defined JS_PLUGIN_SUPPORT || defined MANUAL_PLUGIN_ACTIVATION
case HE_OBJECT:
# ifdef JS_PLUGIN_SUPPORT
if (DOM_Object *dom_obj = iter->GetESElement())
if (ES_Object *plugin_obj = DOM_Utils::GetJSPluginObject(dom_obj))
{
EcmaScript_Object *hostobject = ES_Runtime::GetHostObject(plugin_obj);
if (added)
static_cast<JS_Plugin_HTMLObjectElement_Object *>(hostobject)->Inserted();
else
static_cast<JS_Plugin_HTMLObjectElement_Object *>(hostobject)->Removed();
}
# endif // JS_PLUGIN_SUPPORT
# ifdef MANUAL_PLUGIN_ACTIVATION
// Fall through.
case HE_APPLET:
case HE_EMBED:
if (thread && ES_Runtime::GetIsExternal(thread->GetContext()))
iter->SetPluginExternal(TRUE);
# endif // MANUAL_PLUGIN_ACTIVATION
break;
#endif // JS_PLUGIN_SUPPORT || MANUAL_PLUGIN_ACTIVATION
case HE_IMG:
if (added)
{
// Looks like the page wants to load an image (and
// since it might be hidden we do it here rather than in layout)
URL image_url = iter->GetImageURL(FALSE, logdoc);
if (!image_url.IsEmpty())
frames_doc->LoadInline(&image_url, iter, IMAGE_INLINE);
}
break;
#ifdef MEDIA_HTML_SUPPORT
case Markup::HTE_TRACK:
// For <track> elements we only need to notify the
// MediaElement if it is the root of the changed
// subtree.
if (iter != child)
break;
// Fall through.
case HE_AUDIO:
case HE_VIDEO:
case HE_SOURCE:
{
HTML_Element* media_elm = iter;
if (iter->Type() == Markup::HTE_SOURCE || iter->Type() == Markup::HTE_TRACK)
{
media_elm = iter->ParentActual();
if (!media_elm)
{
OP_ASSERT(iter->Type() == Markup::HTE_SOURCE || iter->Type() == Markup::HTE_TRACK);
media_elm = parent;
if (!parent->IsIncludedActual())
media_elm = media_elm->ParentActual();
OP_ASSERT(media_elm);
}
}
if (MediaElement* media = media_elm->GetMediaElement())
RETURN_IF_ERROR(media->HandleElementChange(iter, added, thread));
break;
}
#endif // MEDIA_HTML_SUPPORT
case HE_META:
iter->CheckMetaElement(context, iter->ParentActual(), added);
if (added && frames_doc->IsLoaded(TRUE))
RETURN_IF_ERROR(frames_doc->CheckRefresh());
break;
#ifdef JS_PLUGIN_SUPPORT
case HE_PARAM:
if (parent)
{
JS_Plugin_Object* jso = parent->GetJSPluginObject();
if (jso)
{
const uni_char* name = iter->GetPARAM_Name();
if (!name)
break;
const uni_char* value = NULL;
if (added)
value = iter->GetPARAM_Value();
jso->ParamSet(name, value);
}
}
break;
# endif // JS_PLUGIN_SUPPORT
}
}
#ifdef DNS_PREFETCHING
if (added)
{
URL anchor_url = iter->GetAnchor_URL(frames_doc);
if (!anchor_url.IsEmpty())
logdoc->DNSPrefetch(anchor_url, DNS_PREFETCH_DYNAMIC);
}
#endif // DNS_PREFETCHING
if (skip_children)
iter = (HTML_Element *) iter->NextSibling();
else
iter = (HTML_Element *) iter->Next();
}
RETURN_IF_ERROR(hld_profile->GetLayoutWorkplace()->HandleDocumentTreeChange(parent, child, added));
#ifdef SVG_SUPPORT
g_svg_manager->OnSVGDocumentChanged(frames_doc, parent, child, added);
#endif // defined(SVG_SUPPORT)
if (added && // removals are handled earlier, in OutSafe
changed_radio_buttons.GetCount() > 0)
{
RETURN_IF_ERROR(FormManager::HandleChangedRadioGroups(frames_doc, changed_radio_buttons, added));
}
if (chardata_changed)
return parent->HandleCharacterDataChange(context, thread, added, FALSE);
else
return OpStatus::OK;
}
OP_STATUS HTML_Element::HandleCharacterDataChange(const DocumentContext &context, ES_Thread *thread, BOOL added, BOOL update_pseudo_elm)
{
FramesDocument *frames_doc = context.frames_doc;
HLDocProfile *hld_profile = context.hld_profile;
#ifdef USER_JAVASCRIPT
DOM_Environment *environment = context.environment;
#endif // USER_JAVASCRIPT
HTML_Element *element = this;
#ifdef SVG_SUPPORT
BOOL is_change_inside_svg = (element->GetNsType() == NS_SVG);
#endif // SVG_SUPPORT
while (element)
{
if (element->IsStyleElement())
{
if (hld_profile)
RETURN_IF_ERROR(LoadStyle(context, FALSE));
}
else if (element->IsScriptElement())
{
// When script text is added to an empty script that hasn't
// previously been run and has no src/xlink:href attribute, that script
// should be run.
if (!added)
return OpStatus::OK;
if (URL* url = element->GetScriptURL(*hld_profile->GetURL(), hld_profile->GetLogicalDocument()))
if (url->Type() != URL_NULL_TYPE)
return OpStatus::OK;
if (DataSrc* src_head = element->GetDataSrc())
src_head->DeleteAll();
int handled = element->GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
/* Script already executed?. */
BOOL already_executed = (handled & SCRIPT_HANDLED_EXECUTED) != 0;
if (!already_executed)
{
#ifdef USER_JAVASCRIPT
if (environment && environment->IsHandlingScriptElement(element))
return OpStatus::OK;
#endif // USER_JAVASCRIPT
RETURN_IF_ERROR(element->HandleScriptElement(hld_profile, thread, TRUE, FALSE));
}
}
else if (element->GetNsType() == NS_HTML)
{
switch (element->Type())
{
case HE_OPTION:
{
HTML_Element *select = FindOptionParent(element);
if (select)
if (SelectionObject *selection_object = (SelectionObject *) select->GetFormObject())
{
HTML_Element *iter = (HTML_Element *) element->Prev();
int index = 0;
while (iter != select)
{
if (iter->Type() == HE_OPTION)
++index;
iter = (HTML_Element *) iter->Prev();
}
BOOL selected = selection_object->IsSelected(index);
BOOL disabled = selection_object->IsDisabled(index);
if (index < selection_object->GetElementCount()) // The element hasn't been added to the select yet.
{
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Expand(element->GetTextContentLength() + 1));
element->GetTextContent(buffer.GetStorage(), buffer.GetCapacity());
RETURN_IF_ERROR(selection_object->ChangeElement(buffer.GetStorage(), selected, disabled, index));
selection_object->ChangeSizeIfNeeded();
}
}
}
break;
case HE_TITLE:
if (Window *window = frames_doc->GetWindow())
RETURN_IF_ERROR(window->UpdateTitle());
break;
case HE_TEXTAREA:
FormValue *formvalue = element->GetFormValue();
if (!formvalue->IsChangedFromOriginalByUser(element))
RETURN_IF_ERROR(formvalue->ResetToDefault(element));
break;
}
}
#ifdef SVG_SUPPORT
else if (element->IsMatchingType(Markup::SVGE_TITLE, NS_SVG))
{
if (Window *window = frames_doc->GetWindow())
RETURN_IF_ERROR(window->UpdateTitle());
break;
}
#endif // SVG_SUPPORT
element = element->Parent();
}
#ifdef SVG_SUPPORT
if(is_change_inside_svg)
{
g_svg_manager->HandleCharacterDataChanged(frames_doc, this);
}
#endif // SVG_SUPPORT
if (update_pseudo_elm && GetUpdatePseudoElm() && hld_profile)
{
RETURN_IF_ERROR(hld_profile->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_UNKNOWN, TRUE));
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::BeforeAttributeChange(const DocumentContext &context, ES_Thread *thread, int attr_idx, short attr, int ns_idx, BOOL is_same_value)
{
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
#if defined ACCESS_KEYS_SUPPORT || defined CSS_VIEWPORT_SUPPORT
HLDocProfile *hld_profile = context.hld_profile;
#endif
BOOL name_or_id_changed = FALSE;
if (g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx)) == NS_HTML)
{
if (!is_same_value)
{
if ((attr == ATTR_NAME
|| attr == ATTR_TYPE
|| attr == ATTR_FORM)
&& IsMatchingType(HE_INPUT, NS_HTML) && GetInputType() == INPUT_RADIO)
{
// Unregister from current radio group
// Changing radio group
if (logdoc)
logdoc->GetRadioGroups().UnregisterFromRadioGroup(frames_doc, this);
}
else if (attr == ATTR_TYPE && IsMatchingType(HE_INPUT, NS_HTML) && GetInputType() == INPUT_FILE)
{
// Clear value when setting from file input to something else
FormValue* old_form_value = GetFormValue();
OP_ASSERT(old_form_value); // Every HE_INPUT must have a FormValue
old_form_value->SetValueFromText(this, NULL);
}
else if (attr == ATTR_ID && IsMatchingType(HE_FORM, NS_HTML))
{
// Any radio buttons anywhere using ATTR_FORM to connect to this
// form will/might become free radio buttons
if (logdoc)
logdoc->GetRadioGroups().UnregisterAllRadioButtonsConnectedByName(this);
// This must be followed by a rebuilding of the radio groups
}
#ifdef ACCESS_KEYS_SUPPORT
else if (attr == ATTR_ACCESSKEY)
{
const uni_char *key = GetAccesskey();
if (key && hld_profile)
hld_profile->RemoveAccessKey(key, this);
}
#endif // ACCESS_KEYS_SUPPORT
#ifdef CSS_VIEWPORT_SUPPORT
else if (attr == ATTR_NAME && attr_idx != -1 && IsMatchingType(HE_META, NS_HTML))
{
if (GetItemType(attr_idx) == ITEM_TYPE_STRING)
{
const uni_char* old_name = static_cast<uni_char*>(GetValueItem(attr_idx));
if (old_name && uni_stri_eq(old_name, "VIEWPORT"))
{
CSS_ViewportMeta* vp_meta = GetViewportMeta(context, FALSE);
if (vp_meta)
{
if (hld_profile)
hld_profile->GetCSSCollection()->RemoveCollectionElement(this);
RemoveSpecialAttribute(ATTR_VIEWPORT_META, SpecialNs::NS_STYLE);
}
}
}
}
#endif // CSS_VIEWPORT_SUPPORT
else if (attr == ATTR_HREF && IsMatchingType(HE_LINK, NS_HTML) && GetCSS())
{
// Need to remove the stylesheet from the CSSCollection before the url
// attribute changes because the skip-optimization in CSSCollection
// uses the url attribute to check the origin of the stylesheet being
// removed.
RemoveCSS(context);
}
}
if (attr == ATTR_SRC)
{
if (IsMatchingType(HE_SCRIPT, NS_HTML))
{
BOOL in_document = FALSE;
if (logdoc)
{
HTML_Element *root = logdoc->GetRoot();
if (root && root->IsAncestorOf(this))
in_document = TRUE;
}
if (in_document && !HasSpecialAttr(Markup::LOGA_ORIGINAL_SRC, SpecialNs::NS_LOGDOC))
{
URL *old_src_url = GetUrlAttr(Markup::HA_SRC, NS_IDX_HTML, logdoc);
if (old_src_url)
{
URL *original_src_url = OP_NEW(URL, (*old_src_url));
if (!original_src_url || SetSpecialAttr(Markup::LOGA_ORIGINAL_SRC, ITEM_TYPE_URL, original_src_url, TRUE, SpecialNs::NS_LOGDOC) == -1)
{
OP_DELETE(original_src_url);
return OpStatus::ERR_NO_MEMORY;
}
}
}
}
#ifdef MEDIA_HTML_SUPPORT
else if (IsMatchingType(Markup::HTE_TRACK, NS_HTML))
{
URL* track_url = GetUrlAttr(Markup::HA_SRC, NS_IDX_HTML, logdoc);
if (track_url && frames_doc)
frames_doc->StopLoadingInline(track_url, this, TRACK_INLINE);
}
#endif // MEDIA_HTML_SUPPORT
else
{
URL old_url = logdoc ? GetImageURL(TRUE, logdoc) : URL();
if (frames_doc)
frames_doc->StopLoadingInline(&old_url, this, IMAGE_INLINE, TRUE);
}
}
else if (attr == ATTR_NAME && !is_same_value)
name_or_id_changed = TRUE;
#ifdef JS_PLUGIN_SUPPORT
if (Type() == HE_PARAM && attr == ATTR_NAME && Parent() && !is_same_value)
{
JS_Plugin_Object* jso = Parent()->GetJSPluginObject();
if (jso)
{
const uni_char* name = GetPARAM_Name();
if (name)
jso->ParamSet(name, NULL);
}
}
#endif //JS_PLUGIN_SUPPORT
}
if (attr_idx != -1 && GetAttrIsId(attr_idx) && !is_same_value)
name_or_id_changed = TRUE;
if (name_or_id_changed && logdoc)
return logdoc->RemoveNamedElement(this, FALSE);
else
return OpStatus::OK;
}
OP_STATUS HTML_Element::AfterAttributeChange(const DocumentContext &context, ES_Thread *thread, int attr_idx, short attr, int ns_idx, BOOL is_same_value)
{
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
DOM_Environment *environment = context.environment;
NS_Type ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
HTML_Element *root = logdoc ? logdoc->GetRoot() : NULL;
BOOL is_in_document = root && root->IsAncestorOf(this);
if (frames_doc && logdoc)
{
// First a block of things that should be done regardless of whether
// the change is in a document fragment or in the real document
if (ns == NS_HTML && GetNsType() == NS_HTML)
{
HTML_ElementType type = Type();
// These should always run, regardless of the document we're in or if we're a fragment.
if (attr == ATTR_SRC)
{
if (type == HE_IMG || type == HE_INPUT && GetInputType() == INPUT_IMAGE)
{
HEListElm *helistelm = GetHEListElmForInline(IMAGE_INLINE);
if (helistelm)
helistelm->ResetEventSent();
if (GetSpecialBoolAttr(ATTR_INLINE_ONLOAD_SENT, SpecialNs::NS_LOGDOC))
SetSpecialBoolAttr(ATTR_INLINE_ONLOAD_SENT, FALSE, SpecialNs::NS_LOGDOC);
URL url = GetImageURL(TRUE, logdoc);
if (!url.IsEmpty() && frames_doc->GetLoadImages())
{
OP_LOAD_INLINE_STATUS load_status = frames_doc->LoadInline(&url, this, IMAGE_INLINE);
helistelm = GetHEListElmForInline(IMAGE_INLINE);
if (helistelm && !helistelm->GetLoadInlineElm())
{
// Remove dangling HEListElm since we did not load or started loading the image.
OP_DELETE(helistelm);
helistelm = NULL;
}
if (load_status == LoadInlineStatus::LOADING_REFUSED)
{
// Fake that we loaded it even though it was blocked (backwards compatible).
load_status = frames_doc->HandleEvent(ONLOAD, NULL, this, SHIFTKEY_NONE);
}
else if (load_status != LoadInlineStatus::LOADING_STARTED)
{
// if LOADING_STARTED then an event will be sent through normal channels
if (helistelm && !helistelm->GetEventSent())
load_status = helistelm->SendImageFinishedLoadingEvent(frames_doc);
}
RETURN_IF_MEMORY_ERROR(load_status);
}
else if (helistelm)
{
// Was kept around to keep old_url available but if we're to replace it with
// nothing we don't need or want it anymore
OP_DELETE(helistelm);
}
} // end if HE_IMG/INPUT_IMAGE
} // end if ATTR_SRC
#ifdef CANVAS_SUPPORT
if (Type() == HE_CANVAS && (attr == ATTR_WIDTH || attr == ATTR_HEIGHT))
{
Canvas* canvas = (Canvas*)GetSpecialAttr(Markup::VEGAA_CANVAS, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_OGP);
if (canvas)
{
int w, h;
if (attr == ATTR_WIDTH)
{
w = GetNumAttr(ATTR_WIDTH);
if (w <= 0)
w = 300;
h = canvas->GetHeight(this);
}
else
{
w = canvas->GetWidth(this);
h = GetNumAttr(ATTR_HEIGHT);
if (h <= 0)
h = 150;
}
RETURN_IF_ERROR(canvas->SetSize(w, h));
}
}
#endif // CANVAS_SUPPORT
#ifdef MEDIA_HTML_SUPPORT
if (Type() == HE_AUDIO || Type() == HE_VIDEO)
{
if (MediaElement* media = GetMediaElement())
RETURN_IF_ERROR(media->HandleAttributeChange(this, attr, thread));
}
else if (Type() == Markup::HTE_TRACK)
if (TrackElement* track_element = GetTrackElement())
RETURN_IF_ERROR(track_element->HandleAttributeChange(frames_doc, this, attr, thread));
#endif // MEDIA_HTML_SUPPORT
if (IsFormElement())
{
FormValue* form_value = GetFormValue();
form_value->SetMarkedPseudoClasses(form_value->CalculateFormPseudoClasses(frames_doc, this));
}
} // end if NS_HTML
}
BOOL name_or_id_changed = ns == NS_HTML && GetNsType() == NS_HTML && (attr == ATTR_ID || attr == ATTR_NAME);
if (!is_same_value && (name_or_id_changed || attr_idx != -1 && GetAttrIsId(attr_idx)))
{
if (environment)
environment->ElementCollectionStatusChanged(this, DOM_Environment::COLLECTION_NAME_OR_ID);
if (is_in_document)
{
RETURN_IF_ERROR(logdoc->AddNamedElement(this, FALSE));
#ifdef XML_EVENTS_SUPPORT
if (attr_idx != -1 && GetAttrIsId(attr_idx))
{
XML_Events_Registration *registration = frames_doc ? frames_doc->GetFirstXMLEventsRegistration() : NULL;
while (registration)
{
RETURN_IF_ERROR(registration->HandleIdChanged(frames_doc, this));
registration = static_cast<XML_Events_Registration *>(registration->Suc());
}
}
#endif // XML_EVENTS_SUPPORT
}
}
if (!is_in_document)
return OpStatus::OK;
OP_ASSERT(frames_doc && logdoc); // Since we're in the document
if (ns == NS_HTML && GetNsType() == NS_HTML)
{
// Whenever a script sets src on an iframe, it should be (re)loaded even
// if it's the same URL.
HTML_ElementType type = Type();
if (frames_doc->IsCurrentDoc() && (attr == ATTR_SRC && (type == HE_FRAME || type == HE_IFRAME) ||
attr == ATTR_DATA && (type == HE_OBJECT)))
{
FramesDocElm *fde = FramesDocElm::GetFrmDocElmByHTML(this);
if (!fde)
{
RETURN_IF_ERROR(frames_doc->Reflow(FALSE));
fde = FramesDocElm::GetFrmDocElmByHTML(this);
}
if (fde)
{
DocumentManager *fde_doc_man = fde->GetDocManager();
FramesDocument *fde_frames_doc = fde_doc_man->GetCurrentDoc();
short src_attr = type == HE_OBJECT ? ATTR_DATA : ATTR_SRC;
if (URL *url = GetUrlAttr(src_attr, NS_IDX_HTML, frames_doc->GetLogicalDocument()))
{
DocumentReferrer ref_url = frames_doc->GetDOMEnvironment()->GetCurrentScriptURL();
if (ref_url.IsEmpty())
{
ES_Thread *interrupt_thread = thread;
while (interrupt_thread)
if (interrupt_thread->Type() == ES_THREAD_JAVASCRIPT_URL)
{
ref_url.url = static_cast<ES_JavascriptURLThread*>(interrupt_thread)->GetURL();
break;
}
else
interrupt_thread = interrupt_thread->GetInterruptedThread();
}
// Gecko and Webkit open about:blank on frame.src = ''.
if (url->IsEmpty() && src_attr == ATTR_SRC && (type == HE_IFRAME || type == HE_FRAME))
*url = g_url_api->GetURL("about:blank");
if (fde_frames_doc)
{
DocumentManager::OpenURLOptions options;
options.user_initiated = FALSE;
options.entered_by_user = NotEnteredByUser;
options.is_walking_in_history = FALSE;
options.origin_thread = thread;
options.from_html_attribute = TRUE;
RETURN_IF_MEMORY_ERROR(fde_frames_doc->ESOpenURL(*url, DocumentReferrer(ref_url), TRUE, FALSE, FALSE, options));
}
else
fde_doc_man->OpenURL(*url, ref_url, TRUE, FALSE, FALSE, FALSE, NotEnteredByUser, FALSE, FALSE, FALSE);
if (thread)
thread->Pause();
}
}
} // end src/data on iframe/frame/object
if (!is_same_value)
{
switch(attr)
{
case ATTR_FORM:
// fallthrough
case ATTR_NAME:
if (Type() == HE_INPUT && GetInputType() == INPUT_RADIO)
{
// Changing radio group
RETURN_IF_ERROR(logdoc->GetRadioGroups().RegisterRadio(FormManager::FindFormElm(frames_doc, this), this));
}
break;
case ATTR_ID:
if (Type() == HE_FORM)
{
// Radio buttons connected to this with a form attribute will
// now be connected to nothing and somethings not connected
// to anything will now be connected to this
RETURN_IF_ERROR(logdoc->GetRadioGroups().RegisterNewRadioButtons(frames_doc, this));
}
break;
case ATTR_TYPE:
if (Type() == HE_INPUT && GetInputType() == INPUT_RADIO)
{
// It became a radio button so we have to register it
RETURN_IF_ERROR(logdoc->GetRadioGroups().RegisterRadio(FormManager::FindFormElm(frames_doc, this), this));
}
break;
#ifdef ACCESS_KEYS_SUPPORT
case ATTR_ACCESSKEY:
{
const uni_char* key = GetAccesskey();
if (key)
RETURN_IF_MEMORY_ERROR(logdoc->GetHLDocProfile()->AddAccessKey(key, this));
}
break;
#endif // ACCESS_KEYS_SUPPORT
}
} // end if (!is_same_value)
} // end if (NS_HTML)
return OpStatus::OK;
}
void HTML_Element::UpdateCollectionStatus(const DocumentContext &context, short attr, NS_Type ns, BOOL in_document)
{
if (context.environment && ns == NS_HTML && GetNsType() == NS_HTML)
{
unsigned collections = 0;
int type = Type();
switch (attr)
{
case ATTR_CLASS:
collections |= DOM_Environment::COLLECTION_CLASSNAME;
break;
case ATTR_TYPE:
if (type == HE_INPUT)
collections |= DOM_Environment::COLLECTION_FORM_ELEMENTS;
break;
case ATTR_HREF:
if (in_document && (type == HE_A || type == HE_AREA))
collections |= DOM_Environment::COLLECTION_LINKS;
break;
case ATTR_ITEMTYPE:
if (in_document)
collections |= DOM_Environment::COLLECTION_MICRODATA_TOPLEVEL_ITEMS;
break;
case ATTR_ITEMSCOPE:
case ATTR_ITEMPROP:
collections |= DOM_Environment::COLLECTION_MICRODATA_PROPERTIES;
if (in_document)
collections |= DOM_Environment::COLLECTION_MICRODATA_TOPLEVEL_ITEMS;
break;
case ATTR_ID:
case ATTR_ITEMREF:
collections |= DOM_Environment::COLLECTION_MICRODATA_PROPERTIES;
break;
case ATTR_REL:
if (in_document && type == HE_LINK)
collections |= DOM_Environment::COLLECTION_STYLESHEETS;
break;
case ATTR_FORM:
if (IsFormElement())
collections |= DOM_Environment::COLLECTION_FORM_ELEMENTS;
break;
case ATTR_FOR:
if (type == HE_LABEL)
collections |= DOM_Environment::COLLECTION_LABELS;
break;
case ATTR_DATA:
if (in_document && type == HE_OBJECT)
collections |= DOM_Environment::COLLECTION_APPLETS | DOM_Environment::COLLECTION_PLUGINS;
break;
}
if (collections != 0)
context.environment->ElementCollectionStatusChanged(this, collections);
}
}
const uni_char *HTML_Element::GetAttrName(int attr_idx, Markup::AttrType attr, NS_Type ns)
{
if (attr == ATTR_XML)
{
if (attr_idx >= 0)
return (const uni_char*)GetValueItem(attr_idx);
else
{
OP_ASSERT(!"No idea what the name of the attribute is");
return NULL;
}
}
else
{
return HTM_Lex::GetAttributeString(attr, ns);
}
}
OP_STATUS HTML_Element::HandleAttributeChange(const DocumentContext &context, ES_Thread *thread, int attr_idx, Markup::AttrType attr, int ns_idx, BOOL was_removed, const uni_char* attr_name)
{
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
HLDocProfile *hld_profile = context.hld_profile;
DOM_Environment *environment = context.environment;
NS_Type ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
BOOL in_document = FALSE;
if (logdoc)
{
HTML_Element *root = logdoc->GetRoot();
if (root && root->IsAncestorOf(this))
in_document = TRUE;
}
UpdateCollectionStatus(context, attr, ns, in_document);
if (attr == ATTR_TYPE && ns == NS_HTML && IsMatchingType(HE_INPUT, NS_HTML))
RETURN_IF_ERROR(HandleInputTypeChange(context));
if (!frames_doc)
return OpStatus::OK;
// Clear the url cache if an attribute used through GetUrlAttr changes
if (ns == NS_HTML && GetNsType() == NS_HTML)
{
HTML_ElementType type = Type();
#ifdef JS_PLUGIN_SUPPORT
// Notify existing jsplugins of the change of attribute
if (type == HE_OBJECT)
{
JS_Plugin_Object* jso = GetJSPluginObject();
if (jso)
{
if (!was_removed || attr != ATTR_XML)
attr_name = GetAttrName(attr_idx, attr, ns);
const uni_char *attr_value = NULL;
TempBuffer buffer;
if (!was_removed)
attr_value = GetAttribute(frames_doc, attr, attr_name, ns, TRUE, &buffer, FALSE, attr_idx);
if (attr_name)
jso->AttributeChanged(attr_name, attr_value);
}
}
#endif //JS_PLUGIN_SUPPORT
// These should always run, regardless of the document we're in or if we're a fragment.
switch (attr)
{
// Clear the url cache if the attribute change
case ATTR_DATA:
case ATTR_CODEBASE:
ClearResolvedUrls();
break;
case ATTR_HREF:
if (type == HE_BASE && in_document)
{
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
URL *url = GetA_URL(frames_doc->GetLogicalDocument());
hld_profile->SetBaseURL(url);
break;
}
break;
case ATTR_TYPE:
#ifdef JS_PLUGIN_SUPPORT
if (type == HE_OBJECT)
{
// If we insert a jsplugin using JavaScript, we need to
// handle that just as if we had parsed it.
// FIXME: No handling of overwriting an existing one yet.
ES_Object *esobj = DOM_Utils::GetJSPluginObject(GetESElement());
if (!esobj)
RETURN_IF_MEMORY_ERROR(SetupJsPluginIfRequested(GetStringAttr(ATTR_TYPE), hld_profile));
}
#endif
break;
case ATTR_VALUE:
// Setting the value attribute at certain input types should affect the
// value of the form element.
if (type == HE_INPUT)
{
switch (GetInputType())
{
case INPUT_HIDDEN:
case INPUT_CHECKBOX:
case INPUT_RADIO:
case INPUT_FILE:
break;
default:
FormValue* form_value = GetFormValue();
if (form_value->GetType() == FormValue::VALUE_NO_OWN_VALUE)
{
FormValueNoOwnValue* form_value_no_own_value = FormValueNoOwnValue::GetAs(form_value);
form_value_no_own_value->SetValueAttributeFromText(this, GetValue());
}
else
RETURN_IF_ERROR(form_value->SetValueFromText(this, GetValue()));
}
}
break;
case ATTR_MULTIPLE:
if (type == Markup::HTE_INPUT && GetInputType() == INPUT_FILE)
if (FormObject *form_object = GetFormObject())
form_object->SetMultiple(GetBoolAttr(attr, ns_idx));
break;
case ATTR_SELECTED:
if (type == Markup::HTE_OPTION && (was_removed || GetBoolAttr(attr, ns_idx)))
{
if (HTML_Element *select = FindOptionParent(this))
if (select->IsMatchingType(HE_SELECT, NS_HTML))
{
FormValueList *form_value_list = FormValueList::GetAs(select->GetFormValue());
if (!was_removed)
RETURN_IF_ERROR(form_value_list->UpdateSelectedValue(select, this));
else
RETURN_IF_ERROR(form_value_list->SetInitialSelection(select, TRUE));
}
}
break;
case ATTR_CHECKED:
if (type == HE_INPUT && (GetInputType() == INPUT_RADIO || GetInputType() == INPUT_CHECKBOX))
{
FormValue* form_value = GetFormValue();
FormValueRadioCheck* bool_value = FormValueRadioCheck::GetAs(form_value);
// Sometimes the checked attribute will modify the state of
// the checkbox/radio button. Sometimes it isn't.
if (bool_value->IsCheckedAttrChangingState(frames_doc, this))
{
SetBoolFormValue(frames_doc, GetChecked());
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
}
}
break;
}
} // end if (NS_HTML)
if (environment)
{
if (!was_removed || attr != ATTR_XML)
attr_name = GetAttrName(attr_idx, attr, ns);
if (attr_name)
RETURN_IF_ERROR(environment->ElementAttributeChanged(this, attr_name, ns_idx));
}
if (!logdoc)
return OpStatus::OK;
if (!in_document)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (logdoc->GetLayoutWorkplace()->IsTraversing() || logdoc->GetLayoutWorkplace()->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, 0, TRUE, attr, ns);
if (ns == NS_HTML && GetNsType() == NS_HTML)
{
HTML_ElementType type = Type();
switch (attr)
{
case ATTR_DISABLED:
if (type == HE_SELECT || type == HE_INPUT
|| type == HE_TEXTAREA || type == HE_OPTION
|| type == HE_BUTTON
|| type == HE_FIELDSET)
{
// Setting a field disabled might move the focus, and that must happen now,
// not during a paint or some other vulnerable time.
BOOL disabled = GetDisabled();
FormObject* form_object = GetFormObject();
if (form_object)
{
BOOL regain_focus = FALSE;
if (!disabled)
if (HTML_Document *html_document = frames_doc->GetHtmlDocument())
regain_focus = html_document->GetFocusedElement() == this;
form_object->SetEnabled(!disabled, regain_focus);
}
// If someone is disabling something during submit or
// unload, then the page will probably not work correctly
// if not reloaded.
if (disabled && thread)
{
ES_ThreadInfo info = thread->GetOriginInfo();
if (info.type == ES_THREAD_EVENT &&
(info.data.event.type == ONSUBMIT ||
info.data.event.type == ONUNLOAD ||
info.data.event.type == ONMOUSEUP ||
info.data.event.type == ONMOUSEDOWN ||
info.data.event.type == ONCLICK))
{
// This has room for improvement. Since this is something
// we would like to avoid, we could for instance limit it
// to cases where the same thread is used for a submit.
frames_doc->SetCompatibleHistoryNavigationNeeded();
}
}
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
}
break;
case ATTR_READONLY:
if (type == HE_INPUT || type == HE_TEXTAREA)
{
if (FormObject *form_object = GetFormObject())
form_object->SetReadOnly(GetBoolAttr(attr, ns_idx));
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
}
break;
case ATTR_MEDIA:
if (type == HE_LINK || type == HE_STYLE)
{
if (CSS* stylesheet = GetCSS())
{
stylesheet->Removed(hld_profile->GetCSSCollection(), frames_doc);
stylesheet->Added(hld_profile->GetCSSCollection(), frames_doc);
stylesheet->MediaAttrChanged();
}
}
break;
case ATTR_HREF:
#ifdef DNS_PREFETCHING
if (type == HE_A || type == HE_LINK || type == HE_AREA)
{
URL* anchor_url = GetUrlAttr(ATTR_HREF, NS_IDX_HTML, logdoc);
if (anchor_url && !anchor_url->IsEmpty())
logdoc->DNSPrefetch(*anchor_url, DNS_PREFETCH_DYNAMIC);
}
// Fall through
#endif // DNS_PREFETCHING
case ATTR_REL:
if (type == HE_LINK)
{
// Stylesheet changes (most likely). Trigger the update code by faking a removal and insertion into the tree.
RETURN_IF_ERROR(HandleDocumentTreeChange(context, Parent(), this, thread, FALSE));
RETURN_IF_ERROR(HandleDocumentTreeChange(context, Parent(), this, thread, TRUE));
if (attr == ATTR_REL)
g_input_manager->UpdateAllInputStates();
}
break;
case ATTR_SRC:
if (type == HE_SCRIPT)
{
#ifdef USER_JAVASCRIPT
if (environment && environment->IsHandlingScriptElement(this))
break;
#endif // USER_JAVASCRIPT
int handled = GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
/* Script already executed. */
if ((handled & SCRIPT_HANDLED_EXECUTED) == SCRIPT_HANDLED_EXECUTED)
break;
if (!was_removed)
{
BOOL handle_change = TRUE;
URL *original_src_url = static_cast<URL*>(GetSpecialAttr(Markup::LOGA_ORIGINAL_SRC, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC));
if (original_src_url)
{
URL *current_src_url = GetUrlAttr(Markup::HA_SRC, NS_IDX_HTML, logdoc);
handle_change = original_src_url == current_src_url;
}
if (handle_change)
{
BOOL parser_inserted = GetInserted() == HE_NOT_INSERTED;
BOOL parser_blocking = parser_inserted && logdoc->GetParser();
if (logdoc->IsXml())
parser_blocking = FALSE;
if (parser_blocking)
RETURN_IF_MEMORY_ERROR(logdoc->GetParser()->AddBlockingScript(this));
RETURN_IF_ERROR(HandleScriptElement(hld_profile, thread, TRUE, parser_inserted));
}
}
}
#ifdef _PLUGIN_SUPPORT_
// Fall through
case ATTR_DATA:
if (type == HE_OBJECT && attr == ATTR_DATA || type == HE_EMBED && attr == ATTR_SRC)
logdoc->GetLayoutWorkplace()->ResetPlugin(this);
else if (type == HE_IFRAME && attr == ATTR_SRC)
logdoc->GetLayoutWorkplace()->HideIFrame(this);
#endif // _PLUGIN_SUPPORT_
break;
case ATTR_VALUE:
if (type == HE_PARAM && Parent())
Parent()->MarkExtraDirty(frames_doc);
else if (type == HE_INPUT)
switch (GetInputType())
{
case INPUT_BUTTON:
case INPUT_HIDDEN:
case INPUT_SUBMIT:
case INPUT_RESET:
case INPUT_IMAGE:
case INPUT_CHECKBOX:
case INPUT_RADIO:
break;
default:
const uni_char *value = GetValue();
RETURN_IF_ERROR(DOMSetFormValue(environment, value ? value : UNI_L("")));
}
break;
// fall through
// For every attribute change that may change a form elements validity
// or other css3 pseudo class, we have to recalculate pseudo classes
case ATTR_MIN:
case ATTR_MAX:
case ATTR_STEP:
if (type == Markup::HTE_INPUT && GetInputType() == INPUT_RANGE)
{
if (FormObject* form_object = GetFormObject())
{
if (attr != ATTR_STEP)
{
double value = 0.0;
if (!was_removed)
{
const uni_char *str = static_cast<const uni_char *>(GetAttr(attr, ITEM_TYPE_STRING, NULL, ns_idx));
OP_ASSERT(str);
value = uni_strtod(str, NULL);
}
else if (attr == ATTR_MAX)
value = 100.0;
if (attr == ATTR_MIN)
form_object->SetMinMax(&value, NULL);
else
form_object->SetMinMax(NULL, &value);
}
}
FormValue *form_value = GetFormValue();
OP_ASSERT(form_value);
OpString text_value;
RETURN_IF_ERROR(form_value->GetValueAsText(this, text_value));
RETURN_IF_ERROR(form_value->SetValueFromText(this, text_value));
}
// fall through
case ATTR_MAXLENGTH:
case ATTR_PATTERN:
case ATTR_REQUIRED:
if (IsFormElement())
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
break;
#ifdef DOCUMENT_EDIT_SUPPORT
case ATTR_CONTENTEDITABLE:
if (IsContentEditable())
RETURN_IF_ERROR(EnableContentEditable(frames_doc));
else
DisableContentEditable(frames_doc);
break;
#endif // DOCUMENT_EDIT_SUPPORT
}
switch (type)
{
case HE_FRAME:
case HE_IFRAME:
case HE_OBJECT:
{
FramesDocElm *fde = FramesDocElm::GetFrmDocElmByHTML(this);
if (fde)
{
if (type != HE_OBJECT && (attr == ATTR_MARGINHEIGHT || attr == ATTR_MARGINWIDTH))
{
fde->UpdateFrameMargins(this);
DocumentManager *fde_doc_man = fde->GetDocManager();
FramesDocument *fde_frames_doc = fde_doc_man->GetCurrentDoc();
if (fde_frames_doc)
if (LogicalDocument *fde_logdoc = fde_frames_doc->GetLogicalDocument())
if (HTML_Element *fde_body = fde_logdoc->GetBodyElm())
fde_body->MarkDirty(fde_frames_doc);
}
else if (attr == ATTR_NAME)
{
const uni_char *name = GetStringAttr(ATTR_NAME, NS_IDX_HTML);
RETURN_IF_ERROR(fde->SetName(name));
}
else if (attr == ATTR_NORESIZE)
fde->SetFrameNoresize(GetBoolAttr(ATTR_NORESIZE, NS_IDX_HTML));
else if (attr == ATTR_SCROLLING)
{
fde->SetFrameScrolling(GetFrameScrolling());
if (frames_doc->GetFramesPolicy() != FRAMES_POLICY_FRAME_STACKING)
{
fde->GetVisualDevice()->SetScrollType((VisualDevice::ScrollType)fde->GetFrameScrolling());
fde->GetVisualDevice()->UpdateScrollbars();
}
}
}
}
break;
case HE_SELECT:
case HE_TEXTAREA:
if (type == HE_SELECT && (attr == ATTR_SIZE || attr == ATTR_MULTIPLE) ||
type == HE_TEXTAREA && (attr == ATTR_COLS || attr == ATTR_ROWS))
{
if (layout_box)
layout_box->MarkDisabledContent(frames_doc);
}
break;
case HE_PARAM:
if (attr == ATTR_NAME || attr == ATTR_VALUE)
{
if (Parent())
Parent()->MarkExtraDirty(frames_doc);
}
#ifdef JS_PLUGIN_SUPPORT
if (Parent() && (attr == ATTR_VALUE || attr == ATTR_NAME))
{
JS_Plugin_Object* jso = Parent()->GetJSPluginObject();
if (jso)
{
const uni_char* name = GetPARAM_Name();
const uni_char* value = NULL;
if (!was_removed)
value = GetPARAM_Value();
if (name)
jso->ParamSet(name, value);
}
}
#endif //JS_PLUGIN_SUPPORT
break;
#ifdef CSS_VIEWPORT_SUPPORT
case HE_META:
if (attr == ATTR_CONTENT || attr == ATTR_NAME)
{
// If this is a viewport meta (or just became one),
// we need to parse the content attribute and store
// the result in a CSS_ViewportMeta object.
const uni_char* name = GetStringAttr(ATTR_NAME);
if (name && uni_stri_eq(name, "VIEWPORT"))
{
const uni_char* content = GetStringAttr(ATTR_CONTENT);
BOOL create = content && *content;
CSS_ViewportMeta* viewport_meta = GetViewportMeta(context, create);
if (viewport_meta)
{
OP_ASSERT(in_document && hld_profile);
viewport_meta->ParseContent(content);
CSSCollection* coll = hld_profile->GetCSSCollection();
if (coll->IsInCollection(viewport_meta))
viewport_meta->Added(coll, frames_doc);
else
coll->AddCollectionElement(viewport_meta);
}
else if (create)
return OpStatus::ERR_NO_MEMORY;
}
}
break;
#endif // CSS_VIEWPORT_SUPPORT
}
}
else if (ns == NS_XML)
{
#ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
g_svg_manager->HandleSVGAttributeChange(frames_doc, this,
attr, ns, was_removed);
#endif // SVG_SUPPORT
// remove all cached URLs below this element
if (attr == XMLA_BASE)
ClearResolvedUrls();
}
#ifdef SVG_SUPPORT
else if ((ns == NS_SVG || ns == NS_XLINK) && GetNsType() == NS_SVG)
{
g_svg_manager->HandleSVGAttributeChange(frames_doc, this, attr, ns, was_removed);
}
#endif // SVG_SUPPORT
return OpStatus::OK;
}
OP_STATUS HTML_Element::HandleInputTypeChange(const DocumentContext &context)
{
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
HLDocProfile *hld_profile = context.hld_profile;
FormValue* old_form_value = GetFormValue();
OP_ASSERT(old_form_value); // Every HE_INPUT must have a FormValue
BOOL updated_inplace = FALSE;
/* If a transition between text-editable types, try
to perform the change in-place by reconfiguring the
underlying external representation. */
if (old_form_value->GetType() == FormValue::VALUE_TEXT)
if (FormObject *form_object = GetFormObject())
updated_inplace = form_object->ChangeTypeInplace(this);
BOOL refocus = FALSE;
if (frames_doc)
if (HTML_Document* html_doc = frames_doc->GetHtmlDocument())
if (html_doc->GetFocusedElement() == this)
refocus = TRUE;
OP_STATUS status = OpStatus::OK;
if (!updated_inplace)
{
/* Sacrifice old value and create new FormValue, copying
over the required state. */
InputType new_input_type = GetInputType();
FormValue* new_form_value;
status = ConstructFormValue(hld_profile, new_form_value);
if (OpStatus::IsSuccess(status))
{
// Must trigger an unexternalize so that the old value
// is moved from the widget to the FormValue before the switch.
// Otherwise the Unexternalize that will come later will have
// a FormObject for the old type and a FormValue for the new type.
if (layout_box)
RemoveLayoutBox(frames_doc);
new_form_value->PrepareToReplace(*old_form_value, this);
if (new_input_type == INPUT_HIDDEN)
{
// Going from type=text to type=hidden should convert
// the value into being the value attribute
if (old_form_value->GetType() == FormValue::VALUE_TEXT)
{
uni_char* new_value = FormValueText::GetAs(old_form_value)->GetCopyOfInternalText();
if (new_value)
{
int idx = SetAttr(ATTR_VALUE, ITEM_TYPE_STRING, new_value, TRUE);
if (idx == -1) // OOM
OP_DELETEA(new_value);
}
}
}
// This will delete the old formvalue
SetSpecialAttr(ATTR_FORM_VALUE, ITEM_TYPE_COMPLEX, new_form_value, TRUE, SpecialNs::NS_LOGDOC);
OP_ASSERT(GetFormValue() == new_form_value); // Since we're replacing it can't fail
if (new_input_type == INPUT_FILE)
{
// *IMPORTANT* Don't preset a file value in any way!
new_form_value->SetValueFromText(this, NULL);
if (GetFormObject())
RETURN_IF_ERROR(GetFormObject()->SetFormWidgetValue(UNI_L("")));
}
}
else
{
// OOM, we can not change formvalue, let's change the type
// back so that the formvalue and the type attribute are consistant
const uni_char* old_input_type = old_form_value->GetFormValueTypeString(this);
SetNumAttr(ATTR_TYPE, ATTR_GetKeyword(old_input_type, uni_strlen(old_input_type)));
}
}
if (OpStatus::IsSuccess(status) && refocus)
{
frames_doc->GetHtmlDocument()->SetFocusedElement(this, FALSE);
frames_doc->SetElementToRefocus(this);
}
if (logdoc)
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
return status;
}
void HTML_Element::RemoveAttribute(short attr, int ns_idx /*=NS_IDX_HTML*/)
{
int idx = FindAttrIndex(attr, NULL, ns_idx, FALSE);
if (idx > -1)
{
RemoveAttrAtIdx(idx);
OP_ASSERT(FindAttrIndex(attr, NULL, ns_idx, FALSE) == -1);
}
}
void HTML_Element::RemoveSpecialAttribute(short attr, SpecialNs::Ns ns_idx)
{
int index = FindSpecialAttrIndex(attr, ns_idx);
if (index > -1)
{
RemoveAttrAtIdx(index);
OP_ASSERT(FindSpecialAttrIndex(attr, static_cast<SpecialNs::Ns>(ns_idx)) == -1);
}
}
void HTML_Element::RemoveAttrAtIdx(int idx)
{
int to = GetAttrSize();
if (0 <= idx && idx < to)
{
int last = to - 1;
// find the last non-null attribute
while (GetAttrItem(last) == ATTR_NULL)
--last;
if (idx != last)
{
ReplaceAttrLocal(idx, data.attrs[last].GetAttr(), data.attrs[last].GetType(), data.attrs[last].GetValue(), data.attrs[last].GetNsIdx(), data.attrs[last].NeedFree(), data.attrs[last].IsSpecial(), data.attrs[last].IsId(), data.attrs[last].IsSpecified());
data.attrs[last].SetNeedFree(FALSE);
}
ReplaceAttrLocal(last, ATTR_NULL, ITEM_TYPE_BOOL, NULL, NS_IDX_DEFAULT, FALSE, TRUE);
}
}
BOOL HTML_Element::IsNumericAttributeFloat(int attr)
{
if (IsMatchingType(HE_METER, NS_HTML))
{
switch (attr)
{
case ATTR_MIN:
case ATTR_MAX:
case ATTR_LOW:
case ATTR_HIGH:
case ATTR_OPTIMUM:
case ATTR_VALUE:
return TRUE;
};
}
else if (IsMatchingType(HE_PROGRESS, NS_HTML))
{
switch (attr)
{
case ATTR_MAX:
case ATTR_VALUE:
return TRUE;
};
}
return FALSE;
}
int HTML_Element::DOMGetNamespaceIndex(DOM_Environment *environment, const uni_char *ns_uri, const uni_char *ns_prefix)
{
int ns_uri_length = uni_strlen(ns_uri), ns_prefix_length = ns_prefix ? uni_strlen(ns_prefix) : 0;
int ns_idx = g_ns_manager->GetNsIdx(ns_uri, ns_uri_length, ns_prefix, ns_prefix_length, FALSE, FALSE, TRUE);
return ns_idx == NS_IDX_NOT_FOUND ? NS_IDX_ANY_NAMESPACE : ns_idx;
}
BOOL HTML_Element::DOMGetNamespaceData(DOM_Environment *environment, int ns_idx, const uni_char *&ns_uri, const uni_char *&ns_prefix)
{
if (ns_idx != NS_IDX_DEFAULT)
if (NS_Element *ns_element = g_ns_manager->GetElementAt(ns_idx))
{
ns_uri = ns_element->GetUri();
ns_prefix = ns_element->GetPrefix();
return TRUE;
}
return FALSE;
}
int HTML_Element::FindNamespaceIndex(const uni_char *ns_prefix)
{
HTML_Element *element = this;
while (element)
{
for (unsigned index = 0, count = element->GetAttrSize(); index < count; ++index)
if (element->GetAttrNs(index) == NS_IDX_XMLNS)
{
const uni_char *prefix = (const uni_char *) element->GetValueItem(index);
const uni_char *uri = prefix + uni_strlen(prefix) + 1;
if (uni_str_eq(prefix, ns_prefix))
return g_ns_manager->FindNsIdx(uri, uni_strlen(uri), prefix, uni_strlen(prefix));
}
element = element->ParentActual();
}
return NS_IDX_NOT_FOUND;
}
const uni_char *HTML_Element::DOMLookupNamespacePrefix(DOM_Environment *environment, const uni_char *ns_uri)
{
HTML_Element *element = this;
if (!ns_uri)
ns_uri = UNI_L("");
while (element)
{
// First check element's own namespace.
const uni_char *this_elm_nsuri, *this_elm_prefix;
if (DOMGetNamespaceData(environment, element->GetNsIdx(), this_elm_nsuri, this_elm_prefix))
if (uni_str_eq(this_elm_nsuri, ns_uri))
return this_elm_prefix;
// Second, find xmlns attributes.
for (unsigned index = 0, count = element->GetAttrSize(); index < count; ++index)
if (element->GetAttrNs(index) == NS_IDX_XMLNS)
{
const uni_char *prefix = (const uni_char *) element->GetValueItem(index);
const uni_char *uri = prefix + uni_strlen(prefix) + 1;
if (uni_str_eq(uri, ns_uri))
{
const uni_char *ns_uri_tmp = DOMLookupNamespaceURI(environment, prefix);
if (ns_uri_tmp && uni_str_eq(ns_uri, ns_uri_tmp))
return prefix;
}
}
element = element->ParentActual();
}
return NULL;
}
const uni_char *HTML_Element::DOMLookupNamespaceURI(DOM_Environment *environment, const uni_char *ns_prefix)
{
HTML_Element *element = this;
if (!ns_prefix)
ns_prefix = UNI_L("");
while (element)
{
if (element->GetNsIdx() > 0)
{
NS_Element *nselement = g_ns_manager->GetElementAt(element->GetNsIdx());
if (uni_strcmp(nselement->GetPrefix(), ns_prefix) == 0)
return nselement->GetUri();
}
for (unsigned index = 0, count = element->GetAttrSize(); index < count; ++index)
{
int attr_ns_idx = element->GetAttrNs(index);
const uni_char *uri = static_cast<const uni_char*>(element->GetValueItem(index));
if (attr_ns_idx == NS_IDX_XMLNS)
{
const uni_char *prefix;
if (element->GetAttrItem(index) == Markup::HA_XML)
{
// HA_XML attributes are stored as name\0value
prefix = uri;
uri = prefix + uni_strlen(prefix) + 1;
}
else
prefix = element->GetAttrNameString(index);
if (uni_str_eq(prefix, ns_prefix))
return *uri ? uri : NULL;
}
else if (attr_ns_idx == NS_IDX_XMLNS_DEF)
{
if (!*ns_prefix)
return *uri ? uri : NULL;
}
}
element = element->ParentActual();
}
return NULL;
}
const uni_char*
HTML_Element::DOMGetElementName(DOM_Environment *environment, TempBuffer *buffer, int &ns_idx, BOOL uppercase)
{
ns_idx = GetNsIdx();
// HTML elements are always in the XHTML namespace in HTML 5
BOOL ascii_uppercase = uppercase && GetNsType() == NS_HTML;
return GetTagName(ascii_uppercase, buffer);
}
BOOL HTML_Element::DOMHasAttribute(DOM_Environment *environment, int attr, const uni_char *name, int ns_idx, BOOL case_sensitive, int &found_at_index, BOOL specified)
{
found_at_index = FindAttrIndex(attr, name, ns_idx, case_sensitive, TRUE);
if (found_at_index != -1)
{
if (GetItemType(found_at_index) == ITEM_TYPE_BOOL)
{
BOOL is_html = g_ns_manager->GetNsTypeAt(GetResolvedAttrNs(found_at_index)) == NS_HTML;
if (is_html && GetAttrItem(found_at_index) == ATTR_FRAMEBORDER)
return TRUE;
/* Note: the result here is (has-attribute-with-bool-type && has-non-false-value) */
return GetValueItem(found_at_index) != NULL;
}
return !specified || GetAttrIsSpecified(found_at_index);
}
return FALSE;
}
BOOL HTML_Element::DOMHasAttribute(DOM_Environment *environment, const uni_char *name, int ns_idx, BOOL specified)
{
int index;
return DOMHasAttribute(environment, ATTR_XML, name, ns_idx, FALSE, index, specified);
}
int HTML_Element::DOMGetAttributeCount()
{
return GetAttributeCount();
}
void HTML_Element::DOMGetAttributeName(DOM_Environment* environment, int index, TempBuffer *buffer, const uni_char *&name, int &ns_idx)
{
OpStatus::Ignore(GetAttributeName(environment->GetFramesDocument(), index, buffer, name, ns_idx));
}
int HTML_Element::DOMGetAttributeNamespaceIndex(DOM_Environment *environment, const uni_char *name, int ns_idx)
{
int index = FindAttrIndex(ATTR_XML, name, ns_idx, GetNsIdx() != NS_IDX_HTML, TRUE);
if (index != -1)
return GetAttrNs(index);
else
return NS_IDX_NOT_FOUND;
}
const uni_char* HTML_Element::DOMGetAttribute(DOM_Environment *environment, int attr, const uni_char *name, int ns_idx, BOOL case_sensitive, BOOL resolve_urls, int at_known_index)
{
return GetAttribute(environment->GetFramesDocument(), attr, name, ns_idx, case_sensitive, environment->GetTempBuffer(), resolve_urls, at_known_index);
}
double HTML_Element::DOMGetNumericAttribute(DOM_Environment *environment, int attr, const uni_char *name, int ns_idx, BOOL &absent)
{
int index = FindAttrIndex(attr, name, ns_idx, GetNsIdx() != NS_IDX_HTML, TRUE);
if (index != -1)
{
attr = GetAttrItem(index);
ns_idx = GetResolvedAttrNs(index);
}
HTML_ElementType type = Type();
NS_Type elmns = GetNsType(), attrns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
absent = index == -1;
if (index != -1)
{
const uni_char *string_value = GetAttrValueValue(index, attr, HE_UNKNOWN);
if (string_value)
{
uni_char* end_ptr;
double value;
value = uni_strtod(string_value, &end_ptr);
/* For some attributes, a negative WIDTH/HEIGHT value means that it is a percentage
value. In that case we need the box rectangle, which we
will do later in this method. */
if (elmns == NS_HTML &&
(Type() == HE_IMG
#ifdef CANVAS_SUPPORT
|| Type() == HE_CANVAS
#endif // CANVAS_SUPPORT
) &&
attrns == NS_HTML && (attr == ATTR_WIDTH || attr == ATTR_HEIGHT) &&
(value < 0 || end_ptr == string_value))
{
// Percentage or illegal value. Return the calculated result below.
}
else if (end_ptr == string_value && elmns == NS_HTML && attrns == NS_HTML && attr == ATTR_START && Type() == HE_OL)
{
// Ignore non-numeric attribute.
}
else
return value;
}
}
if (elmns == NS_HTML && attrns == NS_HTML)
{
absent = FALSE;
if ((type == HE_IMG || type == HE_INPUT && GetInputType() == INPUT_IMAGE) && (attr == ATTR_WIDTH || attr == ATTR_HEIGHT))
{
/* We end up here when no WIDTH/HEIGHT attribute has been
specified for an IMG element, or when the WIDTH/HEIGHT
attribute has a percentage value. If no WIDTH/HEIGHT
attribute has been specified, it doesn't necessarily mean
that we can use the intrinsic dimensions of the image,
since the size of the IMG element may be affected by
CSS. So we need to get the box rectangle. */
FramesDocument *frames_doc = environment->GetFramesDocument();
LogicalDocument *logdoc = frames_doc ? frames_doc->GetLogicalDocument() : 0;
if (logdoc)
{
if (logdoc->GetRoot()->IsAncestorOf(this))
{
RECT rect;
BOOL got_rect = logdoc->GetBoxRect(this, CONTENT_BOX, rect);
if (got_rect)
{
int value;
if (attr == ATTR_WIDTH)
value = rect.right - rect.left;
else
value = rect.bottom - rect.top;
return static_cast<double>(value);
}
}
/* If image has no ancestor (new Image()) or no layout
(display:none) we'll try to get intristic dimensions */
unsigned w, h;
if (DOMGetImageSize(environment, w, h))
return static_cast<double>(attr == ATTR_WIDTH ? w : h);
}
/* If we failed to get the box rectangle, we assume that
the size of the box is 0x0. This is probably correct in
most cases, but logdoc->GetBoxRect() will return FALSE
in OOM cases as well... */
absent = TRUE;
return 0.0;
}
if (type == Markup::HTE_OL && attr == Markup::HA_START)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
LogicalDocument *logdoc = frames_doc ? frames_doc->GetLogicalDocument() : 0;
if (logdoc && HasAttr(Markup::HA_REVERSED) && logdoc->GetRoot()->IsAncestorOf(this))
{
unsigned count;
if (OpStatus::IsSuccess(logdoc->GetLayoutWorkplace()->CountOrderedListItems(this, count)))
return count;
}
return 1.;
}
else if (type == Markup::HTE_COLGROUP && attr == Markup::HA_SPAN ||
type == Markup::HTE_PROGRESS && attr == Markup::HA_MAX ||
type == Markup::HTE_METER && attr == Markup::HA_MAX ||
(type == Markup::HTE_TD || type == Markup::HTE_TH) && (attr == Markup::HA_COLSPAN || attr == Markup::HA_ROWSPAN))
return 1.;
#ifdef CANVAS_SUPPORT
else if (type == HE_CANVAS && (attr == ATTR_WIDTH || attr == ATTR_HEIGHT))
{
Canvas* canvas = (Canvas*)GetSpecialAttr(Markup::VEGAA_CANVAS, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_OGP);
if (canvas)
if (attr == ATTR_WIDTH)
return (double) canvas->GetWidth(this);
else
return (double) canvas->GetHeight(this);
}
#endif // CANVAS_SUPPORT
}
absent = TRUE;
return 0.;
}
BOOL HTML_Element::DOMGetBooleanAttribute(DOM_Environment *environment, int attr, const uni_char *name, int ns_idx)
{
int index = FindAttrIndex(attr, name, ns_idx, GetNsIdx() != NS_IDX_HTML, TRUE);
if (index == -1 || GetItemType(index) == ITEM_TYPE_BOOL && !GetAttrItem(index))
return FALSE;
else
return TRUE;
}
OP_STATUS HTML_Element::DOMSetAttribute(DOM_Environment *environment, Markup::AttrType attr, const uni_char *name, int ns_idx, const uni_char *value, unsigned value_length, BOOL case_sensitive)
{
return SetAttribute(environment, attr, name, ns_idx, value, value_length, environment->GetCurrentScriptThread(), case_sensitive, FALSE, TRUE);
}
OP_STATUS HTML_Element::DOMSetNumericAttribute(DOM_Environment *environment, Markup::AttrType attr, const uni_char *name, int ns_idx, double value)
{
LogicalDocument *logdoc = environment->GetFramesDocument() ? environment->GetFramesDocument()->GetLogicalDocument() : NULL;
BOOL case_sensitive = !logdoc || logdoc->IsXml() || GetNsIdx() != NS_IDX_HTML;
// Room for a 64 bit number including sign and terminator.
uni_char value_string[DBL_MAX_10_EXP + 50]; // ARRAY OK 2010-10-20 emil
if (IsNumericAttributeFloat(attr))
RETURN_IF_ERROR(WebForms2Number::DoubleToString(value, value_string));
else
uni_ltoa(static_cast<int>(value), value_string, 10);
return DOMSetAttribute(environment, attr, name, ns_idx, value_string, uni_strlen(value_string), case_sensitive);
}
OP_STATUS HTML_Element::DOMSetBooleanAttribute(DOM_Environment *environment, Markup::AttrType attr, const uni_char *name, int ns_idx, BOOL value)
{
LogicalDocument *logdoc = environment->GetFramesDocument() ? environment->GetFramesDocument()->GetLogicalDocument() : NULL;
BOOL case_sensitive = !logdoc || logdoc->IsXml() || GetNsIdx() != NS_IDX_HTML;
int index = FindAttrIndex(attr, name, ns_idx, case_sensitive, FALSE);
if (index != -1)
{
/* We shouldn't find another attribute type unless attr == ATTR_XML. */
OP_ASSERT(attr == ATTR_XML || attr == GetAttrItem(index));
attr = GetAttrItem(index);
ns_idx = GetAttrNs(index);
}
else
{
if (ns_idx == NS_IDX_ANY_NAMESPACE)
ns_idx = NS_IDX_DEFAULT;
if (attr == ATTR_XML)
attr = htmLex->GetAttrType(name, g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx)), case_sensitive);
}
if (index == -1 && value || index != -1 && (!value || !PTR_TO_BOOL(GetValueItem(index))))
{
DocumentContext context(environment);
ES_Thread *thread = environment->GetCurrentScriptThread();
OP_STATUS status = BeforeAttributeChange(context, thread, index, attr, ResolveNsIdx(ns_idx), FALSE);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsError(status))
// Script was not allowed to change the attribute.
return OpStatus::OK;
if (value)
{
#if 0
/* This code is untested, and solves a problem that doesn't exist:
unknown attributes that are known to be booleans. */
ItemType attr_item_type;
void *attr_value;
BOOL need_free;
if (attr == ATTR_XML)
{
attr_item_type = ITEM_TYPE_STRING;
attr_value = OP_NEWA(uni_char, uni_strlen(name) * 2 + 2);
if (!attr_value)
return OpStatus::ERR_NO_MEMORY;
uni_strcpy((uni_char *) attr_value, name);
uni_strcpy((uni_char *) attr_value + uni_strlen(name) + 1, name);
need_free = TRUE;
}
else
{
attr_item_type = ITEM_TYPE_BOOL;
attr_value = INT_TO_PTR(TRUE);
need_free = FALSE;
}
index = SetAttr(attr, attr_item_type, attr_value, need_free, ns_idx);
#else // 0
if (attr == ATTR_XML)
{
OP_ASSERT(FALSE);
return OpStatus::OK;
}
index = SetBoolAttr(attr, TRUE, ns_idx);
#endif // 0
}
else
{
RemoveAttrAtIdx(index);
index = -1;
}
status = HandleAttributeChange(context, thread, index, attr, ns_idx);
OP_STATUS status2 = AfterAttributeChange(context, thread, index, attr, ns_idx, FALSE);
return OpStatus::IsError(status) ? status : status2;
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMRemoveAttribute(DOM_Environment *environment, const uni_char *attr_name, int attr_ns_idx, BOOL case_sensitive)
{
DocumentContext context(environment);
int index = FindAttrIndex(ATTR_XML, attr_name, attr_ns_idx, case_sensitive, TRUE);
if (index != -1)
{
Markup::AttrType attr = GetAttrItem(index);
int ns_idx = GetAttrNs(index);
int resolved_ns_idx = ResolveNsIdx(ns_idx);
if (GetAttrIsEvent(index))
{
environment->RemoveEventHandler(GetEventType(attr, resolved_ns_idx));
ClearEventHandler(environment, GetEventType(attr, resolved_ns_idx));
}
LogicalDocument *logdoc = context.logdoc;
if (logdoc && logdoc->IsXml())
if (XMLDocumentInformation *xmldocinfo = logdoc->GetXMLDocumentInfo())
if (XMLDoctype *xmldoctype = xmldocinfo->GetDoctype())
if (XMLDoctype::Element *elementdecl = xmldoctype->GetElement(GetTagName()))
{
TempBuffer buffer;
const uni_char *prefix = g_ns_manager->GetPrefixAt(ns_idx >= 0 ? ns_idx : resolved_ns_idx);
const uni_char *full_attr_name;
if (prefix && *prefix)
{
RETURN_IF_ERROR(buffer.Append(prefix));
RETURN_IF_ERROR(buffer.Append(':'));
RETURN_IF_ERROR(buffer.Append(attr_name));
full_attr_name = buffer.GetStorage();
}
else
full_attr_name = attr_name;
if (XMLDoctype::Attribute *attr = elementdecl->GetAttribute(full_attr_name, uni_strlen(full_attr_name)))
{
const uni_char *defaultvalue = attr->GetDefaultValue();
if (defaultvalue)
return SetAttribute(context, ATTR_XML, attr_name, ns_idx, defaultvalue, uni_strlen(defaultvalue), environment->GetCurrentScriptThread(), case_sensitive, attr->GetType() == XMLDoctype::Attribute::TYPE_Tokenized_ID, FALSE);
}
}
ES_Thread *thread = environment->GetCurrentScriptThread();
OP_STATUS status = BeforeAttributeChange(context, thread, index, attr, resolved_ns_idx, FALSE);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsError(status))
// Script was not allowed to change the attribute.
return OpStatus::OK;
NS_Type ns = g_ns_manager->GetNsTypeAt(resolved_ns_idx);
OpString removed_name;
if (attr == ATTR_XML)
status = removed_name.Set(GetAttrName(index, attr, ns));
RemoveAttrAtIdx(index);
index = -1;
OP_STATUS status2 = HandleAttributeChange(context, thread, index, attr, ns_idx, TRUE, removed_name.CStr());
status = OpStatus::IsError(status) ? status : status2;
status2 = AfterAttributeChange(context, thread, index, attr, ns_idx, FALSE);
return OpStatus::IsError(status) ? status : status2;
}
return OpStatus::OK;
}
void HTML_Element::SetIndeterminate(FramesDocument *frames_doc, BOOL indeterminate, BOOL apply_property_changes)
{
// Update element attribute
SetSpecialBoolAttr(FORMS_ATTR_INDETERMINATE, indeterminate, SpecialNs::NS_FORMS);
// Update the form object
if (FormObject* form_object = GetFormObject())
form_object->SetIndeterminate(indeterminate);
// Update the indeterminate pseudo class
if (apply_property_changes && frames_doc)
if (HTML_Element *root = frames_doc->GetDocRoot())
if (root->IsAncestorOf(this))
if (LogicalDocument* logdoc = frames_doc->GetLogicalDocument())
logdoc->GetLayoutWorkplace()->ApplyPropertyChanges(this, CSS_PSEUDO_CLASS_GROUP_FORM, TRUE);
}
BOOL HTML_Element::GetIndeterminate()
{
return GetSpecialBoolAttr(FORMS_ATTR_INDETERMINATE, SpecialNs::NS_FORMS);
}
BOOL HTML_Element::DOMGetImageSize(DOM_Environment *environment, unsigned& width, unsigned& height)
{
OP_ASSERT(IsMatchingType(HE_IMG, NS_HTML));
FramesDocument *frames_doc = environment->GetFramesDocument();
if (frames_doc && !frames_doc->GetShowImages())
return FALSE;
HEListElm* hle = GetHEListElm(FALSE);
if (hle)
{
Image image = hle->GetImage();
if (!image.IsEmpty())
{
width = image.Width();
height = image.Height();
return TRUE;
}
}
return FALSE;
}
void HTML_Element::DOMMoveToOtherDocument(DOM_Environment *environment, DOM_Environment *new_environment)
{
if (ElementRef *iter = m_first_ref)
{
while (iter)
{
ElementRef *next_ref = iter->NextRef(); // get it now, because iter can be deleted by the call
iter->OnInsert(environment->GetFramesDocument(), new_environment->GetFramesDocument());
iter = next_ref;
}
}
for (int index = 0, count = packed1.attr_size; index < count;)
if (GetAttrItem(index) == ATTR_NULL)
break;
else
{
switch (GetItemType(index))
{
#ifdef XML_EVENTS_SUPPORT
case ITEM_TYPE_XML_EVENTS_REGISTRATION:
if (XML_Events_Registration *registration = static_cast<XML_Events_Registration *>(GetValueItem(index)))
registration->MoveToOtherDocument(environment->GetFramesDocument(), new_environment->GetFramesDocument());
break;
#endif // XML_EVENTS_SUPPORT
case ITEM_TYPE_COMPLEX:
if (ComplexAttr *value = static_cast<ComplexAttr *>(GetValueItem(index)))
if (!value->MoveToOtherDocument(environment->GetFramesDocument(), new_environment->GetFramesDocument()))
{
RemoveAttrAtIdx(index);
continue;
}
break;
}
++index;
}
}
OP_BOOLEAN
HTML_Element::DOMGetDataSrcContents(DOM_Environment *environment, TempBuffer *buffer)
{
LogicalDocument *logdoc = environment->GetFramesDocument()->GetLogicalDocument();
URL base_url = DeriveBaseUrl(logdoc);
URL *url;
if (IsLinkElement() || (url = GetScriptURL(base_url, logdoc)) && !url->IsEmpty())
{
DataSrc* src_head = GetDataSrc();
for (DataSrcElm *src_elm = src_head->First(); src_elm; src_elm = src_elm->Suc())
RETURN_IF_ERROR(buffer->Append(src_elm->GetSrc(), src_elm->GetSrcLen()));
return OpBoolean::IS_TRUE;
}
return OpBoolean::IS_FALSE;
}
const uni_char* HTML_Element::DOMGetContentsString(DOM_Environment *environment, TempBuffer *buffer, BOOL just_childrens_text)
{
if (Type() == HE_COMMENT || Type() == HE_PROCINST)
{
const uni_char *result = GetStringAttr(ATTR_CONTENT);
return (result ? result : UNI_L(""));
}
else if (Type() == HE_TEXT)
{
const uni_char *result = Content();
return (result ? result : UNI_L(""));
}
else if (!just_childrens_text && (IsScriptElement() || IsLinkElement()))
{
OP_BOOLEAN status = DOMGetDataSrcContents(environment, buffer);
if (status != OpBoolean::IS_FALSE)
return OpStatus::IsError(status) ? NULL : buffer->GetStorage();
// Proceed if nothing found.
}
else if (IsMatchingType(HE_OPTION, NS_HTML))
{
if (OpStatus::IsError(GetOptionText(buffer)))
return NULL;
}
HTML_Element *child = FirstChildActual();
if (child && !child->SucActual())
return !just_childrens_text || child->IsText() ?
child->DOMGetContentsString(environment, buffer, just_childrens_text && Type() == HE_TEXTGROUP) :
UNI_L("");
else
{
for (; child; child = child->SucActual())
if (!just_childrens_text || child->IsText())
if (OpStatus::IsError(child->DOMGetContents(environment, buffer, just_childrens_text && Type() == HE_TEXTGROUP)))
return NULL;
}
return (buffer->GetStorage() ? buffer->GetStorage() : UNI_L(""));
}
OP_STATUS HTML_Element::DOMGetContents(DOM_Environment *environment, TempBuffer *buffer, BOOL just_childrens_text)
{
if (Type() == HE_COMMENT || Type() == HE_PROCINST)
return buffer->Append(GetStringAttr(ATTR_CONTENT));
else if (Type() == HE_TEXT)
return buffer->Append(Content());
else if (!just_childrens_text && (IsScriptElement() || IsLinkElement()))
{
OP_BOOLEAN status = DOMGetDataSrcContents(environment, buffer);
if (status != OpBoolean::IS_FALSE)
return OpStatus::IsError(status) ? status : OpStatus::OK;
// Proceed if nothing found.
}
else if (IsMatchingType(HE_OPTION, NS_HTML))
return GetOptionText(buffer);
for (HTML_Element *child = FirstChildActual(); child; child = child->SucActual())
if (!just_childrens_text || child->IsText())
RETURN_IF_ERROR(child->DOMGetContents(environment, buffer, just_childrens_text && Type() == HE_TEXTGROUP));
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetContents(DOM_Environment *environment, const uni_char *contents, HTML_Element::ValueModificationType modification_type /* = MODIFICATION_REPLACING_ALL */, unsigned offset /*= 0*/, unsigned length1 /*= 0*/, unsigned length2 /*= 0*/)
{
#ifndef HAS_NOTEXTSELECTION
// If this modifies the nodes that define the selection, we'll need to update the selection.
BOOL need_to_adjust_selection = FALSE;
SelectionBoundaryPoint start, end;
SelectionBoundaryPoint* points[2] = { &start, &end };
// If we have deleted text before a selection marker in a node, we need to update that selection
// This is similar to the code maintaining DOM_Range objects in DOM.
if (FramesDocument* frames_doc = environment->GetFramesDocument())
{
if (HTML_Document* html_doc = frames_doc->GetHtmlDocument())
{
if (html_doc->GetSelection(start, end))
{
if (start.GetElement() && IsAncestorOf(start.GetElement()) ||
end.GetElement() && IsAncestorOf(end.GetElement()))
{
// Adjust offsets to node offsets from local HE_TEXT element offsets in case we're in a HE_TEXTGROUP
if (Type() == HE_TEXTGROUP)
{
need_to_adjust_selection = TRUE; // Since we will reallocate the text nodes.
// HE_TEXTGROUP, need to make an HE_TEXTGROUP offset
for (int i = 0; i < 2; i++)
{
SelectionBoundaryPoint* point = points[i];
if (!point->GetElement() || !IsAncestorOf(point->GetElement()))
continue;
int old_offset = point->GetElementCharacterOffset();
OP_ASSERT(point->GetElement() != this);
HTML_Element* elm = point->GetElement()->Pred();
while (elm)
{
int elm_len = elm->GetTextContentLength();
old_offset += elm_len;
offset += elm_len;
elm = elm->Pred();
}
point->SetLogicalPosition(this, old_offset);
}
} // end handle HE_TEXTGROUP
BOOL deleting;
BOOL inserting;
int delete_length;
int insert_length;
if (modification_type == MODIFICATION_DELETING
|| modification_type == MODIFICATION_SPLITTING)
{
deleting = TRUE;
inserting = FALSE;
delete_length = length1;
insert_length = 0;
}
else if (modification_type == MODIFICATION_INSERTING)
{
deleting = FALSE;
inserting = TRUE;
delete_length = 0;
insert_length = length1;
}
else if (modification_type == MODIFICATION_REPLACING)
{
deleting = TRUE;
inserting = TRUE;
delete_length = length1;
insert_length = length2;
}
else
{
OP_ASSERT(modification_type == MODIFICATION_REPLACING_ALL);
deleting = TRUE;
inserting = TRUE;
delete_length = GetTextContentLength();
insert_length = uni_strlen(contents);
modification_type = MODIFICATION_REPLACING;
}
// Adjust offsets for the changed SelectionBoundaryPoint
for (int i = 0; i < 2; i++)
{
SelectionBoundaryPoint* point = points[i];
if (point->GetElement() != this)
continue;
unsigned point_offset = point->GetElementCharacterOffset();
if (offset < point_offset)
{
need_to_adjust_selection = TRUE;
if (deleting)
if (offset + delete_length <= point_offset)
point_offset -= delete_length;
else
point_offset = offset;
if (inserting)
point_offset += insert_length;
point->SetLogicalPosition(this, point_offset);
}
} // end adjust offsets
} // end if (is ancestor of selection point)
} // getSelection
} // HTML_Document
} // FramesDocument
#endif // !HAS_NOTEXTSELECTION
if (Type() == HE_COMMENT || Type() == HE_PROCINST)
{
uni_char *contents_copy = UniSetNewStr(contents);
if (contents && !contents_copy)
return OpStatus::ERR_NO_MEMORY;
SetAttr(ATTR_CONTENT, ITEM_TYPE_STRING, contents_copy, TRUE, NS_IDX_DEFAULT);
RETURN_IF_ERROR(environment->ElementCharacterDataChanged(this, modification_type, offset, length1, length2));
}
else if (IsText())
{
OP_ASSERT(!(Parent() && Parent()->Type() == HE_TEXTGROUP));
// SetText invalidates the text box as well as setting the text
RETURN_IF_ERROR(SetText(environment->GetFramesDocument(), contents, (contents ? uni_strlen(contents) : 0),
modification_type, offset, length1, length2));
#ifndef HAS_NOTEXTSELECTION
if (need_to_adjust_selection)
{
// Check both points in case we have created textgroups and have to move
// them down to a suitable HE_TEXT child.
for (int i = 0; i < 2; i++)
{
SelectionBoundaryPoint* point = points[i];
if (point->GetElement() == this && Type() == HE_TEXTGROUP)
{
int child_offset = point->GetElementCharacterOffset();
HTML_Element* child = FirstChild();
while (child)
{
int local_length = child->GetTextContentLength();
if (child_offset <= local_length)
{
point->SetLogicalPosition(child, child_offset);
break;
}
else
child_offset -= local_length;
child = child->Suc();
}
OP_ASSERT(child || !"We decided for a position for the new selection point but suddenly that position doesn't exist");
}
}
}
#endif // !HAS_NOTEXTSELECTION
}
else if (IsScriptElement() || IsLinkElement())
{
if (DataSrc* src_head = GetDataSrc())
{
URL src_origin = src_head->GetOrigin();
src_head->DeleteAll();
return src_head->AddSrc(contents, uni_strlen(contents), src_origin);
}
}
#ifndef HAS_NOTEXTSELECTION
if (need_to_adjust_selection && environment->GetFramesDocument()->IsCurrentDoc())
{
environment->GetFramesDocument()->Reflow(FALSE); // SetSelection doesn't work on a dirty tree.
environment->GetFramesDocument()->GetHtmlDocument()->SetSelection(&start, &end, TRUE);
}
#endif // HAS_NOTEXTSELECTION
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSelectContents(DOM_Environment *environment)
{
if (FramesDocument *frames_doc = environment->GetFramesDocument())
if (frames_doc->IsCurrentDoc())
{
RETURN_IF_ERROR(frames_doc->Reflow(FALSE));
GetFormValue()->SelectAllText(this);
}
return OpStatus::OK;
}
BOOL HTML_Element::DOMGetBoolFormValue(DOM_Environment *environment)
{
// This method is only called for radio buttons and checkboxes
FormValue* form_value = GetFormValue();
FormValueRadioCheck* bool_value = FormValueRadioCheck::GetAs(form_value);
return bool_value->IsChecked(this);
}
void HTML_Element::SetBoolFormValue(FramesDocument *frames_doc, BOOL value)
{
FormValue* form_value = GetFormValue();
FormValueRadioCheck* bool_value = FormValueRadioCheck::GetAs(form_value);
bool_value->SetIsChecked(this, value, frames_doc, TRUE);
}
void HTML_Element::DOMSetBoolFormValue(DOM_Environment *environment, BOOL value)
{
SetBoolFormValue(environment->GetFramesDocument(), value);
if (environment->GetFramesDocument())
{
FormValue* form_value = GetFormValue();
FormValueRadioCheck* bool_value = FormValueRadioCheck::GetAs(form_value);
bool_value->SetWasChangedExplicitly(environment->GetFramesDocument(), this);
}
HandleFormValueChange(environment->GetFramesDocument(), environment->GetCurrentScriptThread());
}
OP_STATUS HTML_Element::DOMGetDefaultOutputValue(DOM_Environment *environment, TempBuffer *buffer)
{
FormValueOutput* output_value = FormValueOutput::GetAs(GetFormValue());
OpString tmp_string;
OP_STATUS status = output_value->GetDefaultValueAsText(this, tmp_string);
if (OpStatus::IsSuccess(status) && !tmp_string.IsEmpty())
{
status = buffer->Append(tmp_string.CStr());
}
RETURN_IF_MEMORY_ERROR(status);
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetDefaultOutputValue(DOM_Environment *environment, const uni_char *value)
{
FormValueOutput* output_value = FormValueOutput::GetAs(GetFormValue());
RETURN_IF_MEMORY_ERROR(output_value->SetDefaultValueFromText(this, value));
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMGetFormValue(DOM_Environment *environment, TempBuffer *buffer, BOOL with_crlf)
{
OP_ASSERT(IsFormElement());
// This is only called for form things
FormValue* form_value = GetFormValue();
OpString text_value;
if (!with_crlf)
{
FormValueTextArea *text_area = FormValueTextArea::GetAs(form_value);
RETURN_IF_ERROR(text_area->GetValueAsTextLF(this, text_value));
}
else
RETURN_IF_ERROR(form_value->GetValueAsText(this, text_value));
RETURN_IF_ERROR(buffer->Expand(text_value.Length() + 1));
if (!text_value.CStr())
*buffer->GetStorage() = '\0';
else
{
buffer->Clear();
buffer->Append(text_value.CStr());
}
if (GetInputType() == INPUT_FILE)
{
/* Strip double quotes and escape characters from the string; the script
expects a "plain" filename. This method is not ideal, because it
looks at the string after the filename quoter has changed it -- user
intention may have been lost. For example, if the user types in a
quoted filename then he may expect that to be passed to the script;
we strip the quoting here regardless.
This code handles only one file name. */
OpString value_obj;
RETURN_IF_MEMORY_ERROR(value_obj.Set(buffer->GetStorage()));
uni_char *value = value_obj.CStr();
UniParameterList file_name_list;
RETURN_IF_MEMORY_ERROR(FormManager::ConfigureForFileSplit(file_name_list, value));
*value = '\0';
UniParameters* file_name_obj = file_name_list.First();
if (file_name_obj)
{
const uni_char* file_name = file_name_obj->Name();
if (file_name)
{
buffer->Clear();
// We don't want scripts to have access to the path as that gives
// the script information about the local computer's directory
// structure. Strip everything before the last path seperator,
// unless this is opera:config.
#ifdef OPERACONFIG_URL
BOOL allow_path = FALSE;
// Check the document URL
FramesDocument* frames_doc = environment->GetFramesDocument();
if (frames_doc)
{
URL url = frames_doc->GetOrigin()->security_context;
allow_path = url.Type() == URL_OPERA && url.GetAttribute(URL::KName).CompareI("opera:config") == 0;
}
if (!allow_path)
#endif
{
const uni_char* last_sep = uni_strrchr(file_name, PATHSEPCHAR);
if (last_sep)
file_name = last_sep + 1;
RETURN_IF_ERROR(buffer->Append(UNI_L("C:\\fakepath\\")));
}
RETURN_IF_ERROR(buffer->Append(file_name));
}
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetFormValue(DOM_Environment *environment, const uni_char *value)
{
// No script is allowed to manipulate file upload fields
OP_ASSERT(GetNsType() == NS_HTML);
BOOL allow_script_to_change = Type() != HE_INPUT || GetInputType() != INPUT_FILE || !*value;
#ifdef OPERACONFIG_URL
FramesDocument* frames_doc = environment->GetFramesDocument();
if (frames_doc)
{
URL url = frames_doc->GetOrigin()->security_context;
if (url.Type() == URL_OPERA && url.GetAttribute(URL::KName).CompareI("opera:config") == 0)
{
// opera:config is allowed to change anything
allow_script_to_change = TRUE;
}
}
#endif // OPERACONFIG_URL
if (!allow_script_to_change)
return OpStatus::OK;
OP_ASSERT(value);
FormValue* form_value = GetFormValue();
OP_ASSERT(form_value); // This function shouldn't be called unless it was a form thing.
if (Type() == HE_OUTPUT)
{
FormValueOutput* form_value_output = FormValueOutput::GetAs(form_value);
RETURN_IF_MEMORY_ERROR(form_value_output->SetOutputValueFromText(this, environment->GetFramesDocument(), value));
}
else
{
RETURN_IF_MEMORY_ERROR(form_value->SetValueFromText(this, value, TRUE));
}
HandleFormValueChange(environment->GetFramesDocument(), environment->GetCurrentScriptThread());
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMStepUpDownFormValue(DOM_Environment *environment, int step_count)
{
OP_ASSERT(IsMatchingType(HE_INPUT, NS_HTML));
OP_STATUS status = GetFormValue()->StepUpDown(this, step_count);
if (OpStatus::IsSuccess(status))
HandleFormValueChange(environment->GetFramesDocument(), environment->GetCurrentScriptThread());
return status;
}
OP_STATUS HTML_Element::DOMGetSelectedIndex(DOM_Environment *environment, int &index)
{
FormValue* form_value = GetFormValue();
OP_ASSERT(form_value);
FormValueList* form_value_list = FormValueList::GetAs(form_value);
unsigned int first_sel_index;
OP_STATUS status = form_value_list->GetIndexOfFirstSelected(this, first_sel_index);
if (OpStatus::IsSuccess(status))
{
index = static_cast<int>(first_sel_index);
return OpStatus::OK;
}
if (OpStatus::IsMemoryError(status))
return OpStatus::ERR_NO_MEMORY;
OP_ASSERT(status == OpStatus::ERR); // There was nothing selected
index = -1;
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetSelectedIndex(DOM_Environment *environment, int index)
{
FormValue* form_value = GetFormValue();
FormValueList* list_value = FormValueList::GetAs(form_value);
if (index < 0 || static_cast<unsigned int>(index) >= list_value->GetOptionCount(this))
{
RETURN_IF_MEMORY_ERROR(list_value->UnselectAll(this));
}
else
{
// Should only have one selected value after this
RETURN_IF_MEMORY_ERROR(list_value->UnselectAll(this));
RETURN_IF_MEMORY_ERROR(list_value->SelectValue(this, index, TRUE));
}
HandleFormValueChange(environment->GetFramesDocument(), environment->GetCurrentScriptThread());
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMGetOptionSelected(DOM_Environment *environment, int index, BOOL &selected)
{
FormValue* form_value = GetFormValue();
OP_ASSERT(form_value);
if (index >= 0)
{
FormValueList* form_value_list = FormValueList::GetAs(form_value);
selected = form_value_list->IsSelected(this, index);
}
else
selected = FALSE;
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetOptionSelected(DOM_Environment *environment, int index, BOOL selected)
{
FormValue* form_value = GetFormValue();
OP_ASSERT(form_value);
if (index >= 0)
{
FormValueList* form_value_list = FormValueList::GetAs(form_value);
form_value_list->SelectValue(this, index, selected);
}
HandleFormValueChange(environment->GetFramesDocument(), environment->GetCurrentScriptThread());
return OpStatus::OK;
}
void HTML_Element::DOMSelectUpdateLock(BOOL lock)
{
FormValue* form_value = GetFormValue();
OP_ASSERT(form_value);
FormValueList* form_value_list = FormValueList::GetAs(form_value);
form_value_list->LockUpdate(this, FALSE, lock);
}
// This is called when DOM (or something similarly non-user) has changed the value
void HTML_Element::HandleFormValueChange(FramesDocument *frames_doc, ES_Thread* thread)
{
if (frames_doc)
FormValueListener::HandleValueChanged(frames_doc, this, FALSE, FALSE, thread);
}
void HTML_Element::DOMGetSelection(DOM_Environment *environment, int &start, int &end, SELECTION_DIRECTION& direction)
{
OP_ASSERT(IsFormElement());
INT32 s, e;
GetFormValue()->GetSelection(this, s, e, direction);
start = s;
end = e;
}
void HTML_Element::DOMSetSelection(DOM_Environment *environment, int start, int end, SELECTION_DIRECTION direction)
{
OP_ASSERT(IsFormElement());
#ifndef RANGESELECT_FROM_EDGE
if (direction == SELECTION_DIRECTION_NONE)
direction = SELECTION_DIRECTION_FORWARD;
#endif // RANGESELECT_FROM_EDGE
GetFormValue()->SetSelection(this, start, end, direction);
}
int HTML_Element::DOMGetCaretPosition(DOM_Environment *environment)
{
OP_ASSERT(IsFormElement());
return GetFormValue()->GetCaretOffset(this);
}
void HTML_Element::DOMSetCaretPosition(DOM_Environment *environment, int position)
{
OP_ASSERT(IsFormElement());
FormValue* form_value = GetFormValue();
// When DOM sets caret position, we also want to remove the current selection
form_value->SetSelection(this, position, position);
form_value->SetCaretOffset(this, position);
}
const uni_char* HTML_Element::DOMGetPITarget(DOM_Environment *environment)
{
return GetStringAttr(ATTR_TARGET, NS_IDX_DEFAULT);
}
OP_STATUS
HTML_Element::DOMGetInlineStyle(CSS_DOMStyleDeclaration *&styledeclaration, DOM_Environment *environment)
{
styledeclaration = OP_NEW(CSS_DOMStyleDeclaration, (environment, this, NULL, CSS_DOMStyleDeclaration::NORMAL));
return styledeclaration ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
OP_STATUS
HTML_Element::DOMGetComputedStyle(CSS_DOMStyleDeclaration *&styledeclaration, DOM_Environment *environment, const uni_char *pseudo_class)
{
styledeclaration = OP_NEW(CSS_DOMStyleDeclaration, (environment, this, NULL, CSS_DOMStyleDeclaration::COMPUTED, pseudo_class));
return styledeclaration ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
#ifdef CURRENT_STYLE_SUPPORT
OP_STATUS
HTML_Element::DOMGetCurrentStyle(CSS_DOMStyleDeclaration *&styledeclaration, DOM_Environment *environment)
{
styledeclaration = OP_NEW(CSS_DOMStyleDeclaration, (environment, this, NULL, CSS_DOMStyleDeclaration::CURRENT, NULL));
return styledeclaration ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
#endif // CURRENT_STYLE_SUPPORT
#ifdef _PLUGIN_SUPPORT_
OpNS4Plugin* HTML_Element::DOMGetNS4Plugin()
{
// FIXME: Inline
return GetNS4Plugin();
}
#endif // _PLUGIN_SUPPORT_
OP_STATUS HTML_Element::DOMGetFrameProxyEnvironment(DOM_ProxyEnvironment*& frame_environment, FramesDocument*& frame_frames_doc, DOM_Environment* environment)
{
frame_environment = NULL;
frame_frames_doc = NULL;
if (FramesDocElm *frames_doc_elm = FramesDocElm::GetFrmDocElmByHTML(this))
{
DocumentManager* docman = frames_doc_elm->GetDocManager();
RETURN_IF_ERROR(docman->ConstructDOMProxyEnvironment());
frame_environment = docman->GetDOMEnvironment();
OP_ASSERT(frame_environment);
frame_frames_doc = docman->GetCurrentDoc();
}
return OpStatus::OK;
}
BOOL HTML_Element::DOMElementLoaded(DOM_Environment *environment)
{
InlineResourceType inline_type = INVALID_INLINE;
if (IsMatchingType(HE_SCRIPT, NS_HTML) && GetStringAttr(ATTR_SRC))
inline_type = SCRIPT_INLINE;
else if (IsMatchingType(HE_IMG, NS_HTML))
inline_type = IMAGE_INLINE;
else if (IsMatchingType(HE_LINK, NS_HTML))
if (FramesDocument *document = environment->GetFramesDocument())
if (HLDocProfile *hld_profile = document->GetHLDocProfile())
for (const LinkElement *link = hld_profile->GetLinkList(); link; link = link->Suc())
if (link->IsElm(this))
{
inline_type = CSS_INLINE;
break;
}
if (inline_type != INVALID_INLINE)
{
HEListElm *helistelm = GetHEListElmForInline(inline_type);
return helistelm && helistelm->GetHandled();
}
return TRUE;
}
BOOL HTML_Element::DOMGetStylesheetDisabled(DOM_Environment *environment)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
CSS *css = GetCSS();
if (!frames_doc || !css)
{
BOOL disabled = GetSpecialBoolAttr(ATTR_STYLESHEET_DISABLED, SpecialNs::NS_LOGDOC);
return disabled;
}
return !css->IsEnabled() || !css->CheckMedia(frames_doc, frames_doc->GetMediaType());
}
const uni_char* HTML_Element::DOMGetInputTypeString()
{
OP_ASSERT(GetNsType() == NS_HTML);
OP_ASSERT(Type() == HE_INPUT || Type() == HE_BUTTON);
// Move all this code to an HTML_Element::DOMGetInputTypeString method?
OP_ASSERT(INPUT_NOT_AN_INPUT_OBJECT == 0); // Since 0 is the default value of GetNumAttr.
OP_ASSERT(INPUT_TEXT > 0);
OP_ASSERT(INPUT_SUBMIT > 0);
InputType type = (enum InputType)GetNumAttr(ATTR_TYPE);
if (type == INPUT_NOT_AN_INPUT_OBJECT)
type = Type() == HE_BUTTON ? INPUT_SUBMIT : INPUT_TEXT;
// const uni_char *GetInputTypeString(InputType type); // FIXME: Fix exported prototype in logdoc
return GetInputTypeString(type);
}
OP_STATUS HTML_Element::DOMSetStylesheetDisabled(DOM_Environment *environment, BOOL value)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::OK;
return SetStylesheetDisabled(frames_doc, value);
}
OP_STATUS HTML_Element::SetStylesheetDisabled(FramesDocument *frames_doc, BOOL value)
{
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
if (!hld_profile)
return OpStatus::OK;
CSSCollection* coll = hld_profile->GetCSSCollection();
CSS *css = GetCSS();
while (css)
{
HTML_Element *css_he = css->GetHtmlElement();
if (!IsAncestorOf(css_he))
break;
else if (!css->IsEnabled() == !value)
{
css->SetEnabled(!value);
if (!value)
css->Added(coll, frames_doc);
else
css->Removed(coll, frames_doc);
}
css = (CSS *) css->Pred();
}
SetSpecialBoolAttr(ATTR_STYLESHEET_DISABLED, value, SpecialNs::NS_LOGDOC);
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMGetOffsetParent(DOM_Environment *environment, HTML_Element *&parent)
{
parent = NULL;
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = logdoc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
HTML_Element* root = logdoc->GetRoot();
if (!root || !root->IsAncestorOf(this))
return OpStatus::OK;
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
if (OpStatus::IsSuccess(status = frames_doc->Reflow(FALSE)))
{
Head props_list;
if (LayoutProperties::CreateCascade(this, props_list, logdoc->GetHLDocProfile()))
{
LayoutProperties *offset_cascade = ((LayoutProperties *)props_list.Last())->FindOffsetParent(logdoc->GetHLDocProfile());
if (offset_cascade)
parent = offset_cascade->html_element;
}
else
status = OpStatus::ERR_NO_MEMORY;
props_list.Clear();
}
return status;
}
static BoxRectType BoxRectTypeFromDOMPositionAndSizeType(HTML_Element::DOMPositionAndSizeType type)
{
switch(type)
{
case HTML_Element::DOM_PS_OFFSET:
return OFFSET_BOX;
case HTML_Element::DOM_PS_CLIENT:
return CLIENT_BOX;
case HTML_Element::DOM_PS_CONTENT:
return CONTENT_BOX;
case HTML_Element::DOM_PS_BORDER:
return BORDER_BOX;
default:
return SCROLL_BOX;
}
}
static OpPoint BoxRectOriginFromDOMPositionAndSizeType(FramesDocument* doc, HTML_Element::DOMPositionAndSizeType type)
{
if (type == HTML_Element::DOM_PS_BORDER || type == HTML_Element::DOM_PS_CONTENT)
return doc->GetVisualViewport().TopLeft();
else
return OpPoint();
}
OP_STATUS HTML_Element::DOMGetPositionAndSize(DOM_Environment *environment, DOMPositionAndSizeType type, int &left, int &top, int &width, int &height)
{
left = top = width = height = 0;
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = frames_doc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
if (frames_doc->IsFrameDoc())
{
if (IsMatchingType(HE_FRAME, NS_HTML))
{
// Everything asked seem to just return the view area
// It's probably a too simple approximation but it
// actually looked like that when I checked MSIE and Moz
width = frames_doc->GetLayoutViewWidth();
height = frames_doc->GetLayoutViewHeight();
}
return OpStatus::OK;
}
OP_STATUS status = OpStatus::OK;
{
OP_PROBE0(OP_PROBE_HTML_ELEMENT_DOMPOS_REFLOW);
status = frames_doc->Reflow(FALSE);
}
if (OpStatus::IsSuccess(status) && layout_box)
{
BoxRectType brt = BoxRectTypeFromDOMPositionAndSizeType(type);
OpPoint origin = BoxRectOriginFromDOMPositionAndSizeType(frames_doc, type);
RECT rect;
if (IsMatchingType(HE_TEXTAREA, NS_HTML) && brt == SCROLL_BOX && GetFormObject())
{
TextAreaObject* textarea_obj = static_cast<TextAreaObject*>(GetFormObject());
textarea_obj->GetWidgetScrollPosition(left, top);
textarea_obj->GetScrollableSize(width, height);
}
else
if (logdoc->GetBoxRect(this, brt, rect))
{
left = rect.left - origin.x;
top = rect.top - origin.y;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
}
return status;
}
OP_STATUS HTML_Element::DOMGetPositionAndSizeList(DOM_Environment *environment, DOMPositionAndSizeType type, OpVector<RECT> &rect_vector)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
OP_ASSERT(rect_vector.GetCount() == 0);
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = logdoc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
if (OpStatus::IsSuccess(status = frames_doc->Reflow(FALSE)) && layout_box)
{
BoxRectType brt = BoxRectTypeFromDOMPositionAndSizeType(type);
OpPoint origin = BoxRectOriginFromDOMPositionAndSizeType(frames_doc, type);
RectList rect_list;
if (!layout_box->GetRectList(frames_doc, brt, rect_list))
{
// Might be OOM, but may also be just unsupported case
// in GetBoxRect. Assuming unsupported for now to avoid
// killing scripts by mistake, so let's just drop down
// and return an empty list.
// status = OpStatus::ERR_NO_MEMORY;
}
else
for (RectListItem *iter = rect_list.First(); iter != NULL && OpStatus::IsSuccess(status); iter = iter->Suc())
{
RECT *new_rect = OP_NEW(RECT, (iter->rect));
if (!new_rect || OpStatus::IsMemoryError(rect_vector.Add(new_rect)))
status = OpStatus::ERR_NO_MEMORY;
else
{
new_rect->left -= origin.x;
new_rect->right -= origin.x;
new_rect->top -= origin.y;
new_rect->bottom -= origin.y;
}
}
rect_list.Clear();
}
return status;
}
OP_STATUS HTML_Element::DOMGetXYPosition(DOM_Environment *environment, int &x, int &y)
{
/* Image.x and Image.y the way firefox does it (which is old and compatible with NS4),
* there isn't really any spec/documentation on it, see CORE-20517.
*
* It mostly behaves like offsetTop/Left with the following exceptions:
* - when the offsetParent is a Table or TableCell it behaves as if the offsetParent was the body
* - when the offsetParent is a fixed positioned element, x/y is the distance to the offsetParent,
* instead of the body.
*/
int width, height; // not really used, needed for the PositionAndSize calls
HTML_Element *offset_parent;
RETURN_IF_ERROR(DOMGetPositionAndSize(environment, HTML_Element::DOM_PS_OFFSET, x, y, width, height));
RETURN_IF_ERROR(DOMGetOffsetParent(environment, offset_parent));
if (offset_parent)
{
if (offset_parent->Type() == HE_TABLE ||
offset_parent->Type() == HE_TD ||
offset_parent->Type() == HE_TH)
{
int tmp_x, tmp_y;
HTML_Element *element = offset_parent;
while(element)
{
GET_FAILED_IF_ERROR(element->DOMGetPositionAndSize(
environment, HTML_Element::DOM_PS_OFFSET, tmp_x, tmp_y, width, height));
x += tmp_x;
y += tmp_y;
GET_FAILED_IF_ERROR(element->DOMGetOffsetParent(environment, element));
}
if (FramesDocument *frames_doc = environment->GetFramesDocument())
offset_parent = frames_doc->GetHLDocProfile()->GetBodyElm();
else
offset_parent = NULL;
}
else if (offset_parent->GetLayoutBox() && offset_parent->GetLayoutBox()->IsFixedPositionedBox())
{
RECT this_rect, parent_rect;
if (GetLayoutBox()->GetRect(environment->GetFramesDocument(), BOUNDING_BOX, this_rect) &&
offset_parent->GetLayoutBox()->GetRect(environment->GetFramesDocument(), BOUNDING_BOX, parent_rect))
{
x = this_rect.left - parent_rect.left;
y = this_rect.top - parent_rect.top;
}
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMGetClientRects(DOM_Environment *environment, RECT *bounding_rect, OpVector<RECT> *rect_vector, HTML_Element *end_elm, int text_start_offset/*=0*/, int text_end_offset/*=-1*/)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
ClientRectObject rect_traversal(frames_doc, bounding_rect, rect_vector, this, end_elm, text_start_offset, text_end_offset);
return rect_traversal.Traverse(logdoc->GetRoot());
}
OP_STATUS HTML_Element::DOMSetPositionAndSize(DOM_Environment *environment, DOMPositionAndSizeType type, int *left, int *top, int *width, int *height)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = frames_doc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
RETURN_IF_ERROR(frames_doc->Reflow(FALSE, TRUE));
if (layout_box && type == DOM_PS_SCROLL)
{
if (frames_doc->GetHLDocProfile() && frames_doc->GetHLDocProfile()->IsInStrictMode()
? IsMatchingType(HE_HTML, NS_HTML) : IsMatchingType(HE_BODY, NS_HTML))
{
if (frames_doc->GetLogicalDocument()->GetRoot()->IsAncestorOf(this))
frames_doc->DOMSetScrollOffset(left, top);
}
else if (IsMatchingType(HE_TEXTAREA, NS_HTML) && GetFormObject())
{
TextAreaObject* textarea_obj = static_cast<TextAreaObject*>(GetFormObject());
int current_left, current_top;
textarea_obj->GetWidgetScrollPosition(current_left, current_top);
textarea_obj->SetWidgetScrollPosition(left ? *left : current_left, top ? *top : current_top);
}
else
layout_box->SetScrollOffset(left, top);
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMScrollIntoView(DOM_Environment *environment, BOOL align_to_top)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
HTML_Document *html_doc = frames_doc->GetHtmlDocument();
if (!html_doc)
return OpStatus::OK;
LogicalDocument* logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = logdoc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
RETURN_IF_ERROR(frames_doc->Reflow(FALSE));
html_doc->ScrollToElement(this, align_to_top ? SCROLL_ALIGN_TOP : SCROLL_ALIGN_BOTTOM, FALSE, VIEWPORT_CHANGE_REASON_SCRIPT_SCROLL);
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMGetDistanceToRelative(DOM_Environment *environment, int &left, int &top, BOOL &relative_found)
{
left = 0;
top = 0;
relative_found = FALSE;
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::OK;
#ifdef NS4P_COMPONENT_PLUGINS
if (LayoutWorkplace* wp = logdoc->GetLayoutWorkplace())
if (wp->IsTraversing() || wp->IsReflowing())
return OpStatus::ERR_NOT_SUPPORTED;
#endif // NS4P_COMPONENT_PLUGINS
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
if (OpStatus::IsSuccess(status = frames_doc->Reflow(FALSE)) && layout_box &&
(!layout_box->IsPositionedBox() || layout_box->IsAbsolutePositionedBox()))
{
HTML_Element *parent = ParentActual();
while (parent)
{
Box *parent_box = parent->layout_box;
if (!parent_box || parent_box->IsPositionedBox() && !parent_box->IsAbsolutePositionedBox())
{
relative_found = TRUE;
break;
}
parent = parent->ParentActual();
}
if (!parent)
parent = logdoc->GetBodyElm();
if (parent && parent->layout_box)
{
RECT parent_rect, this_rect;
if (logdoc->GetBoxRect(parent, BOUNDING_BOX, parent_rect) && logdoc->GetBoxRect(this, BOUNDING_BOX, this_rect))
{
left = this_rect.left - parent_rect.left;
top = this_rect.top - parent_rect.top;
}
}
}
return status;
}
OP_STATUS HTML_Element::DOMGetPageInfo(DOM_Environment *environment, unsigned int& current_page, unsigned int& page_count)
{
current_page = 0;
page_count = 1;
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
RETURN_IF_ERROR(frames_doc->Reflow(FALSE, TRUE));
if (layout_box)
layout_box->GetPageInfo(current_page, page_count);
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetCurrentPage(DOM_Environment *environment, unsigned int current_page)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->IsCurrentDoc())
return OpStatus::OK;
RETURN_IF_ERROR(frames_doc->Reflow(FALSE, TRUE));
if (layout_box)
layout_box->SetCurrentPageNumber(current_page);
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMInsertChild(DOM_Environment *environment, HTML_Element *child, HTML_Element *reference)
{
for (HTML_Element *iter = child, *stop = child->NextSiblingActual(); iter != stop; iter = iter->NextActual())
iter->SetInserted(HE_INSERTED_BY_DOM);
if (reference)
return child->PrecedeSafe(environment, reference);
else
return child->UnderSafe(environment, this);
}
OP_STATUS HTML_Element::DOMRemoveFromParent(DOM_Environment *environment)
{
DocumentContext context(environment);
LogicalDocument *logdoc = context.logdoc;
BOOL in_document = FALSE;
if (logdoc && logdoc->GetRoot())
in_document = logdoc->GetRoot()->IsAncestorOf(this);
Remove(context);
if (in_document)
{
if (logdoc->GetDocRoot() == this)
{
logdoc->SetDocRoot(NULL);
environment->NewRootElement(NULL);
}
#ifdef DOCUMENT_EDIT_SUPPORT
FramesDocument *frames_doc = context.frames_doc;
if (frames_doc->GetDocumentEdit())
{
if (IsContentEditable())
DisableContentEditable(frames_doc);
if (frames_doc->GetDocumentEdit())
frames_doc->GetDocumentEdit()->OnElementRemoved(this);
}
#endif // DOCUMENT_EDIT_SUPPORT
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMRemoveAllChildren(DOM_Environment *environment)
{
DocumentContext context(environment);
FramesDocument *frames_doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
BOOL in_document = FALSE;
if (logdoc && logdoc->GetRoot())
in_document = logdoc->GetRoot()->IsAncestorOf(this);
BOOL removed_something = FALSE;
BOOL need_extra_dirty = FALSE;
// Disconnect all real children
while (HTML_Element *child = FirstChildActual())
{
removed_something = TRUE;
child->Remove(context);
if (child->Clean(context))
child->Free(context);
}
// Remove all children that are invisible to script (the rest was removed above)
while (HTML_Element *child = FirstChild())
{
removed_something = TRUE;
child->Remove(context);
need_extra_dirty = TRUE;
if (child->Clean(context))
child->Free(context);
}
if (in_document && removed_something)
{
#ifdef DOCUMENT_EDIT_SUPPORT
if (frames_doc->GetDocumentEdit())
frames_doc->GetDocumentEdit()->OnElementRemoved(this);
#endif
if (need_extra_dirty)
MarkExtraDirty(frames_doc);
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMSetInnerHTML(DOM_Environment *environment, const uni_char *html, int html_len, HTML_Element *actual_parent_element, BOOL use_xml_parser)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc || !frames_doc->GetHLDocProfile()) // Can happen if the element came from an old document that has been replaced/freed
return OpStatus::ERR;
#ifdef MANUAL_PLUGIN_ACTIVATION
ES_Thread *thread = environment->GetCurrentScriptThread();
frames_doc->GetHLDocProfile()->ESSetScriptExternal(thread && ES_Runtime::GetIsExternal(thread->GetContext()));
#endif // MANUAL_PLUGIN_ACTIVATION
OP_STATUS ret_stat = SetInnerHTML(frames_doc, html, html_len, actual_parent_element, use_xml_parser);
#ifdef MANUAL_PLUGIN_ACTIVATION
frames_doc->GetHLDocProfile()->ESSetScriptExternal(FALSE);
#endif // MANUAL_PLUGIN_ACTIVATION
return ret_stat;
}
OP_STATUS HTML_Element::SetInnerHTML(FramesDocument* frames_doc, const uni_char* html, int html_len/*=-1*/, HTML_Element *actual_parent_element/*=NULL*/, BOOL use_xml_parser/*=FALSE*/)
{
OP_PROBE4(OP_PROBE_HTML_ELEMENT_SETINNERHTML);
if (!frames_doc)
return OpStatus::ERR;
if (!frames_doc->IsContentChangeAllowed())
return OpStatus::OK;
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc || !hld_profile)
return OpStatus::ERR;
BOOL in_document = FALSE;
if (HTML_Element *root = logdoc->GetRoot())
if (root->IsAncestorOf(this))
in_document = TRUE;
hld_profile->SetHandleScript(FALSE);
hld_profile->SetIsParsingInnerHTML(!in_document);
OP_STATUS status = logdoc->ParseFragment(this, actual_parent_element, html, html_len, use_xml_parser);
hld_profile->SetIsParsingInnerHTML(FALSE);
#ifdef DOCUMENT_EDIT_SUPPORT
hld_profile->SetHandleScript(!frames_doc->GetDesignMode());
#else
hld_profile->SetHandleScript(TRUE);
#endif // DOCUMENT_EDIT_SUPPORT
if (in_document)
{
MarkDirty(frames_doc);
}
return status;
}
void HTML_Element::DOMMarqueeStartStop(BOOL stop)
{
SetSpecialBoolAttr(ATTR_MARQUEE_STOPPED, stop, SpecialNs::NS_LOGDOC);
}
OP_STATUS HTML_Element::DOMCreateNullElement(HTML_Element *&element, DOM_Environment *environment)
{
element = NEW_HTML_Element();
if (!element)
return OpStatus::ERR_NO_MEMORY;
element->SetEndTagFound();
g_ns_manager->GetElementAt(0)->IncRefCount();
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMCreateElement(HTML_Element *&element, DOM_Environment *environment, const uni_char *name, int ns_idx/*=NS_IDX_DEFAULT*/, BOOL case_sensitive/*=FALSE*/)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::ERR;
LogicalDocument *logdoc = frames_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::ERR;
HLDocProfile *hld_profile = logdoc->GetHLDocProfile();
HtmlAttrEntry html_attrs[2];
LogdocXmlName elm_name;
unsigned name_length = name ? uni_strlen(name) : 0;
DOM_LOWERCASE_NAME(name, name_length);
int elm_type = HTM_Lex::GetElementType(name, g_ns_manager->GetNsTypeAt(ns_idx), case_sensitive);
if (elm_type == HE_UNKNOWN)
{
html_attrs[0].ns_idx = SpecialNs::NS_LOGDOC;
html_attrs[0].attr = ATTR_XML_NAME;
html_attrs[0].is_id = FALSE;
html_attrs[0].is_special = TRUE;
html_attrs[0].is_specified = FALSE;
RETURN_IF_MEMORY_ERROR(elm_name.SetName(name, name_length, FALSE));
html_attrs[0].value = reinterpret_cast<uni_char*>(&elm_name); // urgh
html_attrs[0].value_len = 0;
html_attrs[1].attr = ATTR_NULL;
}
else
html_attrs[0].attr = ATTR_NULL;
element = NEW_HTML_Element();
if (!element || element->Construct(hld_profile, ns_idx, (HTML_ElementType) elm_type, html_attrs, HE_INSERTED_BY_DOM))
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
element->SetEndTagFound();
// Add default attributes found in the doctype/dtd
if (logdoc->IsXml())
{
if (XMLDocumentInformation *xmldocinfo = logdoc->GetXMLDocumentInfo())
if (XMLDoctype *xmldoctype = xmldocinfo->GetDoctype())
if (XMLDoctype::Element *elementdecl = xmldoctype->GetElement(element->GetTagName()))
{
XMLDoctype::Attribute **attrs = elementdecl->GetAttributes(), **attrs_end = attrs + elementdecl->GetAttributesCount();
while (attrs != attrs_end)
{
XMLDoctype::Attribute *attr = *attrs++;
const uni_char *defaultvalue = attr->GetDefaultValue();
if (defaultvalue)
{
const uni_char *qname = attr->GetAttributeName();
XMLCompleteNameN completenameN(qname, uni_strlen(qname));
XMLCompleteName completename;
if (OpStatus::IsMemoryError(completename.Set(completenameN)))
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
int attr_ns_idx = NS_IDX_DEFAULT;
if (completename.GetPrefix())
if (HTML_Element *root = logdoc->GetDocRoot())
{
attr_ns_idx = root->FindNamespaceIndex(completename.GetPrefix());
if (attr_ns_idx == NS_IDX_NOT_FOUND)
continue;
}
else
continue;
else
attr_ns_idx = NS_IDX_DEFAULT;
if (OpStatus::IsMemoryError(element->SetAttribute(environment, ATTR_XML, completename.GetLocalPart(), attr_ns_idx, defaultvalue, uni_strlen(defaultvalue), environment->GetCurrentScriptThread(), case_sensitive, attr->GetType() == XMLDoctype::Attribute::TYPE_Tokenized_ID, FALSE)))
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
}
}
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMCloneElement(HTML_Element *&element, DOM_Environment *environment, HTML_Element *prototype, BOOL deep)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::ERR;
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
if (!hld_profile)
return OpStatus::ERR;
element = NEW_HTML_Element();
if (!element)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsMemoryError(element->Construct(hld_profile, prototype)) ||
deep && OpStatus::IsMemoryError(element->DeepClone(hld_profile, prototype)))
{
if (element->Clean(frames_doc))
element->Free(frames_doc);
return OpStatus::ERR_NO_MEMORY;
}
element->SetInserted(HE_INSERTED_BY_DOM);
element->SetEndTagFound();
return OpStatus::OK;
}
#define uni_str_eq_safe(a, b) ((a) == (b) || ((a) && (b) && uni_str_eq(a,b)))
/* static */
OP_BOOLEAN HTML_Element::DOMAreEqualNodes(const HTML_Element *left, HLDocProfile *left_hldoc,
const HTML_Element *right, HLDocProfile *right_hldoc, BOOL case_sensitive)
{
OP_ASSERT(left && right);
OP_ASSERT(left != right); // Don't compare the same nodes, it's a waste of time.
// success means that the code traversed the tree to the end without finding differences.
BOOL oom = FALSE, success = FALSE;
TempBuffer left_buffer, right_buffer;
const HTML_Element *left_stop = left->NextSiblingActual(), *right_stop = right->NextSiblingActual();
OP_NEW_DBG("HTML_Element::DOMAreEqualNodes","logdoc");
while (!success)
{
if (left == NULL || right == NULL)
break;
#ifdef _DEBUG
OP_DBG(("Comparing %d/%S vs. %d/%S\n", left->Type(), left->GetTagName(),
right->Type(), right->GetTagName()));
# define DOMAreEqualNodes_trace(expr) { OP_DBG(("Failed at line %d\n", __LINE__)); expr; }
#else
# define DOMAreEqualNodes_trace(expr) expr
#endif
// Deal with TEXTGROUP here because of Type() perhaps not matching.
if (left->IsText() && right->IsText())
{
// nodeName == #text
// localName == always null
// namespaceURI == always null
// prefix == always null
// nodeValue is the text checked below
const uni_char *left_text, *right_text;
unsigned left_length, right_length;
if (OpStatus::IsMemoryError(DOMAreEqualNodes_GetText(left, left_buffer, left_text, left_length)) ||
OpStatus::IsMemoryError(DOMAreEqualNodes_GetText(right, right_buffer, right_text, right_length)))
{
oom = TRUE;
break;
}
if (left_length != right_length || !uni_str_eq_safe(left_text, right_text))
DOMAreEqualNodes_trace(break);
}
else if (left->Type() != right->Type())
DOMAreEqualNodes_trace(break);
switch (left->Type())
{
case HE_TEXTGROUP:
case HE_TEXT:
// These were handled above.
break;
case HE_PROCINST:
{
// nodeName == proc inst target, checked below
// localName == always null
// namespaceURI == always null
// prefix == always null
// nodeValue checked below after fall through
const uni_char *left_target = left->GetStringAttr(ATTR_TARGET, NS_IDX_DEFAULT);
const uni_char *right_target = right->GetStringAttr(ATTR_TARGET, NS_IDX_DEFAULT);
if (!uni_str_eq_safe(left_target, right_target))
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
// allow fall through
}
case HE_COMMENT:
{
// nodeName == #comment or the proc inst target, checked above
// localName == always null
// namespaceURI == always null
// prefix == always null
// nodeValue is the comment text or proc inst data, checked below
const uni_char *left_content = left->GetStringAttr(ATTR_CONTENT);
const uni_char *right_content = right->GetStringAttr(ATTR_CONTENT);
if (!uni_str_eq_safe(left_content, right_content))
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
break;
}
case HE_ENTITY:
case HE_ENTITYREF:
// These are never kept in the tree after parsing, nor is the DOM code enabled.
OP_ASSERT(!"Not supported ATM");
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
case HE_DOCTYPE:
{
// nodeName == the dtd name
// localName == always null
// namespaceURI == always null
// prefix == always null
// nodeValue always null
// publicId, systemId and internalSubset need to be checked too because it's a doctype
// and need to check too the entities map and notations map
const uni_char *left_pubid, *left_sysid, *left_name, *left_intsubset;
const uni_char *right_pubid, *right_sysid, *right_name, *right_intsubset;
DOMAreEqualNodes_GetDocTypeHEInfo(left, left_hldoc, left_pubid, left_sysid, left_name, left_intsubset);
DOMAreEqualNodes_GetDocTypeHEInfo(right, right_hldoc, right_pubid, right_sysid, right_name, right_intsubset);
if (!uni_str_eq_safe(left_pubid, right_pubid) ||
!uni_str_eq_safe(left_sysid, right_sysid) ||
!uni_str_eq_safe(left_name, right_name) ||
!uni_str_eq_safe(left_intsubset, right_intsubset))
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
break;
}
case HE_DOC_ROOT:
case HE_UNKNOWN:
default: // includes all HE types after HE_UNKNOWN
if (left->Type() != HE_DOC_ROOT)
{
OP_ASSERT(Markup::IsRealElement(left->Type()));
// nodeName == elements name or tagName. Special case for unknown types, all others are already checked by Type()
// localName == the tagName (again)
// namespaceURI == compare namespace index
// prefix == compare namespace index
// nodeValue == null
if (left->Type() == HE_UNKNOWN)
{
const uni_char *left_tag, *right_tag;
left_tag = left->GetTagName();
right_tag = right->GetTagName();
OP_ASSERT(left_tag && right_tag);
if (case_sensitive ? uni_strcmp(left_tag, right_tag) != 0 : uni_stricmp(left_tag, right_tag) != 0)
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
}
if (left->GetNsIdx() != right->GetNsIdx())
// Compares namespace and prefix.
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
// Compare attributes -> O(N^2) is pain
unsigned left_attr_count = 0;
int left_attr_index = 0, attr_size = left->GetAttrSize();
for (; left_attr_index < attr_size; left_attr_index++)
{
if (left->GetAttrIsSpecial(left_attr_index))
continue;
left_attr_count++;
// nodeName == the attr name
// localName == the attr name
// namespaceURI == compare namespace index
// prefix == compare namespace index
// nodeValue == the attr value
//int attr, const uni_char *name, int ns_idx, BOOL case_sensitive, BOOL strict_ns
int right_attr_index = right->FindAttrIndex(
left->GetAttrItem(left_attr_index),
left->GetAttrNameString(left_attr_index),
left->GetAttrNs(left_attr_index),
case_sensitive,
FALSE);
// Attr not found -> this validates nodeName, localName, namespaceURI and prefix (hopefully).
if (right_attr_index < 0)
DOMAreEqualNodes_trace(break);
ItemType attr_type = left->GetItemType(left_attr_index);
if (attr_type == right->GetItemType(right_attr_index))
{
void *left_attr_value = left->GetValueItem(left_attr_index);
if (!AreAttributesEqual(left->GetAttrItem(left_attr_index), attr_type, left_attr_value, right->GetValueItem(right_attr_index)))
{
if (attr_type == ITEM_TYPE_COMPLEX && !static_cast<ComplexAttr*>(left_attr_value)->Equals(static_cast<ComplexAttr*>(left_attr_value)))
{
// Unfortunate hack. Most derived classes from
// ComplexAttr do not implement Equals so we need
// to fallback to string serialization and comparison,
// if that works too.
goto DOMAreEqualNodes_compareAttrsString;
}
DOMAreEqualNodes_trace(break);
}
}
else
{
DOMAreEqualNodes_compareAttrsString:
// Different types... just serialize to string. This section will rarely run anyway,
// because the attributes are the same, so they will most likely be of the same type.
left_buffer.Clear();
right_buffer.Clear();
const uni_char *left_value = left->GetAttrValueValue(left_attr_index, left->GetAttrItem(left_attr_index), HE_UNKNOWN, &left_buffer);
// Need to copy the value to the TempBuffer because of use of global shared buffers by logdoc.
if (left_value && left_value != left_buffer.GetStorage())
{
if (OpStatus::IsMemoryError(left_buffer.Append(left_value)))
{
oom = TRUE;
DOMAreEqualNodes_trace(break);
}
else
left_value = left_buffer.GetStorage();
}
const uni_char *right_value = right->GetAttrValueValue(right_attr_index, right->GetAttrItem(right_attr_index), HE_UNKNOWN, &right_buffer);
if (!uni_str_eq_safe(left_value, right_value))
DOMAreEqualNodes_trace(break);
}
}
// Different number of attributes or loop aborted before
// traversing all attributes.
if (left_attr_index < attr_size || left_attr_count != (unsigned)right->GetAttrCount())
DOMAreEqualNodes_trace(goto DOMAreEqualNodes_end);
}
}
if (left->IsText())
{
// Special case so this loop won't go through
// the children of HE_TEXTGROUP.
left = left->NextSiblingActual();
right = right->NextSiblingActual();
}
else
{
left = left->NextActual();
right = right->NextActual();
}
if (left == left_stop && right == right_stop)
{
// Both trees are the same size, and if we
// got here then they are also equal.
success = TRUE;
break;
}
else if (left == left_stop || right == right_stop)
// One of the trees is bigger than the other.
break;
}
DOMAreEqualNodes_end:
if (oom)
return OpStatus::ERR_NO_MEMORY;
else if (success)
return OpBoolean::IS_TRUE;
else
return OpBoolean::IS_FALSE;
}
#undef uni_str_eq_safe
/* static */
void HTML_Element::DOMAreEqualNodes_GetDocTypeHEInfo(const HTML_Element *element, HLDocProfile *hldoc,
const uni_char *&pubid, const uni_char *&sysid, const uni_char *&name, const uni_char *&intsubset)
{
const XMLDocumentInformation *docinfo = element->GetXMLDocumentInfo();
if (docinfo)
{
pubid = docinfo->GetPublicId();
sysid = docinfo->GetSystemId();
name = docinfo->GetDoctypeName();
intsubset = docinfo->GetInternalSubset();
}
else if (hldoc)
{
pubid = hldoc->GetDoctypePubId();
sysid = hldoc->GetDoctypeSysId();
name = hldoc->GetDoctypeName();
intsubset = NULL;
}
else
pubid = sysid = name = intsubset = NULL;
}
/* static */
OP_STATUS HTML_Element::DOMAreEqualNodes_GetText(const HTML_Element *elm, TempBuffer &buffer, const uni_char *&result, unsigned &result_length)
{
if (elm->Type() == HE_TEXTGROUP)
{
buffer.Clear();
for (HTML_Element *child = elm->FirstChild(); child; child = child->Suc())
{
OP_ASSERT(child->Type() == HE_TEXT);
RETURN_IF_ERROR(buffer.Append(child->Content(), child->ContentLength()));
}
result = buffer.GetStorage();
result_length = buffer.Length();
}
else
{
result = elm->Content();
result_length = elm->ContentLength();
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMCreateTextNode(HTML_Element *&element, DOM_Environment *environment, const uni_char *text, BOOL comment, BOOL cdata_section)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::ERR;
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
if (!hld_profile)
return OpStatus::ERR;
if (comment)
{
element = NEW_HTML_Element();
if (!element)
return OpStatus::ERR_NO_MEMORY;
HtmlAttrEntry ha_list[2];
ha_list[0].attr = ATTR_CONTENT;
ha_list[0].ns_idx = NS_IDX_DEFAULT;
ha_list[0].value = text;
ha_list[0].value_len = uni_strlen(text);
ha_list[1].attr = ATTR_NULL;
if (element->Construct(hld_profile, NS_IDX_HTML, HE_COMMENT, ha_list, HE_INSERTED_BY_DOM) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
}
else
{
BOOL expand_wml_vars = FALSE; // Or? It used to be this way, but that doesn't mean it's right
element = HTML_Element::CreateText(text, uni_strlen(text), FALSE, cdata_section, expand_wml_vars);
if (!element)
{
return OpStatus::ERR_NO_MEMORY;
}
element->SetInserted(HE_INSERTED_BY_DOM);
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMCreateProcessingInstruction(HTML_Element *&element, DOM_Environment *environment, const uni_char *target, const uni_char *data)
{
OP_ASSERT(target);
OP_ASSERT(data);
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::ERR;
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
if (!hld_profile)
return OpStatus::ERR;
element = NEW_HTML_Element();
if (!element)
return OpStatus::ERR_NO_MEMORY;
HtmlAttrEntry ha_list[9];
ha_list[0].attr = ATTR_TARGET;
ha_list[0].ns_idx = NS_IDX_DEFAULT;
ha_list[0].value = target;
ha_list[0].value_len = uni_strlen(target);
ha_list[1].attr = ATTR_CONTENT;
ha_list[1].ns_idx = NS_IDX_DEFAULT;
ha_list[1].value = data;
ha_list[1].value_len = uni_strlen(data);
ha_list[2].attr = ATTR_NULL;
if (uni_str_eq(target, "xml-stylesheet"))
{
int lexer_status;
int ha_index = 2;
int attributes[] = { ATTR_HREF, ATTR_TYPE, ATTR_TITLE, ATTR_MEDIA, ATTR_CHARSET, ATTR_ALTERNATE };
int attribute_found[] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE };
OP_ASSERT(sizeof(attributes) == sizeof(attribute_found));
uni_char* attr_p = const_cast<uni_char*>(data); // HTM_Lex doesn't want a const pointer
uni_char* end = const_cast<uni_char*>(data + ha_list[1].value_len);
do
{
lexer_status = htmLex->GetAttrValue(&attr_p, end, ha_list+ha_index,
TRUE, hld_profile, FALSE, NS_HTML, 1, FALSE);
if (lexer_status == HTM_Lex::ATTR_RESULT_FOUND)
{
for (size_t i = 0; i < sizeof(attributes)/sizeof(*attributes); i++)
{
if (ha_list[ha_index].attr == attributes[i] && !attribute_found[i])
{
ha_index++;
attribute_found[i] = TRUE;
break;
}
}
}
ha_list[ha_index].attr = ATTR_NULL;
}
while (lexer_status == HTM_Lex::ATTR_RESULT_FOUND);
}
if (element->Construct(hld_profile, NS_IDX_HTML, HE_PROCINST, ha_list, HE_INSERTED_BY_DOM) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DOMCreateDoctype(HTML_Element *&element, DOM_Environment *environment, XMLDocumentInformation *docinfo)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!frames_doc)
return OpStatus::ERR;
HLDocProfile *hld_profile = frames_doc->GetHLDocProfile();
if (!hld_profile)
return OpStatus::ERR;
element = NEW_HTML_Element();
if (!element)
return OpStatus::ERR_NO_MEMORY;
HtmlAttrEntry ha_list[1];
ha_list[0].attr = ATTR_NULL;
if (element->Construct(hld_profile, NS_IDX_HTML, HE_DOCTYPE, ha_list, HE_INSERTED_BY_DOM) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
if (docinfo && docinfo->GetDoctypeDeclarationPresent())
{
XMLDocumentInfoAttr *attr;
if (OpStatus::IsMemoryError(XMLDocumentInfoAttr::Make(attr, docinfo)))
{
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
if (element->SetSpecialAttr(ATTR_XMLDOCUMENTINFO, ITEM_TYPE_COMPLEX, static_cast<ComplexAttr *>(attr), TRUE, SpecialNs::NS_LOGDOC) == -1)
{
OP_DELETE(attr);
DELETE_HTML_Element(element);
return OpStatus::ERR_NO_MEMORY;
}
}
return OpStatus::OK;
}
void HTML_Element::DOMFreeElement(HTML_Element *element, DOM_Environment *environment)
{
if (element && element->Clean(environment))
element->Free(environment);
}
BOOL HTML_Element::HasEventHandlerAttribute(FramesDocument *doc, DOM_EventType type)
{
for (unsigned index = 0, size = GetAttrSize(); index < size; ++index)
if (GetAttrIsEvent(index) && GetEventType(GetAttrItem(index), GetResolvedAttrNs(index)) == type)
return TRUE;
return FALSE;
}
BOOL HTML_Element::HasEventHandlerAttributes(FramesDocument *doc)
{
for (unsigned index = 0, size = GetAttrSize(); index < size; ++index)
if (GetAttrIsEvent(index))
return TRUE;
return FALSE;
}
BOOL HTML_Element::DOMHasEventHandlerAttribute(DOM_Environment *environment, DOM_EventType type)
{
return HasEventHandlerAttribute(environment->GetFramesDocument(), type);
}
BOOL HTML_Element::DOMHasEventHandlerAttributes(DOM_Environment *environment)
{
return HasEventHandlerAttributes(environment->GetFramesDocument());
}
OP_STATUS HTML_Element::DOMSetEventHandlers(DOM_Environment *environment)
{
FramesDocument *doc = environment->GetFramesDocument();
if (doc
#ifdef DOCUMENT_EDIT_SUPPORT
&& !doc->GetDesignMode()
#endif
)
for (unsigned index = 0, size = GetAttrSize(); index < size; ++index)
if (GetAttrIsEvent(index))
{
short attr_item = GetAttrItem(index);
int ns_idx = GetResolvedAttrNs(index);
NS_Type ns_type = g_ns_manager->GetNsTypeAt(ns_idx);
BOOL already_set = FALSE;
for (unsigned index2 = index; index2 != 0 && !already_set; --index2)
if (GetAttrItem(index2 - 1) == attr_item && g_ns_manager->GetNsTypeAt(GetResolvedAttrNs(index2 - 1)) == ns_type)
already_set = TRUE;
if (!already_set)
{
DOM_EventType type = GetEventType(GetAttrItem(index), ns_idx);
OP_ASSERT(type != DOM_EVENT_NONE);
const uni_char *value = (const uni_char *) GetValueItem(index);
RETURN_IF_ERROR(SetEventHandler(doc, type, value, uni_strlen(value)));
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::SendEvent(DOM_EventType event, FramesDocument *doc)
{
if (event == ONLOAD || event == ONERROR)
if (SetSpecialBoolAttr(ATTR_INLINE_ONLOAD_SENT, TRUE, SpecialNs::NS_LOGDOC) == -1)
return OpStatus::ERR_NO_MEMORY;
#ifdef DELAYED_SCRIPT_EXECUTION
if (GetInserted() == HE_INSERTED_BY_PARSE_AHEAD && (event == ONLOAD || event == ONERROR))
{
SetSpecialBoolAttr(event == ONLOAD ? ATTR_JS_DELAYED_ONLOAD : ATTR_JS_DELAYED_ONERROR, TRUE, SpecialNs::NS_LOGDOC);
return OpStatus::OK;
}
#endif // DELAYED_SCRIPT_EXECUTION
return doc->HandleEvent(event, NULL, this, SHIFTKEY_NONE);
}
BOOL HTML_Element::HasEventHandler(FramesDocument *doc, DOM_EventType type, BOOL local_only)
{
DOM_Environment *environment = doc->GetDOMEnvironment();
if (environment)
if (local_only)
return environment->HasLocalEventHandler(this, type);
else
return environment->HasEventHandler(this, type);
else
{
HTML_Element *element = this;
unsigned count;
if (doc->GetLogicalDocument()->GetEventHandlerCount(type, count) && count == 0)
return FALSE;
while (element)
{
if (DOM_Utils::GetEventTargetElement(element)->HasEventHandlerAttribute(doc, type))
return TRUE;
else if (local_only)
break;
else
element = DOM_Utils::GetEventPathParent(element, this);
}
return FALSE;
}
}
#ifdef XSLT_SUPPORT
void HTML_Element::XSLTStripWhitespace(LogicalDocument *logdoc, XSLT_Stylesheet *stylesheet)
{
LogdocXSLTHandler::StripWhitespace(logdoc, this, stylesheet);
}
#endif // XSLT_SUPPORT
const uni_char* HTML_Element::GetXmlName() const
{
LogdocXmlName *name = static_cast<LogdocXmlName*>(GetSpecialAttr(ATTR_XML_NAME, ITEM_TYPE_COMPLEX, (void*)NULL, SpecialNs::NS_LOGDOC));
return name ? name->GetName().GetLocalPart() : NULL;
}
const uni_char* HTML_Element::GetTagName(BOOL as_uppercase, TempBuffer *buffer) const
{
Markup::Type type = Type();
if (Markup::HasNameEntry(type))
return HTM_Lex::GetElementString(type, GetNsIdx(), as_uppercase);
else if (type == Markup::HTE_UNKNOWN)
{
const uni_char *name = GetXmlName();
if (!as_uppercase || !buffer)
return name;
if (OpStatus::IsError(buffer->Append(name)))
return NULL;
uni_char *tmp_name = buffer->GetStorage();
if (tmp_name)
{
while (*tmp_name)
{
if (*tmp_name >= 'a' && *tmp_name <= 'z')
*tmp_name = *tmp_name - 'a' + 'A';
tmp_name++;
}
}
return buffer->GetStorage();
}
else
return NULL;
}
const uni_char* HTML_Element::GetAttrNameString(int i) const
{
if (GetAttrIsSpecial(i))
return NULL;
Markup::AttrType attr_code = GetAttrItem(i);
if (attr_code == ATTR_XML)
return (uni_char*)GetValueItem(i);
return HTM_Lex::GetAttributeString(attr_code, g_ns_manager->GetNsTypeAt(GetResolvedAttrNs(i)));
}
const uni_char* HTML_Element::GetAttrValueString(int i) const
{
return GetAttrValueValue(i, GetAttrItem(i));
}
void HTML_Element::SetFormObjectBackup(FormObject* fobj)
{
SetSpecialAttr(ATTR_FORMOBJECT_BACKUP, ITEM_TYPE_NUM, (void*) fobj, TRUE, SpecialNs::NS_LOGDOC);
}
FormObject* HTML_Element::GetFormObjectBackup()
{
return (FormObject*) GetSpecialAttr(ATTR_FORMOBJECT_BACKUP, ITEM_TYPE_NUM, NULL, SpecialNs::NS_LOGDOC);
}
void HTML_Element::DestroyFormObjectBackup()
{
FormObject* form_object = GetFormObjectBackup();
if (form_object)
{
OP_DELETE(form_object);
SetFormObjectBackup(NULL);
}
}
#ifdef DOCUMENT_EDIT_SUPPORT
BOOL HTML_Element::IsContentEditable(BOOL inherit)
{
HTML_Element* helm = this;
while(helm)
{
/* MS spec: "Though the TABLE, COL, COLGROUP, TBODY, TD, TFOOT, TH, THEAD, and TR elements cannot
be set as content editable directly, a content editable SPAN, or DIV element can be placed
inside the individual table cells (TD and TH elements). See the example below." */
BOOL allowed = TRUE;
NS_Type ns = helm->GetNsType();
if(ns == NS_HTML)
{
switch (helm->Type())
{
case HE_TABLE:
case HE_COL:
case HE_COLGROUP:
case HE_TBODY:
case HE_TD:
case HE_TFOOT:
case HE_TH:
case HE_THEAD:
case HE_TR:
allowed = FALSE;
}
}
if (allowed)
{
BOOL3 is_content_editable = helm->GetContentEditableValue();
if (is_content_editable == YES)
return TRUE;
else if (is_content_editable == NO)
return FALSE;
}
if (!inherit)
return FALSE;
helm = helm->ParentActual();
}
return FALSE;
}
BOOL3
HTML_Element::GetContentEditableValue()
{
const uni_char* val = GetStringAttr(ATTR_CONTENTEDITABLE);
if (val)
{
if (uni_stricmp(val, UNI_L("TRUE")) == 0 || !*val) // "true" or the empty string turns on documentedit
return YES;
else if (uni_stricmp(val, UNI_L("FALSE")) == 0)
return NO;
}
return MAYBE;
}
#endif // DOCUMENT_EDIT_SUPPORT
#if defined(DOCUMENT_EDIT_SUPPORT) && defined(WIDGETS_IME_SUPPORT)
void HTML_Element::SetIMEStyling(int value)
{
SetSpecialNumAttr(ATTR_IME_STYLING, value, SpecialNs::NS_LOGDOC);
}
int HTML_Element::GetIMEStyling()
{
return (int) GetSpecialNumAttr(ATTR_IME_STYLING, SpecialNs::NS_LOGDOC);
}
#endif
#ifdef SVG_SUPPORT
const ClassAttribute* HTML_Element::GetSvgClassAttribute() const
{
return g_svg_manager->GetClassAttribute(const_cast<HTML_Element*>(this), FALSE);
}
void HTML_Element::SetSVGContext(SVGContext* ctx)
{
OP_ASSERT(IsText() || GetNsType() == NS_SVG); // Dont' call this for random elements. Only SVG elements can store an SVGContext
OP_ASSERT(ctx || GetSVGContext());
OP_ASSERT(!ctx || !GetSVGContext());
svg_context = ctx;
}
void HTML_Element::DestroySVGContext()
{
if (IsText() || GetNsType() == NS_SVG)
{
OP_DELETE(svg_context);
svg_context = NULL;
}
}
#endif // SVG_SUPPORT
HEListElm* HTML_Element::BgImageIterator::Next()
{
if (!m_current)
m_current = m_elm->GetFirstReference();
else
m_current = m_current->NextRef();
while (m_current)
{
if (m_current->IsA(ElementRef::HELISTELM))
{
HEListElm *ref = static_cast<HEListElm*>(m_current);
if (ref->GetInlineType() == BGIMAGE_INLINE || ref->GetInlineType() == EXTRA_BGIMAGE_INLINE)
return ref;
}
m_current = m_current->NextRef();
}
return NULL;
}
HEListElm* HTML_Element::GetHEListElmForInline(InlineResourceType inline_type)
{
ElementRef *iter = m_first_ref;
while (iter)
{
if (iter->IsA(ElementRef::HELISTELM))
{
HEListElm *ref = static_cast<HEListElm*>(iter);
if (ref->GetInlineType() == inline_type)
return ref;
}
iter = iter->NextRef();
}
return NULL;
}
HEListElm* HTML_Element::GetHEListElm(BOOL background)
{
return GetHEListElmForInline(background ? BGIMAGE_INLINE : IMAGE_INLINE);
}
void HTML_Element::UndisplayImage(FramesDocument* doc, BOOL background)
{
if (background)
{
HTML_Element::BgImageIterator iter(this);
HEListElm *iter_elm = iter.Next();
while (iter_elm)
{
iter_elm->Undisplay();
iter_elm = iter.Next();
}
}
else
{
HEListElm* helm = GetHEListElmForInline(IMAGE_INLINE);
if (helm)
helm->Undisplay();
}
}
#ifdef _PRINT_SUPPORT_
HTML_Element* HTML_Element::CopyAll(HLDocProfile* hld_profile)
{
HTML_Element* copy_root = NEW_HTML_Element();
if (!copy_root || copy_root->Construct(hld_profile, this, TRUE) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(copy_root);
hld_profile->SetIsOutOfMemory(TRUE);
return NULL;
}
HTML_Element* this_iter = this;
HTML_Element* copy_iter = copy_root;
HTML_Element* next;
BOOL sidestep = FALSE;
while (this_iter)
{
HTML_Element* first_child_actual = this_iter->FirstChildActual();
HTML_Element* suc_actual = NULL;
if (!first_child_actual || sidestep)
suc_actual = this_iter->SucActual();
if (first_child_actual || suc_actual)
{
if (first_child_actual && !sidestep)
next = first_child_actual;
else
next = suc_actual;
HTML_Element* new_elm = NEW_HTML_Element();
if (!new_elm || new_elm->Construct(hld_profile, next, TRUE) == OpStatus::ERR_NO_MEMORY)
{
DELETE_HTML_Element(new_elm);
hld_profile->SetIsOutOfMemory(TRUE);
copy_root->Free(hld_profile->GetFramesDocument());
return NULL;
}
if (new_elm->GetNs() == Markup::HTML
&& (new_elm->Type() == HE_IFRAME || new_elm->Type() == HE_FRAME || new_elm->Type() == HE_FRAMESET || new_elm->Type() == HE_OBJECT))
{
FramesDocElm *fde = FramesDocElm::GetFrmDocElmByHTML(next);
if (fde)
fde->SetPrintTwinElm(new_elm);
}
if (this_iter->FirstChildActual() && !sidestep)
new_elm->Under(copy_iter);
else
new_elm->Follow(copy_iter);
sidestep = FALSE;
this_iter = next;
copy_iter = new_elm;
}
else
{
while (this_iter && !this_iter->SucActual())
{
this_iter = this_iter->ParentActual();
copy_iter = copy_iter->ParentActual();
}
sidestep = TRUE;
}
}
return copy_root;
}
#endif // _PRINT_SUPPORT_
URL*
HTML_Element::GetUrlAttr(short attr, int ns_idx/*=NS_IDX_HTML*/, LogicalDocument *logdoc/*=NULL*/)
{
OP_PROBE4(OP_PROBE_LOGDOC_GETURLATTR);
int index = FindAttrIndex(attr, NULL, ns_idx, GetNsIdx() != NS_IDX_HTML, ns_idx != NS_IDX_HTML);
if (index == -1)
return NULL;
ns_idx = GetAttrNs(index);
UrlAndStringAttr *url_attr;
if (GetItemType(index) == ITEM_TYPE_STRING)
{
uni_char *string_val = static_cast<uni_char*>(GetValueItem(index));
OP_STATUS oom = UrlAndStringAttr::Create(string_val, uni_strlen(string_val), url_attr);
if (OpStatus::IsMemoryError(oom))
return NULL;
ReplaceAttrLocal(index, attr, ITEM_TYPE_URL_AND_STRING, (void*)url_attr, ns_idx, TRUE, FALSE, FALSE, GetAttrIsSpecified(index), FALSE);
}
else
url_attr = static_cast<UrlAndStringAttr*>(GetValueItem(index));
if (URL* cached_url = url_attr->GetResolvedUrl())
return cached_url;
const uni_char *url_str = url_attr->GetString();
if (!url_str)
return NULL;
URL ret_url;
#ifdef _PLUGIN_SUPPORT_
// URLs with only whitespace should be treated as the empty string (DSK-154635)
if (attr == ATTR_DATA && WhiteSpaceOnly(url_str))
ret_url = ResolveUrl(UNI_L(""), logdoc, attr);
else
#endif // _PLUGIN_SUPPORT_
ret_url = ResolveUrl(url_str, logdoc, attr);
OP_ASSERT(uni_strchr(url_str, ':') || logdoc); // Or we will put a relative unresolved url in the cache and all future accesses of it will be wrong
#ifdef WEB_TURBO_MODE
// Plugin URLs should not use Turbo
if ((packed2.object_is_embed || Type() == HE_EMBED) && ret_url.GetAttribute(URL::KUsesTurbo))
{
const OpStringC8 url_str = ret_url.GetAttribute(URL::KName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect);
ret_url = g_url_api->GetURL(url_str);
}
#endif // WEB_TURBO_MODE
#if defined LOGDOC_LOAD_IMAGES_FROM_PARSER && defined _WML_SUPPORT_
/* In WML images may have attribute set to some variable. Moreover variable value may be set later than during parsing - e.g. by the timer - so
* in such a case, if URL can not be resolved, do not cache it.
*/
if (logdoc && Type() == HE_IMG && ret_url.IsEmpty() && logdoc->GetHLDocProfile()->IsWml() && logdoc->GetHLDocProfile()->HasWmlContent() &&
logdoc->GetHLDocProfile()->WMLGetContext()->NeedSubstitution(url_str, uni_strlen(url_str)))
return NULL;
#endif // LOGDOC_LOAD_IMAGES_FROM_PARSER && _WML_SUPPORT_
if (OpStatus::IsMemoryError(url_attr->SetResolvedUrl(ret_url)))
return NULL;
return url_attr->GetResolvedUrl();
}
URL
HTML_Element::DeriveBaseUrl(LogicalDocument *&logdoc) const
{
OP_PROBE4(OP_PROBE_LOGDOC_DERIVEBASEURL);
URL parent_base;
if (Parent())
{
parent_base = Parent()->DeriveBaseUrl(logdoc);
}
else
{
if (!logdoc)
{
if (Type() == HE_DOC_ROOT)
{
logdoc = static_cast<LogicalDocument *>(static_cast<ComplexAttr *>(GetSpecialAttr(ATTR_LOGDOC,
ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_LOGDOC)));
}
if (!logdoc)
return URL();
}
if (URL *base_url = logdoc->GetBaseURL())
{
// See 2.5 URLs and 2.5.1 Terminology in HTML5 on base url and url resolving.
if (IsAboutBlankURL(*base_url))
{
FramesDocument *frames_doc = logdoc->GetDocument();
FramesDocument *candidate = NULL;
URL *candidate_base_url = NULL;
while (frames_doc)
{
LogicalDocument *candidate_logdoc = frames_doc->GetLogicalDocument();
candidate_base_url = candidate_logdoc ? candidate_logdoc->GetBaseURL() : NULL;
if (!IsAboutBlankURL(frames_doc->GetURL()) && candidate_base_url)
{
if (!IsAboutBlankURL(*candidate_base_url))
{
candidate = frames_doc;
break;
}
}
frames_doc = frames_doc->GetParentDoc();
}
if (candidate)
parent_base = *candidate_base_url;
else
parent_base = *base_url;
}
else
parent_base = *base_url;
}
}
const uni_char *xml_base = GetStringAttr(XMLA_BASE, NS_IDX_XML);
if (xml_base)
{
return g_url_api->GetURL(parent_base, xml_base);
}
return parent_base;
}
URL
#ifdef WEB_TURBO_MODE
HTML_Element::ResolveUrl(const uni_char *url_str, LogicalDocument *logdoc/*=NULL*/, short attr/*=ATTR_NULL*/, BOOL set_context_id/*=FALSE*/) const
#else // WEB_TURBO_MODE
HTML_Element::ResolveUrl(const uni_char *url_str, LogicalDocument *logdoc/*=NULL*/, short attr/*=ATTR_NULL*/) const
#endif // WEB_TURBO_MODE
{
OP_PROBE4(OP_PROBE_LOGDOC_RESOLVEURL);
if (!url_str)
return URL();
URL base_url = DeriveBaseUrl(logdoc);
if (!logdoc)
{
// OP_ASSERT(!"The url will be resolved as an absolute url since we couldn't find a base url.");
// Whatever you wanted to do, see if you can do it some other way that
// doesn't trigger an url resolve.
return g_url_api->GetURL(url_str);
}
#ifdef _WML_SUPPORT_
if (logdoc->IsWml())
{
WML_Context *wc = logdoc->GetHLDocProfile()->WMLGetContext();
uni_char *sub_buf = (uni_char*)g_memory_manager->GetTempBuf();
wc->SubstituteVars(url_str, uni_strlen(url_str), sub_buf,
UNICODE_DOWNSIZE(g_memory_manager->GetTempBufLen()), FALSE);
url_str = sub_buf;
}
#endif // _WML_SUPPORT_
URL doc_url;
if (logdoc->GetFramesDocument())
doc_url = logdoc->GetFramesDocument()->GetURL();
else
doc_url = base_url;
if (attr == ATTR_DATA && Type() == HE_OBJECT)
{
const uni_char *codebase_str = GetStringAttr(ATTR_CODEBASE);
if (codebase_str)
{
OpString tmp_str;
if (tmp_str.Set(codebase_str) == OpStatus::ERR_NO_MEMORY)
return URL();
if (tmp_str.Find("adobe.com/pub/shockwave/cabs") == KNotFound &&
tmp_str.Find("macromedia.com/pub/shockwave/cabs") == KNotFound &&
tmp_str.Find("macromedia.com/flash2/cabs") == KNotFound &&
tmp_str.Find("activex.microsoft.com/activex/controls/mplayer/") == KNotFound)
{
base_url = g_url_api->GetURL(base_url, codebase_str);
}
}
}
else if (attr == ATTR_USEMAP)
base_url = doc_url;
if (!*url_str && logdoc->GetFramesDocument()
&& logdoc->GetFramesDocument()->IsGeneratedDocument())
{
#ifdef WEB_TURBO_MODE
if (set_context_id)
{
const OpStringC doc_url_str
= doc_url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI,
URL::KNoRedirect);
URL new_url = g_url_api->GetURL(doc_url_str, logdoc->GetCurrentContextId());
return new_url;
}
else
#endif // WEB_TURBO_MODE
return doc_url;
}
else
{
URL *urlp = CreateUrlFromString(url_str, uni_strlen(url_str),
&base_url, logdoc->GetHLDocProfile(),
Type() == HE_IMG && attr == ATTR_SRC, // check_for_internal_img
attr == ATTR_HREF && Type() != Markup::HTE_LINK // accept_empty -> if true, empty str resolves to base url.
#ifdef WEB_TURBO_MODE
, set_context_id
#endif // WEB_TURBO_MODE
);
if (!urlp)
return URL();
URL resolved_url = *urlp;
OP_DELETE(urlp);
return resolved_url;
}
}
void HTML_Element::ClearResolvedUrls()
{
if (Type() == HE_TEXT)
return;
int stop_at = GetAttrSize();
for (int i = 0; i < stop_at; i++)
{
if (data.attrs[i].GetType() == ITEM_TYPE_URL_AND_STRING)
{
UrlAndStringAttr *url_attr = static_cast<UrlAndStringAttr*>(data.attrs[i].GetValue());
OpStatus::Ignore(url_attr->SetResolvedUrl(static_cast<URL*>(NULL)));
}
}
HTML_Element *child = FirstChild();
while (child)
{
child->ClearResolvedUrls();
child = child->Suc();
}
}
BOOL HTML_Element::HasParentTable() const
{
HTML_Element* parent = ParentActualStyle();
while (parent && parent->Type() != Markup::HTE_TABLE)
parent = parent->ParentActualStyle();
return parent != NULL;
}
BOOL HTML_Element::HasParentElement(HTML_ElementType type, int ns_idx /* = NS_IDX_HTML*/, BOOL stop_at_special /* = TRUE*/) const
{
// The list of elements below must be kept somewhat in sync with the code to find a matching element
// to end in HTML_Element::Load or we will get hangs like the one in bug 339368.
// Exclude the root element from this (see method documentation).
for (const HTML_Element* parent = this; parent->Parent(); parent = parent->Parent())
{
HTML_ElementType parent_type = parent->Type();
if (parent_type == type && g_ns_manager->CompareNsType(parent->GetNsIdx(), ns_idx))
return TRUE;
else if (stop_at_special &&
(parent_type == HE_TABLE || parent_type == HE_BUTTON || parent_type == HE_SELECT || parent_type == HE_DATALIST || parent_type == HE_APPLET || parent_type == HE_OBJECT || parent_type == HE_MARQUEE) &&
parent->GetNsType() == NS_HTML)
return FALSE;
}
return FALSE;
}
void HTML_Element::MarkContainersDirty(FramesDocument* doc)
{
if (layout_box)
layout_box->MarkContainersDirty(doc);
}
void HTML_Element::MarkDirty(FramesDocument* doc, BOOL delete_minmax_widths, BOOL needs_update)
{
if (!doc)
return;
LayoutWorkplace* wp = doc->GetLogicalDocument() ? doc->GetLogicalDocument()->GetLayoutWorkplace() : NULL;
#ifdef _DEBUG
if (wp)
// marking things dirty during traverse is forbidden. Marking thigs dirty during reflow is only allowed under certain circumstances.
OP_ASSERT(!wp->IsTraversing() && !wp->IsReflowing());
/* we can not mark dirty on a -o-content-size iframe document while the parent doc is traversing. */
if (doc->IsInlineFrame() && doc->GetDocManager()->GetFrame() && doc->GetDocManager()->GetFrame()->GetNotifyParentOnContentChange())
{
FramesDocument* parent_doc = doc->GetDocManager() ? doc->GetDocManager()->GetParentDoc() : NULL;
LayoutWorkplace* parent_wp = parent_doc && parent_doc->GetLogicalDocument() ? parent_doc->GetLogicalDocument()->GetLayoutWorkplace() : NULL;
if (parent_wp)
OP_ASSERT(!parent_wp->IsTraversing());
}
#endif
#ifdef LAYOUT_YIELD_REFLOW
/* The tree changed, we need to mark the yield cascade dirty and discard it. */
if (wp)
wp->MarkYieldCascade(this);
#endif // LAYOUT_YIELD_REFLOW
#ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG && Type() != Markup::SVGE_SVG)
{
HTML_Element* parent = Parent();
while (parent)
{
if (parent->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
{
// SVG element inside a SVG block, so it won't affect the HTML layout engine
return;
}
parent = parent->Parent();
}
}
#endif // SVG_SUPPORT
if (needs_update)
packed2.needs_update = TRUE;
HTML_Element *elm = this;
do
{
#ifdef SVG_SUPPORT
if (elm->IsMatchingType(Markup::SVGE_FOREIGNOBJECT, NS_SVG) && elm->HasAttr(Markup::XLINKA_HREF, NS_IDX_XLINK))
{
g_svg_manager->HandleInlineChanged(doc, elm);
return;
}
#endif // SVG_SUPPORT
if (!(elm->packed2.dirty & ELM_DIRTY) ||
(delete_minmax_widths && !(elm->packed2.dirty & ELM_MINMAX_DELETED)))
{
elm->packed2.dirty |= ELM_DIRTY;
if (delete_minmax_widths)
{
if (elm->layout_box)
elm->layout_box->ClearMinMaxWidth();
elm->packed2.dirty |= ELM_MINMAX_DELETED;
}
HTML_Element* parent = elm->Parent();
if (parent)
{
elm = parent;
continue;
}
HTML_Element* doc_root = doc->GetDocRoot();
if (elm->Type() == HE_DOC_ROOT && doc_root == elm)
{
if (delete_minmax_widths)
{
wp->HandleContentSizedIFrame(TRUE);
}
#ifdef _PRINT_SUPPORT_
if (doc->IsCurrentDoc() || doc->IsPrintDocument())
#else // _PRINT_SUPPORT_
if (doc->IsCurrentDoc())
#endif // _PRINT_SUPPORT_
doc->PostReflowMsg();
}
}
break;
} while (1);
}
#ifdef SVG_SUPPORT
/** A SVG fragment root is defined to be a <svg> element in the svg
namespace with a parent outside the svg namespace. The fragment
must be placed in a document root or an element in another
namespace. */
static inline BOOL IsSVGFragmentRoot(HTML_Element *elm)
{
if (!elm->IsMatchingType(Markup::SVGE_SVG, NS_SVG))
return FALSE;
if (!elm->Parent() || elm->Parent()->GetNsType() == NS_SVG)
return FALSE;
return TRUE;
}
#endif
void HTML_Element::MarkExtraDirty(FramesDocument* doc, int successors)
{
if (doc)
{
#ifdef _DEBUG
if (doc->GetLogicalDocument())
{
LayoutWorkplace* wp = doc->GetLogicalDocument()->GetLayoutWorkplace();
// marking things dirty during traverse is forbidden. Marking thigs dirty during reflow is only allowed under certain circumstances.
OP_ASSERT(!wp->IsTraversing() && !wp->IsReflowing());
}
/* we can not mark dirty on a -o-content-size iframe document while the parent doc is traversing. */
if (doc->IsInlineFrame() && doc->GetDocManager()->GetFrame() && doc->GetDocManager()->GetFrame()->GetNotifyParentOnContentChange())
{
FramesDocument* parent_doc = doc->GetDocManager() ? doc->GetDocManager()->GetParentDoc() : NULL;
LayoutWorkplace* parent_wp = parent_doc && parent_doc->GetLogicalDocument() ? parent_doc->GetLogicalDocument()->GetLayoutWorkplace() : NULL;
if (parent_wp)
OP_ASSERT(!parent_wp->IsTraversing());
}
#endif
#ifdef LAYOUT_YIELD_REFLOW
LayoutWorkplace* wp = doc->GetLogicalDocument() ? doc->GetLogicalDocument()->GetLayoutWorkplace() : NULL;
if (wp)
{
if (wp->GetYieldForceLayoutChanged() == LayoutWorkplace::FORCE_FROM_ELEMENT)
/* If we do something drastic to the document, we need to force all elements */
wp->SetYieldForceLayoutChanged(LayoutWorkplace::FORCE_ALL);
/* The tree changed, we need to mark the yield cascade dirty and discard it */
wp->MarkYieldCascade(this);
}
#endif // LAYOUT_YIELD_REFLOW
int type = Type();
int ns_type = GetNsType();
if (((type == HE_FRAMESET || type == HE_FRAME) && ns_type == NS_HTML) && doc->IsFrameDoc())
{
doc->PostReflowFramesetMsg();
return;
}
HTML_Element* const parent = Parent();
#ifdef SVG_SUPPORT
if (GetNsType() == NS_SVG)
{
BOOL is_svg_fragment_root = IsSVGFragmentRoot(this);
if (!is_svg_fragment_root && type != Markup::SVGE_FOREIGNOBJECT)
{
HTML_Element* ancestor = Parent();
while (ancestor)
{
if (IsSVGFragmentRoot(ancestor))
{
// SVG element inside a SVG block, so it won't affect the HTML
// layout engine. If we mark something dirty and the HTML
// layout engine sees it, it will do an Invalidate on the
// whole Line with SVG which will force a full repaint,
// which will make it impossible to have DOM animations in SVG.
return;
}
ancestor = ancestor->Parent();
}
}
}
#endif // SVG_SUPPORT
packed2.dirty |= ELM_BOTH_DIRTY;
if (parent)
{
if (GetInserted() == HE_INSERTED_BY_LAYOUT || parent->GetInserted() == HE_INSERTED_BY_LAYOUT)
parent->MarkExtraDirty(doc);
else
parent->MarkDirty(doc);
}
else if (type == HE_DOC_ROOT)
{
BOOL post_message;
#ifdef _PRINT_SUPPORT_
if (doc->IsPrintDocument())
post_message = doc->GetLogicalDocument()->GetPrintRoot() == this;
else
#endif // _PRINT_SUPPORT_
post_message = doc->GetLogicalDocument()->GetRoot() == this;
if (post_message)
{
#ifdef _PRINT_SUPPORT_
if (doc->IsCurrentDoc() || doc->IsPrintDocument())
#else // _PRINT_SUPPORT_
if (doc->IsCurrentDoc())
#endif // _PRINT_SUPPORT_
doc->PostReflowMsg();
}
}
HTML_Element* element = this;
while (successors)
{
element = element->SucActual();
if (element)
switch (element->Type())
{
case HE_TEXT:
case HE_TEXTGROUP:
case HE_COMMENT:
case HE_PROCINST:
case HE_DOCTYPE:
case HE_ENTITY:
case HE_ENTITYREF:
break;
default:
element->MarkExtraDirty(doc);
successors--;
break;
}
else
break;
}
}
}
void HTML_Element::MarkPropsDirty(FramesDocument* doc, int successor_subtrees, BOOL mark_this_subtree)
{
if (!doc)
return;
#ifdef _DEBUG
LayoutWorkplace* wp = doc->GetLogicalDocument() ? doc->GetLogicalDocument()->GetLayoutWorkplace() : NULL;
if (wp)
OP_ASSERT(!wp->IsTraversing() && !wp->IsReflowing());
#endif // _DEBUG
packed2.props_clean = 0;
// Mark child_props_dirty on ancestors that don't already have it set.
HTML_Element* ancestor;
for (ancestor = Parent(); ancestor && !ancestor->packed2.child_props_dirty; ancestor = ancestor->Parent())
ancestor->packed2.child_props_dirty = 1;
if (!ancestor && doc->IsCurrentDoc())
// Root element didn't have child_props_dirty - until now.
doc->PostReflowMsg();
int subtrees = successor_subtrees;
if (subtrees < INT_MAX && mark_this_subtree)
subtrees ++;
if (subtrees)
{
/* Possible performance improvement to consider here: Add another bit of information to
HTML_Element which expresses "reload props on entire subtree", instead of going through
the entire subtree now. */
HTML_Element* elm = mark_this_subtree ? this : SucActualStyle();
while (subtrees > 0 && elm)
{
HTML_Element* next_elm = elm->SucActualStyle();
if (Markup::IsRealElement(elm->Type()))
{
HTML_Element* stop = next_elm;
if (!stop)
stop = elm->NextSiblingActualStyle();
for (HTML_Element* child = elm->FirstChildActualStyle(); child && child != stop; child = child->NextActualStyle())
if (Markup::IsRealElement(child->Type()))
{
child->packed2.props_clean = 0;
child->packed2.child_props_dirty = 1;
// The *Actual*() methods may skip children. Be sure to mark them as well.
for (HTML_Element* p = child->Parent(); p && !p->packed2.child_props_dirty; p = p->Parent())
p->packed2.child_props_dirty = 1;
}
elm->packed2.props_clean = 0;
elm->packed2.child_props_dirty = 1;
// The *Actual*() methods may skip children. Be sure to mark them as well.
for (HTML_Element* p = elm->Parent(); p && !p->packed2.child_props_dirty; p = p->Parent())
p->packed2.child_props_dirty = 1;
-- subtrees;
}
elm = next_elm;
}
}
}
int HTML_Element::CountParams() const
{
if (Type() == HE_PARAM)
return 1;
else
{
int count = 0;
for (HTML_Element* he = FirstChildActual(); he; he = he->SucActual())
{
if (he->Type() != HE_APPLET && he->Type() != HE_OBJECT)
count += he->CountParams();
}
return count;
}
}
const uni_char* HTML_Element::GetParamURL() const
{
if (Type() == HE_PARAM)
{
const uni_char* param_name = GetPARAM_Name();
if (param_name)
{
if (uni_stri_eq(param_name, "FILENAME"))
return GetPARAM_Value();
else if (uni_stri_eq(param_name, "MOVIE"))
return GetPARAM_Value();
else if (uni_stri_eq(param_name, "SRC"))
return GetPARAM_Value();
else if (uni_stri_eq(param_name, "URL"))
return GetPARAM_Value();
}
return NULL;
}
else
{
const uni_char* url = NULL;
HTML_Element* he = FirstChildActual();
while (he && !url)
{
if (he->Type() != HE_OBJECT && he->Type() != HE_APPLET)
url = he->GetParamURL();
he = he->SucActual();
}
return url;
}
}
const uni_char* HTML_Element::GetParamType(const uni_char* &codetype) const
{
if (Type() == HE_PARAM)
{
const uni_char* param_name = GetPARAM_Name();
if (param_name)
{
if (uni_stri_eq(param_name, "TYPE"))
return GetPARAM_Value();
else if (!codetype && uni_stri_eq(param_name, "CODETYPE"))
codetype = GetPARAM_Value();
}
return NULL;
}
else
{
const uni_char* type = NULL;
HTML_Element* he = FirstChildActual();
while (he && !type)
{
if (he->Type() != HE_OBJECT && he->Type() != HE_APPLET)
type = he->GetParamType(codetype);
he = he->SucActual();
}
return type;
}
}
#ifdef _PLUGIN_SUPPORT_
OpNS4Plugin* HTML_Element::GetNS4Plugin()
{
if (layout_box && layout_box->IsContentEmbed())
return static_cast<EmbedContent*>(static_cast<Content_Box*>(layout_box)->GetContent())->GetOpNS4Plugin();
else
return NULL;
}
OP_STATUS HTML_Element::GetEmbedAttrs(int& argc, const uni_char** &argn, const uni_char** &argv) const
{
OP_ASSERT(Type() == HE_EMBED || Type() == HE_APPLET || Type() == HE_OBJECT);
argn = NULL;
argv = NULL;
int attr_count = 0;
int param_count = 0;
PrivateAttrs* pa = (PrivateAttrs*)GetSpecialAttr(ATTR_PRIVATE, ITEM_TYPE_PRIVATE_ATTRS, (void*)0, SpecialNs::NS_LOGDOC);
if (pa)
attr_count = pa->GetLength();
if (Type() == HE_APPLET || Type() == HE_OBJECT)
param_count = CountParams() + 1; // Params + "PARAM"
argc = attr_count + param_count;
if (argc)
{
argn = OP_NEWA(const uni_char*, argc); // FIXME:REPORT_MEMMAN-KILSMO
argv = OP_NEWA(const uni_char*, argc); // FIXME:REPORT_MEMMAN-KILSMO
if (!argn || !argv)
{
OP_DELETEA(argn);
OP_DELETEA(argv);
argn = NULL;
argv = NULL;
return OpStatus::ERR_NO_MEMORY;
}
if (pa)
{
uni_char** pa_argn = pa->GetNames();
uni_char** pa_argv = pa->GetValues();
for (int i = 0; i < attr_count; i++)
{
argn[i] = pa_argn[i];
argv[i] = pa_argv[i];
if (!argv[i])
argv[i] = UNI_L("");
}
}
if (param_count)
{
int next_index = attr_count;
// Add a placeholder that shows the plugin where attributes end and params start
argn[next_index] = UNI_L("PARAM");
argv[next_index++] = NULL;
GetParams(argn, argv, next_index);
OP_ASSERT(next_index <= argc);
if (next_index < argc)
argc = next_index;
}
}
return OpStatus::OK;
}
#endif // _PLUGIN_SUPPORT_
void HTML_Element::GetParams(const uni_char** names, const uni_char** values, int& next_index) const
{
HTML_Element* stop = NextSiblingActual();
const HTML_Element* it = NextActual();
while (it != stop)
{
if (it->IsMatchingType(HE_PARAM, NS_HTML))
{
names[next_index] = it->GetPARAM_Name();
if (names[next_index])
{
values[next_index] = it->GetPARAM_Value();
if (!values[next_index])
values[next_index] = UNI_L("");
next_index++;
}
}
if (it->GetNsType() == NS_HTML && (it->Type() == HE_APPLET || it->Type() == HE_OBJECT || it->Type() == HE_PARAM))
// Skip this subtree
it = it->NextSiblingActual();
else
it = it->NextActual();
}
}
/**
* Tries to determine if the parser is currently working
* inside the element (or has just inserted it). Will error on
* the side of TRUE for backwards compatibility.
*/
static BOOL IsParsingInsideElement(HTML_Element* elm, LogicalDocument* logdoc)
{
OP_ASSERT(elm && logdoc);
BOOL parsing_inside_element = logdoc->IsParsingUnderElm(elm);
return parsing_inside_element;
}
OP_BOOLEAN HTML_Element::GetResolvedEmbedType(URL* inline_url, HTML_ElementType &resolved_type, LogicalDocument* logdoc)
{
OP_ASSERT(Type() == HE_EMBED);
if (!inline_url || inline_url->IsEmpty())
{
resolved_type = HE_EMBED;
return OpBoolean::IS_TRUE;
}
const uni_char* type_str = GetStringAttr(ATTR_TYPE);
#ifndef _APPLET_2_EMBED_
if (type_str &&
(uni_strnicmp(type_str, UNI_L("application/x-java-applet"), 25) == 0 ||
uni_strnicmp(type_str, UNI_L("application/java"), 16) == 0))
{
resolved_type = HE_APPLET;
return OpBoolean::IS_TRUE;
}
#endif // !_APPLET_2_EMBED_
OpString8 resource_type;
RETURN_IF_ERROR(resource_type.SetUTF8FromUTF16(type_str));
URLStatus url_stat = inline_url->Status(TRUE);
if (url_stat == URL_LOADING_FAILURE)
{
resolved_type = HE_EMBED;
return OpBoolean::IS_TRUE;
}
else if (url_stat == URL_UNLOADED ||
(url_stat == URL_LOADING && inline_url->ContentType() == URL_UNDETERMINED_CONTENT))
{
return OpBoolean::IS_FALSE;
}
else if (inline_url->Type() == URL_HTTP || inline_url->Type() == URL_HTTPS)
{
uint32 http_response = inline_url->GetAttribute(URL::KHTTP_Response_Code, TRUE);
if (url_stat == URL_LOADING && http_response == HTTP_NO_RESPONSE)
return OpBoolean::IS_FALSE;
else if (http_response >= 400)
{
resolved_type = HE_EMBED;
return OpBoolean::IS_TRUE;
}
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::TrustServerTypes))
RETURN_IF_ERROR(inline_url->GetAttribute(URL::KMIME_Type, resource_type, TRUE));
}
return GetResolvedHtmlElementType(inline_url, logdoc, resource_type.CStr(), HE_EMBED, resolved_type);
}
OP_BOOLEAN HTML_Element::GetResolvedHtmlElementType(URL* inline_url, LogicalDocument* logdoc, const char* resource_type, HTML_ElementType default_type, HTML_ElementType& resolved_type, BOOL is_currently_parsing_this /* = FALSE */)
{
OP_ASSERT(inline_url);
ViewActionReply reply;
OpString mime_type;
RETURN_IF_ERROR(mime_type.Set(resource_type));
RETURN_IF_MEMORY_ERROR(Viewers::GetViewAction(*inline_url, mime_type, reply, TRUE));
resolved_type = default_type;
if (reply.action == VIEWER_PLUGIN)
{
if (is_currently_parsing_this)
return OpBoolean::IS_FALSE;
if (default_type == HE_OBJECT)
{
#ifdef SVG_SUPPORT
// Prevents execution of applets and plugins for foreignObjects in svg in <img> elements, DSK-240651.
if (logdoc && !g_svg_manager->IsEcmaScriptEnabled(logdoc->GetFramesDocument()))
{
resolved_type = HE_OBJECT; // return HE_OBJECT because that will give a nodisplay box.
}
else
#endif // SVG_SUPPORT
# ifdef USE_FLASH_PREF
if (!g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::FlashEnabled)
&& reply.mime_type.Length() && HTML_Element::IsFlashType(reply.mime_type.CStr()))
{
resolved_type = HE_OBJECT; // return HE_OBJECT because that will give a nodisplay box.
}
else
# endif // USE_FLASH_PREF
resolved_type = CheckLocalCodebase(logdoc, HE_EMBED, reply.mime_type.CStr());
}
return OpBoolean::IS_TRUE;
}
else
{
URLContentType inline_url_cnt_type = inline_url->ContentType();
if (inline_url_cnt_type == URL_UNDETERMINED_CONTENT)
if (Viewer* v = g_viewers->FindViewerByMimeType(resource_type))
inline_url_cnt_type = v->GetContentType();
switch (inline_url_cnt_type)
{
# ifdef SVG_SUPPORT
case URL_SVG_CONTENT:
resolved_type = (!logdoc || logdoc->GetFramesDocument()->GetShowImages()) ? HE_IFRAME : default_type;
return OpBoolean::IS_TRUE;
# endif
case URL_HTML_CONTENT:
case URL_TEXT_CONTENT:
case URL_CSS_CONTENT:
case URL_X_JAVASCRIPT:
case URL_XML_CONTENT:
# ifdef _WML_SUPPORT_
case URL_WML_CONTENT:
# endif
resolved_type = HE_IFRAME;
return OpBoolean::IS_TRUE;
/*
case URL_AVI_CONTENT:
case URL_MPG_CONTENT:
break;
*/
case URL_PNG_CONTENT:
case URL_GIF_CONTENT:
case URL_JPG_CONTENT:
case URL_XBM_CONTENT:
case URL_BMP_CONTENT:
# ifdef _WML_SUPPORT_
case URL_WBMP_CONTENT:
# endif
case URL_WEBP_CONTENT:
resolved_type = HE_IMG;
return OpBoolean::IS_TRUE;
case URL_MIDI_CONTENT:
case URL_WAV_CONTENT:
resolved_type = HE_EMBED;
return OpBoolean::IS_TRUE;
# ifdef HAS_ATVEF_SUPPORT // TV: works with object
case URL_TV_CONTENT:
{
if (default_type == HE_OBJECT)
{
resolved_type = HE_IMG;
return OpBoolean::IS_TRUE;
}
}
# endif // HAS_ATVEF_SUPPORT
}
}
return OpBoolean::IS_TRUE;
}
#if defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
static BOOL IsJavaEnabled()
{
Viewer* viewer = g_viewers->FindViewerByMimeType(UNI_L("application/x-java-applet"));
return viewer && (viewer->GetAction() == VIEWER_PLUGIN);
}
#endif // defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
OP_BOOLEAN HTML_Element::GetResolvedObjectType(URL* inline_url, HTML_ElementType &resolved_type, LogicalDocument* logdoc)
{
#if !defined _PLUGIN_SUPPORT_ && defined SVG_SUPPORT
OP_ASSERT(Type() == HE_OBJECT || Type() == HE_EMBED || Type() == HE_IMG); // This is not right, but it saves us some asserts.
#else
OP_ASSERT(Type() == HE_OBJECT);
#endif
URLType url_type = URL_UNKNOWN;
#ifndef ONLY_USE_TYPE_FOR_OBJECTS
if (inline_url)
url_type = inline_url->Type();
#endif // ONLY_USE_TYPE_FOR_OBJECTS
#ifdef DELAYED_SCRIPT_EXECUTION
HTML_Element *child = FirstChild();
HTML_Element *stop = NextSibling();
while (child && child != stop)
{
if (child->Type() == HE_PARAM && child->GetInserted() == HE_INSERTED_BY_PARSE_AHEAD || child->Type() == HE_SCRIPT && logdoc->GetHLDocProfile()->ESIsFirstDelayedScript(child))
{
resolved_type = HE_OBJECT;
return OpBoolean::IS_FALSE;
}
child = child->Next();
}
#endif // DELAYED_SCRIPT_EXECUTION
#ifdef _PLUGIN_SUPPORT_
#ifdef SVG_SUPPORT
// Prevents execution of applets and plugins for foreignObjects in svg in <img> elements, DSK-240651.
BOOL suppress_plugins = logdoc && !g_svg_manager->IsEcmaScriptEnabled(logdoc->GetFramesDocument());
#else
BOOL suppress_plugins = FALSE;
#endif // SVG_SUPPORT
#endif // _PLUGIN_SUPPORT_
BOOL is_currently_parsing_this = logdoc && !GetEndTagFound() && !logdoc->IsParsed() && IsParsingInsideElement(this, logdoc);
const uni_char* class_id = GetStringAttr(ATTR_CLASSID);
if (class_id && *class_id)
{
#if defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
if (!suppress_plugins && uni_strni_eq(class_id, "JAVA:", 5) && IsJavaEnabled())
{
resolved_type = CheckLocalCodebase(logdoc, HE_APPLET);
return OpBoolean::IS_TRUE;
}
else
#endif // defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
if (uni_stri_eq(class_id, "HTTP://WWW.OPERA.COM/ERA"))
{
if (is_currently_parsing_this)
{
// wait for object element to complete
return OpBoolean::IS_FALSE;
}
else
{
resolved_type = HE_IFRAME;
return OpBoolean::IS_TRUE;
}
}
// Unknown CLASSID -> Should use the fallback according to the
// HTML5 plugin loading algorithm, see 4.8.6 The object element
resolved_type = HE_OBJECT;
return OpBoolean::IS_TRUE;
}
#ifdef HAS_ATVEF_SUPPORT
if (url_type == URL_TV)
{
#ifdef JS_PLUGIN_ATVEF_VISUAL
// If this is an OBJECT pointing to a visual jsplugin, we need to
// register a listener. inline_url will point to an internal "tv:"
// URL made up specially for this object, which we need to ask
// it to listen to.
JS_Plugin_Object *obj_p = NULL;
OP_BOOLEAN is_jsplugin = IsJSPluginObject(logdoc->GetHLDocProfile(), &obj_p);
if (is_jsplugin == OpBoolean::IS_TRUE && obj_p->IsAtvefVisualPlugin() &&
!GetSpecialBoolAttr(Markup::JSPA_TV_LISTENER_REGISTERED,
SpecialNs::NS_JSPLUGINS))
{
// Get the JS_Plugin_HTMLObjectElement_Object that correspond to
// the OBJECT tag. This is not the same as the obj_p we just
// retrieved...
ES_Object *esobj =
DOM_Utils::GetJSPluginObject(GetESElement());
EcmaScript_Object *ecmascriptobject = NULL;
JS_Plugin_Object *jsobject = NULL;
if (esobj && (ecmascriptobject = ES_Runtime::GetHostObject(esobj)) != NULL)
{
OP_ASSERT(ecmascriptobject->IsA(ES_HOSTOBJECT_JSPLUGIN));
jsobject =
static_cast<JS_Plugin_Object *>(ecmascriptobject);
}
// Check that we actually did request visualization when
// instantiating this object.
if (jsobject && jsobject->IsAtvefVisualPlugin())
{
// Listen to the tv: URL we have set up.
if (OpStatus::IsSuccess(jsobject->RegisterAsTvListener(inline_url->GetAttribute(URL::KUniName, FALSE))))
{
SetSpecialBoolAttr(Markup::JSPA_TV_LISTENER_REGISTERED,
TRUE, SpecialNs::NS_JSPLUGINS);
}
}
}
else if (OpStatus::IsMemoryError(is_jsplugin))
{
return is_jsplugin;
}
#endif
resolved_type = HE_IMG;
return OpBoolean::IS_TRUE;
}
#endif
const uni_char* type_str = GetStringAttr(ATTR_TYPE);
if (!type_str && !(type_str = GetStringAttr(ATTR_CODETYPE)))
{
// check if there is a <PARAM> with name == type or codetype
const uni_char* codetype_str = NULL;
type_str = GetParamType(codetype_str);
if (!type_str)
type_str = codetype_str;
if (!type_str && is_currently_parsing_this)
{
// wait for object element to complete
resolved_type = HE_OBJECT;
return OpBoolean::IS_FALSE;
}
}
if (is_currently_parsing_this)
{
// wait for object element to complete
resolved_type = HE_OBJECT;
return OpBoolean::IS_FALSE;
}
#if defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
if (!suppress_plugins &&
type_str &&
(uni_strni_eq(type_str, "APPLICATION/X-JAVA-APPLET", 25) ||
uni_strni_eq(type_str, "APPLICATION/JAVA", 16)) &&
IsJavaEnabled())
{
resolved_type = CheckLocalCodebase(logdoc, HE_APPLET);
return OpBoolean::IS_TRUE;
}
#endif // defined(_APPLET_2_EMBED_) && defined(_PLUGIN_SUPPORT_)
#ifdef ONLY_USE_TYPE_FOR_OBJECTS
// Despite not loading the URL we'll still use any cached data in it to make
// an educated guess about what resource we'll get if we do load it. This
// is really wrong, but since ONLY_USE_TYPE_FOR_OBJECTS is an optional feature
// they know that already.
if (inline_url && !inline_url->IsEmpty())
{
URLContentType inline_url_cnt_type = inline_url->ContentType();
if (inline_url_cnt_type == URL_UNDETERMINED_CONTENT)
{
Viewer* v;
OpString resource_type;
const char* url_mimetype = inline_url->GetAttribute(URL::KMIME_Type, TRUE).CStr();
if (url_mimetype && g_pcnet->GetIntegerPref(PrefsCollectionNetwork::TrustServerTypes))
RETURN_IF_ERROR(resource_type.Set(url_mimetype));
else
RETURN_IF_ERROR(resource_type.Set(type_str));
if (g_viewers->FindViewerByMimeType(resource_type, v) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
if (v)
inline_url_cnt_type = v->GetContentType();
}
switch (inline_url_cnt_type)
{
case URL_HTML_CONTENT:
case URL_TEXT_CONTENT:
case URL_XML_CONTENT:
# ifdef _WML_SUPPORT_
case URL_WML_CONTENT:
# endif
resolved_type = HE_IFRAME;
return OpBoolean::IS_TRUE;
}
}
URL sniffer_url; // Empty URL so that the viewer system can focus on the mime type.
BOOL check_with_viewers = TRUE;
#else // ONLY_USE_TYPE_FOR_OBJECTS
URL sniffer_url = inline_url ? *inline_url : URL();
BOOL check_with_viewers = FALSE;
if (sniffer_url.IsEmpty())
check_with_viewers = TRUE;
#endif // ONLY_USE_TYPE_FOR_OBJECTS
if (check_with_viewers)
{
#ifdef _PLUGIN_SUPPORT_
HTML_Element* embed_present = GetFirstElm(HE_EMBED);
if (!embed_present && type_str)
{
ViewActionReply reply;
RETURN_IF_MEMORY_ERROR(Viewers::GetViewAction(sniffer_url, type_str, reply, TRUE));
resolved_type = reply.action != VIEWER_PLUGIN || suppress_plugins ? HE_OBJECT : CheckLocalCodebase(logdoc, HE_EMBED, reply.mime_type.CStr());
}
else
#endif // _PLUGIN_SUPPORT_
resolved_type = HE_OBJECT;
return OpBoolean::IS_TRUE;
}
OP_ASSERT(!sniffer_url.IsEmpty());
URLStatus url_stat = sniffer_url.Status(TRUE);
OpString8 resource_type;
RETURN_IF_ERROR(resource_type.SetUTF8FromUTF16(type_str));
if (url_stat == URL_LOADING_FAILURE)
{
resolved_type = HE_OBJECT;
return OpBoolean::IS_TRUE;
}
else if (url_stat == URL_UNLOADED ||
(url_stat == URL_LOADING && inline_url->ContentType() == URL_UNDETERMINED_CONTENT))
{
return OpBoolean::IS_FALSE;
}
else if (url_type == URL_HTTP || url_type == URL_HTTPS)
{
uint32 http_response = inline_url->GetAttribute(URL::KHTTP_Response_Code, TRUE);
if (http_response == HTTP_NO_RESPONSE && url_stat == URL_LOADING)
return OpBoolean::IS_FALSE;
else if (http_response >= 400)
{
resolved_type = HE_OBJECT;
return OpBoolean::IS_TRUE;
}
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::TrustServerTypes))
RETURN_IF_ERROR(sniffer_url.GetAttribute(URL::KMIME_Type, resource_type, TRUE));
}
return GetResolvedHtmlElementType(&sniffer_url, logdoc, resource_type.CStr(), HE_OBJECT, resolved_type, is_currently_parsing_this);
}
OP_BOOLEAN HTML_Element::GetResolvedImageType(URL* inline_url, HTML_ElementType &resolved_type, BOOL doc_loading, FramesDocument* doc)
{
OP_ASSERT(doc);
OP_ASSERT(Type() == HE_IMG || Type() == HE_INPUT);
resolved_type = Type();
#ifdef SVG_SUPPORT
if (!inline_url)
{
return OpBoolean::IS_FALSE;
}
else if (inline_url->Status(TRUE) == URL_LOADING_FAILURE)
{
return OpBoolean::IS_TRUE;
}
else if (inline_url->ContentType() == URL_SVG_CONTENT)
{
resolved_type = HE_IFRAME;
}
#endif // SVG_SUPPORT
return OpBoolean::IS_TRUE;
}
// The following methods handles traversing of the three skipping the elements inserted by the LayoutEngine
HTML_Element* HTML_Element::ParentActual() const
{
const HTML_Element *candidate = Parent();
while (candidate && !candidate->IsIncludedActual())
candidate = candidate->Parent();
return const_cast<HTML_Element*>(candidate); // casting to avoid constness trouble
}
HTML_Element* HTML_Element::SucActual() const
{
OP_PROBE3(OP_PROBE_HTML_ELEMENT_SUCACTUAL);
HTML_Element *stop = ParentActual() ? (HTML_Element *) ParentActual()->NextSibling() : NULL;
for (HTML_Element *e = (HTML_Element *) NextSibling(); e && e != stop; e = (HTML_Element *) e->Next())
if (e->IsIncludedActual())
{
OP_ASSERT(e->ParentActual() == ParentActual());
return e;
}
return NULL;
}
HTML_Element* HTML_Element::PredActual() const
{
HTML_Element *stop = ParentActual() ? (HTML_Element *) ParentActual()->PrevSibling() : NULL;
for (HTML_Element *e = (HTML_Element *) PrevSibling(); e && e != stop; e = (HTML_Element *) e->PrevSibling())
if (e->IsIncludedActual())
{
OP_ASSERT(e->ParentActual() == ParentActual());
OP_ASSERT(e->SucActual() == (IsIncludedActual() ? this : SucActual()));
return e;
}
else if (HTML_Element *lc = e->LastChildActual())
{
OP_ASSERT(lc->ParentActual() == ParentActual());
OP_ASSERT(lc->SucActual() == (IsIncludedActual() ? this : SucActual()));
return lc;
}
return NULL;
}
HTML_Element* HTML_Element::FirstChildActual() const
{
for (HTML_Element *e = FirstChild(); e; e = e->FirstChild())
if (e->IsIncludedActual())
{
OP_ASSERT(e->ParentActual() == (IsIncludedActual() ? this : ParentActual()));
return e;
}
else if (!e->FirstChild())
{
HTML_Element *stop = (HTML_Element *) NextSibling();
for (e = (HTML_Element *) e->Next(); e && e != stop; e = (HTML_Element *) e->Next())
if (e->IsIncludedActual())
{
OP_ASSERT(e->ParentActual() == (IsIncludedActual() ? this : ParentActual()));
return e;
}
break;
}
return NULL;
}
HTML_Element* HTML_Element::LastChildActual() const
{
for (HTML_Element *e = LastChild(); e; e = e->LastChild())
if (e->IsIncludedActual())
{
OP_ASSERT(e->ParentActual() == (IsIncludedActual() ? this : ParentActual()));
return e;
}
else if (!e->LastChild())
{
for (e = (HTML_Element *) e->Prev(); e && e != this; e = (HTML_Element *) e->Prev())
if (e->IsIncludedActual())
{
const HTML_Element *parent = IsIncludedActual() ? this : ParentActual();
while (e->ParentActual() != parent)
{
OP_ASSERT(IsAncestorOf(e));
e = e->ParentActual();
}
return e;
}
break;
}
return NULL;
}
HTML_Element *HTML_Element::PrevSiblingActual() const
{
for (const HTML_Element *leaf = this; leaf; leaf = leaf->ParentActual())
if (leaf->PredActual())
return leaf->PredActual();
return NULL;
}
HTML_Element *HTML_Element::FirstLeafActual() const
{
HTML_Element *leaf = FirstChildActual();
if (!leaf)
return NULL;
while (HTML_Element *next_child = leaf->FirstChildActual())
leaf = next_child;
return leaf;
}
HTML_Element *HTML_Element::LastLeafActual() const
{
HTML_Element *leaf = LastChildActual();
if (!leaf)
return NULL;
while (leaf->LastChildActual())
leaf = leaf->LastChildActual();
return leaf;
}
HTML_Element* HTML_Element::NextActual() const
{
for (HTML_Element *e = (HTML_Element *) Next(); e; e = (HTML_Element *) e->Next())
if (e->IsIncludedActual())
return e;
return NULL;
}
HTML_Element* HTML_Element::NextSiblingActual() const
{
for( const HTML_Element *leaf = this; leaf; leaf = leaf->ParentActual() )
{
HTML_Element *candidate = leaf->SucActual();
if( candidate )
return candidate;
}
return NULL;
}
HTML_Element* HTML_Element::PrevActual() const
{
for (HTML_Element *e = (HTML_Element *) Prev(); e; e = (HTML_Element *) e->Prev())
if (e->IsIncludedActual())
return e;
return NULL;
}
#ifdef DELAYED_SCRIPT_EXECUTION
HTML_Element* HTML_Element::SucActualStyle() const
{
HTML_Element *stop = ParentActualStyle() ? (HTML_Element *) ParentActualStyle()->NextSibling() : NULL;
for (HTML_Element *e = (HTML_Element *) NextSibling(); e && e != stop; e = (HTML_Element *) e->Next())
if (e->IsIncludedActualStyle())
{
OP_ASSERT(e->ParentActualStyle() == ParentActualStyle());
return e;
}
return NULL;
}
HTML_Element* HTML_Element::PredActualStyle() const
{
HTML_Element *stop = ParentActualStyle() ? (HTML_Element *) ParentActualStyle()->PrevSibling() : NULL;
for (HTML_Element *e = (HTML_Element *) PrevSibling(); e && e != stop; e = (HTML_Element *) e->PrevSibling())
if (e->IsIncludedActualStyle())
{
OP_ASSERT(e->ParentActualStyle() == ParentActualStyle());
OP_ASSERT(e->SucActualStyle() == (IsIncludedActualStyle() ? this : SucActualStyle()));
return e;
}
else if (HTML_Element *lc = e->LastChildActualStyle())
{
OP_ASSERT(lc->ParentActualStyle() == ParentActualStyle());
OP_ASSERT(lc->SucActualStyle() == (IsIncludedActualStyle() ? this : SucActualStyle()));
return lc;
}
return NULL;
}
HTML_Element* HTML_Element::FirstChildActualStyle() const
{
for (HTML_Element *e = FirstChild(); e; e = e->FirstChild())
if (e->IsIncludedActualStyle())
{
OP_ASSERT(e->ParentActualStyle() == (IsIncludedActualStyle() ? this : ParentActualStyle()));
return e;
}
else if (!e->FirstChild())
{
HTML_Element *stop = (HTML_Element *) NextSibling();
for (e = (HTML_Element *) e->Next(); e && e != stop; e = (HTML_Element *) e->Next())
if (e->IsIncludedActualStyle())
{
OP_ASSERT(e->ParentActualStyle() == (IsIncludedActualStyle() ? this : ParentActualStyle()));
return e;
}
break;
}
return NULL;
}
HTML_Element* HTML_Element::LastChildActualStyle() const
{
for (HTML_Element *e = LastChild(); e; e = e->LastChild())
if (e->IsIncludedActualStyle())
{
OP_ASSERT(e->ParentActualStyle() == (IsIncludedActualStyle() ? this : ParentActualStyle()));
return e;
}
else if (!e->LastChild())
{
for (e = (HTML_Element *) e->Prev(); e && e != this; e = (HTML_Element *) e->Prev())
if (e->IsIncludedActualStyle())
{
const HTML_Element *parent = IsIncludedActualStyle() ? this : ParentActualStyle();
while (e->ParentActualStyle() != parent)
{
OP_ASSERT(IsAncestorOf(e));
e = e->ParentActualStyle();
}
return e;
}
break;
}
return NULL;
}
HTML_Element* HTML_Element::LastLeafActualStyle() const
{
HTML_Element *leaf = LastChildActualStyle();
if (!leaf)
return NULL;
while( leaf->LastChildActualStyle() )
leaf = leaf->LastChildActualStyle();
return leaf;
}
HTML_Element* HTML_Element::FirstLeafActualStyle() const
{
HTML_Element *leaf = FirstChildActualStyle();
if (!leaf)
return NULL;
while (leaf->FirstChildActualStyle())
leaf = leaf->FirstChildActualStyle();
return leaf;
}
HTML_Element* HTML_Element::NextActualStyle() const
{
for (HTML_Element* e = (HTML_Element*) Next(); e; e = (HTML_Element*) e->Next())
if (e->IsIncludedActualStyle())
return e;
return NULL;
}
HTML_Element* HTML_Element::PrevActualStyle() const
{
for (HTML_Element* e = (HTML_Element*) Prev(); e; e = (HTML_Element*) e->Prev())
if (e->IsIncludedActualStyle())
return e;
return NULL;
}
HTML_Element* HTML_Element::NextSiblingActualStyle() const
{
for (const HTML_Element* leaf = this; leaf; leaf = leaf->ParentActualStyle())
{
HTML_Element* candidate = leaf->SucActualStyle();
if (candidate)
return candidate;
}
return NULL;
}
#endif // DELAYED_SCRIPT_EXECUTION
BOOL HTML_Element::OutSafe(const DocumentContext &context, BOOL going_to_delete/*=TRUE*/)
{
if (FramesDocument *doc = context.frames_doc)
if (LogicalDocument* logdoc = doc->GetLogicalDocument())
logdoc->GetLayoutWorkplace()->SignalHtmlElementRemoved(this);
#if defined SEARCH_MATCHES_ALL && !defined HAS_NO_SEARCHTEXT
CleanSearchHit(context.frames_doc);
#endif // SEARCH_MATCHES_ALL && !HAS_NO_SEARCHTEXT
BOOL had_body = FALSE;
HTML_Element *parent = Parent();
if (parent)
{
if (FramesDocument *doc = context.frames_doc)
{
if (!doc->IsBeingDeleted())
{
doc->RemoveFromSelection(this);
had_body = context.logdoc && context.logdoc->GetBodyElm() != NULL;
}
if (context.logdoc)
{
// FIXME: OOM handling here (though OOM is unlikely to occur and if it does leaves everything in an acceptable state).
if (!doc->IsBeingDeleted())
OpStatus::Ignore(context.logdoc->RemoveNamedElement(this, TRUE));
// Must be done before the tree has changed so
// that we can figure out which forms each radio button belonged to
context.logdoc->GetRadioGroups().UnregisterAllRadioButtonsInTree(doc, this);
}
#ifdef DOCUMENT_EDIT_SUPPORT
if (doc->GetDocumentEdit())
doc->GetDocumentEdit()->OnBeforeElementOut(this);
#endif // DOCUMENT_EDIT_SUPPORT
// Let the hover bubble up to something that is not being removed
doc->BubbleHoverToParent(this);
#if defined SEARCH_MATCHES_ALL && !defined HAS_NO_SEARCHTEXT
if (IsReferenced() && doc->GetHtmlDocument())
// Needs unchanged tree to find all elements in the selection
doc->GetHtmlDocument()->RemoveElementFromSearchHit(this);
#endif // SEARCH_MATCHES_ALL && !HAS_NO_SEARCHTEXT
}
if (DOM_Environment *environment = context.environment)
{
if (Parent())
OpStatus::Ignore(environment->ElementRemoved(this));
}
Out();
if (!context.frames_doc || !context.frames_doc->IsBeingDeleted())
ClearResolvedUrls();
}
// This will clean the subtree recursively
BOOL return_value = Clean(context, going_to_delete);
if (had_body && !context.logdoc->GetBodyElm() && context.logdoc->GetDocRoot() && context.logdoc->GetDocRoot()->IsMatchingType(HE_HTML, NS_HTML))
{
// Lost the document body element. Find a replacement.
for (HTML_Element *child = context.logdoc->GetDocRoot()->FirstChildActualStyle(); child; child = child->SucActualStyle())
if (child->IsMatchingType(HE_BODY, NS_HTML) || child->IsMatchingType(HE_FRAMESET, NS_HTML))
{
context.logdoc->SetBodyElm(child);
break;
}
}
return return_value;
}
void HTML_Element::OutSafe(int *ptr)
{
OP_ASSERT(ptr == NULL);
OutSafe(static_cast<FramesDocument *>(NULL), TRUE);
}
static void SendElementRefOnInserted(HTML_Element* elm, FramesDocument* doc)
{
for (ElementRef* ref = elm->GetFirstReference(); ref;)
{
ElementRef* next_ref = ref->NextRef();
ref->OnInsert(NULL, doc);
ref = next_ref;
}
}
static OP_STATUS ElementSignalInserted(const HTML_Element::DocumentContext &context, HTML_Element* element, BOOL mark_dirty)
{
FramesDocument *doc = context.frames_doc;
LogicalDocument *logdoc = context.logdoc;
HTML_Element *parent = element->Parent(), *root = logdoc ? logdoc->GetRoot() : NULL;
OP_STATUS status = OpStatus::OK; OpStatus::Ignore(status);
if (root && root->IsAncestorOf(element))
{
if (!logdoc->GetDocRoot() && parent == root)
{
HTML_Element* doc_root_candidate = element;
do
{
if (Markup::IsRealElement(doc_root_candidate->Type()))
{
if (doc_root_candidate->IsIncludedActual())
break;
#ifdef DELAYED_SCRIPT_EXECUTION
// The doc_root can also be speculatively inserted in which case we should also pick it up but
// it's important to not by accident pick up the wrapper elements we use to style XML documents,
// thus the !logdoc->IsXml() check.
if (!logdoc->IsXml() && doc_root_candidate->IsIncludedActualStyle())
break;
#endif // DELAYED_SCRIPT_EXECUTION
}
doc_root_candidate = doc_root_candidate->NextActualStyle();
}
while (doc_root_candidate);
if (doc_root_candidate)
logdoc->SetDocRoot(doc_root_candidate);
}
if (context.logdoc->GetDocRoot() && context.logdoc->GetDocRoot()->IsMatchingType(HE_HTML, NS_HTML) &&
(parent->Type() == HE_DOC_ROOT || element->ParentActualStyle() == context.logdoc->GetDocRoot()))
{
// Someone might just have inserted a better document body.
for (HTML_Element *child = context.logdoc->GetDocRoot()->FirstChildActualStyle(); child; child = child->SucActualStyle())
if (child->IsMatchingType(HE_BODY, NS_HTML) || child->IsMatchingType(HE_FRAMESET, NS_HTML))
{
context.logdoc->SetBodyElm(child);
break;
}
}
if (mark_dirty)
{
int sibling_subtrees = logdoc->GetHLDocProfile()->GetCSSCollection()->GetSuccessiveAdjacent();
if (sibling_subtrees < INT_MAX && context.hld_profile->GetCSSCollection()->MatchFirstChild() && element->IsFirstChild())
/* If the element inserted is first-child, its sibling (if any) is it no longer.
Must recalculate its properties, and all siblings of it that may be affected by
this change. Note that we have to add one for :first-child even if we have
succ_adj > 0 because for :first-child + elm, we would have to load properties
for the old first-child in addition to the old first-child's sibling. */
++ sibling_subtrees;
element->MarkPropsDirty(doc, sibling_subtrees, TRUE);
#ifdef SVG_SUPPORT
BOOL is_insertion_to_svg = parent->IsMatchingType(Markup::SVGE_SVG, NS_SVG); // This is the only kind that isn't covered by the svg code in Mark[Extra]Dirty.
if (is_insertion_to_svg)
{
// Nothing to do. We only need to avoid the other code blocks with
// MarkDirty so that we don't trigger a full repaint of the SVG which
// would kill the performance.
}
else
#endif // SVG_SUPPORT
if (parent->HasBeforeOrAfter())
parent->MarkExtraDirty(doc);
else
element->MarkExtraDirty(doc);
}
if (OpStatus::IsMemoryError(logdoc->AddNamedElement(element, TRUE)))
status = OpStatus::ERR_NO_MEMORY;
#ifndef HAS_NOTEXTSELECTION
if (TextSelection* text_selection = context.frames_doc->GetTextSelection())
text_selection->InsertElement(element);
#endif // !HAS_NOTEXTSELECTION
#ifdef DOCUMENT_EDIT_SUPPORT
if (context.frames_doc->GetDocumentEdit())
context.frames_doc->GetDocumentEdit()->OnElementInserted(element);
#endif // DOCUMENT_EDIT_SUPPORT
#ifdef XML_EVENTS_SUPPORT
if (context.frames_doc->HasXMLEvents())
{
HTML_Element* next_sibling = element->NextSibling();
HTML_Element* element_it = element;
while (element_it != next_sibling)
{
if (element_it->HasXMLEventAttribute())
element_it->HandleInsertedElementWithXMLEvent(context.frames_doc);
element_it = element_it->Next();
}
}
for (XML_Events_Registration *registration = context.frames_doc->GetFirstXMLEventsRegistration();
registration;
registration = (XML_Events_Registration *) registration->Suc())
if (OpStatus::IsMemoryError(registration->HandleElementInsertedIntoDocument(context.frames_doc, element)))
status = OpStatus::ERR_NO_MEMORY;
#endif // XML_EVENTS_SUPPORT
ES_Thread *current_thread = NULL;
if (context.environment)
{
if (element == logdoc->GetDocRoot())
if (OpStatus::IsMemoryError(context.environment->NewRootElement(element)))
status = OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsMemoryError(context.environment->ElementInserted(element)))
status = OpStatus::ERR_NO_MEMORY;
current_thread = context.environment->GetCurrentScriptThread();
}
if (OpStatus::IsMemoryError(parent->HandleDocumentTreeChange(context, parent, element, current_thread, TRUE)))
status = OpStatus::ERR_NO_MEMORY;
SendElementRefOnInserted(element, doc);
}
else if (context.environment)
{
if (OpStatus::IsMemoryError(context.environment->ElementInserted(element)))
status = OpStatus::ERR_NO_MEMORY;
/* Perform actions that really must happen on element trees being
created via innerHTML, but on elements that may not be inserted
later into the document.
That is, the alternatives of doing this in either HandleDocumentTreeChange()
(on addition to the tree) or HLDocProfile::InsertElementInternal()
(on document construction) aren't available as options. Options
that are preferable if you really don't have schedule any actions this
eagerly (== before document tree insertion.) */
BOOL skip_script_elms = context.environment->SkipScriptElements();
BOOL load_images = doc && doc->IsCurrentDoc();
HTML_Element *stop = element->NextSibling();
for (HTML_Element *iter = element; iter != stop; iter = iter->Next())
{
/* If we would have skipped any inserted script elements now if they
had been inserted into the document here, we need to make sure
they're skipped when they are inserted into as well (if they ever
are.) */
if (skip_script_elms && iter->IsMatchingType(HE_SCRIPT, NS_HTML))
{
long handled = iter->GetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, SpecialNs::NS_LOGDOC);
iter->SetSpecialNumAttr(ATTR_JS_SCRIPT_HANDLED, handled | SCRIPT_HANDLED_EXECUTED, SpecialNs::NS_LOGDOC);
}
/* Eagerly load images on innerHTML insertion: CORE-19120 + CORE-46429. */
else if (load_images && OpStatus::IsSuccess(status) && iter->IsMatchingType(HE_IMG, NS_HTML) && !iter->GetHEListElmForInline(IMAGE_INLINE))
{
if (URL *src = iter->GetUrlAttr(ATTR_SRC, NS_IDX_HTML, doc->GetLogicalDocument()))
if (!src->IsEmpty() && doc->GetLoadImages())
if (OpStatus::IsMemoryError(doc->LoadInline(src, iter, IMAGE_INLINE)))
status = OpStatus::ERR_NO_MEMORY;
}
}
#ifdef MEDIA_HTML_SUPPORT
// The HTML5 media resource selection algorithm waits for
// source elements to be inserted (even when the media element
// is not in a document). Similarly tracks can be added by
// inserting track elements as children of the media element.
if (OpStatus::IsSuccess(status))
{
if ((element->Type() == Markup::HTE_SOURCE ||
element->Type() == Markup::HTE_TRACK) &&
element->GetNsType() == NS_HTML &&
element->ParentActual())
{
MediaElement* media = element->ParentActual()->GetMediaElement();
if (media)
{
if (OpStatus::IsMemoryError(media->HandleElementChange(element, TRUE, context.environment->GetCurrentScriptThread())))
status = OpStatus::ERR_NO_MEMORY;
}
}
}
#endif // MEDIA_HTML_SUPPORT
SendElementRefOnInserted(element, doc);
}
return status;
}
OP_STATUS HTML_Element::UnderSafe(const DocumentContext &context, HTML_Element* parent, BOOL mark_dirty)
{
Under(parent);
return ElementSignalInserted(context, this, mark_dirty);
}
OP_STATUS HTML_Element::PrecedeSafe(const DocumentContext &context, HTML_Element* sibling, BOOL mark_dirty)
{
Precede(sibling);
return ElementSignalInserted(context, this, mark_dirty);
}
OP_STATUS HTML_Element::FollowSafe(const DocumentContext &context, HTML_Element* sibling, BOOL mark_dirty)
{
Follow(sibling);
return ElementSignalInserted(context, this, mark_dirty);
}
DOM_EventType HTML_Element::GetEventType(int attr, int attr_ns_idx)
{
NS_Type attr_ns_type = g_ns_manager->GetNsTypeAt(ResolveNsIdx(attr_ns_idx));
if (attr_ns_type == NS_HTML)
{
switch (attr)
{
case ATTR_ONLOAD:
return ONLOAD;
case ATTR_ONUNLOAD:
return ONUNLOAD;
case ATTR_ONBLUR:
return ONBLUR;
case ATTR_ONFOCUS:
return ONFOCUS;
case ATTR_ONFOCUSIN:
return ONFOCUSIN;
case ATTR_ONFOCUSOUT:
return ONFOCUSOUT;
case ATTR_ONERROR:
return ONERROR;
case ATTR_ONSUBMIT:
return ONSUBMIT;
case ATTR_ONCLICK:
return ONCLICK;
case ATTR_ONDBLCLICK:
return ONDBLCLICK;
case ATTR_ONCHANGE:
return ONCHANGE;
case ATTR_ONKEYDOWN:
return ONKEYDOWN;
case ATTR_ONKEYPRESS:
return ONKEYPRESS;
case ATTR_ONKEYUP:
return ONKEYUP;
case ATTR_ONMOUSEOVER:
return ONMOUSEOVER;
case ATTR_ONMOUSEENTER:
return ONMOUSEENTER;
case ATTR_ONMOUSEOUT:
return ONMOUSEOUT;
case ATTR_ONMOUSELEAVE:
return ONMOUSELEAVE;
case ATTR_ONMOUSEMOVE:
return ONMOUSEMOVE;
case ATTR_ONMOUSEUP:
return ONMOUSEUP;
case ATTR_ONMOUSEDOWN:
return ONMOUSEDOWN;
case ATTR_ONMOUSEWHEEL:
return ONMOUSEWHEEL;
case ATTR_ONRESET:
return ONRESET;
case ATTR_ONSELECT:
return ONSELECT;
case ATTR_ONRESIZE:
return ONRESIZE;
case ATTR_ONSCROLL:
return ONSCROLL;
case ATTR_ONHASHCHANGE:
return ONHASHCHANGE;
case ATTR_ONINPUT:
return ONINPUT;
case ATTR_ONFORMINPUT:
return ONFORMINPUT;
case ATTR_ONINVALID:
return ONINVALID;
case ATTR_ONFORMCHANGE:
return ONFORMCHANGE;
case ATTR_ONCONTEXTMENU:
return ONCONTEXTMENU;
#ifdef MEDIA_HTML_SUPPORT
case ATTR_ONLOADSTART:
return ONLOADSTART;
case ATTR_ONPROGRESS:
return ONPROGRESS;
case ATTR_ONSUSPEND:
return ONSUSPEND;
case ATTR_ONSTALLED:
return ONSTALLED;
case ATTR_ONLOADEND:
return ONLOADEND;
case ATTR_ONEMPTIED:
return MEDIAEMPTIED;
case ATTR_ONPLAY:
return MEDIAPLAY;
case ATTR_ONPAUSE:
return MEDIAPAUSE;
case ATTR_ONLOADEDMETADATA:
return MEDIALOADEDMETADATA;
case ATTR_ONLOADEDDATA:
return MEDIALOADEDDATA;
case ATTR_ONWAITING:
return MEDIAWAITING;
case ATTR_ONPLAYING:
return MEDIAPLAYING;
case ATTR_ONSEEKING:
return MEDIASEEKING;
case ATTR_ONSEEKED:
return MEDIASEEKED;
case ATTR_ONTIMEUPDATE:
return MEDIATIMEUPDATE;
case ATTR_ONENDED:
return MEDIAENDED;
case ATTR_ONCANPLAY:
return MEDIACANPLAY;
case ATTR_ONCANPLAYTHROUGH:
return MEDIACANPLAYTHROUGH;
case ATTR_ONRATECHANGE:
return MEDIARATECHANGE;
case ATTR_ONDURATIONCHANGE:
return MEDIADURATIONCHANGE;
case ATTR_ONVOLUMECHANGE:
return MEDIAVOLUMECHANGE;
case Markup::HA_ONCUECHANGE:
return MEDIACUECHANGE;
#endif // MEDIA_HTML_SUPPORT
#ifdef CLIENTSIDE_STORAGE_SUPPORT
case ATTR_ONSTORAGE:
return STORAGE;
#endif // CLIENTSIDE_STORAGE_SUPPORT
#ifdef TOUCH_EVENTS_SUPPORT
case ATTR_ONTOUCHSTART:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHSTART;
break;
case ATTR_ONTOUCHMOVE:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHMOVE;
break;
case ATTR_ONTOUCHEND:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHEND;
break;
case ATTR_ONTOUCHCANCEL:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHCANCEL;
break;
#endif // TOUCH_EVENTS_SUPPORT
case ATTR_ONPOPSTATE:
return ONPOPSTATE;
#ifdef PAGED_MEDIA_SUPPORT
case Markup::HA_ONPAGECHANGE:
return ONPAGECHANGE;
#endif // PAGED_MEDIA_SUPPORT
#ifdef DRAG_SUPPORT
case Markup::HA_ONDRAG:
return ONDRAG;
case Markup::HA_ONDRAGOVER:
return ONDRAGOVER;
case Markup::HA_ONDRAGENTER:
return ONDRAGENTER;
case Markup::HA_ONDRAGLEAVE:
return ONDRAGLEAVE;
case Markup::HA_ONDRAGSTART:
return ONDRAGSTART;
case Markup::HA_ONDRAGEND:
return ONDRAGEND;
case Markup::HA_ONDROP:
return ONDROP;
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
case Markup::HA_ONCOPY:
return ONCOPY;
case Markup::HA_ONCUT:
return ONCUT;
case Markup::HA_ONPASTE:
return ONPASTE;
#endif // USE_OP_CLIPBOARD
}
}
#ifdef SVG_DOM
else if (attr_ns_type == NS_SVG)
{
switch (attr)
{
case Markup::SVGA_ONFOCUSIN:
return ONFOCUSIN;
case Markup::SVGA_ONFOCUSOUT:
return ONFOCUSOUT;
case Markup::SVGA_ONACTIVATE:
return DOMACTIVATE;
case Markup::SVGA_ONCLICK:
return ONCLICK;
case Markup::SVGA_ONMOUSEDOWN:
return ONMOUSEDOWN;
case Markup::SVGA_ONMOUSEUP:
return ONMOUSEUP;
case Markup::SVGA_ONMOUSEOVER:
return ONMOUSEOVER;
case Markup::SVGA_ONMOUSEENTER:
return ONMOUSEENTER;
case Markup::SVGA_ONMOUSEMOVE:
return ONMOUSEMOVE;
case Markup::SVGA_ONMOUSEOUT:
return ONMOUSEOUT;
case Markup::SVGA_ONMOUSELEAVE:
return ONMOUSELEAVE;
case Markup::SVGA_ONUNLOAD:
return SVGUNLOAD;
case Markup::SVGA_ONLOAD:
return SVGLOAD;
case Markup::SVGA_ONABORT:
return SVGABORT;
case Markup::SVGA_ONERROR:
return SVGERROR;
case Markup::SVGA_ONRESIZE:
return SVGRESIZE;
case Markup::SVGA_ONSCROLL:
return SVGSCROLL;
case Markup::SVGA_ONZOOM:
return SVGZOOM;
case Markup::SVGA_ONBEGIN:
return BEGINEVENT;
case Markup::SVGA_ONEND:
return ENDEVENT;
case Markup::SVGA_ONREPEAT:
return REPEATEVENT;
#ifdef PROGRESS_EVENTS_SUPPORT
case Markup::SVGA_ONLOADSTART:
return ONLOADSTART;
case Markup::SVGA_ONPROGRESS:
return ONPROGRESS;
case Markup::SVGA_ONSUSPEND:
return ONSUSPEND;
case Markup::SVGA_ONSTALLED:
return ONSTALLED;
case Markup::SVGA_ONLOADEND:
return ONLOADEND;
#endif // PROGRESS_EVENTS_SUPPORT
#ifdef TOUCH_EVENTS_SUPPORT
case Markup::SVGA_ONTOUCHSTART:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHSTART;
break;
case Markup::SVGA_ONTOUCHMOVE:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHMOVE;
break;
case Markup::SVGA_ONTOUCHEND:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHEND;
break;
case Markup::SVGA_ONTOUCHCANCEL:
# ifdef PI_UIINFO_TOUCH_EVENTS
if(g_op_ui_info->IsTouchEventSupportWanted())
# endif // PI_UIINFO_TOUCH_EVENTS
return TOUCHCANCEL;
break;
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
case Markup::SVGA_ONDRAG:
return ONDRAG;
case Markup::SVGA_ONDRAGOVER:
return ONDRAGOVER;
case Markup::SVGA_ONDRAGENTER:
return ONDRAGENTER;
case Markup::SVGA_ONDRAGLEAVE:
return ONDRAGLEAVE;
case Markup::SVGA_ONDRAGSTART:
return ONDRAGSTART;
case Markup::SVGA_ONDRAGEND:
return ONDRAGEND;
case Markup::SVGA_ONDROP:
return ONDROP;
#endif // DRAG_SUPPORT
#ifdef USE_OP_CLIPBOARD
case Markup::SVGA_ONCOPY:
return ONCOPY;
case Markup::SVGA_ONCUT:
return ONCUT;
case Markup::SVGA_ONPASTE:
return ONPASTE;
#endif // USE_OP_CLIPBOARD
}
}
#endif // SVG_DOM
return DOM_EVENT_NONE;
}
#ifdef XML_EVENTS_SUPPORT
OP_STATUS HTML_Element::HandleInsertedElementWithXMLEvent(FramesDocument* frames_doc)
{
OP_ASSERT(HasXMLEventAttribute());
RETURN_IF_MEMORY_ERROR(frames_doc->ConstructDOMEnvironment());
if (!frames_doc->GetDOMEnvironment())
return OpStatus::OK; // No scripts to worry about
XML_Events_Registration *registration = GetXMLEventsRegistration();
if (!registration)
{
registration = OP_NEW(XML_Events_Registration, (this));
if (!registration)
return OpStatus::ERR_NO_MEMORY;
int attr_index = SetSpecialAttr(ATTR_XML_EVENTS_REGISTRATION, ITEM_TYPE_XML_EVENTS_REGISTRATION, registration, TRUE, SpecialNs::NS_LOGDOC);
if (attr_index == -1)
{
OP_DELETE(registration);
return OpStatus::ERR_NO_MEMORY;
}
frames_doc->AddXMLEventsRegistration(registration);
}
int xml_ev_attrs[] = {
XML_EV_EVENT, XML_EV_PHASE, XML_EV_TARGET, XML_EV_HANDLER,
XML_EV_OBSERVER,XML_EV_PROPAGATE,XML_EV_DEFAULTACTION };
for (unsigned i = 0; i < sizeof(xml_ev_attrs)/sizeof(*xml_ev_attrs); i++)
{
const uni_char* value;
int attr = xml_ev_attrs[i];
if ((value = GetStringAttr(attr, NS_IDX_EVENT)) != NULL)
HandleXMLEventAttribute(frames_doc, registration, attr, value, uni_strlen(value));
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::HandleXMLEventAttribute(FramesDocument* frames_doc, XML_Events_Registration *registration, int ns_event_attr, const uni_char* value, int value_len)
{
OP_ASSERT(frames_doc->GetDOMEnvironment());
OP_ASSERT(GetXMLEventsRegistration() == registration);
OP_STATUS ret_stat = OpStatus::OK;
switch (ns_event_attr)
{
case XML_EV_EVENT:
ret_stat = registration->SetEventType(frames_doc, value, value_len);
break;
case XML_EV_TARGET:
ret_stat = registration->SetTargetId(frames_doc, value, value_len);
break;
case XML_EV_OBSERVER:
ret_stat = registration->SetObserverId(frames_doc, value, value_len);
break;
case XML_EV_HANDLER:
ret_stat = registration->SetHandlerURI(frames_doc, value, value_len);
break;
case XML_EV_PHASE:
if (value_len == 7 && uni_strncmp(UNI_L("capture"), value, value_len) == 0)
registration->SetCapture(TRUE);
break;
case XML_EV_PROPAGATE:
if (value_len == 4 && uni_strncmp(UNI_L("stop"), value, value_len) == 0)
registration->SetStopPropagation(TRUE);
break;
case XML_EV_DEFAULTACTION:
if (value_len == 6 && uni_strncmp(UNI_L("cancel"), value, value_len) == 0)
registration->SetPreventDefault(TRUE);
break;
}
return ret_stat;
}
BOOL HTML_Element::HasXMLEventAttribute()
{
if (!Markup::IsRealElement(Type()))
return FALSE;
for (int i = 0 ; i < GetAttrCount(); i++)
{
if (!GetAttrIsSpecial(i))
{
int ns_idx = GetAttrNs(i);
NS_Type ns = g_ns_manager->GetNsTypeAt(ResolveNsIdx(ns_idx));
if (ns == NS_EVENT)
return TRUE;
}
}
return FALSE;
}
#endif // XML_EVENTS_SUPPORT
void HTML_Element::UpdateLinkVisited(FramesDocument* doc)
{
// Use ApplyPropertyChanges instead and let the layout engine determine what has to be done more exactly?
if (GetLayoutBox())
{
URL href_url = GetAnchor_URL(doc);
if (!href_url.IsEmpty())
{
if (href_url.GetAttribute(URL::KIsFollowed, URL::KFollowRedirect))
MarkPropsDirty(doc);
}
for (HTML_Element* child = FirstChildActual(); child; child = child->SucActual())
child->UpdateLinkVisited(doc);
}
}
/** Deprecated! Please use Box::GetRect() */
BOOL HTML_Element::GetBoxRect(FramesDocument* doc, BoxRectType type, RECT& rect)
{
return GetLayoutBox() && GetLayoutBox()->GetRect(doc, type, rect);
}
const XMLDocumentInformation *HTML_Element::GetXMLDocumentInfo() const
{
if (Type() == HE_DOCTYPE)
{
XMLDocumentInfoAttr *attr = static_cast<XMLDocumentInfoAttr *>(static_cast<ComplexAttr *>(GetSpecialAttr(ATTR_XMLDOCUMENTINFO, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_LOGDOC)));
if (attr)
return attr->GetDocumentInfo();
}
return NULL;
}
#ifdef _WML_SUPPORT_
const uni_char*
HTML_Element::GetHtmlOrWmlStringAttr(short html_attr, short wml_attr) const
{
if (GetNsType() == NS_WML)
{
const uni_char *candidate = GetStringAttr(wml_attr, NS_IDX_WML);
if (candidate)
return candidate;
}
return GetStringAttr(html_attr);
}
#endif // _WML_SUPPORT_
HTTP_Method HTML_Element::GetMethod() const
{
#ifdef _WML_SUPPORT_
if (GetNsType() == NS_WML && HasAttr(WA_METHOD, NS_IDX_WML))
return (HTTP_Method)GetNumAttr(WA_METHOD, NS_IDX_WML, HTTP_METHOD_GET);
#endif // _WML_SUPPORT_
return (HTTP_Method)GetNumAttr(ATTR_METHOD, NS_IDX_HTML, HTTP_METHOD_GET);
}
InputType
HTML_Element::GetInputType() const
{
#ifdef _WML_SUPPORT_
if (GetNsType() == NS_WML && HasAttr(WA_TYPE, NS_IDX_WML))
{
return (InputType)GetNumAttr(WA_TYPE, NS_IDX_WML, INPUT_TEXT);
}
#endif // _WML_SUPPORT_
InputType def = ((HTML_ElementType) packed1.type == HE_BUTTON) ? INPUT_SUBMIT : INPUT_TEXT;
InputType type = (InputType)GetNumAttr(ATTR_TYPE, NS_IDX_HTML, def);
return type;
}
const uni_char* HTML_Element::GetElementTitle() const
{
#if defined SVG_SUPPORT || defined _WML_SUPPORT_
NS_Type ns_type = GetNsType();
#endif // SVG_SUPPORT || _WML_SUPPORT_
#ifdef SVG_SUPPORT
if (ns_type == NS_SVG)
return (const uni_char*)GetAttr(Markup::XLINKA_TITLE, ITEM_TYPE_STRING, NULL, NS_IDX_XLINK);
#endif // SVG_SUPPORT
#ifdef _WML_SUPPORT_
if (ns_type == NS_WML)
{
// we don't want the card title popping up when hovering <do>/<go>-elements
if ((WML_ElementType)Type() == WE_CARD)
return NULL;
else
{
const uni_char *elm_title = GetStringAttr(WA_TITLE, NS_IDX_WML);
if (elm_title)
return elm_title;
}
}
#endif //_WML_SUPPORT
// We let the html:title attribute work wherever it is
return GetStringAttr(ATTR_TITLE);
}
BOOL HTML_Element::GetAutocompleteOff()
{
if (Type() == HE_INPUT || Type() == HE_FORM)
{
const uni_char* on_status = GetAttrValue(UNI_L("AUTOCOMPLETE"));
if (on_status && uni_stricmp(on_status, UNI_L("OFF")) == 0)
return TRUE;
}
return FALSE;
}
BOOL HTML_Element::GetUnselectable()
{
const uni_char *unselectable = GetStringAttr(ATTR_UNSELECTABLE);
if (unselectable && uni_stri_eq(unselectable, UNI_L("on")))
return TRUE;
return FALSE;
}
int HTML_Element::GetRowsOrCols(BOOL get_row) const
{
if (GetNsType() == NS_HTML && (Type() == HE_TEXTAREA || Type() == HE_INPUT))
{
short attr = (get_row) ? ATTR_ROWS : ATTR_COLS;
int val = (int)GetNumAttr(attr);
if (!val)
{
const uni_char* size = GetStringAttr(ATTR_SIZE);
if (size && !HasAttr(attr))
{
const uni_char *tmp = size;
while (*tmp && *tmp++ != ',') {}
if (*tmp)
{
if (get_row)
tmp = size;
val = uni_atoi(tmp);
}
}
if (!val && Type() == HE_TEXTAREA)
val = get_row ? 2 : 20;
}
return val;
}
return 0;
}
int HTML_Element::GetRows() const
{
return GetRowsOrCols(TRUE);
}
int HTML_Element::GetCols() const
{
return GetRowsOrCols(FALSE);
}
BOOL HTML_Element::GetMultiple() const
{
#ifdef _WML_SUPPORT_
if (GetNsType() == NS_WML)
{
BOOL multiple = GetBoolAttr(WA_MULTIPLE, NS_IDX_WML);
if (multiple)
return multiple;
}
#endif // _WML_SUPPORT_
if (Type() == HE_SELECT)
return GetBoolAttr(ATTR_MULTIPLE);
else
return FALSE;
}
int HTML_Element::GetTabIndex(FramesDocument* doc /*= NULL */)
{
#ifdef _WML_SUPPORT_
if (GetNsType() == NS_WML)
{
int index = (int)GetNumAttr(WA_TABINDEX, NS_IDX_WML, -1);
if (index != -1)
return index;
}
#endif // _WML_SUPPORT_
int default_value = -1; // Default value for things that are normally not focusable
if (IsFormElement() ||
(IsMatchingType(HE_A, NS_HTML) ||
IsMatchingType(HE_AREA, NS_HTML)) && HasAttr(ATTR_HREF)
#ifdef DOCUMENT_EDIT_SUPPORT
|| IsContentEditable()
#endif // DOCUMENT_EDIT_SUPPORT
)
{
default_value = 0; // Default value for things that are normally focusable.
}
#ifdef MEDIA_HTML_SUPPORT
if (IsMatchingType(HE_VIDEO, NS_HTML) || IsMatchingType(HE_AUDIO, NS_HTML)
#ifdef DOM_JIL_API_SUPPORT
|| IsMatchingType(HE_OBJECT, NS_HTML)
#endif //DOM_JIL_API_SUPPORT
)
{
Media* media_elm = GetMedia();
if (media_elm && media_elm->IsFocusable())
{
default_value = 0;
}
}
#endif // MEDIA_HTML_SUPPORT
#ifdef DOCUMENT_EDIT_SUPPORT
// tabIndex of editable iframes is 0
if (IsMatchingType(HE_IFRAME, NS_HTML))
{
if (doc)
{
FramesDocElm *fde = FramesDocElm::GetFrmDocElmByHTML(this);
// No reason to tab to an empty or readonly iframe
if (fde && fde->GetCurrentDoc() && fde->GetCurrentDoc()->GetDocumentEdit())
{
default_value = 0;
}
}
}
#endif // DOCUMENT_EDIT_SUPPORT
return (int)GetNumAttr(ATTR_TABINDEX, NS_IDX_HTML, default_value);
}
#if defined SAVE_DOCUMENT_AS_TEXT_SUPPORT
// line_length == 0 means start of new line, line_length < 0 means (-line_length) empty lines.
/**
* Wrapper method to encapsulate the LEAVE functionality and convert it to OP_STATUS.
*/
static OP_STATUS WriteToStream(UnicodeOutputStream* out, const uni_char* str, int len)
{
TRAPD(status, out->WriteStringL(str, len));
return status;
}
/**
* Wrapper method to encapsulate the LEAVE functionality and convert it to OP_STATUS.
*/
static OP_STATUS WriteToStream(UnicodeOutputStream* out, uni_char c)
{
TRAPD(status, out->WriteStringL(&c, 1));
return status;
}
OP_STATUS HTML_Element::WriteAsText(UnicodeOutputStream* out, HLDocProfile* hld_profile, LayoutProperties* cascade, int max_line_length, int& line_length, BOOL& trailing_ws, BOOL& prevent_newline, BOOL& pending_newline)
{
OpString new_line_string;
RETURN_IF_ERROR(new_line_string.Set(NEWLINE));
if (Type() == HE_TEXT)
{
const uni_char* text_content = LocalContent();
if (text_content)
{
WordInfo word_info;
FontSupportInfo font_info(0);
font_info.current_font = 0; // we are not interested in fonts ...
const uni_char* tmp = text_content;
short white_space = cascade->GetProps()->white_space;
int len = GetTextContentLength();
for (;;)
{
const uni_char* word = tmp;
word_info.Reset();
word_info.SetLength(0);
if (!GetNextTextFragment(tmp, len, word_info, CSSValue(white_space),
white_space == CSS_VALUE_nowrap, TRUE, font_info,
hld_profile ? hld_profile->GetFramesDocument() : NULL,
#ifdef FONTSWITCHING
hld_profile ? hld_profile->GetPreferredScript() :
#endif // FONTSWITCHING
WritingSystem::Unknown))
break;
len -= (tmp-word);
if (word_info.GetLength() && *word != 173) // Soft hyphen
{
if (pending_newline)
{
prevent_newline = FALSE;
pending_newline = FALSE;
trailing_ws = FALSE;
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = 0;
}
if (line_length > 0 && trailing_ws && max_line_length >= 0 && line_length + word_info.GetLength() > (unsigned int) max_line_length && (white_space == CSS_VALUE_normal || white_space == CSS_VALUE_pre_wrap))
{
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = 0;
}
if (line_length < 0)
line_length = 0;
WriteToStream(out, word, word_info.GetLength());//FIXME:
trailing_ws = FALSE;
line_length += word_info.GetLength();
}
if (word_info.IsTabCharacter())
{
if (line_length < 0)
line_length = 0;
WriteToStream(out, '\t');//FIXME:OOM
trailing_ws = TRUE;
line_length++;
}
else
{
// Trailing ws is only interesting if not in pre/pre-wrap since in pre-wrap and
// pre it will come as a seperate word anyway.
BOOL word_has_trailing_ws = word_info.HasTrailingWhitespace() && white_space != CSS_VALUE_pre && white_space != CSS_VALUE_pre_wrap;
if (line_length > 0 && word_has_trailing_ws)
{
if (!trailing_ws)
{
WriteToStream(out, ' ');//FIXME:OOM
trailing_ws = TRUE;
line_length++;
}
}
}
if (word_info.HasEndingNewline())
{
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = 0;
}
}
}
}
else if (Type() == HE_BR)
{
prevent_newline = FALSE;
pending_newline = FALSE;
trailing_ws = FALSE;
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
if (line_length > 0)
line_length = 0;
else
line_length--;
}
else
{
BOOL is_block = FALSE;
LayoutProperties* child_cascade;
switch (cascade->GetProps()->display_type)
{
case CSS_VALUE_none:
return OpStatus::OK;
case CSS_VALUE_table_cell:
prevent_newline = TRUE;
break;
case CSS_VALUE_block:
if (cascade->GetProps()->float_type != CSS_VALUE_none)
break; // treat floats as inline
case CSS_VALUE_list_item:
if (pending_newline)
{
pending_newline = FALSE;
trailing_ws = FALSE;
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = 0;
}
if (!prevent_newline && line_length >= 0)
{
trailing_ws = FALSE;
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
if (line_length > 0)
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = -1;
}
is_block = TRUE;
break;
}
for (HTML_Element* child = FirstChild(); child; child = child->Suc())
{
child_cascade = cascade->GetChildProperties(hld_profile, child);
if (child_cascade)
{
OP_STATUS status = child->WriteAsText(out, hld_profile, child_cascade, max_line_length, line_length, trailing_ws, prevent_newline, pending_newline);
child_cascade->Clean();
RETURN_IF_ERROR(status);
}
else
return OpStatus::ERR_NO_MEMORY;
}
if (is_block)
{
prevent_newline = FALSE;
if (line_length > 0)
pending_newline = TRUE;
}
else if (cascade->GetProps()->display_type == CSS_VALUE_table_row)
{
prevent_newline = FALSE;
pending_newline = FALSE;
trailing_ws = FALSE;
if (line_length > 0)
{
WriteToStream(out, new_line_string.CStr(), new_line_string.Length());//FIXME:OOM
line_length = 0;
}
}
else if (line_length > 0 && cascade->GetProps()->display_type == CSS_VALUE_table_cell)
{
trailing_ws = TRUE;
WriteToStream(out, ' ');//FIXME:OOM
line_length++;
}
}
return OpStatus::OK;
}
#endif // SAVE_DOCUMENT_AS_TEXT_SUPPORT
int
HTML_AttrIterator::Count()
{
int i, count;
for (i = 0, count = 0; i < element->GetAttrSize(); ++i)
{
short attr = element->GetAttrItem(i);
if (attr != ATTR_NULL && !element->GetAttrIsSpecial(i))
++count;
}
return count;
}
BOOL
HTML_AttrIterator::GetNext(const uni_char *&name, const uni_char *&value, int* ns_idx /* = NULL */)
{
int ns_idx_tmp;
BOOL specified, id;
if (GetNext(name, value, ns_idx_tmp, specified, id))
{
if (ns_idx)
*ns_idx = ns_idx_tmp;
return TRUE;
}
else
return FALSE;
}
const uni_char*
HTML_ImmutableAttrIterator::GetNextId()
{
int attr_size = element->GetAttrSize();
while (idx < attr_size)
{
if (element->GetAttrIsId(idx) &&
element->GetItemType(idx) == ITEM_TYPE_STRING)
{
return element->GetAttrValueString(idx++);
}
idx++;
}
return NULL;
}
BOOL
HTML_AttrIterator::GetNext(const uni_char *&name, const uni_char *&value, int &ns_idx, BOOL &specified, BOOL &id)
{
int i, j;
for (i = 0, j = idx; i < element->GetAttrSize(); ++i)
{
short attr = element->GetAttrItem(i);
if (attr != ATTR_NULL && !element->GetAttrIsSpecial(i))
if (j == 0)
{
buffer.Clear();
name = element->GetAttrNameString(i); OP_ASSERT(name);
value = element->GetAttrValueValue(i, attr, HE_ANY, &buffer);
ns_idx = element->GetAttrNs(i);
specified = element->data.attrs[i].IsSpecified();
id = element->GetAttrIsId(i);
if (!value)
/* Not just to be safe: if an attribute that is generated into the buffer is
empty and the buffer has no storage allocated already, GetAttrValueValue
returns NULL when it actually means "empty string".
Also just to be safe. :-) */
value = UNI_L("");
++idx;
return TRUE;
}
else
--j;
}
return FALSE;
}
#ifdef WEB_TURBO_MODE
BOOL
HTML_AttrIterator::GetNext(int& attr, int& ns_idx, BOOL& is_special, void*& obj, ItemType& item_type)
{
int i, j;
for (i = 0, j = idx; i < element->GetAttrSize(); ++i)
{
short a = element->GetAttrItem(i);
if (a != ATTR_NULL)
if (j == 0)
{
attr = a;
idx++;
ns_idx = element->GetAttrNs(i);
is_special = element->GetAttrIsSpecial(i);
obj = element->GetValueItem(i);
item_type = element->GetItemType(i);
return TRUE;
}
else
--j;
}
return FALSE;
}
#endif // WEB_TURBO_MODE
#ifdef SVG_SUPPORT
BOOL
HTML_ImmutableAttrIterator::GetNext(int& attr, int& ns_idx, BOOL& is_special, void*& obj, ItemType& item_type)
{
int attr_size = element->GetAttrSize();
while (idx < attr_size)
{
short a = element->GetAttrItem(idx);
if (a != ATTR_NULL)
{
attr = a;
ns_idx = element->GetAttrNs(idx);
is_special = element->GetAttrIsSpecial(idx);
obj = element->GetValueItem(idx);
item_type = element->GetItemType(idx);
idx++;
return TRUE;
}
idx++;
}
return FALSE;
}
#endif // SVG_SUPPORT
void
HTML_AttrIterator::Reset(HTML_Element *new_element)
{
element = new_element;
idx = 0;
}
COLORREF HTML_Element::GetCssBackgroundColorFromStyleAttr(FramesDocument* doc /* = NULL */)
{
/* This is wrong! Avoid using this function. */
if (IsPropsDirty())
{
if (doc)
doc->GetLogicalDocument()->GetLayoutWorkplace()->UnsafeLoadProperties(this);
else
OP_ASSERT(!"Will return the wrong value since we had no Document pointer.");
}
return CssPropertyItem::GetCssBackgroundColor(this);
}
COLORREF HTML_Element::GetCssColorFromStyleAttr(FramesDocument* doc /* = NULL */)
{
/* This is wrong! Avoid using this function.
The color CSS property is inherited, so the cascade is needed to give correct results. */
if (IsPropsDirty())
{
if (doc)
doc->GetLogicalDocument()->GetLayoutWorkplace()->UnsafeLoadProperties(this);
else
OP_ASSERT(!"Will return the wrong value since we had no Document pointer.");
}
return CssPropertyItem::GetCssColor(this);
}
CursorType HTML_Element::GetCursorType()
{
/* This is wrong! Avoid using this function.
The cursor CSS property is inherited, so the cascade is needed to give correct results. */
return CssPropertyItem::GetCursorType(this);
}
void HTML_Element::DeleteCssProperties()
{
if (css_properties)
{
if (packed2.shared_css)
g_sharedCssManager->DeleteSharedCssProperties(css_properties, GetCssPropLen() * sizeof(CssPropertyItem));
else
OP_DELETEA(css_properties);
css_properties = 0;
packed2.shared_css = 0;
SetCssPropLen(0);
}
}
void HTML_Element::UnshareCssProperties()
{
if (packed2.shared_css || !css_properties)
{
DeleteCssProperties();
packed2.shared_css = 0;
}
}
#ifdef MANUAL_PLUGIN_ACTIVATION
BOOL
HTML_Element::GetPluginActivated()
{
return GetSpecialBoolAttr(ATTR_PLUGIN_ACTIVE, SpecialNs::NS_LOGDOC);
}
void
HTML_Element::SetPluginActivated(BOOL activate)
{
SetSpecialBoolAttr(ATTR_PLUGIN_ACTIVE, activate, SpecialNs::NS_LOGDOC);
}
BOOL
HTML_Element::GetPluginExternal()
{
return GetSpecialBoolAttr(ATTR_PLUGIN_EXTERNAL, SpecialNs::NS_LOGDOC);
}
void
HTML_Element::SetPluginExternal(BOOL external)
{
SetSpecialBoolAttr(ATTR_PLUGIN_EXTERNAL, external, SpecialNs::NS_LOGDOC);
}
#endif // MANUAL_PLUGIN_ACTIVATION
BOOL HTML_Element::IsFirstChild()
{
if (Parent())
{
HTML_Element* child = ParentActual()->FirstChildActual();
while (child && !Markup::IsRealElement(child->Type()))
child = child->SucActual();
return (child == this);
}
else
return FALSE;
}
BOOL
HTML_Element::IsPreFocused() const
{
if (IsMatchingType(HE_INPUT, NS_HTML))
{
InputType inp_type = GetInputType();
switch (inp_type)
{
case INPUT_CHECKBOX:
case INPUT_RADIO:
case INPUT_SUBMIT:
case INPUT_RESET:
case INPUT_BUTTON:
return FALSE;
}
}
else if (!IsMatchingType(HE_TEXTAREA, NS_HTML) && !IsMatchingType(HE_SELECT, NS_HTML))
return FALSE;
return GetSpecialBoolAttr(ATTR_PREFOCUSED, SpecialNs::NS_LOGDOC);
}
BOOL
HTML_Element::IsDisplayingReplacedContent()
{
return GetLayoutBox() && GetLayoutBox()->IsContentReplaced();
}
#if defined(JS_PLUGIN_SUPPORT)
JS_Plugin_Object* HTML_Element::GetJSPluginObject()
{
JS_Plugin_Object* jso = NULL;
ES_Object* esobj = DOM_Utils::GetJSPluginObject(GetESElement());
if (esobj)
{
EcmaScript_Object* eso = ES_Runtime::GetHostObject(esobj);
if (eso)
{
OP_ASSERT(eso->IsA(ES_HOSTOBJECT_JSPLUGIN));
jso = static_cast<JS_Plugin_Object*>(eso);
}
}
return jso;
}
OP_BOOLEAN HTML_Element::IsJSPluginObject(HLDocProfile* hld_profile, JS_Plugin_Object **obj_pp) const
{
if (Type() == HE_OBJECT)
{
const uni_char* type = GetStringAttr(ATTR_TYPE);
if (type)
{
FramesDocument *frames_doc = hld_profile->GetFramesDocument();
OP_STATUS status = frames_doc->ConstructDOMEnvironment();
RETURN_IF_MEMORY_ERROR(status);
if (OpStatus::IsError(status))
{
// No scripting allowed, this is not a jsplugin object
return OpBoolean::IS_FALSE;
}
DOM_Environment *environment = frames_doc->GetDOMEnvironment();
if (environment && environment->IsEnabled())
if (JS_Plugin_Context *ctx = environment->GetJSPluginContext())
if (ctx->HasObjectHandler(type, obj_pp))
return OpBoolean::IS_TRUE;
}
}
return OpBoolean::IS_FALSE;
}
OP_STATUS HTML_Element::PassParamsForJSPlugin(LogicalDocument* logdoc)
{
OP_STATUS res = OpStatus::OK;
if (Type() == HE_OBJECT)
{
int param_count = CountParams();
if (param_count)
{
JS_Plugin_Object *handler = NULL;
JS_Plugin_Object *js_obj = NULL;
if (IsJSPluginObject(logdoc->GetHLDocProfile(), &handler) == OpBoolean::IS_TRUE && (js_obj = GetJSPluginObject()) != NULL)
{
int next_index = 0;
const uni_char** names = OP_NEWA(const uni_char*, param_count);
const uni_char** values = OP_NEWA(const uni_char*, param_count);
if (!names || !values)
{
OP_DELETEA(names);
OP_DELETEA(values);
return OpStatus::ERR_NO_MEMORY;
}
GetParams(names, values, next_index);
if (param_count == next_index)
{
for (int i = 0; i < param_count; i++)
{
if (names[i])
js_obj->ParamSet(names[i], values[i]);
}
}
else
res = OpStatus::ERR_PARSING_FAILED;
OP_DELETEA(names);
OP_DELETEA(values);
}
}
}
return res;
}
#endif // JS_PLUGIN_SUPPORT
#ifdef INTERNAL_SPELLCHECK_SUPPORT
HTML_Element::SPC_ATTR_STATE HTML_Element::SpellcheckEnabledByAttr()
{
HTML_Element* he = this;
SPC_ATTR_STATE spellcheck = SPC_ENABLE_DEFAULT;
while (he)
{
spellcheck = static_cast<SPC_ATTR_STATE>(he->GetNumAttr(ATTR_SPELLCHECK));
if (spellcheck == SPC_ENABLE || spellcheck == SPC_DISABLE)
return spellcheck;
he = he->Parent();
}
return IsMatchingType(HE_INPUT, NS_HTML) ? SPC_DISABLE_DEFAULT : SPC_ENABLE_DEFAULT;
}
#endif // INTERNAL_SPELLCHECK_SUPPORT
#ifdef WEB_TURBO_MODE
OP_STATUS HTML_Element::UpdateTurboMode(LogicalDocument *logdoc, URL_CONTEXT_ID context_id)
{
HTML_AttrIterator iter(this);
int attr_code = 0;
int attr_ns_idx = 0;
BOOL attr_is_special = FALSE;
void *attr_value = NULL;
ItemType attr_type;
// Check if this is a link.
if (IsMatchingType(HE_A, NS_HTML))
{
while (iter.GetNext(attr_code, attr_ns_idx, attr_is_special, attr_value, attr_type))
{
if (attr_code == ATTR_HREF
&& attr_ns_idx == NS_IDX_HTML
&& attr_is_special == FALSE
&& attr_type == ITEM_TYPE_URL_AND_STRING)
{
UrlAndStringAttr *url_attr = static_cast<UrlAndStringAttr*>(attr_value);
URL new_url = ResolveUrl(url_attr->GetString(), logdoc, attr_code, TRUE);
OpStatus::Ignore(url_attr->SetResolvedUrl(new_url));
}
}
return OpStatus::OK;
}
#ifdef _WML_SUPPORT_
// WML Links are handled in WML_Context::GetWmlUrl()
#endif //_WML_SUPPORT_
#ifdef SVG_SUPPORT
# if 0
if (IsMatchingType(Markup::SVGE_A, NS_SVG))
{
// TODO: fix this for SVG links
}
# endif // 0
#endif // SVG_SUPPORT
int idx = FindSpecialAttrIndex(ATTR_CSS_LINK, SpecialNs::NS_LOGDOC);
if (idx != -1)
{
URL_CONTEXT_ID current_context_id = logdoc->GetCurrentContextId();
URL *css_url = static_cast<URL*>(GetValueItem(idx));
if (css_url && css_url->GetContextId() != current_context_id)
{
const OpStringC8 css_str
= css_url->GetAttribute(URL::KName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect);
URL new_url = g_url_api->GetURL(css_str.CStr(), current_context_id);
URL *allocated_url = new URL(new_url);
ReplaceAttrLocal(idx, ATTR_CSS_LINK, ITEM_TYPE_URL, allocated_url, SpecialNs::NS_LOGDOC, TRUE, TRUE, FALSE, FALSE, FALSE);
}
}
return OpStatus::OK;
}
OP_STATUS HTML_Element::DisableTurboForImage()
{
short attr = ATTR_NULL;
if (GetNsType() != NS_HTML)
return OpStatus::ERR_NOT_SUPPORTED;
HTML_ElementType type = Type();
switch (type)
{
case HE_IMG:
#ifdef PICTOGRAM_SUPPORT
if (GetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC) != NULL)
return OpStatus::OK;
#endif // PICTOGRAM_SUPPORT
// fall through
case HE_INPUT:
attr = ATTR_SRC;
break;
case HE_OBJECT:
#ifdef PICTOGRAM_SUPPORT
if (GetSpecialAttr(ATTR_LOCALSRC_URL, ITEM_TYPE_URL, NULL, SpecialNs::NS_LOGDOC) != NULL)
return OpStatus::OK;
#endif // PICTOGRAM_SUPPORT
attr = ATTR_DATA;
break;
case HE_TABLE:
case HE_TD:
case HE_TH:
case HE_BODY:
attr = ATTR_BACKGROUND;
break;
default:
return OpStatus::ERR_NOT_SUPPORTED;
}
UrlAndStringAttr *url_attr = static_cast<UrlAndStringAttr*>(GetAttr(attr, ITEM_TYPE_URL_AND_STRING, (void*)NULL));
if (url_attr)
{
URL *old_url = url_attr->GetResolvedUrl();
if (!old_url || old_url->IsEmpty() || !old_url->GetAttribute(URL::KUsesTurbo))
return OpStatus::OK; // Either no URL to convert or URL is not using Turbo
const OpStringC img_url_str = old_url->GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect);
URL new_url = g_url_api->GetURL(img_url_str);
if (new_url.IsEmpty())
return OpStatus::ERR;
// There is currently only support for one src/data/background attribute
return url_attr->SetResolvedUrl(new_url);
}
return OpStatus::OK;
}
#endif // WEB_TURBO_MODE
void HTML_Element::ResetExtraBackgroundList()
{
HTML_Element::BgImageIterator iter(this);
HEListElm *iter_elm = iter.Next();
while (iter_elm)
{
if (iter_elm->GetInlineType() == EXTRA_BGIMAGE_INLINE)
iter_elm->SetActive(FALSE);
iter_elm = iter.Next();
}
}
void HTML_Element::CommitExtraBackgroundList()
{
HTML_Element::BgImageIterator iter(this);
HEListElm *iter_elm = iter.Next();
while (iter_elm)
{
HEListElm *next_iter_elm = iter.Next();
if (!iter_elm->IsActive())
OP_DELETE(iter_elm);
iter_elm = next_iter_elm;
}
}
#ifdef ON_DEMAND_PLUGIN
void HTML_Element::SetIsPluginPlaceholder()
{
SetSpecialBoolAttr(ATTR_PLUGIN_PLACEHOLDER, TRUE, SpecialNs::NS_LOGDOC);
}
void HTML_Element::SetPluginDemanded()
{
SetSpecialBoolAttr(ATTR_PLUGIN_DEMAND, TRUE, SpecialNs::NS_LOGDOC);
RemoveSpecialAttribute(ATTR_PLUGIN_PLACEHOLDER, SpecialNs::NS_LOGDOC);
# ifdef MANUAL_PLUGIN_ACTIVATION
SetPluginActivated(TRUE);
# endif // MANUAL_PLUGIN_ACTIVATION
}
#endif // ON_DEMAND_PLUGIN
#ifdef MEDIA_HTML_SUPPORT
OP_STATUS HTML_Element::ConstructMediaElement(int attr_index, MediaElement **element)
{
OP_ASSERT(!GetSpecialAttr(Markup::MEDA_COMPLEX_MEDIA_ELEMENT, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_MEDIA));
MediaElement* media;
media = OP_NEW(MediaElement, (this));
if (!media)
return OpStatus::ERR_NO_MEMORY;
if (attr_index >= 0)
SetAttrLocal(attr_index, Markup::MEDA_COMPLEX_MEDIA_ELEMENT, ITEM_TYPE_COMPLEX, media, SpecialNs::NS_MEDIA, TRUE, TRUE);
else
if (SetSpecialAttr(Markup::MEDA_COMPLEX_MEDIA_ELEMENT, ITEM_TYPE_COMPLEX, media, TRUE, SpecialNs::NS_MEDIA) < 0)
return OpStatus::ERR_NO_MEMORY;
if (element)
*element = media;
return OpStatus::OK;
}
MediaElement* HTML_Element::GetMediaElement()
{
MediaElement *media = static_cast<MediaElement *>(GetSpecialAttr(Markup::MEDA_COMPLEX_MEDIA_ELEMENT, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_MEDIA));
if (!media &&
(IsMatchingType(HE_AUDIO, NS_HTML) || IsMatchingType(HE_VIDEO, NS_HTML)) &&
OpStatus::IsError(ConstructMediaElement(-1, &media)))
media = NULL;
return media;
}
#endif // MEDIA_HTML_SUPPORT
#ifdef MEDIA_SUPPORT
Media* HTML_Element::GetMedia()
{
Markup::AttrType attr_id = static_cast<Markup::AttrType>(GetSpecialNumAttr(Markup::MEDA_MEDIA_ATTR_IDX, SpecialNs::NS_MEDIA, Markup::HA_NULL));
if (attr_id != Markup::HA_NULL)
return static_cast<Media *>(GetSpecialAttr(attr_id, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_MEDIA));
return NULL;
}
BOOL HTML_Element::SetMedia(Markup::AttrType media_attr, Media *media, BOOL need_free)
{
if(SetSpecialNumAttr(Markup::MEDA_MEDIA_ATTR_IDX, media_attr, SpecialNs::NS_MEDIA) != -1)
return SetSpecialAttr(media_attr, ITEM_TYPE_COMPLEX, reinterpret_cast<void*>(media), need_free, SpecialNs::NS_MEDIA) != -1;
return FALSE;
}
#endif // MEDIA_SUPPORT
void HTML_Element::ConstructL(LogicalDocument *logdoc, Markup::Type type, Markup::Ns ns, HTML5TokenWrapper *token)
{
OP_PROBE8_L(OP_PROBE_HTML_ELEMENT_CONSTRUCTL);
NS_Type ns_type = NS_HTML;
int ns_idx = NS_IDX_HTML;
if (ns == Markup::SVG)
{
ns_type = NS_SVG;
ns_idx = NS_IDX_SVG;
}
else if (ns == Markup::MATH)
{
ns_type = NS_MATHML;
ns_idx = NS_IDX_MATHML;
}
g_ns_manager->GetElementAt(GetNsIdx())->DecRefCount();
SetNsIdx(ns_idx);
g_ns_manager->GetElementAt(ns_idx)->IncRefCount();
SetType(type);
SetInserted(HE_NOT_INSERTED);
HLDocProfile *hld_profile = logdoc->GetHLDocProfile();
HtmlAttrEntry *ha_list = NULL;
unsigned token_attr_count = 0;
unsigned attr_count_extra = 0;
if (token)
{
ha_list = token->GetOrCreateAttrEntries(token_attr_count, attr_count_extra, logdoc);
if (!ha_list)
LEAVE_IF_ERROR(OpStatus::ERR_NO_MEMORY);
}
int attr_count = attr_count_extra;
attr_count += GetNumberOfExtraAttributesForType(type, ns_type, hld_profile, ha_list);
if (attr_count)
{
LEAVE_IF_NULL(data.attrs = NEW_HTML_Attributes((attr_count)));
SetAttrSize(attr_count);
REPORT_MEMMAN_INC(attr_count * sizeof(AttrItem));
}
else
data.attrs = NULL;
unsigned attr_i = 0, set_attr_i = 0;
if (attr_count_extra > 0)
{
for (; attr_i < attr_count_extra; attr_i++)
{
HtmlAttrEntry *hae = &ha_list[attr_i];
const uni_char* orig_hae_value = hae->value;
UINT orig_hae_value_len = hae->value_len;
BOOL may_steal = hae->delete_after_use;
void *value;
ItemType item_type;
BOOL need_free, is_event;
OP_STATUS status = ConstructAttrVal(hld_profile,
hae,
may_steal,
value,
item_type,
need_free,
is_event,
ha_list,
&set_attr_i);
if (OpStatus::IsError(status))
{
if (token)
token->DeleteAllocatedAttrEntries();
LEAVE(status);
}
if (may_steal && !hae->value) // value has been stolen
{
hae->delete_after_use = FALSE;
hae->value = orig_hae_value;
hae->value_len = orig_hae_value_len;
}
if (item_type != ITEM_TYPE_UNDEFINED)
SetAttrLocal(set_attr_i++, hae->attr, item_type, value, hae->ns_idx, need_free, hae->is_special, hae->is_id, hae->is_specified, is_event);
}
}
OP_STATUS oom_stat = OpStatus::OK;
if (attr_count - attr_count_extra > 0)
oom_stat = SetExtraAttributesForType(set_attr_i, ns_type, ha_list, token_attr_count, hld_profile);
if (attr_count_extra > 0 && token)
token->DeleteAllocatedAttrEntries();
#if defined(JS_PLUGIN_SUPPORT)
if (type == HE_OBJECT)
LEAVE_IF_FATAL(SetupJsPluginIfRequested(GetStringAttr(ATTR_TYPE), hld_profile));
#endif // JS_PLUGIN_SUPPORT
#if defined(SVG_SUPPORT)
if (ns_type == NS_SVG && type == Markup::SVGE_SVG)
{
SVGContext* ctx = g_svg_manager->CreateDocumentContext(this, hld_profile->GetLogicalDocument());
if (!ctx)
oom_stat = OpStatus::ERR_NO_MEMORY;
}
#endif // SVG_SUPPORT
LEAVE_IF_ERROR(oom_stat);
}
Markup::Ns HTML_Element::GetNs() const
{
NS_Type ns_type = GetNsType();
if (ns_type == NS_SVG)
return Markup::SVG;
else if (ns_type == NS_MATHML)
return Markup::MATH;
else
return Markup::HTML;
}
void HTML_Element::AddAttributeL(LogicalDocument *logdoc, const HTML5TokenBuffer *name, const uni_char *value, unsigned value_len)
{
Markup::AttrType attr = g_html5_name_mapper->GetAttrTypeFromTokenBuffer(name);
LEAVE_IF_ERROR(SetAttribute(logdoc, attr, attr == Markup::HA_XML ? name->GetBuffer() : NULL, NS_IDX_DEFAULT, value, value_len, NULL, FALSE, attr == Markup::HA_ID, TRUE));
}
/**
* Checks if the codebase attribute is a local file, which might be a security issue
*/
HTML_ElementType HTML_Element::CheckLocalCodebase(LogicalDocument* logdoc, HTML_ElementType type, const uni_char* mime_type)
{
OP_ASSERT(type == HE_APPLET || type == HE_EMBED);
if (type == HE_APPLET || (type == HE_EMBED && mime_type && uni_strni_eq(mime_type, "APPLICATION/X-JAVA", 18)))
{
URL* url = GetUrlAttr(ATTR_CODEBASE, NS_IDX_HTML, logdoc);
if (url && url->Type() == URL_FILE && logdoc && logdoc->GetFramesDocument())
{
URLType doc_url_type = logdoc->GetFramesDocument()->GetURL().Type();
if (doc_url_type != URL_FILE && doc_url_type != URL_EMAIL)
return HE_OBJECT;
}
}
return type;
}
#ifdef CSS_VIEWPORT_SUPPORT
CSS_ViewportMeta* HTML_Element::GetViewportMeta(const DocumentContext &context, BOOL create)
{
// Sanity check.
OP_ASSERT(Type() == HE_META);
CSS_ViewportMeta* viewport_meta = static_cast<CSS_ViewportMeta*>(GetSpecialAttr(ATTR_VIEWPORT_META, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_STYLE));
if (!viewport_meta && create)
{
viewport_meta = OP_NEW(CSS_ViewportMeta, (this));
if (viewport_meta)
{
if (SetSpecialAttr(ATTR_VIEWPORT_META, ITEM_TYPE_COMPLEX, viewport_meta, TRUE, SpecialNs::NS_STYLE) == -1)
{
OP_DELETE(viewport_meta);
viewport_meta = NULL;
}
}
if (!viewport_meta)
context.hld_profile->SetIsOutOfMemory(TRUE);
}
return viewport_meta;
}
#endif // CSS_VIEWPORT_SUPPORT
/* static */
HTML_Element *HTML_Element::GetCommonAncestorActual(HTML_Element *left, HTML_Element *right)
{
HTML_Element *tmp;
if (left == right || !left || !right)
return left;
//1. First get tree height from each node
unsigned path_height_left = 0, path_height_right = 0;
tmp = left;
while (tmp)
{
path_height_left++;
tmp = tmp->ParentActual();
}
tmp = right;
while (tmp)
{
path_height_right++;
tmp = tmp->ParentActual();
}
//2. Climb up the difference in height from each
// two nodes so they get to the same level
while (path_height_left > path_height_right)
{
path_height_left--;
left = left->ParentActual();
}
while (path_height_right > path_height_left)
{
path_height_right--;
right = right->ParentActual();
}
//3. Continue traversing upwards until they are the same, or NULL
while (left != right)
{
OP_ASSERT(left && right); // The trees are the same height by now, this must uphold.
left = left->ParentActual();
right = right->ParentActual();
}
return left;
}
OP_STATUS
HE_AncestorToDescendantIterator::Init(HTML_Element *ancestor, HTML_Element *descendant, BOOL skip_ancestor)
{
OP_ASSERT(descendant);
OP_ASSERT(!ancestor || (ancestor && ancestor->IsAncestorOf(descendant)));
m_path.Clear();
for (; descendant; descendant = descendant->ParentActual())
{
if (skip_ancestor && ancestor == descendant)
break;
RETURN_IF_ERROR(m_path.Add(descendant));
if (ancestor == descendant)
break;
};
return OpStatus::OK;
}
HTML_Element *
HE_AncestorToDescendantIterator::GetNextActual()
{
HTML_Element *current = NULL;
if (m_path.GetCount() > 0)
{
current = m_path.Get(m_path.GetCount()-1);
m_path.Remove(m_path.GetCount()-1);
}
return current;
}
#ifdef DRAG_SUPPORT
static BOOL IsInteractiveHtmlElement(HTML_Element* elem, FramesDocument* doc)
{
return elem->IsMatchingType(Markup::HTE_INPUT, NS_HTML) || elem->IsMatchingType(Markup::HTE_SELECT, NS_HTML) ||
elem->IsMatchingType(Markup::HTE_TEXTAREA, NS_HTML) || elem->IsMatchingType(Markup::HTE_OPTION, NS_HTML) ||
elem->IsMatchingType(Markup::HTE_ISINDEX, NS_HTML) || elem->IsMatchingType(Markup::HTE_BUTTON, NS_HTML)
#ifdef DOCUMENT_EDIT_SUPPORT
|| (doc && elem->IsContentEditable(TRUE) && (!doc->GetDocumentEdit()->m_layout_modifier.IsActive()
|| doc->GetDocumentEdit()->m_layout_modifier.m_helm != elem))
#endif // DOCUMENT_EDIT_SUPPORT
;
}
BOOL HTML_Element::IsDraggable(FramesDocument* doc)
{
return GetDraggable(doc) != NULL;
}
HTML_Element* HTML_Element::GetDraggable(FramesDocument* doc)
{
if (IsInteractiveHtmlElement(this, doc))
return NULL;
HTML_Element* elm = this;
do
{
if (elm->GetNsType() == NS_HTML)
{
const uni_char* drag_attr = elm->GetStringAttr(Markup::HA_DRAGGABLE);
if (drag_attr)
{
if (uni_stri_eq(drag_attr, "true"))
return elm;
else if (uni_stri_eq(drag_attr, "false"))
return NULL;
}
if (elm->Type() == HE_IMG)
return elm;
}
#ifdef SVG_SUPPORT
else if (elm->GetNsType() == NS_SVG)
{
if (doc && g_svg_manager->IsEditableElement(doc, elm))
return NULL;
const uni_char* drag_attr = elm->GetStringAttr(Markup::SVGA_DRAGGABLE, NS_IDX_SVG);
if (drag_attr)
{
if (uni_stri_eq(drag_attr, "true"))
return elm;
else if (uni_stri_eq(drag_attr, "false"))
return NULL;
}
}
#endif // SVG_SUPPORT
// We need FramesDocument to be sure the element is draggable by default but if we don't have one
// return TRUE for HTML <a href="url"> at least.
if ((doc && elm->IsAnchorElement(doc)) ||
(elm->IsMatchingType(Markup::HTE_A, NS_HTML) && elm->HasAttr(Markup::HA_HREF)))
return elm;
elm = elm->ParentActual();
}
while (elm);
return NULL;
}
const uni_char* HTML_Element::GetDropzone()
{
DropzoneAttribute* dropzone_attr = NULL;
if (GetNsType() == NS_HTML)
dropzone_attr = static_cast<DropzoneAttribute*>(GetAttr(Markup::HA_DROPZONE, ITEM_TYPE_COMPLEX, NULL));
#ifdef SVG_SUPPORT
else if (GetNsType() == NS_SVG)
dropzone_attr = static_cast<DropzoneAttribute*>(GetAttr(Markup::SVGA_DROPZONE, ITEM_TYPE_COMPLEX, NULL, NS_IDX_SVG));
#endif // SVG_SUPPORT
if (!dropzone_attr)
return NULL;
return dropzone_attr->GetAttributeString();
}
#endif // DRAG_SUPPORT
|
#include "ScrollViewScene.h"
#include "ScrollView.h"
#include "TestLayer.h"
#include "parentMode.h"
ScrollViewScene::ScrollViewScene()
{
}
ScrollViewScene::~ScrollViewScene()
{
}
bool ScrollViewScene::init()
{
auto visibleSize = Director::getInstance()->getVisibleSize();
//ScrollView::setWindow(480, 320);
bool bRet = false;
do {
CC_BREAK_IF(!CCScene::init());
ScrollView *scrollView = ScrollView::create();
Schedule();
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
for (int i = 0; i<10; ++i) {
auto *layer = TestLayer::create();
layer->addimage(i);
layer->setAnchorPoint(Vec2::ZERO);
layer->setTag(i);
scrollView->addPage(layer);
}
this->addChild(scrollView, 1);
ScrollView::setWindow(winSize.width * 0.25f, winSize.height * 0.5f, visibleSize.height / 2);
scrollView->setPosition(Vec2(0, visibleSize.height / 2));
//scrollView->setPosition(Vec2(0, visibleSize.height - ScrollView::WINDOW_HEIGHT));
//ScrollView::setWindow(480, 320, visibleSize.height / 2);
//scrollView->setPosition(Vec2(0, visibleSize.height / 2));
//
//ScrollView::WINDOW_HEIGHT / 2
auto bg = Sprite::create("res/bg.png");
float odds;
float oddsY;
oddsY = bg->getContentSize().height / visibleSize.height;
odds = bg->getContentSize().width / visibleSize.width;
bg->setScaleY(1 / oddsY);
bg->setScaleX(1 / odds);
this->addChild(bg, 0);
bg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
bRet = true;
} while (0);
/*auto back = MenuItemImage::create("timeset/back.png", "timeset/back.png", CC_CALLBACK_1(ScrollViewScene::returnto, this));
auto back_menu = Menu::create(back, NULL);
back_menu->setPosition(Vec2(back->getContentSize().width, visibleSize.height - back->getContentSize().height));
this->addChild(back_menu, 3);*/
return bRet;
}
void ScrollViewScene::returnto(Ref* ref)
{
this->stopAllActions();
auto scene = parentMode::createScene();
CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY));
}
void ScrollViewScene::girlwalk() {}
void ScrollViewScene::updateTime1(float dt){
totalTime1 += dt;
}
void ScrollViewScene::Schedule() {
schedule(schedule_selector(ScrollViewScene::updateTime1), 0.1f);
}
|
/**
* Copyright (c) 2021, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file injector.hh
*/
#ifndef lnav_injector_hh
#define lnav_injector_hh
#include <map>
#include <memory>
#include <type_traits>
#include <vector>
#include <assert.h>
#include "base/lnav_log.hh"
namespace injector {
enum class scope {
undefined,
none,
singleton,
};
template<typename Annotation>
void force_linking(Annotation anno);
template<class...>
using void_t = void;
template<typename T, typename... Annotations>
struct with_annotations {
T value;
};
template<class, class = void>
struct has_injectable : std::false_type {};
template<class T>
struct has_injectable<T, void_t<typename T::injectable>> : std::true_type {};
template<typename T, typename... Annotations>
struct singleton_storage {
static scope get_scope() { return ss_scope; }
static T* get()
{
static int _[] = {0, (force_linking(Annotations{}), 0)...};
(void) _;
return ss_data;
}
static std::shared_ptr<T> get_owner()
{
static int _[] = {0, (force_linking(Annotations{}), 0)...};
(void) _;
return ss_owner;
}
static std::shared_ptr<T> create()
{
static int _[] = {0, (force_linking(Annotations{}), 0)...};
(void) _;
return ss_factory();
}
protected:
static scope ss_scope;
static T* ss_data;
static std::shared_ptr<T> ss_owner;
static std::function<std::shared_ptr<T>()> ss_factory;
};
template<typename T, typename... Annotations>
T* singleton_storage<T, Annotations...>::ss_data = nullptr;
template<typename T, typename... Annotations>
scope singleton_storage<T, Annotations...>::ss_scope = scope::undefined;
template<typename T, typename... Annotations>
std::shared_ptr<T> singleton_storage<T, Annotations...>::ss_owner;
template<typename T, typename... Annotations>
std::function<std::shared_ptr<T>()>
singleton_storage<T, Annotations...>::ss_factory;
template<typename T>
struct Impl {
using type = T;
};
template<typename T>
struct multiple_storage {
static std::vector<std::shared_ptr<T>> create()
{
std::vector<std::shared_ptr<T>> retval;
for (const auto& pair : get_factories()) {
retval.template emplace_back(pair.second());
}
return retval;
}
protected:
using factory_map_t
= std::map<std::string, std::function<std::shared_ptr<T>()>>;
static factory_map_t& get_factories()
{
static factory_map_t retval;
return retval;
}
};
template<typename T,
typename... Annotations,
std::enable_if_t<std::is_reference<T>::value, bool> = true>
T
get()
{
using plain_t = std::remove_const_t<std::remove_reference_t<T>>;
return *singleton_storage<plain_t, Annotations...>::get();
}
template<typename T,
typename... Annotations,
std::enable_if_t<std::is_pointer<T>::value, bool> = true>
T
get()
{
using plain_t = std::remove_const_t<std::remove_pointer_t<T>>;
return singleton_storage<plain_t, Annotations...>::get();
}
template<class T>
struct is_shared_ptr : std::false_type {};
template<class T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template<class T>
struct is_vector : std::false_type {};
template<class T>
struct is_vector<std::vector<T>> : std::true_type {};
template<typename I, typename R, typename... IArgs, typename... Args>
std::function<std::shared_ptr<I>()> create_from_injectable(R (*)(IArgs...),
Args&... args);
template<typename T,
typename... Args,
std::enable_if_t<has_injectable<typename T::element_type>::value, bool>
= true,
std::enable_if_t<is_shared_ptr<T>::value, bool> = true>
T
get(Args&... args)
{
typename T::element_type::injectable* i = nullptr;
if (singleton_storage<typename T::element_type>::get_scope()
== scope::singleton)
{
return singleton_storage<typename T::element_type>::get_owner();
}
return create_from_injectable<typename T::element_type>(i, args...)();
}
template<
typename T,
typename... Annotations,
std::enable_if_t<!has_injectable<typename T::element_type>::value, bool>
= true,
std::enable_if_t<is_shared_ptr<T>::value, bool> = true>
T
get()
{
return singleton_storage<typename T::element_type,
Annotations...>::get_owner();
}
template<typename T, std::enable_if_t<is_vector<T>::value, bool> = true>
T
get()
{
return multiple_storage<typename T::value_type::element_type>::create();
}
template<typename I, typename R, typename... IArgs, typename... Args>
std::function<std::shared_ptr<I>()>
create_from_injectable(R (*)(IArgs...), Args&... args)
{
return [&]() {
return std::make_shared<I>(args..., ::injector::get<IArgs>()...);
};
}
} // namespace injector
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch_system_includes.h"
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
#include "modules/pi/OpSystemInfo.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/regexp/include/regexp_api.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/opstring.h"
#include "platforms/vega_backends/vega_blocklist_file.h"
void DeleteBlocklistEntryPair(const void* key, void* val)
{
OP_DELETEA((uni_char*)key);
OP_DELETEA((uni_char*)val);
}
// static
VEGABlocklistRegexEntry::Comparison VEGABlocklistRegexEntry::GetComp(const uni_char* comp)
{
if (!uni_strcmp(comp, UNI_L("==")))
return EqualTo;
if (!uni_strcmp(comp, UNI_L("!=")))
return NotEqualTo;
if (!uni_strcmp(comp, UNI_L(">")))
return GreaterThan;
if (!uni_strcmp(comp, UNI_L(">=")))
return GreaterThanOrEqual;
if (!uni_strcmp(comp, UNI_L("<")))
return LessThan;
if (!uni_strcmp(comp, UNI_L("<=")))
return LessThanOrEqual;
OP_ASSERT(!"unexpected comparison string");
return CompCount;
}
// determines whether l1 is less than (<0), equal to (0) or greater than (>0) l2
static inline
INT32 compare_versions(const OpINT32Vector& l1, const OpINT32Vector& l2)
{
const UINT32 n1 = l1.GetCount(), n2 = l2.GetCount();
for (UINT32 i = 0; i < n1 && i < n2; ++i)
{
const INT32 v1 = l1.Get(i), v2 = l2.Get(i);
if (v1 != v2)
return v1 - v2;
}
return n1 - n2;
}
BOOL VEGABlocklistRegexEntry::RegexComp::Matches(const OpINT32Vector& values)
{
// let empty comparison match all - eases implemetation
if (!m_values.GetCount())
return TRUE;
const INT32 vercomp = compare_versions(values, m_values);
switch (m_comp)
{
case EqualTo: return vercomp == 0; break;
case NotEqualTo: return vercomp != 0; break;
case GreaterThan: return vercomp > 0; break;
case GreaterThanOrEqual: return vercomp >= 0; break;
case LessThan: return vercomp < 0; break;
case LessThanOrEqual: return vercomp <= 0; break;
}
OP_ASSERT(!"unexpected comparison");
return FALSE;
}
OP_BOOLEAN VEGABlocklistRegexEntry::Matches(const uni_char* str)
{
// compile regex
OpREFlags flags;
flags.multi_line = FALSE;
flags.case_insensitive = TRUE;
flags.ignore_whitespace = FALSE;
OpRegExp* exp;
RETURN_IF_ERROR(OpRegExp::CreateRegExp(&exp, m_exp, &flags));
OpAutoPtr<OpRegExp> _exp(exp);
// match regex
OpREMatchLoc* matchlocs;
int nmatches;
RETURN_IF_ERROR(exp->Match(str, &nmatches, &matchlocs));
OpAutoArray<OpREMatchLoc> _matchlocs(matchlocs);
if (nmatches <= 0 ||
matchlocs[0].matchloc || (size_t)matchlocs[0].matchlen != uni_strlen(str)) // must match entire string!
return OpBoolean::IS_FALSE;
if (nmatches > 1) // there were subexpressions
{
// collect values
OpINT32Vector vals;
for (int i = 1; i < nmatches; ++i)
{
if (matchlocs[i].matchloc != REGEXP_NO_MATCH && matchlocs[i].matchlen != REGEXP_NO_MATCH)
{
// copy match, so we don't trickle past end
OpString8 s;
RETURN_IF_ERROR(s.Set(str + matchlocs[i].matchloc, matchlocs[i].matchlen));
INT32 val = (INT32)op_atoi(s);
RETURN_IF_ERROR(vals.Add((INT32)val));
}
}
// compare values
for (int i = 0; i < 2; ++i)
if (!m_comp[i].Matches(vals))
return OpBoolean::IS_FALSE;
}
return OpBoolean::IS_TRUE;
}
OP_BOOLEAN VEGABlocklistRegexCollection::Matches(VEGABlocklistDevice::DataProvider* provider)
{
OP_ASSERT(provider);
OpHashIterator* it = regex_entries.GetIterator();
if (!it)
return OpStatus::ERR_NO_MEMORY;
OpAutoPtr<OpHashIterator> _it(it);
OP_STATUS status;
for (status = it->First(); OpStatus::IsSuccess(status); status = it->Next())
{
const uni_char* key = (const uni_char*)it->GetKey();
VEGABlocklistRegexEntry* exp = (VEGABlocklistRegexEntry*)it->GetData();
OP_ASSERT(key);
OP_ASSERT(exp);
OpString valstr;
RETURN_IF_ERROR(provider->GetValueForKey(key, valstr));
if (!valstr.CStr())
return OpBoolean::IS_FALSE;
const OP_BOOLEAN res = exp->Matches(valstr.CStr());
if (res == OpBoolean::IS_FALSE || OpStatus::IsError(res))
return res;
}
if (OpStatus::IsMemoryError(status))
return OpStatus::ERR_NO_MEMORY;
return OpBoolean::IS_TRUE;
}
// static
const uni_char* VEGABlocklistFile::GetName(VEGABlocklistDevice::BlocklistType type)
{
switch (type)
{
case VEGABlocklistDevice::D3d10:
return UNI_L("windows-direct3d-10.blocklist.json");
break;
case VEGABlocklistDevice::UnixGL:
return UNI_L("unix-opengl.blocklist.json");
break;
case VEGABlocklistDevice::WinGL:
return UNI_L("windows-opengl.blocklist.json");
break;
case VEGABlocklistDevice::MacGL:
return UNI_L("mac-opengl.blocklist.json");
break;
#ifdef SELFTEST
case VEGABlocklistDevice::SelftestBlocklistFile:
return UNI_L("selftest-blocklist.json");
break;
#endif // SELFTEST
}
return 0;
}
#ifdef VEGA_BACKENDS_BLOCKLIST_FETCH
// static
OP_STATUS VEGABlocklistFile::GetURL(VEGABlocklistDevice::BlocklistType type, OpString& s)
{
#ifdef SELFTEST
if (type == VEGABlocklistDevice::SelftestBlocklistFile)
return s.Set(g_vega_backends_module.m_selftest_blocklist_url);
#endif // SELFTEST
const uni_char* name = GetName(type);
if (!name)
return OpStatus::ERR;
// HACK: apparently it's not possible to fetch .json files
const size_t namelen = uni_strlen(name);
OP_ASSERT(namelen > 5 && !uni_strcmp(name + namelen - 5, UNI_L(".json")));
RETURN_IF_ERROR(s.Set(g_pccore->GetStringPref(PrefsCollectionCore::BlocklistLocation)));
RETURN_IF_ERROR(s.Append(name, namelen - 5));
return s.Append(UNI_L(".txt"));
}
// static
void VEGABlocklistFile::Fetch(VEGABlocklistDevice::BlocklistType type, unsigned long delay)
{
g_vega_backends_module.FetchBlocklist(type, delay);
}
// static
void VEGABlocklistFile::FetchWhenExpired(VEGABlocklistDevice::BlocklistType type, time_t mod)
{
const time_t expiry_seconds = g_pccore->GetIntegerPref(PrefsCollectionCore::BlocklistRefetchDelay);
time_t seconds_left = expiry_seconds;
time_t now = (time_t)(g_op_time_info->GetTimeUTC() / 1000);
if (now < mod + expiry_seconds)
seconds_left = mod + expiry_seconds - now;
Fetch(type, (unsigned long)seconds_left * 1000/*ms*/);
}
void VEGABlocklistFile::FetchLater(VEGABlocklistDevice::BlocklistType type)
{
// something went wrong - re-fetch later
const unsigned int retry_seconds = g_pccore->GetIntegerPref(PrefsCollectionCore::BlocklistRetryDelay);
Fetch(type, retry_seconds * 1000/*ms*/);
}
// static
OP_STATUS VEGABlocklistFile::OnBlocklistFetched(URL url, VEGABlocklistDevice::BlocklistType type)
{
unsigned long res = url.PrepareForViewing(TRUE);
if (res)
return res == MSG_OOM_CLEANUP ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR;
OpString path;
RETURN_IF_ERROR(url.GetAttribute(URL::KFilePathName, path, TRUE));
OpFile file;
RETURN_IF_ERROR(file.Construct(path));
time_t fetched_time;
OP_STATUS status = CheckFile(&file, &fetched_time);
if (OpStatus::IsSuccess(status))
{
// replace old blocklist with fetched
const uni_char* name = GetName(type);
OP_ASSERT(name);
OpFile out;
status = out.Construct(name, VEGA_BACKENDS_BLOCKLIST_FETCHED_FOLDER);
if (OpStatus::IsSuccess(status))
status = out.CopyContents(&file, FALSE);
}
else
{
// downloaded blocklist file corrupt
OP_ASSERT(!"corrupt blocklist file");
}
if (OpStatus::IsError(status))
{
FetchLater(type);
return status;
}
FetchWhenExpired(type, fetched_time);
// TODO: pass new blocklist status to VOP so it can recreate its
// 3dDevice if necessary. this is currently not possible, as it
// requires VOP to be able to recreate its backend.
return OpStatus::OK;
}
#endif // VEGA_BACKENDS_BLOCKLIST_FETCH
// static
OP_STATUS VEGABlocklistFile::CheckFile(OpFile* file
#ifdef VEGA_BACKENDS_BLOCKLIST_FETCH
, time_t* fetched_time/* = 0*/
#endif
)
{
RETURN_IF_ERROR(file->Open(OPFILE_READ));
VEGABlocklistFile bf;
OP_STATUS status = bf.Load(file);
file->Close();
#ifdef VEGA_BACKENDS_BLOCKLIST_FETCH
if (fetched_time)
*fetched_time = bf.GetFetched();
#endif
return status;
}
// static
OP_STATUS VEGABlocklistFile::OpenFile(VEGABlocklistDevice::BlocklistType type, OpFile* file, BOOL* from_resources)
{
OP_ASSERT(file);
const uni_char* name = GetName(type);
OP_ASSERT(name);
*from_resources = FALSE;
OP_STATUS status = file->Construct(name, VEGA_BACKENDS_BLOCKLIST_FETCHED_FOLDER);
if (OpStatus::IsSuccess(status))
{
status = file->Open(OPFILE_READ);
// if there is no blocklist file present in the home folder check
// resources folder, and trigger immediate refetch
if (OpStatus::IsError(status))
{
*from_resources = TRUE;
status = file->Construct(name, VEGA_BACKENDS_BLOCKLIST_SHIPPED_FOLDER);
if (OpStatus::IsSuccess(status))
status = file->Open(OPFILE_READ);
}
}
return status;
}
OP_STATUS VEGABlocklistFile::Load(VEGABlocklistDevice::BlocklistType type)
{
OP_ASSERT(GetName(type));
BOOL force_immediate_fetch;
OpFile file;
OP_STATUS status = OpenFile(type, &file, &force_immediate_fetch);
if (OpStatus::IsSuccess(status))
status = Load(&file);
#ifdef VEGA_BACKENDS_BLOCKLIST_FETCH
// trigger fetch as necessary
if (OpStatus::IsError(status) || force_immediate_fetch)
Fetch(type, 0);
else
FetchWhenExpired(type, GetFetched());
#endif // VEGA_BACKENDS_BLOCKLIST_FETCH
return status;
}
OP_STATUS VEGABlocklistFile::Load(OpFile* file)
{
OP_ASSERT(file && file->IsOpen());
#ifdef VEGA_BACKENDS_BLOCKLIST_FETCH
time_t mod;
// get last-modified, in UTC seconds
if (OpStatus::IsSuccess(file->GetLastModified(mod)))
m_blocklist_fetched = mod;
else
m_blocklist_fetched = 0;
#endif // VEGA_BACKENDS_BLOCKLIST_FETCH
VEGABlocklistFileLoader* file_loader;
OP_STATUS status = VEGABlocklistFileLoader::Create(file_loader, this);
if (OpStatus::IsSuccess(status))
{
status = file_loader->Load(file);
OP_DELETE(file_loader);
}
return status;
}
OP_STATUS VEGABlocklistFile::OnDriverEntryLoaded(VEGABlocklistDriverLinkEntry* driver_link)
{
return m_driver_links.Add(driver_link);
}
OP_STATUS VEGABlocklistFile::OnElementLoaded(VEGABlocklistFileEntry* entry)
{
const OP_STATUS status = m_entries.Add(entry);
if (OpStatus::IsError(status))
OP_DELETE(entry);
return status;
}
template <typename T>
OP_STATUS FindMatchingEntry(VEGABlocklistDevice::DataProvider* provider, const OpAutoVector<T>& entries, T*& entry)
{
OP_ASSERT(provider);
entry = 0;
UINT32 idx = 0;
for (T* e; (e = entries.Get(idx)) != NULL; ++idx)
{
const OP_BOOLEAN match = e->Matches(provider);
RETURN_IF_ERROR(match);
if (match == OpBoolean::IS_TRUE)
{
entry = e;
break;
}
}
return OpStatus::OK;
}
OP_STATUS VEGABlocklistFile::FindMatchingEntry(VEGABlocklistDevice::DataProvider* const data_provider, VEGABlocklistFileEntry*& entry) const
{
return ::FindMatchingEntry(data_provider, m_entries, entry);
}
OP_STATUS VEGABlocklistFile::FindMatchingDriverLink(VEGABlocklistDevice::DataProvider* const data_provider, VEGABlocklistDriverLinkEntry*& entry) const
{
return ::FindMatchingEntry(data_provider, m_driver_links, entry);
}
#endif // VEGA_BACKENDS_USE_BLOCKLIST
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "Ipv4Resolver.h"
#include <cassert>
#include <random>
#include <stdexcept>
#include <netdb.h>
#include <System/Dispatcher.h>
#include <System/ErrorMessage.h>
#include <System/InterruptedException.h>
#include <System/Ipv4Address.h>
namespace platform_system {
Ipv4Resolver::Ipv4Resolver() : dispatcher(nullptr) {
}
Ipv4Resolver::Ipv4Resolver(Dispatcher& dispatcher) : dispatcher(&dispatcher) {
}
Ipv4Resolver::Ipv4Resolver(Ipv4Resolver&& other) : dispatcher(other.dispatcher) {
if (dispatcher != nullptr) {
other.dispatcher = nullptr;
}
}
Ipv4Resolver::~Ipv4Resolver() {
}
Ipv4Resolver& Ipv4Resolver::operator=(Ipv4Resolver&& other) {
dispatcher = other.dispatcher;
if (dispatcher != nullptr) {
other.dispatcher = nullptr;
}
return *this;
}
Ipv4Address Ipv4Resolver::resolve(const std::string& host) {
assert(dispatcher != nullptr);
if (dispatcher->interrupted()) {
throw InterruptedException();
}
addrinfo hints = { 0, AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL };
addrinfo* addressInfos;
int result = getaddrinfo(host.c_str(), NULL, &hints, &addressInfos);
if (result != 0) {
throw std::runtime_error("Ipv4Resolver::resolve, getaddrinfo failed, " + errorMessage(result));
}
std::size_t count = 0;
for (addrinfo* addressInfo = addressInfos; addressInfo != nullptr; addressInfo = addressInfo->ai_next) {
++count;
}
std::mt19937 generator{ std::random_device()() };
std::size_t index = std::uniform_int_distribution<std::size_t>(0, count - 1)(generator);
addrinfo* addressInfo = addressInfos;
for (std::size_t i = 0; i < index; ++i) {
addressInfo = addressInfo->ai_next;
}
Ipv4Address address(ntohl(reinterpret_cast<sockaddr_in*>(addressInfo->ai_addr)->sin_addr.s_addr));
freeaddrinfo(addressInfo);
return address;
}
}
|
#include<bits/stdc++.h>
using namespace std;
double calc(double x) {
return x*1.8+32.0;
}
int main(){
double n;
printf("input degree Celsius!!\n");
scanf("%lf",&n);
printf("degree Fahrenheit is %lf!!\n",calc(n));
return 0;
}
|
#include <iostream>
struct debug_info {};
class satellite {
public:
virtual debug_info get_debug() {
std::cout << "satellite::get_debug() called" << std::endl;
return debug_info{};
}
};
class displayed {
public:
virtual debug_info get_debug() {
std::cout << "dispalyed::get_debug() called" << std::endl;
return debug_info{};
}
};
class comm_sat : public satellite, public displayed {};
class comm_sat1 : public satellite, public displayed {
public:
debug_info get_debug() {
// override get_debug from satellite/displayed
auto di1 = satellite::get_debug();
auto di2 = displayed::get_debug();
return debug_info {};
}
};
void f(comm_sat &cs) {
// auto di = cs.get_debug(); // error: member 'get_debug' found in multiple base classes of
debug_info di{};
di = cs.satellite::get_debug();
di = cs.displayed::get_debug();
}
class window {
public:
void draw() {}
};
class cowboy {
public:
void draw() {}
};
class wwindow : public window {
public:
using window::window; // inherit ctors
virtual void win_draw() = 0;
void draw() override final { win_draw(); }
};
class ccowboy : public cowboy {
public:
using cowboy::cowboy; // inherti ctors
virtual void cow_draw() = 0;
void draw() override final { cow_draw(); }
};
class cowboy_window : public ccowboy, public wwindow {
public:
void cow_draw() override {}
void win_draw() override {}
};
int main() {
return 0;
}
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
struct Node {
int data;
Node* left;
Node* right;
};
// utility fxn
Node* newNode(int n) {
Node* temp = new Node;
temp->data = n;
temp->left = temp->right = NULL;
return(temp);
}
// T.C - O(N)
void level(Node* root) {
queue <Node*> q;
q.push(root);
vector<vector<int>> ans;
while(!q.empty()) {
vector<int> sub;
int n = q.size();
for(int i=0; i<n; i++) {
Node* cur = q.front();
sub.push_back(cur->data);
// cout << cur->data << " ";
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
q.pop();
}
ans.push_back(sub);
}
for(auto x: ans) {
for(auto y: x) {
cout << y << " ";
}
cout << endl;
}
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
Node* root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(60);
level(root);
return 0;
}
|
#pragma once
class CD3DFont;
namespace ui
{
class Pos
{
public:
Pos();
~Pos();
void render();
void reset();
public:
int xpos;
int ypos;
int draw;
private:
CD3DFont* d3dfont;
};
};
|
#include "Common.h"
#include "IndexBuffer.h"
#include "VertexBuffer.h"
#include "VertexArray.h"
#include "Shader.h"
#include "Renderer.h"
#include "Texture.h"
#include "Timeline.h"
#include "Solver.cuh"
extern Solver solver;
#include "imgui/imgui.h"
#include "imgui/backends/imgui_impl_opengl3.h"
#include "imgui/backends/imgui_impl_glfw.h"
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <filesystem>
#include <experimental/filesystem>
#include <thread>
#include <imgui/imgui_internal.h>
//#include <imgui_tables.cpp>
#include <imgui/misc/cpp/imgui_stdlib.h>
#include <imgui/misc/single_file/imgui_single_file.h>
void AddObject2(int,int,int ps = 0);
//#define WINDOWS7_BUILD
static void cursorPositionCallback(GLFWwindow* window, double xPos, double yPos);
void cursorEnterCallback(GLFWwindow *window, int entered);
void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
void scrollCallback(GLFWwindow* window, double xOffset, double yOffset);
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
const char* itemse[] = { "emitter", "explosion" , "force", "power", "turbulance", "wind", "sphere", "particle", "object" };
bool TimelineInitialized = false;
bool AddParticleSystem = false;
bool AddObjectSystem = false;
char temp_object_path[512] = { "./input/obj/suzanne/" };
char temp_particle_path[512] = { "./input/exp2/" };
static int selectedEntry = -1;
MySequence Timeline;
//////////////////FUNCTIONS
int sinresolution = 8;
float sinmid = 20;
float sinspeed = 0.1;
float sinsize = 8;
float sinoffset = 0.0;
#define CURVE_SIZE 0
#define CURVE_X 1
#define CURVE_Y 2
#define CURVE_Z 3
void UpdateTimelinePartially() {
for (int i = 0; i < Timeline.myItems.size(); i++) {
Timeline.myItems[i].mFrameStart = &solver.object_list[i].frame_range_min;
Timeline.myItems[i].mFrameEnd = &solver.object_list[i].frame_range_max;
}
}
void ClearTimeline(int minn = 0) {
for (int object = solver.object_list.size()-1; object >= minn; object++) { //>=
//int t = solver.object_list[object].type;
solver.object_list[object].free();
solver.object_list[object].collisions.clear();
solver.object_list.erase(solver.object_list.begin() + object);
//Timeline.Del(object);
Timeline.myItems.erase(Timeline.myItems.begin() + object);
Timeline.rampEdit.erase(Timeline.rampEdit.begin() + object);
}
selectedEntry = -1;
}
void UpdateTimeline() {
Timeline.myItems.clear();
for (int i = 0; i < Timeline.rampEdit.size(); i++)
for (int j = 0; j < Timeline.rampEdit[i].mMax.size(); j++) {
Timeline.rampEdit[i].RemovePoints(j);
}
Timeline.focused = false;
Timeline.rampEdit.clear();
//dodawanie elementow
for (int j = 0; j < solver.object_list.size(); j++) {
int current_item_id = 0;
for (int i = 0; i < EmitterCount; i++)
if (solver.object_list[j].get_type2() == itemse[i]) {
current_item_id = i;
break;
}
if (solver.object_list[j].get_type2() == "particle")
AddObject2(solver.object_list[j].type, j, 1);
else if (solver.object_list[j].type == VDBOBJECT)
AddObject2(solver.object_list[j].type, j, 3);
else
AddObject2(solver.object_list[j].type, j);
}
}
void UpdateAnimation() {
int frame = solver.frame;
//#pragma omp parallel for num_threads(4)
for (int j = 0; j < solver.object_list.size(); j++) {
if (solver.object_list[j].get_type2() == "explosion" && frame >= solver.object_list[j].frame_range_min &&
frame <= solver.object_list[j].frame_range_max) {
solver.object_list[j].set_size(Timeline.rampEdit[j].GetPointYAtTime(0,frame));
float x = Timeline.rampEdit[j].GetPointYAtTime(CURVE_X, frame);
float y = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Y, frame);
float z = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Z, frame);
solver.object_list[j].set_location(make_float3(x,y,z));
}
//if (solver.object_list[j].get_type2() == "emitter") {
else if (solver.object_list[j].type != PARTICLE && solver.object_list[j].type != VDBOBJECT){
solver.object_list[j].set_size(Timeline.rampEdit[j].GetPointYAtTime(0, frame));
float x = Timeline.rampEdit[j].GetPointYAtTime(CURVE_X, frame);
float y = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Y, frame);
float z = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Z, frame);
solver.object_list[j].set_location(make_float3(x, y, z));
}
else if (solver.object_list[j].type == PARTICLE){
solver.object_list[j].set_size(Timeline.rampEdit[j].GetPointYAtTime(0, frame));
float x = Timeline.rampEdit[j].GetPointYAtTime(CURVE_X, frame);
float y = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Y, frame);
float z = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Z, frame);
solver.object_list[j].set_location(make_float3(x, y, z));
}
else if (solver.object_list[j].type == VDBOBJECT) {
/*
float sizeee = solver.object_list[j].size;
solver.object_list[j].set_size(Timeline.rampEdit[j).GetPointYAtTime(0, frame));
if (solver.object_list[j].size != sizeee) {
int frame_start = solver.object_list[j].frame_range_min;
int frame_end = solver.object_list[j].frame_range_max;
solver.object_list[j].collisions.clear();
int SIZEEEE = min(min(solver.getDomainResolution().x, solver.getDomainResolution().y), solver.getDomainResolution().z);
solver.object_list[j].LoadObjects(solver.getDomainResolution(),
solver.devicesCount, solver.deviceIndex, SIZEEEE * solver.object_list[j].size);
solver.object_list[j].frame_range_min = frame_start;
solver.object_list[j].frame_range_max = frame_end;
}
*/
float x = Timeline.rampEdit[j].GetPointYAtTime(CURVE_X, frame);
float y = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Y, frame);
float z = Timeline.rampEdit[j].GetPointYAtTime(CURVE_Z, frame);
solver.object_list[j].set_location(make_float3(x, y, z));
}
}
}
void AddObject2(int type, int j, int particle_system) {
type = max(0, type)%EmitterCount;
int current_item_id = 0;
for (int i = 0; i < EmitterCount; i++)
if (solver.object_list[j].get_type2() == itemse[i]) {
current_item_id = i;
break;
}
Timeline.myItems.push_back(MySequence::MySequenceItem{ current_item_id, &solver.object_list[j].frame_range_min,
&solver.object_list[j].frame_range_max, false });
if (type == EXPLOSION || type == PARTICLE) {
Timeline.rampEdit.push_back(RampEdit(solver.object_list[j].frame_range_min, solver.object_list[j].frame_range_max,
(float)solver.getDomainResolution().x / 2.f, 5.f, (float)solver.getDomainResolution().z / 2.f, particle_system));
}
else if (type == VDBOBJECT) {
Timeline.rampEdit.push_back(RampEdit(solver.object_list[j].frame_range_min, solver.object_list[j].frame_range_max,
0, 5.f, 0, particle_system));
}
else {
Timeline.rampEdit.push_back(RampEdit(solver.object_list[j].frame_range_min, solver.object_list[j].frame_range_max,
(float)solver.getDomainResolution().x / 2.f, 5.f, (float)solver.getDomainResolution().z / 2.f, 2));
}
}
void AddObject(int type) {
//std::cout << "Adding object of index " << type << std::endl;
type = max(0,type) % EmitterCount;
std::string name = itemse[type];
if (name == "particle") {
}
else {
solver.object_list.push_back(OBJECT(name, 18.0f, 50, 5.2, 5, 0.9, make_float3(float(solver.getDomainResolution().x) * 0.5f, 5.0f, float(solver.getDomainResolution().z) * 0.5f), solver.object_list.size(), solver.devicesCount));
int j = solver.object_list.size() - 1;
AddObject2(solver.object_list[j].type, j);
}
}
void DuplicateObject(int index) {
OBJECT obj = OBJECT(solver.object_list[index], solver.object_list.size(),solver.devicesCount);
std::string name = obj.get_type2();
obj.set_name(name + std::to_string(index+1));
solver.object_list.push_back(OBJECT(obj, solver.object_list.size(), solver.devicesCount));
int j = solver.object_list.size() - 1;
if (solver.object_list[j].type == VDBOBJECT) {
solver.object_list[j].load_density_grid(solver.object_list[index].get_density_grid(),
solver.object_list[index].get_initial_temp(), solver.deviceIndex);
}
//solver.object_list[j).vdb_object = obj.vdb_object;
int current_item_id = 0;
#pragma unroll
for (int i = 0; i < EmitterCount; i++)
if (solver.object_list[j].get_type2() == itemse[i]) {
current_item_id = i;
break;
}
Timeline.myItems.push_back(MySequence::MySequenceItem{ current_item_id, &solver.object_list[j].frame_range_min,
&solver.object_list[j].frame_range_max, false });
//Timeline.rampEdit.push_back(RampEdit(solver.object_list[j].frame_range_min, solver.object_list[j].frame_range_max));
RampEdit ramp = RampEdit();
ramp.Copy(Timeline.rampEdit[index]);
Timeline.rampEdit.push_back(&ramp); //tu problem?
UpdateTimeline();
}
void DeleteObject(const int object) {
/*
if (solver.object_list[object].get_type() == "object" ||
solver.object_list[object].get_type() == "vdbs")
solver.object_list[object].cudaFree();
*/
solver.object_list[object].free();
solver.object_list[object].collisions.clear();
solver.object_list.erase(solver.object_list.begin() + object);
//Timeline.Del(object);
Timeline.myItems.erase(Timeline.myItems.begin() + object);
Timeline.rampEdit.erase(Timeline.rampEdit.begin() + object);
UpdateTimeline();
//std::cout << "Lists: " << solver.object_list.size() << ":" << Timeline.myItems.size() << ":" << Timeline.rampEdit.size() << std::endl;
}
std::vector<std::thread> threads;
void UpdateSolver(bool full = false, std::string filename = "") {
solver.LOCK = true;
solver.writing = true;
solver.THIS_IS_THE_END = true;
for (auto& thread : threads)
thread.join();
std::cout << "\nRestarting\n";
solver.ThreadsJoin();
//clearing
//solver.ClearCache();
solver.frame = 0;
solver.THIS_IS_THE_END = false;
//solver.SIMULATE = true;
if ((solver.New_DOMAIN_RESOLUTION.x == solver.getDomainResolution().x) &&
(solver.New_DOMAIN_RESOLUTION.y == solver.getDomainResolution().y) &&
(solver.New_DOMAIN_RESOLUTION.z == solver.getDomainResolution().z) &&
!full && solver.preserve_object_list ) {
solver.Clear_Simulation_Data2();
solver.ResetObjects1(); //loc rot scale
UpdateTimelinePartially();
}
else if (full) {
//ClearTimeline(1);
solver.Clear_Simulation_Data();
solver.LoadSceneFromFile(filename);
//solver.Initialize_Simulation();
UpdateTimelinePartially();
}
else {// if (solver.preserve_object_list) {
solver.Clear_Simulation_Data();
solver.UpdateDomainResolution();
solver.ResetObjects();
solver.Initialize_Simulation();
UpdateTimelinePartially();
}
/*
else {
solver.preserve_object_list = true;
ClearTimeline(1);
solver.Clear_Simulation_Data();
solver.UpdateDomainResolution();
solver.Initialize_Simulation();
UpdateTimeline();
UpdateAnimation();
ClearTimeline(0);
UpdateTimeline();
solver.LOCK = false;
solver.writing = false;
threads.clear();
return;
}
*/
if (!full) {
if (solver.SAMPLE_SCENE == 0)
solver.ExampleScene();
else if (solver.SAMPLE_SCENE == 1 || solver.SAMPLE_SCENE == 2)
solver.ExportVDBScene();
}
//preparation
//solver.Initialize();
//solver.UpdateTimeStep();
//
//solver.Initialize_Simulation(); //tutaj
solver.LOCK = false;
solver.writing = false;
threads.clear();
}
static const ImGuiDataTypeInfo GDataTypeInfo[] =
{
{ sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8
{ sizeof(unsigned char), "U8", "%u", "%u" },
{ sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16
{ sizeof(unsigned short), "U16", "%u", "%u" },
{ sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32
{ sizeof(unsigned int), "U32", "%u", "%u" },
#ifdef _MSC_VER
{ sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64
{ sizeof(ImU64), "U64", "%I64u","%I64u" },
#else
{ sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64
{ sizeof(ImU64), "U64", "%llu", "%llu" },
#endif
{ sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
{ sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
};
bool SliderPos(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format = "%.3f", float power = 1)
{
using namespace ImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
v_min = (void*)((char*)v_min + type_size);
v_max = (void*)((char*)v_max + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
float InterfaceScale = 1.0f;
float ImageScale = 1.0f;
int begin_frame = 0;
void RenderGUI(bool& SAVE_FILE_TAB, bool& OPEN_FILE_TAB, float& fps,
float& progress, bool& save_panel, bool& helper_window, bool& confirm_button, int2 Image) {
Timeline.mFrameMin = solver.START_FRAME;
Timeline.mFrameMax = solver.END_FRAME;
if (helper_window) {
ImGui::Begin("Helper Panel");
{
ImGui::SetWindowFontScale(InterfaceScale);
ImGui::Text("Useful shortcuts:");
ImGui::Text("W/A/S/D - Camera movement");
ImGui::Text("Q/Z - Camera up/down");
ImGui::Text("Left mouse + A/D - Camera rotation");
ImGui::Text("R - reset simulation");
ImGui::Text("F - stop exporting");
ImGui::Text("LM double click on curve - new point");
ImGui::Text("LCtrl+Scroll on animation panel\n - zoom in/out");
ImGui::Text("Space - pause simulation");
ImGui::Text("LCtrl+LM on slider - writing mode");
ImGui::SliderFloat("Interface scale", &InterfaceScale, 0.9, 2.0f);
if (ImGui::Button("Close")) {
helper_window = false;
}
}
ImGui::End();
}
if (SAVE_FILE_TAB) {
ImGui::Begin("Save Panel");
{
ImGui::SetWindowFontScale(InterfaceScale);
ImGui::Text("Enter filename");
ImGui::InputText("Filename", solver.SAVE_FOLDER, IM_ARRAYSIZE(solver.SAVE_FOLDER));
if (ImGui::Button("Save")) {
std::string filename = solver.SAVE_FOLDER;
filename = trim(filename);
solver.SaveSceneToFile(filename);
SAVE_FILE_TAB = false;
}
if (ImGui::Button("Close")) {
SAVE_FILE_TAB = false;
}
ImGui::Text("Saved projects:");
ImGui::BeginChild("Scrolling");
std::string directory = "scenes\\";
std::vector <std::string> list = solver.getFilesList(directory);
for (int object = 0; object < list.size(); object++) {
std::string name = (" -> " + list[object]);
ImGui::Text(name.c_str());
}
ImGui::EndChild();
}
ImGui::End();
}
if (OPEN_FILE_TAB) {
ImGui::Begin("Open Panel");
{
ImGui::SetWindowFontScale(InterfaceScale);
ImGui::Text("Enter filename");
//ImGui::InputText("Filename", solver.OPEN_FOLDER, IM_ARRAYSIZE(solver.OPEN_FOLDER));
if (ImGui::Button("Open")) {
//solver.ThreadsJoin();
std::string filename = solver.OPEN_FOLDER;
filename = trim(filename);
//////////////////////////////
bool temporary = solver.preserve_object_list;
solver.preserve_object_list = false;
UpdateSolver(true);
solver.preserve_object_list = temporary;
//////////////////////////////
//solver.LoadSceneFromFile(filename);
//UpdateTimeline();
OPEN_FILE_TAB = false;
}
if (ImGui::Button("Close")) {
OPEN_FILE_TAB = false;
}
///////////////////////////////////////
ImGui::Text("Saved projects:");
ImGui::BeginChild("Scrolling");
std::string directory = "scenes\\";
std::vector <std::string> list = solver.getFilesList(directory);
for (int object = 0; object < list.size(); object++) {
std::string name = (" -> " + list[object]);
//ImGui::Text(name.c_str());
if (ImGui::Button(name.c_str())) {
solver.ThreadsJoin();
std::string filename = list[object];
filename = trim(filename);
solver.preserve_object_list = false;
UpdateSolver(true,filename);
UpdateTimeline();
solver.preserve_object_list = true;
//solver.LoadSceneFromFile(filename);
//UpdateTimeline();
OPEN_FILE_TAB = false;
}
}
ImGui::EndChild();
///////////////////////////////////////
}
ImGui::End();
}
ImGui::Begin("IO Panel", &save_panel, ImGuiWindowFlags_MenuBar);
{
ImGui::SetWindowFontScale(InterfaceScale);
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Open..", "")) {
SAVE_FILE_TAB = false;
OPEN_FILE_TAB = true;
//solver.LoadSceneFromFile("scene2");
}
if (ImGui::MenuItem("Save", "")) {
OPEN_FILE_TAB = false;
SAVE_FILE_TAB = true;
}
if (ImGui::MenuItem("Close", "")) {
save_panel = false;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help")) {
if (ImGui::MenuItem("Help", "")) {
helper_window = true;
}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Text("Example scenes");
const char* items[] = { "VDB","VDBFire", "Objects" };// , "vdb", "vdbs" };
static const char* current_item = "Objects";
if (ImGui::BeginCombo("##combo", current_item)) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
bool is_selected = (current_item == items[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(items[n], is_selected)) {
current_item = items[n];
}
if (is_selected)
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
ImGui::EndCombo();
}
if (ImGui::Button("Load Scene")) {
if (current_item == "VDB")
solver.SAMPLE_SCENE = 1;
else if (current_item == "Objects")
solver.SAMPLE_SCENE = 0;
else if (current_item == "VDBFire")
solver.SAMPLE_SCENE = 2;
solver.preserve_object_list = false;
UpdateSolver();
UpdateTimeline();
solver.preserve_object_list = true;
}
ImGui::Text("Exporting settings");
ImGui::InputInt("Start frame", &solver.EXPORT_START_FRAME);
ImGui::InputInt("End frame", &solver.EXPORT_END_FRAME);
ImGui::InputText("Cache Folder", solver.EXPORT_FOLDER, IM_ARRAYSIZE(solver.EXPORT_FOLDER));
if (ImGui::Button("Export VDB")) {
solver.ClearCache();
solver.EXPORT_VDB = true;
UpdateSolver();
progress = 0.0;
}
if (solver.EXPORT_VDB) {
ImGui::ProgressBar(progress, ImVec2(-1, 0));
//progress += 1.0 / ((float)solver.EXPORT_END_FRAME);
progress = (float)solver.frame / ((float)solver.EXPORT_END_FRAME);
}
if (solver.EXPORT_VDB)
if (ImGui::Button("Stop")) {
progress = 0.0;
solver.EXPORT_VDB = false;
}
}
ImGui::End();
ImGui::Begin("Properties Panel");
{
ImGui::SetWindowFontScale(InterfaceScale);
ImGui::Text("Domain Resolution");
int maxx = round(MAX_BOK * ratioo);
int maxy = round(MAX_BOK * ratioo);
int maxz = round(MAX_BOK * ratioo);
ImGui::SliderInt("x", &solver.New_DOMAIN_RESOLUTION.x, 2, maxx);
ImGui::SliderInt("y", &solver.New_DOMAIN_RESOLUTION.y, 2, maxy);
ImGui::SliderInt("z", &solver.New_DOMAIN_RESOLUTION.z, 2, maxz);
solver.New_DOMAIN_RESOLUTION.x = min(solver.New_DOMAIN_RESOLUTION.x, maxx);
solver.New_DOMAIN_RESOLUTION.y = min(solver.New_DOMAIN_RESOLUTION.y, maxy);
solver.New_DOMAIN_RESOLUTION.z = min(solver.New_DOMAIN_RESOLUTION.z, maxz);
ratioo = (MAX_BOK * 3.f) / float(solver.New_DOMAIN_RESOLUTION.x + solver.New_DOMAIN_RESOLUTION.y + solver.New_DOMAIN_RESOLUTION.z);
ImGui::Text("Simulation Settings");
ImGui::SliderFloat("Ambient Temp", &solver.Ambient_Temperature, -10.0f, 100.0f);
ImGui::SliderFloat("Smoke Dissolve", &solver.Smoke_Dissolve, 0.93f, 1.0f);
ImGui::SliderFloat("Flame Dissolve", &solver.Flame_Dissolve, 0.9f, 1.0f);
ImGui::SliderFloat("Diverge rate", &solver.DIVERGE_RATE, 0.1f, 0.8f);
ImGui::SliderFloat("Buoyancy", &solver.Smoke_Buoyancy, 0.0f, 10.0f);
ImGui::SliderFloat("Pressure", &solver.Pressure, -1.5f, 0.0f);
ImGui::SliderFloat("Max Velocity", &solver.max_velocity, 0.0f, 20.0f);
ImGui::SliderFloat("Influence on Velocity", &solver.influence_on_velocity, 0.0f, 5.1f);
ImGui::SliderInt("Simulation accuracy", &solver.ACCURACY_STEPS, 1, 150);
if (ImGui::Button("Simulate")) {
solver.SIMULATE = !solver.SIMULATE;
}
ImGui::SliderFloat("Simulation speed", &solver.speed, 0.1f, 1.5f);
ImGui::Checkbox("Wavelet Upresing", &solver.Upsampling);
if (solver.Upsampling || true) {
ImGui::SliderFloat("Offset", &solver.OFFSET, 0.0001f, 0.3f);
ImGui::SliderFloat("Scale", &solver.SCALE, 0.01f, 4.0f);
//ImGui::Checkbox("Simulation Influence", &solver.INFLUENCE_SIM);
ImGui::SliderFloat("Strength", &solver.noise_intensity, 0.01f, 3.0f);
ImGui::SliderFloat("Time", &solver.time_anim, 0.0f, 2.0f);
if (solver.INFLUENCE_SIM) {
ImGui::Checkbox("Velocity", &solver.UpsamplingVelocity);
ImGui::SameLine();
}
ImGui::Checkbox("Density&Temp", &solver.UpsamplingDensity);
//ImGui::SameLine();
//ImGui::Checkbox("Temperature", &solver.UpsamplingTemperature);
if (solver.UpsamplingDensity)
ImGui::SliderFloat("Density cutoff", &solver.density_cutoff, 0.0001f, 0.01f);
}
//ImGui::ColorEdit3("clear color", (float*)&clear_color);
ImGui::Text("Render Settings:");
ImGui::Checkbox("Fire&Smoke render", &solver.Smoke_And_Fire);
ImGui::Checkbox("Shadows render", &solver.render_shadows);
ImGui::Checkbox("Collision obj render", &solver.render_collision_objects);
ImGui::SliderFloat("Fire Emission Rate", &solver.Fire_Max_Temperature, 0.9, 2);
ImGui::SliderFloat("Fire Multiply", &solver.fire_multiply, 0, 1);
ImGui::SliderInt("Render samples", &solver.STEPS, 128, 2048);
ImGui::SliderFloat("Render Step Size", &solver.render_step_size, 0.5, 2);
ImGui::SliderFloat("Density", &solver.density_influence, 0, 2);
if (!solver.render_shadows)
ImGui::SliderFloat("Transparency Compensation", &solver.transparency_compensation, 0.01, 1);
else
ImGui::SliderFloat("Shadow Quality", &solver.shadow_quality, 0.1, 2);
ImGui::Checkbox("Legacy render", &solver.legacy_renderer);
if (ImGui::Button("Reset")) {
UpdateSolver();
}
ImGui::SameLine();
ImGui::Text(("FPS: " + std::to_string(fps)).c_str());
//ImGui::Checkbox("Preserve object list", &solver.preserve_object_list);
ImGui::Text(("Frame: " + std::to_string(solver.frame)).c_str());
}
ImGui::End();
/////////////////////////////
ImGui::Begin("Objects Panel");
{
ImGui::SetWindowFontScale(InterfaceScale);
ImGui::Text("Emitter type");
static const char* current_item = "emitter";
int current_item_id = 0;
if (ImGui::BeginCombo("##combo", current_item)) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < IM_ARRAYSIZE(itemse); n++)
{
bool is_selected = (current_item == itemse[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(itemse[n], is_selected)) {
current_item = itemse[n];
}
if (is_selected)
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
ImGui::EndCombo();
}
if (ImGui::Button("Delete All")) {
confirm_button = true;
}
if (confirm_button) {
ImGui::SameLine();
if (ImGui::Button("Confirm")) {
for (int object = 0; object < solver.object_list.size(); object++) {
solver.object_list[object].free();
}
solver.object_list.clear();
confirm_button = false;
TimelineInitialized = false;
selectedEntry = -1;
}
}
if (ImGui::Button("Delete selected")) {
REPEAT:
for (int object = 0; object < solver.object_list.size(); object++) {
if (solver.object_list[object].selected) {
/*
if (solver.object_list[object].get_type() == "vdb" ||
solver.object_list[object].get_type() == "vdbs")
solver.object_list[object].cudaFree();
solver.object_list[object].free();
solver.object_list.erase(solver.object_list.begin() + object);
Timeline.Del(object);
*/
DeleteObject(object);
goto REPEAT;
//TODO
}
}
selectedEntry = min((int)selectedEntry, int(solver.object_list.size()-1));
//TimelineInitialized = false;
}
if (ImGui::Button("Add Emitter")) {
/*
solver.object_list.push_back(OBJECT(current_item, 18.0f, 50, 5.2, 5, 0.9, make_float3(float(solver.getDomainResolution().x) * 0.5f, 5.0f, float(solver.getDomainResolution().z) * 0.5f), solver.object_list.size()));
//if (current_item == "explosion") {
for (int i = 0; i < EmitterCount; i++)
if (current_item == itemse[i]) {
current_item_id = i;
break;
}
int j = solver.object_list.size() - 1;
std::cout << current_item_id << " : " << j << std::endl;
AddObject2(current_item_id,j);
*/
for (int i = 0; i < EmitterCount; i++)
if (current_item == itemse[i]) {
current_item_id = i;
break;
}
if (current_item == "particle")
AddParticleSystem = true;
else if (current_item == "object")
AddObjectSystem = true;
else
AddObject(current_item_id);
}
if (AddParticleSystem && current_item == "particle") {
ImGui::InputText("filepath", temp_particle_path, IM_ARRAYSIZE(temp_particle_path));
if (std::experimental::filesystem::is_directory(temp_particle_path)) {
if (ImGui::Button("Confirm")) {
OBJECT prt("particle", 1.0f, make_float3(0, 0, 0), 5.0, 0.8, solver.object_list.size(), solver.devicesCount);
prt.particle_filepath = temp_particle_path;
prt.LoadParticles();
if (prt.velocities.size() != 0) {
if (prt.velocities[0].size() != 0) {
solver.object_list.push_back(prt);
int j = solver.object_list.size() - 1;
AddObject2(PARTICLE, j, 1);
}
}
AddParticleSystem = false;
}
}
}
if (AddObjectSystem && current_item == "object") {
ImGui::InputText("filepath2", temp_object_path, IM_ARRAYSIZE(temp_object_path));
if (std::experimental::filesystem::is_directory(temp_object_path)) {
if (ImGui::Button("Confirm")) {
OBJECT prt("object", 1.0f, make_float3(0, 0, 0), 5.0, 0.8, solver.object_list.size(), solver.devicesCount);
prt.particle_filepath = temp_object_path;
prt.LoadObjects(solver.getDomainResolution(),solver.devicesCount,solver.deviceIndex);
if (prt.collisions.size() != 0) {
solver.object_list.push_back(prt);
int j = solver.object_list.size() - 1;
AddObject2(VDBOBJECT, j, 1);
}
AddObjectSystem = false;
}
}
}
ImGui::Text("Object list:");
ImGui::BeginChild("Scrolling");
for (int object = 0; object < solver.object_list.size(); object++) {
std::string name = (" -> " + solver.object_list[object].get_name());
ImGui::Text(name.c_str());
ImGui::SameLine();
ImGui::Checkbox(std::to_string(object).c_str(), &solver.object_list[object].selected);
float maxs[] = { solver.New_DOMAIN_RESOLUTION.x,solver.New_DOMAIN_RESOLUTION.y,solver.New_DOMAIN_RESOLUTION.z };
float minns[] = { 0.0f,0.0f,0.0f };
if (solver.object_list[object].type != PARTICLE) {
if (solver.SIMULATE) {
solver.object_list[object].Location[0] = solver.object_list[object].get_location().x;
solver.object_list[object].Location[1] = solver.object_list[object].get_location().y;
solver.object_list[object].Location[2] = solver.object_list[object].get_location().z;
SliderPos(("position-" + std::to_string(object)).c_str(), ImGuiDataType_Float, solver.object_list[object].Location, 3, minns, maxs);
}
else {
SliderPos(("position-" + std::to_string(object)).c_str(), ImGuiDataType_Float, solver.object_list[object].Location, 3, minns, maxs);
int position = -1;
if (Timeline.rampEdit[object].IsOnPoint(CURVE_X, solver.frame, position) &&
Timeline.rampEdit[object].IsOnPoint(CURVE_Y, solver.frame, position) &&
Timeline.rampEdit[object].IsOnPoint(CURVE_Z, solver.frame, position)) {
ImGui::Checkbox(std::string("Edit Keyframe XYZ-" + std::to_string(object)).c_str(), &solver.object_list[object].edit_frame_translation);
if (solver.object_list[object].edit_frame_translation) {
Timeline.rampEdit[object].EditPoint(CURVE_X, position, ImVec2(solver.frame, solver.object_list[object].Location[0]));
Timeline.rampEdit[object].EditPoint(CURVE_Y, position, ImVec2(solver.frame, solver.object_list[object].Location[1]));
Timeline.rampEdit[object].EditPoint(CURVE_Z, position, ImVec2(solver.frame, solver.object_list[object].Location[2]));
}
}
else {
if (ImGui::Button(std::string("Add Keyframe XYZ" + std::to_string(object)).c_str())) {
if (!Timeline.rampEdit[object].IsOnPoint(CURVE_X, solver.frame, position))
Timeline.rampEdit[object].AddPoint(CURVE_X, ImVec2(solver.frame, solver.object_list[object].Location[0]));
if (!Timeline.rampEdit[object].IsOnPoint(CURVE_Y, solver.frame, position))
Timeline.rampEdit[object].AddPoint(CURVE_Y, ImVec2(solver.frame, solver.object_list[object].Location[1]));
if (!Timeline.rampEdit[object].IsOnPoint(CURVE_Z, solver.frame, position))
Timeline.rampEdit[object].AddPoint(CURVE_Z, ImVec2(solver.frame, solver.object_list[object].Location[2]));
}
}
}
}
else { /////PARTICLE
if (solver.SIMULATE) {
solver.object_list[object].Location[0] = solver.object_list[object].get_location().x;
solver.object_list[object].Location[1] = solver.object_list[object].get_location().y;
solver.object_list[object].Location[2] = solver.object_list[object].get_location().z;
SliderPos(("position-" + std::to_string(object)).c_str(), ImGuiDataType_Float, solver.object_list[object].Location, 3, minns, maxs);
}
else {
SliderPos(("position-" + std::to_string(object)).c_str(), ImGuiDataType_Float, solver.object_list[object].Location, 3, minns, maxs);
ImGui::Checkbox(std::string("Edit Keyframe XYZ-" + std::to_string(object)).c_str(), &solver.object_list[object].edit_frame_translation);
if (solver.object_list[object].edit_frame_translation) {
for (int position = 0; position < Timeline.rampEdit[object].mPointCount[CURVE_X]; position++)
Timeline.rampEdit[object].EditPoint(CURVE_X, position, ImVec2(Timeline.rampEdit[object].mPts[CURVE_X][position].x, solver.object_list[object].Location[0]));
for (int position = 0; position < Timeline.rampEdit[object].mPointCount[CURVE_Y]; position++)
Timeline.rampEdit[object].EditPoint(CURVE_Y, position, ImVec2(Timeline.rampEdit[object].mPts[CURVE_Y][position].x, solver.object_list[object].Location[1]));
for (int position = 0; position < Timeline.rampEdit[object].mPointCount[CURVE_Z]; position++)
Timeline.rampEdit[object].EditPoint(CURVE_Z, position, ImVec2(Timeline.rampEdit[object].mPts[CURVE_Z][position].x, solver.object_list[object].Location[2]));
}
}
ImGui::SliderFloat(("scale-" + std::to_string(object)).c_str(), &solver.object_list[object].scale, 0.01f, 10.f);
}
if (solver.object_list[object].type == VDBOBJECT) {
ImGui::Checkbox(("emitter-" + std::to_string(object)).c_str(), &solver.object_list[object].is_emitter);
}
if (solver.SIMULATE) {
ImGui::SliderFloat(("size-" + std::to_string(object)).c_str(), &solver.object_list[object].size, 0.0, 200.0);
solver.object_list[object].initial_size = solver.object_list[object].size;
}
else {
ImGui::SliderFloat(("size-" + std::to_string(object)).c_str(), &solver.object_list[object].initial_size, 0.0, 200.0);
//solver.object_list[object].initial_size = solver.object_list[object].size;
int position = -1;
if (Timeline.rampEdit[object].IsOnPoint(CURVE_SIZE, solver.frame, position)) {
ImGui::Checkbox(std::string("Edit Keyframe S" + std::to_string(object)).c_str(), &solver.object_list[object].edit_frame);
if (solver.object_list[object].edit_frame) {
Timeline.rampEdit[object].EditPoint(CURVE_SIZE, position, ImVec2(solver.frame, solver.object_list[object].initial_size));
}
}
else {
if (ImGui::Button(std::string("Add Keyframe S" + std::to_string(object)).c_str())) {
Timeline.rampEdit[object].AddPoint(CURVE_SIZE, ImVec2(solver.frame, solver.object_list[object].initial_size));
}
}
}
if (solver.object_list[object].type >= 5 && solver.object_list[object].type < 9) {
ImGui::SliderFloat(("force strength-" + std::to_string(object)).c_str(), &solver.object_list[object].force_strength, -100.0, 100.0);
ImGui::SameLine();
ImGui::Checkbox(("Square-" + std::to_string(object)).c_str(), &solver.object_list[object].square);
if (solver.object_list[object].type == FORCE_FIELD_TURBULANCE) {
ImGui::SliderFloat(("turbulance frequence-" + std::to_string(object)).c_str(), &solver.object_list[object].velocity_frequence, 0.0, 20);
ImGui::SliderFloat(("turbulance scale-" + std::to_string(object)).c_str(), &solver.object_list[object].scale, 0.005, 1.3);
}
if (solver.object_list[object].type == FORCE_FIELD_WIND)
ImGui::SliderFloat3(("wind direction-" + std::to_string(object)).c_str(), solver.object_list[object].force_direction, -1, 1);
}
else if (solver.object_list[object].type == EMITTER) {
ImGui::SliderFloat(("initial temperature-" + std::to_string(object)).c_str(), &solver.object_list[object].impulseTemp, -50.0, 50.0);
ImGui::SliderFloat(("velocity frequence-" + std::to_string(object)).c_str(), &solver.object_list[object].velocity_frequence, 0.0, solver.object_list[object].max_vel_freq);
//solver.object_list[object].set_vel_freq = solver.object_list[object].velocity_frequence;
}
else if (solver.object_list[object].type == EXPLOSION) {
ImGui::SliderFloat(("initial temperature-" + std::to_string(object)).c_str(), &solver.object_list[object].impulseTemp, -50.0, 50.0);
ImGui::SliderFloat(("velocity frequence-" + std::to_string(object)).c_str(), &solver.object_list[object].velocity_frequence, 0.0, solver.object_list[object].max_vel_freq);
ImGui::InputInt(("start frame-" + std::to_string(object)).c_str(), &solver.object_list[object].frame_range_min);
ImGui::InputInt(("end frame-" + std::to_string(object)).c_str(), &solver.object_list[object].frame_range_max);
}
solver.object_list[object].UpdateLocation();
}
ImGui::EndChild();
}
ImGui::End();
/////////////////////////////
ImGui::Begin("Timeline && Animation");
{
ImGui::SetWindowFontScale(InterfaceScale);
if (!TimelineInitialized) {
UpdateTimeline();
TimelineInitialized = true;
}
// let's create the sequencer
static bool expanded = true;//true
ImGui::PushItemWidth(130);
ImGui::InputInt("Frame Min", &solver.START_FRAME);
//ImGui::SameLine();
//ImGui::InputInt("Frame ", ¤tFrame);
ImGui::SameLine();
ImGui::InputInt("Frame Max", &solver.END_FRAME);
ImGui::PopItemWidth();
if (solver.START_FRAME < 0) solver.START_FRAME = 0;
if (solver.END_FRAME < 0) solver.END_FRAME = 0;
//Timeline.mFrameMin = solver.START_FRAME;
//Timeline.mFrameMax = solver.END_FRAME;
//Sequencer(&Timeline, &solver.frame, &expanded, &selectedEntry, &solver.START_FRAME, ImSequencer::SEQUENCER_EDIT_STARTEND | ImSequencer::SEQUENCER_ADD | ImSequencer::SEQUENCER_DEL | ImSequencer::SEQUENCER_COPYPASTE | ImSequencer::SEQUENCER_CHANGE_FRAME);
Sequencer(&Timeline, &solver.frame, &expanded, &selectedEntry, &begin_frame, ImSequencer::SEQUENCER_EDIT_STARTEND | ImSequencer::SEQUENCER_ADD | ImSequencer::SEQUENCER_DEL | ImSequencer::SEQUENCER_COPYPASTE | ImSequencer::SEQUENCER_CHANGE_FRAME);
// add a UI to edit that particular item
if (selectedEntry != -1 && Timeline.rampEdit.size() > 0)
{
const MySequence::MySequenceItem& item = Timeline.myItems[selectedEntry];
ImGui::SliderFloat("Minimum", &Timeline.rampEdit[selectedEntry].mMin[0].y, 0.0, 500);
ImGui::SliderFloat("Maksimum", &Timeline.rampEdit[selectedEntry].mMax[0].y, 0.0, 500);
const char* items2[] = { "sine", "random_noise"};
static const char* current_item2 = "sine";
int current_item_id = 0;
if (ImGui::BeginCombo("##combo1", current_item2)) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < IM_ARRAYSIZE(items2); n++)
{
bool is_selected = (current_item2 == items2[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(items2[n], is_selected)) {
current_item2 = items2[n];
}
if (is_selected)
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
ImGui::EndCombo();
}
const char* axes[] = { "size", "x" , "y", "z" };
static const char* axis = "size";
int ax = 0;
if (ImGui::BeginCombo("##combo2", axis)) {
for (int n = 0; n < IM_ARRAYSIZE(axes); n++)
{
bool is_selected = (axis == axes[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(axes[n], is_selected)) {
axis = axes[n];
}
if (is_selected) {
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
}
ImGui::EndCombo();
}
if (current_item2 == "sine") {
ImGui::SliderInt("step_size", &sinresolution, 1, 16);
ImGui::SliderFloat("speed", &sinspeed, 0.01f, 5);
ImGui::SliderFloat("size", &sinsize, 0.01f, 500);
ImGui::SliderFloat("mid", &sinmid, 0, 500);
ImGui::SliderFloat("offset", &sinoffset, 0, 1);
if (ImGui::Button("Add")) {
for (int z = 0; z < IM_ARRAYSIZE(axes); z++) {
if (axes[z] == axis) {
ax = z;
break;
}
}
Timeline.rampEdit[selectedEntry].RemovePoints(ax);
for (int i = 0; i < solver.END_FRAME; i += sinresolution) {
Timeline.rampEdit[selectedEntry].AddPoint(ax, ImVec2(i, sinsize * std::sinf(sinoffset + (float)i * sinspeed) + sinmid));
}
}
}
else if (current_item2 == "random_noise") {
ImGui::SliderInt("step_size", &sinresolution, 1, 16);
//ImGui::SliderFloat("speed", &sinspeed, 0.01f, 5);
ImGui::SliderFloat("size", &sinsize, 0.01f, 500);
ImGui::SliderFloat("mid", &sinmid, 0, 500);
ImGui::SliderFloat("SEED", &sinoffset, 0, 1);
srand(unsigned int(sinoffset * 1000));
if (ImGui::Button("Add")) {
for (int z = 0; z < IM_ARRAYSIZE(axes); z++) {
if (axes[z] == axis) {
ax = z;
break;
}
}
Timeline.rampEdit[selectedEntry].RemovePoints(ax);
for (int i = 0; i < solver.END_FRAME; i += sinresolution) {
Timeline.rampEdit[selectedEntry].AddPoint(ax, ImVec2(i, sinsize * (float(rand() % 1000) / 1000.0f) + sinmid));
}
}
}
}
if (solver.frame > solver.END_FRAME)
UpdateSolver();
}
ImGui::End();
}
#include <Windows.h>
#include <WinUser.h>
int Window(float* Img_res, float dpi) {
#ifndef WINDOWS7_BUILD
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); //skalowanie globalne //bez _V2 chyba lepsze
#endif // WINDOWS7_BUILD
InterfaceScale = dpi;
GLFWwindow* window;
//initialize
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//create a windowed mode window
window = glfwCreateWindow(Img_res[0], Img_res[1], FULL_NAME.c_str(), NULL, NULL);
if (!window) {
std::cout << "Cannot create window";
glfwTerminate();
return -1;
}
//////////KURSOR
glfwSetCursorPosCallback(window, cursorPositionCallback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); //GLFW_CURSOR_HIDDEN
glfwSetCursorEnterCallback(window, cursorEnterCallback);
glfwSetMouseButtonCallback(window, mouseButtonCallback);
glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1);
glfwSetScrollCallback(window, scrollCallback);
/////////////KLAWIATURA
glfwSetKeyCallback(window, keyCallback);
////////////
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK)
std::cout << "Error: glewInit\n";
std::cout << glGetString(GL_VERSION) << std::endl;
///////////////////////////////////////////////
//calculate sizes
int2 Image = make_int2(solver.getImageResoltion().x, solver.getImageResoltion().y);
int2 Window = make_int2(Img_res[0], Img_res[1]);
{
float range_x = ((float)Image.x / (float)Window.x);
range_x = 2.0 * range_x - 1.0;
float range_y = ((float)Image.y / (float)Window.y);
range_y = 2.0 * range_y - 1.0;
if (Image.x == Window.x) range_x = 1.0f;
if (Image.y == Window.y) range_y = 1.0f;
float positions[] = {
-1.0f, -1.0f, 0.0f, 0.0f, //lewy dół
range_x, -1.0f, 1.0f, 0.0f,
range_x, range_y, 1.0f, 1.0f,
-1.0f, range_y, 0.0f, 1.0f
};
unsigned int indices[] = {
0,1,2,
2,3,0
};
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
GLCall(glEnable(GL_BLEND));
///////////////////////////////////////////////
unsigned int vao;
GLCall(glGenVertexArrays(1, &vao));//1
GLCall(glBindVertexArray(vao));
///////////////////////////////////////////////
VertexArray va;
VertexBuffer vb(positions, 4 * 4 * sizeof(float));
VertexBufferLayout layout;
layout.Push<float>(2);
layout.Push<float>(2);
va.AddBuffer(vb, layout);
/////////////////////////////////////////////
IndexBuffer ib(indices, 6);
/////////////////SHADERS/////////////////////
Shader shader("./Shaders.shader");
shader.Bind();
//////////////////UNIFORM SHADER////////////////////
//shader.SetUniform4f("u_Color", 0.2f, 0.3f, 0.9f, 1.0f);
float r = 0.0f;
float increment = 0.01f;
/////////////////////////////////////////////////
//Texture texture("file.bmp");
//texture.Bind(/*slot*/0);
//shader.SetUniform1i("u_Texture", /*slot*/0);
Texture texture("mf.bmp");
///////////////////////////////////////////
va.UnBind();
shader.UnBind();
vb.Unbind();
ib.Unbind();
Renderer renderer;
solver.frame = 0;
/////////////////////////////////////////////////
//////////////IMGUI/////////////////////////////
//Setup IMGUI
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init((char*)glGetString(GL_NUM_SHADING_LANGUAGE_VERSIONS));
//ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
float fps = 0;
bool save_panel = true;
bool SAVE_FILE_TAB = false;
bool OPEN_FILE_TAB = false;
float progress = 0.0f;
bool helper_window = true;
bool confirm_button = false;
//std::thread* sim;
solver.DONE_FRAME = true;
/////////////////////////////////////////////////
//TImeline
//Timeline.myItems.push_back(MySequence::MySequenceItem{ 0, 10, 30, false });
//Timeline.myItems.push_back(MySequence::MySequenceItem{ 1, 20, 30, true });
solver.frame = 0;
solver.state->time_step = solver.speed * 0.1;
solver.DONE_FRAME = false;
//UpdateSolver();
UpdateTimeline();
///////////////////////////////////////////////////
while (!glfwWindowShouldClose(window)) {
//clock_t startTime = clock();
if (solver.LOCK) continue;
UpdateAnimation();
//////////////////
//solver.Simulation_Frame();
if (threads.size() == 0) {
threads.push_back(std::thread([&]() {
while (true) {
clock_t startTime = clock();
solver.Simulation_Frame();
fps = 1.0 / ((double(clock() - startTime) / (double)CLOCKS_PER_SEC));
if (solver.THIS_IS_THE_END) {
std::cout << "I'm breaking out" << std::endl;
break;
}
}
}));
}
/*
*/
//////////////////
//Texture texture("output/R" + pad_number(frame) + ".bmp");
//texture.UpdateTexture("output/R" + pad_number(solver.frame) + ".bmp");
if (!solver.writing) {
solver.writing = true;
texture.UpdateTexture("./output/temp.bmp");
solver.writing = false;
texture.Bind(/*slot*/0);
}
//shader.SetUniform1i("u_Texture", /*slot*/0);
//////////////////
renderer.Clear();
shader.Bind();
/////////////////////////////
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
//std::thread GUI_THR( RenderGUI ,std::ref(SAVE_FILE_TAB), std::ref(OPEN_FILE_TAB), std::ref(fps), std::ref(progress), std::ref(save_panel));
RenderGUI(SAVE_FILE_TAB, OPEN_FILE_TAB, fps, progress, save_panel, helper_window, confirm_button, Image);
//New Frame//////////////////
renderer.Draw(va, ib, shader);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
GLCall(glfwSwapBuffers(window));
GLCall(glfwPollEvents());
//fps = 1.0 / ((double(clock() - startTime) / (double)CLOCKS_PER_SEC));
}
solver.THIS_IS_THE_END = true;
std::cout << "Threads join together" << std::endl;
for (auto& thread : threads)
thread.join();
threads.clear();
}
//Shutdown
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwTerminate();
return 0;
}
static void cursorPositionCallback(GLFWwindow* window, double xPos, double yPos) {
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
/*Rotate*/
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
solver.setRotation(solver.getRotation() - 0.1f);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
solver.setRotation(solver.getRotation() + 0.1f);
}
}
else{ /*Left-Right*/
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x - 2.5f, solver.getCamera().y, solver.getCamera().z);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x + 2.5f, solver.getCamera().y, solver.getCamera().z);
}
} /*Forward - Backward*/
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x, solver.getCamera().y, solver.getCamera().z + 2.5f);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x, solver.getCamera().y, solver.getCamera().z - 2.5f);
}
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) {
UpdateSolver();
}
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x, solver.getCamera().y + 2.5f, solver.getCamera().z);
}
if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
solver.setCamera(solver.getCamera().x, solver.getCamera().y - 2.5f, solver.getCamera().z);
}
if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) {
solver.EXPORT_VDB = false;
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
solver.SIMULATE = solver.SIMULATE ? false : true;
}
}
void cursorEnterCallback(GLFWwindow* window, int entered) {
if (entered) {
}
}
void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) {
double xPos, yPos;
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
//left button released
}
}
void scrollCallback(GLFWwindow* window, double xOffset, double yOffset) {
solver.setCamera(solver.getCamera().x, solver.getCamera().y,
solver.getCamera().z + 2.5f * yOffset);
//std::cout <<" "<< yOffset;
}
|
#pragma once
#include <stdexcept>
#include "i_enumerator.h"
#include "i_collection.h"
template <typename T>
class ArrayEnumerator : public IEnumerator<T>
{
private:
T* p_begin = nullptr;
T* p_current = nullptr;
T* p_end = nullptr;
public:
ArrayEnumerator(T* begin, T* end);
bool MoveNext() override;
T GetCurrent() override;
void Reset() override;
};
template <class T> class DynamicArray : public IEnumerable<T>, public ICollection<T>
{
private:
size_t size_ = 0;
size_t capacity_ = 0;
float growth_factor_ = 2;
T* p_data_ = nullptr;
public:
// Constructors
DynamicArray() = default;
DynamicArray(T* items, size_t count);
DynamicArray(size_t size);
DynamicArray(const DynamicArray<T>& dynamic_array);
DynamicArray(const DynamicArray<T>* dynamic_array);
// Decomposition
T Get(size_t index) const;
size_t GetCount() const;
void DeleteAt(size_t index);
void Set(size_t index, T value);
void Swap(size_t first_index, size_t second_index);
// Operators
DynamicArray<T>& operator=(const DynamicArray<T>& other);
// Operations
void Resize(size_t new_size);
DynamicArray<T>* Slice(size_t start_index, size_t end_index) const;
// Iterator
IEnumerator<T>* GetEnumerator() override;
// Destructor
~DynamicArray();
};
// Realization
template <typename T>
ArrayEnumerator<T>::ArrayEnumerator(T* begin, T* end)
{
p_begin = begin;
p_current = begin;
p_end = end;
}
template <typename T>
bool ArrayEnumerator<T>::MoveNext()
{
if (p_current + 1 != p_end && p_current != p_end)
{
++p_current;
return true;
}
return false;
}
template <typename T>
T ArrayEnumerator<T>::GetCurrent()
{
if(p_current == nullptr)
{
throw std::out_of_range("ArrayEnumerator GetCurrent: out of range");
}
return *p_current;
}
template <typename T>
void ArrayEnumerator<T>::Reset()
{
p_current = p_begin;
}
template <class T>
DynamicArray<T>::DynamicArray(T* items, size_t count)
{
capacity_ = count;
size_ = count;
p_data_ = new T[capacity_]();
for (size_t i = 0; i < count; ++i)
{
p_data_[i] = items[i];
}
}
template <class T>
DynamicArray<T>::DynamicArray(size_t size)
{
capacity_ = size;
size_ = size;
p_data_ = new T[capacity_]();
}
template <class T>
DynamicArray<T>::DynamicArray(const DynamicArray<T>& dynamic_array)
{
*this = dynamic_array;
/*
capacity_ = dynamic_array.capacity_;
size_ = dynamic_array.size_;
p_data_ = new T[capacity_]();
for (size_t i = 0; i < size_; ++i)
{
p_data_[i] = dynamic_array.p_data_[i];
}
*/
}
template <class T>
DynamicArray<T>::DynamicArray(const DynamicArray<T>* dynamic_array)
{
*this = DynamicArray<T>(dynamic_array->p_data_, dynamic_array->size_);
}
template <class T>
DynamicArray<T>& DynamicArray<T>::operator=(const DynamicArray<T>& other)
{
if (this == &other) return *this;
size_ = other.size_;
capacity_ = size_;
p_data_ = new T[size_];
for(int i = 0; i < size_; ++i)
{
p_data_[i] = other.p_data_[i];
}
return *this;
}
template <class T>
T DynamicArray<T>::Get(size_t index) const
{
if (index >= size_)
{
throw std::out_of_range("DynamicArray Get: index out of range");
}
return p_data_[index];
}
template <class T>
size_t DynamicArray<T>::GetCount() const
{
return size_;
}
template <class T>
void DynamicArray<T>::DeleteAt(size_t index)
{
if(index >= size_)
{
throw std::out_of_range("DynamicArray DeleteAt: index out of range");
}
for(size_t i = index; i < size_ - 1; ++i)
{
p_data_[i] = p_data_[i + 1];
}
this->Resize(size_ - 1);
}
template <class T>
void DynamicArray<T>::Set(size_t index, T value)
{
if (index >= size_)
{
throw std::out_of_range("DynamicArray Set: index out of range");
}
p_data_[index] = value;
}
template <class T>
void DynamicArray<T>::Swap(size_t first_index, size_t second_index)
{
T tmp = p_data_[first_index];
p_data_[first_index] = p_data_[second_index];
p_data_[second_index] = tmp;
}
template <class T>
void DynamicArray<T>::Resize(size_t new_size)
{
if (new_size > capacity_)
{
// TODO
if (capacity_ == 0)
{
capacity_ = 10;
}
while (new_size > capacity_)
{
capacity_ = (int)(capacity_ * growth_factor_);
}
T* old_p_data = p_data_;
p_data_ = new T[capacity_]();
for (size_t i = 0; i < size_; ++i)
{
p_data_[i] = old_p_data[i];
}
delete[] old_p_data;
}
if(new_size < size_)
{
for (size_t i = new_size; i < size_; ++i)
{
p_data_[i] = T{};
}
}
size_ = new_size;
}
template <class T>
DynamicArray<T>* DynamicArray<T>::Slice(size_t start_index, size_t end_index) const
{
if (size_ == 0)
{
throw std::out_of_range(
"DynamicArray Slice: list is empty");
}
if (start_index >= size_)
{
throw std::out_of_range(
"DynamicArray Slice: start_index out of range");
}
if (end_index >= size_)
{
throw std::out_of_range(
"DynamicArray Slice: end_index out of range");
}
if (start_index > end_index)
{
throw std::out_of_range("DynamicArray Slice: "
"end_index is less than start_index");
}
DynamicArray<T>* res = new DynamicArray(&p_data_[start_index], end_index - start_index + 1);
return res;
}
template <class T>
IEnumerator<T>* DynamicArray<T>::GetEnumerator()
{
return new ArrayEnumerator<T>(p_data_, p_data_ + size_);
}
template <class T>
DynamicArray<T>::~DynamicArray()
{
delete[] p_data_;
}
|
//
// Created by DELL on 10/25/2020.
//
#include "Logic.h"
Logic::Logic() {}
Logic::~Logic() {}
Logic::Logic(vector<int> tiles_amt, vector <int> player_point) {
this->tiles_amt = tiles_amt;
this->player_point = player_point;
}
void Logic::firstTimeSet() {
tiles_amt.resize(13);
for (int i = 1; i <= 12; i++){
tiles_amt[i] = 5;
}
tiles_amt[6] = tiles_amt[12] = 10;
player_point.resize(3);
player_point[2] = player_point[1] = 0;
}
void Logic::setupTilesAmt(int mark, int index, string key, vector <int> &a, vector <int> &b) {
if (key != "") {
pickAndDropAndTake(mark, key, index);
checkEmpty(index);
}
for (int i = 1; i <= 12; i++){
a[i] = tiles_amt[i];
}
for (int i = 1; i <= 2; i++){
b[i] = player_point[i];
}
}
int Logic::resetTilesAmt(int mark, int index) {
int tmp;
if (index == 1){
tmp = tiles_amt[mark+1];
tiles_amt[mark+1] = 0;
}
else{
tmp = tiles_amt[12-(mark+1)];
tiles_amt[12-(mark+1)] = 0;
}
return tmp;
}
void Logic::pickAndDropAndTake(int mark, string key, int index) {
int tiles_process;
if (index == 1) tiles_process = mark + 1;
else tiles_process = 12 - (mark + 1);
int share_amt = resetTilesAmt(mark, index);
// ----------------Key: Right || Index: 1 -------------------
if (key == "right" && index == 1) {
while (share_amt--) {
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
tiles_amt[tiles_process]++;
if (share_amt == 0) {
if (tiles_process == 12) {
if (tiles_amt[1] != 0) {
share_amt = tiles_amt[1];
tiles_amt[1] = 0;
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
}
}
else {
if (tiles_amt[tiles_process + 1] != 0) {
share_amt = tiles_amt[tiles_process + 1];
tiles_amt[tiles_process + 1] = 0;
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
}
}
}
}
int add_point_pos;
while (true){
add_point_pos = tiles_process + 2;
if (add_point_pos == 14) add_point_pos = 2;
else if (add_point_pos == 13) add_point_pos = 1;
if (tiles_amt[add_point_pos] == 0) break;
player_point[1] += tiles_amt[add_point_pos];
tiles_amt[add_point_pos] = 0;
}
}
// ----------------Key: Right || Index: 2 -------------------
if (key == "right" && index == 2){
while (share_amt--){
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
tiles_amt[tiles_process]++;
if (share_amt == 0){
if (tiles_process == 1){
if (tiles_amt[12] != 0){
share_amt = tiles_amt[12];
tiles_amt[12] = 0;
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
}
}
else{
if (tiles_amt[tiles_process-1] != 0) {
share_amt = tiles_amt[tiles_process - 1];
tiles_amt[tiles_process - 1] = 0;
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
}
}
}
}
while (true){
int add_point_pos = tiles_process - 2;
if (add_point_pos == 0) add_point_pos = 12;
else if (add_point_pos == -1) add_point_pos = 11;
if (tiles_amt[add_point_pos] == 0) break;
player_point[2] += tiles_amt[add_point_pos];
tiles_amt[add_point_pos] = 0;
}
}
// ----------------Key: Left || Index: 1 -------------------
if (key == "left" && index == 1){
while (share_amt--){
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
tiles_amt[tiles_process]++;
if (share_amt == 0){
if (tiles_process == 1){
if (tiles_amt[12] != 0){
share_amt = tiles_amt[12];
tiles_amt[12] = 0;
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
}
}
else{
if (tiles_amt[tiles_process-1] != 0) {
share_amt = tiles_amt[tiles_process - 1];
tiles_amt[tiles_process - 1] = 0;
tiles_process--;
if (tiles_process == 0) tiles_process = 12;
}
}
}
}
while (true){
int add_point_pos = tiles_process - 2;
if (add_point_pos == 0) add_point_pos = 12;
else if (add_point_pos == -1) add_point_pos = 11;
if (tiles_amt[add_point_pos] == 0) break;
player_point[1] += tiles_amt[add_point_pos];
tiles_amt[add_point_pos] = 0;
}
}
// ----------------Key: Left || Index: 2 -------------------
if (key == "left" && index == 2){
while (share_amt--){
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
tiles_amt[tiles_process]++;
if (share_amt == 0){
if (tiles_process == 12){
if (tiles_amt[1] != 0){
share_amt = tiles_amt[1];
tiles_amt[1] = 0;
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
}
}
else{
if (tiles_amt[tiles_process+1] != 0) {
share_amt = tiles_amt[tiles_process + 1];
tiles_amt[tiles_process + 1] = 0;
tiles_process++;
if (tiles_process == 13) tiles_process = 1;
}
}
}
}
while (true){
int add_point_pos = tiles_process + 2;
if (add_point_pos == 14) add_point_pos = 2;
else if (add_point_pos == 13) add_point_pos = 1;
if (tiles_amt[add_point_pos] == 0) break;
player_point[2] += tiles_amt[add_point_pos];
tiles_amt[add_point_pos] = 0;
}
}
cout << "Diem nguoi 1: " << player_point[1] << "\n" << "Diem nguoi 2: " << player_point[2] << "\n";
}
void Logic::checkEmpty(int index) {
bool empty = true;
if (index == 1){
for (int i = 1; i <= 5; i++){
if (tiles_amt[i] != 0) empty = false;
}
if (empty){
player_point[1] -= 5;
for (int i = 1; i <= 5; i++){
tiles_amt[i] = 1;
}
}
}
else if (index == 2){
for (int i = 7; i <= 11; i++){
if (tiles_amt[i] != 0) empty = false;
}
if (empty){
player_point[1] -= 5;
for (int i = 7; i <= 11; i++){
tiles_amt[i] = 1;
}
}
}
}
|
#define F(NAME,TARGET) class NAME { \
allowedTargets = TARGET; \
};
#define JIP(NAME,TARGET) class NAME { \
allowedTargets = TARGET; \
jip = 1; \
};
#define ANYONE 0
#define CLIENT 1
#define SERVER 2
//#define HC CXP_HC
class CfgRemoteExec {
class Functions {
mode = 1;
jip = 0;
/* Bounty Hunter */
F(cxp_fnc_setGroupTrackMarker,CLIENT)
F(cxp_fnc_alvoKilled,CLIENT)
F(cxp_fnc_wantedGetBounty,SERVER)
F(cxp_fnc_wantedBountyCiv,SERVER)
F(cxp_fnc_setBounty,ANYONE)
F(cxp_fnc_removerBountyLic,ANYONE)
F(cxp_fnc_updateBountyListLocal,ANYONE)
F(cxp_fnc_checarGlobal,ANYONE)
F(cxp_fnc_flashbang,ANYONE)
/* Funcoes Cliente CXP */
// cxp
F(cxp_fnc_getOffmem,CLIENT)
F(cxp_fnc_hintTggGZ,CLIENT)
F(cxp_fnc_speedCamera,CLIENT)
F(cxp_fnc_msgSafezone,CLIENT)
F(cxp_fnc_receiveMoney,CLIENT)
F(cxp_fnc_setupCellPhone,CLIENT)
F(cxp_fnc_moveInCargo,CLIENT)
F(cxp_fnc_tieing,CLIENT)
F(cxp_fnc_tieingb,CLIENT)
F(cxp_fnc_gagged,CLIENT)
F(cxp_fnc_AAN,CLIENT)
F(cxp_fnc_addVehicle2Chain,CLIENT)
F(cxp_fnc_perdeuRabo,CLIENT)
F(cxp_fnc_terminarCurarAnal,CLIENT)
JIP(cxp_fnc_copLights,CLIENT)
JIP(cxp_fnc_copSiren,CLIENT)
JIP(cxp_fnc_copSiren2,CLIENT)
F(cxp_fnc_copSearch,CLIENT)
F(cxp_fnc_gangCreated,CLIENT)
F(cxp_fnc_gangDisbanded,CLIENT)
F(cxp_fnc_gangInvite,CLIENT)
F(cxp_fnc_garageRefund,CLIENT)
F(cxp_fnc_giveDiff,CLIENT)
F(cxp_fnc_impoundMenu,CLIENT)
F(cxp_fnc_jail,CLIENT)
F(cxp_fnc_jailMe,CLIENT)
F(cxp_fnc_knockedOut,CLIENT)
F(cxp_fnc_licenseCheck,CLIENT)
F(cxp_fnc_licensesRead,CLIENT)
F(cxp_fnc_lightHouse,CLIENT)
JIP(cxp_fnc_mediclights,CLIENT)
JIP(cxp_fnc_medicSiren,CLIENT)
JIP(cxp_fnc_medicSiren2,CLIENT)
F(cxp_fnc_moveIn,CLIENT)
F(cxp_fnc_pickupItem,CLIENT)
F(cxp_fnc_pickupMoney,CLIENT)
F(cxp_fnc_receiveItem,CLIENT)
F(cxp_fnc_removeLicenses,CLIENT)
F(cxp_fnc_restrain,CLIENT)
F(cxp_fnc_revived,CLIENT)
F(cxp_fnc_robPerson,CLIENT)
F(cxp_fnc_robReceive,CLIENT)
F(cxp_fnc_searchClient,CLIENT)
F(cxp_fnc_seizeClient,CLIENT)
F(cxp_fnc_seizeClientMed,CLIENT)
F(cxp_fnc_soundDevice,CLIENT)
F(cxp_fnc_spikeStripEffect,CLIENT)
F(cxp_fnc_ticketPaid,CLIENT)
F(cxp_fnc_ticketPrompt,CLIENT)
F(cxp_fnc_vehicleAnimate,CLIENT)
F(cxp_fnc_wantedList,CLIENT)
F(cxp_fnc_wireTransfer,CLIENT)
F(cxp_fnc_breathalyzer,CLIENT)
F(cxp_fnc_geradordeefeitos,CLIENT)
F(cxp_fnc_multaAutomatica,CLIENT)
F(cxp_fnc_calcMoneyRemote,CLIENT)
F(cxp_fnc_vAHreciever,CLIENT)
F(cxp_fnc_stopEscorting,CLIENT)
F(cxp_fnc_custPlaySound,CLIENT)
F(cxp_fnc_updateBaseLic,CLIENT)
F(cxp_fnc_completeBugTracking,CLIENT)
F(cxp_fnc_getNamesExUID,CLIENT)
F(cxp_fnc_novoDonator,CLIENT)
F(cxp_fnc_pickupAction,SERVER)
// CXPSKT
F(CXPSKT_fnc_dataQuery,CLIENT)
F(CXPSKT_fnc_insertPlayerInfo,CLIENT)
F(CXPSKT_fnc_requestReceived,CLIENT)
F(CXPSKT_fnc_updateRequest,CLIENT)
// CXPSV
F(CXPSV_fnc_clientGangKick,CLIENT)
F(CXPSV_fnc_clientGangLeader,CLIENT)
F(CXPSV_fnc_clientGangLeft,CLIENT)
F(CXPSV_fnc_clientGetKey,CLIENT)
F(CXPSV_fnc_clientMessage,CLIENT)
/* Funcoes Servidor CXP */
// BIS
F(BIS_fnc_execVM,SERVER)
// CXPDB
F(CXPDB_fnc_insertRequest,SERVER)
F(CXPDB_fnc_queryRequest,SERVER)
F(CXPDB_fnc_updatePartial,SERVER)
F(CXPDB_fnc_updateRequest,SERVER)
F(CXPDB_fnc_cellPhoneRequest,SERVER)
F(CXPDB_fnc_saveCellPhone,SERVER)
F(CXPDB_fnc_getRealTime,SERVER)
F(CXPDB_fnc_insertDoadores,SERVER)
// cxp
F(cxp_fnc_jailSys,SERVER)
F(cxp_fnc_wantedAdd,SERVER)
F(cxp_fnc_wantedBounty,SERVER)
F(cxp_fnc_wantedCrimes,SERVER)
F(cxp_fnc_wantedFetch,SERVER)
F(cxp_fnc_wantedProfUpdate,SERVER)
F(cxp_fnc_wantedRemove,SERVER)
// CXPSV
F(CXPSV_fnc_addContainer,SERVER)
F(CXPSV_fnc_addHouse,SERVER)
F(CXPSV_fnc_chopShopSell,SERVER)
F(CXPSV_fnc_cleanupRequest,SERVER)
F(CXPSV_fnc_deleteDBContainer,SERVER)
F(CXPSV_fnc_getVehicles,SERVER)
F(CXPSV_fnc_insertGang,SERVER)
F(CXPSV_fnc_keyManagement,SERVER)
F(CXPSV_fnc_manageSC,SERVER)
F(CXPSV_fnc_removeGang,SERVER)
F(CXPSV_fnc_sellHouse,SERVER)
F(CXPSV_fnc_sellHouseContainer,SERVER)
F(CXPSV_fnc_spawnVehicle,SERVER)
F(CXPSV_fnc_spikeStrip,SERVER)
F(CXPSV_fnc_updateGang,SERVER)
F(CXPSV_fnc_updateHouseContainers,SERVER)
F(CXPSV_fnc_updateHouseTrunk,SERVER)
F(CXPSV_fnc_vehicleCreate,SERVER)
F(CXPSV_fnc_vehicleDelete,SERVER)
F(CXPSV_fnc_vehicleStore,SERVER)
F(CXPSV_fnc_vehicleUpdate,SERVER)
F(CXPSV_fnc_handleBlastingCharge,SERVER)
F(CXPSV_fnc_houseGarage,SERVER)
F(CXPSV_fnc_insureCar,SERVER)
F(CXPSV_fnc_vAHupdate,SERVER)
F(CXPSV_fnc_vAHinit,SERVER)
F(CXPSV_fnc_adjustPrices,SERVER)
F(CXPSV_fnc_donoCartel,SERVER)
F(CXPSV_fnc_addMorteListaSv,SERVER)
F(CXPSV_fnc_rmMorteListaSv,SERVER)
F(CXPSV_fnc_envListaClient,SERVER)
F(CXPSV_fnc_baseGangueSet,SERVER)
F(CXPSV_fnc_saveBugReported,SERVER)
F(CXPSV_fnc_getNameByUID,SERVER)
F(CXPSV_fnc_getOfflineMemb,SERVER)
/* Funcoes HC CXP */
/*
F(CXPHC_fnc_addContainer,HC)
F(CXPHC_fnc_addHouse,HC)
F(CXPHC_fnc_chopShopSell,HC)
F(CXPHC_fnc_deleteDBContainer,HC)
F(CXPHC_fnc_getVehicles,HC)
F(CXPHC_fnc_houseGarage,HC)
F(CXPHC_fnc_insertGang,HC)
F(CXPHC_fnc_insertRequest,HC)
F(CXPHC_fnc_insertVehicle,HC)
F(CXPHC_fnc_jailSys,HC)
F(CXPHC_fnc_keyManagement,HC)
F(CXPHC_fnc_queryRequest,HC)
F(CXPHC_fnc_removeGang,HC)
F(CXPHC_fnc_sellHouse,HC)
F(CXPHC_fnc_sellHouseContainer,HC)
F(CXPHC_fnc_spawnVehicle,HC)
F(CXPHC_fnc_spikeStrip,HC)
F(CXPHC_fnc_insureCar,HC)
F(CXPHC_fnc_cellPhoneRequest,HC)
F(CXPHC_fnc_saveCellPhone,HC)
F(CXPHC_fnc_updateGang,HC)
F(CXPHC_fnc_updateHouseContainers,HC)
F(CXPHC_fnc_updateHouseTrunk,HC)
F(CXPHC_fnc_updatePartial,HC)
F(CXPHC_fnc_updateRequest,HC)
F(CXPHC_fnc_vehicleCreate,HC)
F(CXPHC_fnc_vehicleDelete,HC)
F(CXPHC_fnc_vehicleStore,HC)
F(CXPHC_fnc_vehicleUpdate,HC)
F(CXPHC_fnc_wantedAdd,HC)
F(CXPHC_fnc_wantedBounty,HC)
F(CXPHC_fnc_wantedCrimes,HC)
F(CXPHC_fnc_wantedFetch,HC)
F(CXPHC_fnc_wantedProfUpdate,HC)
F(CXPHC_fnc_wantedRemove,HC)*/
/* Funcoes Globais (Cliente/Servidor) CXP */
// BIS
F(BIS_fnc_effectKilledAirDestruction,ANYONE)
F(BIS_fnc_effectKilledSecondaries,ANYONE)
F(BIS_fnc_setTask,ANYONE)
F(BIS_fnc_deletetask,ANYONE)
F(BIS_fnc_holdActionAdd,ANYONE)
// cxp
F(cxp_fnc_animate,ANYONE)
F(cxp_fnc_animSync,ANYONE)
F(cxp_fnc_animDynSync,ANYONE)
F(cxp_fnc_broadcast,ANYONE)
F(cxp_fnc_colorVehicle,ANYONE)
F(cxp_fnc_corpse,ANYONE)
F(cxp_fnc_demoChargeTimer,ANYONE)
F(cxp_fnc_jumpFnc,ANYONE)
F(cxp_fnc_lockVehicle,ANYONE)
F(cxp_fnc_pulloutVeh,ANYONE)
F(cxp_fnc_say3D,ANYONE)
F(cxp_fnc_setFuel,ANYONE)
F(cxp_fnc_simDisable,ANYONE)
F(cxp_fnc_recebListClient,ANYONE)
F(cxp_fnc_deleteClienteProx,ANYONE)
F(cxp_fnc_pacienteAceito,ANYONE)
F(cxp_fnc_rmCorpseArr,ANYONE)
F(cxp_fnc_avisarPvpEntorno,ANYONE)
F(cxp_fnc_showRRMessage,ANYONE)
// CXPSV
F(CXPSV_fnc_receiveClientFunct,ANYONE)
};
class Commands {
mode = 1;
jip = 0;
F(addHandgunItem,ANYONE)
F(addMagazine,ANYONE)
F(addPrimaryWeaponItem,ANYONE)
F(addWeapon,ANYONE)
F(setFuel,ANYONE)
};
};
|
#include <iostream>
using namespace std;
int Feb(int a)
{
if (a == 0)
return 0;
else
if (a == 1)
return 1;
else
return Feb(a - 1) + Feb(a - 2);
}
int main()
{
int t = 0;
cin >> t;
cout << Feb(t);
return 0;
}
|
//
// Created by peto184 on 27-Oct-17.
//
#include "background.h"
std::unique_ptr<ppgso::Mesh> Background::mMesh;
std::unique_ptr<ppgso::Shader> Background::mShader;
std::unique_ptr<ppgso::Texture> Background::mTexture;
Background::Background(){
if (!mShader) mShader = std::make_unique<ppgso::Shader>(texture_vert_glsl, texture_frag_glsl);
if (!mTexture) mTexture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("background.bmp"));
if (!mMesh) mMesh = std::make_unique<ppgso::Mesh>("quad.obj");
}
bool Background::update(Scene &scene, float dt) {
mTextureOffset.x -= dt/20.0f;
mModelMatrix = glm::translate(mat4(1.0f), mPosition)
* glm::rotate(mat4(1.0f), 0.0f, mRotation)
* glm::scale(mat4(1.0f), mScale);
return false;
}
void Background::render(Scene &scene) {
// Disable writing to the depth buffer so we render a "background"
glDepthMask(GL_FALSE);
// NOTE: this object does not use camera, just renders the entire quad as is
(*mShader).use();
// Pass UV mapping offset to the shader
(*mShader).setUniform("TextureOffset", mTextureOffset);
// Render mesh, not using any projections, we just render in 2D
(*mShader).setUniform("ModelMatrix", mModelMatrix);
(*mShader).setUniform("ViewMatrix", mat4{});
(*mShader).setUniform("ProjectionMatrix", mat4{});
(*mShader).setUniform("Texture", *mTexture);
(*mMesh).render();
glDepthMask(GL_TRUE);
}
|
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#include "draw.hpp"
#include "ui/ElementLinked.hpp"
using namespace ui;
ElementLinked::ElementLinked(){
set_parent(0);
set_child(0);
}
ElementLinked::ElementLinked(ElementLinked * parent, ElementLinked * child) {
// TODO Auto-generated constructor stub
set_parent(parent);
set_child(child);
}
Element * ElementLinked::handle_event(const Event & event, const DrawingAttr & attr){
switch(event.type()){
case Event::SETUP:
if( parent() ){
//set_dim(parent());
}
if( child() ){
child()->handle_event(event, attr);
}
break;
default:
break;
}
return Element::handle_event(event, attr);
}
|
#include "xr_xml.h"
namespace xr
{
int xml_t::open(const char *name)
{
if (NULL != this->doc_ptr)
{
ALERT_LOG("doc_ptr not null");
return FAIL;
}
//this->doc_ptr = xmlReadFile(name, "UTF-8", XML_PARSE_RECOVER); //解析文件
xmlKeepBlanksDefault(0);
this->doc_ptr = xmlReadFile(name, 0, XML_PARSE_NOBLANKS);
//m_doc = xmlParseFile(pszFilePath);
//检查解析文档是否成功,如果不成功,libxml将指一个注册的错误并停止。
//一个常见错误是不适当的编码。XML标准文档除了用UTF-8或UTF-16外还可用其它编码保存。
//如果文档是这样,libxml将自动地为你转换到UTF-8。更多关于XML编码信息包含在XML标准中.
if (NULL == this->doc_ptr)
{
ALERT_LOG("open fail:%s", name);
return FAIL;
}
this->node_ptr = xmlDocGetRootElement(this->doc_ptr); //确定文档根元素
if (NULL == this->node_ptr)
{
ALERT_LOG("root element null");
this->close();
return FAIL;
}
return SUCC;
}
void xml_t::close()
{
if (NULL != this->doc_ptr)
{
xmlFreeDoc(this->doc_ptr);
this->doc_ptr = NULL;
this->node_ptr = NULL;
}
}
int xml_t::strcmp(const xmlNodePtr node_ptr, const char *name)
{
return xmlStrcmp(node_ptr->name, (const xmlChar *)name);
}
void xml_t::move2children_node()
{
this->node_ptr = this->node_ptr->xmlChildrenNode;
}
void xml_t::move2next_node()
{
this->node_ptr = this->node_ptr->next;
}
xml_t::xml_t()
{
this->doc_ptr = NULL;
this->node_ptr = NULL;
}
xml_t::~xml_t()
{
this->close();
}
uint32_t xml_t::get_prop(xmlNodePtr cur, const char *prop, manip_t manip /*= std::dec*/)
{
uint32_t t = 0;
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
else
{
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
iss >> manip >> t;
xmlFree(str);
}
return t;
}
uint32_t xml_t::get_prop_def(xmlNodePtr cur, const char *prop, const uint32_t def, manip_t manip /*= std::dec*/)
{
uint32_t t = 0;
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
t = def;
}
else
{
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
iss >> manip >> t;
xmlFree(str);
}
return t;
}
} // namespace xr
|
#pragma once
#include <vector>
#include <array>
#include <cassert>
#include <iostream>
#include <unordered_set>
#include <algorithm>
#include "defs.hpp"
#include "tile.hpp"
#include "citygen.hpp"
#include "overlay.hpp"
namespace ecs {
struct Ent;
}
struct City {
using ents_t = unordered_set<ecs::Ent*>;
int xsz;
int ysz;
Overlay<Tile> tiles;
Overlay<ents_t> ents;
Overlay<char> designs;
Overlay<struct Furniture*> furniture;
std::vector<struct Room*> rooms;
int getXSize() const;
int getYSize() const;
Tile tile(int x, int y) const;
Tile& tile(int x, int y);
const ents_t& ent(int x, int y) const;
ents_t& ent(int x, int y);
void add_ent(int x, int y, ecs::Ent* e);
void del_ent(int x, int y, ecs::Ent* e);
/// Insert a room. Fast Amortized O(1).
/// @pre Room has not already been added (asserted).
/// @pre Room != nullptr (asserted).
void add_room(struct Room* r);
/// Delete a room by pointer. Fast O(R).
/// @pre Room has been added (asserted).
/// @pre Room != nullptr (asserted).
void del_room(struct Room* r);
/// Place a piece of furniture. Fast O(1).
/// @pre Location has no furniture.
/// @post Location has furniture f.
void add_furniture(struct Furniture* f);
/// Remove a piece of furniture. Fast O(1).
/// @pre Location has furniture f.
/// @post Location has no furniture.
void del_furniture(struct Furniture* f);
/// Find all furniture within a rectangle. Fast O(w*h).
/// @return List of found furniture.
std::vector<struct Furniture*> find_furniture(int x, int y, int w, int h);
/// Convenience overload for find_furniture(x,y,w,h).
/// @pre Rect r is associated with this city (not checked).
/// @return List of found furniture
std::vector<struct Furniture*> find_furniture(Rect r);
/// Find all rooms containing a point. Fast O(R).
/// @return List of found rooms
std::vector<struct Room*> find_rooms(int x, int y);
/// Check that x and y are within the current city
bool check(int x, int y) const;
/// Toggle whether the wall at (x, y) should have a dig job.
void toggle_dig_wall(int x, int y);
/// Toggle whether the wall at (x, y) should have a construct job.
void toggle_build_wall(int x, int y);
/// Replace a wall at (x, y) with empty ground.
void remove_wall(int x, int y);
/// Replace the ground at (x, y) with a wall.
void add_wall(int x, int y);
/// Resize the city. This should not be called after initialization.
void resize(int x, int y);
/// Selects a random walkable tile in the city
point random_point();
/// Default constructor. Doesn't generate a city.
City();
/// Constructor: uses the city properties to generate a city
void generate(struct CityProperties const& cityP);
};
wistream& operator>>(wistream& is, City& city);
|
#include "Game.h"
#include <iostream>
#include <fstream>
#include <string>
Game::Game() {
std::string init_stage_data;
//-----------------------
// ステージデータ読み込み
//-----------------------
loadStageData("stageData.txt", init_stage_data);
//---------------
// ステージ初期化
//---------------
stage_ = std::make_unique<Stage>(init_stage_data);
//-----------------
// プレイヤー初期化
//-----------------
auto player_position = init_stage_data.find(PLAYER_CHAR);
player_ = std::make_unique<Player>(player_position % (stage_->Width() + 1), player_position / (stage_->Width() + 1));
}
void Game::getInput() {
std::cin >> input_;
}
void Game::update() {
player_->update(input_, *stage_);
}
void Game::draw() {
std::string drawing_area;
stage_->draw(drawing_area);
player_->draw(*stage_, drawing_area);
for (unsigned int i = 0; i < stage_->Height(); i++)
std::cout << drawing_area.substr(stage_->Width() * i, stage_->Width()) << std::endl;
std::cout << "a:left d:right w:up s:down. command?" << std::endl;
}
void Game::loadStageData(const std::string& file_name, std::string& stage_data) {
//--------------------------------
// ステージデータファイルの読み込み
//--------------------------------
std::ifstream fin(file_name);
if (fin.fail()) {
std::cout << "Error!!: Can't read " << file_name << "." << std::endl;
char tmp;
std::cin >> tmp;
exit(EXIT_FAILURE);
}
fin.seekg(0, std::ios::end);
auto file_size = static_cast<size_t>(fin.tellg());
fin.seekg(0, std::ios::beg);
auto buf = std::make_unique<char[]>(file_size);
fin.read(buf.get(), file_size);
stage_data = buf.get();
}
|
#include<stdio.h>
main(){
int i;
int *p;
p=&i;
*p=17;
printf("%d\n",i);
}
|
#include "Globals.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleInput.h"
#include "ModuleParticles.h"
#include "ModuleRender.h"
#include "ModuleCollision.h"
#include "ModuleAudio.h"
#include "ModuleFadeToBlack.h"
#include "ModulePlayer.h"
#include "ModuleEnemies.h"
#include "ModuleUI.h"
#include "SDL\include\SDL_timer.h"
#include "SDL\include\SDL_render.h"
#include "ModuleAyin.h"
#include "ModuleAyinArrow.h"
#include "ModuleAyinUltimate.h"
#include "ModuleSceneTemple.h"
#include "CharSelec.h"
#include "ModuleInterface.h"
ModuleAyin::ModuleAyin()
{
graphics = NULL;
current_animation = NULL;
position.x = 10;
position.y = 20;
// idle animation
idle.PushBack({ 63, 1, 33, 33 });
idle.PushBack({ 101, 1, 33, 33 });
idle.PushBack({ 29, 1, 33, 33 });
idle.speed = 0.20f;
// walk backward animation
backward.PushBack({ 88, 37, 21, 33 });
backward.PushBack({ 114, 37, 20, 33 });
backward.PushBack({ 139, 37, 20, 33 });
backward.speed = 0.10f;
//Intermediate
intermediate.PushBack({ 4, 39, 31, 33 });
intermediate.PushBack({ 38, 39, 24, 32 });
intermediate.PushBack({ 64, 37, 19, 32 });
intermediate.speed = 0.10f;
//Intermediate return
intermediate_return.PushBack({ 64, 37, 19, 32 });
intermediate_return.PushBack({ 38, 39, 24, 32 });
intermediate_return.PushBack({ 4, 39, 31, 33 });
intermediate_return.speed = 0.10f;
//Spin
spin.PushBack({ 145,2,23,32 });
spin.PushBack({ 172,2,15,32 });
spin.PushBack({ 189,1,21,33 });
spin.PushBack({ 212,2,15,32 });
spin.PushBack({ 145,2,23,32 });
spin.PushBack({ 172,2,15,32 });
spin.PushBack({ 189,1,21,33 });
spin.PushBack({ 212,2,15,32 });
spin.speed = 0.15f;
//Spin Circle
spin_circle.PushBack({ 91,342,22,23 });
spin_circle.PushBack({ 114,338,30,31 });
spin_circle.PushBack({ 145,338,32,32 });
spin_circle.PushBack({ 178,338,32,32 });
spin_circle.PushBack({ 211,338,32,32 });
spin_circle.PushBack({ 245,338,32,32 });
spin_circle.PushBack({ 279,338,32,32 });
spin_circle.PushBack({ 313,338,32,32 });
spin_circle.speed = 0.3f;
//Death
death_circle.PushBack({ 153,0, 130, 130 });
death_circle.PushBack({ 298,0, 130, 130 });
death_circle.PushBack({ 153,0, 130, 130 });
death_circle.PushBack({ 298,0, 130, 130 });
death_circle.PushBack({ 153,0, 130, 130 });
death_circle.PushBack({ 298,0, 130, 130 });
death_circle.PushBack({ 153,0, 130, 130 });
death_circle.PushBack({ 1,0, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 1,0, 130, 130 });
death_circle.PushBack({ 1,0, 130, 130 });
death_circle.PushBack({ 153,0, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 2,153, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 143,153, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 143,153, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 300,153, 130, 130 });
death_circle.PushBack({});
death_circle.PushBack({ 2,292, 130, 130 });
death_circle.speed = 0.8f;
//Death Player
death.x = 323;
death.y = 56;
death.w = 27;
death.h = 26;
//Charging
charging.PushBack({ 3, 108, 22, 32 });
charging.PushBack({ 27, 110, 18, 32 });
charging.PushBack({ 47, 110, 21, 32 });
charging.speed = 0.10f;
//Charge
charge.PushBack({ 79, 108, 21, 32 });
charge.PushBack({ 100, 108, 21, 32 });
charge.PushBack({ 124, 108, 21, 32 });
charge.PushBack({ 147, 108, 21, 32 });
charge.speed = 0.10f;
//Spin Decharging
spin_decharging.PushBack({ 171, 107, 29, 32 });
spin_decharging.PushBack({ 204, 108, 17, 32 });
spin_decharging.speed = 0.15f;
/*spin_decharging.loop = false;*/
//Decharging
decharging.PushBack({ 225, 110, 35, 30 });
decharging.PushBack({ 3, 148, 34, 30 });
decharging.PushBack({ 39, 149, 33, 30 });
decharging.speed = 0.15f;
return_idle.PushBack({ 76, 149, 31, 30 });
return_idle.PushBack({ 109, 149, 28, 30 });
return_idle.PushBack({ 141, 149, 27, 30 });
return_idle.PushBack({ 170, 149, 28, 30 });
return_idle.PushBack({ 202, 148, 28, 30 });
return_idle.PushBack({ 233, 148, 26, 30 });
return_idle.speed = 0.17f;
//Ultimate Ayin
ulti_ayin.PushBack({ 187, 444, 20, 33 });
ulti_ayin.PushBack({ 213, 444, 16, 32 });
ulti_ayin.PushBack({ 234, 445, 22, 32 });
ulti_ayin.PushBack({ 259, 444, 30, 33 });
ulti_ayin.PushBack({ 292, 445, 18, 33 });
ulti_ayin.PushBack({ 313, 448, 35, 30 });
ulti_ayin.loop = false;
ulti_ayin.speed = 0.12f;
}
ModuleAyin::~ModuleAyin()
{}
// Load assets
bool ModuleAyin::Start()
{
LOG("Loading player textures");
graphics = App->textures->Load("assets/sprites/characters/ayin/Ayin_Spritesheet2.png");
player_death = App->textures->Load("assets/sprites/characters/death_player/Death_Player.png");
coll = App->collision->AddCollider({ (int)position.x, (int)position.y, 32, 32 }, COLLIDER_PLAYER);
if (App->charmenu->P1ayin) {
position.x = (App->render->camera.x) / SCREEN_SIZE - 20;
position.y = (App->render->camera.y) / SCREEN_SIZE + 100;
}
else if (App->charmenu->P2ayin) {
position.x = (App->render->camera.x) / SCREEN_SIZE - 20;
position.y = (App->render->camera.y) / SCREEN_SIZE + 155;
}
state = SPAWN_PLAYER_2;
time = true;
destroyed = false;
App->ayin_arrow->Enable();
App->ulti_ayin->Enable();
App->inter->num_life_ayin = 3;
App->inter->num_ult_ayin = 2;
return true;
}
// Unload assets
bool ModuleAyin::CleanUp()
{
LOG("Unloading player");
if (coll != nullptr)
coll->to_delete = true;
App->textures->Unload(graphics);
App->textures->Unload(player_death);
App->ayin_arrow->Disable();
App->ulti_ayin->Disable();
App->inter->game_over_ayin = true;
return true;
}
update_status ModuleAyin::Update()
{
if (App->charmenu->P1ayin==true) controller_state == AYN1;
if (App->charmenu->P2ayin==true) controller_state == AYN2;
//Create bool variables
bool pressed_I = App->input->keyboard[SDL_SCANCODE_I] == KEY_STATE::KEY_REPEAT;
bool pressed_J = App->input->keyboard[SDL_SCANCODE_J] == KEY_STATE::KEY_REPEAT;
bool pressed_K = App->input->keyboard[SDL_SCANCODE_K] == KEY_STATE::KEY_REPEAT;
bool pressed_L = App->input->keyboard[SDL_SCANCODE_L] == KEY_STATE::KEY_REPEAT;
bool gamepad_UP = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE;
bool gamepad_DOWN = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) > CONTROLLER_DEAD_ZONE;
bool gamepad_RIGHT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE;
bool gamepad_LEFT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE;
bool gamepad_UP2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE;
bool gamepad_DOWN2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTY) > CONTROLLER_DEAD_ZONE;
bool gamepad_RIGHT2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE;
bool gamepad_LEFT2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE;
bool shot_space = App->input->keyboard[SDL_SCANCODE_Y] == KEY_STATE::KEY_DOWN;
speed = 1.25;
//Power Up Limits
if (power_up < 0) {
power_up = 0;
}
if (power_up > 4) {
power_up = 4;
}
//check state
CheckState();
//state actions
PerformActions();
//Inputs
if (App->input->gamepad2==NULL) {
if (input)
{
if (pressed_J || App->input->controller_Dpad_LEFT == KEY_STATE::KEY_REPEAT) {
position.x -= speed;
}
if (pressed_I || App->input->controller_Dpad_UP == KEY_STATE::KEY_REPEAT) {
position.y -= speed;
}
if (pressed_L || App->input->controller_Dpad_RIGHT == KEY_STATE::KEY_REPEAT) {
position.x += speed;
}
if (pressed_K || App->input->controller_Dpad_DOWN == KEY_STATE::KEY_REPEAT) {
position.y += speed;
}
if (App->input->keyboard[SDL_SCANCODE_L] == KEY_STATE::KEY_DOWN || App->input->controller_Y_button == KEY_STATE::KEY_DOWN) {
state = ULTI_AYIN;
App->inter->num_ult_ayin--;
App->particles->AddEmmiter(AJIN_ULT, &position);
}
if (shot_space /*|| App->input->keyboard[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_REPEAT*/ || App->input->controller_A_button == KEY_STATE::KEY_DOWN) {
LOG("Shooting bullets");
/*current_bullet_time = SDL_GetTicks() - bullet_on_entry;
if (current_bullet_time > 100) {
bullet_on_entry = SDL_GetTicks();*/
aux1++;
switch (aux1) {
case 0:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot1, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot1_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot1_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
LOG("Shoot 1");
break;
case 1:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot2_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot2_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
break;
case 2:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot3_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot3_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
aux1 = 0;
break;
}
}
}
}
else {
if (input)
{
if (pressed_J || App->input->controller2_Dpad_LEFT == KEY_STATE::KEY_REPEAT) {
position.x -= speed;
}
if (pressed_I || App->input->controller2_Dpad_UP == KEY_STATE::KEY_REPEAT) {
position.y -= speed;
}
if (pressed_L || App->input->controller2_Dpad_RIGHT == KEY_STATE::KEY_REPEAT) {
position.x += speed;
}
if (pressed_K || App->input->controller2_Dpad_DOWN == KEY_STATE::KEY_REPEAT) {
position.y += speed;
}
if (App->input->keyboard[SDL_SCANCODE_L] == KEY_STATE::KEY_DOWN || App->input->controller2_Y_button == KEY_STATE::KEY_DOWN) {
state = ULTI_AYIN;
App->inter->num_ult_ayin--;
App->particles->AddEmmiter(AJIN_ULT, &position);
}
if (shot_space /*|| App->input->keyboard[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_REPEAT*/ || App->input->controller2_A_button == KEY_STATE::KEY_DOWN) {
LOG("Shooting bullets");
/*current_bullet_time = SDL_GetTicks() - bullet_on_entry;
if (current_bullet_time > 100) {
bullet_on_entry = SDL_GetTicks();*/
aux1++;
switch (aux1) {
case 0:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot1, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot1_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot1_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
LOG("Shoot 1");
break;
case 1:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot2_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot2_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
break;
case 2:
if (power_up == 0 || power_up == 1) {
App->particles->AddParticle(App->particles->ayin_shoot3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 2) {
App->particles->AddParticle(App->particles->ayin_shoot3_2, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
else if (power_up == 3 || power_up == 4) {
App->particles->AddParticle(App->particles->ayin_shoot3_3, position.x, position.y - 20, COLLIDER_PLAYER_AYIN_SHOT, PARTICLE_SHOT_AYIN);
}
aux1 = 0;
break;
}
}
}
}
//Fade
SDL_SetTextureAlphaMod(graphics, alpha_player);
//Set spin posotion
if (spin_pos) {
aux_spin.x = position.x - 4;
aux_spin.y = position.y - 32;
//spin_pos = false;
}
if (death_pos) {
aux_death.x = position.x - 40;
aux_death.y = position.y - 70;
death_pos = false;
}
// Draw everything --------------------------------------
SDL_Rect r = current_animation->GetCurrentFrame();
if (!check_death) {
if (check_spawn) {
position.x++;
coll->SetPos(App->render->camera.x, App->render->camera.y - 32);
}
else {
coll->SetPos(position.x, position.y - 32);
}
App->render->Blit(graphics, position.x, position.y - r.h, &r);
}
else {
App->render->Blit(graphics, position.x, position.y - 32, &death);
coll->SetPos(App->render->camera.x, App->render->camera.y - 32);
position.x -= 1;
position.y += 3;
}
if (coll->CheckCollision(App->scene_temple->coll_left->rect)) {
position.x = (App->render->camera.x / SCREEN_SIZE);
}
if (coll->CheckCollision(App->scene_temple->coll_right->rect)) {
position.x = (SCREEN_WIDTH + App->render->camera.x / SCREEN_SIZE) - 33;
}
if (coll->CheckCollision(App->scene_temple->coll_up->rect)) {
position.y = 35;
}
if (coll->CheckCollision(App->scene_temple->coll_down->rect)) {
position.y = SCREEN_HEIGHT - 4;
}
return UPDATE_CONTINUE;
}
void ModuleAyin::CheckState()
{
//Create Input Bools
bool pressed_J = App->input->keyboard[SDL_SCANCODE_J] == KEY_STATE::KEY_REPEAT;
bool pressed_I = App->input->keyboard[SDL_SCANCODE_I] == KEY_STATE::KEY_REPEAT;
bool press_J = App->input->keyboard[SDL_SCANCODE_J] == KEY_STATE::KEY_DOWN;
bool press_I = App->input->keyboard[SDL_SCANCODE_I] == KEY_STATE::KEY_DOWN;
bool release_J = App->input->keyboard[SDL_SCANCODE_J] == KEY_STATE::KEY_UP;
bool release_I = App->input->keyboard[SDL_SCANCODE_I] == KEY_STATE::KEY_UP;
bool released_I = App->input->keyboard[SDL_SCANCODE_I] == KEY_STATE::KEY_IDLE;
bool released_J = App->input->keyboard[SDL_SCANCODE_J] == KEY_STATE::KEY_IDLE;
bool gamepad_UP = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE;
bool gamepad_RIGHT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE;
bool gamepad_LEFT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE;
bool gamepad_UP2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE;
bool gamepad_RIGHT2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE;
bool gamepad_LEFT2 = SDL_GameControllerGetAxis(App->input->gamepad2, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE;
//switch (controller_state) {
//case AYN1:
// switch (state)
// {
// case SPAWN_PLAYER_2:
// if (time) {
// time_on_entry = SDL_GetTicks();
// time = false;
// }
// current_time = SDL_GetTicks() - time_on_entry;
// if (current_time > 1500) {
// state = IDLE_2;
// }
// power_up = 0;
// break;
// case IDLE_2:
// if (press_I || press_J || App->input->controller_Dpad_UP==KEY_STATE::KEY_DOWN || App->input->controller_Dpad_LEFT==KEY_STATE::KEY_DOWN ) {
// state = GO_BACKWARD_2;
// }
// break;
// case GO_BACKWARD_2:
// if (release_I || gamepad_UP ) {
// state = BACK_IDLE_2;
// }
// if (release_J || gamepad_LEFT ) {
// state = BACK_IDLE_2;
// }
// if (current_animation->Finished()) {
// intermediate.Reset();
// state = BACKWARD_2;
// }
// break;
// case BACKWARD_2:
// if (release_I || release_J || App->input->controller_Dpad_UP == KEY_STATE::KEY_IDLE || App->input->controller_Dpad_LEFT == KEY_STATE::KEY_IDLE) {
// if (released_I || released_J || App->input->controller_Dpad_UP==KEY_STATE::KEY_IDLE || App->input->controller_Dpad_LEFT==KEY_STATE::KEY_IDLE ) {
// state = BACK_IDLE_2;
// /*if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_UP || gamepad_UP) {
// if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE || gamepad_LEFT) {
// state = BACK_IDLE;
// }
// }
// if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_UP || gamepad_LEFT) {
// if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE || gamepad_UP) {
// state = BACK_IDLE;*/
// }
// }
// break;
// case BACK_IDLE_2:
// if (pressed_I || App->input->controller_Dpad_UP==KEY_STATE::KEY_REPEAT ) {
// state = BACK_IDLE_2;
// }
// if (pressed_J || App->input->controller_Dpad_LEFT == KEY_STATE::KEY_REPEAT) {
// state = BACK_IDLE_2;
// }
// if (current_animation->Finished()) {
// intermediate.Reset();
// state = IDLE_2;
// }
// break;
// case ULTI_AYIN:
// if (ulti_ayin.Finished()) {
// ulti_ayin.Reset();
// state = IDLE_2;
// }
// case SPIN_2:
// if (spin.Finished()) {
// spin.Reset();
// spin_circle.Reset();
// spin_pos = false;
// state = IDLE_2;
// }
// break;
// case DEATH_2:
// if (position.y > SCREEN_HEIGHT + 80) {
// state = POST_DEATH_2;
// }
// break;
// /*case SPIN_DECHARGING_AYIN:
// if (spin_decharging.Finished()) {
// state = DECHARGING_AYIN;
// }*/
// case POST_DEATH_2:
// if (App->inter->num_life_ayin > 0) {
// position.x = (App->render->camera.x) / SCREEN_SIZE - 20;
// position.y = (App->render->camera.y) / SCREEN_SIZE + 100;
// time = true;
// state = SPAWN_PLAYER_2;
// }
// break;
// }
// break;
//case AYN2:
switch (state)
{
case SPAWN_PLAYER_2:
if (time) {
time_on_entry = SDL_GetTicks();
time = false;
}
current_time = SDL_GetTicks() - time_on_entry;
if (current_time > 1500) {
state = IDLE_2;
}
power_up = 0;
break;
case IDLE_2:
if (press_I || press_J || App->input->controller2_Dpad_UP==KEY_STATE::KEY_DOWN || App->input->controller2_Dpad_LEFT==KEY_STATE::KEY_DOWN ) {
state = GO_BACKWARD_2;
}
break;
case GO_BACKWARD_2:
if (release_I || App->input->controller2_Dpad_UP==KEY_STATE::KEY_UP ) {
state = BACK_IDLE_2;
}
if (release_J || App->input->controller2_Dpad_LEFT == KEY_STATE::KEY_UP) {
state = BACK_IDLE_2;
}
if (current_animation->Finished()) {
intermediate.Reset();
state = BACKWARD_2;
}
break;
case BACKWARD_2:
if (release_I || release_J || App->input->controller2_Dpad_UP == KEY_STATE::KEY_UP || App->input->controller2_Dpad_LEFT == KEY_STATE::KEY_UP) {
if (released_I || released_J || App->input->controller2_Dpad_UP == KEY_STATE::KEY_IDLE || App->input->controller2_Dpad_LEFT == KEY_STATE::KEY_IDLE) {
state = BACK_IDLE_2;
/*if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_UP || gamepad_UP) {
if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE || gamepad_LEFT) {
state = BACK_IDLE;
}
}
if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_UP || gamepad_LEFT) {
if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE || gamepad_UP) {
state = BACK_IDLE;*/
}
}
break;
case BACK_IDLE_2:
if (pressed_I || App->input->controller2_Dpad_UP==KEY_REPEAT ) {
state = BACK_IDLE_2;
}
if (pressed_J || App->input->controller2_Dpad_LEFT == KEY_REPEAT) {
state = BACK_IDLE_2;
}
if (current_animation->Finished()) {
intermediate.Reset();
state = IDLE_2;
}
break;
case ULTI_AYIN:
if (ulti_ayin.Finished()) {
ulti_ayin.Reset();
state = IDLE_2;
}
case SPIN_2:
if (spin.Finished()) {
spin.Reset();
spin_circle.Reset();
spin_pos = false;
state = IDLE_2;
}
break;
case DEATH_2:
if (position.y > SCREEN_HEIGHT + 80) {
state = POST_DEATH_2;
}
break;
/*case SPIN_DECHARGING_AYIN:
if (spin_decharging.Finished()) {
state = DECHARGING_AYIN;
}*/
case POST_DEATH_2:
if (App->inter->num_life_ayin > 0) {
position.x = (App->render->camera.x) / SCREEN_SIZE - 20;
position.y = (App->render->camera.y) / SCREEN_SIZE + 100;
time = true;
state = SPAWN_PLAYER_2;
}
break;
}
//switch (state)
//{
//case SPAWN_PLAYER_2:
// if (time) {
// time_on_entry = SDL_GetTicks();
// time = false;
// }
// current_time = SDL_GetTicks() - time_on_entry;
// if (current_time > 1500) {
// state = IDLE_2;
// }
// power_up = 0;
// break;
//case IDLE_2:
// if (press_I || press_J || gamepad_UP || gamepad_LEFT || gamepad_UP2 || gamepad_LEFT2) {
// state = GO_BACKWARD_2;
// }
// break;
//case GO_BACKWARD_2:
// if (release_I || gamepad_UP || gamepad_UP2) {
// state = BACK_IDLE_2;
// }
// if (release_J || gamepad_LEFT || gamepad_LEFT2) {
// state = BACK_IDLE_2;
// }
// if (current_animation->Finished()) {
// intermediate.Reset();
// state = BACKWARD_2;
// }
// break;
//case BACKWARD_2:
// if (release_I || release_J || gamepad_UP || gamepad_LEFT || gamepad_UP2 || gamepad_LEFT2) {
// if (released_I || released_J || gamepad_UP || gamepad_LEFT || gamepad_UP2 || gamepad_LEFT2) {
// state = BACK_IDLE_2;
// /*if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_UP || gamepad_UP) {
// if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE || gamepad_LEFT) {
// state = BACK_IDLE;
// }
// }
// if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_UP || gamepad_LEFT) {
// if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE || gamepad_UP) {
// state = BACK_IDLE;*/
// }
// }
// break;
//case BACK_IDLE_2:
// if (pressed_I || gamepad_UP || gamepad_UP2) {
// state = BACK_IDLE_2;
// }
// if (pressed_J || gamepad_LEFT || gamepad_LEFT2) {
// state = BACK_IDLE_2;
// }
// if (current_animation->Finished()) {
// intermediate.Reset();
// state = IDLE_2;
// }
// break;
//case ULTI_AYIN:
// if (ulti_ayin.Finished()) {
// ulti_ayin.Reset();
// state = IDLE_2;
// }
//case SPIN_2:
// if (spin.Finished()) {
// spin.Reset();
// spin_circle.Reset();
// spin_pos = false;
// state = IDLE_2;
// }
// break;
//case DEATH_2:
// if (position.y > SCREEN_HEIGHT + 80) {
// state = POST_DEATH_2;
// }
// break;
///*case SPIN_DECHARGING_AYIN:
// if (spin_decharging.Finished()) {
// state = DECHARGING_AYIN;
// }*/
//case POST_DEATH_2:
// if (App->inter->num_life_ayin > 0) {
// position.x = (App->render->camera.x) / SCREEN_SIZE - 20;
// position.y = (App->render->camera.y) / SCREEN_SIZE + 100;
// time = true;
// state = SPAWN_PLAYER_2;
// }
//
// break;
//}
}
void ModuleAyin::PerformActions()
{
switch (state) {
case SPAWN_PLAYER_2:
App->inter->game_over_ayin = false;
check_spawn = true;
current_animation = &idle;
blink_time = SDL_GetTicks() - blink_on_entry;
if (blink_time > 10) {
blink_on_entry = SDL_GetTicks();
if (blink) {
alpha_player = 0;
blink = false;
}
else {
alpha_player = 255;
blink = true;
}
}
input = false;
check_death = false;
break;
case IDLE_2:
if (App->render->camera.x > 40000) {
input = false;
}
if (App->render->camera.x < 40000) {
input = true;
}
death_pos = true;
check_spawn = false;
alpha_player = 255;
spin.Reset();
current_animation = &idle;
break;
case GO_BACKWARD_2:
if (intermediate.Finished())
{
intermediate.Reset();
}
current_animation = &intermediate;
break;
case BACKWARD_2:
if (backward.Finished())
backward.Reset();
current_animation = &backward;
break;
case BACK_IDLE_2:
if (intermediate_return.Finished())
intermediate_return.Reset();
current_animation = &intermediate_return;
break;
case CHARGING_AYIN:
if (charging.Finished())
charging.Reset();
current_animation = &charging;
break;
case CHARGE_AYIN:
current_animation = &charge;
break;
case SPIN_DECHARGING_AYIN:
if (spin_decharging.Finished())
spin_decharging.Reset();
current_animation = &spin_decharging;
break;
case DECHARGING_AYIN:
if (decharging.Finished())
decharging.Reset();
current_animation = &decharging;
break;
case RETURN_IDLE_AYIN:
if (return_idle.Finished())
return_idle.Reset();
current_animation = &return_idle;
break;
case ULTI_AYIN:
/*if (ulti_ayin.Finished())
ulti_ayin.Reset();*/
current_animation = &ulti_ayin;
break;
case SPIN_2:
SDL_Rect spin_rect = spin_circle.GetCurrentFrame();
App->render->Blit(graphics, aux_spin.x, aux_spin.y, &spin_rect);
current_animation = &spin;
break;
case DEATH_2:
SDL_Rect death_rect = death_circle.GetCurrentFrame();
power_up = 0;
check_death = true;
input = false;
App->render->Blit(player_death, aux_death.x, aux_death.y, &death_rect, 1.0f);
/*if (explosion) {
App->particles->AddParticle(App->particles->explosion, position.x - 8, position.y - 8);
explosion = false;*/
//}
alpha_player = 255;
break;
case POST_DEATH_2:
if (App->inter->num_life_ayin == 0) {
if (App->inter->score_ayin > 1000) {
App->inter->score_ayin -= 1000;
}
App->ayin->Disable();
}
else {
check_death = false;
}
break;
}
}
|
/************************************************************************
* @project : $rootnamespace$
* @class : $safeitemrootname$
* @version : v1.0.0
* @description :
* @author : $username$
* @creat : $time$
* @revise : $time$
************************************************************************
* Copyright @ OscarShen 2017. All rights reserved.
************************************************************************/
#pragma once
#ifndef SLOTH_TEXT_MESH_DATA_HPP
#define SLOTH_TEXT_MESH_DATA_HPP
#include <sloth.h>
namespace sloth {
class TextMeshData
{
private:
std::shared_ptr<std::vector<float>> m_VertexPositions;
std::shared_ptr<std::vector<float>> m_TexCoords;
public:
TextMeshData(std::shared_ptr<std::vector<float>> vertexPositions, std::shared_ptr<std::vector<float>> texCoords)
: m_VertexPositions(vertexPositions), m_TexCoords(texCoords) {}
inline std::shared_ptr<std::vector<float>> getVertexPositions() const { return m_VertexPositions; }
inline std::shared_ptr<std::vector<float>> getTexCoords() const { return m_TexCoords; }
inline unsigned int getVertexCount() const { return m_VertexPositions->size() / 2; }
};
//typedef typename std::shared_ptr<TextMeshData> TextMeshData_s;
}
#endif // !SLOTH_TEXT_MESH_DATA_HPP
|
#include <iostream>
#include "Array.h"
using namespace std;
void array_main()
{
try
{
Array arr(1, 3, 2);
Array cc_a(3, 3, 1);
Array c_a(arr);
Array ccc_a(cc_a);
cc_a.set(1, 1, 100);
cc_a.set(2, 2, 10);
cc_a.set(0, 2, 7);
// std::cout << cc_a.inv_LU() << std::endl;
// std::cout << cc_a.getDet() << std::endl;
// +
std::cout << "cc_a: " << cc_a << "arr: " << arr << "cc_a + arr: " << cc_a + arr << std::endl;
std::cout << "cc_a: " << cc_a << "cc_a + cc_a: " << cc_a + cc_a << std::endl;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a + e: " << cc_a + 2 << std::endl;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e + cc_a: " << 2 + cc_a << std::endl;
cc_a += arr;
std::cout << "cc_a += arr: " << cc_a << std::endl;
cc_a += cc_a;
std::cout << "cc_a += cc_a: " << cc_a << std::endl;
cc_a += 3;
std::cout << "cc_a += 3: " << cc_a << std::endl;
// -
std::cout << "cc_a: " << cc_a << "arr: " << arr << "cc_a - arr: " << cc_a - arr << std::endl;
std::cout << "cc_a: " << cc_a << "cc_a - cc_a: " << cc_a - cc_a << std::endl;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a - e: " << cc_a - 2 << std::endl;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e - cc_a: " << 2 - cc_a << std::endl;
cc_a -= arr;
std::cout << "cc_a -= arr: " << cc_a << std::endl;
cc_a -= cc_a;
std::cout << "cc_a -= cc_a: " << cc_a << std::endl;
cc_a -= 3;
std::cout << "cc_a -= 3: " << cc_a << std::endl;
// *
std::cout << "cc_a: " << cc_a << "arr: " << arr << "cc_a * arr: " << cc_a * arr << std::endl;
std::cout << "cc_a: " << cc_a << "cc_a * cc_a: " << cc_a * cc_a << std::endl;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a * e: " << cc_a * 2 << std::endl;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e * cc_a: " << 2 * cc_a << std::endl;
cc_a *= arr;
std::cout << "cc_a *= arr: " << cc_a << std::endl;
cc_a *= cc_a;
std::cout << "cc_a *= cc_a: " << cc_a << std::endl;
cc_a *= 3;
std::cout << "cc_a *= 3: " << cc_a << std::endl;
// /
std::cout << "cc_a: " << cc_a << "arr: " << arr << "cc_a / arr: " << cc_a / arr << std::endl;
std::cout << "cc_a: " << cc_a << "cc_a / cc_a: " << cc_a / cc_a << std::endl;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a / e: " << cc_a / 2 << std::endl;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e / cc_a: " << 2 / cc_a << std::endl;
cc_a /= arr;
std::cout << "cc_a /= arr: " << cc_a << std::endl;
cc_a /= cc_a;
std::cout << "cc_a /= cc_a: " << cc_a << std::endl;
cc_a /= 3;
std::cout << "cc_a /= 3: " << cc_a << std::endl;
// <
Array arr_(3, 3, 1);
Array out = cc_a < arr_;
std::cout << "cc_a: " << cc_a << "arr_: " << arr_ << "cc_a < arr_: " << out << std::endl;
out = cc_a < 2;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a < e: " << out << std::endl;
out = 2 < cc_a;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e < cc_a: " << out << std::endl;
// >
out = cc_a > arr_;
std::cout << "cc_a: " << cc_a << "arr_: " << arr_ << "cc_a > arr_: " << out << std::endl;
out = cc_a > 2;
std::cout << "cc_a: " << cc_a << "e: " << 2 << "\ncc_a > e: " << out << std::endl;
out = 2 > cc_a;
std::cout << "e: " << 2 << "\ncc_a: " << cc_a << "e > cc_a: " << out << std::endl;
Array A(3, 4);
A.set(0, 0, 1);
A.set(2, 1, 3);
A.set(1, 3, 8);
A.set(2, 2, 6);
A.set(0, 3, 9);
A.set(0, 2, 5);
Array B(4, 2);
B.set(3, 0, 1);
B.set(2, 0, 3);
B.set(1, 0, 8);
B.set(2, 1, 6);
B.set(0, 0, 9);
B.set(0, 1, 5);
std::cout << "A: " << A << "B: " << B << std::endl;
std::cout << "gemm(A, B): " << gemm_nn(A, B) << std::endl;
std::cout << "A.dot(B): " << A.dot(B) << std::endl;
std::cout << "A.T(): " << A.T() << std::endl;
std::cout << "gemm_tn(A.T(), B): " << gemm_tn(A.T(), B) << std::endl;
std::cout << "gemm_nt(A, B.T()): " << gemm_nt(A, B.T()) << std::endl;
std::cout << "gemm_tt(A.T(), B.T()): " << gemm_tt(A.T(), B.T()) << std::endl;
std::cout << "gemm(A.T(), true, B.T(), true): " << gemm(A.T(), true, B.T(), true) << std::endl;
std::cout << "gemm(A, false, B.T(), true): " << gemm(A, false, B.T(), true) << std::endl;
std::cout << "gemm(A, false, B, false): " << gemm(A, false, B, false) << std::endl;
std::cout << "gemm(A.T(), true, B, false): " << gemm(A.T(), true, B, false) << std::endl;
std::cout << "A.sum: " << A.sum() << A.sum(0) << A.sum(1) << std::endl;
std::cout << "A.mean: " << A.mean() << A.mean(0) << A.mean(1) << std::endl;
}
catch (Exception &e)
{
std::cerr << e.what() << std::endl;
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
}
/*********************************
int main()
{
array_main();
}
*********************************/
|
#include <iostream>
#include "productregister.h"
#include "shoes.h"
#include "nikeshoes.h"
using namespace std;
int main()
{
// ========================== 生产耐克球鞋过程 ===========================//
// 注册产品种类为Shoes(基类),产品为NiKe(子类)到工厂,产品名为nike
ProductRegister<Shoes, NikeShoes> NikeShoes("nike");
// 从工厂获取产品种类为Shoes,名称为nike的产品对象
Shoes *pNikeShoes =IFactory<Shoes>::getInstance().getProduct("nike");
// 显示产品的广告语
pNikeShoes->show();
// 释放资源
if (pNikeShoes)
delete pNikeShoes;
return 0;
}
|
#include "solver.h"
#include <time.h>
int main() {
clock_t tStart = clock();
Solver s;
s.run();
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
|
#pragma once
class AI_ChargeBeam : public Hourglass::IAction
{
public:
void LoadFromXML( tinyxml2::XMLElement* data );
void AI_ChargeBeam::Init( Hourglass::Entity* entity );
IBehavior::Result Update( Hourglass::Entity* entity );
IBehavior* MakeCopy() const;
private:
uint32_t m_PoweringDown : 1;
hg::Light* m_ChargingLight;
float m_Duration;
float m_StartIntensity;
float m_EndIntensity;
float m_StartRadius;
float m_EndRadius;
float m_Timer;
};
|
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;
#define MSG_BUF_SIZE 1024
#define CLI_BIND_PORT 2345
#define EXIT_KEYWORD "Exit"
#define CHAT_HANDLE_SIZE 20
int cli_d = -1; // Client Socket Descriptor
char chat_handle[CHAT_HANDLE_SIZE]; // Name of the Person connecting
bool exit_connection = false; // Connection Termination
/*
* Thread of execution for Sending Messages
*/
void *send_msg_fn(void *arg)
{
cout << "Type in message to send. Type just "<< EXIT_KEYWORD <<" to terminate connection.";
cout << "Pressing Enter Key sends out the message\n";
while (!exit_connection) {
char send_buff[MSG_BUF_SIZE]; // Send Message Buffer
char input[MSG_BUF_SIZE];
cin.getline(input, MSG_BUF_SIZE);
memset(send_buff, '\0', MSG_BUF_SIZE);
strncpy(send_buff, chat_handle, strlen(chat_handle));
strncpy(send_buff + strlen(chat_handle), input, strlen(input));
/* Send only if connection has not been terminated by the other party */
if (!exit_connection) {
send(cli_d, send_buff, strlen(send_buff), 0);
}
if (strcmp(input, EXIT_KEYWORD) == 0) {
exit_connection = true;
break;
}
}
}
/*
* Thread of execution for Receiving Messages
*/
void *recv_msg_fn(void *arg)
{
while (!exit_connection) {
/*
* Search the received message to see if other side wants to
* close the connection
*/
char search_exit[sizeof(EXIT_KEYWORD)];
char recv_buff[MSG_BUF_SIZE]; // Receive Message Buffer
memset(recv_buff, '\0', MSG_BUF_SIZE);
recv(cli_d, recv_buff, MSG_BUF_SIZE, 0);
cout << recv_buff << endl;
strncpy(search_exit, recv_buff + (strlen(recv_buff) - sizeof(EXIT_KEYWORD) + 1),
sizeof(EXIT_KEYWORD));
if (strcmp(search_exit, EXIT_KEYWORD) == 0) {
exit_connection = true;
break;
}
}
}
int main()
{
int ret = 0;
struct sockaddr_in conn_sock_addr;
cout << "Enter your Chat Handle:\n";
cin.getline(chat_handle, CHAT_HANDLE_SIZE);
/*
* Create the client socket
*/
if ((cli_d = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << "Client Socket Creation failed. Exiting\n";
ret = -1; // < 0 return value simply for indicating error
goto exit_client;
}
conn_sock_addr.sin_family = AF_INET;
conn_sock_addr.sin_port = htons(CLI_BIND_PORT);
/*
* Connect to the server socket
*/
if (connect(cli_d, (struct sockaddr *)&conn_sock_addr, sizeof(conn_sock_addr)) < 0) {
cout << "Connection to server failed. Exiting\n";
ret = -1;
goto exit_client;
}
/*
* If control gets here, then the connection to the server has been established
*/
strcat(chat_handle, ": ");
if (cli_d > 0) {
pthread_t send_thread, recv_thread;
int send_ret = -1, recv_ret = -1;
/* Create threads for sending and receiving messages */
send_ret = pthread_create(&send_thread, NULL, send_msg_fn, NULL);
recv_ret = pthread_create(&recv_thread, NULL, recv_msg_fn, NULL);
if (send_ret || recv_ret) {
cout << "Error spawning message threads. Exiting\n";
ret = -1;
goto exit_client;
}
pthread_join(send_thread, NULL);
pthread_join(recv_thread, NULL);
}
exit_client:
if (cli_d > 0) {
cout << "Connection Terminating.\n";
close(cli_d);
}
return ret;
}
|
#include "eventManager.h"
eventManager::eventManager() {}
vector<Event*> eventManager::getQueue() {
return evt;
}
|
#include"stdio.h"
#include"conio.h"
void main(void)
{
int a,b,c,x,y;
clrscr();
gotoxy(15,7);
printf("\t\tThis Programs Created By\n\n\t\t\t YOGESHWAR KHATRI \n\n\t\t\t 2k10-CSE-86");
getch();
clrscr();
printf("\n\nPut the value of a = ");
scanf("%d",&a);
printf("\nPut the value of b = ");
scanf("%d",&b);
x=++a+b*c;
y=(a++)+b*c;
printf("\n\n\nThe result of X=++a+b*c is %d",x);
printf("\n\nThe result of Y=a++ +b*c is %d",y);
printf("\n\n\n\n\n\n\n\n\n\n\n\t\t\t To Exit Press Enter Key");
getch();
}
|
/*
* Program: SIFT.h
* Usage: Define C++ class to deal and realize SIFT process
*/
#ifndef SIFT_H
#define SIFT_H
#include "CImg.h"
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
using namespace cimg_library;
#define GAUSSKERN 3.5
#define PI 3.14159265358979323846
#define INITSIGMA 0.5
#define SCALESPEROCTAVE 2
#define CONTRAST_THRESHOLD 0.02
#define CURVATURE_THRESHOLD 10.0
#define MAXOCTAVES 4
// Structure of every level in octave
struct ImageLevel{
int length;
float sigma;
float absolute_sigma;
CImg<float> level;
};
// Structure of every octave
struct ImageOctave{
int width, height;
float subSample;
ImageLevel octave[5];
};
// Structure of a key point in an image
struct KeyPoint{
int height, width; // Origin image's height and width
float x = -1, y = -1; // Key point's location
int octave_order, level_order; // Key point in which octave and level
// Points self-private variables
float scale, ori, mag; // The point's level's scale, orientation, and magniture
float* descriptors; // The key description word
};
class SIFT{
public:
SIFT(CImg<float> src);
// SIFT process steps
// 1. Preprocess input image
CImg<float> InitImage(CImg<float> input);
// 2. Establish gaussian octaves
ImageOctave* BuildGaussianOctave(CImg<float> input);
// 3. Detect key points locations
int DetectKeyPoints();
void DisplayKeyPoints();
// 4. Calculate gaussian image's gradients, magniture and direction
void ComputeGrad_Mag_Dir();
// Nearest neighbor binlinear filtering
int FindNearestRotationNei(float angle, int count);
void AverageWeakBins(float* bins, int count);
bool InterpolateOrientation(float left, float middle, float right, float* correction, float* peak);
void AssignTheMainOrientation();
void DisplayOrientation(CImg<float> img);
// 5. Extract key points' feature descriptors
void ExtractFeatureDescriptors();
// SIFT matrix tools functions
CImg<float> makeHalfSize(CImg<float> input); // Using down sampling
CImg<float> makeDoubleSize(CImg<float> input); // Using up sampling
CImg<float> makeDoubleSizeLinear(CImg<float> input); // Using up smapling and linear interpolation
CImg<float> make2DGaussianKernel(float sigma); // Get 2D gaussian kernel
float getPixelBi(CImg<float> input, int row, int col); // Bilinear interpolation
float getNormVector(float input[], int dim);
// Pyrmids associate functions
CImg<float> ImgJoinHorizen(CImg<float> img1, CImg<float> img2);
CImg<float> ImgJoinVertical(CImg<float> img1, CImg<float> img2);
// Gray tool function
CImg<float> toGrayImage(CImg<float> img);
CImg<float> convertScale(CImg<float> src, float scale, float shift);
// Main process startup functions
void SIFT_Start();
vector<KeyPoint> GetFirstKeyDescriptor();
void saveKeyPointsImg(char* fileName);
private:
CImg<float> srcImg;
CImg<float> keyPointsImg;
// Octave infos of input image
int octavesNum;
vector<ImageOctave> octaves; // store all octaves
vector<ImageOctave> DOGoctaves; // Here choose DOG cause it's easy to write
vector<ImageOctave> magPyr; // Store Magniture octaves
vector<ImageOctave> gradPyr; // Store gradient octaves
// Feature key points
int keyPointsNum = 0;
vector<KeyPoint> keyPoint; // Store all the keyPoints
vector<KeyPoint> keyDescriptors; // Store all the descriptors of keypoints
};
#endif
|
#pragma once
#include <memory>
#include <vector>
namespace Events
{
///<summary>
///Base class for every function wrapper in the system.
///</summary>
template<typename ReturnType, typename ...Args>
class FunctionWrapperBase
{
public:
/// Execute function with given arguments
virtual ReturnType operator()(Args&& ...args) = 0;
};
template<typename Signature, typename ReturnType, typename ...Args>
class FunctionWrapper : public FunctionWrapperBase<ReturnType, Args...>
{
protected:
Signature funcPtr;
public:
FunctionWrapper(Signature funcPtr) : funcPtr(funcPtr) { }
bool IsFunction(Signature function)
{
return funcPtr == function;
}
};
///<summary>
///Wrapper for global or static functions.
///</summary>
template<typename ReturnType, typename ...Args >
class GlobalFunctionWrapper : public FunctionWrapper<ReturnType(*)(Args...), ReturnType, Args...>
{
public:
GlobalFunctionWrapper(ReturnType(*funcPtr)(Args...)) : FunctionWrapper<ReturnType(*)(Args...), ReturnType, Args...>(funcPtr) { }
ReturnType operator() (Args&& ...args) override
{
return FunctionWrapper<ReturnType(*)(Args...), ReturnType, Args...>::funcPtr(std::forward<Args>(args)...);
}
bool operator ==(ReturnType(*otherFuncPtr)(Args...)) const
{
return FunctionWrapper<ReturnType(*)(Args...), ReturnType, Args...>::funcPtr == otherFuncPtr;
}
bool operator ==(GlobalFunctionWrapper<ReturnType, Args...>& otherGlobalFunction) const
{
return FunctionWrapper<ReturnType(*)(Args...), ReturnType, Args...>::funcPtr == otherGlobalFunction.funcPtr;
}
};
///<summary>
///Base wrapper class for non-static class functions.
///</summary>
template<typename Signature, typename CallerType, typename ReturnType, typename ...Args>
class MemberFunctionWrapper : public FunctionWrapper<Signature, ReturnType, Args...>
{
private:
CallerType& caller;
public:
MemberFunctionWrapper(Signature funcPtr, CallerType& caller) :
FunctionWrapper<Signature, ReturnType, Args...>(funcPtr), caller(caller) { }
ReturnType operator()(Args&& ...args) override
{
//return caller.funcPtr(std::forward<Args>(args)...);
//gotta wrap everything in ( ) before the parameters, else the compiler complains about a parameter missing and stuff...
return (caller.*(FunctionWrapper<Signature, ReturnType, Args...>::funcPtr))(std::forward<Args>(args)...);
}
bool IsCaller(CallerType& possibleCaller)
{
return &caller == &possibleCaller; //just compare memory addresses
}
};
///<summary>
///Wrapper for non-static non-const class functions.
///</summary>
template<typename CallerType, typename ReturnType, typename ...Args>
class RegularMemberFunctionWrapper : public MemberFunctionWrapper<ReturnType(CallerType::*)(Args...), CallerType, ReturnType, Args...>
{
public:
RegularMemberFunctionWrapper(ReturnType(CallerType::* funcPtr)(Args...), CallerType& caller) :
MemberFunctionWrapper<ReturnType(CallerType::*)(Args...), CallerType, ReturnType, Args...>(funcPtr, caller) { }
};
///<summary>
///Wrapper for non-static const class functions.
///</summary>
template<typename CallerType, typename ReturnType, typename ...Args>
class ConstMemberFunctionWrapper : public MemberFunctionWrapper<ReturnType(CallerType::*)(Args...) const, CallerType, ReturnType, Args...>
{
public:
ConstMemberFunctionWrapper(ReturnType(CallerType::* funcPtr)(Args...) const, CallerType& caller) :
MemberFunctionWrapper<ReturnType(CallerType::*)(Args...) const, CallerType, ReturnType, Args...>(funcPtr, caller) { }
};
/// <summary>
/// An event stores a vector of functions with no return value.
/// To bind a function to an event, said function must match the arguments required by the event.
/// Eg. for an Event<string, int>, any function that wishes to be bound to it must require
/// exclusively a string and an int parameters, in this exact order, and not return anything.
/// </summary>
template<typename... Args>
class Event
{
private:
std::vector<std::unique_ptr<FunctionWrapperBase<void, Args...>>> boundFunctions;
private:
/// <summary>
/// Unbinds functions that satisfy a given condition. Used internally when public Unbind methods are called to
/// locate said functions in the vector boundFunctions.
/// </summary>
/// <param name="ShouldRemove">Condition that a function must meet to be removed.</param>
template <typename FuncType, typename ConditionType>
inline void UnbindFunction(ConditionType&& ShouldRemove)
{
for (int i = boundFunctions.size() - 1; i >= 0; --i)
{
auto func = dynamic_cast<FuncType*>(boundFunctions[i].get());
if (func != nullptr && ShouldRemove(func))
{
boundFunctions.erase(boundFunctions.begin() + i);
}
}
}
public:
~Event()
{
UnbindAll();
}
void operator() (Args&& ... args)
{
for (auto& function : boundFunctions)
{
//Note to self: can't call the () operator directly like in the FunctionWrappers because the pointer is not the function itself.
//Must dereference it first, otherwise the compiler won't be happy and complain about a function receiving X amount of parameters not existing.
(*function)(std::forward<Args>(args)...);
}
}
//TODO: research how to go about creating a Bind method that works for both reference AND value parameters
///<summary>
///Receives a member function from a given object and stores it in the list of functions attached to this event.
///</summary>
template <typename CallerType>
void Bind(void (CallerType::* funcPtr)(Args...), CallerType& caller)
{
boundFunctions.emplace_back(std::make_unique<RegularMemberFunctionWrapper<CallerType, void, Args...>>(funcPtr, caller));
}
///<summary>
///Receives a member function from a given object and stores it in the list of functions attached to this event.
///</summary>
template <typename CallerType>
void Bind(void (CallerType::* funcPtr)(Args&&...), CallerType& caller)
{
boundFunctions.emplace_back(std::make_unique<RegularMemberFunctionWrapper<CallerType, void, Args...>>(funcPtr, caller));
}
///<summary>
///Receives a const member function from a given object and stores it in the list of functions attached to this event.
///</summary>
template <typename CallerType>
void Bind(void(CallerType::* funcPtr) (Args&&...) const, CallerType& caller)
{
boundFunctions.emplace_back(std::make_unique<ConstMemberFunctionWrapper<CallerType, void, Args...>>(funcPtr, caller));
}
///<summary>
///Receives a global function and stores it in the list of functions attached to this event.
///</summary>
void Bind(void(*funcPtr)(Args...))
{
boundFunctions.emplace_back(std::make_unique<GlobalFunctionWrapper<void, Args...>>(funcPtr));
}
///<summary>
///Removes a global function from the list of functions attached to this event.
///</summary>
void Unbind(void(*funcPtr)(Args...))
{
UnbindFunction<GlobalFunctionWrapper<void, Args...>>
([funcPtr](GlobalFunctionWrapper<void, Args...>* v)
{ return (*v) == funcPtr; });
}
///<summary>
///Removes an object's member function from the list of functions attached to this event.
///</summary>
template <typename CallerType>
void Unbind(void (CallerType::* funcPtr)(Args...), CallerType& caller)
{
UnbindFunction<MemberFunctionWrapper<CallerType, void, Args...>>
([funcPtr, &caller](MemberFunctionWrapper<CallerType, void, Args...>* v)
{ return v->IsFunctionFromCaller(funcPtr, caller); });
}
///<summary>
///Removes an object's const member function from the list of functions attached to this event.
///</summary>
template <typename CallerType>
void Unbind(void(CallerType::* funcPtr) (Args...) const, CallerType& caller)
{
UnbindFunction<ConstMemberFunctionWrapper<CallerType, void, Args...>>
([funcPtr, &caller](ConstMemberFunctionWrapper<CallerType, void, Args...>* v)
{ return v->IsFunctionFromCaller(funcPtr, caller); });
}
///<summary>
///Removes every function from the list of functions attached to this event.
///</summary>
void UnbindAll()
{
boundFunctions.clear();
}
};
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
struct edge {
ll to;
ll cost;
};
typedef pair<long long, long long> P_dij;
/* params
* @s -> start, n -> 要素数, G -> グラフ, d -> 結果(参照渡し)
* グラフの要素を0 ~ n - 1として見る
*/
void dijkstra(const long long s, const long long n,
vector< vector<edge> > const &G, vector<long long> & d){
d.resize(n);
for(int i=0; i<n; i++) d[i] = INF;
priority_queue<P_dij, vector<P_dij>, greater<P_dij>> que;
d[s] = 0;
que.push(P_dij(0, s));
while (!que.empty()) {
P_dij p = que.top();
que.pop();
long long v = p.second;
if(d[v] < p.first)continue;
for(int i=0;i<G[v].size(); i++){
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost){
d[e.to] = d[v] + e.cost;
que.push(P_dij(d[e.to], e.to));
}
}
}
}
int main() {
int n;
cin >> n;
ll u,v,w;
vector< vector<edge> > G(n);
rep(i,n-1) {
cin >> u >> v >> w;
u--, v--;
G[u].push_back({v,w});
G[v].push_back({u,w});
}
vector<ll> d, d2;
vector<bool> ans(n);
dijkstra(0, n, G, d);
ans[0] = 1;
ll cnt = 0, tm = 0;
for (int i = 1; i < n; ++i) {
if (d[i] % 2 == 0) {
ans[i] = 1;
} else {
cnt += 1;
tm = i;
}
}
/*
if (cnt == 1) {
dijkstra(0, n, G, d2);
for (int i = 0; i < n; ++i) {
if (i == tm) continue;
if (d2[i] % 2 == 0) {
ans[i] = 0;
break;
}
}
}*/
for (int i = 0; i < n; ++i) {
cout << ans[i] << endl;
}
}
|
#include <iostream>
#include <vector>
using namespace std;
struct BSTnode {
int data = 0;
struct BSTnode* rightPtr = NULL;
struct BSTnode* leftPtr = NULL;
int level = 0;
};
struct BSTnode Vforest[100];
void printPost(BSTnode* node, bool root) {
if (node) {
printPost(node->leftPtr, false);
printPost(node->rightPtr, false);
if (root) {
cout << node->data;
}
else {
cout << node->data << " ";
}
}
}
int first;
int forestNUM = 0;
void printIn(BSTnode* node) {
if (node) {
printIn(node->leftPtr);
if (first == 1) {
cout << node->data;
first = 0;
}
else {
cout << " " << node->data;
}
printIn(node->rightPtr);
}
}
void printPre(BSTnode* node) {
if (node) {
if (first == 1) {
cout << node->data;
first = 0;
}
else {
cout << " " << node->data;
}
printPre(node->leftPtr);
printPre(node->rightPtr);
}
}
int insertvalue(BSTnode** node, int value) {
struct BSTnode* current = NULL;
struct BSTnode* previous = NULL;
current = *node;
while (current != NULL) { //search
if (value > current->data) {
previous = current;
current = current->rightPtr;
}
else if (value < current->data) {
previous = current;
current = current->leftPtr;
}
else if (value == current->data) {
break;
}
}
if (current == NULL) {
if (value > previous->data) {
previous->rightPtr = new BSTnode;
previous->rightPtr->data = value;
}
else if (value < previous->data) {
previous->leftPtr = new BSTnode;
previous->leftPtr->data = value;
}
}
else if (current->data == value) {
return 0;
}
return 1;
}
void levelcounter(BSTnode* node, int count, int level[]) {
if (node != NULL) {
level[count]++;
count++;
levelcounter(node->rightPtr, count, level);
levelcounter(node->leftPtr, count, level);
node->level = count;
}
}
BSTnode* findLargest(BSTnode* node) {
if (node->rightPtr) {
return findLargest(node->rightPtr);
}
else {
return node;
}
}
void Delete(BSTnode** node, int value) {
if (value < (*node)->data) {
Delete(&(*node)->leftPtr, value);
}
else if (value > (*node)->data) {
Delete(&(*node)->rightPtr, value);
}
else if ((*node)->leftPtr && (*node)->rightPtr) {
struct BSTnode* temp = findLargest((*node)->leftPtr);
(*node)->data = temp->data;
Delete(&(*node)->leftPtr, temp->data);
}
else {
struct BSTnode* temp = NULL;
if ((*node)->leftPtr == NULL && (*node)->rightPtr == NULL) {
(*node) = NULL;
}
else if ((*node)->leftPtr != NULL) {
(*node) = (*node)->leftPtr;
}
else {
(*node) = (*node)->rightPtr;
}
}
}
void cutoperator(BSTnode** node,int point,int count) {
if (count == point) {
if ((*node)->leftPtr) {
Vforest[forestNUM] = *(*node)->leftPtr;
forestNUM++;
(*node)->leftPtr = NULL;
}
if ((*node)->rightPtr) {
Vforest[forestNUM] = *(*node)->rightPtr;
forestNUM++;
(*node)->rightPtr = NULL;
}
}
else {
count++;
if ((*node)->leftPtr) {
cutoperator(&(*node)->leftPtr, point, count);
}
if ((*node)->rightPtr) {
cutoperator(&(*node)->rightPtr, point, count);
}
}
}
int main() {
int input;
bool insertOrnot = true;
struct BSTnode* root = NULL;
struct BSTnode* current = NULL;
struct BSTnode* previous = NULL;
int insertnum = 0;
int deletenum = 0;
int levelNodeNum[400] = { 0 };
while (cin >> input) {
if (insertOrnot) { //insert
insertnum++;
if (root == NULL) {
root = new BSTnode;
root->data = input;
root->level = 1;
}
else {
if (!insertvalue(&root, input)) {
insertOrnot = false;
printPost(root, true);
cout << endl;
Delete(&root, input);
insertnum--;
deletenum++;
}
}
}
else {//delete
Delete(&root, input);
deletenum++;
}
}
//printPost(root, true);
//cout << endl;
insertnum -= deletenum;
levelcounter(root, 0, levelNodeNum);
float halfnum = insertnum / 2.0;
int cc = 0;
int cut = 0;
float downpoint = 0.0, uppoint = 0.0, downvalue = 0.0, upvalue = 0.0;
int point = 0;
while (cut < halfnum) {
cut += levelNodeNum[cc];
if (cut > halfnum) {
downpoint = cc - 1;
downvalue = cut-levelNodeNum[cc];
uppoint = cc;
upvalue = cut;
}
else if (cut == halfnum) {
point = cc;
}
cc++;
}
float compare = 0.0;
float compare2 = 0.0;
if (!point) {
compare = halfnum - downvalue;
compare2 = upvalue - halfnum;
if (compare > compare2) {
point = uppoint;
}
else {
point = downpoint;
}
}
struct BSTnode* S;
S = root;
cutoperator(&S, point, 0);
first = 1;
printIn(S);
cout << endl;
for (int i = 0; i < forestNUM; i++) {
first = i + 1;
printPre(&Vforest[i]);
}
}
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
#include <cstring>
using namespace std;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
#define int long long
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
const int mod = 1e9 + 7;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
const int N = 1e2 + 5;
char Graph[N][N];
int vis[N][N];
bool flag;
int n, m;
string alliswell = "ALLIZZWELL";
int row[] = {0, -1, 1, 0, 0, -1, -1, 1, 1};
int col[] = {0, 0, 0, 1, -1, -1, 1, -1, 1};
bool is_valid(int i, int j) {
return (i >= 1 && i <= n && j >= 1 && j <= m);
}
void dfs(int sx, int sy, int ptr) {
if (ptr == 10) {
flag = true;
return ;
}
vis[sx][sy] = 1;
REP(i, 1, 8) {
int r = row[i] + sx;
int c = col[i] + sy;
if (!vis[r][c] && is_valid(r, c) && Graph[r][c] == alliswell[ptr]) {
dfs(r, c, ptr + 1);
if (flag) {
return ;
}
}
}
vis[sx][sy] = 0;
}
void solve() {
memset(vis, 0, sizeof(vis));
cin >> n >> m;
REP(i, 1, n) {
REP(j, 1, m) {
cin >> Graph[i][j];
}
}
bool ans = false;
REP(i, 1, n) {
REP(j, 1, m) {
if (Graph[i][j] == 'A' && !vis[i][j]) {
flag = false;
dfs(i, j, 1);
if (flag) {
ans = true;
break;
}
}
}
if (ans)
break;
}
if (ans)
cout << "YES" << endl;
else
cout << "NO" << endl;
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
int t; cin >> t; while (t--)
solve();
return 0;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef BAJKA_EQ_QUINT_H_
#define BAJKA_EQ_QUINT_H_
#include "IEquation.h"
#include <cmath>
namespace Tween {
class QuintIn : public IEquation {
public:
virtual ~QuintIn () {}
double compute (double t, double b, double c, double d) const
{
t /= d;
return c * t * t * t * t * t + b;
}
};
class QuintOut : public IEquation {
public:
virtual ~QuintOut () {}
double compute (double t, double b, double c, double d) const
{
t = t / d - 1;
return c * (t * t * t * t * t + 1) + b;
}
};
class QuintInOut : public IEquation {
public:
virtual ~QuintInOut () {}
double compute (double t, double b, double c, double d) const
{
if ((t /= d / 2) < 1) {
return c / 2 * t * t * t * t * t + b;
}
t -= 2;
return c / 2 * (t * t * t * t * t + 2) + b;
}
};
} // namespace
# endif /* CIRC_H_ */
|
#include <stdio.h>
#include <stdlib.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#define GLSL(src) #src
static void errorCallback(int error, const char* description);
static void framebufferSizeCallback(GLFWwindow* window, int width, int height);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
// Settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main(void) {
// Initialization
glfwSetErrorCallback(errorCallback);
if(!glfwInit()) {
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// Create window
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "OpelGL", NULL, NULL);
if(!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
glfwSetKeyCallback(window, keyCallback);
// Load OpenGL API
if(!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
exit(EXIT_FAILURE);
}
// Vertex shader
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main() {\n"
"FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n";
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Shader program
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINK_FAILED\n" << infoLog << std::endl;
}
glUseProgram(shaderProgram);
// Buffers
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Vertex attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Render loop
while(!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
glfwWaitEvents();
}
// Terminate
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
static void errorCallback(int error, const char* description) {
fputs(description, stderr);
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
static void framebufferSizeCallback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
|
class Jeep_base: epoch_car
{
scope = 0;
displayname = "Old Jeep";
model = "\z\addons\dayz_epoch_v\vehicles\jeep\h4_jeep";
picture = "\dayz_epoch_c\icons\vehicles\jeep.paa";
armor = 25;
transportsoldier = 2;
transportmaxweapons = 15;
transportmaxmagazines = 50;
transportmaxbackpacks = 5;
fuelcapacity = 115;
maxspeed = 110;
terraincoef = 2.0;
weapons[] = {minicarhorn};
driveraction = "HMMWV_Driver";
cargoaction[] = {"Skodovka_Cargo01","suv_cargo02_ep1","Skodovka_Cargo01","suv_cargo02_ep1","Skodovka_Cargo012"};
//class HitPoints;
hiddenselectionstextures[]=
{
"\z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_main_co.paa",
"\z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_parts_co.paa"
};
class damage
{
tex[]={};
mat[]=
{
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_main.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_main_damage.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_main_destruct.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_parts.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_parts_damage.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_parts_destruct.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_dash.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_dash_damage.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_dash_destruct.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_glass.rvmat",
"Ca\wheeled_E\Data\auta_skla_damage.rvmat",
"Ca\wheeled_E\Data\auta_skla_damage.rvmat",
"z\addons\dayz_epoch_v\vehicles\jeep\data\jeep_in_glass.rvmat",
"Ca\wheeled_E\Data\auta_skla_in_damage.rvmat",
"Ca\wheeled_E\Data\auta_skla_in_damage.rvmat"
};
};
class NVGMarkers {};
class SoundEvents
{
class AccelerationIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\HMMWV\int\int-acceleration1",0.1,1};
limit = "0.8";
expression = "(engineOn*(1-camPos))*gmeterZ";
};
class AccelerationOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\HMMWV\ext\turspecial1",0.1,1,200};
limit = "0.8";
expression = "(engineOn*camPos)*gmeterZ";
};
};
class Sounds
{
class Engine
{
sound[] = {"\ca\sounds\Vehicles\Wheeled\HMMWV\ext\Engine_Loop_Low_1b",1,1,300};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "camPos*engineOn*((rpm factor[0.15, 0.4]) min (rpm factor[0.7, 0.5]))";
};
class EngineHighOut
{
sound[] = {"\ca\sounds\Vehicles\Wheeled\HMMWV\ext\Engine_Loop_High_1b",1,1,400};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "camPos*engineOn*(rpm factor[0.5, 0.8])";
};
class IdleOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\HMMWV\ext\idle_2",0.562341,1,100};
frequency = "1";
volume = "engineOn*camPos*(rpm factor[0.3, 0])";
};
class TiresRockOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-rock2",0.316228,1,30};
frequency = "1";
volume = "camPos*rock*(speed factor[2, 20])";
};
class TiresSandOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-sand2",0.316228,1,30};
frequency = "1";
volume = "camPos*sand*(speed factor[2, 20])";
};
class TiresGrassOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-grass2",0.316228,1,30};
frequency = "1";
volume = "camPos*grass*(speed factor[2, 20])";
};
class TiresMudOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-mud2",0.316228,1,30};
frequency = "1";
volume = "camPos*mud*(speed factor[2, 20])";
};
class TiresGravelOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-gravel2",0.316228,1,30};
frequency = "1";
volume = "camPos*gravel*(speed factor[2, 20])";
};
class TiresAsphaltOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-asphalt3",0.316228,1,30};
frequency = "1";
volume = "camPos*asphalt*(speed factor[2, 20])";
};
class NoiseOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Noises\ext\noise2",0.177828,1,30};
frequency = "1";
volume = "camPos*(damper0 max 0.03)*(speed factor[0, 8])";
};
class EngineLowIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\HMMWV\ext\Engine_Loop_Low_1b",1,1};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "(1-camPos)*engineOn*((rpm factor[0.2, 0.4]) min (rpm factor[0.8, 0.6]))";
};
class EngineHighIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\HMMWV\ext\Engine_Loop_High_1b",1,1};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "(1-camPos)*engineOn*(rpm factor[0.5, 1.0])";
};
class IdleIn
{
sound[] = {"\ca\sounds\Vehicles\Wheeled\HMMWV\ext\idle_2",0.316228,1};
frequency = "1";
volume = "engineOn*(rpm factor[0.4, 0])*(1-camPos)";
};
class TiresRockIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-rock2",1,1};
frequency = "1";
volume = "(1-camPos)*rock*(speed factor[2, 20])";
};
class TiresSandIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-sand2",1,1};
frequency = "1";
volume = "(1-camPos)*sand*(speed factor[2, 20])";
};
class TiresGrassIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-grass2",1,1};
frequency = "1";
volume = "(1-camPos)*grass*(speed factor[2, 20])";
};
class TiresMudIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-mud2",1,1};
frequency = "1";
volume = "(1-camPos)*mud*(speed factor[2, 20])";
};
class TiresGravelIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-gravel2",1,1};
frequency = "1";
volume = "(1-camPos)*gravel*(speed factor[2, 20])";
};
class TiresAsphaltIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-asphalt3",1,1};
frequency = "1";
volume = "(1-camPos)*asphalt*(speed factor[2, 20])";
};
class NoiseIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Noises\int\noise2",0.446684,1};
frequency = "1";
volume = "(damper0 max 0.03)*(speed factor[0, 8])*(1-camPos)";
};
class Movement
{
sound = "soundEnviron";
frequency = "1";
volume = "0";
};
};
};
class Jeep_DZE: Jeep_base
{
scope = 2;
displayname = "$STR_VEH_NAME_OLD_JEEP";
class HitPoints: HitPoints {
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
};
class Upgrades {
ItemORP[] = {"Jeep_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",1},{"PartWheel",4},{"ItemScrews",2}}};
};
};
// Performance 1
class Jeep_DZE1: Jeep_DZE {
displayname = "$STR_VEH_NAME_OLD_JEEP+";
original = "Jeep_DZE";
maxspeed = 150;
terrainCoef = 1.0;
class HitPoints: HitPoints {
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class HitGlass4;
};
class Upgrades {
ItemAVE[] = {"Jeep_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"PartGeneric",6},{"ItemScrews",4}}};
};
};
// Armor 2
class Jeep_DZE2: Jeep_DZE1 {
displayname = "$STR_VEH_NAME_OLD_JEEP++";
armor = 65;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.3;
};
class HitLBWheel: HitLBWheel {
armor = 0.3;
};
class HitRFWheel: HitRFWheel {
armor = 0.3;
};
class HitRBWheel: HitRBWheel {
armor = 0.3;
};
class HitFuel: HitFuel {
armor = 0.5;
};
class HitEngine: HitEngine {
armor = 1;
};
class HitGlass1: HitGlass1 {
armor = 1.3;
};
class HitGlass2: HitGlass2 {
armor = 1.3;
};
};
class Upgrades {
ItemLRK[] = {"Jeep_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",2},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemScrews",2}}};
};
};
// Cargo 3
class Jeep_DZE3: Jeep_DZE2 {
displayname = "$STR_VEH_NAME_OLD_JEEP+++";
transportMaxWeapons = 30;
transportMaxMagazines = 100;
transportmaxbackpacks = 10;
class Upgrades {
ItemTNK[] = {"Jeep_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",2},{"ItemJerrycan",4},{"ItemScrews",1}}};
};
};
// Fuel 4
class Jeep_DZE4: Jeep_DZE3 {
displayname = "$STR_VEH_NAME_OLD_JEEP++++";
fuelCapacity = 250;
};
|
/* XMRig
* Copyright (c) 2018-2019 tevador <tevador@gmail.com>
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "crypto/rx/RxFix.h"
#include "base/io/log/Log.h"
#include <csignal>
#include <cstdlib>
#include <ucontext.h>
namespace xmrig {
static thread_local std::pair<const void*, const void*> mainLoopBounds = { nullptr, nullptr };
static void MainLoopHandler(int sig, siginfo_t *info, void *ucontext)
{
ucontext_t *ucp = (ucontext_t*) ucontext;
LOG_VERBOSE(YELLOW_BOLD("%s at %p"), (sig == SIGSEGV) ? "SIGSEGV" : "SIGILL", ucp->uc_mcontext.gregs[REG_RIP]);
void* p = reinterpret_cast<void*>(ucp->uc_mcontext.gregs[REG_RIP]);
const std::pair<const void*, const void*>& loopBounds = mainLoopBounds;
if ((loopBounds.first <= p) && (p < loopBounds.second)) {
ucp->uc_mcontext.gregs[REG_RIP] = reinterpret_cast<size_t>(loopBounds.second);
}
else {
abort();
}
}
} // namespace xmrig
void xmrig::RxFix::setMainLoopBounds(const std::pair<const void *, const void *> &bounds)
{
mainLoopBounds = bounds;
}
void xmrig::RxFix::setupMainLoopExceptionFrame()
{
struct sigaction act = {};
act.sa_sigaction = MainLoopHandler;
act.sa_flags = SA_RESTART | SA_SIGINFO;
sigaction(SIGSEGV, &act, nullptr);
sigaction(SIGILL, &act, nullptr);
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
====================================================================*/
#pragma once
// Local includes
#include "IConfigurable.h"
#include "IStabilizedComponent.h"
#include "IVoiceInput.h"
namespace DX
{
class StepTimer;
}
namespace HoloIntervention
{
namespace Rendering
{
class ModelRenderer;
}
namespace Input
{
class VoiceInput;
}
namespace UI
{
class Icons;
}
namespace System
{
class NetworkSystem;
class NotificationSystem;
class RegistrationSystem;
class ToolSystem;
namespace Tasks
{
class TargetSphereTask;
class RegisterModelTask;
}
class TaskSystem : public IStabilizedComponent, public Input::IVoiceInput, public IConfigurable
{
public:
virtual concurrency::task<bool> WriteConfigurationAsync(Windows::Data::Xml::Dom::XmlDocument^ document);
virtual concurrency::task<bool> ReadConfigurationAsync(Windows::Data::Xml::Dom::XmlDocument^ document);
public:
virtual Windows::Foundation::Numerics::float3 GetStabilizedPosition(Windows::UI::Input::Spatial::SpatialPointerPose^ pose) const;
virtual Windows::Foundation::Numerics::float3 GetStabilizedVelocity() const;
virtual float GetStabilizePriority() const;
public:
virtual void RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap);
public:
TaskSystem(HoloInterventionCore& core, NotificationSystem&, NetworkSystem&, ToolSystem&, RegistrationSystem&, Rendering::ModelRenderer&, UI::Icons&);
~TaskSystem();
void Update(Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem, DX::StepTimer& stepTimer);
protected:
// Cached system variables
NotificationSystem& m_notificationSystem;
NetworkSystem& m_networkSystem;
ToolSystem& m_toolSystem;
RegistrationSystem& m_registrationSystem;
Rendering::ModelRenderer& m_modelRenderer;
UI::Icons& m_icons;
std::shared_ptr<Tasks::TargetSphereTask> m_touchingSphereTask;
std::shared_ptr<Tasks::RegisterModelTask> m_regModelTask;
};
}
}
|
#include <iostream>
#include<stdio.h>
#include<string.h>
#include <vector>
#include <string>
#include <cctype>
#include<math.h>
using namespace std;
typedef struct Node{
int val;
int w; //weight
struct Node *next;
}node;
node *arr[1000000];
int dist[1000000];
int p[1000000];
int path[1000000];
int count=0;
int vis[1000000];
void del2(int row,int x) {
node*ptr=arr[row];
node *parent=ptr;
while(ptr->val!=x){
parent=ptr;
ptr=ptr->next;
}
if(parent==ptr)arr[row]=ptr->next;
else{
parent->next=ptr->next;
}
return ;
}
void del(int row,int col) {
node* ptr=arr[row];
node *parent=ptr;
int i=0;
// std::cout << "chu chu col = "<<col << '\n';
// std::cout << "chu chu row = "<<row << '\n';
while(i!=col){
parent=ptr;
ptr=ptr->next;
i++;
}
if(parent==ptr){
arr[row]=ptr->next;
}
else{
parent->next=ptr->next;
}
vis[ptr->val]=1;
count++;
path[count]=ptr->val;
p[ptr->val]=row;
dist[ptr->val]=ptr->w+dist[row];
del2(ptr->val,row);
return ;
}
node* createNode(int a,int b){
node *newnode=(node*)malloc(sizeof(node));
newnode->val=a;
newnode->w=b;
newnode->next=NULL;
return newnode;
}
void addNode(int i,int val,int w){
node *newnode=createNode(val,w);
if(arr[i]==NULL){
arr[i]=newnode;
}
else{
node *ptr=arr[i];
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=newnode;
}
}
int main(){
int n,m;
cin>>n>>m;
// int p[n];
for(int i=0; i<n;i++){
p[i]=-1;
arr[i]=NULL;
path[i]=-1;
dist[i]=-1;
vis[i]=0;
}
for(int i=0;i<m;i++){ //store the input into adjasency list
int a,b,w;
cin>>a>>b>>w;
addNode(a,b,w);
addNode(b,a,w);
}
// for(int i=0;i<n;i++){
// std::cout <<"index " <<i<< '=';
// if(arr[i]==NULL){
// std::cout << "NO" << '\n';
// }
// else{
// node *p=arr[i];
// while(p->next!=NULL){
// std::cout << p->val<<" "<<p->w<<" ";
// p=p->next;
// }
// std::cout << p->val<<" "<<p->w<<" ";
// std::cout << '\n';
// }
// }
int dst=n-1;
dist[0]=0;
path[0]=0;
int flag=0;
while(path[count]!=dst){
int i=0,min=99999999,wt,row=-1,col=-1;
while(path[i]!=-1&&i<=count){ //path[i] =rows that are visited
int index=0; //first element of row
node *pt=arr[path[i]];
if(pt==NULL){
//i++;
// std::cout << "okkkkkkkkkkkkkkkkkkkkkkkkkk i= "<<i<<" path= "<<path[i]<< '\n';
//count++;
// continue;
// break;
}
else if(pt->next==NULL && (dist[path[i]]+pt->w)< min){
if(vis[pt->val]==0){
min=dist[path[i]]+pt->w;
row=path[i];
col=index;
}
}
else{
while (pt!=NULL){
if((dist[path[i]]+pt->w)<min){
if(vis[pt->val]==0){
min=dist[path[i]]+pt->w;
row=path[i];
col=index;
// std::cout << "min becomes ======"<<min<<"where i= "<<i<<"and path[i]="<<path[i]<< '\n';
}
}
index++;
pt=pt->next;
}
}
i++;
}
if(row!=-1&&col!=-1){
del(row,col);
// for(int i=0;i<n;i++){
// std::cout <<"index " <<i<< '=';
// if(arr[i]==NULL){
// std::cout << "NULLLL" << '\n';
// }
// else{
// node *p=arr[i];
// while(p->next!=NULL){
// std::cout << p->val<<" "<<p->w<<" ";
// p=p->next;
// }
// std::cout << p->val<<" "<<p->w<<" ";
// std::cout << '\n';
// }
// }
}
else{
break;
}
}
std::cout <<dist[dst]<< '\n';
return 0;
}
// for(int i=0;i<n;i++){
// std::cout <<"index " <<i<< '=';
// if(arr[i]==NULL){
// std::cout << "NO" << '\n';
// }
// else{
// node *p=arr[i];
// while(p->next!=NULL){
// std::cout << p->val<<" "<<p->w<<" ";
// p=p->next;
// }
// std::cout << p->val<<" "<<p->w<<" ";
// std::cout << '\n';
// }
// }
// 7 12
// 0 2 2
// 0 3 16
// 0 1 6
// 0 6 14
// 1 3 5
// 1 4 5
// 2 4 3
// 2 5 8
// 3 6 3
// 4 3 4
// 4 6 10
// 5 6 1
//
// 7 8
// 0 2 2
// 0 3 16
// 0 1 6
// 1 3 5
// 1 4 5
// 2 4 3
// 2 5 8
// 4 3 4
// 9 14
// 0 1 4
// 0 7 8
// 1 2 8
// 1 7 11
// 2 3 7
// 2 5 4
// 2 8 2
// 3 4 9
// 3 4 14
// 4 5 10
// 5 6 2
// 6 8 6
// 6 7 1
// 7 8 7
//
// 9 11
// 0 1 4
// 0 7 8
// 1 7 11
// 2 3 7
// 2 5 4
// 2 8 2
// 3 4 9
// 3 4 14
// 4 5 10
// 5 6 2
// 6 8 6
// 8 7
// 0 1 1
// 1 2 2
// 2 3 3
// 3 4 4
// 4 5 5
// 5 6 6
// 6 7 7
//
// 6 8
// 0 1 3
// 0 4 4
// 0 2 2
// 1 2 8
// 1 5 10
// 2 3 1
// 3 4 3
// 3 5 15
|
// Copyright (c) 2017 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_LightSet_HeaderFile
#define _Graphic3d_LightSet_HeaderFile
#include <Graphic3d_CLight.hxx>
//! Class defining the set of light sources.
class Graphic3d_LightSet : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Graphic3d_LightSet, Standard_Transient)
public:
//! Iteration filter flags.
enum IterationFilter
{
IterationFilter_None = 0x0000, //!< no filter
IterationFilter_ExcludeAmbient = 0x0002, //!< exclude ambient light sources
IterationFilter_ExcludeDisabled = 0x0004, //!< exclude disabled light sources
IterationFilter_ExcludeNoShadow = 0x0008, //!< exclude light sources not casting shadow
IterationFilter_ExcludeDisabledAndAmbient = IterationFilter_ExcludeAmbient | IterationFilter_ExcludeDisabled,
IterationFilter_ActiveShadowCasters = IterationFilter_ExcludeDisabledAndAmbient | IterationFilter_ExcludeNoShadow,
};
//! Iterator through light sources.
class Iterator
{
public:
//! Empty constructor.
Iterator() : myFilter (0) {}
//! Constructor with initialization.
Iterator (const Graphic3d_LightSet& theSet,
IterationFilter theFilter = IterationFilter_None)
: myIter (theSet.myLights),
myFilter (theFilter)
{
skipFiltered();
}
//! Constructor with initialization.
Iterator (const Handle(Graphic3d_LightSet)& theSet,
IterationFilter theFilter = IterationFilter_None)
: myFilter (theFilter)
{
if (!theSet.IsNull())
{
myIter = NCollection_IndexedDataMap<Handle(Graphic3d_CLight), Standard_Size>::Iterator (theSet->myLights);
skipFiltered();
}
}
//! Returns TRUE if iterator points to a valid item.
Standard_Boolean More() const { return myIter.More(); }
//! Returns current item.
const Handle(Graphic3d_CLight)& Value() const { return myIter.Key(); }
//! Moves to the next item.
void Next()
{
myIter.Next();
skipFiltered();
}
protected:
//! Skip filtered items.
void skipFiltered()
{
if (myFilter == 0)
{
return;
}
for (; myIter.More(); myIter.Next())
{
if ((myFilter & IterationFilter_ExcludeAmbient) != 0
&& myIter.Key()->Type() == Graphic3d_TypeOfLightSource_Ambient)
{
continue;
}
else if ((myFilter & IterationFilter_ExcludeDisabled) != 0
&& !myIter.Key()->IsEnabled())
{
continue;
}
else if ((myFilter & IterationFilter_ExcludeNoShadow) != 0
&& !myIter.Key()->ToCastShadows())
{
continue;
}
break;
}
}
protected:
NCollection_IndexedDataMap<Handle(Graphic3d_CLight), Standard_Size>::Iterator myIter;
Standard_Integer myFilter;
};
public:
//! Empty constructor.
Standard_EXPORT Graphic3d_LightSet();
//! Return lower light index.
Standard_Integer Lower() const { return 1; }
//! Return upper light index.
Standard_Integer Upper() const { return myLights.Extent(); }
//! Return TRUE if lights list is empty.
Standard_Boolean IsEmpty() const { return myLights.IsEmpty(); }
//! Return number of light sources.
Standard_Integer Extent() const { return myLights.Extent(); }
//! Return the light source for specified index within range [Lower(), Upper()].
const Handle(Graphic3d_CLight)& Value (Standard_Integer theIndex) const { return myLights.FindKey (theIndex); }
//! Return TRUE if light source is defined in this set.
Standard_Boolean Contains (const Handle(Graphic3d_CLight)& theLight) const { return myLights.Contains (theLight); }
//! Append new light source.
Standard_EXPORT Standard_Boolean Add (const Handle(Graphic3d_CLight)& theLight);
//! Remove light source.
Standard_EXPORT Standard_Boolean Remove (const Handle(Graphic3d_CLight)& theLight);
//! Returns total amount of lights of specified type.
Standard_Integer NbLightsOfType (Graphic3d_TypeOfLightSource theType) const { return myLightTypes[theType]; }
//! @name cached state of lights set updated by UpdateRevision()
public:
//! Update light sources revision.
Standard_EXPORT Standard_Size UpdateRevision();
//! Return light sources revision.
//! @sa UpdateRevision()
Standard_Size Revision() const { return myRevision; }
//! Returns total amount of enabled lights EXCLUDING ambient.
//! @sa UpdateRevision()
Standard_Integer NbEnabled() const { return myNbEnabled; }
//! Returns total amount of enabled lights of specified type.
//! @sa UpdateRevision()
Standard_Integer NbEnabledLightsOfType (Graphic3d_TypeOfLightSource theType) const { return myLightTypesEnabled[theType]; }
//! Returns total amount of enabled lights castings shadows.
//! @sa UpdateRevision()
Standard_Integer NbCastShadows() const { return myNbCastShadows; }
//! Returns cumulative ambient color, which is computed as sum of all enabled ambient light sources.
//! Values are NOT clamped (can be greater than 1.0f) and alpha component is fixed to 1.0f.
//! @sa UpdateRevision()
const Graphic3d_Vec4& AmbientColor() const { return myAmbient; }
//! Returns a string defining a list of enabled light sources as concatenation of letters 'd' (Directional), 'p' (Point), 's' (Spot)
//! depending on the type of light source in the list.
//! Example: "dppp".
//! @sa UpdateRevision()
const TCollection_AsciiString& KeyEnabledLong() const { return myKeyEnabledLong; }
//! Returns a string defining a list of enabled light sources as concatenation of letters 'd' (Directional), 'p' (Point), 's' (Spot)
//! depending on the type of light source in the list, specified only once.
//! Example: "dp".
//! @sa UpdateRevision()
const TCollection_AsciiString& KeyEnabledShort() const { return myKeyEnabledShort; }
protected:
NCollection_IndexedDataMap<Handle(Graphic3d_CLight), Standard_Size>
myLights; //!< list of light sources with their cached state (revision)
Graphic3d_Vec4 myAmbient; //!< cached value of cumulative ambient color
TCollection_AsciiString myKeyEnabledLong; //!< key identifying the list of enabled light sources by their type
TCollection_AsciiString myKeyEnabledShort; //!< key identifying the list of enabled light sources by the number of sources of each type
Standard_Integer myLightTypes [Graphic3d_TypeOfLightSource_NB]; //!< counters per each light source type defined in the list
Standard_Integer myLightTypesEnabled[Graphic3d_TypeOfLightSource_NB]; //!< counters per each light source type enabled in the list
Standard_Integer myNbEnabled; //!< number of enabled light sources, excluding ambient
Standard_Integer myNbCastShadows; //!< number of enabled light sources casting shadows
Standard_Size myRevision; //!< current revision of light source set
Standard_Size myCacheRevision; //!< revision of cached state
};
DEFINE_STANDARD_HANDLE(Graphic3d_LightSet, Standard_Transient)
#endif // _Graphic3d_LightSet_HeaderFile
|
#include "No.h"
No::No(string id, int peso) {
this->id = id;
this->peso = peso;
arestas = new unordered_map<int, int>();
}
void No::inserirAresta(int destino, int peso) {
if (encontrarArestasComDestino(destino) != NULL) return; // caso a aresta já tenha sido inserida, retornar
arestas->insert(make_pair(destino, peso));
grau++;
}
// método retorna o número de arestas excluídas
int No::removerAresta(int destino) {
int n = arestas->erase(destino);
if (n != 0) grau--;
return n;
}
// função auxiliar que atualiza os índices dos nós no map de arestas quando ocorre exclusão de nó
void No::atualizarIndices(int indiceRemovido) {
// auxiliar que dirá se a aresta atual já foi reinserida. Como não tratamos multigrafo, um map de key int (destino)
// e bool (foi reinserida) é suficiente
unordered_map<int, bool> arestaReinserida;
// como os containers key-value da STL usam keys constantes, é preciso remover e reinserir qualquer indice que
// seja maior ou igual ao indiceRemovido (que são os nós que tiveram seus índices subtraídos.
// O iterador não é
unordered_map<int, int>::iterator it;
for (it = arestas->begin(); it != arestas->end();) {
if (it->first > indiceRemovido && arestaReinserida.find(it->first) == arestaReinserida.end()) {
int indiceAnterior = it->first;
int peso = it->second;
arestas->erase(it++);
(*arestas)[indiceAnterior - 1] = peso;
arestaReinserida[indiceAnterior - 1] = true;
} else {
// como há deleções durante a iteração, é necessário realizar a incrementação aqui, para evitar
// exceções dentro da hashtable
++it;
}
}
}
pair<const int, int> *No::encontrarArestasComDestino(int destino) {
unordered_map<int, int>::iterator it = arestas->find(destino);
if (it != arestas->end()) return &(*it);
else return NULL;
}
No::~No() {
delete (arestas);
}
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _THREAD_CPU_USAGE_H
#define _THREAD_CPU_USAGE_H
#include <cpustats/CentralTendencyStatistics.h>
// Track CPU usage for the current thread, and maintain statistics on
// the CPU usage. Units are in per-thread CPU ns, as reported by
// clock_gettime(CLOCK_THREAD_CPUTIME_ID). Simple usage: for cyclic
// threads where you want to measure the execution time of the whole
// cycle, just call sampleAndEnable() at the start of each cycle.
// Then call statistics() to get the results, and resetStatistics()
// to start a new set of measurements.
// For acyclic threads, or for cyclic threads where you want to measure
// only part of each cycle, call enable(), disable(), and/or setEnabled()
// to demarcate the region(s) of interest, and then call sample() periodically.
// This class is not thread-safe for concurrent calls from multiple threads;
// the methods of this class may only be called by the current thread
// which constructed the object.
class ThreadCpuUsage
{
public:
ThreadCpuUsage() :
mIsEnabled(false),
mWasEverEnabled(false),
mAccumulator(0),
// mPreviousTs
// mMonotonicTs
mMonotonicKnown(false)
// mStatistics
{ }
~ThreadCpuUsage() { }
// Return whether currently tracking CPU usage by current thread
bool isEnabled() { return mIsEnabled; }
// Enable tracking of CPU usage by current thread;
// any CPU used from this point forward will be tracked.
// Returns the previous enabled status.
bool enable() { return setEnabled(true); }
// Disable tracking of CPU usage by current thread;
// any CPU used from this point forward will be ignored.
// Returns the previous enabled status.
bool disable() { return setEnabled(false); }
// Set the enabled status and return the previous enabled status.
// This method is intended to be used for safe nested enable/disabling.
bool setEnabled(bool isEnabled);
// Add a sample point for central tendency statistics, and also
// enable tracking if needed. If tracking has never been enabled, then
// enables tracking but does not add a sample (it is not possible to add
// a sample the first time because no previous). Otherwise if tracking is
// enabled, then adds a sample for tracked CPU ns since the previous
// sample, or since the first call to sampleAndEnable(), enable(), or
// setEnabled(true). If there was a previous sample but tracking is
// now disabled, then adds a sample for the tracked CPU ns accumulated
// up until the most recent disable(), resets this accumulator, and then
// enables tracking. Calling this method rather than enable() followed
// by sample() avoids a race condition for the first sample.
void sampleAndEnable();
// Add a sample point for central tendency statistics, but do not
// change the tracking enabled status. If tracking has either never been
// enabled, or has never been enabled since the last sample, then log a warning
// and don't add sample. Otherwise, adds a sample for tracked CPU ns since
// the previous sample or since the first call to sampleAndEnable(),
// enable(), or setEnabled(true) if no previous sample.
void sample();
// Return the elapsed delta wall clock ns since initial enable or statistics reset,
// as reported by clock_gettime(CLOCK_MONOTONIC).
long long elapsed() const;
// Reset statistics and elapsed. Has no effect on tracking or accumulator.
void resetStatistics();
// Return a const reference to the central tendency statistics.
// Note that only the const methods can be called on this object.
const CentralTendencyStatistics& statistics() const {
return mStatistics;
}
private:
bool mIsEnabled; // whether tracking is currently enabled
bool mWasEverEnabled; // whether tracking was ever enabled
long long mAccumulator; // accumulated thread CPU time since last sample, in ns
struct timespec mPreviousTs; // most recent thread CPU time, valid only if mIsEnabled is true
struct timespec mMonotonicTs; // most recent monotonic time
bool mMonotonicKnown; // whether mMonotonicTs has been set
CentralTendencyStatistics mStatistics;
};
#endif // _THREAD_CPU_USAGE_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/wand/wandmanager.h"
#include "modules/forms/formvalue.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#ifdef WAND_SUPPORT
#ifdef WAND_ECOMMERCE_SUPPORT
#define PREFS_NAMESPACE PrefsCollectionCore
const WandModule::ECOM_ITEM* GetECommerceItem(HTML_Element* he, const uni_char* name)
{
const uni_char* common_prefix = UNI_L("Ecom_");
const int common_prefix_len = 5;
// Can be smarter and more efficient
if (name && uni_strncmp(name, common_prefix, common_prefix_len) == 0)
{
const int item_count = ECOM_ITEMS_LEN;
const WandModule::ECOM_ITEM* eCom_items = g_opera->wand_module.m_eCom_items;
for (int i = 0; i < item_count; i++)
if (uni_str_eq(name+common_prefix_len, eCom_items[i].field_name))
return &eCom_items[i];
}
#ifdef WAND_GUESS_COMMON_FORMFIELD_MEANING
const WandModule::ECOM_ITEM* common_items = g_opera->wand_module.m_common_items;
if (name && he && he->Type() == HE_INPUT && he->GetInputType() == INPUT_TEXT)
{
const int item_count = ECOM_COMMON_ITEMS_LEN;
for (int i = 0; i < item_count; i++)
if (uni_stristr(name, common_items[i].field_name))
return &common_items[i];
}
if (he && he->Type() == HE_INPUT && he->GetInputType() == INPUT_EMAIL)
{
const int index_of_email_entry = 0; // See table above
OP_ASSERT(common_items[index_of_email_entry].pref_id == PREFS_NAMESPACE::EMail);
return common_items + index_of_email_entry;
}
#endif // WAND_GUESS_COMMON_FORMFIELD_MEANING
return NULL;
}
/* static */
BOOL WandManager::IsECommerceName(const uni_char* field_name)
{
return GetECommerceItem(NULL, field_name) ? TRUE : FALSE;
}
BOOL WandManager::CanImportValueFromPrefs(HTML_Element* he, const uni_char* field_name)
{
FormValue* form_value = he->GetFormValue();
if (form_value && form_value->IsChangedFromOriginal(he))
// Ignore changed formfields.
return FALSE;
const WandModule::ECOM_ITEM* item = GetECommerceItem(he, field_name);
if (item && item->pref_id != 0)
if (g_pccore->GetStringPref((PREFS_NAMESPACE::stringpref)item->pref_id).Length())
return TRUE;
return FALSE;
}
/* static */
OP_STATUS WandManager::ImportValueFromPrefs(HTML_Element* he, const uni_char* field_name, OpString& str)
{
const WandModule::ECOM_ITEM* item = GetECommerceItem(he, field_name);
OP_ASSERT(item && item->pref_id != 0);
return str.Set(g_pccore->GetStringPref((PREFS_NAMESPACE::stringpref)item->pref_id));
}
#endif // WAND_ECOMMERCE_SUPPORT
#endif // WAND_SUPPORT
|
//使用するヘッダーファイル
#include "GameL\DrawTexture.h"
#include "GameL\SceneManager.h"
#include "GameL\SceneObjManager.h"
#include "GameL\HitBoxManager.h"
#include "GameL\DrawFont.h"
#include "GameHead.h"
#include "ObjChangeGate1.h"
//使用するネームスペース
using namespace GameL;
extern bool m_change;
CObjChangeGate1::CObjChangeGate1(float x, float y)
{
m_px = x; //位置
m_py = y;
//当たり判定用のHitBoxを作成
Hits::SetHitBox(this, m_px, m_py, 32, 32, ELEMENT_MYSTERY, OBJ_CHANGEGATE, 1);
}
//イニシャライズ
void CObjChangeGate1::Init()
{
m_vx = 0.0f; //移動ベクトル
m_vy = 0.0f;
}
//アクション
void CObjChangeGate1::Action()
{
//自身のHitBoxを持ってくる
CHitBox* hit = Hits::GetHitBox(this);
CObjHero* hero = (CObjHero*)Objs::GetObj(COBJ_HERO);
//チェンジスイッチの情報を取得
CObjChangeSwitch* change = (CObjChangeSwitch*)Objs::GetObj(OBJ_CHANGESWITCH);
//チェンジフラグがオンの場合
if (m_change == false) {
hit->SetInvincibility(false); //無敵オフ
}
else {
hit->SetInvincibility(true); //無敵オン
}
//位置の更新
m_px += m_vx;
m_py += m_vy;
//ブロック情報を持ってくる
CObjBlock* block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK);
//HitBoxの位置の変更
hit->SetPos(m_px + block->GetScrollX(), m_py + block->GetScrollY());
}
//ドロー
void CObjChangeGate1::Draw()
{
//描画カラー情報
float c[4] = { 1.0f,1.0f,1.0f,1.0f };
float g[4] = { 0.0f,1.0f,1.0f,1.0f };
float a[4] = { 0.0f,0.0f,0.0f,0.0f };
RECT_F src; //描画元切り取り位置
RECT_F dst; //描画先表示位置
//切り取り位置の設定
src.m_top = 0.0f;
src.m_left = 0.0f;
src.m_right = 32.0f;
src.m_bottom = 32.0f;
CObjBlock* block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK);
//表示位置の設定
dst.m_top = 0.0f + m_py + block->GetScrollY(); //描画に対してスクロールの影響を加える
dst.m_left = 0.0f + m_px + block->GetScrollX();
dst.m_right = 32.0f + m_px + block->GetScrollX();
dst.m_bottom = 32.0f + m_py + block->GetScrollY();
//描画
if (m_change == false) {
Draw::Draw(2, &src, &dst, c, 0.0f);
}
}
|
// Helena Ruiz Ramirez
// A01282531
// Febrero 15, 2018
// Actividad Fecha
// Descripcion: Programa para mostrar fechas de acuerdo a
// un formato de estilo dd/nombre del mes/aa
#include <iostream>
#include <string>
#include "Fecha.h"
#include "Album.h"
using namespace std;
int main() {
int op=0,albumes=0;
Album arr[10];
Fecha f;
cout<<"Biblioteca de musica digital"<<endl;
do {
int dia,mes,anio,count=0;
string nom,artista,genero;
cout<<"1) Dar de alta albumes"<<endl;
cout<<"2) Mostrar la lista completa"<<endl;
cout<<"3) Buscar por artista"<<endl;
cout<<"4) Buscar por genero"<<endl;
cout<<"5) Salir"<<endl;
cout<<"¿Que desea hacer?: ";
cin>>op;
cout<<endl;
switch (op){
case 1:{
cout<<"¿Cuantos albumes quiere dar de alta?: ";
cin>>albumes;
while (albumes>5){
cout<<"Deben ser 10 o menos: ";
cin>>albumes;
}
cout<<endl;
for (int i=0;i<albumes;i++){
cout<<"Album "<<i+1<<"..."<<endl;
cout<<"Nombre: ";
cin.ignore();
getline(cin,nom);
arr[i].setNom(nom);
cout<<"Artista: ";
getline(cin,artista);
arr[i].setArtista(artista);
cout<<"Genero: ";
getline(cin,genero);
arr[i].setGenero(genero);
cout<<"Fecha de lanzamiento (dd/mm/aa):"<<endl;
cout<<"Dia: ";
cin>>dia;
f.setDia(dia);
cout<<"Mes: ";
cin>>mes;
f.setMes(mes);
cout<<"Año: ";
cin>>anio;
f.setAnio(anio);
arr[i].setLanz(f);
cout<<endl;
}
break;
}
case 2:{
for(int i=0;i<albumes;i++){
arr[i].Muestra();
cout<<endl;
}
break;
}
case 3:{
cout<<"¿Por cual artista quieres buscar?: ";
cin.ignore();
getline(cin,artista);
cout<<endl;
for (int i=0;i<albumes;i++){
string check=arr[i].getArtista();
if (artista==check){
count++;
arr[i].Muestra();
cout<<endl;
}
}
if (count==1){
cout<<"Se encontro "<<count<<" album del artista "<<artista<<endl;
}
else {
cout<<"Se encontraron "<<count<<" albumes del artista "<<artista<<endl;
}
break;
}
case 4:{
cout<<"¿Por cual genero quieres buscar?: ";
cin.ignore();
getline(cin,genero);
cout<<endl;
for (int i=0;i<albumes;i++){
string check=arr[i].getGenero();
if (genero==check){
count++;
arr[i].Muestra();
cout<<endl;
}
}
if (count==1){
cout<<"Se encontro "<<count<<" album del genero "<<artista<<endl;
}
else {
cout<<"Se encontraron "<<count<<" albumes del genero "<<artista<<endl;
}
break;
}
case 5:{
break;
}
}
cout<<"----------------------------"<<endl;
} while(op!=5);
cout<<endl;
return 0;
}
|
//===----RTLs/wasm32/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// RTL for WeebAssemblly machine
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <cstddef>
#include <list>
#include <string>
#include <vector>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "omptargetplugin.h"
#ifndef TARGET_NAME
#define TARGET_NAME WASM32
#endif
#ifdef OMPTARGET_DEBUG
static int DebugLevel = 1;
#define GETNAME2(name) #name
#define GETNAME(name) GETNAME2(name)
#define DP(...) \
do { \
if (DebugLevel > 0) { \
DEBUGP("Target " GETNAME(TARGET_NAME) " RTL", __VA_ARGS__); \
} \
} while (false)
#else // OMPTARGET_DEBUG
#define DP(...) {}
#endif // OMPTARGET_DEBUG
#include "../../common/elf_common.c"
/// Keep entries table per device.
struct FuncOrGblEntryTy {
__tgt_target_table Table;
std::vector<__tgt_offload_entry> Entries;
};
/// Device envrionment data
/// Manually sync with the deviceRTL side for now, move to a dedicated header file later.
struct omptarget_device_environmentTy {
int32_t debug_level;
};
struct DataTy {
void* hostptr;
void* devptr;
int64_t size; // can't really be more than 4GB
void* buf; // can be NULL if uninitialized
};
struct DeviceTy {
std::vector<__tgt_offload_entry> Entries;
__tgt_target_table Table;
int64_t DataPtrNext;
std::map<int64_t, DataTy*> Data;
// we don't really need this
// OpenMP properties
// int NumTeams;
// int NumThreads;
void addOffloadEntry( __tgt_offload_entry& entry) {
Entries.push_back(entry);
}
__tgt_offload_entry* findOffloadEntry(void *addr) {
for (auto &it : Entries) {
if (it.addr == addr)
return ⁢
}
return NULL;
}
// Return the pointer to the target entries table
__tgt_target_table *getOffloadEntriesTable() {
int32_t size = Entries.size();
// Table is empty
if (!size)
return 0;
__tgt_offload_entry *begin = &Entries[0];
__tgt_offload_entry *end = &Entries[size - 1];
// Update table info according to the entries and return the pointer
Table.EntriesBegin = begin;
Table.EntriesEnd = ++end;
return &Table;
}
void clearOffloadEntriesTable() {
Entries.clear();
Table.EntriesBegin = Table.EntriesEnd = 0;
}
void *allocData(void *hostptr, int64_t size) {
DataTy *al;
int64_t devptr;
if (size == 0 || size >= 0x100000000L)
return NULL;
devptr = DataPtrNext;
DataPtrNext += size;
al = new DataTy;
al->hostptr = hostptr;
al->devptr = (void *) devptr;
al->size = size;
al->buf = NULL;
Data.insert(std::make_pair(devptr, al));
return al->devptr;
}
bool copyToData(void *devptr, void *hostptr, int64_t size) {
DataTy *al = Data[(int64_t) devptr];
if (al == NULL)
return false;
if (al->size != size)
return false;
if (al->buf == NULL) {
al->buf = malloc(al->size);
if (al->buf == NULL)
return false;
}
memcpy(al->buf, hostptr, size);
return true;
}
bool copyFromData(void *hostptr, void *devptr, int64_t size) {
DataTy *al = Data[(int64_t) devptr];
if (al == NULL || al->buf == NULL)
return false;
if (al->size != size)
return false;
memcpy(hostptr, al->buf, size);
return true;
}
bool deleteData(void *devptr) {
DataTy *al = Data[(int64_t) devptr];
if (al == NULL)
return false;
if (al->buf) {
free(al->buf);
al->buf = NULL;
}
Data.erase((int64_t) devptr);
delete(al);
return true;
}
};
/// Class containing all the device information.
class RTLDeviceInfoTy {
std::vector<DeviceTy> Devices;
public:
int NumberOfDevices;
// OpenMP Environment properties
int EnvNumTeams;
int EnvTeamLimit;
//static int EnvNumThreads;
static const int HardTeamLimit = 1<<16; // 64k
static const int HardThreadLimit = 1024;
static const int DefaultNumTeams = 128;
static const int DefaultNumThreads = 128;
RTLDeviceInfoTy() {
#ifdef OMPTARGET_DEBUG
if (char *envStr = getenv("LIBOMPTARGET_DEBUG")) {
DebugLevel = std::stoi(envStr);
}
#endif // OMPTARGET_DEBUG
// TODO: put the actual ceph code once it is implemented
NumberOfDevices = 1;
Devices.resize(NumberOfDevices);
// Get environment variables regarding teams
char *envStr = getenv("OMP_TEAM_LIMIT");
if (envStr) {
// OMP_TEAM_LIMIT has been set
EnvTeamLimit = std::stoi(envStr);
DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
} else {
EnvTeamLimit = -1;
}
envStr = getenv("OMP_NUM_TEAMS");
if (envStr) {
// OMP_NUM_TEAMS has been set
EnvNumTeams = std::stoi(envStr);
DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
} else {
EnvNumTeams = -1;
}
}
~RTLDeviceInfoTy() {
// TODO: free the ceph resources
}
DeviceTy& getDevice(int32_t device_id) {
assert(device_id < (int32_t)Devices.size() && "Unexpected device id!");
return Devices[device_id];
}
};
static RTLDeviceInfoTy DeviceInfo;
#ifdef __cplusplus
extern "C" {
#endif
int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
// return elf_check_machine(image, 190); // EM_CUDA = 190.
char *start = (char *) image->ImageStart;
char *end = (char *) image->ImageEnd;
int size = end - start;
if (size < 4)
return false;
// wasm module starts with \0asm
if (start[0] != '\0' || start[1] != 'a' || start[2] != 's' || start[3] != 'm')
return false;
return true;
}
int32_t __tgt_rtl_number_of_devices() {
return DeviceInfo.NumberOfDevices;
}
int32_t __tgt_rtl_init_device(int32_t device_id) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
dev.DataPtrNext = 16; // TODO: is this good number?
// TODO: initialize ceph?
return OFFLOAD_SUCCESS;
}
__tgt_target_table *__tgt_rtl_load_binary(int32_t device_id, __tgt_device_image *image) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
// Clear the offload table as we are going to create a new one.
dev.clearOffloadEntriesTable();
// Create the module and extract the function pointers.
DP("Load data from image " DPxMOD " " DPxMOD "\n", DPxPTR(image->ImageStart), DPxPTR(image->ImageEnd));
// TODO:
DP("Wasm32 module successfully loaded!\n");
// Find the symbols in the module by name.
__tgt_offload_entry *HostBegin = image->EntriesBegin;
__tgt_offload_entry *HostEnd = image->EntriesEnd;
for (__tgt_offload_entry *e = HostBegin; e != HostEnd; ++e) {
if (!e->addr) {
// We return NULL when something like this happens, the host should have
// always something in the address to uniquely identify the target region.
DP("Invalid binary: host entry '<null>' (size = %zd)...\n", e->size);
return NULL;
}
if (e->size) {
// TODO: no idea what this is
DP("Entry point to global %s\n", e->name);
dev.addOffloadEntry(*e);
} else {
DP("Entry point %s\n", e->name);
// __tgt_offload_entry entry = *e;
dev.addOffloadEntry(*e);
}
}
{
int fd = open("omp.wasm", O_CREAT | O_RDWR | O_TRUNC, 0666);
write(fd, image->ImageStart, (char *) image->ImageEnd - (char *) image->ImageStart);
close(fd);
}
return dev.getOffloadEntriesTable();
}
void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *hst_ptr) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
DP("Data alloc size %ld hostptr %p\n", size, hst_ptr);
return dev.allocData(hst_ptr, size);
}
int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr, int64_t size) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
DP("Data submit size %ld tgtptr %p hostptr %p\n", size, tgt_ptr, hst_ptr);
return dev.copyToData(tgt_ptr, hst_ptr, size)?OFFLOAD_SUCCESS:OFFLOAD_FAIL;
}
int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr, int64_t size) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
DP("Data retrieve size %ld tgtptr %p hostptr %p\n", size, tgt_ptr, hst_ptr);
return dev.copyFromData(hst_ptr, tgt_ptr, size)?OFFLOAD_SUCCESS:OFFLOAD_FAIL;
}
int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
DP("Data delete tgtptr %p\n", tgt_ptr);
return dev.deleteData(tgt_ptr)?OFFLOAD_SUCCESS:OFFLOAD_FAIL;
}
int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
int32_t thread_limit, uint64_t loop_tripcount) {
return __tgt_rtl_run_target_region(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num);
}
int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num) {
DeviceTy& dev = DeviceInfo.getDevice(device_id);
__tgt_offload_entry* e = dev.findOffloadEntry(tgt_entry_ptr);
if (e == NULL) {
DP("__tgt_rtl_run_target_region: can't find entry point %p\n", tgt_entry_ptr);
return OFFLOAD_FAIL;
}
DP("target team region: entry '%s' arg_num %d\n", e->name, arg_num);
for(int i = 0; i < arg_num; i++) {
DP("\tArg %d: %p + %ld\n", i, tgt_args[i], tgt_offsets[i]);
}
// TODO
return OFFLOAD_SUCCESS;
}
#ifdef __cplusplus
}
#endif
|
/*
* ====================================================================
* Pyrecog.cpp
*
* Recognizer plug-in
*
* Copyright (c) 2005 Nokia Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
#include <apmrec.h>
#include <apmstd.h>
#include <f32file.h>
const TUid KUidPyrecog = {0x10201513};
class CApaPyRecognizer : public CApaDataRecognizerType
{
public:
CApaPyRecognizer():CApaDataRecognizerType(KUidPyrecog, EHigh) {
iCountDataTypes = 1;
}
virtual TUint PreferredBufSize() {return 0x10;}
virtual TDataType SupportedDataTypeL(TInt /*aIndex*/) const {
return TDataType(_L8("x-application/x-python"));
}
private:
virtual void DoRecognizeL(const TDesC& aName, const TDesC8& aBuffer);
};
void CApaPyRecognizer::DoRecognizeL(const TDesC& aName, const TDesC8& /*aBuffer*/)
{
TParsePtrC p(aName);
if ((p.Ext().CompareF(_L(".py")) == 0) ||
(p.Ext().CompareF(_L(".pyc")) == 0) ||
(p.Ext().CompareF(_L(".pyo")) == 0) ||
(p.Ext().CompareF(_L(".pyd")) == 0))
{
iConfidence = ECertain;
iDataType = TDataType(_L8("x-application/x-python"));
}
}
EXPORT_C CApaDataRecognizerType* CreateRecognizer()
{
return new CApaPyRecognizer;
}
GLDEF_C TInt E32Dll(TDllReason /*aReason*/)
{
return KErrNone;
}
|
#ifndef PERSISTENCE_PERSISTER_H
#define PERSISTENCE_PERSISTER_H
#include <string>
#include "../model/image.h"
namespace persistence {
// Encapsulates a persister that could load and save images.
class Persister {
public:
// Loads the image file specified by the value of fileName.
virtual model::Image *load(const std::string &fileName) = 0;
// Saves image to a file with named with the value of fileName.
virtual void save(model::Image *image, const std::string &fileName) = 0;
};
};
#endif
|
#ifndef SIMPLE_MEM_IF_H
#define SIMPLE_MEM_IF_H
#include <systemc.h>
#include <math.h>
#include "assignment_part.h"
#define NUM_BLOCKS 1
#define BLOCK_SIZE 3
#define INPUT1_ADDR 0
#define INPUT2_ADDR 3
#define SAD_OUTPUT_ADDR 6
#define MEM_SIZE 10
class simple_mem_if : virtual public sc_interface
{
public:
virtual bool Write(unsigned int addr, unsigned int data) = 0;
virtual bool Read(unsigned int addr, unsigned int& data) = 0;
};
#endif // SIMPLE_MEM_IF_H
|
#ifndef FEK_DAEMONIZE_HPP
#define FEK_DAEMONIZE_HPP
// posix
#include <unistd.h> // fork, close, getpid, write, ...
#include <syslog.h> // syslog closer
#include <signal.h> // sig_atomic_t
#include <fcntl.h> // open pid file
#include <sys/stat.h> // umask
// libc
#include <cerrno> // fork on failure writes error on errno
#include <cassert>
#include <cstring> // strerror
// std
#include <limits>
#include <stdexcept>
#include <string>
// from c++17
template <typename T>
const T& myclamp(const T& n, const T& lower, const T& upper) {
return std::max(lower, std::min(n, upper));
}
struct update_flag{
volatile sig_atomic_t& flag; // common signature for flag in signal handler
sig_atomic_t val_out;
update_flag(volatile sig_atomic_t& flag_, sig_atomic_t val_in_, sig_atomic_t val_out_) : flag(flag_), val_out(val_out_){
flag = val_in_;
}
update_flag(volatile sig_atomic_t& flag_, sig_atomic_t val_out_) : flag(flag_), val_out(val_out_){}
~update_flag(){
flag = val_out;
}
};
inline std::string errno_to_string(const int error){
// for some reason, I'm unable to pick the right strerror_r -> using the not thread safe variant
const std::string err = strerror(error);
/*
std::string err(32, '\0');
auto res = strerror_r(error, &err.at(0), err.size());
while(res == ERANGE){
err.resize(err.size()*2);
res = strerror_r(error, &err.at(0), err.size());
}
assert( err != EINVAL);
err = err.c_str(); // remove trailing '\0'
*/
return err;
}
// terminates parent with EXIT_SUCCESS if ok, terminates with EXIT_FAILURE if not
// FIXME: unclear if I should use exit or _exit
// _exit does not remove tmpfiles, exit does...
inline void fork_and_close_parent(){
// Fork off the parent process
const auto pid = fork();
// Check if an error occurred
if (pid < 0) { // fork failed, return error
const auto err = errno;
throw std::runtime_error("fork failed with following error:" + errno_to_string(err));
}
// Success: Let the parent terminate
if (pid > 0) { // We are parent: _exit() or exit() ?
exit(EXIT_SUCCESS);
}
}
class open_file_descriptor{
public:
int fd = -1;
// fd should be a valid and opened file descriptor
explicit open_file_descriptor(const int fd_ = -1) : fd(fd_){}
// copy
open_file_descriptor(const open_file_descriptor&) = delete;
// move
open_file_descriptor& operator=(const open_file_descriptor&) = delete;
open_file_descriptor(open_file_descriptor&& of) noexcept :fd(of.fd){
of.fd = -1;
}
open_file_descriptor& operator=(open_file_descriptor&& other){
if(this != &other){
fd = other.fd;
other.fd = -1;
}
return *this;
}
~open_file_descriptor(){
if(fd != -1){
close(fd);
}
}
};
struct syslog_closer{
syslog_closer(){}
syslog_closer(const syslog_closer&) = delete;
~syslog_closer(){
closelog();
}
};
class lock_file{
public:
int fd = -1;
int lockres = -1;
explicit lock_file(const int fd_ = -1) :fd(fd_){
lockres = lockf(fd_, F_TLOCK, 0);
}
static lock_file create_or_throw(const int fd){
const auto lockres = lockf(fd, F_TLOCK, 0);
if (lockres< 0) {
const auto err = errno;
throw std::runtime_error("lockf failed with following error:" + errno_to_string(err));
}
lock_file lf;
lf.fd = fd;
lf.lockres = lockres;
return lf;
}
// copy
lock_file(const lock_file&) = delete;
lock_file& operator=(const lock_file&) = delete;
// move
lock_file(lock_file&& o) noexcept : fd(o.fd), lockres(o.lockres){
o.fd = -1;
o.lockres = -1;
}
lock_file& operator=(lock_file&& o){
if(this != &o){
o.fd = -1;
o.lockres = -1;
}
return *this;
}
~lock_file(){
if(lockres >= 0){
lockf(fd, F_ULOCK, 0);
}
}
};
class locked_file{
public:
open_file_descriptor openfile_;
lock_file lock_file_;
locked_file() = default;
locked_file(open_file_descriptor openfile__, lock_file lock_file__) :
openfile_(std::move(openfile__)), lock_file_(std::move(lock_file__)){
assert(openfile_.fd == lock_file_.fd);
}
// copy
locked_file(const locked_file&) = delete;
locked_file& operator=(const locked_file&) = delete;
// move
locked_file(locked_file&& o) noexcept : openfile_(std::move(o.openfile_)), lock_file_(std::move(o.lock_file_)){
}
locked_file& operator=(locked_file&& o){
if(this != &o){
openfile_ = std::move(o.openfile_);
lock_file_ = std::move(o.lock_file_);
}
return *this;
}
};
inline locked_file create_pid_file(const std::string& pid_file){
const int fd = open(pid_file.c_str(), O_RDWR|O_CREAT, 0640);
if(fd == -1){
const auto err = errno;
throw std::runtime_error("open failed with following error:" + errno_to_string(err));
}
open_file_descriptor file(fd);
lock_file lf = lock_file::create_or_throw(fd);
locked_file toreturn(std::move(file), std::move(lf));
// save PID to file
const auto pid = std::to_string(getpid()) + "\n";
const auto write_res = write(fd, pid.c_str(), pid.size());
if(write_res == static_cast<decltype(write_res)>(-1)){
const auto err = errno;
throw std::runtime_error("writing pid to file failed with following error:" + errno_to_string(err));
}
return toreturn;
}
inline void daemonize(){
// Fork off the parent process
fork_and_close_parent();
// The child process becomes session leader
if (setsid() < 0) {
exit(EXIT_FAILURE);
}
// Ignore signal sent from child to parent process
signal(SIGCHLD, SIG_IGN);
// Fork off for the second time
fork_and_close_parent();
// Set new file permissions
const auto old_mode = umask(0);
(void)old_mode;
// Change the working directory to the root directory
// or another appropriated directory
const auto chdir_res = chdir("/");
if(chdir_res != 0){
// what to do? we have already forked once -> is it ok to chdir before the first fork?
const auto err = errno;
throw std::runtime_error("open failed with following error:" + errno_to_string(err));
}
// Close all open file descriptors
// since close takes a positive int, (and sysconf returns a long) ignore those outside the [0, max_int] range
constexpr long i_max{std::numeric_limits<int>::max()};
const auto first_fd = sysconf(_SC_OPEN_MAX);
const auto first_fd_i = static_cast<int>(myclamp(first_fd, 0l, i_max));
for (auto fd = first_fd_i; fd > 0; fd--) {
close(fd);
}
// Reopen stdin (fd = 0), stdout (fd = 1), stderr (fd = 2)
stdin = fopen("/dev/null", "r");
stdout = fopen("/dev/null", "w+");
stderr = fopen("/dev/null", "w+");
}
#endif
|
#include "gtest/gtest.h"
#include "wali/Reach.hpp"
#include "wali/wpds/WPDS.hpp"
#include "wali/wfa/TransFunctor.hpp"
using namespace wali;
using namespace wali::wpds;
using namespace wali::wfa;
namespace {
struct SimpleQuery
{
Key start, accept, symbol;
WFA wfa;
sem_elem_t one, zero;
SimpleQuery()
: start(getKey("start"))
, accept(getKey("accept"))
, symbol(getKey("symbol"))
, one(Reach(true).one())
, zero(Reach(true).zero())
{
wfa.addState(start, zero);
wfa.addState(accept, zero);
wfa.setInitialState(start);
wfa.addFinalState(accept);
wfa.addTrans(start, symbol, accept, one);
}
};
}
TEST(wali$wpds$WPDS$prestar, canTakePrestarOfEmptyWpds)
{
WPDS empty;
SimpleQuery query;
WFA result = empty.prestar(query.wfa);
TransCounter counter;
result.for_each(counter);
EXPECT_EQ(2u, result.numStates());
EXPECT_EQ(1, counter.getNumTrans());
}
TEST(wali$wpds$WPDS$poststar, canTakePoststarOfEmptyWpds)
{
WPDS empty;
SimpleQuery query;
WFA result = empty.poststar(query.wfa);
TransCounter counter;
result.for_each(counter);
EXPECT_EQ(2u, result.numStates());
EXPECT_EQ(1u, counter.getNumTrans());
}
|
//
// Created by Nikita Kruk on 25.07.18.
//
#include "Thread.hpp"
#include <cassert>
#if defined(MPI_PARALLELIZATION)
#include <mpi.h>
#endif
#if defined(MPI_PARALLELIZATION)
Thread::Thread(int argc, char **argv)
{
root_rank_ = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &rank_);
MPI_Comm_size(MPI_COMM_WORLD, &number_of_mpich_threads_);
}
#else
Thread::Thread(int argc, char **argv)
{
root_rank_ = 0;
rank_ = 0;
number_of_mpich_threads_ = 1;
}
#endif
#if defined(MPI_PARALLELIZATION)
Thread::~Thread()
{
}
#else
Thread::~Thread()
{
}
#endif
#if defined(MPI_PARALLELIZATION)
bool Thread::IsRoot()
{
return (rank_ == root_rank_);
}
#else
bool Thread::IsRoot()
{
return true;
}
#endif
#if defined(MPI_PARALLELIZATION)
int Thread::GetNumberOfMpichThreads()
{
return number_of_mpich_threads_;
}
#else
int Thread::GetNumberOfMpichThreads()
{
return number_of_mpich_threads_;
}
#endif
#if defined(MPI_PARALLELIZATION)
int Thread::GetRank()
{
return rank_;
}
#else
int Thread::GetRank()
{
return 0;
}
#endif
|
// Created on: 1995-12-01
// Created by: EXPRESS->CDL V0.2 Translator
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepShape_BrepWithVoids_HeaderFile
#define _StepShape_BrepWithVoids_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepShape_HArray1OfOrientedClosedShell.hxx>
#include <StepShape_ManifoldSolidBrep.hxx>
#include <Standard_Integer.hxx>
class TCollection_HAsciiString;
class StepShape_ClosedShell;
class StepShape_OrientedClosedShell;
class StepShape_BrepWithVoids;
DEFINE_STANDARD_HANDLE(StepShape_BrepWithVoids, StepShape_ManifoldSolidBrep)
class StepShape_BrepWithVoids : public StepShape_ManifoldSolidBrep
{
public:
//! Returns a BrepWithVoids
Standard_EXPORT StepShape_BrepWithVoids();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepShape_ClosedShell)& aOuter, const Handle(StepShape_HArray1OfOrientedClosedShell)& aVoids);
Standard_EXPORT void SetVoids (const Handle(StepShape_HArray1OfOrientedClosedShell)& aVoids);
Standard_EXPORT Handle(StepShape_HArray1OfOrientedClosedShell) Voids() const;
Standard_EXPORT Handle(StepShape_OrientedClosedShell) VoidsValue (const Standard_Integer num) const;
Standard_EXPORT Standard_Integer NbVoids() const;
DEFINE_STANDARD_RTTIEXT(StepShape_BrepWithVoids,StepShape_ManifoldSolidBrep)
protected:
private:
Handle(StepShape_HArray1OfOrientedClosedShell) voids;
};
#endif // _StepShape_BrepWithVoids_HeaderFile
|
#pragma once
/****************************************************************************
* Copyright (c) 2011 GeoMind Srl. www.geomind.it
* All rights reserved.
*
*---------------------------------------------------------------------------
* This software is part of the GeoTree library by GeoMind Srl;
* it is not allowed to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of software in parts or as a whole,
* in source and binary forms, without a written permission of GeoMind Srl.
*
****************************************************************************/
#ifndef CGeoTile_h
#define CGeoTile_h
#include "CPoints3d.h"
// ==========================================================================
// CGeoTile
// ==========================================================================
/**
* \brief unitary terrain object
*
* \internal
**/
// forward declaration
class CGeoTerrain;
class CGeoTile
{
public:
// bool original;
// constructor and destructor
CGeoTile( CGeoTerrain* inTerrain );
virtual ~CGeoTile();
// initialization
void SetupTile( int inLevel, int posX, int posY, const GeoRect& inR );
void SetTileRect( const GeoRect& inR ){ mBounds=inR; };
int GetLevel() const { return mLevel; };
const IPoint& GetPosId() const { return mPosId; };
CGeoTerrain* GetTerrain() const { return mTerrain; };
int GetTerrainId() const;
protected:
// implementation data
CGeoTerrain* mTerrain; ///< owner terrain
CGeoTile* mParent; ///< ptr to parent tile, if any
int mLevel; ///< tile level, with 0=root
IPoint mPosId; ///< tile position, in its level; [0,0] is left top
enum ESubTileFlag
{
eSubtileLeft=0,
eSubtileTop=0,
eSubtileRight=1,
eSubtileBottom=2
}; ///< bit flags whose combination indicates sub-tile position
enum ESubTileId
{
eSubtileIdLT=eSubtileLeft | eSubtileTop,
eSubtileIdRT=eSubtileRight | eSubtileTop,
eSubtileIdLB=eSubtileLeft | eSubtileBottom,
eSubtileIdRB=eSubtileRight | eSubtileBottom
}; ///< identifier of sub-tile position
ESubTileId mSubTileId; ///< sub-tile position in parent tile
// --- sub-tiles config
enum ESubTileConfigFlag
{
eSubTileNone = 0,
eSubTileLT = (1 >> eSubtileIdLT),
eSubTileRT = (1 >> eSubtileIdRT),
eSubTileLB = (1 >> eSubtileIdLB),
eSubTileRB = (1 >> eSubtileIdRB),
eSubTileAll = eSubTileLT | eSubTileRT | eSubTileLB | eSubTileRB
}; ///< used to specify if a tile exists
ESubTileConfigFlag mSubTilesFlags; ///< 4 bits flags indicating where there can be sub-tiles; each bit corresponds to the sub-tile position
int mMaxSubTileCount; ///< how many sub-tiles it can have; this must be in synch with mSubTileFlags
// --- sub-tiles running prop
CGeoTile* mSubTiles[4]; ///< sub-tiles pointers
int mSubTileCount; ///< how many sub-tiles there are currently
// --- geo-refs
GeoRect mBounds; ///< in absolute world coords
double mMinZ, mMaxZ;
FPoint3d mCenter; ///< center of the tile in 3D absolute coords
double mRadius; ///< radius of the sphere enclosing the tile
double mDistance; ///< it is the distance from the tile bounding sphere to the closest camera
///< (radius is taken into account)
bool mIsInViewFrustum; ///< current tile visibility
double mScreenPixSize; ///< this is the size of a screen pixel on the ground tile (closest part)
bool mIsInWorld; ///< states if the tile is rendered
// ----- subtiles ----------
inline void GetSubTileBounds( ESubTileId inSubId, GeoRect* outRect ); ///< retrieves the sub-tile rect in terrain coords
//// --- loading stuffs
//list<CGeoTile*> mLoadingSubTiles; ///< sub-tiles currently under loading
//CGeoTileLoader* mLoaderObj; ///< loader obj in charge of loading this
//bool mDoLoadMesh; ///< to be used in loader, to know if only texture update
// ///< is needed or if the mesh too needs to be loaded
//int mTxtRes; ///< current texture resolution
//int mTargetRes; ///< resolution to be loaded
//int mThemeIdx; ///< current theme
//int mTargetThemeIdx; ///< theme to be loaded
//string mMeshUrl[2];
//string mTxtUrl[2];
//int mCacheIdx;
//unsigned int mClusterId; ///< id of the cluster to be loaded
//TileCluster* mClusterObj;
//gmi::CPixmap* mTxtImage;
//IRect mTxtBaseRect; ///< rect of tile in the base texture image
//// --- mesh model
//gg3d::CModel* mModel; ///< ptr to terrain mesh model; texture is stored here
//CGeoTileContext* mTileContext;
//// --- vector textures
//CTxtTile* mTxtTile;
//CTxtTile* mLoadingTxtTile;
//// --- buildings
//CBldTile* mBldTile;
//void UpdateBuildings( gg3d::CCamera* inCamera, bool inCategoryChange );
//bool TileHasBuildings();
public:
// ==========================================================================
// GeoTileSort
// ==========================================================================
class GeoTileSort
{
public:
inline bool operator()( const CGeoTile *t1, const CGeoTile *t2 ) const
{ return t1->mDistance < t2->mDistance; };
};
private:
void InitCommon();
}; // class CGeoTile
#endif // CGeoTile_h
|
// Created on: 1996-01-26
// Created by: Philippe MANGIN
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _FairCurve_BattenLaw_HeaderFile
#define _FairCurve_BattenLaw_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Real.hxx>
#include <math_Function.hxx>
#include <Standard_Boolean.hxx>
//! This class compute the Heigth of an batten
class FairCurve_BattenLaw : public math_Function
{
public:
DEFINE_STANDARD_ALLOC
//! Constructor of linear batten with
//! Heigth : the Heigth at the middle point
//! Slope : the geometric slope of the batten
//! Sliding : Active Length of the batten without extension
Standard_EXPORT FairCurve_BattenLaw(const Standard_Real Heigth, const Standard_Real Slope, const Standard_Real Sliding);
//! Change the value of sliding
void SetSliding (const Standard_Real Sliding);
//! Change the value of Heigth at the middle point.
void SetHeigth (const Standard_Real Heigth);
//! Change the value of the geometric slope.
void SetSlope (const Standard_Real Slope);
//! computes the value of the heigth for the parameter T
//! on the neutral fibber
virtual Standard_Boolean Value (const Standard_Real T, Standard_Real& THeigth) Standard_OVERRIDE;
protected:
private:
Standard_Real MiddleHeigth;
Standard_Real GeometricSlope;
Standard_Real LengthSliding;
};
#include <FairCurve_BattenLaw.lxx>
#endif // _FairCurve_BattenLaw_HeaderFile
|
// maindriver.cc
// 2/1/2013 jichi
#include "config.h"
#include "driver/maindriver.h"
#include "driver/maindriver_p.h"
#include "driver/rpcclient.h"
#include "driver/settings.h"
#include "embed/embeddriver.h"
#include "hijack/hijackdriver.h"
#include "hijack/hijackdriver.h"
#include "window/windowdriver.h"
#include "windbg/unload.h"
#define DEBUG "maindriver"
#include "sakurakit/skdebug.h"
/** Public class */
MainDriver::MainDriver(QObject *parent)
: Base(parent), d_(new D(this))
{
connect(this, SIGNAL(deleteLaterRequested()), SLOT(deleteLater()), Qt::QueuedConnection);
}
MainDriver::~MainDriver() { delete d_; }
void MainDriver::requestDeleteLater() { emit deleteLaterRequested(); }
void MainDriver::quit() { d_->quit(); }
/** Private class */
MainDriverPrivate::MainDriverPrivate(QObject *parent)
: Base(parent), settings(nullptr), rpc(nullptr), hijack(nullptr), win(nullptr), eng(nullptr)
{
DOUT("enter");
settings = new Settings(this);
{
connect(settings, SIGNAL(loadFinished()), SLOT(onLoadFinished()));
}
rpc = new RpcClient(this);
{
//connect(rpc, SIGNAL(enableWindowTranslationRequested(bool)), settings, SLOT(setWindowTranslationEnabled(bool)));
connect(rpc, SIGNAL(disconnected()), SLOT(onDisconnected()));
connect(rpc, SIGNAL(detachRequested()), SLOT(unload()));
//connect(rpc, SIGNAL(enabledRequested(bool)), settings, SLOT(setEnabled(bool)));
connect(rpc, SIGNAL(settingsReceived(QString)), settings, SLOT(load(QString)));
connect(rpc, SIGNAL(disableRequested()), settings, SLOT(disable()));
}
DOUT("leave");
}
void MainDriverPrivate::quit()
{
if (eng)
eng->quit();
rpc->quit();
}
void MainDriverPrivate::createHijackDriver()
{
if (hijack)
return;
hijack = new HijackDriver(this);
hijack->setEncoding(settings->gameEncoding());
hijack->setFontFamily(settings->embeddedFontFamily());
hijack->setFontCharSet(settings->embeddedFontCharSet());
hijack->setFontCharSetEnabled(settings->isEmbeddedFontCharSetEnabled());
hijack->setFontScale(settings->embeddedFontScale());
hijack->setFontWeight(settings->embeddedFontWeight());
connect(settings, SIGNAL(gameEncodingChanged(QString)), hijack, SLOT(setEncoding(QString)));
connect(settings, SIGNAL(embeddedFontFamilyChanged(QString)), hijack, SLOT(setFontFamily(QString)));
connect(settings, SIGNAL(embeddedFontCharSetChanged(int)), hijack, SLOT(setFontCharSet(int)));
connect(settings, SIGNAL(embeddedFontCharSetEnabledChanged(bool)), hijack, SLOT(setFontCharSetEnabled(bool)));
connect(settings, SIGNAL(embeddedFontScaleChanged(float)), hijack, SLOT(setFontScale(float)));
connect(settings, SIGNAL(embeddedFontWeightChanged(int)), hijack, SLOT(setFontWeight(int)));
if (eng) {
hijack->setDeviceContextFontEnabled(eng->isDeviceContextFontEnabled());
hijack->setLocaleEmulationEnabled(eng->isLocaleEmulationEnabled());
}
}
void MainDriverPrivate::createWindowDriver()
{
if (win)
return;
win = new WindowDriver(this);
win->setEncoding(settings->gameEncoding());
win->setTextVisible(settings->isWindowTextVisible());
win->setTranscodingEnabled(settings->isWindowTranscodingEnabled());
win->setTranslationEnabled(settings->isWindowTranslationEnabled());
connect(settings, SIGNAL(gameEncodingChanged(QString)), win, SLOT(setEncoding(QString)));
connect(settings, SIGNAL(windowTextVisibleChanged(bool)), win, SLOT(setTextVisible(bool)));
connect(settings, SIGNAL(windowTranscodingEnabledChanged(bool)), win, SLOT(setTranscodingEnabled(bool)));
connect(settings, SIGNAL(windowTranslationEnabledChanged(bool)), win, SLOT(setTranslationEnabled(bool)));
connect(win, SIGNAL(translationRequested(QString)), rpc, SLOT(requestWindowTranslation(QString)));
connect(rpc, SIGNAL(clearTranslationRequested()), win, SLOT(clearTranslation()));
connect(rpc, SIGNAL(windowTranslationReceived(QString)), win, SLOT(updateTranslation(QString)));
win->setEnabled(settings->isWindowDriverNeeded()); // enable it at last
}
void MainDriverPrivate::createEmbedDriver()
{
if (eng)
return;
eng = new EmbedDriver(this);
// Use queued connection to quarantine the engine thrread
connect(eng, SIGNAL(textReceived(QString,qint64,long,int,bool)), rpc, SLOT(sendEngineText(QString,qint64,long,int,bool)),
Qt::QueuedConnection);
//connect(eng, SIGNAL(textReceivedDelayed(QString,qint64,int,bool)), rpc, SLOT(sendEngineTextLater(QString,qint64,int,bool)),
// Qt::QueuedConnection);
connect(eng, SIGNAL(engineNameChanged(QString)), rpc, SLOT(sendEngineName(QString)));
connect(rpc, SIGNAL(clearTranslationRequested()), eng, SLOT(clearTranslation()));
//connect(rpc, SIGNAL(enableEngineRequested(bool)), eng, SLOT(setEnable(bool)));
//connect(rpc, SIGNAL(engineTranslationReceived(QString,qint64,int,QString)), eng, SLOT(updateTranslation(QString,qint64,int,QString)));
connect(rpc, SIGNAL(reconnected()), eng, SLOT(sendEngineName()));
connect(settings, SIGNAL(embeddedScenarioVisibleChanged(bool)), eng, SLOT(setScenarioVisible(bool)));
connect(settings, SIGNAL(embeddedScenarioTextVisibleChanged(bool)), eng, SLOT(setScenarioTextVisible(bool)));
connect(settings, SIGNAL(embeddedScenarioTranscodingEnabledChanged(bool)), eng, SLOT(setScenarioTranscodingEnabled(bool)));
connect(settings, SIGNAL(embeddedScenarioTranslationEnabledChanged(bool)), eng, SLOT(setScenarioTranslationEnabled(bool)));
connect(settings, SIGNAL(embeddedNameVisibleChanged(bool)), eng, SLOT(setNameVisible(bool)));
connect(settings, SIGNAL(embeddedNameTextVisibleChanged(bool)), eng, SLOT(setNameTextVisible(bool)));
connect(settings, SIGNAL(embeddedNameTranscodingEnabledChanged(bool)), eng, SLOT(setNameTranscodingEnabled(bool)));
connect(settings, SIGNAL(embeddedNameTranslationEnabledChanged(bool)), eng, SLOT(setNameTranslationEnabled(bool)));
connect(settings, SIGNAL(embeddedOtherVisibleChanged(bool)), eng, SLOT(setOtherVisible(bool)));
connect(settings, SIGNAL(embeddedOtherTextVisibleChanged(bool)), eng, SLOT(setOtherTextVisible(bool)));
connect(settings, SIGNAL(embeddedOtherTranscodingEnabledChanged(bool)), eng, SLOT(setOtherTranscodingEnabled(bool)));
connect(settings, SIGNAL(embeddedOtherTranslationEnabledChanged(bool)), eng, SLOT(setOtherTranslationEnabled(bool)));
connect(settings, SIGNAL(embeddedTextEnabledChanged(bool)), eng, SLOT(setEnabled(bool)));
connect(settings, SIGNAL(embeddedScenarioWidthChanged(int)), eng, SLOT(setScenarioWidth(int)));
connect(settings, SIGNAL(embeddedSpaceAlwaysInsertedChanged(bool)), eng, SLOT(setAlwaysInsertsSpaces(bool)));
connect(settings, SIGNAL(embeddedSpaceSmartInsertedChanged(bool)), eng, SLOT(setSmartInsertsSpaces(bool)));
connect(settings, SIGNAL(embeddedSpacePolicyEncodingChanged(QString)), eng, SLOT(setSpacePolicyEncoding(QString)));
//connect(settings, SIGNAL(embeddedTextCancellableByControlChanged(bool)), eng, SLOT(setDetectsControl(bool)));
connect(settings, SIGNAL(embeddedAllTextsExtractedChanged(bool)), eng, SLOT(setExtractsAllTexts(bool)));
connect(settings, SIGNAL(scenarioSignatureChanged(long)), eng, SLOT(setScenarioSignature(long)));
connect(settings, SIGNAL(nameSignatureChanged(long)), eng, SLOT(setNameSignature(long)));
connect(settings, SIGNAL(embeddedTranslationWaitTimeChanged(int)), eng, SLOT(setTranslationWaitTime(int)));
eng->setTranslationWaitTime(settings->embeddedTranslationWaitTime());
connect(settings, SIGNAL(gameEncodingChanged(QString)), eng, SLOT(setEncoding(QString)));
if (eng->load()) {
eng->setEncoding(settings->gameEncoding());
eng->setScenarioVisible(settings->isEmbeddedScenarioVisible());
eng->setScenarioTextVisible(settings->isEmbeddedScenarioTextVisible());
eng->setScenarioTranscodingEnabled(settings->isEmbeddedScenarioTranscodingEnabled());
eng->setScenarioTranslationEnabled(settings->isEmbeddedScenarioTranslationEnabled());
eng->setNameVisible(settings->isEmbeddedNameVisible());
eng->setNameTextVisible(settings->isEmbeddedNameTextVisible());
eng->setNameTranscodingEnabled(settings->isEmbeddedNameTranscodingEnabled());
eng->setNameTranslationEnabled(settings->isEmbeddedNameTranslationEnabled());
eng->setOtherVisible(settings->isEmbeddedOtherVisible());
eng->setOtherTextVisible(settings->isEmbeddedOtherTextVisible());
eng->setOtherTranscodingEnabled(settings->isEmbeddedOtherTranscodingEnabled());
eng->setOtherTranslationEnabled(settings->isEmbeddedOtherTranslationEnabled());
eng->setAlwaysInsertsSpaces(settings->isEmbeddedSpaceAlwaysInserted());
eng->setSmartInsertsSpaces(settings->isEmbeddedSpaceSmartInserted());
eng->setSpacePolicyEncoding(settings->embeddedSpacePolicyEncoding());
eng->setScenarioWidth(settings->embeddedScenarioWidth());
//eng->setDetectsControl(settings->isEmbeddedTextCancellableByControl());
eng->setExtractsAllTexts(settings->isEmbeddedAllTextsExtracted());
eng->setScenarioSignature(settings->scenarioSignature());
eng->setNameSignature(settings->nameSignature());
// Always enable text extraction
eng->setScenarioExtractionEnabled(true);
eng->setNameExtractionEnabled(true);
}
//eng->setEnabled(settings->isEmbedDriverNeeded()); // enable it at last
eng->setEnabled(settings->isEmbeddedTextEnabled());
}
void MainDriverPrivate::onDisconnected()
{
if (win)
win->setEnabled(false);
//DOUT("pass");
unload();
}
void MainDriverPrivate::unload()
{
#ifdef VNRAGENT_ENABLE_UNLOAD
// Add contents to qDebug will crash the application while unload.
//DOUT("enter");
if (hijack) hijack->unload();
if (eng) eng->unload();
//DOUT("leave");
WinDbg::unloadCurrentModule();
#endif // VNRAGENT_ENABLE_UNLOAD
}
void MainDriverPrivate::onLoadFinished()
{
if (eng)
; //eng->setEnabled(settings->isEmbedDriverNeeded());
else if (settings->isEmbedDriverNeeded()){
createEmbedDriver();
createHijackDriver();
}
if (win)
win->setEnabled(settings->isWindowDriverNeeded());
else if (settings->isWindowDriverNeeded()){
createWindowDriver();
createHijackDriver();
}
}
// EOF
|
#ifndef _ASYNC_REQUESTDISPATCH_H_
#define _ASYNC_REQUESTDISPATCH_H_
#include <google/protobuf/message.h>
#include "request_dispatch.h"
#include "../common/znb_thread.h"
#include "../common/znb_message_queue.h"
#include "../common/znb_mysql.h"
using namespace google::protobuf;
const int WorkerSize = 10;
namespace znb
{
class AsyncRequestMfcMap : public RequestMfcMap
{
public:
AsyncRequestMfcMap(DBConf& dbConf);
~AsyncRequestMfcMap();
void start();
void stop();
struct RequestType
{
RequestType(IConn* pConn, Message* pMsg, uint32_t uCmd, uint32_t uRequestId, uint64_t uUid, BaseEntry* pEntry):
conn(pConn),
msg(pMsg),
cmd(uCmd),
requestId(uRequestId),
uid(uUid),
entry(pEntry)
{
}
RequestType():conn(NULL),msg(NULL),cmd(0),requestId(0),uid(0),entry(NULL)
{
}
void operator= (volatile RequestType& r)
{
conn = r.conn;
msg = r.msg;
cmd = r.cmd;
requestId = r.requestId;
uid = r.uid;
entry = r.entry;
}
void operator= (const RequestType& r) volatile
{
conn = r.conn;
msg = r.msg;
cmd = r.cmd;
requestId = r.requestId;
uid = r.uid;
entry = r.entry;
}
IConn* conn;
Message* msg;
uint32_t cmd;
uint32_t requestId;
uint64_t uid;
BaseEntry* entry;
};
class Worker : public Thread
{
friend class AsyncRequestMfcMap;
public:
Worker(DBConf& dbConf);
~Worker();
virtual void process();
bool pushRequest(const RequestType& req)
{
return m_queue.pushElement(req);
}
Mutex getMutex()
{
return mutex;
}
void setMutex()
{
m_cond.setMutex(mutex);
}
Condition getCond()
{
return m_cond;
}
void notify()
{
m_cond.notify();
}
typedef TMessageQueue<RequestType> Queue;
Queue m_queue;
bool _bTerminate;
Mutex mutex;
Condition m_cond;
MysqlDao mysql;
};
void dispatcherToWorkers(google::protobuf::Message* msg,
BaseEntry* entry, uint32_t cmd, uint32_t requestId, uint64_t uid, IConn* conn);
virtual void requestDispatch(std::string &strMsg, uint32_t cmd, uint32_t requestId, uint64_t uid64, IConn* conn);
typedef std::vector<Worker*> Workers;
Workers m_workers;
int m_nDispIndex;
};
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
struct surface{
int w,h;
void init(int a, int b){
w = min(a,b);
h = max(a,b);
};
bool operator<(surface &rhs){
if( w == rhs.w ) return h < rhs.h;
return w < rhs.w;
};
}S[10];
bool isBox(){
sort(&S[0],&S[6]);
if( !(S[0].w == S[1].w && S[0].h == S[1].h &&
S[2].w == S[3].w && S[2].h == S[3].h &&
S[4].w == S[5].w && S[4].h == S[5].h))
return false;
if( !(S[0].w == S[2].w &&
S[4].w == min(S[0].h,S[2].h) &&
S[4].h == max(S[0].h,S[2].h)))
return false;
return true;
}
int main(int argc, char const *argv[])
{
int w,h;
while( ~scanf("%d %d",&w,&h) ){
S[0].init(w,h);
for(int i = 1 ; i < 6 ; i++ ){
scanf("%d %d",&w,&h);
S[i].init(w,h);
}
if( isBox() ) printf("POSSIBLE\n");
else printf("IMPOSSIBLE\n");
}
return 0;
}
|
class Category_542 {
class HandChemBlue {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class HandChemGreen {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class HandChemRed {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FlareGreen_M203 {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FlareWhite_M203 {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FlareWhite_GP25 {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FlareGreen_GP25 {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class HandRoadFlare {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
};
|
#include "fw/mainFrame.h"
#include "fw/mainPanel.h"
CMainFrame::CMainFrame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(854, 768))
{
// menubar
wxMenuBar * pMenubar = new wxMenuBar();
wxMenu * pMenuFile = new wxMenu();
pMenuFile->Append(wxID_EXIT, wxT("&Quit"));
Connect(wxID_EXIT,
wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler(CMainFrame::__OnQuit));
pMenubar->Append(pMenuFile, wxT("&File"));
this->SetMenuBar(pMenubar);
// statusbar
this->CreateStatusBar();
// panel
m_pPanel = new CMainPanel(this);
m_pPanel->SetFocus();
// position
Centre();
}
wxStatusBar* CMainFrame::OnCreateStatusBar(
int number,
long style,
wxWindowID id,
const wxString& name)
{
wxStatusBar * pBar = new wxStatusBar(this, id, style, name);
return pBar;
}
void CMainFrame::__OnQuit(wxCommandEvent& event)
{
Close(true);
}
|
#include "FirstPersonCamera.h"
FirstPersonCamera::FirstPersonCamera()
{
this->Reset(0, 0, 1,
0, 0, 0,
0, 1, 0);
SetPerspectiveProjection(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f);
}
FirstPersonCamera::~FirstPersonCamera()
{
}
FirstPersonCamera::FirstPersonCamera(std::unique_ptr<FirstPersonCamera> tmp)
{
this->mDirection = -tmp->GetLookDirection();
this->mPosition = tmp->GetEyePosition();
this->mProjectionMatrix = tmp->GetProjectionMatrix();
this->mRight = tmp->mRight;
this->mUp = tmp->mUp;
this->mViewMatrix = tmp->GetViewMatrix();
}
vec3 FirstPersonCamera::GetLookDirection()
{
return -mDirection;
}
void FirstPersonCamera::Reset(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ)
{
vec3 eyePt(eyeX, eyeY, eyeZ);
vec3 centerPt(centerX, centerY, centerZ);
vec3 upVec(upX, upY, upZ);
this->Reset(eyePt, centerPt, upVec);
}
void FirstPersonCamera::Reset(const vec3 &eye, const vec3 ¢er, vec3 &up)
{
mPosition = eye;
mDirection = normalize(mPosition - center);
mRight = normalize(cross(up, mDirection));
mUp = normalize(cross(mDirection, mRight));
this->UpdateViewMatrix();
}
mat4 FirstPersonCamera::GetViewMatrix()
{
return mViewMatrix;
}
void FirstPersonCamera::UpdateViewMatrix()
{
vec3 mCenter = mPosition + this->GetLookDirection();
mViewMatrix = lookAt(mPosition, mCenter, mUp);
}
mat4 FirstPersonCamera::GetProjectionMatrix()
{
return mProjectionMatrix;
}
void FirstPersonCamera::SetPerspectiveProjection(float FOV, float aspectRatio, float near, float far)
{
mProjectionMatrix = perspective(FOV, aspectRatio, near, far);
}
void FirstPersonCamera::Slide(float stepR, float stepU, float stepD)
{
mPosition += stepR * mRight;
mPosition += stepU * mUp;
mPosition += stepD * this->GetLookDirection();
}
void FirstPersonCamera::Yaw(float angleDegrees)
{
mDirection = glm::rotate(mDirection, angleDegrees, mUp);
mRight = glm::rotate(mRight, angleDegrees, mUp);
}
bool FirstPersonCamera::Pitch(float angleDegrees)
{
mUp = glm::vec3(0,1,0);
vec3 temp = glm::rotate(mDirection, angleDegrees, mRight);
temp *= -1;
vec3 lookY = temp;
lookY.y = 0;
if (glm::dot(temp, lookY) > 0.75)
{
mDirection = -temp;
return 1;
}
else return 0;
}
void FirstPersonCamera::Roll(float angleDegrees)
{
mRight = glm::rotate(mRight, angleDegrees, mDirection);
mUp = glm::vec3(0, 1, 0);
}
void FirstPersonCamera::Walk(float dist)
{
vec3 mCenter =this->mPosition + this->GetLookDirection();
vec3 walkdir = vec3(mCenter.x, this->mPosition.y, mCenter.z) - this->mPosition;
mPosition += dist * walkdir;
}
void FirstPersonCamera::Strafe(float dist)
{
vec3 mR = this->mPosition + mRight;
vec3 strafedir = vec3(mR.x, mPosition.y, mR.z) - mPosition;
mPosition += dist *strafedir;
}
void FirstPersonCamera::Fly(float dist)
{
mPosition += dist * mUp;
}
glm::vec3 FirstPersonCamera::GetEyePosition()
{
return mPosition;
}
void FirstPersonCamera::CheckWalls()
{
int maxx = 995.7;
int maxy = 995.7;
vec3 Position = this->GetEyePosition();
if (Position.x > maxx)
this->mPosition.x = maxx;
else if (Position.x < -maxx)
this->mPosition.x = -maxx;
if (Position.y > maxy)
this->mPosition.y = maxy;
else if (Position.y < -maxy)
this->mPosition.y = -maxy;
if (Position.z > maxx)
this->mPosition.z = maxx;
else if (Position.z < -maxx)
this->mPosition.z = -maxx;
}
|
#include <iostream>
#include <iomanip> // precision cout and fstream
#include <fstream>
#include <string>
#include "../include/drift_diffusion.h"
// Show all variables in space for the given time. If t=-1 then show steady state
void Drift_diffusion::save_space(void)
{
string dir_file = folder_name + '/' + file_name;
ifstream infile(dir_file.c_str());
//bool file_exist = infile.good(); // Check if file exists
ofstream drift_diffusion_file; // Create a reference to file
drift_diffusion_file.open(dir_file.c_str(), ios::app);
//if (!(file_exist)) drift_diffusion_file << "New file" << endl;
drift_diffusion_file << "Time: " << result_it.t << " s" << endl;
drift_diffusion_file << "The applied voltage: " << layers_params.device.V_a << " V" << endl;
drift_diffusion_file << "The total current: " << result_it.J_total << " A m-2" << endl;
drift_diffusion_file << "The precision: " << result_it.epsilon_calc * 100 << " %" << endl;
drift_diffusion_file << setprecision(9)
<< setw(11) << "x" << "\t"
<< setw(11) << "G" << "\t"
<< setw(11) << "V" << "\t"
<< setw(11) << "E" << "\t"
<< setw(11) << "n" << "\t"
<< setw(11) << "p" << "\t"
<< setw(11) << "n_t" << "\t"
<< setw(11) << "p_t" << "\t"
<< setw(11) << "a" << "\t"
//<< setw(11) << "c" << "\t"
<< setw(11) << "E_c" << "\t"
<< setw(11) << "E_v" << "\t"
<< setw(11) << "E_fn" << "\t"
<< setw(11) << "E_fp" << "\t"
<< setw(11) << "J_n" << "\t"
<< setw(11) << "J_p" << "\t"
<< setw(11) << "J_a" << "\t"
//<< setw(11) << "J_c" << "\t"
<< setw(11) << "J_disp" << "\t"
<< setw(11) << "layer" << endl;
for (unsigned int i = 0; i < grid.N_points; i++)
{
drift_diffusion_file << setprecision(9)
<< setw(11) << grid.xi[i] << "\t"
<< setw(11) << grid.Gi[i] << "\t"
<< setw(11) << result_it.V[i] << "\t"
<< setw(11) << result_it.E[i] << "\t"
<< setw(11) << result_it.n[i] << "\t"
<< setw(11) << result_it.p[i] << "\t"
<< setw(11) << result_it.n_t[i] << "\t"
<< setw(11) << result_it.p_t[i] << "\t"
<< setw(11) << result_it.a[i] << "\t"
//<< setw(11) << result_it.c[i] << "\t"
<< setw(11) << result_it.E_c[i] << "\t"
<< setw(11) << result_it.E_v[i] << "\t"
<< setw(11) << result_it.E_fn[i] << "\t"
<< setw(11) << result_it.E_fp[i] << "\t"
<< setw(11) << result_it.J_n[i] << "\t"
<< setw(11) << result_it.J_p[i] << "\t"
<< setw(11) << result_it.J_a[i] << "\t"
//<< setw(11) << result_it.J_c[i] << "\t"
<< setw(11) << result_it.J_disp[i] << "\t"
<< setw(11) << grid.li[i] << endl;
}
drift_diffusion_file << endl;
drift_diffusion_file.close(); // Close the file
}
// Show voltage-current value - overrides the file
void Drift_diffusion::save_jV_result(string const &file_name)
{
string dir_file = folder_name + '/' + file_name;
ifstream infile(dir_file.c_str());
bool file_exist = infile.good(); // Check if file exists
ofstream drift_diffusion_file; // Create a reference to file
drift_diffusion_file.open(dir_file.c_str(), ios::app);
if (!(file_exist)) drift_diffusion_file << setw(11) << "Voltage" << "\t" << setw(11) << "Current" << "\n";
drift_diffusion_file << setw(11) << layers_params.device.V_a << "\t" << setw(11) << result_it.J_total << "\n";
cout << "Filename: " << dir_file << endl;
drift_diffusion_file.close(); // Close the file
}
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 5 //최대 스택 크기
//함수 선언
void push(char);
void pop();
void peek();
//스택 구조체
struct stack {
char array[MAX_STACK_SIZE]; //배열로 스택 만들기
int top = -1; //제거할 스택 원소 가리킴
} stack;
int main(void) {
//예1
printf("예1출력\n");
push('A'); peek(); push('B'); peek(); push('C'); peek(); push('D'), push('E'), push('F'); pop(); pop(); push('D');
peek(); push('E'); peek(); pop(); pop(); pop(); pop(); pop(); pop();
stack.top = 0; //다시 스택 초기화
//예2
printf("\n");
printf("\n예2 출력\n");
push('1'); pop(); push('2'); pop(); push('3'); pop();
printf("\n");
push('1'); push('2'); pop(); pop(); push('3'); pop();
printf("\n");
push('1'); pop(); push('2'); push('3'); pop(); pop();
printf("\n");
push('1'); push('2'); pop(); push('3'); pop(); pop();
printf("\n");
push('1'); push('2'); push('3'); pop(); pop(); pop();
//3 1 2의 순서로 출력이 가능한가
}
//스택에 원소 넣기
void push(char newone)
{
//스택이 꽉 차지 않으면
if (stack.top < 4) {
// 스택에 원소 삽입
stack.top++;
stack.array[stack.top] = newone;
}
else {
//스택이 꽉 찼으면 오버플로우라고 알려주기
printf("stack overflow ");
}
}
//스택에서 원소 꺼내기
void pop() {
//스택이 비어있으면
if (stack.top == -1) {
//비어있다고 알려주기
printf("stack empty ");
}
//아니라면
else{
//스택 원소 하나 꺼내서 출력
printf("%c ", stack.array[stack.top]);
//원소 제거
stack.top--;
}
}
//스택의 top 원소 출력
void peek() {
//스택 비어있으면 비어있다고 출력
if (stack.top == -1) {
printf("stack empty ");
}
//아니라면 top원소 출력
else {
printf("%c ", stack.array[stack.top]);
}
}
|
/*
* Touch.h
*
* Created on: Nov 1, 2017
* Author: robert
*/
#ifndef TOUCH_H_
#define TOUCH_H_
#include <iostream>
#include "../inc/GUI.h"
#include "../inc/Utils.h"
#include "../inc/ConfigReader.h"
#include "../inc/Control.h"
struct Touch
{
int x,y,n,n_1;
std::string id;
int event;
int previous_event;
int screen;
};
int main_touch(std::unique_ptr<Control>&control, Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
int Screen0_callback(std::unique_ptr<Control>&control,Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
int Screen1_callback(std::unique_ptr<Control>&control,Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
int Screen2_callback(std::unique_ptr<Control>&control,Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
int Screen3_callback(std::unique_ptr<Control>&control,Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
int Screen4_callback(std::unique_ptr<Control>&control,Touch touch,std::unique_ptr<GUI>&gui,std::unique_ptr<ConfigReader>&config);
#endif /* TOUCH_H_ */
|
#ifndef mailRefList_h
#define mailRefList_h
#include <string>
#include <fstream>
typedef struct
{
std::string id;
bool read;
}tMailRef;
const int Max_Ref = 50;
typedef tMailRef tArrayRef[Max_Ref];
typedef struct
{
tArrayRef references;
int counter;
}tMailRefList;
void initialize(tMailRefList &refList); //Initialize a list of references
void load(tMailRefList &refList, std::ifstream &file); //Load a list of references from a file
void save(const tMailRefList &refList, std::ofstream &file); //Save a list of references into a file
bool insertRef(tMailRefList &refList, tMailRef ref); //Insert a new reference in the list of references
bool deleteRef(tMailRefList &refList, std::string id); //Delete a reference from the list of references
bool readMail(tMailRefList &refList, std::string id); //Mark a mail as read in the list of references
int find(const tMailRefList &refList, std::string id); //Find the position of a reference in the list of references and return that position
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef SCOPE_EXEC_SUPPORT
#include "modules/scope/scope_display_listener.h"
#include "modules/scope/src/scope_manager.h"
#include "modules/scope/src/scope_exec.h"
/* static */ void
OpScopeDisplayListener::OnWindowPainted(Window* window, OpRect rect)
{
if (g_scope_manager && g_scope_manager->exec)
g_scope_manager->exec->WindowPainted(window, rect);
}
#endif // SCOPE_EXEC_SUPPORT
|
// KC Text Adventure Framework - (c) Rachel J. Morris, 2012 - 2013. zlib license. Moosader.com
#ifndef _ITEMWRAPPER
#define _ITEMWRAPPER
#include <string>
#include <vector>
#include "BaseLuaWrapper.h"
class ItemWrapper : public BaseLuaWrapper
{
public:
void Init(lua_State* state);
std::string GetDescriptionOfItem( const std::string& itemName );
std::string GetNameOfItem( const std::string& itemKey );
bool SetItemCollected( const std::string& itemName );
std::vector<std::string> GetListOfItemsOnMap( const std::string& mapKey );
std::string GetItemKeyFromName( const std::string& itemName );
bool ItemExistsAndIsOnMap( const std::string& itemName, const std::string& mapKey );
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick/extensions/views/ExtensionsManagerView.h"
#include "adjunct/quick/managers/FavIconManager.h"
#include "adjunct/quick/managers/DesktopExtensionsManager.h"
#include "adjunct/quick_toolkit/widgets/OpIcon.h"
#include "adjunct/quick_toolkit/widgets/OpLabel.h"
#include "adjunct/quick_toolkit/widgets/QuickImage.h"
#include "adjunct/quick_toolkit/widgets/QuickLabel.h"
#include "adjunct/quick_toolkit/widgets/QuickSeparator.h"
#include "adjunct/quick_toolkit/widgets/QuickButton.h"
#include "adjunct/quick_toolkit/widgets/QuickButtonStrip.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickGrid.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickStackLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickCentered.h"
#include "adjunct/quick_toolkit/widgets/QuickSkinElement.h"
#include "modules/locale/oplanguagemanager.h"
namespace
{
const unsigned PUZZLE_ICON_PADDING = 12;
const unsigned NO_EXTENSIONS_DESCRIPTION_PREFERRED_WIDTH = 800;
};
ExtensionsManagerViewItem::ExtensionsManagerViewItem(
const ExtensionsModelItem& item) :
m_model_item(item)
{
}
QuickWidget* ExtensionsManagerView::ConstructEmptyPageWidget()
{
OpAutoPtr<QuickStackLayout> main(OP_NEW(QuickStackLayout,
(QuickStackLayout::VERTICAL)));
main->InsertEmptyWidget(1,20,1,20);
OpAutoPtr<QuickImage> puzzle_image(OP_NEW(QuickImage,()));
RETURN_VALUE_IF_NULL(puzzle_image.get(), NULL);
RETURN_VALUE_IF_ERROR(puzzle_image->Init(), NULL);
puzzle_image->GetOpWidget()->GetForegroundSkin()->SetImage("Extensions 64 Gray");
unsigned puzzle_image_height = puzzle_image->GetPreferredHeight();
QuickStackLayout* row = OP_NEW(QuickStackLayout,(QuickStackLayout::HORIZONTAL));
RETURN_VALUE_IF_NULL(row, NULL);
main->InsertWidget(row);
row->SetFixedHeight(puzzle_image_height + 30);
RETURN_VALUE_IF_ERROR(row->InsertEmptyWidget(
2 * PUZZLE_ICON_PADDING, 0, 2 * PUZZLE_ICON_PADDING, 0), NULL);
RETURN_VALUE_IF_ERROR(row->InsertWidget(puzzle_image.release()), NULL);
RETURN_VALUE_IF_ERROR(row->InsertEmptyWidget(PUZZLE_ICON_PADDING, 0,
PUZZLE_ICON_PADDING, 0), NULL);
OpAutoPtr<QuickStackLayout> row_main(OP_NEW(QuickStackLayout,
(QuickStackLayout::VERTICAL)));
RETURN_VALUE_IF_NULL(row_main.get(), NULL);
row_main->SetFixedHeight(puzzle_image_height);
RETURN_VALUE_IF_ERROR(row_main->InsertEmptyWidget(1,10,1,10), NULL);
OpString text_string;
RETURN_VALUE_IF_ERROR(g_languageManager->GetString(
Str::D_EXTENSION_PANEL_NO_EXTENSIONS,text_string), NULL);
OpAutoPtr<QuickCenteredHorizontal> centered_label(OP_NEW(QuickCenteredHorizontal, ()));
RETURN_VALUE_IF_NULL(centered_label.get(), NULL);
QuickLabel* text_label = QuickLabel::ConstructLabel(text_string);
RETURN_VALUE_IF_NULL(text_label, NULL);
centered_label->SetContent(text_label);
text_label->SetSystemFontWeight(QuickOpWidgetBase::WEIGHT_BOLD);
text_label->SetRelativeSystemFontSize(120);
text_label->SetSkin("Extensions Panel List No Extensions");
RETURN_VALUE_IF_ERROR(row_main->InsertWidget(centered_label.release()), NULL);
RETURN_VALUE_IF_ERROR(
row_main->InsertEmptyWidget(
0, 10, NO_EXTENSIONS_DESCRIPTION_PREFERRED_WIDTH, 10), NULL);
OpAutoPtr<QuickButtonStrip> strip(OP_NEW(QuickButtonStrip, ()));
if (!strip.get() || OpStatus::IsError(strip->Init()))
{
return NULL;
}
OpInputAction getmore_action(OpInputAction::ACTION_GET_MORE_EXTENSIONS);
QuickButton* start_button = QuickButton::ConstructButton(
Str::D_EXTENSION_PANEL_GET_STARTED, &getmore_action);
if (!start_button)
{
return NULL;
}
OpAutoPtr<QuickButton> start_button_aptr(start_button);
start_button->GetOpWidget()->SetButtonTypeAndStyle(
OpButton::TYPE_CUSTOM,OpButton::STYLE_TEXT);
start_button->SetSkin("Extensions Panel List Item Button");
#ifndef _MACINTOSH_
start_button->GetOpWidget()->SetTabStop(g_op_ui_info->IsFullKeyboardAccessActive());
#endif //_MACINTOSH_
QuickCenteredHorizontal* centered_button=
OP_NEW(QuickCenteredHorizontal, ());
RETURN_VALUE_IF_NULL(centered_button, NULL);
centered_button->SetContent(start_button);
start_button_aptr.release();
RETURN_VALUE_IF_ERROR(row_main->InsertWidget(centered_button), NULL);
RETURN_VALUE_IF_ERROR(row->InsertWidget(row_main.release()), NULL);
QuickSkinElement* qs_elem =
QuickSkinWrap(main.release(), "Extensions Panel Empty List Skin");
RETURN_VALUE_IF_NULL(qs_elem, NULL);
return qs_elem;
}
OP_STATUS ExtensionsManagerView::AddItem(ExtensionsManagerViewItem* item)
{
if (!item)
{
return OpStatus::ERR;
}
return m_view_items.Add(item);
}
OP_STATUS ExtensionsManagerView::RemoveItem(ExtensionsManagerViewItem* item)
{
return m_view_items.RemoveByItem(item);
}
void ExtensionsManagerView::OnExtensionDisabled(
const ExtensionsModelItem& model_item)
{
ExtensionsManagerViewItem* item =
FindExtensionViewItemById(model_item.GetExtensionId());
if (item)
{
item->SetEnabled(FALSE);
}
}
void ExtensionsManagerView::OnExtensionEnabled(
const ExtensionsModelItem& model_item)
{
ExtensionsManagerViewItem* item =
FindExtensionViewItemById(model_item.GetExtensionId());
if (item)
{
item->SetEnabled(TRUE);
}
}
void ExtensionsManagerView::OnExtensionUpdateAvailable(
const ExtensionsModelItem& model_item)
{
ExtensionsManagerViewItem* item =
FindExtensionViewItemById(model_item.GetExtensionId());
if (item)
{
item->UpdateAvailable();
}
}
void ExtensionsManagerView::OnExtensionExtendedNameUpdate(
const ExtensionsModelItem& model_item)
{
ExtensionsManagerViewItem* item =
FindExtensionViewItemById(model_item.GetExtensionId());
if (item)
{
item->UpdateExtendedName(model_item.GetExtendedName());
}
}
ExtensionsManagerViewItem* ExtensionsManagerView::FindExtensionViewItemById(
const OpStringC& id)
{
for (unsigned i = 0; i < m_view_items.GetCount(); ++i)
{
if (m_view_items.Get(i)->GetExtensionId() == id)
{
return m_view_items.Get(i);
}
}
return NULL;
}
|
/***************************************************************************
*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
* B142877
*
**************************************************************************/
/**
* @file char_lib.h
* @author liuxufeng (liuxufeng@baidu.com)
* @date 2017/05/27 20:09:03
* @version 1.0.0-alpha
* @brief
* make a desription
**/
#ifndef CPROCLIB_CHAR_LIB_H
#define CPROCLIB_CHAR_LIB_H
namespace char_lib{
std::string rstrip_str(std::string ori_str, const char ch);
std::string lstrip_str(std::string ori_str, char ch);
std::string strip_str(std::string ori_str, char ch);
std::string replace_str(std::string ori_str, const std::string sub,
const std::string rep, bool replace_all=true);
int split_str(std::string src, std::string seps, std::vector<std::string>& dest);
// 计算字符之间的编辑距离
int edit_dist(const char * A, const char * B);
// 根据编辑距离计算字符串之间的相似度
float string_edit_sim(const char * string1, const char * string2);
}
#endif //CPROCLIB_CHAR_LIB_H
|
#ifndef _MACHINEMENU_H_
#define _MACHINEMENU_H_
#include <menu.h>
#include <string>
class MachineMenu{
private:
ITEM **items;
WINDOW *window;
MENU *menu;
size_t size;
public:
MachineMenu( WINDOW *win );
void post();
void unpost();
void up();
void down();
std::string get_current();
};
#endif
|
#include "CUSocket.hh"
#include "Exception.hh"
#include "Defines.hh"
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
//Initialization of the ressources and properties of the UNIX socket
CUSocket::CUSocket(bool isServer)
{
int one = 1;
const int *val = &one;
this->_sock = -1;
this->_info.sin_family = AF_INET;
this->_timeout.tv_sec = 0;
this->_timeout.tv_usec = TIMEOUT_PACKET;
if (getuid() != 0)
throw Exception("With the raw sockets you have to run the client in administrator rights.");
if (isServer)
this->_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
else
this->_sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
if (this->_sock == -1)
{
this->_sock = -1;
throw Exception("socket has failed.");
}
if ((setsockopt(this->_sock, IPPROTO_IP, IP_HDRINCL, val, sizeof(int))) == -1)
throw Exception("setsockopt has failed.");
}
CUSocket::~CUSocket()
{
this->closeSocket();
}
//Send the data with the size specified
void CUSocket::send(const void *data, size_t size)
{
if (this->_sock == -1)
throw Exception("This socket type isn't initialized.");
if (::sendto(this->_sock, data, size, 0, (SOCKADDR *)&this->_info, sizeof(this->_info)) == -1)
throw Exception("send has failed.");
}
//Close the socket
void CUSocket::closeSocket()
{
if ((this->_sock != -1) && (close(this->_sock) != 0))
throw Exception("closesocket of sock has failed.");
this->_sock = -1;
}
//Set the socket attribute
void CUSocket::setSocket(int sock)
{
this->_sock = sock;
}
//Accessor method for the socket attribute
int CUSocket::getSocket() const
{
return (this->_sock);
}
//Accessor method for the info attribute
const struct sockaddr_in &CUSocket::getInfo()
{
return (this->_info);
}
//Check if the address specified is valid
bool CUSocket::isValidIPAddress(const char *ipAddress) const
{
struct sockaddr_in tmp;
bool ret = true;
if (::inet_pton(AF_INET, ipAddress, &tmp.sin_addr) != 1)
{
throw Exception("Address is invalid.");
ret = false;
}
return (ret);
}
//Mutator method for the port within the socket
void CUSocket::setPort(int port)
{
this->_port = port;
this->_info.sin_port = ::htons(port);
}
//Mutator method for the address within the socket
void CUSocket::setAddress(const std::string &address)
{
this->_info.sin_addr.s_addr = ::inet_addr(address.c_str());
}
//Accessor method for the address of the socket
uint32_t CUSocket::getDestAddress() const
{
return (this->_info.sin_addr.s_addr);
}
//Convert the address specified for using with the socket
uint32_t CUSocket::convertAddress(const char *address) const
{
return (::inet_addr(address));
}
//Accessor method for the port of the socket
int CUSocket::getDestPort() const
{
return (this->_port);
}
//Receive data
void *CUSocket::receive(int *sizeReceiv)
{
char *data = new char[PACKET_SIZE_RECV];
socklen_t fromlen;
if (this->_sock == -1)
throw Exception("This socket type isn't initialized.");
if ((*sizeReceiv = ::recvfrom(this->_sock, data, PACKET_SIZE_RECV, 0, (SOCKADDR *)&this->_info, &fromlen)) == -1)
throw Exception("recvfrom has failed.");
if (*sizeReceiv <= 0)
{
delete data;
return (NULL);
}
return (data);
}
//Wait the read
int CUSocket::select(long int *usecTimeout)
{
int ret;
this->_timeout.tv_usec = 1000;
ret = ::select(this->_sock + 1, &this->_fds, NULL, NULL, &this->_timeout);
*usecTimeout += (1000 - this->_timeout.tv_usec);
return (ret);
}
//Wait the read
int CUSocket::select(long int usecTimeout)
{
if (usecTimeout >= 0)
this->_timeout.tv_usec = usecTimeout;
else
this->_timeout.tv_usec = TIMEOUT_PACKET;
return (::select(this->_sock + 1, &this->_fds, NULL, NULL, &this->_timeout));
}
//Reset sockets, with input fd or not
void CUSocket::resetSockets(bool input)
{
FD_ZERO(&this->_fds);
if (input)
FD_SET(0, &this->_fds);
FD_SET(this->_sock, &this->_fds);
}
//Check if the input fd is readable
bool CUSocket::inputFdReadable() const
{
return (FD_ISSET(0, &this->_fds));
}
//Check if the socket is readable
bool CUSocket::socketReadable() const
{
return (FD_ISSET(this->_sock, &this->_fds));
}
|
#include <iostream>
using namespace std;
void bubbleSort(int arr[])
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < (5 - i - 1); j++)
{
if (arr[j] > arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int myArray[5];
cout << "Enter the 5 Elements" << endl;
for (int i = 0; i < 5; i++)
{
cin >> myArray[i];
}
cout << "Before Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
bubbleSort(myArray);
cout << endl;
cout << "After Sorting Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
return 0;
}
|
#ifndef YELLOWDIALOG_H
#define YELLOWDIALOG_H
#include <QDialog>
class YellowDialog : public QDialog
{
Q_OBJECT
public:
explicit YellowDialog(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
};
#endif // YELLOWDIALOG_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef INPUT_MANAGER_DIALOG_H
#define INPUT_MANAGER_DIALOG_H
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/desktop_util/treemodel/simpletreemodel.h"
#include "adjunct/quick/managers/opsetupmanager.h"
#include "modules/inputmanager/inputmanager.h"
class OpTreeView;
class PrefsFile;
class URL;
/***********************************************************************************
**
** InputManagerDialog
**
***********************************************************************************/
class InputManagerDialog : public Dialog
{
public:
InputManagerDialog(INT32 index, OpSetupType type) :
m_input_treeview(NULL),
m_input_prefs(NULL),
m_input_index(index),
m_input_model(2),
m_input_type(type) {}
virtual ~InputManagerDialog();
DialogType GetDialogType() {return TYPE_OK_CANCEL;}
Type GetType() {return DIALOG_TYPE_BOOKMARK_MANAGER;}
const char* GetWindowName() {return "Input Manager Dialog";}
const char* GetHelpAnchor();
virtual void OnInit();
virtual UINT32 OnOk();
void OnCancel();
void OnInitVisibility();
void OnChange(OpWidget *widget, BOOL changed_by_mouse);
virtual BOOL OnInputAction(OpInputAction* action);
virtual void OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks);
virtual void OnItemEdited(OpWidget *widget, INT32 pos, INT32 column, OpString& text);
enum ItemType
{
ITEM_CATEGORY,
ITEM_SECTION,
ITEM_ENTRY
};
static void WriteShortcutSections(OpSetupType input_type, URL& url);
static void WriteShortcutSections(OpSetupType input_type, const char** shortcut_section, URL& url);
private:
class Item
{
public:
Item(ItemType type, const char* section) : m_item_type(type), m_is_changed(FALSE)
{
m_section.Set(section);
}
OpString8& GetSection() {return m_section;}
void SetChanged(BOOL changed) {m_is_changed = changed;}
BOOL IsChanged() {return m_is_changed;}
BOOL IsCategory() {return m_item_type == ITEM_CATEGORY;}
BOOL IsSection() {return m_item_type == ITEM_SECTION;}
BOOL IsEntry() {return m_item_type == ITEM_ENTRY;}
void MakeSectionString(OpString8& string, BOOL defaults)
{
string.Set(m_section);
if (defaults)
{
string.Append(" (defaults)");
}
else if (m_is_changed)
{
string.Append(" (changed)");
}
}
private:
ItemType m_item_type;
BOOL m_is_changed;
OpString8 m_section;
};
void AddShortcutSection(const char* shortcut_section, INT32 root, INT32 parent_index,BOOL force_default);
void AddShortcutSections(const char** shortcut_section, INT32 root);
void OnItemChanged(INT32 model_pos);
static const char* m_shortcut_sections[];
static const char* m_advanced_shortcut_sections[];
OpTreeView* m_input_treeview;
PrefsFile* m_input_prefs;
INT32 m_input_index;
AutoTreeModel<Item> m_input_model;
OpSetupType m_input_type;
INT32 m_old_file_index; //used in setupmanager
INT32 m_new_file_index; //used in setupmanager
};
#endif //INPUT_MANAGER_DIALOG_H
|
#include "RegexTool.h"
int RegexTool::Match(const char* string, const char* pattern)
{
regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
{
return -1;
}
int status = regexec(&re, string, 0, NULL, 0);
regfree(&re);
if (status != 0)
{
return 0;
}
return 1;
}
int RegexTool::MatchIgnoreCase(const char* string, const char* pattern)
{
regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED|REG_ICASE|REG_NOSUB) != 0)
{
return -1;
}
int status = regexec(&re, string, 0, NULL, 0);
regfree(&re);
if (status != 0)
{
return 0;
}
return 1;
}
|
/*----------------------------------------------------------------------------
ライブラリ名:
バージョン:1.0.1.0
ライブラリ概要:
開発言語:Microsoft Visual C++ 2015
統合開発環境:Microsoft Visual Studio 2015 Community Edition
開発開始日:
最終更新日:
-------------------------------------------------------------------------------
更新日一覧
--------------------------------------------------------------------------------
*/
#include <Windows.h>
static HINSTANCE hInstance;
BOOL WINAPI DllMain ( HINSTANCE hDLL , DWORD dwReason , LPVOID lpReserved ) {
switch ( dwReason ) {
case DLL_PROCESS_ATTACH:
hInstance = hDLL;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
#include<iostream>
using namespace std;
int main()
{
int xia, shang;
int x[5] = { 0 };
int counter(0),k(0);
cin >> xia >> shang;
if (xia > shang || xia < 1) {
cout << "Error!"; cin.get();
cin.get(); return 0;
}
else for (int i = xia; i < shang + 1; i++)
{
x[1] = i % 10; x[2] = i / 10 % 10; x[3] = i / 100 % 10; x[4] = i / 1000;
for (int i = 1; i < 5; i++)
{
x[5] += x[i] * x[i] * x[i];
}
if (i == x[5]) { counter++; }
}
if (counter == 0)cout << "no";
else for (int i = xia; i < shang + 1; i++)
{
x[1] = i % 10; x[2] = i / 10 % 10; x[3] = i / 100 % 10; x[4] = i / 1000;
for (int i = 1; i < 5; i++)
{
x[5] += x[i] * x[i] * x[i];
}
if (i == x[5]) { k++;
if (k<counter)
{
cout << i << endl;
}
else cout << i;
}
}
cin.get();
cin.get();
return 0;
}
|
void BlinkLed(uint16_t LEDdelay, uint16_t LEDTimeOn)
{
static unsigned long millistemp;
static bool state;
if (SettingsNow.ShowACK == 1 || SettingsNow.ShowPercentage > 0)
{
//blink very fast
LEDdelay = 50;
LEDTimeOn = 50;
}
if ( ((millis() - millistemp > LEDdelay) && state==0) || ((millis() - millistemp > LEDTimeOn) && state == 1))
{
millistemp = millis();
state = !state;
digitalWrite(13, state);
}
}
|
#include "platforms/mac/QuickOperaApp/CocoaApplication.h"
#include "platforms/mac/QuickOperaApp/QuickWidgetLibHandler.h"
#include "platforms/mac/QuickOperaApp/QuickWidgetManager.h"
#include <string.h>
#include "platforms/mac/embrowser/EmBrowserInit.h"
#include "platforms/mac/bundledefines.h"
#include "adjunct/quick/managers/LaunchManager.h"
#include "platforms/crashlog/crashlog.h"
#if defined(_AM_DEBUG)
#include "platforms/mac/debug/anders/settings.anders.h"
#endif
#ifdef WIDGET_RUNTIME_SUPPORT
BOOL IsBrowserStartup();
CFStringRef GetOperaBundleID();
#endif
QuickWidgetLibHandler *gWidgetLibHandler = NULL;
void StrFilterOutChars(char *szArg, const char* szCharsToRemove)
{
if( szArg && *szArg)
{
int i = 0;
int j = 0;
while( szArg[i])
{
if( !strchr( szCharsToRemove, szArg[i]))
szArg[j++] = szArg[i++];
else
i++;
}
szArg[j] = 0;
}
}
QuickWidgetLibHandler::QuickWidgetLibHandler(int argc, const char** argv)
{
Pool swim;
initProc = NULL;
success = false;
memset(&commonParams, 0, sizeof(commonParams));
memset(&quickParams, 0, sizeof(quickParams));
commonParams.majorVersion = EMBROWSER_MAJOR_VERSION;
commonParams.minorVersion = EMBROWSER_MINOR_VERSION;
quickParams.majorVersion = EMBROWSER_MAJOR_VERSION;
quickParams.minorVersion = EMBROWSER_MINOR_VERSION;
commonParams.malloc = NULL;
commonParams.realloc = NULL;
commonParams.free = NULL;
commonParams.vendorDataID = 'OPRA';
char primaryKey[]= KEY_PRIMARY_NAME;
StrFilterOutChars( primaryKey, KEY_STRIPCHARS);
strcpy((char*)quickParams.registrationCode,primaryKey);
memset(primaryKey,0,sizeof(primaryKey));
commonParams.vendorData = &quickParams;
commonParams.vendorDataMajorVersion = 2;
commonParams.vendorDataMinorVersion = 0;
commonParams.notifyCallbacks = new EmBrowserAppNotification();
if (commonParams.notifyCallbacks)
{
memset(commonParams.notifyCallbacks, 0, sizeof(EmBrowserAppNotification));
commonParams.notifyCallbacks->majorVersion = EMBROWSER_MAJOR_VERSION;
commonParams.notifyCallbacks->minorVersion = EMBROWSER_MINOR_VERSION;
commonParams.notifyCallbacks->notification = QuickWidgetManager::Notification;
}
// Save the command line options
quickParams.argv = argv;
quickParams.argc = argc;
quickParams.appProcs = new EmQuickBrowserAppProcs();
if (quickParams.appProcs)
{
memset(quickParams.appProcs, 0, sizeof(EmQuickBrowserAppProcs));
quickParams.appProcs->majorVersion = EMBROWSER_MAJOR_VERSION;
quickParams.appProcs->minorVersion = EMBROWSER_MINOR_VERSION;
quickParams.appProcs->createMenu = QuickWidgetManager::CreateQuickMenu;
quickParams.appProcs->disposeMenu = QuickWidgetManager::DisposeQuickMenu;
quickParams.appProcs->addMenuItem = QuickWidgetManager::AddQuickMenuItem;
quickParams.appProcs->removeMenuItem= QuickWidgetManager::RemoveQuickMenuItem;
quickParams.appProcs->insertMenu = QuickWidgetManager::InsertQuickMenuInMenuBar;
quickParams.appProcs->removeMenu = QuickWidgetManager::RemoveQuickMenuFromMenuBar;
quickParams.appProcs->refreshMenu = QuickWidgetManager::RefreshMenu;
// These 2 aren't used in the DLL. Might as well save the overhead.
// quickParams.appProcs->refreshMenuBar= QuickWidgetManager::RefreshMenuBar;
// quickParams.appProcs->refreshCommand= QuickWidgetManager::RefreshCommand;
quickParams.appProcs->removeMenuItems = QuickWidgetManager::RemoveAllQuickMenuItemsFromMenu;
quickParams.appProcs->installSighandlers = InstallCrashSignalHandler;
}
#ifdef AUTO_UPDATE_SUPPORT
// Set the Launch Manager
quickParams.launch_manager = g_launch_manager;
#endif
// Set the address of the GPU info
extern GpuInfo *g_gpu_info;
quickParams.pGpuInfo = g_gpu_info;
// try to locate the widget.
#if defined(_XCODE_)
CFBundleRef bundle = CFBundleGetMainBundle(), opera_framework_bundle = NULL;
// See comment in LoadOperaFramework to understand why this is here
opera_framework_bundle = QuickWidgetLibHandler::LoadOperaFramework(bundle);
#ifdef WIDGET_RUNTIME_SUPPORT
// This code looks for an Opera.framework inside the Frameworks folder in the parent bundle. This is intended to make Widgetinstaller run with the framework it was built with.
if (!opera_framework_bundle)
{
CFURLRef bundleURL = CFBundleCopyBundleURL(bundle);
if (bundleURL) {
bundle = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
if (bundle) {
CFURLRef bundle_frameworks_url = CFBundleCopyPrivateFrameworksURL(bundle);
CFRelease(bundle);
if (bundle_frameworks_url) {
CFURLRef opera_framework_url = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, bundle_frameworks_url, CFSTR("Opera.framework"), false);
CFRelease(bundle_frameworks_url);
if (opera_framework_url)
{
opera_framework_bundle = CFBundleCreate(kCFAllocatorSystemDefault, opera_framework_url);
CFRelease(opera_framework_url);
}
}
}
CFRelease(bundleURL);
}
}
// It is possible that we won't be able to locate framework, because we are inside of the widget bundle (without Opera.framework
// In that case we have to locate framework outside and then run it
if (!opera_framework_bundle)
{
// This is the bundleID that is in the widget so we should go for first
CFURLRef bundleURL = NULL;
LSFindApplicationForInfo(kLSUnknownCreator,GetOperaBundleID(), NULL, NULL, &bundleURL);
CFBundleRef bundle = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
if (!bundle)
{
// Didn't find the targeted Framework so go for the fallbacks Opera then Opera Next
LSFindApplicationForInfo(kLSUnknownCreator,CFSTR(XSTRINGIFY(OPERA_BUNDLE_ID)), NULL, NULL, &bundleURL);
bundle = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
if (!bundle)
{
// Look for Opera Next
LSFindApplicationForInfo(kLSUnknownCreator,CFSTR(XSTRINGIFY(OPERA_NEXT_BUNDLE_ID)), NULL, NULL, &bundleURL);
bundle = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
}
}
CFURLRef operaurl = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, bundleURL, CFSTR("Contents/MacOS/Opera"), false);
char* path = new char[PATH_MAX];
CFStringRef oppath = NULL;
if (CFURLGetFileSystemRepresentation(bundleURL, true, (UInt8*)path, PATH_MAX))
oppath = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (const UInt8*)path, strlen(path), kCFStringEncodingUTF8, false);
CFURLGetFileSystemRepresentation(operaurl, true, (UInt8*)path, PATH_MAX);
CFRelease(operaurl);
quickParams.opera_bundle = bundleURL;
quickParams.argv[0] = path;
CFURLRef bundle_frameworks_url = CFBundleCopyPrivateFrameworksURL(bundle);
CFRelease(bundle);
if (bundle_frameworks_url)
{
// If we are here - we need to check one more thing. We are linking to the external Frameworks folder. We need to create a link in our local folder
// (Frameworks folder) to Growl.framework. This is somewhat crucial so we can start the stuff up
CFURLRef opera_framework_url = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, bundle_frameworks_url, CFSTR("Opera.framework"), false);
CFRelease(bundle_frameworks_url);
if (opera_framework_url)
{
opera_framework_bundle = CFBundleCreate(kCFAllocatorSystemDefault, opera_framework_url);
if (opera_framework_bundle)
{
if (!CFBundleIsExecutableLoaded(opera_framework_bundle))
CFBundleLoadExecutable(opera_framework_bundle);
}
CFRelease(opera_framework_url);
}
}
}
#endif //WIDGET_RUNTIME_SUPPORT
if (opera_framework_bundle)
{
EmBrowserInitLibraryProc widgetInitLibrary = (EmBrowserInitLibraryProc) CFBundleGetFunctionPointerForName(opera_framework_bundle, CFSTR("WidgetInitLibrary"));
if (widgetInitLibrary)
{
success = (emBrowserNoErr == widgetInitLibrary(&commonParams));
}
CFRelease(opera_framework_bundle);
}
#else
success = (emBrowserNoErr == WidgetInitLibrary(&commonParams));
#endif
}
QuickWidgetLibHandler::~QuickWidgetLibHandler()
{
if (commonParams.shutdown)
{
commonParams.shutdown();
}
delete commonParams.notifyCallbacks;
delete quickParams.appProcs;
}
Boolean QuickWidgetLibHandler::Initialized()
{
return success;
}
EmBrowserStatus QuickWidgetLibHandler::CallStartupQuickMethod(int argc, const char** argv)
{
if (quickParams.libProcs && quickParams.libProcs->startupQuick)
{
return quickParams.libProcs->startupQuick(argc, argv);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallStartupQuickSecondPhaseMethod(int argc, const char** argv)
{
if (quickParams.libProcs && quickParams.libProcs->startupQuickSecondPhase)
{
return quickParams.libProcs->startupQuickSecondPhase(argc, argv);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallHandleQuickMenuCommandMethod(EmQuickMenuCommand command)
{
if (quickParams.libProcs && quickParams.libProcs->handleQuickCommand)
{
return quickParams.libProcs->handleQuickCommand(command);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallGetQuickMenuCommandStatusMethod(EmQuickMenuCommand command, EmQuickMenuFlags &flags)
{
if (quickParams.libProcs && quickParams.libProcs->getQuickCommandStatus)
{
return quickParams.libProcs->getQuickCommandStatus(command, &flags);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallRebuildQuickMenuMethod(EmQuickMenuRef menu)
{
if (quickParams.libProcs && quickParams.libProcs->rebuildQuickMenu)
{
return quickParams.libProcs->rebuildQuickMenu(menu);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallSharedMenuHitMethod(UInt16 menuID, UInt16 menuItemIndex)
{
if (quickParams.libProcs && quickParams.libProcs->sharedMenuHit)
{
return quickParams.libProcs->sharedMenuHit(menuID, menuItemIndex);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallUpdateMenuTracking(BOOL tracking)
{
if (quickParams.libProcs && quickParams.libProcs->updateMenuTracking)
{
return quickParams.libProcs->updateMenuTracking(tracking);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallMenuItemHighlighted(CFStringRef item_title, BOOL main_menu, BOOL is_submenu)
{
if (quickParams.libProcs && quickParams.libProcs->menuItemHighlighted)
{
return quickParams.libProcs->menuItemHighlighted(item_title, main_menu, is_submenu);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallSetActiveNSMenu(void *nsmenu)
{
if (quickParams.libProcs && quickParams.libProcs->setActiveNSMenu)
{
return quickParams.libProcs->setActiveNSMenu(nsmenu);
}
return emBrowserGenericErr;
}
EmBrowserStatus QuickWidgetLibHandler::CallOnMenuShown(void *nsmenu, BOOL shown)
{
if (quickParams.libProcs && quickParams.libProcs->onMenuShown)
{
return quickParams.libProcs->onMenuShown(nsmenu, shown);
}
return emBrowserGenericErr;
}
CFBundleRef QuickWidgetLibHandler::LoadOperaFramework(CFBundleRef main_bundle)
{
// This steaming pile is sadly needed, because Xcode's linker doesn't know how to properly
// link against a private framework. It tries, but when ZeroLink is off (i.e Release)
// it will generate dependencies to symbols that cannot be loaded.
// Additionally, it fails when it attemtemps to link a non-native binary against a
// universal framework. I Hope we can get rid of this, once Apple makes a proper linker.
// This code looks for an Opera.framework inside the Frameworks folder of the running application. This will fail for widgets and widgetinstaller.
CFBundleRef bundle = main_bundle, opera_framework_bundle = NULL;
CFURLRef bundle_frameworks_url = NULL, opera_framework_url = NULL;
if (bundle)
{
bundle_frameworks_url = CFBundleCopyPrivateFrameworksURL(bundle);
if (bundle_frameworks_url)
{
opera_framework_url = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, bundle_frameworks_url, CFSTR("Opera.framework"), false);
CFRelease(bundle_frameworks_url);
if (opera_framework_url)
{
opera_framework_bundle = CFBundleCreate(kCFAllocatorSystemDefault, opera_framework_url);
CFRelease(opera_framework_url);
}
}
}
return opera_framework_bundle;
}
#pragma mark -
Boolean QuickWidgetLibHandler::InitWidgetLibrary()
{
if (initProc)
{
return (emBrowserNoErr == initProc(&commonParams));
}
return false;
}
|
#include "ActionInitialization.hh"
#include "B1PrimaryGeneratorAction.hh"
#include "B1RunAction.hh"
#include "B1EventAction.hh"
#include "B1SteppingAction.hh"
ActionInitialization::ActionInitialization()
: G4VUserActionInitialization()
{}
ActionInitialization::~ActionInitialization()
{}
void ActionInitialization::BuildForMaster() const
{
B1RunAction* runAction = new B1RunAction;
SetUserAction(runAction);
}
void ActionInitialization::Build() const
{
SetUserAction(new B1PrimaryGeneratorAction);
B1RunAction* runAction = new B1RunAction;
SetUserAction(runAction);
B1EventAction* eventAction = new B1EventAction(runAction);
SetUserAction(eventAction);
SetUserAction(new B1SteppingAction(eventAction));
}
|
#include <controller.h>
void Controller::control()
{
if (!reset_n.read())
{
sel_const.write(0);
sel_in_1.write(0);
sel_in_2.write(0);
sel_op.write(0);
we_n.write("1111");
s_sel_op_mem.write(0);
s_we_mem1_n.write("1111");
s_we_mem2_n.write("1111");
}
else
{
sel_in_1.write(static_cast< sc_bv<3> > (addr_in_1.read()));
sel_in_2.write(static_cast< sc_bv<3> > (addr_in_2.read()));
sc_bv<4> tmp_we_n;
if (opcode.read() == 0)
{
tmp_we_n = "1111";
}
else if (addr_out.read() == 0)
{
tmp_we_n = "1110";
}
else if (addr_out.read() == 1)
{
tmp_we_n = "1101";
}
else if (addr_out.read() == 2)
{
tmp_we_n = "1011";
}
else
{
tmp_we_n = "0111";
}
s_we_mem1_n.write(tmp_we_n);
s_we_mem2_n.write(s_we_mem1_n.read());
we_n.write(s_we_mem2_n.read());
s_sel_op_mem.write(static_cast< sc_bv<3> > (opcode.read()));
sel_op.write(s_sel_op_mem.read());
sel_const.write((opcode.read() == 1) | (opcode.read() == 5));
}
}
|
#include <mycanvas.h>
#include <vector>
MyCanvas::MyCanvas(QWidget *parent) : QWidget (parent)
{
int scene_height = 631;
int scene_width = 711;
scene.main_scene = QImage(scene_width, scene_height, QImage::Format_RGB32);
scene.main_scene.fill(QColor(Qt::white));
cutter.min_point = {-1, -1};
cutter.max_point = {-1, -1};
}
void MyCanvas::update_scene()
{
scene.main_scene.fill(QColor(Qt::white));
QPoint unpoint = {-1, -1};
if ((cutter.max_point != unpoint) && (cutter.min_point != unpoint))
draw_cutter(color.color_cutter);
draw_all_lines(color.color_line);
repaint();
}
// For using repaint()
void MyCanvas::paintEvent(QPaintEvent *event)
{
QPainter painter(this); // scene.main_scene
painter.drawImage(0, 0, scene.main_scene);
}
void MyCanvas::clear_scene()
{
clear_lines();
clear_cutter();
update_scene();
}
void MyCanvas::clear_lines()
{
lines.clear();
update_scene();
}
void MyCanvas::clear_cutter()
{
cutter.min_point = {-1, -1};
cutter.max_point = {-1, -1};
update_scene();
}
void MyCanvas::add_line(const Line &line)
{
lines.back() = line;
update_scene();
}
void MyCanvas::add_new_line(const QPoint &point, const ModeAdd& mode)
{
QPoint cur_point = point;
QPoint unpoint = {-1, -1};
auto& cur_line = lines.back();
if (lines.empty())
lines.push_back(Line(point, {-1, -1}));
else if((cur_line.start != unpoint) && (cur_line.end != unpoint))
lines.push_back(Line(point, {-1, -1}));
else if (cur_line.end == unpoint)
{
if (mode == HORIZONTAL)
{
if (abs(point.x() - cur_line.start.x()) <
abs(point.y() - cur_line.start.y()))
cur_point.setX(cur_line.start.x());
else
cur_point.setY(cur_line.start.y());
}
cur_line = {cur_line.start, cur_point};
update_scene();
}
}
void MyCanvas::update_rectangle_cutter(const QPoint &point)
{
QPoint unpoint = {-1, -1};
if ((cutter.max_point == unpoint) && (cutter.min_point != unpoint))
{
cutter.max_point = point;
if (cutter.min_point.rx() > cutter.max_point.rx())
swap(cutter.min_point.rx(), cutter.max_point.rx());
if (cutter.min_point.ry() > cutter.max_point.ry())
swap(cutter.min_point.ry(), cutter.max_point.ry());
update_scene();
}
else
{
cutter.min_point = point;
cutter.max_point = unpoint;
}
}
bool MyCanvas::region_is_empty()
{
return lines.empty();
}
|
#define IONIR_TESTS_ROOT_FILENAME ".root"
#include <ionir/test/filesystem.h>
#include "pch.h"
// Testing environment initialization.
int main(int argc, char **argv) {
// Ensure root directory anchor file is visible.
if (!ionir::test::fs::exists(ionir::test::fs::resolveTestPath(IONIR_TESTS_ROOT_FILENAME))) {
throw std::runtime_error("Cannot find root file");
}
// Initialize Google tests.
::testing::InitGoogleTest(&argc, argv);
// Run tests.
return RUN_ALL_TESTS();
}
|
/**
* Copyright (c) 2020, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef lnav_func_util_hh
#define lnav_func_util_hh
#include <functional>
#include <utility>
template<typename F, typename FrontArg>
decltype(auto)
bind_mem(F&& f, FrontArg&& frontArg)
{
return [f = std::forward<F>(f),
frontArg = std::forward<FrontArg>(frontArg)](auto&&... backArgs) {
return (frontArg->*f)(std::forward<decltype(backArgs)>(backArgs)...);
};
}
struct noop_func {
struct anything {
template<class T>
operator T()
{
return {};
}
// optional reference support. Somewhat evil.
template<class T>
operator T&() const
{
static T t{};
return t;
}
};
template<class... Args>
anything operator()(Args&&...) const
{
return {};
}
};
namespace lnav {
namespace func {
class scoped_cb {
public:
class guard {
public:
explicit guard(scoped_cb* owner) : g_owner(owner) {}
guard(const guard&) = delete;
guard& operator=(const guard&) = delete;
guard(guard&& gu) noexcept : g_owner(std::exchange(gu.g_owner, nullptr))
{
}
guard& operator=(guard&& gu) noexcept
{
this->g_owner = std::exchange(gu.g_owner, nullptr);
return *this;
}
~guard()
{
if (this->g_owner != nullptr) {
this->g_owner->s_callback = {};
}
}
private:
scoped_cb* g_owner;
};
guard install(std::function<void()> cb)
{
this->s_callback = std::move(cb);
return guard{this};
}
void operator()()
{
if (s_callback) {
s_callback();
}
}
private:
std::function<void()> s_callback;
};
template<typename Fn,
typename... Args,
std::enable_if_t<std::is_member_pointer<std::decay_t<Fn>>{}, int> = 0>
constexpr decltype(auto)
invoke(Fn&& f, Args&&... args) noexcept(
noexcept(std::mem_fn(f)(std::forward<Args>(args)...)))
{
return std::mem_fn(f)(std::forward<Args>(args)...);
}
template<typename Fn,
typename... Args,
std::enable_if_t<!std::is_member_pointer<std::decay_t<Fn>>{}, int> = 0>
constexpr decltype(auto)
invoke(Fn&& f, Args&&... args) noexcept(
noexcept(std::forward<Fn>(f)(std::forward<Args>(args)...)))
{
return std::forward<Fn>(f)(std::forward<Args>(args)...);
}
template<class F, class... Args>
struct is_invocable {
template<typename U, typename Obj, typename... FuncArgs>
static auto test(U&& p)
-> decltype((std::declval<Obj>().*p)(std::declval<FuncArgs>()...),
void(),
std::true_type());
template<typename U, typename... FuncArgs>
static auto test(U* p) -> decltype((*p)(std::declval<FuncArgs>()...),
void(),
std::true_type());
template<typename U, typename... FuncArgs>
static auto test(...) -> decltype(std::false_type());
static constexpr bool value = decltype(test<F, Args...>(0))::value;
};
} // namespace func
} // namespace lnav
#endif
|
#ifndef __VIVADO_SYNTH__
#include <fstream>
using namespace std;
// Debug utility
ofstream* global_debug_handle;
#endif //__VIVADO_SYNTH__
#include "pw16_opt_compute_units.h"
#include "hw_classes.h"
struct input_input_update_0_write0_merged_banks_1_cache {
// RAM Box: {[0, 299], [0, 299]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct input_cache {
input_input_update_0_write0_merged_banks_1_cache input_input_update_0_write0_merged_banks_1;
};
inline void input_input_update_0_write0_write(hw_uint<16>& input_input_update_0_write0, input_cache& input, int d0, int d1) {
input.input_input_update_0_write0_merged_banks_1.push(input_input_update_0_write0);
}
inline hw_uint<16> pw16_rd0_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// pw16_rd0 read pattern: { pw16_update_0[d0, d1] -> input[d0, d1] : 0 <= d0 <= 299 and 0 <= d1 <= 299 }
// Read schedule : { pw16_update_0[d0, d1] -> [d1, d0, 2] : 0 <= d0 <= 299 and 0 <= d1 <= 299 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 299 and 0 <= d1 <= 299 }
// DD fold: { }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// input_update_0_write
// input_input_update_0_write0
inline void input_input_update_0_write_bundle_write(hw_uint<16>& input_update_0_write, input_cache& input, int d0, int d1) {
hw_uint<16> input_input_update_0_write0_res = input_update_0_write.extract<0, 15>();
input_input_update_0_write0_write(input_input_update_0_write0_res, input, d0, d1);
}
// pw16_update_0_read
// pw16_rd0
inline hw_uint<16> input_pw16_update_0_read_bundle_read(input_cache& input, int d0, int d1) {
// # of ports in bundle: 1
// pw16_rd0
hw_uint<16> result;
hw_uint<16> pw16_rd0_res = pw16_rd0_select(input, d0, d1);
set_at<0, 16>(result, pw16_rd0_res);
return result;
}
// Operation logic
inline void input_update_0(HWStream<hw_uint<16> >& /* buffer_args num ports = 1 */input_arg, input_cache& input, int d0, int d1) {
// Consume: input_arg
auto input_arg_0_c__0_value = input_arg.read();
auto compute_result = input_generated_compute_unrolled_1(input_arg_0_c__0_value);
// Produce: input
input_input_update_0_write_bundle_write(compute_result, input, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<16> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
*global_debug_handle << "input_update_0," << (1*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
#endif //__VIVADO_SYNTH__
}
inline void pw16_update_0(input_cache& input, HWStream<hw_uint<16> >& /* buffer_args num ports = 1 */pw16, int d0, int d1) {
// Consume: input
auto input_0_c__0_value = input_pw16_update_0_read_bundle_read(input/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "pw16_update_0_input," << d0<< "," << d1<< "," << input_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = pw16_generated_compute_unrolled_1(input_0_c__0_value);
// Produce: pw16
pw16.write(compute_result);
#ifndef __VIVADO_SYNTH__
hw_uint<16> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
*global_debug_handle << "pw16_update_0," << (1*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
#endif //__VIVADO_SYNTH__
}
// Driver function
void pw16_opt(HWStream<hw_uint<16> >& /* get_args num ports = 1 */input_arg, HWStream<hw_uint<16> >& /* get_args num ports = 1 */pw16, uint64_t num_epochs) {
#ifndef __VIVADO_SYNTH__
ofstream debug_file("pw16_opt_debug.csv");
global_debug_handle = &debug_file;
#endif //__VIVADO_SYNTH__
input_cache input;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (uint64_t epoch = 0; epoch < num_epochs; epoch++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (int c0 = 0; c0 <= 299; c0++) {
for (int c1 = 0; c1 <= 299; c1++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS pipeline II=1
#endif // __VIVADO_SYNTH__
if ((0 <= c1 && c1 <= 299) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 299) && ((c0 - 0) % 1 == 0)) {
input_update_0(input_arg, input, (c1 - 0) / 1, (c0 - 0) / 1);
}
if ((0 <= c1 && c1 <= 299) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 299) && ((c0 - 0) % 1 == 0)) {
pw16_update_0(input, pw16, (c1 - 0) / 1, (c0 - 0) / 1);
}
}
}
}
#ifndef __VIVADO_SYNTH__
debug_file.close();
#endif //__VIVADO_SYNTH__
}
void pw16_opt(HWStream<hw_uint<16> >& /* get_args num ports = 1 */input_arg, HWStream<hw_uint<16> >& /* get_args num ports = 1 */pw16) {
pw16_opt(input_arg, pw16, 1);
}
#ifdef __VIVADO_SYNTH__
#include "pw16_opt.h"
#define INPUT_SIZE 90000
#define OUTPUT_SIZE 90000
extern "C" {
static void read_input(hw_uint<16>* input, HWStream<hw_uint<16> >& v, const int size) {
hw_uint<16> burst_reg;
for (int i = 0; i < INPUT_SIZE; i++) {
#pragma HLS pipeline II=1
burst_reg = input[i];
v.write(burst_reg);
}
}
static void write_output(hw_uint<16>* output, HWStream<hw_uint<16> >& v, const int size) {
hw_uint<16> burst_reg;
for (int i = 0; i < OUTPUT_SIZE; i++) {
#pragma HLS pipeline II=1
burst_reg = v.read();
output[i] = burst_reg;
}
}
void pw16_opt_accel(hw_uint<16>* input_update_0_read, hw_uint<16>* pw16_update_0_write, const int size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = input_update_0_read offset = slave depth = 65536 bundle = gmem0
#pragma HLS INTERFACE m_axi port = pw16_update_0_write offset = slave depth = 65536 bundle = gmem1
#pragma HLS INTERFACE s_axilite port = input_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = pw16_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static HWStream<hw_uint<16> > input_update_0_read_channel;
static HWStream<hw_uint<16> > pw16_update_0_write_channel;
read_input(input_update_0_read, input_update_0_read_channel, size);
pw16_opt(input_update_0_read_channel, pw16_update_0_write_channel);
write_output(pw16_update_0_write, pw16_update_0_write_channel, size);
}
}
#endif //__VIVADO_SYNTH__
|
#include"ProjetC++2(ClassObject).h"
set<Object*>Object::_pool;
Object::Object (const string& nom) : _nom(nom) // registerObject
{
_pool.insert(this);
cout << "enregistrer " << _nom << endl;
}
static void viderPool()
{ // vider Pool
set<Object*>::iterator it;
while ( (it = _pool.begin()) != _pool.end() )
delete (*it);
}
Object:: ~Object() //unregisterObject
{
_pool.erase(this);
cout << "liberer " << _nom << endl;
}
void Object :: setNom(const string & nom)
{
_nom=nom;
}
/*string str() const;{ return _object; }*/
|
struct Point {
int x;
int y;
bool operator==(const Point& o) {
return x == o.x && y == o.y;
}
bool operator!=(const Point& o) {
return !(*this == o);
}
Point operator=(const Point& o) {
x = o.x;
y = o.y;
return *this;
}
bool operator<(const Point& o) const {
return (this->x < o.x && this->y < o.y);
}
};
class Rect {
public:
Point uL;
Point lR;
Rect(Point u, Point l)
{
uL = u;
lR = l;
}
Rect(int x, int y, int w, int h)
{
uL.x = x;
uL.y = y;
lR.x = x+w;
lR.y = y+h;
}
Rect() { }
Rect(const Rect&) { }
};
|
#include <iostream>
using namespace std;
class File
{
private:
/* data */
public:
File(/* args */);
~File();
};
File::File(/* args */)
{
}
File::~File()
{
}
|
#include<iostream>
int main(){
cout<<"huak"<<endl;
return 0;
}
|
// Created on: 1993-05-07
// Created by: Jacques GOUSSARD
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntPatch_RstInt_HeaderFile
#define _IntPatch_RstInt_HeaderFile
#include <Adaptor3d_Surface.hxx>
class IntPatch_Line;
class Adaptor3d_TopolTool;
//! trouver les points d intersection entre la ligne de
//! cheminement et les arcs de restriction
class IntPatch_RstInt
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT static void PutVertexOnLine (const Handle(IntPatch_Line)& L,
const Handle(Adaptor3d_Surface)& Surf,
const Handle(Adaptor3d_TopolTool)& Domain,
const Handle(Adaptor3d_Surface)& OtherSurf,
const Standard_Boolean OnFirst,
const Standard_Real Tol);
};
#endif // _IntPatch_RstInt_HeaderFile
|
#ifndef STUDENTINFO_H
#define STUDENTINFO_H
#include<string>
//Replace "Your Name" and "Your ID#";
namespace StudentInfo {
std::string name() { return "Se Rang Seo"; }
std::string id() { return "1575601"; }
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//solved.
int main(){
ll d;
cin>>d;
while(d--){
ll a;
vector<ll> agnes;
cin>>a;
while(a){
agnes.push_back(a);
cin>>a;
//cout<<a<<" ";
}
ll n = agnes.size();
vector<vector<ll>> tom;
vector<ll> t;
while(1){
cin>>a;
if(a==0) break;
while(a) {t.push_back(a); cin>>a;}
tom.push_back(t);
t.clear();
}
ll ans = 0;
for(int i=0;i<tom.size();i++){
vector<vector<ll>> temp(tom[i].size(), vector<ll>(n,-1));
for(int j=0;j<temp.size();j++){
for(int k =0;k<n;k++){
if(tom[i][j] == agnes[k]){
//temp[j][k] = ((j-1)>=0 && (k-1)>=0)? 1+temp[j-1][k-1] : 1;
if((j-1)>=0 && (k-1)>=0) temp[j][k] = temp[j-1][k-1] + 1;
else temp[j][k] = 1;
}
else{
if(j-1>=0 && k-1>=0){
temp[j][k] = max(temp[j-1][k-1], max(temp[j][k-1], temp[j-1][k]));
}
else if(j-1>=0){
temp[j][k] = temp[j-1][k];
}
else if(k-1>=0){
temp[j][k] = temp[j][k-1];
}
else temp[j][k] = 0;
}
}
}
ans = max(ans, temp[temp.size()-1][n-1]);
}
cout<<ans<<endl;
}
}
|
#ifndef NV_MEMORY_INPUT_STREAM_H
#define NV_MEMORY_INPUT_STREAM_H
#include <cstdio>
#include <string>
namespace nv_test
{
class MemoryInputStream
{
MemoryInputStream(MemoryInputStream const & other) = delete;
MemoryInputStream& operator=(MemoryInputStream const & other) = delete;
public:
MemoryInputStream();
explicit MemoryInputStream(std::string const & contents);
~MemoryInputStream();
operator FILE*();
FILE * file();
private:
void init();
std::string contents_;
FILE * file_;
};
}
#endif
|
#include <math.h>
#include <limits.h>
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int sum = 0;
for (int a:A){
sum+=a;
}
int sum_pre = A[0];
int sum_post = sum-A[0];
int cur_diff = abs(sum_post-sum_pre);
int min_diff = cur_diff;
for (int P=1; P<A.size()-1; P++){
sum_pre+=A[P];
sum_post-=A[P];
cur_diff = abs(sum_post-sum_pre);
min_diff = min(min_diff, cur_diff);
}
return min_diff;
}
|
#ifndef IOREMAP_THEVOID_SERVER_P_HPP
#define IOREMAP_THEVOID_SERVER_P_HPP
#include "server.hpp"
#include "acceptorlist_p.hpp"
#include "connection_p.hpp"
#include "monitor_connection_p.hpp"
#include <signal.h>
#include <mutex>
#include <set>
namespace ioremap {
namespace thevoid {
int get_connections_counter();
//! This handler is created to resolve creation of several servers in one process,
//! all of them must be stopped on SIGINT/SIGTERM signal
class signal_handler
{
public:
signal_handler()
{
if (SIG_ERR == signal(SIGINT, handler)) {
throw std::runtime_error("Cannot set up SIGINT handler");
}
if (SIG_ERR == signal(SIGTERM, handler)) {
throw std::runtime_error("Cannot set up SIGTERM handler");
}
}
~signal_handler()
{
}
static void handler(int);
std::mutex lock;
std::set<server_data*> all_servers;
};
typedef std::shared_ptr<base_stream_factory> factory_ptr;
class server_data
{
public:
server_data();
~server_data();
void handle_stop();
//! Weak pointer to server itself
std::weak_ptr<base_server> server;
//! The io_service used to perform asynchronous operations.
boost::asio::io_service io_service;
//! Size of thread pool per socket
unsigned int threads_count;
unsigned int backlog_size;
//! List of activated acceptors
acceptors_list<unix_connection> local_acceptors;
acceptors_list<tcp_connection> tcp_acceptors;
acceptors_list<monitor_connection> monitor_acceptors;
//! The signal_set is used to register for process termination notifications.
std::shared_ptr<signal_handler> signal_set;
//! User handlers for urls
std::vector<std::pair<std::string, factory_ptr>> prefix_handlers;
std::map<std::string, factory_ptr> handlers;
};
}}
#endif // IOREMAP_THEVOID_SERVER_P_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.