diff --git a/CMakeLists.txt b/CMakeLists.txt index fac5bcfd8..ac2e8469f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -509,10 +509,6 @@ if (GUI) # add_subdirectory(third) // reenable once not qtwebkit. endif() - if (SOLIDITY) - add_subdirectory(mix) - endif () - endif() if (APPLE AND GUI) diff --git a/mix/.gitignore b/mix/.gitignore deleted file mode 100644 index f96209dc3..000000000 --- a/mix/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pro diff --git a/mix/CMakeLists.txt b/mix/CMakeLists.txt deleted file mode 100644 index 06d9c2ecd..000000000 --- a/mix/CMakeLists.txt +++ /dev/null @@ -1,97 +0,0 @@ -cmake_policy(SET CMP0015 NEW) -# let cmake autolink dependencies on windows -cmake_policy(SET CMP0020 NEW) -# this policy was introduced in cmake 3.0 -# remove if, once 3.0 will be used on unix -if (${CMAKE_MAJOR_VERSION} GREATER 2) - cmake_policy(SET CMP0043 OLD) -endif() - -set(CMAKE_INCLUDE_CURRENT_DIR ON) - -aux_source_directory(. SRC_LIST) - -include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS}) -include_directories(${Boost_INCLUDE_DIRS}) -include_directories(BEFORE ..) - -if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "3.6") AND NOT APPLE) - # Supress warnings for qt headers for clang+ccache - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-inconsistent-missing-override") -endif () - -#TODO: remove once qt 5.5.1 is out -if (APPLE) - qt5_add_resources(UI_RESOURCES osx.qrc) -endif() - -find_package (Qt5WebEngine) -if (APPLE AND (NOT "${Qt5Core_VERSION_STRING}" VERSION_LESS "5.5")) -# TODO: remove indirect dependencies once macdeployqt is fixed - find_package (Qt5WebEngineCore) - find_package (Qt5DBus) - find_package (Qt5PrintSupport) -endif() -qt5_add_resources(UI_RESOURCES res.qrc qml.qrc) - -file(GLOB HEADERS "*.h") - -set(EXECUTABLE mix) - -if ("${Qt5WebEngine_VERSION_STRING}" VERSION_GREATER "5.3.0") - set (ETH_HAVE_WEBENGINE TRUE) - qt5_add_resources(UI_RESOURCES web.qrc) -else() - qt5_add_resources(UI_RESOURCES noweb.qrc) -endif() - -if (CMAKE_BUILD_TYPE MATCHES Debug) - add_definitions(-DQT_QML_DEBUG) -endif() - -# eth_add_executable is defined in cmake/EthExecutableHelper.cmake -eth_add_executable(${EXECUTABLE} - ICON mix - UI_RESOURCES ${UI_RESOURCES} -) - - -set(LIBRARIES "Qt5::Core;Qt5::Gui;Qt5::Widgets;Qt5::Network;Qt5::Quick;Qt5::Qml;webthree;ethereum;evm;ethcore;devcrypto;solidity;evmcore;devcore;jsqrc;web3jsonrpc") -if (${ETH_HAVE_WEBENGINE}) - add_definitions(-DETH_HAVE_WEBENGINE) - list(APPEND LIBRARIES "Qt5::WebEngine") -endif() -if (APPLE AND (NOT "${Qt5Core_VERSION_STRING}" VERSION_LESS "5.5")) - list(APPEND LIBRARIES "Qt5::WebEngineCore") - list(APPEND LIBRARIES "Qt5::DBus") - list(APPEND LIBRARIES "Qt5::PrintSupport") -endif() - -target_link_libraries(${EXECUTABLE} ${LIBRARIES}) - -# eth_install_executable is defined in cmake/EthExecutableHelper.cmake -eth_install_executable(${EXECUTABLE} - QMLDIR ${CMAKE_CURRENT_SOURCE_DIR}/qml -) - -#add qml asnd stdc files to project tree in Qt creator -file(GLOB_RECURSE QMLFILES "qml/*.*") -file(GLOB_RECURSE TESTFILES "test/qml/*.*") -file(GLOB_RECURSE SOLFILES "stdc/*.*") -add_custom_target(mix_qml SOURCES ${QMLFILES} ${SOLFILES} ${TESTFILES}) - -#test target -find_package(Qt5QuickTest REQUIRED) -find_package(Qt5Test REQUIRED) -set(TEST_EXECUTABLE mix_test) -list(APPEND LIBRARIES "Qt5::QuickTest") -list(APPEND LIBRARIES "Qt5::Test") -list(REMOVE_ITEM SRC_LIST "./main.cpp") -aux_source_directory(test SRC_LIST) -file(GLOB HEADERS "test/*.h") -add_executable(${TEST_EXECUTABLE} ${UI_RESOURCES} ${SRC_LIST} ${HEADERS}) -target_link_libraries(${TEST_EXECUTABLE} ${LIBRARIES}) -set_target_properties(${TEST_EXECUTABLE} PROPERTIES EXCLUDE_FROM_ALL 1 EXCLUDE_FROM_DEFAULT_BUILD 1) - - - diff --git a/mix/ClientModel.cpp b/mix/ClientModel.cpp deleted file mode 100644 index d5973ce5e..000000000 --- a/mix/ClientModel.cpp +++ /dev/null @@ -1,986 +0,0 @@ -/* - This file is part of cpp-ethereum. - cpp-ethereum 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. - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file ClientModel.cpp - * @author Yann yann@ethdev.com - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -// Make sure boost/asio.hpp is included before windows.h. -#include - -#include "ClientModel.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "DebuggingStateWrapper.h" -#include "Exceptions.h" -#include "QContractDefinition.h" -#include "QVariableDeclaration.h" -#include "QVariableDefinition.h" -#include "ContractCallDataEncoder.h" -#include "CodeModel.h" -#include "QEther.h" -#include "Web3Server.h" -#include "MixClient.h" - -using namespace dev; -using namespace dev::eth; -using namespace std; - -namespace dev -{ -namespace mix -{ - -class RpcConnector: public jsonrpc::AbstractServerConnector -{ -public: - virtual bool StartListening() override { return true; } - virtual bool StopListening() override { return true; } - virtual bool SendResponse(string const& _response, void*) override - { - m_response = QString::fromStdString(_response); - return true; - } - QString response() const { return m_response; } - -private: - QString m_response; -}; - - -ClientModel::ClientModel(): - m_running(false), m_rpcConnector(new RpcConnector()) -{ - qRegisterMetaType("QBigInt*"); - qRegisterMetaType("QVariableDefinition*"); - qRegisterMetaType>("QList"); - qRegisterMetaType>("QList"); - qRegisterMetaType("QVariableDeclaration*"); - qRegisterMetaType("QSolidityType*"); - qRegisterMetaType("QMachineState"); - qRegisterMetaType("QInstruction"); - qRegisterMetaType("QCode"); - qRegisterMetaType("QCallData"); - qRegisterMetaType("RecordLogEntry*"); -} - -ClientModel::~ClientModel() -{ - m_runFuture.waitForFinished(); -} - -void ClientModel::init(QString _dbpath) -{ - m_dbpath = _dbpath; - if (m_dbpath.isEmpty()) - m_client.reset(new MixClient(QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdString())); - else - m_client.reset(new MixClient(m_dbpath.toStdString())); - - m_ethAccounts = make_shared([=](){return m_client.get();}, std::vector()); - m_web3Server.reset(new Web3Server(*m_rpcConnector.get(), m_ethAccounts, std::vector(), m_client.get())); - connect(m_web3Server.get(), &Web3Server::newTransaction, this, &ClientModel::onNewTransaction, Qt::DirectConnection); -} - -QString ClientModel::apiCall(QString const& _message) -{ - try - { - m_rpcConnector->OnRequest(_message.toStdString(), nullptr); - return m_rpcConnector->response(); - } - catch (...) - { - cerr << boost::current_exception_diagnostic_information(); - return QString(); - } -} - -void ClientModel::mine() -{ - if (m_mining) - BOOST_THROW_EXCEPTION(ExecutionStateException()); - m_mining = true; - emit miningStarted(); - emit miningStateChanged(); - m_runFuture = QtConcurrent::run([=]() - { - try - { - m_client->mine(); - newBlock(); - m_mining = false; - emit miningComplete(); - } - catch (...) - { - m_mining = false; - cerr << boost::current_exception_diagnostic_information(); - emit runFailed(QString::fromStdString(boost::current_exception_diagnostic_information())); - } - emit miningStateChanged(); - }); -} - -QString ClientModel::newSecret() -{ - KeyPair a = KeyPair::create(); - return QString::fromStdString(dev::toHex(a.secret().ref())); -} - -QString ClientModel::address(QString const& _secret) -{ - return QString::fromStdString(dev::toHex(KeyPair(Secret(_secret.toStdString())).address().ref())); -} - -QString ClientModel::toHex(QString const& _int) -{ - return QString::fromStdString(dev::toHex(dev::u256(_int.toStdString()))); -} - -QString ClientModel::encodeAbiString(QString _string) -{ - ContractCallDataEncoder encoder; - return QString::fromStdString(dev::toHex(encoder.encodeBytes(_string))); -} - -QString ClientModel::encodeStringParam(QString const& _param) -{ - ContractCallDataEncoder encoder; - return QString::fromStdString(dev::toHex(encoder.encodeStringParam(_param, 32))); -} - -QStringList ClientModel::encodeParams(QVariant const& _param, QString const& _contract, QString const& _function) -{ - QStringList ret; - CompiledContract const& compilerRes = m_codeModel->contract(_contract); - QList paramsList; - shared_ptr contractDef = compilerRes.sharedContract(); - if (_contract == _function) - paramsList = contractDef->constructor()->parametersList(); - else - for (QFunctionDefinition* tf: contractDef->functionsList()) - if (tf->name() == _function) - { - paramsList = tf->parametersList(); - break; - } - if (paramsList.length() > 0) - for (QVariableDeclaration* var: paramsList) - { - ContractCallDataEncoder encoder; - QSolidityType const* type = var->type(); - QVariant value = _param.toMap().value(var->name()); - encoder.encode(value, type->type()); - ret.push_back(QString::fromStdString(dev::toHex(encoder.encodedData()))); - } - return ret; -} - -QVariantMap ClientModel::contractAddresses() const -{ - QVariantMap res; - for (auto const& c: m_contractAddresses) - res.insert(c.first.first, QString::fromStdString(toJS(c.second))); - return res; -} - -QVariantList ClientModel::gasCosts() const -{ - QVariantList res; - for (auto const& c: m_gasCosts) - res.append(QVariant::fromValue(static_cast(c))); - return res; -} - -void ClientModel::addAccount(QString const& _secret) -{ - KeyPair key(Secret(_secret.toStdString())); - m_accountsSecret.push_back(key); - Address address = key.address(); - m_accounts[address] = Account(u256(0), Account::NormalCreation); - m_ethAccounts->setAccounts(m_accountsSecret); -} - -QString ClientModel::resolveAddress(QString const& _secret) -{ - KeyPair key(Secret(_secret.toStdString())); - return "0x" + QString::fromStdString(key.address().hex()); -} - -void ClientModel::setupScenario(QVariantMap _scenario) -{ - onStateReset(); - WriteGuard(x_queueTransactions); - m_running = true; - - QVariantList blocks = _scenario.value("blocks").toList(); - QVariantList stateAccounts = _scenario.value("accounts").toList(); - QVariantList stateContracts = _scenario.value("contracts").toList(); - - m_accounts.clear(); - m_accountsSecret.clear(); - for (auto const& b: stateAccounts) - { - QVariantMap account = b.toMap(); - Address address = {}; - if (account.contains("secret")) - { - KeyPair key(Secret(account.value("secret").toString().toStdString())); - m_accountsSecret.push_back(key); - address = key.address(); - } - else if (account.contains("address")) - address = Address(fromHex(account.value("address").toString().toStdString())); - if (!address) - continue; - - m_accounts[address] = Account(qvariant_cast(account.value("balance"))->toU256Wei(), Account::NormalCreation); - } - m_ethAccounts->setAccounts(m_accountsSecret); - - for (auto const& c: stateContracts) - { - QVariantMap contract = c.toMap(); - Address address = Address(fromHex(contract.value("address").toString().toStdString())); - Account account(qvariant_cast(contract.value("balance"))->toU256Wei(), Account::ContractConception); - bytes code = fromHex(contract.value("code").toString().toStdString()); - account.setCode(std::move(code)); - QVariantMap storageMap = contract.value("storage").toMap(); - for(auto s = storageMap.cbegin(); s != storageMap.cend(); ++s) - account.setStorage(fromBigEndian(fromHex(s.key().toStdString())), fromBigEndian(fromHex(s.value().toString().toStdString()))); - m_accounts[address] = account; - } - - bool trToExecute = false; - for (auto const& b: blocks) - { - QVariantList transactions = b.toMap().value("transactions").toList(); - m_queueTransactions.push_back(transactions); - trToExecute = transactions.size() > 0; - } - m_client->resetState(m_accounts, Secret(_scenario.value("miner").toMap().value("secret").toString().toStdString())); - if (m_queueTransactions.count() > 0 && trToExecute) - { - setupExecutionChain(); - processNextTransactions(); - } - else - m_running = false; -} - -void ClientModel::setupExecutionChain() -{ - connect(this, &ClientModel::newBlock, this, &ClientModel::processNextTransactions, Qt::QueuedConnection); - connect(this, &ClientModel::runFailed, this, &ClientModel::stopExecution, Qt::QueuedConnection); - connect(this, &ClientModel::runStateChanged, this, &ClientModel::finalizeBlock, Qt::QueuedConnection); -} - -void ClientModel::stopExecution() -{ - disconnect(this, &ClientModel::newBlock, this, &ClientModel::processNextTransactions); - disconnect(this, &ClientModel::runStateChanged, this, &ClientModel::finalizeBlock); - disconnect(this, &ClientModel::runFailed, this, &ClientModel::stopExecution); - m_running = false; -} - -void ClientModel::finalizeBlock() -{ - m_queueTransactions.pop_front();// pop last execution group. The last block is never mined (pending block) - if (m_queueTransactions.size() > 0) - mine(); - else - { - stopExecution(); - emit runComplete(); - } -} - -TransactionSettings ClientModel::transaction(QVariant const& _tr) const -{ - QVariantMap transaction = _tr.toMap(); - QString contractId = transaction.value("contractId").toString(); - QString functionId = transaction.value("functionId").toString(); - bool gasAuto = transaction.value("gasAuto").toBool(); - u256 gas = 0; - if (transaction.value("gas").data()) - gas = boost::get(qvariant_cast(transaction.value("gas"))->internalValue()); - else - gasAuto = true; - - u256 value = (qvariant_cast(transaction.value("value")))->toU256Wei(); - u256 gasPrice = (qvariant_cast(transaction.value("gasPrice")))->toU256Wei(); - QString sender = transaction.value("sender").toString(); - bool isContractCreation = transaction.value("isContractCreation").toBool(); - bool isFunctionCall = transaction.value("isFunctionCall").toBool(); - if (contractId.isEmpty() && m_codeModel->hasContract()) //TODO: This is to support old project files, remove later - contractId = m_codeModel->contracts().keys()[0]; - Secret f = Secret(sender.toStdString()); - TransactionSettings transactionSettings(contractId, functionId, value, gas, gasAuto, gasPrice, f, isContractCreation, isFunctionCall); - transactionSettings.parameterValues = transaction.value("parameters").toMap(); - if (contractId == functionId || functionId == "Constructor") - transactionSettings.functionId.clear(); - return transactionSettings; -} - -void ClientModel::processNextTransactions() -{ - WriteGuard(x_queueTransactions); - vector transactionSequence; - for (auto const& t: m_queueTransactions.front()) - { - TransactionSettings transactionSettings = transaction(t); - transactionSequence.push_back(transactionSettings); - } - executeSequence(transactionSequence); -} - -void ClientModel::executeSequence(vector const& _sequence) -{ - if (m_running) - { - qWarning() << "Waiting for current execution to complete"; - m_runFuture.waitForFinished(); - } - emit runStarted(); - //run sequence - m_runFuture = QtConcurrent::run([=]() - { - try - { - m_gasCosts.clear(); - for (TransactionSettings const& transaction: _sequence) - { - std::pair ctrInstance = resolvePair(transaction.contractId); - QString address = resolveToken(ctrInstance); - if (!transaction.isFunctionCall) - { - callAddress(Address(address.toStdString()), bytes(), transaction); - onNewTransaction(); - continue; - } - ContractCallDataEncoder encoder; - //encode data - CompiledContract const& compilerRes = m_codeModel->contract(ctrInstance.first); - QFunctionDefinition const* f = nullptr; - bytes contractCode = compilerRes.bytes(); - shared_ptr contractDef = compilerRes.sharedContract(); - if (transaction.functionId.isEmpty()) - f = contractDef->constructor(); - else - for (QFunctionDefinition const* tf: contractDef->functionsList()) - if (tf->name() == transaction.functionId) - { - f = tf; - break; - } - if (!f) - emit runFailed("Function '" + transaction.functionId + tr("' not found. Please check transactions or the contract code.")); - if (!transaction.functionId.isEmpty()) - encoder.encode(f); - for (QVariableDeclaration const* p: f->parametersList()) - { - QSolidityType const* type = p->type(); - QVariant value = transaction.parameterValues.value(p->name()); - if (type->type().type == SolidityType::Type::Address) - { - if (type->array()) - { - QJsonArray jsonDoc = QJsonDocument::fromJson(value.toString().toUtf8()).array(); - int k = 0; - for (QJsonValue const& item: jsonDoc) - { - if (item.toString().startsWith("<")) - { - std::pair ctrParamInstance = resolvePair(item.toString()); - jsonDoc.replace(k, resolveToken(ctrParamInstance)); - } - k++; - } - QJsonDocument doc(jsonDoc); - value = QVariant(doc.toJson(QJsonDocument::Compact)); - } - else if (value.toString().startsWith("<")) - { - std::pair ctrParamInstance = resolvePair(value.toString()); - value = QVariant(resolveToken(ctrParamInstance)); - } - } - encoder.encode(value, type->type()); - } - - if (transaction.functionId.isEmpty() || transaction.functionId == ctrInstance.first) - { - bytes param = encoder.encodedData(); - contractCode.insert(contractCode.end(), param.begin(), param.end()); - Address newAddress = deployContract(contractCode, transaction); - std::pair contractToken = retrieveToken(transaction.contractId); - m_contractAddresses[contractToken] = newAddress; - m_contractNames[newAddress] = contractToken.first; - contractAddressesChanged(); - gasCostsChanged(); - } - else - { - auto contractAddressIter = m_contractAddresses.find(ctrInstance); - if (contractAddressIter == m_contractAddresses.end()) - { - emit runFailed("Contract '" + transaction.contractId + tr(" not deployed.") + "' " + tr(" Cannot call ") + transaction.functionId); - Address fakeAddress = Address::random(); - std::pair contractToken = resolvePair(transaction.contractId); - m_contractNames[fakeAddress] = contractToken.first; - callAddress(fakeAddress, encoder.encodedData(), transaction); //Transact to a random fake address to that transaction is added to the list anyway - } - else - callAddress(contractAddressIter->second, encoder.encodedData(), transaction); - } - m_gasCosts.append(m_client->lastExecution().gasUsed); - onNewTransaction(); - TransactionException exception = m_client->lastExecution().excepted; - if (exception != TransactionException::None) - break; - } - emit runComplete(); - } - catch(boost::exception const&) - { - cerr << boost::current_exception_diagnostic_information(); - emit runFailed(QString::fromStdString(boost::current_exception_diagnostic_information())); - } - catch(exception const& e) - { - cerr << boost::current_exception_diagnostic_information(); - emit runFailed(e.what()); - } - emit runStateChanged(); - }); -} - -void ClientModel::executeTr(QVariantMap _tr) -{ - WriteGuard(x_queueTransactions); - QVariantList trs; - trs.push_back(_tr); - m_queueTransactions.push_back(trs); - if (!m_running) - { - m_running = true; - setupExecutionChain(); - processNextTransactions(); - } -} - -std::pair ClientModel::resolvePair(QString const& _contractId) -{ - std::pair ret = std::make_pair(_contractId, 0); - if (_contractId.startsWith("<") && _contractId.endsWith(">")) - { - QStringList values = ret.first.remove("<").remove(">").split(" - "); - ret = std::make_pair(values[0], values[1].toUInt()); - } - if (_contractId.startsWith("0x")) - ret = std::make_pair(_contractId, -2); - return ret; -} - -QString ClientModel::resolveToken(std::pair const& _value) -{ - if (_value.second == -2) //-2: first contains a real address - return _value.first; - else if (m_contractAddresses.size() > 0) - return QString::fromStdString("0x" + dev::toHex(m_contractAddresses[_value].ref())); - else - return _value.first; -} - -std::pair ClientModel::retrieveToken(QString const& _value) -{ - std::pair ret; - ret.first = _value; - ret.second = m_contractAddresses.size(); - return ret; -} - -void ClientModel::showDebugger() -{ - ExecutionResult last = m_client->lastExecution(); - showDebuggerForTransaction(last); -} - -void ClientModel::showDebuggerForTransaction(ExecutionResult const& _t) -{ - //we need to wrap states in a QObject before sending to QML. - QDebugData* debugData = new QDebugData(); - QQmlEngine::setObjectOwnership(debugData, QQmlEngine::JavaScriptOwnership); - QList codes; - QList> codeMaps; - QList codeItems; - QList contracts; - for (MachineCode const& code: _t.executionCode) - { - QHash codeMap; - codes.push_back(QMachineState::getHumanReadableCode(debugData, code.address, code.code, codeMap)); - codeMaps.push_back(move(codeMap)); - //try to resolve contract for source level debugging - auto nameIter = m_contractNames.find(code.address); - CompiledContract const* compilerRes = nullptr; - if (nameIter != m_contractNames.end() && (compilerRes = m_codeModel->tryGetContract(nameIter->second))) //returned object is guaranteed to live till the end of event handler in main thread - { - eth::AssemblyItems assemblyItems = !_t.isConstructor() ? compilerRes->assemblyItems() : compilerRes->constructorAssemblyItems(); - codes.back()->setDocument(compilerRes->documentId()); - codeItems.push_back(move(assemblyItems)); - contracts.push_back(compilerRes); - } - else - { - codeItems.push_back(AssemblyItems()); - contracts.push_back(nullptr); - } - } - - QList data; - for (bytes const& d: _t.transactionData) - data.push_back(QMachineState::getDebugCallData(debugData, d)); - - QVariantList states; - QVariantList solCallStack; - map solLocals; // - map storageDeclarations; // - - unsigned prevInstructionIndex = 0; - for (MachineState const& s: _t.machineStates) - { - int instructionIndex = codeMaps[s.codeIndex][static_cast(s.curPC)]; - QSolState* solState = nullptr; - if (!codeItems[s.codeIndex].empty() && contracts[s.codeIndex]) - { - CompiledContract const* contract = contracts[s.codeIndex]; - AssemblyItem const& instruction = codeItems[s.codeIndex][instructionIndex]; - - if (instruction.type() == eth::Push && !instruction.data()) - { - //register new local variable initialization - auto localIter = contract->locals().find(LocationPair(instruction.getLocation().start, instruction.getLocation().end)); - if (localIter != contract->locals().end()) - solLocals[s.stack.size()] = new QVariableDeclaration(debugData, localIter.value().name.toStdString(), localIter.value().type); - } - - if (instruction.type() == eth::Tag) - { - //track calls into functions - AssemblyItem const& prevInstruction = codeItems[s.codeIndex][prevInstructionIndex]; - QString functionName = m_codeModel->resolveFunctionName(instruction.getLocation()); - if (!functionName.isEmpty() && ((prevInstruction.getJumpType() == AssemblyItem::JumpType::IntoFunction) || solCallStack.empty())) - solCallStack.push_front(QVariant::fromValue(functionName)); - else if (prevInstruction.getJumpType() == AssemblyItem::JumpType::OutOfFunction && !solCallStack.empty()) - { - solCallStack.pop_front(); - solLocals.clear(); - } - } - - //format solidity context values - QVariantMap locals; - QVariantList localDeclarations; - QVariantMap localValues; - for (auto l: solLocals) - if (l.first < (int)s.stack.size()) - { - if (l.second->type()->name().startsWith("mapping")) - break; //mapping type not yet managed - localDeclarations.push_back(QVariant::fromValue(l.second)); - localValues[l.second->name()] = formatValue(l.second->type()->type(), s.stack[l.first]); - } - locals["variables"] = localDeclarations; - locals["values"] = localValues; - - QVariantMap storage; - QVariantList storageDeclarationList; - QVariantMap storageValues; - for (auto st: s.storage) - if (st.first < numeric_limits::max()) - { - auto storageIter = contract->storage().find(static_cast(st.first)); - if (storageIter != contract->storage().end()) - { - QVariableDeclaration* storageDec = nullptr; - for (SolidityDeclaration const& codeDec : storageIter.value()) - { - if (codeDec.type.name.startsWith("mapping")) - continue; //mapping type not yet managed - auto decIter = storageDeclarations.find(codeDec.name); - if (decIter != storageDeclarations.end()) - storageDec = decIter->second; - else - { - storageDec = new QVariableDeclaration(debugData, codeDec.name.toStdString(), codeDec.type); - storageDeclarations[storageDec->name()] = storageDec; - } - storageDeclarationList.push_back(QVariant::fromValue(storageDec)); - storageValues[storageDec->name()] = formatStorageValue(storageDec->type()->type(), s.storage, codeDec.offset, codeDec.slot); - } - } - } - storage["variables"] = storageDeclarationList; - storage["values"] = storageValues; - - prevInstructionIndex = instructionIndex; - - // filter out locations that match whole function or contract - SourceLocation location = instruction.getLocation(); - QString source; - if (location.sourceName) - source = QString::fromUtf8(location.sourceName->c_str()); - if (m_codeModel->isContractOrFunctionLocation(location)) - location = dev::SourceLocation(-1, -1, location.sourceName); - - solState = new QSolState(debugData, move(storage), move(solCallStack), move(locals), location.start, location.end, source); - } - - states.append(QVariant::fromValue(new QMachineState(debugData, instructionIndex, s, codes[s.codeIndex], data[s.dataIndex], solState))); - } - - debugData->setStates(move(states)); - debugDataReady(debugData); -} - -QVariant ClientModel::formatValue(SolidityType const& _type, u256 const& _value) -{ - ContractCallDataEncoder decoder; - bytes val = toBigEndian(_value); - QVariant res = decoder.decode(_type, val); - return res; -} - -QVariant ClientModel::formatStorageValue(SolidityType const& _type, unordered_map const& _storage, unsigned _offset, u256 const& _slot) -{ - u256 slot = _slot; - QVariantList values; - ContractCallDataEncoder decoder; - u256 count = 1; - if (_type.dynamicSize) - { - count = _storage.at(slot); - slot = fromBigEndian(sha3(toBigEndian(slot)).asBytes()); - } - else if (_type.array) - count = _type.count; - - unsigned offset = _offset; - while (count--) - { - - auto slotIter = _storage.find(slot); - u256 slotValue = slotIter != _storage.end() ? slotIter->second : u256(); - bytes slotBytes = toBigEndian(slotValue); - auto start = slotBytes.end() - _type.size - offset; - bytes val(32 - _type.size); //prepend with zeroes - if (_type.type == SolidityType::SignedInteger && (*start & 0x80)) //extend sign - std::fill(val.begin(), val.end(), 0xff); - val.insert(val.end(), start, start + _type.size); - values.append(decoder.decode(_type, val)); - offset += _type.size; - if ((offset + _type.size) > 32) - { - slot++; - offset = 0; - } - } - - if (!_type.array) - return values[0]; - - return QVariant::fromValue(values); -} - -void ClientModel::emptyRecord() -{ - debugDataReady(new QDebugData()); -} - -void ClientModel::debugRecord(unsigned _index) -{ - ExecutionResult e = m_client->execution(_index); - showDebuggerForTransaction(e); -} - -Address ClientModel::deployContract(bytes const& _code, TransactionSettings const& _ctrTransaction) -{ - eth::TransactionSkeleton ts; - ts.creation = true; - ts.value = _ctrTransaction.value; - ts.data = _code; - ts.gas = _ctrTransaction.gas; - ts.gasPrice = _ctrTransaction.gasPrice; - ts.from = toAddress(_ctrTransaction.sender); - return m_client->submitTransaction(ts, _ctrTransaction.sender, _ctrTransaction.gasAuto).second; -} - -void ClientModel::callAddress(Address const& _contract, bytes const& _data, TransactionSettings const& _tr) -{ - eth::TransactionSkeleton ts; - ts.creation = false; - ts.value = _tr.value; - ts.to = _contract; - ts.data = _data; - ts.gas = _tr.gas; - ts.gasPrice = _tr.gasPrice; - ts.from = toAddress(_tr.sender); - m_client->submitTransaction(ts, _tr.sender, _tr.gasAuto); -} - -RecordLogEntry* ClientModel::lastBlock() const -{ - eth::BlockInfo blockInfo = m_client->blockInfo(); - stringstream strGas; - strGas << blockInfo.gasUsed(); - stringstream strNumber; - strNumber << blockInfo.number(); - RecordLogEntry* record = new RecordLogEntry(0, QString::fromStdString(strNumber.str()), tr(" - Block - "), tr("Hash: ") + QString(QString::fromStdString(dev::toHex(blockInfo.hash().ref()))), QString(), QString(), QString(), false, RecordLogEntry::RecordType::Block, QString::fromStdString(strGas.str()), QString(), tr("Block"), QVariantMap(), QVariantMap(), QVariantList()); - QQmlEngine::setObjectOwnership(record, QQmlEngine::JavaScriptOwnership); - return record; -} - -void ClientModel::onStateReset() -{ - m_contractAddresses.clear(); - m_contractNames.clear(); - m_stdContractAddresses.clear(); - m_stdContractNames.clear(); - m_queueTransactions.clear(); - emit stateCleared(); -} - -void ClientModel::onNewTransaction() -{ - ExecutionResult const& tr = m_client->lastExecution(); - - switch (tr.excepted) - { - case TransactionException::None: - break; - case TransactionException::NotEnoughCash: - emit runFailed("Insufficient balance"); - break; - case TransactionException::OutOfGasIntrinsic: - case TransactionException::OutOfGasBase: - case TransactionException::OutOfGas: - emit runFailed("Not enough gas"); - break; - case TransactionException::BlockGasLimitReached: - emit runFailed("Block gas limit reached"); - break; - case TransactionException::BadJumpDestination: - emit runFailed("Solidity exception (bad jump)"); - break; - case TransactionException::OutOfStack: - emit runFailed("Out of stack"); - break; - case TransactionException::StackUnderflow: - emit runFailed("Stack underflow"); - //these should not happen in mix - case TransactionException::Unknown: - case TransactionException::BadInstruction: - case TransactionException::InvalidSignature: - case TransactionException::InvalidNonce: - case TransactionException::InvalidFormat: - case TransactionException::BadRLP: - emit runFailed("Internal execution error"); - break; - } - - - unsigned block = m_client->number() + 1; - unsigned recordIndex = tr.executonIndex; - QString transactionIndex = tr.isCall() ? QObject::tr("Call") : QString("%1:%2").arg(block).arg(tr.transactionIndex); - QString address = QString::fromStdString(toJS(tr.address)); - QString value = QString::fromStdString(toString(tr.value)); - QString contract = address; - QString function; - QString returned; - QString gasUsed; - - bool creation = (bool)tr.contractAddress; - - if (!tr.isCall()) - gasUsed = QString::fromStdString(toString(tr.gasUsed)); - - //TODO: handle value transfer - FixedHash<4> functionHash; - bool abi = false; - if (creation) - { - //contract creation - function = QObject::tr("Constructor"); - address = QObject::tr("(Create contract)"); - } - else - { - //transaction/call - if (tr.inputParameters.size() >= 4) - { - functionHash = FixedHash<4>(tr.inputParameters.data(), FixedHash<4>::ConstructFromPointer); - function = QString::fromStdString(toJS(functionHash)); - abi = true; - } - else - function = QObject::tr(""); - } - - if (creation) - returned = QString::fromStdString(toJS(tr.contractAddress)); - - Address contractAddress = (bool)tr.address ? tr.address : tr.contractAddress; - auto contractAddressIter = m_contractNames.find(contractAddress); - QVariantMap inputParameters; - QVariantMap returnParameters; - QVariantList logs; - if (contractAddressIter != m_contractNames.end()) - { - ContractCallDataEncoder encoder; - CompiledContract const& compilerRes = m_codeModel->contract(contractAddressIter->second); - const QContractDefinition* def = compilerRes.contract(); - contract = def->name(); - if (creation) - function = contract; - if (abi) - { - QFunctionDefinition const* funcDef = def->getFunction(functionHash); - if (funcDef) - { - function = funcDef->name(); - QStringList returnValues = encoder.decode(funcDef->returnParameters(), tr.result.output); - returned += "("; - returned += returnValues.join(", "); - returned += ")"; - - QStringList returnParams = encoder.decode(funcDef->returnParameters(), tr.result.output); - for (int k = 0; k < returnParams.length(); ++k) - returnParameters.insert(funcDef->returnParameters().at(k)->name(), returnParams.at(k)); - - bytes data = tr.inputParameters; - data.erase(data.begin(), data.begin() + 4); - QStringList parameters = encoder.decode(funcDef->parametersList(), data); - for (int k = 0; k < parameters.length(); ++k) - inputParameters.insert(funcDef->parametersList().at(k)->name(), parameters.at(k)); - } - } - - // Fill generated logs and decode parameters - for (auto const& log: tr.logs) - { - QVariantMap l; - l.insert("address", QString::fromStdString(log.address.hex())); - std::ostringstream s; - s << log.data; - l.insert("data", QString::fromStdString(s.str())); - std::ostringstream streamTopic; - streamTopic << log.topics; - l.insert("topic", QString::fromStdString(streamTopic.str())); - auto const& sign = log.topics.front(); // first hash supposed to be the event signature. To check - auto dataIterator = log.data.begin(); - int topicDataIndex = 1; - for (auto const& event: def->eventsList()) - { - if (sign == event->fullHash()) - { - QVariantList paramsList; - l.insert("name", event->name()); - for (auto const& e: event->parametersList()) - { - bytes data; - QString param; - if (!e->isIndexed()) - { - data = bytes(dataIterator, dataIterator + 32); - dataIterator = dataIterator + 32; - } - else - { - data = log.topics.at(topicDataIndex).asBytes(); - topicDataIndex++; - } - param = encoder.decode(e, data); - QVariantMap p; - p.insert("indexed", e->isIndexed()); - p.insert("value", param); - p.insert("name", e->name()); - paramsList.push_back(p); - } - l.insert("param", paramsList); - break; - } - } - logs.push_back(l); - } - } - - QString sender; - for (auto const& secret: m_accountsSecret) - { - if (secret.address() == tr.sender) - { - sender = QString::fromStdString(dev::toHex(secret.secret().ref())); - break; - } - } - QString label; - if (function != QObject::tr("")) - label = contract + "." + function + "()"; - else - label = contract; - - if (!creation) - for (auto const& ctr: m_contractAddresses) - { - if (ctr.second == tr.address) - { - contract = "<" + ctr.first.first + " - " + QString::number(ctr.first.second) + ">"; - break; - } - } - - RecordLogEntry* log = new RecordLogEntry(recordIndex, transactionIndex, contract, function, value, address, returned, tr.isCall(), RecordLogEntry::RecordType::Transaction, - gasUsed, sender, label, inputParameters, returnParameters, logs); - QQmlEngine::setObjectOwnership(log, QQmlEngine::JavaScriptOwnership); - emit newRecord(log); - - // retrieving all accounts balance - QVariantMap state; - QVariantMap accountBalances; - for (auto const& ctr : m_contractAddresses) - { - u256 wei = m_client->balanceAt(ctr.second, PendingBlock); - accountBalances.insert("0x" + QString::fromStdString(ctr.second.hex()), QEther(wei, QEther::Wei).format()); - } - for (auto const& account : m_accounts) - { - u256 wei = m_client->balanceAt(account.first, PendingBlock); - accountBalances.insert("0x" + QString::fromStdString(account.first.hex()), QEther(wei, QEther::Wei).format()); - } - state.insert("accounts", accountBalances); - emit newState(recordIndex, state); -} - -} -} diff --git a/mix/ClientModel.h b/mix/ClientModel.h deleted file mode 100644 index cff767dad..000000000 --- a/mix/ClientModel.h +++ /dev/null @@ -1,298 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file ClientModel.h - * @author Yann yann@ethdev.com - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include "MachineStates.h" -#include "QEther.h" - -namespace dev -{ - -namespace eth { class FixedAccountHolder; } - -namespace mix -{ - -class Web3Server; -class RpcConnector; -class QEther; -class QDebugData; -class MixClient; -class QVariableDefinition; -class CodeModel; -struct SolidityType; - -/// Backend transaction config class -struct TransactionSettings -{ - TransactionSettings() {} - TransactionSettings(QString const& _contractId, QString const& _functionId, u256 _value, u256 _gas, bool _gasAuto, u256 _gasPrice, Secret const& _sender, bool _isContractCreation, bool _isFunctionCall): - contractId(_contractId), functionId(_functionId), value(_value), gas(_gas), gasAuto(_gasAuto), gasPrice(_gasPrice), sender(_sender), isContractCreation(_isContractCreation), isFunctionCall(_isFunctionCall) {} - TransactionSettings(QString const& _stdContractName, QString const& _stdContractUrl): - contractId(_stdContractName), gasAuto(true), stdContractUrl(_stdContractUrl), isContractCreation(true), isFunctionCall(true) {} - - /// Contract name - QString contractId; - /// Contract function name - QString functionId; - /// Transaction value - u256 value; - /// Gas - u256 gas; - /// Calculate gas automatically - bool gasAuto = true; - /// Gas price - u256 gasPrice; - /// Mapping from contract function parameter name to value - QVariantMap parameterValues; - /// Standard contract url - QString stdContractUrl; - /// Sender - Secret sender; - /// Tr deploys a contract - bool isContractCreation; - /// Tr call a ctr function - bool isFunctionCall; -}; - - -/// UI Transaction log record -class RecordLogEntry: public QObject -{ - Q_OBJECT - Q_ENUMS(RecordType) - /// Recording index - Q_PROPERTY(unsigned recordIndex MEMBER m_recordIndex CONSTANT) - /// Human readable transaction bloack and transaction index - Q_PROPERTY(QString transactionIndex MEMBER m_transactionIndex CONSTANT) - /// Contract name if any - Q_PROPERTY(QString contract MEMBER m_contract CONSTANT) - /// Function name if any - Q_PROPERTY(QString function MEMBER m_function CONSTANT) - /// Transaction value - Q_PROPERTY(QString value MEMBER m_value CONSTANT) - /// Receiving address - Q_PROPERTY(QString address MEMBER m_address CONSTANT) - /// Returned value or transaction address in case of creation - Q_PROPERTY(QString returned MEMBER m_returned CONSTANT) - /// true if call, false if transaction - Q_PROPERTY(bool call MEMBER m_call CONSTANT) - /// @returns record type - Q_PROPERTY(RecordType type MEMBER m_type CONSTANT) - /// Gas used - Q_PROPERTY(QString gasUsed MEMBER m_gasUsed CONSTANT) - /// Sender - Q_PROPERTY(QString sender MEMBER m_sender CONSTANT) - /// label - Q_PROPERTY(QString label MEMBER m_label CONSTANT) - /// input parameters - Q_PROPERTY(QVariantMap parameters MEMBER m_inputParameters CONSTANT) - /// return parameters - Q_PROPERTY(QVariantMap returnParameters MEMBER m_returnParameters CONSTANT) - /// logs - Q_PROPERTY(QVariantList logs MEMBER m_logs CONSTANT) - -public: - enum RecordType - { - Transaction, - Block - }; - - RecordLogEntry(): - m_recordIndex(0), m_call(false), m_type(RecordType::Transaction) {} - RecordLogEntry(unsigned _recordIndex, QString _transactionIndex, QString _contract, QString _function, QString _value, QString _address, QString _returned, bool _call, RecordType _type, QString _gasUsed, - QString _sender, QString _label, QVariantMap _inputParameters, QVariantMap _returnParameters, QVariantList _logs): - m_recordIndex(_recordIndex), m_transactionIndex(_transactionIndex), m_contract(_contract), m_function(_function), m_value(_value), m_address(_address), m_returned(_returned), m_call(_call), m_type(_type), m_gasUsed(_gasUsed), - m_sender(_sender), m_label(_label), m_inputParameters(_inputParameters), m_returnParameters(_returnParameters), m_logs(_logs) {} - -private: - unsigned m_recordIndex; - QString m_transactionIndex; - QString m_contract; - QString m_function; - QString m_value; - QString m_address; - QString m_returned; - bool m_call; - RecordType m_type; - QString m_gasUsed; - QString m_sender; - QString m_label; - QVariantMap m_inputParameters; - QVariantMap m_returnParameters; - QVariantList m_logs; -}; - -/** - * @brief Ethereum state control - */ -class ClientModel: public QObject -{ - Q_OBJECT - -public: - ClientModel(); - ~ClientModel(); - /// @returns true if currently executing contract code - Q_PROPERTY(bool running MEMBER m_running NOTIFY runStateChanged) - /// @returns true if currently mining - Q_PROPERTY(bool mining MEMBER m_mining NOTIFY miningStateChanged) - /// @returns deployed contracts addresses - Q_PROPERTY(QVariantMap contractAddresses READ contractAddresses NOTIFY contractAddressesChanged) - /// @returns deployed contracts gas costs - Q_PROPERTY(QVariantList gasCosts READ gasCosts NOTIFY gasCostsChanged) - /// @returns the last block - Q_PROPERTY(RecordLogEntry* lastBlock READ lastBlock CONSTANT) - /// ethereum.js RPC request entry point - /// @param _message RPC request in Json format - /// @returns RPC response in Json format - Q_INVOKABLE QString apiCall(QString const& _message); - /// Simulate mining. Creates a new block - Q_INVOKABLE void mine(); - /// Get/set code model. Should be set from qml - Q_PROPERTY(CodeModel* codeModel MEMBER m_codeModel) - /// Encode parameters - Q_INVOKABLE QStringList encodeParams(QVariant const& _param, QString const& _contract, QString const& _function); - /// Encode parameter - Q_INVOKABLE QString encodeStringParam(QString const& _param); - /// To Hex number - Q_INVOKABLE QString toHex(QString const& _int); - /// Add new account to the model - Q_INVOKABLE void addAccount(QString const& _secret); - /// Return the address associated with the current secret - Q_INVOKABLE QString resolveAddress(QString const& _secret); - /// Compute required gas for a list of transactions @arg _tr - QBigInt computeRequiredGas(QVariantList _tr); - /// init eth client - Q_INVOKABLE void init(QString _dbpath); - -public slots: - /// Setup scenario, run transaction sequence, show debugger for the last transaction - /// @param _state JS object with state configuration - void setupScenario(QVariantMap _scenario); - /// Execute the given @param _tr on the current state - void executeTr(QVariantMap _tr); - /// Show the debugger for a specified record - Q_INVOKABLE void debugRecord(unsigned _index); - /// Show the debugger for an empty record - Q_INVOKABLE void emptyRecord(); - /// Generate new secret - Q_INVOKABLE QString newSecret(); - /// retrieve the address of @arg _secret - Q_INVOKABLE QString address(QString const& _secret); - /// Encode a string to ABI parameter. Returns a hex string - Q_INVOKABLE QString encodeAbiString(QString _string); - -private slots: - /// Update UI with machine states result. Display a modal dialog. - void showDebugger(); - -signals: - /// Transaction execution started - void runStarted(); - /// Transaction execution completed successfully - void runComplete(); - /// Mining has started - void miningStarted(); - /// Mined a new block - void miningComplete(); - /// Mining stopped or started - void miningStateChanged(); - /// Transaction execution completed with error - /// @param _message Error message - void runFailed(QString const& _message); - /// Contract address changed - void contractAddressesChanged(); - /// Gas costs updated - void gasCostsChanged(); - /// Execution state changed - void newBlock(); - /// Execution state changed - void runStateChanged(); - /// Show debugger window request - void debugDataReady(QObject* _debugData); - /// ethereum.js RPC response ready - /// @param _message RPC response in Json format - void apiResponse(QString const& _message); - /// New transaction log entry - void newRecord(RecordLogEntry* _r); - /// State (transaction log) cleared - void stateCleared(); - /// new state has been processed - void newState(unsigned _record, QVariantMap _accounts); - -private: - RecordLogEntry* lastBlock() const; - QVariantMap contractAddresses() const; - QVariantList gasCosts() const; - void executeSequence(std::vector const& _sequence); - Address deployContract(bytes const& _code, TransactionSettings const& _tr = TransactionSettings()); - void callAddress(Address const& _contract, bytes const& _data, TransactionSettings const& _tr); - void onNewTransaction(); - void onStateReset(); - void showDebuggerForTransaction(ExecutionResult const& _t); - QVariant formatValue(SolidityType const& _type, dev::u256 const& _value); - QString resolveToken(std::pair const& _value); - std::pair retrieveToken(QString const& _value); - std::pair resolvePair(QString const& _contractId); - QVariant formatStorageValue(SolidityType const& _type, std::unordered_map const& _storage, unsigned _offset, dev::u256 const& _slot); - void processNextTransactions(); - void finalizeBlock(); - void stopExecution(); - void setupExecutionChain(); - TransactionSettings transaction(QVariant const& _tr) const; - - std::atomic m_running; - std::atomic m_mining; - QFuture m_runFuture; - std::unique_ptr m_client; - std::unique_ptr m_rpcConnector; - std::unique_ptr m_web3Server; - std::shared_ptr m_ethAccounts; - std::unordered_map m_accounts; - std::vector m_accountsSecret; - QList m_gasCosts; - std::map, Address> m_contractAddresses; - std::map m_contractNames; - std::map m_stdContractAddresses; - std::map m_stdContractNames; - CodeModel* m_codeModel = nullptr; - QList m_queueTransactions; - mutable boost::shared_mutex x_queueTransactions; - QString m_dbpath; -}; - -} -} - -Q_DECLARE_METATYPE(dev::mix::RecordLogEntry*) diff --git a/mix/Clipboard.cpp b/mix/Clipboard.cpp deleted file mode 100644 index b364a6b31..000000000 --- a/mix/Clipboard.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - This file is part of cpp-ethereum. - cpp-ethereum 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. - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Clipboard.cpp - * @author Yann yann@ethdev.com - * @date 2015 - */ - -#include "Clipboard.h" -#include -#include - -using namespace dev::mix; - -Clipboard::Clipboard() -{ - connect(QApplication::clipboard(), &QClipboard::dataChanged, [this] { emit clipboardChanged();}); -} - -QString Clipboard::text() const -{ - QClipboard *clipboard = QApplication::clipboard(); - return clipboard->text(); -} - -void Clipboard::setText(QString _text) -{ - QClipboard *clipboard = QApplication::clipboard(); - clipboard->setText(_text); -} diff --git a/mix/Clipboard.h b/mix/Clipboard.h deleted file mode 100644 index 317698e41..000000000 --- a/mix/Clipboard.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Clipboard.h - * @author Yann yann@ethdev.com - * @date 2015 - */ - -#pragma once - -#include - -namespace dev -{ -namespace mix -{ - -/** - * @brief Provides access to system clipboard - */ - -class Clipboard: public QObject -{ - Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText NOTIFY clipboardChanged) - -public: - Clipboard(); - /// Copy text to clipboard - void setText(QString _text); - /// Get text from clipboard - QString text() const; - -signals: - void clipboardChanged(); -}; - -} -} diff --git a/mix/CodeHighlighter.cpp b/mix/CodeHighlighter.cpp deleted file mode 100644 index a3908a1b5..000000000 --- a/mix/CodeHighlighter.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file CodeHighlighter.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "CodeHighlighter.h" - -using namespace dev::mix; - -CodeHighlighterSettings::CodeHighlighterSettings() -{ - backgroundColor = QColor(0x00, 0x2b, 0x36); - foregroundColor = QColor(0xee, 0xe8, 0xd5); - formats[Keyword].setForeground(QColor(0x93, 0xa1, 0xa1)); - formats[Comment].setForeground(QColor(0x85, 0x99, 0x00)); - formats[StringLiteral].setForeground(QColor(0xdc, 0x32, 0x2f)); - formats[NumLiteral].setForeground(foregroundColor); - formats[Import].setForeground(QColor(0x6c, 0x71, 0xc4)); - formats[CompilationError].setUnderlineColor(Qt::red); - formats[CompilationError].setUnderlineStyle(QTextCharFormat::SingleUnderline); -} - -namespace -{ - using namespace dev::solidity; - class HighlightVisitor: public ASTConstVisitor - { - public: - HighlightVisitor(CodeHighlighter::Formats* _formats) { m_formats = _formats; } - private: - CodeHighlighter::Formats* m_formats; - - virtual bool visit(ImportDirective const& _node) - { - m_formats->push_back(CodeHighlighter::FormatRange(CodeHighlighterSettings::Import, _node.getLocation())); - return true; - } - }; -} - -CodeHighlighter::FormatRange::FormatRange(CodeHighlighterSettings::Token _t, dev::SourceLocation const& _location): - token(_t), start(_location.start), length(_location.end - _location.start) -{} - -void CodeHighlighter::processSource(std::string const& _source) -{ - processComments(_source); - solidity::CharStream stream(_source); - solidity::Scanner scanner(stream); - solidity::Token::Value token = scanner.getCurrentToken(); - while (token != Token::EOS) - { - if ((token >= Token::Break && token < Token::TypesEnd) || - token == Token::In || token == Token::Delete || token == Token::NullLiteral || token == Token::TrueLiteral || token == Token::FalseLiteral) - m_formats.push_back(FormatRange(CodeHighlighterSettings::Keyword, scanner.getCurrentLocation())); - else if (token == Token::StringLiteral) - m_formats.push_back(FormatRange(CodeHighlighterSettings::StringLiteral, scanner.getCurrentLocation())); - else if (token == Token::CommentLiteral) - m_formats.push_back(FormatRange(CodeHighlighterSettings::Comment, scanner.getCurrentLocation())); - else if (token == Token::Number) - m_formats.push_back(FormatRange(CodeHighlighterSettings::NumLiteral, scanner.getCurrentLocation())); - - token = scanner.next(); - } - std::sort(m_formats.begin(), m_formats.end()); -} - -void CodeHighlighter::processAST(dev::solidity::ASTNode const& _ast) -{ - HighlightVisitor visitor(&m_formats); - _ast.accept(visitor); - - std::sort(m_formats.begin(), m_formats.end()); -} - -void CodeHighlighter::processError(dev::Exception const& _exception) -{ - SourceLocation const* location = boost::get_error_info(_exception); - if (location) - m_formats.push_back(FormatRange(CodeHighlighterSettings::CompilationError, *location)); -} - -void CodeHighlighter::processComments(std::string const& _source) -{ - unsigned i = 0; - size_t size = _source.size(); - if (size == 0) - return; - while (i < size - 1) - { - if (_source[i] == '/' && _source[i + 1] == '/') - { - //add single line comment - int start = i; - i += 2; - while (i < size && _source[i] != '\n') - ++i; - m_formats.push_back(FormatRange(CodeHighlighterSettings::Comment, start, i - start)); - } - else if (_source[i] == '/' && _source[i + 1] == '*') - { - //add multiline comment - int start = i; - i += 2; - while ((_source[i] != '/' || _source[i - 1] != '*') && i < size) - ++i; - m_formats.push_back(FormatRange(CodeHighlighterSettings::Comment, start, i - start + 1)); - } - ++i; - } -} - -void CodeHighlighter::updateFormatting(QTextDocument* _document, CodeHighlighterSettings const& _settings) -{ - QTextBlock block = _document->firstBlock(); - QList ranges; - - Formats::const_iterator format = m_formats.begin(); - while (true) - { - while ((format == m_formats.end() || (block.position() + block.length() <= format->start)) && block.isValid()) - { - auto layout = block.layout(); - layout->clearAdditionalFormats(); - layout->setAdditionalFormats(ranges); - _document->markContentsDirty(block.position(), block.length()); - block = block.next(); - ranges.clear(); - } - if (!block.isValid()) - break; - - int intersectionStart = std::max(format->start, block.position()); - int intersectionLength = std::min(format->start + format->length, block.position() + block.length()) - intersectionStart; - if (intersectionLength > 0) - { - QTextLayout::FormatRange range; - range.format = _settings.formats[format->token]; - range.start = format->start - block.position(); - range.length = format->length; - ranges.append(range); - } - ++format; - } -} diff --git a/mix/CodeHighlighter.h b/mix/CodeHighlighter.h deleted file mode 100644 index 7fce7ed95..000000000 --- a/mix/CodeHighlighter.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file CodeHighlighter.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include - -class QTextDocument; - -namespace dev -{ - -struct Exception; -struct SourceLocation; -namespace solidity -{ - class ASTNode; -} - -namespace mix -{ - -/// Code highligting settings -class CodeHighlighterSettings -{ -public: - enum Token - { - Import, - Keyword, - Comment, - StringLiteral, - NumLiteral, - CompilationError, - Size, //this must be kept last - }; - - CodeHighlighterSettings(); - ///Format for each token - QTextCharFormat formats[Size]; - ///Background color - QColor backgroundColor; - ///Foreground color - QColor foregroundColor; -}; - -/// Code highlighting engine class -class CodeHighlighter -{ -public: - /// Formatting range - struct FormatRange - { - FormatRange(CodeHighlighterSettings::Token _t, int _start, int _length): token(_t), start(_start), length(_length) {} - FormatRange(CodeHighlighterSettings::Token _t, SourceLocation const& _location); - bool operator<(FormatRange const& _other) const { return start < _other.start || (start == _other.start && length < _other.length); } - - CodeHighlighterSettings::Token token; - int start; - int length; - }; - using Formats = std::vector; // Sorted by start position - -public: - /// Collect highligting information by lexing the source - void processSource(std::string const& _source); - /// Collect additional highligting information from AST - void processAST(solidity::ASTNode const& _ast); - /// Collect highlighting information from compilation exception - void processError(dev::Exception const& _exception); - - /// Apply formatting for a text document - /// @todo Remove this once editor is reworked - void updateFormatting(QTextDocument* _document, CodeHighlighterSettings const& _settings); - -private: - /// Collect highligting information by paring for comments - /// @todo Support this in solidity? - void processComments(std::string const& _source); - -private: - Formats m_formats; -}; - -} - -} diff --git a/mix/CodeModel.cpp b/mix/CodeModel.cpp deleted file mode 100644 index 213c1c1ee..000000000 --- a/mix/CodeModel.cpp +++ /dev/null @@ -1,698 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file CodeModel.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "QContractDefinition.h" -#include "QFunctionDefinition.h" -#include "QVariableDeclaration.h" -#include "CodeHighlighter.h" -#include "FileIo.h" -#include "CodeModel.h" - -using namespace dev::mix; - -const std::set c_predefinedContracts = -{ "Config", "Coin", "CoinReg", "coin", "service", "owned", "mortal", "NameReg", "named", "std", "configUser" }; - - -namespace -{ -using namespace dev::eth; -using namespace dev::solidity; - -class CollectLocalsVisitor: public ASTConstVisitor -{ -public: - CollectLocalsVisitor(QHash* _locals): - m_locals(_locals), m_functionScope(false) {} - -private: - LocationPair nodeLocation(ASTNode const& _node) - { - return LocationPair(_node.getLocation().start, _node.getLocation().end); - } - - virtual bool visit(FunctionDefinition const&) override - { - m_functionScope = true; - return true; - } - - virtual void endVisit(FunctionDefinition const&) override - { - m_functionScope = false; - } - - virtual bool visit(VariableDeclaration const& _node) override - { - SolidityDeclaration decl; - decl.type = CodeModel::nodeType(_node.getType().get()); - decl.name = QString::fromStdString(_node.getName()); - decl.slot = 0; - decl.offset = 0; - if (m_functionScope) - m_locals->insert(nodeLocation(_node), decl); - return true; - } - -private: - QHash* m_locals; - bool m_functionScope; -}; - -class CollectLocationsVisitor: public ASTConstVisitor -{ -public: - CollectLocationsVisitor(SourceMap* _sourceMap): - m_sourceMap(_sourceMap) {} - -private: - LocationPair nodeLocation(ASTNode const& _node) - { - return LocationPair(_node.getLocation().start, _node.getLocation().end); - } - - virtual bool visit(FunctionDefinition const& _node) override - { - m_sourceMap->functions.insert(nodeLocation(_node), QString::fromStdString(_node.getName())); - return true; - } - - virtual bool visit(ContractDefinition const& _node) override - { - m_sourceMap->contracts.insert(nodeLocation(_node), QString::fromStdString(_node.getName())); - return true; - } - -private: - SourceMap* m_sourceMap; -}; - -QHash collectStorage(dev::solidity::ContractDefinition const& _contract) -{ - QHash result; - dev::solidity::ContractType contractType(_contract); - - for (auto v : contractType.getStateVariables()) - { - dev::solidity::VariableDeclaration const* declaration = std::get<0>(v); - dev::u256 slot = std::get<1>(v); - unsigned offset = std::get<2>(v); - result[static_cast(slot)].push_back(SolidityDeclaration { QString::fromStdString(declaration->getName()), CodeModel::nodeType(declaration->getType().get()), slot, offset }); - } - return result; -} - -} //namespace - -void BackgroundWorker::queueCodeChange(int _jobId) -{ - m_model->runCompilationJob(_jobId); -} - -CompiledContract::CompiledContract(const dev::solidity::CompilerStack& _compiler, QString const& _contractName, QString const& _source): - QObject(nullptr), - m_sourceHash(qHash(_source)) -{ - std::string name = _contractName.toStdString(); - ContractDefinition const& contractDefinition = _compiler.getContractDefinition(name); - m_contract.reset(new QContractDefinition(nullptr, &contractDefinition)); - QQmlEngine::setObjectOwnership(m_contract.get(), QQmlEngine::CppOwnership); - m_contract->moveToThread(QApplication::instance()->thread()); - m_bytes = _compiler.getBytecode(_contractName.toStdString()); - - dev::solidity::InterfaceHandler interfaceHandler; - m_contractInterface = QString::fromStdString(interfaceHandler.getABIInterface(contractDefinition)); - if (m_contractInterface.isEmpty()) - m_contractInterface = "[]"; - if (contractDefinition.getLocation().sourceName.get()) - m_documentId = QString::fromStdString(*contractDefinition.getLocation().sourceName); - - CollectLocalsVisitor visitor(&m_locals); - m_storage = collectStorage(contractDefinition); - contractDefinition.accept(visitor); - m_assemblyItems = *_compiler.getRuntimeAssemblyItems(name); - m_constructorAssemblyItems = *_compiler.getAssemblyItems(name); -} - -QString CompiledContract::codeHex() const -{ - return QString::fromStdString(toJS(m_bytes)); -} - -CodeModel::CodeModel(): - m_compiling(false), - m_codeHighlighterSettings(new CodeHighlighterSettings()), - m_backgroundWorker(this), - m_backgroundJobId(0) -{ - m_backgroundThread.start(); - m_backgroundWorker.moveToThread(&m_backgroundThread); - connect(this, &CodeModel::scheduleCompilationJob, &m_backgroundWorker, &BackgroundWorker::queueCodeChange, Qt::QueuedConnection); - qRegisterMetaType("CompiledContract*"); - qRegisterMetaType("QContractDefinition*"); - qRegisterMetaType("QFunctionDefinition*"); - qRegisterMetaType("QVariableDeclaration*"); - qmlRegisterType("org.ethereum.qml", 1, 0, "QFunctionDefinition"); - qmlRegisterType("org.ethereum.qml", 1, 0, "QVariableDeclaration"); -} - -CodeModel::~CodeModel() -{ - stop(); - disconnect(this); - releaseContracts(); - if (m_gasCostsMaps) - delete m_gasCostsMaps; -} - -void CodeModel::stop() -{ - ///@todo: cancel bg job - m_backgroundThread.exit(); - m_backgroundThread.wait(); -} - -void CodeModel::reset(QVariantMap const& _documents) -{ - ///@todo: cancel bg job - Guard l(x_contractMap); - releaseContracts(); - Guard pl(x_pendingContracts); - m_pendingContracts.clear(); - - for (QVariantMap::const_iterator d = _documents.cbegin(); d != _documents.cend(); ++d) - m_pendingContracts[d.key()] = d.value().toString(); - // launch the background thread - m_compiling = true; - emit stateChanged(); - emit scheduleCompilationJob(++m_backgroundJobId); -} - -void CodeModel::unregisterContractSrc(QString const& _documentId) -{ - { - Guard pl(x_pendingContracts); - m_pendingContracts.erase(_documentId); - } - - // launch the background thread - m_compiling = true; - emit stateChanged(); - emit scheduleCompilationJob(++m_backgroundJobId); -} - -void CodeModel::registerCodeChange(QString const& _documentId, QString const& _code) -{ - { - Guard pl(x_pendingContracts); - m_pendingContracts[_documentId] = _code; - } - - // launch the background thread - m_compiling = true; - emit stateChanged(); - emit scheduleCompilationJob(++m_backgroundJobId); -} - -QVariantMap CodeModel::contracts() const -{ - QVariantMap result; - Guard l(x_contractMap); - for (ContractMap::const_iterator c = m_contractMap.cbegin(); c != m_contractMap.cend(); ++c) - result.insert(c.key(), QVariant::fromValue(c.value())); - return result; -} - -CompiledContract* CodeModel::contractByDocumentId(QString const& _documentId) const -{ - Guard l(x_contractMap); - for (ContractMap::const_iterator c = m_contractMap.cbegin(); c != m_contractMap.cend(); ++c) - if (c.value()->m_documentId == _documentId) - return c.value(); - return nullptr; -} - -CompiledContract const& CodeModel::contract(QString const& _name) const -{ - Guard l(x_contractMap); - CompiledContract* res = m_contractMap.value(_name); - if (res == nullptr) - BOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment("Contract not found: " + _name.toStdString())); - return *res; -} - -CompiledContract const* CodeModel::tryGetContract(QString const& _name) const -{ - Guard l(x_contractMap); - CompiledContract* res = m_contractMap.value(_name); - return res; -} - -void CodeModel::releaseContracts() -{ - for (ContractMap::iterator c = m_contractMap.begin(); c != m_contractMap.end(); ++c) - c.value()->deleteLater(); - m_contractMap.clear(); - m_sourceMaps.clear(); -} - -void CodeModel::runCompilationJob(int _jobId) -{ - if (_jobId != m_backgroundJobId) - return; //obsolete job - solidity::CompilerStack cs(true); - try - { - cs.addSource("configUser", R"(contract configUser{function configAddr()constant returns(address a){ return 0xf025d81196b72fba60a1d4dddad12eeb8360d828;}})"); - std::vector sourceNames; - { - Guard l(x_pendingContracts); - for (auto const& c: m_pendingContracts) - { - cs.addSource(c.first.toStdString(), c.second.toStdString()); - sourceNames.push_back(c.first.toStdString()); - } - } - cs.compile(m_optimizeCode); - gasEstimation(cs); - collectContracts(cs, sourceNames); - } - catch (dev::Exception const& _exception) - { - std::stringstream error; - solidity::SourceReferenceFormatter::printExceptionInformation(error, _exception, "Error", cs); - QString message = QString::fromStdString(error.str()); - QVariantMap firstLocation; - QVariantList secondLocations; - if (SourceLocation const* first = boost::get_error_info(_exception)) - firstLocation = resolveCompilationErrorLocation(cs, *first); - if (SecondarySourceLocation const* second = boost::get_error_info(_exception)) - { - for (auto const& c: second->infos) - secondLocations.push_back(resolveCompilationErrorLocation(cs, c.second)); - } - compilationError(message, firstLocation, secondLocations); - } - m_compiling = false; - emit stateChanged(); -} - -QVariantMap CodeModel::resolveCompilationErrorLocation(CompilerStack const& _compiler, SourceLocation const& _location) -{ - std::tuple pos = _compiler.positionFromSourceLocation(_location); - QVariantMap startError; - startError.insert("line", std::get<0>(pos) > 1 ? (std::get<0>(pos) - 1) : 1); - startError.insert("column", std::get<1>(pos) > 1 ? (std::get<1>(pos) - 1) : 1); - QVariantMap endError; - endError.insert("line", std::get<2>(pos) > 1 ? (std::get<2>(pos) - 1) : 1); - endError.insert("column", std::get<3>(pos) > 1 ? (std::get<3>(pos) - 1) : 1); - QVariantMap error; - error.insert("start", startError); - error.insert("end", endError); - QString sourceName; - if (_location.sourceName) - sourceName = QString::fromStdString(*_location.sourceName); - error.insert("source", sourceName); - if (!sourceName.isEmpty()) - if (CompiledContract* contract = contractByDocumentId(sourceName)) - sourceName = contract->contract()->name(); //substitute the location to match our contract names - error.insert("contractName", sourceName); - return error; -} - -void CodeModel::gasEstimation(solidity::CompilerStack const& _cs) -{ - if (m_gasCostsMaps) - m_gasCostsMaps->deleteLater(); - m_gasCostsMaps = new GasMapWrapper; - for (std::string n: _cs.getContractNames()) - { - ContractDefinition const& contractDefinition = _cs.getContractDefinition(n); - QString sourceName = QString::fromStdString(*contractDefinition.getLocation().sourceName); - - if (!m_gasCostsMaps->contains(sourceName)) - m_gasCostsMaps->insert(sourceName, QVariantList()); - - if (!contractDefinition.isFullyImplemented()) - continue; - dev::solidity::SourceUnit const& sourceUnit = _cs.getAST(*contractDefinition.getLocation().sourceName); - AssemblyItems const* items = _cs.getRuntimeAssemblyItems(n); - std::map gasCosts = GasEstimator::breakToStatementLevel(GasEstimator::structuralEstimation(*items, std::vector({&sourceUnit})), {&sourceUnit}); - - auto gasToString = [](GasMeter::GasConsumption const& _gas) - { - if (_gas.isInfinite) - return QString("0"); - else - return QString::fromStdString(toString(_gas.value)); - }; - - // Structural gas costs (per opcode) - for (auto gasItem = gasCosts.begin(); gasItem != gasCosts.end(); ++gasItem) - { - SourceLocation const& location = gasItem->first->getLocation(); - GasMeter::GasConsumption cost = gasItem->second; - m_gasCostsMaps->push(sourceName, location.start, location.end, gasToString(cost), cost.isInfinite, GasMap::type::Statement); - } - - eth::AssemblyItems const& runtimeAssembly = *_cs.getRuntimeAssemblyItems(n); - QString contractName = QString::fromStdString(contractDefinition.getName()); - // Functional gas costs (per function, but also for accessors) - for (auto it: contractDefinition.getInterfaceFunctions()) - { - if (!it.second->hasDeclaration()) - continue; - SourceLocation loc = it.second->getDeclaration().getLocation(); - GasMeter::GasConsumption cost = GasEstimator::functionalEstimation(runtimeAssembly, it.second->externalSignature()); - m_gasCostsMaps->push(sourceName, loc.start, loc.end, gasToString(cost), cost.isInfinite, GasMap::type::Function, - contractName, QString::fromStdString(it.second->getDeclaration().getName())); - } - if (auto const* fallback = contractDefinition.getFallbackFunction()) - { - SourceLocation loc = fallback->getLocation(); - GasMeter::GasConsumption cost = GasEstimator::functionalEstimation(runtimeAssembly, "INVALID"); - m_gasCostsMaps->push(sourceName, loc.start, loc.end, gasToString(cost), cost.isInfinite, GasMap::type::Function, - contractName, "fallback"); - } - for (auto const& it: contractDefinition.getDefinedFunctions()) - { - if (it->isPartOfExternalInterface() || it->isConstructor()) - continue; - SourceLocation loc = it->getLocation(); - size_t entry = _cs.getFunctionEntryPoint(n, *it); - GasEstimator::GasConsumption cost = GasEstimator::GasConsumption::infinite(); - if (entry > 0) - cost = GasEstimator::functionalEstimation(runtimeAssembly, entry, *it); - m_gasCostsMaps->push(sourceName, loc.start, loc.end, gasToString(cost), cost.isInfinite, GasMap::type::Function, - contractName, QString::fromStdString(it->getName())); - } - if (auto const* constructor = contractDefinition.getConstructor()) - { - SourceLocation loc = constructor->getLocation(); - GasMeter::GasConsumption cost = GasEstimator::functionalEstimation(*_cs.getAssemblyItems(n)); - m_gasCostsMaps->push(sourceName, loc.start, loc.end, gasToString(cost), cost.isInfinite, GasMap::type::Constructor, - contractName, contractName); - } - } -} - -QVariantList CodeModel::gasCostByDocumentId(QString const& _documentId) const -{ - if (m_gasCostsMaps) - return m_gasCostsMaps->gasCostsByDocId(_documentId); - else - return QVariantList(); -} - -QVariantList CodeModel::gasCostBy(QString const& _contractName, QString const& _functionName) const -{ - if (m_gasCostsMaps) - return m_gasCostsMaps->gasCostsBy(_contractName, _functionName); - else - return QVariantList(); -} - -void CodeModel::collectContracts(dev::solidity::CompilerStack const& _cs, std::vector const& _sourceNames) -{ - Guard pl(x_pendingContracts); - Guard l(x_contractMap); - ContractMap result; - SourceMaps sourceMaps; - for (std::string const& sourceName: _sourceNames) - { - dev::solidity::SourceUnit const& source = _cs.getAST(sourceName); - SourceMap sourceMap; - CollectLocationsVisitor collector(&sourceMap); - source.accept(collector); - sourceMaps.insert(QString::fromStdString(sourceName), std::move(sourceMap)); - } - for (std::string n: _cs.getContractNames()) - { - if (c_predefinedContracts.count(n) != 0) - continue; - QString name = QString::fromStdString(n); - ContractDefinition const& contractDefinition = _cs.getContractDefinition(n); - if (!contractDefinition.isFullyImplemented()) - continue; - QString sourceName = QString::fromStdString(*contractDefinition.getLocation().sourceName); - auto sourceIter = m_pendingContracts.find(sourceName); - QString source = sourceIter != m_pendingContracts.end() ? sourceIter->second : QString(); - CompiledContract* contract = new CompiledContract(_cs, name, source); - QQmlEngine::setObjectOwnership(contract, QQmlEngine::CppOwnership); - result[name] = contract; - CompiledContract* prevContract = nullptr; - // find previous contract by name - for (ContractMap::const_iterator c = m_contractMap.cbegin(); c != m_contractMap.cend(); ++c) - if (c.value()->contract()->name() == contract->contract()->name()) - prevContract = c.value(); - - // if not found, try by documentId - if (!prevContract) - { - for (ContractMap::const_iterator c = m_contractMap.cbegin(); c != m_contractMap.cend(); ++c) - if (c.value()->documentId() == contract->documentId()) - { - //make sure there are no other contracts in the same source, otherwise it is not a rename - if (!std::any_of(result.begin(),result.end(), [=](ContractMap::const_iterator::value_type _v) { return _v != contract && _v->documentId() == contract->documentId(); })) - prevContract = c.value(); - } - } - if (prevContract != nullptr && prevContract->contractInterface() != result[name]->contractInterface()) - emit contractInterfaceChanged(name); - if (prevContract == nullptr) - emit newContractCompiled(name); - else if (prevContract->contract()->name() != name) - emit contractRenamed(contract->documentId(), prevContract->contract()->name(), name); - } - releaseContracts(); - m_contractMap.swap(result); - m_sourceMaps.swap(sourceMaps); - emit codeChanged(); - emit compilationComplete(); -} - -bool CodeModel::hasContract() const -{ - Guard l(x_contractMap); - return m_contractMap.size() != 0; -} - -dev::bytes const& CodeModel::getStdContractCode(const QString& _contractName, const QString& _url) -{ - auto cached = m_compiledContracts.find(_contractName); - if (cached != m_compiledContracts.end()) - return cached->second; - - FileIo fileIo; - std::string source = fileIo.readFile(_url).toStdString(); - solidity::CompilerStack cs(false); - cs.setSource(source); - cs.compile(false); - for (std::string const& name: cs.getContractNames()) - { - dev::bytes code = cs.getBytecode(name); - m_compiledContracts.insert(std::make_pair(QString::fromStdString(name), std::move(code))); - } - return m_compiledContracts.at(_contractName); -} - -void CodeModel::retrieveSubType(SolidityType& _wrapperType, dev::solidity::Type const* _type) -{ - if (_type->getCategory() == Type::Category::Array) - { - ArrayType const* arrayType = dynamic_cast(_type); - _wrapperType.baseType = std::make_shared(nodeType(arrayType->getBaseType().get())); - } -} - -SolidityType CodeModel::nodeType(dev::solidity::Type const* _type) -{ - SolidityType r { SolidityType::Type::UnsignedInteger, 32, 1, false, false, QString::fromStdString(_type->toString(true)), std::vector(), std::vector(), nullptr }; - if (!_type) - return r; - switch (_type->getCategory()) - { - case Type::Category::Integer: - { - IntegerType const* it = dynamic_cast(_type); - r.size = it->getNumBits() / 8; - r.type = it->isAddress() ? SolidityType::Type::Address : it->isSigned() ? SolidityType::Type::SignedInteger : SolidityType::Type::UnsignedInteger; - } - break; - case Type::Category::Bool: - r.type = SolidityType::Type::Bool; - break; - case Type::Category::FixedBytes: - { - FixedBytesType const* b = dynamic_cast(_type); - r.type = SolidityType::Type::Bytes; - r.size = static_cast(b->numBytes()); - } - break; - case Type::Category::Contract: - r.type = SolidityType::Type::Address; - break; - case Type::Category::Array: - { - ArrayType const* array = dynamic_cast(_type); - if (array->isString()) - r.type = SolidityType::Type::String; - else if (array->isByteArray()) - r.type = SolidityType::Type::Bytes; - else - { - SolidityType elementType = nodeType(array->getBaseType().get()); - elementType.name = r.name; - r = elementType; - } - r.count = static_cast(array->getLength()); - r.dynamicSize = _type->isDynamicallySized(); - r.array = true; - retrieveSubType(r, _type); - } - break; - case Type::Category::Enum: - { - r.type = SolidityType::Type::Enum; - EnumType const* e = dynamic_cast(_type); - for(auto const& enumValue: e->getEnumDefinition().getMembers()) - r.enumNames.push_back(QString::fromStdString(enumValue->getName())); - } - break; - case Type::Category::Struct: - { - r.type = SolidityType::Type::Struct; - StructType const* s = dynamic_cast(_type); - for(auto const& structMember: s->getMembers()) - { - auto slotAndOffset = s->getStorageOffsetsOfMember(structMember.name); - r.members.push_back(SolidityDeclaration { QString::fromStdString(structMember.name), nodeType(structMember.type.get()), slotAndOffset.first, slotAndOffset.second }); - } - } - break; - case Type::Category::Function: - case Type::Category::IntegerConstant: - case Type::Category::StringLiteral: - case Type::Category::Magic: - case Type::Category::Mapping: - case Type::Category::Modifier: - case Type::Category::Real: - case Type::Category::TypeType: - case Type::Category::Void: - default: - break; - } - return r; -} - -bool CodeModel::isContractOrFunctionLocation(dev::SourceLocation const& _location) -{ - if (!_location.sourceName) - return false; - Guard l(x_contractMap); - auto sourceMapIter = m_sourceMaps.find(QString::fromStdString(*_location.sourceName)); - if (sourceMapIter != m_sourceMaps.cend()) - { - LocationPair location(_location.start, _location.end); - return sourceMapIter.value().contracts.contains(location) || sourceMapIter.value().functions.contains(location); - } - return false; -} - -QString CodeModel::resolveFunctionName(dev::SourceLocation const& _location) -{ - if (!_location.sourceName) - return QString(); - Guard l(x_contractMap); - auto sourceMapIter = m_sourceMaps.find(QString::fromStdString(*_location.sourceName)); - if (sourceMapIter != m_sourceMaps.cend()) - { - LocationPair location(_location.start, _location.end); - auto functionNameIter = sourceMapIter.value().functions.find(location); - if (functionNameIter != sourceMapIter.value().functions.cend()) - return functionNameIter.value(); - } - return QString(); -} - -void CodeModel::setOptimizeCode(bool _value) -{ - m_optimizeCode = _value; - emit scheduleCompilationJob(++m_backgroundJobId); -} - -void GasMapWrapper::push(QString _source, int _start, int _end, QString _value, bool _isInfinite, GasMap::type _type, QString _contractName, QString _functionName) -{ - GasMap* gas = new GasMap(_start, _end, _value, _isInfinite, _type, _contractName, _functionName, this); - m_gasMaps.find(_source).value().push_back(QVariant::fromValue(gas)); -} - -bool GasMapWrapper::contains(QString _key) -{ - return m_gasMaps.contains(_key); -} - -void GasMapWrapper::insert(QString _source, QVariantList _variantList) -{ - m_gasMaps.insert(_source, _variantList); -} - -QVariantList GasMapWrapper::gasCostsByDocId(QString _source) -{ - auto gasIter = m_gasMaps.find(_source); - if (gasIter != m_gasMaps.end()) - return gasIter.value(); - else - return QVariantList(); -} - -QVariantList GasMapWrapper::gasCostsBy(QString _contractName, QString _functionName) -{ - QVariantList gasMap; - for (auto const& map: m_gasMaps) - { - for (auto const& gas: map) - { - if (gas.value()->contractName() == _contractName && (_functionName.isEmpty() || gas.value()->functionName() == _functionName)) - gasMap.push_back(gas); - } - } - return gasMap; -} - diff --git a/mix/CodeModel.h b/mix/CodeModel.h deleted file mode 100644 index 73835d807..000000000 --- a/mix/CodeModel.h +++ /dev/null @@ -1,308 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file CodeModel.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SolidityType.h" -#include "QBigInt.h" - -class QTextDocument; - -namespace dev -{ - -namespace solidity -{ -class CompilerStack; -class Type; -} - -namespace mix -{ - -class CodeModel; -class CodeHighlighter; -class CodeHighlighterSettings; -class QContractDefinition; - -//utility class to perform tasks in background thread -class BackgroundWorker: public QObject -{ - Q_OBJECT - -public: - BackgroundWorker(CodeModel* _model): QObject(), m_model(_model) {} - -public slots: - void queueCodeChange(int _jobId); -private: - CodeModel* m_model; -}; - -using LocationPair = QPair; - -///Compilation result model. Contains all the compiled contract data required by UI -class CompiledContract: public QObject -{ - Q_OBJECT - Q_PROPERTY(QContractDefinition* contract READ contract) - Q_PROPERTY(QString contractInterface READ contractInterface CONSTANT) - Q_PROPERTY(QString codeHex READ codeHex CONSTANT) - Q_PROPERTY(QString documentId READ documentId CONSTANT) - -public: - /// Successful compilation result constructor - CompiledContract(solidity::CompilerStack const& _compiler, QString const& _contractName, QString const& _source); - - /// @returns contract definition for QML property - QContractDefinition* contract() const { return m_contract.get(); } - /// @returns contract definition - std::shared_ptr sharedContract() const { return m_contract; } - /// @returns contract bytecode - dev::bytes const& bytes() const { return m_bytes; } - /// @returns contract bytecode as hex string - QString codeHex() const; - /// @returns contract definition in JSON format - QString contractInterface() const { return m_contractInterface; } - /// @return assebly item locations - eth::AssemblyItems const& assemblyItems() const { return m_assemblyItems; } - eth::AssemblyItems const& constructorAssemblyItems() const { return m_constructorAssemblyItems; } - /// @returns contract source Id - QString documentId() const { return m_documentId; } - - QHash const& locals() const { return m_locals; } - QHash const& storage() const { return m_storage; } - -private: - uint m_sourceHash; - std::shared_ptr m_contract; - QString m_compilerMessage; ///< @todo: use some structure here - dev::bytes m_bytes; - QString m_contractInterface; - QString m_documentId; - eth::AssemblyItems m_assemblyItems; - eth::AssemblyItems m_constructorAssemblyItems; - QHash m_locals; - QHash m_storage; - - friend class CodeModel; -}; - -using ContractMap = QMap; //needs to be sorted - -/// Source map -using LocationMap = QHash; - -struct SourceMap -{ - LocationMap contracts; - LocationMap functions; -}; - -using SourceMaps = QMap; //by source id -using GasCostsMaps = QMap; //gas cost by contract name - -class GasMap: public QObject -{ - Q_OBJECT - Q_ENUMS(type) - Q_PROPERTY(int start MEMBER m_start CONSTANT) - Q_PROPERTY(int end MEMBER m_end CONSTANT) - Q_PROPERTY(QString gas MEMBER m_gas CONSTANT) - Q_PROPERTY(bool isInfinite MEMBER m_isInfinite CONSTANT) - Q_PROPERTY(QString codeBlockType READ codeBlockType CONSTANT) - Q_PROPERTY(QString contractName MEMBER m_contractName CONSTANT) - Q_PROPERTY(QString functionName MEMBER m_functionName CONSTANT) - -public: - - enum type - { - Statement, - Function, - Constructor - }; - - GasMap(int _start, int _end, QString _gas, bool _isInfinite, type _type, QString _contractName, QString _functionName, QObject* _parent): QObject(_parent), - m_start(_start), m_end(_end), m_gas(_gas), m_isInfinite(_isInfinite), m_type(_type), m_contractName(_contractName), m_functionName(_functionName) {} - QString contractName() { return m_contractName; } - QString functionName() { return m_functionName; } - -private: - int m_start; - int m_end; - QString m_gas; - bool m_isInfinite; - type m_type; - QString m_contractName; - QString m_functionName; - - QString codeBlockType() const - { - QMetaEnum units = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("type")); - if (m_type) - { - const char* key = units.valueToKey(m_type); - return QString(key).toLower(); - } - return QString(""); - } -}; - -class GasMapWrapper: public QObject -{ - Q_OBJECT - - Q_PROPERTY(GasCostsMaps gasMaps MEMBER m_gasMaps CONSTANT) - -public: - GasMapWrapper(QObject* _parent = nullptr): QObject(_parent){} - void push(QString _source, int _start, int _end, QString _value, bool _isInfinite, GasMap::type _type, QString _contractName = "", QString _functionName = ""); - bool contains(QString _key); - void insert(QString _source, QVariantList _variantList); - QVariantList gasCostsByDocId(QString _source); - QVariantList gasCostsBy(QString _contractName, QString _functionName = ""); - -private: - GasCostsMaps m_gasMaps; -}; - -/// Code compilation model. Compiles contracts in background an provides compiled contract data -class CodeModel: public QObject -{ - Q_OBJECT - -public: - CodeModel(); - ~CodeModel(); - - Q_PROPERTY(QVariantMap contracts READ contracts NOTIFY codeChanged) - Q_PROPERTY(bool compiling READ isCompiling NOTIFY stateChanged) - Q_PROPERTY(bool hasContract READ hasContract NOTIFY codeChanged) - Q_PROPERTY(bool optimizeCode MEMBER m_optimizeCode WRITE setOptimizeCode) - Q_PROPERTY(int callStipend READ callStipend) - Q_PROPERTY(int txGas READ txGas) - - /// @returns latest compilation results for contracts - QVariantMap contracts() const; - /// @returns compilation status - bool isCompiling() const { return m_compiling; } - /// @returns true there is a contract which has at least one function - bool hasContract() const; - /// Get contract code by url. Contract is compiled on first access and cached - dev::bytes const& getStdContractCode(QString const& _contractName, QString const& _url); - /// Get contract by name - /// Throws if not found - CompiledContract const& contract(QString const& _name) const; - /// Get contract by name - /// @returns nullptr if not found - Q_INVOKABLE CompiledContract const* tryGetContract(QString const& _name) const; - /// Find a contract by document id - /// @returns CompiledContract object or null if not found - Q_INVOKABLE CompiledContract* contractByDocumentId(QString const& _documentId) const; - /// Reset code model - Q_INVOKABLE void reset() { reset(QVariantMap()); } - /// Delete a contract source - Q_INVOKABLE void unregisterContractSrc(QString const& _documentId); - /// Convert solidity type info to mix type - static SolidityType nodeType(dev::solidity::Type const* _type); - /// Retrieve subtype - static void retrieveSubType(SolidityType& _wrapperType, dev::solidity::Type const* _type); - /// Check if given location belongs to contract or function - bool isContractOrFunctionLocation(dev::SourceLocation const& _location); - /// Get funciton name by location - QString resolveFunctionName(dev::SourceLocation const& _location); - /// Gas estimation for compiled sources - void gasEstimation(solidity::CompilerStack const& _cs); - /// Gas cost by doc id - Q_INVOKABLE QVariantList gasCostByDocumentId(QString const& _documentId) const; - /// Gas cost by @arg contractName @arg functionName - Q_INVOKABLE QVariantList gasCostBy(QString const& _contractName, QString const& _functionName) const; - /// Set optimize code - Q_INVOKABLE void setOptimizeCode(bool _value); - /// sha3 - Q_INVOKABLE QString sha3(QString _source) { return QString::fromStdString(dev::sha3(_source.toStdString()).hex()); } - int txGas() { return static_cast(dev::eth::c_txGas); } - int callStipend() { return static_cast(dev::eth::c_callStipend); } - -signals: - /// Emited on compilation state change - void stateChanged(); - /// Emitted on compilation complete - void compilationComplete(); - /// Emitted on compilation error - void compilationError(QString _error, QVariantMap _firstErrorLoc, QVariantList _secondErrorLoc); - /// Internal signal used to transfer compilation job to background thread - void scheduleCompilationJob(int _jobId); - /// Emitted if there are any changes in the code model - void codeChanged(); - /// Emitted if there are any changes in the contract interface - void contractInterfaceChanged(QString _documentId); - /// Emitted if there is a new contract compiled for the first time - void newContractCompiled(QString _documentId); - /// Emitted if a contract name has been changed - void contractRenamed(QString _documentId, QString _oldName, QString _newName); - -public slots: - /// Update code model on source code change - void registerCodeChange(QString const& _documentId, QString const& _code); - /// Reset code model for a new project - void reset(QVariantMap const& _documents); - -private: - void runCompilationJob(int _jobId); - void stop(); - void releaseContracts(); - void collectContracts(dev::solidity::CompilerStack const& _cs, std::vector const& _sourceNames); - QVariantMap resolveCompilationErrorLocation(dev::solidity::CompilerStack const& _cs, dev::SourceLocation const& _location); - - std::atomic m_compiling; - mutable dev::Mutex x_contractMap; - ContractMap m_contractMap; - SourceMaps m_sourceMaps; - GasMapWrapper* m_gasCostsMaps = 0; - std::unique_ptr m_codeHighlighterSettings; - QThread m_backgroundThread; - BackgroundWorker m_backgroundWorker; - int m_backgroundJobId = 0; //protects from starting obsolete compilation job - std::map m_compiledContracts; //by name - dev::Mutex x_pendingContracts; - std::map m_pendingContracts; //name to source - bool m_optimizeCode = false; - friend class BackgroundWorker; -}; - -} - -} diff --git a/mix/ContractCallDataEncoder.cpp b/mix/ContractCallDataEncoder.cpp deleted file mode 100644 index 42cb50607..000000000 --- a/mix/ContractCallDataEncoder.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file ContractCallDataEncoder.cpp - * @author Yann yann@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "QVariableDeclaration.h" -#include "QVariableDefinition.h" -#include "QFunctionDefinition.h" -#include "ContractCallDataEncoder.h" -using namespace std; -using namespace dev; -using namespace dev::solidity; -using namespace dev::mix; - -bytes ContractCallDataEncoder::encodedData() -{ - bytes r(m_encodedData); - size_t headerSize = m_encodedData.size() & ~0x1fUL; //ignore any prefix that is not 32-byte aligned - //apply offsets - for (auto const& p: m_dynamicOffsetMap) - { - vector_ref offsetRef(m_dynamicData.data() + p.first, 32); - toBigEndian(p.second + headerSize, offsetRef); //add header size minus signature hash - } - for (auto const& p: m_staticOffsetMap) - { - vector_ref offsetRef(r.data() + p.first, 32); - toBigEndian(p.second + headerSize, offsetRef); //add header size minus signature hash - } - if (m_dynamicData.size() > 0) - r.insert(r.end(), m_dynamicData.begin(), m_dynamicData.end()); - return r; -} - -void ContractCallDataEncoder::encode(QFunctionDefinition const* _function) -{ - bytes hash = _function->hash().asBytes(); - m_encodedData.insert(m_encodedData.end(), hash.begin(), hash.end()); -} - -void ContractCallDataEncoder::encodeArray(QJsonArray const& _array, SolidityType const& _type, bytes& _content) -{ - size_t offsetStart = _content.size(); - if (_type.dynamicSize) - { - bytes count = bytes(32); - toBigEndian((u256)_array.size(), count); - _content += count; //reserved space for count - } - - int k = 0; - for (QJsonValue const& c: _array) - { - if (c.isArray()) - { - if (_type.baseType->dynamicSize) - m_dynamicOffsetMap.push_back(std::make_pair(m_dynamicData.size() + offsetStart + 32 + k * 32, m_dynamicData.size() + _content.size())); - encodeArray(c.toArray(), *_type.baseType, _content); - } - else - { - // encode single item - if (c.isDouble()) - encodeSingleItem(QString::number(c.toDouble()), _type, _content); - else if (c.isString()) - encodeSingleItem(c.toString(), _type, _content); - } - k++; - } -} - -void ContractCallDataEncoder::encode(QVariant const& _data, SolidityType const& _type) -{ - if (_type.dynamicSize && (_type.type == SolidityType::Type::Bytes || _type.type == SolidityType::Type::String)) - { - bytes empty(32); - size_t sizePos = m_dynamicData.size(); - m_dynamicData += empty; //reserve space for count - encodeSingleItem(_data.toString(), _type, m_dynamicData); - vector_ref sizeRef(m_dynamicData.data() + sizePos, 32); - toBigEndian(static_cast(_data.toString().size()), sizeRef); - m_staticOffsetMap.push_back(std::make_pair(m_encodedData.size(), sizePos)); - m_encodedData += empty; //reserve space for offset - } - else if (_type.array) - { - bytes content; - size_t size = m_encodedData.size(); - if (_type.dynamicSize) - { - m_encodedData += bytes(32); // reserve space for offset - m_staticOffsetMap.push_back(std::make_pair(size, m_dynamicData.size())); - } - QJsonDocument jsonDoc = QJsonDocument::fromJson(_data.toString().toUtf8()); - encodeArray(jsonDoc.array(), _type, content); - - if (!_type.dynamicSize) - m_encodedData.insert(m_encodedData.end(), content.begin(), content.end()); - else - m_dynamicData.insert(m_dynamicData.end(), content.begin(), content.end()); - } - else - encodeSingleItem(_data.toString(), _type, m_encodedData); -} - -unsigned ContractCallDataEncoder::encodeSingleItem(QString const& _data, SolidityType const& _type, bytes& _dest) -{ - if (_type.type == SolidityType::Type::Struct) - BOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment("Struct parameters are not supported yet")); - - unsigned const alignSize = 32; - QString src = _data; - bytes result; - - if ((src.startsWith("\"") && src.endsWith("\"")) || (src.startsWith("\'") && src.endsWith("\'"))) - src = src.remove(src.length() - 1, 1).remove(0, 1); - - if (src.startsWith("0x")) - { - result = fromHex(src.toStdString().substr(2)); - if (_type.type != SolidityType::Type::Bytes) - result = padded(result, alignSize); - } - else - { - try - { - bigint i(src.toStdString()); - result = bytes(alignSize); - toBigEndian((u256)i, result); - } - catch (std::exception const&) - { - // manage input as a string. - result = encodeStringParam(src, alignSize); - } - } - - size_t dataSize = _type.dynamicSize ? result.size() : alignSize; - if (result.size() % alignSize != 0) - result.resize((result.size() & ~(alignSize - 1)) + alignSize); - _dest.insert(_dest.end(), result.begin(), result.end()); - return dataSize; -} - -bigint ContractCallDataEncoder::decodeInt(dev::bytes const& _rawValue) -{ - dev::u256 un = dev::fromBigEndian(_rawValue); - if (un >> 255) - return (-s256(~un + 1)); - return un; -} - -QString ContractCallDataEncoder::toString(dev::bigint const& _int) -{ - std::stringstream str; - str << std::dec << _int; - return QString::fromStdString(str.str()); -} - -dev::bytes ContractCallDataEncoder::encodeBool(QString const& _str) -{ - bytes b(1); - b[0] = _str == "1" || _str.toLower() == "true " ? 1 : 0; - return padded(b, 32); -} - -bool ContractCallDataEncoder::decodeBool(dev::bytes const& _rawValue) -{ - byte ret = _rawValue.at(_rawValue.size() - 1); - return (ret != 0); -} - -QString ContractCallDataEncoder::toString(bool _b) -{ - return _b ? "true" : "false"; -} - -dev::bytes ContractCallDataEncoder::encodeStringParam(QString const& _str, unsigned alignSize) -{ - bytes result; - QByteArray bytesAr = _str.toLocal8Bit(); - result = bytes(bytesAr.begin(), bytesAr.end()); - return paddedRight(result, alignSize); -} - -dev::bytes ContractCallDataEncoder::encodeBytes(QString const& _str) -{ - QByteArray bytesAr = _str.toLocal8Bit(); - bytes r = bytes(bytesAr.begin(), bytesAr.end()); - return padded(r, 32); -} - -dev::bytes ContractCallDataEncoder::decodeBytes(dev::bytes const& _rawValue) -{ - return _rawValue; -} - -QString ContractCallDataEncoder::toString(dev::bytes const& _b) -{ - return QString::fromStdString(dev::toJS(_b)); -} - -QString ContractCallDataEncoder::toChar(dev::bytes const& _b) -{ - QString str; - asString(_b, str); - return str; -} - -QJsonValue ContractCallDataEncoder::decodeArrayContent(SolidityType const& _type, bytes const& _value, int& pos) -{ - if (_type.baseType->array) - { - QJsonArray sub = decodeArray(*_type.baseType, _value, pos); - return sub; - } - else - { - bytesConstRef value(_value.data() + pos, 32); - bytes rawParam(32); - value.populate(&rawParam); - QVariant i = decode(*_type.baseType, rawParam); - pos = pos + 32; - return i.toString(); - } -} - -QJsonArray ContractCallDataEncoder::decodeArray(SolidityType const& _type, bytes const& _value, int& pos) -{ - QJsonArray array; - bytesConstRef value(&_value); - int count = 0; - bigint offset = pos; - int valuePosition = pos; - if (!_type.dynamicSize) - count = _type.count; - else - { - bytesConstRef value(_value.data() + pos, 32); // offset - bytes rawParam(32); - value.populate(&rawParam); - offset = decodeInt(rawParam); - valuePosition = static_cast(offset) + 32; - pos += 32; - value = bytesConstRef(_value.data() + static_cast(offset), 32); // count - value.populate(&rawParam); - count = static_cast(decodeInt(rawParam)); - } - if (_type.type == QSolidityType::Type::Bytes || _type.type == QSolidityType::Type::String) - { - bytesConstRef value(_value.data() + (static_cast(offset) + 32), 32); - bytes rawParam(count); - value.populate(&rawParam); - if (_type.type == QSolidityType::Type::Bytes) - array.append(toString(decodeBytes(rawParam))); - else - array.append(toChar(decodeBytes(rawParam))); - } - else - { - for (int k = 0; k < count; ++k) - { - if (_type.dynamicSize) - array.append(decodeArrayContent(_type, _value, valuePosition)); - else - array.append(decodeArrayContent(_type, _value, pos)); - } - } - return array; -} - -QVariant ContractCallDataEncoder::decode(SolidityType const& _type, bytes const& _value) -{ - bytesConstRef value(&_value); - bytes rawParam(32); - value.populate(&rawParam); - QSolidityType::Type type = _type.type; - if (type == QSolidityType::Type::SignedInteger || type == QSolidityType::Type::UnsignedInteger) - return QVariant::fromValue(toString(decodeInt(rawParam))); - else if (type == QSolidityType::Type::Bool) - return QVariant::fromValue(toString(decodeBool(rawParam))); - else if (type == QSolidityType::Type::Bytes || type == QSolidityType::Type::Hash) - return QVariant::fromValue(toString(decodeBytes(rawParam))); - else if (type == QSolidityType::Type::String) - return QVariant::fromValue(toChar(decodeBytes(rawParam))); - else if (type == QSolidityType::Type::Struct) - return QVariant::fromValue(QString("struct")); //TODO - else if (type == QSolidityType::Type::Address) - return QVariant::fromValue(toString(decodeBytes(unpadLeft(rawParam)))); - else if (type == QSolidityType::Type::Enum) - return QVariant::fromValue(decodeEnum(rawParam)); - else - BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Parameter declaration not found")); -} - -QString ContractCallDataEncoder::decodeEnum(bytes _value) -{ - return toString(decodeInt(_value)); -} - -QString ContractCallDataEncoder::decode(QVariableDeclaration* const& _param, bytes _value) -{ - SolidityType const& type = _param->type()->type(); - return decode(type, _value).toString(); -} - -QStringList ContractCallDataEncoder::decode(QList const& _returnParameters, bytes _value) -{ - bytes _v = _value; - QStringList r; - int readPosition = 0; - for (int k = 0; k <_returnParameters.length(); k++) - { - QVariableDeclaration* dec = static_cast(_returnParameters.at(k)); - SolidityType const& type = dec->type()->type(); - if (type.array) - { - QJsonArray array = decodeArray(type, _v, readPosition); - if (type.type == SolidityType::String && array.count() <= 1) - { - if (array.count() == 1) - r.append(array[0].toString()); - else - r.append(QString()); - } - else - { - QJsonDocument jsonDoc = QJsonDocument::fromVariant(array.toVariantList()); - r.append(jsonDoc.toJson(QJsonDocument::Compact)); - } - } - else - { - bytesConstRef value(_value.data() + readPosition, 32); - bytes rawParam(32); - value.populate(&rawParam); - r.append(decode(type, rawParam).toString()); - readPosition += 32; - } - } - return r; -} - - -bool ContractCallDataEncoder::asString(dev::bytes const& _b, QString& _str) -{ - dev::bytes bunPad = unpadded(_b); - for (unsigned i = 0; i < bunPad.size(); i++) - { - if (bunPad.at(i) < 9 || bunPad.at(i) > 127) - return false; - else - _str += QString::fromStdString(dev::toJS(bunPad.at(i))).replace("0x", ""); - } - return true; -} diff --git a/mix/ContractCallDataEncoder.h b/mix/ContractCallDataEncoder.h deleted file mode 100644 index d62b65187..000000000 --- a/mix/ContractCallDataEncoder.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file ContractCallDataEncoder.h - * @author Yann yann@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#pragma once - -#include "QVariableDeclaration.h" -#include "QVariableDefinition.h" - -namespace dev -{ -namespace mix -{ - -class QFunctionDefinition; -class QVariableDeclaration; -class QVariableDefinition; -class QSolidityType; - -/** - * @brief Encode/Decode data to be sent to a transaction or to be displayed in a view. - */ -class ContractCallDataEncoder -{ -public: - ContractCallDataEncoder() {} - /// Encode hash of the function to call. - void encode(QFunctionDefinition const* _function); - /// Encode data for corresponding type - void encode(QVariant const& _data, SolidityType const& _type); - /// Decode variable in order to be sent to QML view. - QStringList decode(QList const& _dec, bytes _value); - /// Decode @param _parameter - QString decode(QVariableDeclaration* const& _param, bytes _value); - /// Decode single variable - QVariant decode(SolidityType const& _type, bytes const& _value); - /// Get all encoded data encoded by encode function. - bytes encodedData(); - /// Encode a string to bytes (in order to be used as funtion param) - dev::bytes encodeStringParam(QString const& _str, unsigned _alignSize); - /// Encode a string to ABI bytes - dev::bytes encodeBytes(QString const& _str); - /// Decode bytes from ABI - dev::bytes decodeBytes(dev::bytes const& _rawValue); - /// Decode array - QJsonArray decodeArray(SolidityType const& _type, bytes const& _value, int& pos); - /// Decode array items - QJsonValue decodeArrayContent(SolidityType const& _type, bytes const& _value, int& pos); - /// Decode enum - QString decodeEnum(bytes _value); - -private: - unsigned encodeSingleItem(QString const& _data, SolidityType const& _type, bytes& _dest); - bigint decodeInt(dev::bytes const& _rawValue); - dev::bytes encodeInt(QString const& _str); - QString toString(dev::bigint const& _int); - dev::bytes encodeBool(QString const& _str); - bool decodeBool(dev::bytes const& _rawValue); - QString toString(bool _b); - QString toString(dev::bytes const& _b); - bool asString(dev::bytes const& _b, QString& _str); - void encodeArray(QJsonArray const& _array, SolidityType const& _type, bytes& _content); - QString toChar(dev::bytes const& _b); - -private: - bytes m_encodedData; - bytes m_dynamicData; - std::vector> m_dynamicOffsetMap; - std::vector> m_staticOffsetMap; -}; - -} -} diff --git a/mix/DebuggingStateWrapper.cpp b/mix/DebuggingStateWrapper.cpp deleted file mode 100644 index 42c429224..000000000 --- a/mix/DebuggingStateWrapper.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file DebuggingStateWrapper.cpp - * @author Yann yann@ethdev.com - * @date 2014 - * Used to translate c++ type (u256, bytes, ...) into friendly value (to be used by QML). - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "DebuggingStateWrapper.h" -#include "QBigInt.h" -using namespace dev; -using namespace dev::eth; -using namespace dev::mix; - -namespace -{ - static QVariantList memDumpToList(bytes const& _bytes, unsigned _width, bool _includeAddress = false) - { - QVariantList dumpList; - for (unsigned i = 0; i < _bytes.size(); i += _width) - { - std::stringstream ret; - if (_includeAddress) - { - ret << std::setfill('0') << std::setw(6) << std::hex << i << " "; - ret << " "; - } - for (unsigned j = i; j < i + _width; ++j) - if (j < _bytes.size()) - if (_bytes[j] >= 32 && _bytes[j] < 127) - ret << (char)_bytes[j]; - else - ret << '?'; - else - ret << ' '; - QString strPart = QString::fromStdString(ret.str()); - - ret.clear(); - ret.str(std::string()); - - for (unsigned j = i; j < i + _width && j < _bytes.size(); ++j) - ret << std::setfill('0') << std::setw(2) << std::hex << (unsigned)_bytes[j] << " "; - QString hexPart = QString::fromStdString(ret.str()); - - QStringList line = { strPart, hexPart }; - dumpList.push_back(line); - } - return dumpList; - } -} - -QCode* QMachineState::getHumanReadableCode(QObject* _owner, const Address& _address, const bytes& _code, QHash& o_codeMap) -{ - QVariantList codeStr; - for (unsigned i = 0; i <= _code.size(); ++i) - { - byte b = i < _code.size() ? _code[i] : 0; - try - { - QString s = QString::fromStdString(instructionInfo((Instruction)b).name); - std::ostringstream out; - out << std::hex << std::setw(4) << std::setfill('0') << i; - int offset = i; - if (b >= (byte)Instruction::PUSH1 && b <= (byte)Instruction::PUSH32) - { - unsigned bc = getPushNumber((Instruction)b); - s = "PUSH 0x" + QString::fromStdString(toHex(bytesConstRef(&_code[i + 1], bc))); - i += bc; - } - o_codeMap[offset] = codeStr.size(); - codeStr.append(QVariant::fromValue(new QInstruction(_owner, QString::fromStdString(out.str()) + " " + s))); - } - catch (...) - { - qDebug() << QString("Unhandled exception!") << endl << - QString::fromStdString(boost::current_exception_diagnostic_information()); - break; // probably hit data segment - } - } - return new QCode(_owner, QString::fromStdString(toString(_address)), std::move(codeStr)); -} - -QBigInt* QMachineState::gasCost() -{ - return new QBigInt(m_state.gasCost); -} - -QBigInt* QMachineState::gas() -{ - return new QBigInt(m_state.gas); -} - -QBigInt* QMachineState::newMemSize() -{ - return new QBigInt(m_state.newMemSize); -} - -QStringList QMachineState::debugStack() -{ - QStringList stack; - for (std::vector::reverse_iterator i = m_state.stack.rbegin(); i != m_state.stack.rend(); ++i) - stack.append(QString::fromStdString(prettyU256(*i))); - return stack; -} - -QStringList QMachineState::debugStorage() -{ - QStringList storage; - for (auto const& i: m_state.storage) - { - std::stringstream s; - s << "@" << prettyU256(i.first) << "\t" << prettyU256(i.second); - storage.append(QString::fromStdString(s.str())); - } - return storage; -} - -QVariantList QMachineState::debugMemory() -{ - return memDumpToList(m_state.memory, 16, true); -} - -QCallData* QMachineState::getDebugCallData(QObject* _owner, bytes const& _data) -{ - return new QCallData(_owner, memDumpToList(_data, 16)); -} - -QVariantList QMachineState::levels() -{ - QVariantList levelList; - for (unsigned l: m_state.levels) - levelList.push_back(l); - return levelList; -} - -QString QMachineState::instruction() -{ - return QString::fromStdString(dev::eth::instructionInfo(m_state.inst).name); -} - -QString QMachineState::endOfDebug() -{ - if (m_state.gasCost > m_state.gas) - return QObject::tr("OUT-OF-GAS"); - else if (m_state.inst == Instruction::RETURN && m_state.stack.size() >= 2) - { - unsigned from = (unsigned)m_state.stack.back(); - unsigned size = (unsigned)m_state.stack[m_state.stack.size() - 2]; - unsigned o = 0; - bytes out(size, 0); - for (; o < size && from + o < m_state.memory.size(); ++o) - out[o] = m_state.memory[from + o]; - return QObject::tr("RETURN") + " " + QString::fromStdString(dev::memDump(out, 16, false)); - } - else if (m_state.inst == Instruction::STOP) - return QObject::tr("STOP"); - else if (m_state.inst == Instruction::SUICIDE && m_state.stack.size() >= 1) - return QObject::tr("SUICIDE") + " 0x" + QString::fromStdString(toString(right160(m_state.stack.back()))); - else - return QObject::tr("EXCEPTION"); -} diff --git a/mix/DebuggingStateWrapper.h b/mix/DebuggingStateWrapper.h deleted file mode 100644 index c80aecdd8..000000000 --- a/mix/DebuggingStateWrapper.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file DebuggingStateWrapper.h - * @author Yann yann@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#pragma once - -// Make sure boost/asio.hpp is included before windows.h. -#include - -#include -#include -#include -#include -#include -#include "MachineStates.h" -#include "QVariableDefinition.h" -#include "QBigInt.h" - -namespace dev -{ -namespace mix -{ - -/** - * @brief Contains the line nb of the assembly code and the corresponding index in the code bytes array. - */ -class QInstruction: public QObject -{ - Q_OBJECT - Q_PROPERTY(QString line MEMBER m_line CONSTANT) - -public: - QInstruction(QObject* _owner, QString _line): QObject(_owner), m_line(_line) {} - -private: - QString m_line; -}; - -/** - * @brief Solidity state - */ -class QSolState: public QObject -{ - Q_OBJECT - Q_PROPERTY(QVariantMap storage MEMBER m_storage CONSTANT) - Q_PROPERTY(QVariantList callStack MEMBER m_callStack CONSTANT) - Q_PROPERTY(QVariantMap locals MEMBER m_locals CONSTANT) - Q_PROPERTY(int start MEMBER m_start CONSTANT) - Q_PROPERTY(int end MEMBER m_end CONSTANT) - Q_PROPERTY(QString sourceName MEMBER m_sourceName CONSTANT) - -public: - QSolState(QObject* _parent, QVariantMap&& _storage, QVariantList&& _callStack, QVariantMap&& _locals, int _start, int _end, QString _sourceName): - QObject(_parent), m_storage(std::move(_storage)), m_callStack(std::move(_callStack)), m_locals(std::move(_locals)), m_start(_start), m_end(_end), m_sourceName(_sourceName) - { } - -private: - QVariantMap m_storage; - QVariantList m_callStack; - QVariantMap m_locals; - int m_start; - int m_end; - QString m_sourceName; -}; - -/** - * @brief Shared container for lines - */ -class QCode: public QObject -{ - Q_OBJECT - Q_PROPERTY(QVariantList instructions MEMBER m_instructions CONSTANT) - Q_PROPERTY(QString address MEMBER m_address CONSTANT) - Q_PROPERTY(QString documentId MEMBER m_document CONSTANT) - -public: - QCode(QObject* _owner, QString const& _address, QVariantList&& _instrunctions): QObject(_owner), m_instructions(std::move(_instrunctions)), m_address(_address) {} - void setDocument(QString const& _documentId) { m_document = _documentId; } - -private: - QVariantList m_instructions; - QString m_address; - QString m_document; -}; - -/** - * @brief Shared container for call data - */ -class QCallData: public QObject -{ - Q_OBJECT - Q_PROPERTY(QVariantList items MEMBER m_items CONSTANT) - -public: - QCallData(QObject* _owner, QVariantList&& _items): QObject(_owner), m_items(std::move(_items)) {} - -private: - QVariantList m_items; -}; - -/** - * @brief Shared container for machine states - */ -class QDebugData: public QObject -{ - Q_OBJECT - Q_PROPERTY(QVariantList states MEMBER m_states CONSTANT) - -public: - QDebugData() { } - void setStates(QVariantList&& _states) { m_states = std::move(_states); } - -private: - QVariantList m_states; -}; - -/** - * @brief Wrap MachineState in QObject - */ -class QMachineState: public QObject -{ - Q_OBJECT - Q_PROPERTY(int step READ step CONSTANT) - Q_PROPERTY(int curPC READ curPC CONSTANT) - Q_PROPERTY(int instructionIndex MEMBER m_instructionIndex CONSTANT) - Q_PROPERTY(QBigInt* gasCost READ gasCost CONSTANT) - Q_PROPERTY(QBigInt* gas READ gas CONSTANT) - Q_PROPERTY(QString instruction READ instruction CONSTANT) - Q_PROPERTY(QStringList debugStack READ debugStack CONSTANT) - Q_PROPERTY(QStringList debugStorage READ debugStorage CONSTANT) - Q_PROPERTY(QVariantList debugMemory READ debugMemory CONSTANT) - Q_PROPERTY(QObject* code MEMBER m_code CONSTANT) - Q_PROPERTY(QObject* callData MEMBER m_callData CONSTANT) - Q_PROPERTY(QString endOfDebug READ endOfDebug CONSTANT) - Q_PROPERTY(QBigInt* newMemSize READ newMemSize CONSTANT) - Q_PROPERTY(QVariantList levels READ levels CONSTANT) - Q_PROPERTY(unsigned codeIndex READ codeIndex CONSTANT) - Q_PROPERTY(unsigned dataIndex READ dataIndex CONSTANT) - Q_PROPERTY(QObject* solidity MEMBER m_solState CONSTANT) - -public: - QMachineState(QObject* _owner, int _instructionIndex, MachineState const& _state, QCode* _code, QCallData* _callData, QSolState* _solState): - QObject(_owner), m_instructionIndex(_instructionIndex), m_state(_state), m_code(_code), m_callData(_callData), m_solState(_solState) { } - /// Get the step of this machine states. - int step() { return (int)m_state.steps; } - /// Get the proccessed code index. - int curPC() { return (int)m_state.curPC; } - /// Get the code id - unsigned codeIndex() { return m_state.codeIndex; } - /// Get the call data id - unsigned dataIndex() { return m_state.dataIndex; } - /// Get gas cost. - QBigInt* gasCost(); - /// Get gas used. - QBigInt* gas(); - /// Get stack. - QStringList debugStack(); - /// Get storage. - QStringList debugStorage(); - /// Get memory. - QVariantList debugMemory(); - /// Get end of debug information. - QString endOfDebug(); - /// Get the new memory size. - QBigInt* newMemSize(); - /// Get current instruction - QString instruction(); - /// Get all previous steps. - QVariantList levels(); - /// Get the current processed machine state. - MachineState const& state() const { return m_state; } - /// Convert all machine states in human readable code. - static QCode* getHumanReadableCode(QObject* _owner, const Address& _address, const bytes& _code, QHash& o_codeMap); - /// Convert call data into human readable form - static QCallData* getDebugCallData(QObject* _owner, bytes const& _data); - -private: - int m_instructionIndex; - MachineState m_state; - QCode* m_code; - QCallData* m_callData; - QSolState* m_solState; -}; - -} -} diff --git a/mix/Exceptions.cpp b/mix/Exceptions.cpp deleted file mode 100644 index 08f59f7ef..000000000 --- a/mix/Exceptions.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Exceptions.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include -#include -#include "Exceptions.h" - -std::ostream& operator<<(std::ostream& _out, QQmlError const& _error) -{ - _out << _error.toString().toStdString(); - return _out; -} diff --git a/mix/Exceptions.h b/mix/Exceptions.h deleted file mode 100644 index 02e31760f..000000000 --- a/mix/Exceptions.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Exceptions.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include - -class QTextDocument; -class QQmlError; - -namespace dev -{ -namespace mix -{ - -struct QmlLoadException: virtual Exception {}; -struct FileIoException: virtual Exception {}; -struct InvalidBlockException: virtual Exception {}; -struct FunctionNotFoundException: virtual Exception {}; -struct ExecutionStateException: virtual Exception {}; -struct ParameterChangedException: virtual Exception {}; -struct OutOfGasException: virtual Exception {}; - -using QmlErrorInfo = boost::error_info; -using FileError = boost::error_info; -using BlockIndex = boost::error_info; -using FunctionName = boost::error_info; - -} -} - -std::ostream& operator<<(std::ostream& _out, QQmlError const& _error); diff --git a/mix/FileIo.cpp b/mix/FileIo.cpp deleted file mode 100644 index 525715d5a..000000000 --- a/mix/FileIo.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file FileIo.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "FileIo.h" - -using namespace dev; -using namespace dev::crypto; -using namespace dev::mix; - -FileIo::FileIo(): m_watcher(new QFileSystemWatcher(this)) -{ - connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &FileIo::fileChanged); -} - -void FileIo::openFileBrowser(QString const& _dir) -{ - QDesktopServices::openUrl(QUrl(_dir)); -} - -QString FileIo::pathFromUrl(QString const& _url) -{ - QUrl url(_url); - QString path(url.path()); - if (url.scheme() == "qrc") - path = ":" + path; -#ifdef WIN32 - if (url.scheme() == "file") - { - if (path.startsWith("/")) - path = path.right(path.length() - 1); - if (!url.host().isEmpty()) - path = url.host() + ":/" + path; - } -#endif - return path; -} - -void FileIo::makeDir(QString const& _url) -{ - QDir dirPath(pathFromUrl(_url)); - if (dirPath.exists()) - dirPath.removeRecursively(); - dirPath.mkpath(dirPath.path()); -} - -void FileIo::deleteDir(QString const& _url) -{ - QDir dirPath(pathFromUrl(_url)); - if (dirPath.exists()) - dirPath.removeRecursively(); -} - -QString FileIo::readFile(QString const& _url) -{ - QFile file(pathFromUrl(_url)); - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - QTextStream stream(&file); - QString data = stream.readAll(); - return data; - } - else - error(tr("Error reading file %1").arg(_url)); - return QString(); -} - -void FileIo::writeFile(QString const& _url, QString const& _data) -{ - QString path = pathFromUrl(_url); - m_watcher->removePath(path); - QFile file(path); - if (file.open(QIODevice::WriteOnly | QIODevice::Text)) - { - QTextStream stream(&file); - stream << _data; - } - else - error(tr("Error writing file %1").arg(_url)); - file.close(); - m_watcher->addPath(path); -} - -void FileIo::copyFile(QString const& _sourceUrl, QString const& _destUrl) -{ - if (QUrl(_sourceUrl).scheme() == "qrc") - { - writeFile(_destUrl, readFile(_sourceUrl)); - return; - } - - if (!QFile::copy(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) - error(tr("Error copying file %1 to %2").arg(_sourceUrl).arg(_destUrl)); -} - -QString FileIo::getHomePath() const -{ - return QDir::homePath(); -} - -void FileIo::moveFile(QString const& _sourceUrl, QString const& _destUrl) -{ - if (!QFile::rename(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) - error(tr("Error moving file %1 to %2").arg(_sourceUrl).arg(_destUrl)); -} - -bool FileIo::fileExists(QString const& _url) -{ - QFile file(pathFromUrl(_url)); - return file.exists(); -} - -QStringList FileIo::makePackage(QString const& _deploymentFolder) -{ - Json::Value manifest; - Json::Value entries(Json::arrayValue); - - QDir deployDir = QDir(pathFromUrl(_deploymentFolder)); - dev::RLPStream rlpStr; - int k = 1; - std::vector files; - QMimeDatabase mimeDb; - for (auto item: deployDir.entryInfoList(QDir::Files)) - { - QFile qFile(item.filePath()); - if (qFile.open(QIODevice::ReadOnly)) - { - k++; - QFileInfo fileInfo = QFileInfo(qFile.fileName()); - Json::Value jsonValue; - std::string path = fileInfo.fileName() == "index.html" ? "/" : fileInfo.fileName().toStdString(); - jsonValue["path"] = path; //TODO: Manage relative sub folder - jsonValue["file"] = "/" + fileInfo.fileName().toStdString(); - jsonValue["contentType"] = mimeDb.mimeTypeForFile(qFile.fileName()).name().toStdString(); - QByteArray a = qFile.readAll(); - bytes data = bytes(a.begin(), a.end()); - files.push_back(data); - jsonValue["hash"] = toHex(dev::sha3(data).ref()); - entries.append(jsonValue); - } - qFile.close(); - } - rlpStr.appendList(k); - - manifest["entries"] = entries; - std::stringstream jsonStr; - jsonStr << manifest; - QByteArray b = QString::fromStdString(jsonStr.str()).toUtf8(); - rlpStr.append(bytesConstRef((const unsigned char*)b.data(), b.size())); - - for (unsigned int k = 0; k < files.size(); k++) - rlpStr.append(files.at(k)); - - bytes dapp = rlpStr.out(); - dev::h256 dappHash = dev::sha3(dapp); - //encrypt - KeyPair key((Secret(dappHash))); - Secp256k1PP enc; - enc.encrypt(key.pub(), dapp); - - QUrl url(_deploymentFolder + "package.dapp"); - QFile compressed(url.path()); - QByteArray qFileBytes((char*)dapp.data(), static_cast(dapp.size())); - if (compressed.open(QIODevice::WriteOnly | QIODevice::Truncate)) - { - compressed.write(qFileBytes); - compressed.flush(); - } - else - error(tr("Error creating package.dapp")); - compressed.close(); - QStringList ret; - ret.append(QString::fromStdString(toHex(dappHash.ref()))); - ret.append(qFileBytes.toBase64()); - ret.append(url.toString()); - return ret; -} - -void FileIo::watchFileChanged(QString const& _path) -{ - m_watcher->addPath(pathFromUrl(_path)); -} - -void FileIo::stopWatching(QString const& _path) -{ - m_watcher->removePath(pathFromUrl(_path)); -} - -void FileIo::deleteFile(QString const& _path) -{ - QFile file(pathFromUrl(_path)); - file.remove(); -} - -QUrl FileIo::pathFolder(QString const& _path) -{ - QFileInfo info(_path); - if (info.exists() && info.isDir()) - return QUrl::fromLocalFile(_path); - return QUrl::fromLocalFile(QFileInfo(_path).absolutePath()); -} diff --git a/mix/FileIo.h b/mix/FileIo.h deleted file mode 100644 index 0db399a73..000000000 --- a/mix/FileIo.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file FileIo.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include - -class QFileSystemWatcher; - -namespace dev -{ -namespace mix -{ - -///File services for QML -class FileIo: public QObject -{ - Q_OBJECT - Q_PROPERTY(QString homePath READ getHomePath CONSTANT) - -signals: - /// Signalled in case of IO error - void error(QString const& _errorText); - /// Signnalled when a file is changed. - void fileChanged(QString const& _filePath); - -public: - FileIo(); - /// Create a directory if it does not exist. Signals on failure. - Q_INVOKABLE void makeDir(QString const& _url); - /// Read file contents to a string. Signals on failure. - Q_INVOKABLE QString readFile(QString const& _url); - /// Write contents to a file. Signals on failure. - Q_INVOKABLE void writeFile(QString const& _url, QString const& _data); - /// Copy a file from _sourcePath to _destPath. Signals on failure. - Q_INVOKABLE void copyFile(QString const& _sourceUrl, QString const& _destUrl); - /// Move (rename) a file from _sourcePath to _destPath. Signals on failure. - Q_INVOKABLE void moveFile(QString const& _sourceUrl, QString const& _destUrl); - /// Check if file exists - Q_INVOKABLE bool fileExists(QString const& _url); - /// Compress a folder, @returns sha3 of the compressed file. - Q_INVOKABLE QStringList makePackage(QString const& _deploymentFolder); - /// Open a file browser. - Q_INVOKABLE void openFileBrowser(QString const& _dir); - /// Listen for files change in @arg _path. - Q_INVOKABLE void watchFileChanged(QString const& _path); - /// Stop Listenning for files change in @arg _path. - Q_INVOKABLE void stopWatching(QString const& _path); - /// Delete a file - Q_INVOKABLE void deleteFile(QString const& _path); - /// delete a directory - Q_INVOKABLE void deleteDir(QString const& _url); - - //TODO: remove once qt 5.5.1 is out - Q_INVOKABLE QString urlToPath(QUrl const& _url) { return _url.toLocalFile(); } - Q_INVOKABLE QUrl pathToUrl(QString const& _path) { return QUrl::fromLocalFile(_path); } - Q_INVOKABLE QUrl pathFolder(QString const& _path); - -private: - QString getHomePath() const; - QString pathFromUrl(QString const& _url); - QFileSystemWatcher* m_watcher; -}; - -} -} diff --git a/mix/HttpServer.cpp b/mix/HttpServer.cpp deleted file mode 100644 index fa09f51d0..000000000 --- a/mix/HttpServer.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file HttpServer.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include -#include -#include "HttpServer.h" - - -using namespace dev::mix; - -HttpServer::HttpServer() - : m_port(0) , m_listen(false) , m_accept(true) , m_componentCompleted(true) -{ -} - -HttpServer::~HttpServer() -{ - setListen(false); -} - -void HttpServer::classBegin() -{ - m_componentCompleted = false; -} - -void HttpServer::componentComplete() -{ - init(); - m_componentCompleted = true; -} - -QUrl HttpServer::url() const -{ - QUrl url; - url.setPort(m_port); - url.setHost("localhost"); - url.setScheme("http"); - return url; -} - -void HttpServer::setPort(int _port) -{ - if (_port == m_port) - return; - - m_port = _port; - emit portChanged(_port); - emit urlChanged(url()); - - if (m_componentCompleted && this->isListening()) - updateListening(); -} - -QString HttpServer::errorString() const -{ - return QTcpServer::errorString(); -} - -void HttpServer::setListen(bool _listen) -{ - if (_listen == m_listen) - return; - - m_listen = _listen; - emit listenChanged(_listen); - - if (m_componentCompleted) - updateListening(); -} - -void HttpServer::setAccept(bool _accept) -{ - if (_accept == m_accept) - return; - - m_accept = _accept; - emit acceptChanged(_accept); -} - -void HttpServer::init() -{ - updateListening(); -} - -void HttpServer::updateListening() -{ - if (this->isListening()) - this->close(); - - if (!m_listen) - return; - - if (!QTcpServer::listen(QHostAddress::LocalHost, m_port)) - { - errorStringChanged(); - return; - } - - if (m_port != QTcpServer::serverPort()) - { - m_port = QTcpServer::serverPort(); - emit portChanged(m_port); - emit urlChanged(url()); - } -} - -void HttpServer::incomingConnection(qintptr _socket) -{ - if (!m_accept) - return; - - QTcpSocket* s = new QTcpSocket(this); - connect(s, SIGNAL(readyRead()), this, SLOT(readClient())); - connect(s, SIGNAL(disconnected()), this, SLOT(discardClient())); - s->setSocketDescriptor(_socket); -} - -void HttpServer::readClient() -{ - if (!m_accept) - return; - - QTcpSocket* socket = (QTcpSocket*)sender(); - try - { - if (socket->canReadLine()) - { - QString hdr = QString(socket->readLine()); - QVariantMap headers; - if (hdr.startsWith("POST") || hdr.startsWith("GET")) - { - QUrl url(hdr.split(' ')[1]); - QString l; - do - { - l = socket->readLine(); - //collect headers - int colon = l.indexOf(':'); - if (colon > 0) - headers[l.left(colon).trimmed().toLower()] = l.right(l.length() - colon - 1).trimmed(); - } - while (!(l.isEmpty() || l == "\r" || l == "\r\n")); - - QString content = socket->readAll(); - std::unique_ptr request(new HttpRequest(this, std::move(url), std::move(content), std::move(headers))); - clientConnected(request.get()); - QTextStream os(socket); - os.setAutoDetectUnicode(true); - QString q; - ///@todo: allow setting response content-type, charset, etc - os << "HTTP/1.0 200 Ok\r\n"; - if (!request->m_responseContentType.isEmpty()) - os << "Content-Type: " << request->m_responseContentType << "; "; - os << "charset=\"utf-8\"\r\n\r\n"; - os << request->m_response; - } - } - } - catch(...) - { - delete socket; - throw; - } - socket->close(); - if (socket->state() == QTcpSocket::UnconnectedState) - delete socket; -} - -void HttpServer::discardClient() -{ - QTcpSocket* socket = (QTcpSocket*)sender(); - socket->deleteLater(); -} diff --git a/mix/HttpServer.h b/mix/HttpServer.h deleted file mode 100644 index 606fa4ff1..000000000 --- a/mix/HttpServer.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file HttpServer.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace dev -{ -namespace mix -{ - -/// Simple http server for serving jsonrpc requests -class HttpRequest: public QObject -{ - Q_OBJECT - /// Request url - Q_PROPERTY(QUrl url MEMBER m_url CONSTANT) - /// Request body contents - Q_PROPERTY(QString content MEMBER m_content CONSTANT) - /// Request HTTP headers - Q_PROPERTY(QVariantMap headers MEMBER m_headers CONSTANT) - -private: - HttpRequest(QObject* _parent, QUrl&& _url, QString&& _content, QVariantMap&& _headers): - QObject(_parent), m_url(std::move(_url)), m_content(std::move(_content)), m_headers(std::move(_headers)) - { - } - -public: - /// Set response for a request - /// @param _response Response body. If no response is set, server returns status 200 with empty body - Q_INVOKABLE void setResponse(QString const& _response) { m_response = _response; } - /// Set response content type - /// @param _contentType Response content type string. text/plain by default - Q_INVOKABLE void setResponseContentType(QString const& _contentType) { m_responseContentType = _contentType ; } - -private: - QUrl m_url; - QString m_content; - QString m_response; - QString m_responseContentType; - QVariantMap m_headers; - friend class HttpServer; -}; - -class HttpServer: public QTcpServer, public QQmlParserStatus -{ - Q_OBJECT - Q_DISABLE_COPY(HttpServer) - Q_INTERFACES(QQmlParserStatus) - - /// Server url - Q_PROPERTY(QUrl url READ url NOTIFY urlChanged) - /// Server port - Q_PROPERTY(int port READ port WRITE setPort NOTIFY portChanged) - /// Listen for connections - Q_PROPERTY(bool listen READ listen WRITE setListen NOTIFY listenChanged) - /// Accept new connections - Q_PROPERTY(bool accept READ accept WRITE setAccept NOTIFY acceptChanged) - /// Error string if any - Q_PROPERTY(QString errorString READ errorString NOTIFY errorStringChanged) - -public: - explicit HttpServer(); - virtual ~HttpServer(); - - QUrl url() const; - int port() const { return m_port; } - void setPort(int _port); - bool listen() const { return m_listen; } - void setListen(bool _listen); - bool accept() const { return m_accept; } - void setAccept(bool _accept); - QString errorString() const; - -protected: - virtual void classBegin() override; - virtual void componentComplete() override; - virtual void incomingConnection(qintptr _socket) override; - -signals: - void clientConnected(HttpRequest* _request); - void errorStringChanged(); - void urlChanged(QUrl const& _url); - void portChanged(int _port); - void listenChanged(bool _listen); - void acceptChanged(bool _accept); - -private: - void init(); - void updateListening(); - void newConnection(); - void serverError(); - -private slots: - void readClient(); - void discardClient(); - -private: - int m_port; - bool m_listen; - bool m_accept; - bool m_componentCompleted; -}; - -} -} diff --git a/mix/InverseMouseArea.cpp b/mix/InverseMouseArea.cpp deleted file mode 100644 index 9a29513a7..000000000 --- a/mix/InverseMouseArea.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file InverseMouseArea.cpp - * @author Yann yann@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include "InverseMouseArea.h" - -using namespace dev::mix; - -void InverseMouseArea::itemChange(ItemChange _c, const ItemChangeData& _v) -{ - Q_UNUSED(_v); - if (this->m_active && _c == ItemSceneChange && window()) - window()->installEventFilter(this); -} - -bool InverseMouseArea::eventFilter(QObject* _obj, QEvent* _ev) -{ - Q_UNUSED(_obj); - if (this->m_active && _ev->type() == QEvent::MouseButtonPress && !this->contains(static_cast(_ev)->pos())) - emit clickedOutside(QPointF(static_cast(_ev)->pos())); - return false; -} - -bool InverseMouseArea::contains(const QPointF& _point) const -{ - if (!this->m_active) - return false; - QPointF global = this->parentItem()->mapToItem(0, QPointF(0, 0)); - return QRectF(global.x(), global.y(), this->parentItem()->width(), this->parentItem()->height()).contains(_point); -} - -void InverseMouseArea::setActive(bool _v) -{ - m_active = _v; - if (m_active && window()) - window()->installEventFilter(this); -} diff --git a/mix/InverseMouseArea.h b/mix/InverseMouseArea.h deleted file mode 100644 index 0d19e0f1b..000000000 --- a/mix/InverseMouseArea.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file InverseMouseArea.h - * @author Yann yann@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include - -namespace dev -{ -namespace mix -{ - -class InverseMouseArea: public QQuickItem -{ - Q_OBJECT - Q_PROPERTY(bool active MEMBER m_active WRITE setActive) - -public: - InverseMouseArea(QQuickItem* _parent = 0): QQuickItem(_parent) {} - ~InverseMouseArea() { if (window()) { window()->removeEventFilter(this); } } - void setActive(bool _v); - -protected: - void itemChange(ItemChange _c, const ItemChangeData& _v) override; - bool eventFilter(QObject* _obj, QEvent *_ev) override; - bool contains(const QPointF& _point) const override; - -private: - bool m_active; - -signals: - void clickedOutside(QPointF _point); -}; - -} -} - diff --git a/mix/MachineStates.h b/mix/MachineStates.h deleted file mode 100644 index bb1c46c1d..000000000 --- a/mix/MachineStates.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -This file is part of cpp-ethereum. - -cpp-ethereum 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. - -cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file MixClient.h -* @author Yann yann@ethdev.com -* @author Arkadiy Paronyan arkadiy@ethdev.com -* @date 2015 -* Ethereum IDE client. -*/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace mix -{ - -/** - * @brief Store information about a machine state. - */ -struct MachineState -{ - uint64_t steps; - dev::u256 curPC; - dev::eth::Instruction inst; - dev::bigint newMemSize; - dev::u256 gas; - dev::u256s stack; - dev::bytes memory; - dev::bigint gasCost; - std::unordered_map storage; - std::vector levels; - unsigned codeIndex; - unsigned dataIndex; -}; - -/** - * @brief Executed conract code info - */ -struct MachineCode -{ - dev::Address address; - bytes code; -}; - -/** - * @brief Store information about a machine states. - */ -struct ExecutionResult -{ - ExecutionResult(): transactionIndex(std::numeric_limits::max()) {} - - std::vector machineStates; - std::vector transactionData; - std::vector executionCode; - dev::eth::ExecutionResult result; - dev::Address address; - dev::Address sender; - dev::Address contractAddress; - dev::u256 value; - dev::u256 gasUsed; - unsigned transactionIndex; - unsigned executonIndex = 0; - bytes inputParameters; - eth::LocalisedLogEntries logs; - eth::TransactionException excepted = eth::TransactionException::Unknown; - - bool isCall() const { return transactionIndex == std::numeric_limits::max(); } - bool isConstructor() const { return !isCall() && !address; } -}; - -using ExecutionResults = std::vector; -} -} diff --git a/mix/MixApplication.cpp b/mix/MixApplication.cpp deleted file mode 100644 index 4972b6cf5..000000000 --- a/mix/MixApplication.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file MixApplication.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include "MixApplication.h" -#include -#include -#include -#include -#include -#ifdef ETH_HAVE_WEBENGINE -#include -#endif -#include "CodeModel.h" -#include "ClientModel.h" -#include "FileIo.h" -#include "QEther.h" -#include "QVariableDeclaration.h" -#include "SortFilterProxyModel.h" -#include "Clipboard.h" -#include "HttpServer.h" -#include "InverseMouseArea.h" - -extern int qInitResources_js(); -using namespace dev::mix; - - - - -ApplicationService::ApplicationService() -{ -#ifdef ETH_HAVE_WEBENGINE - QtWebEngine::initialize(); -#endif - QFont f; - m_systemPointSize = f.pointSize(); -} - -MixApplication::MixApplication(int& _argc, char* _argv[]): - QApplication(_argc, _argv), m_engine(new QQmlApplicationEngine()) -{ - setWindowIcon(QIcon(":/res/mix_256x256x32.png")); - m_engine->load(QUrl("qrc:/qml/Application.qml")); -} - -void MixApplication::initialize() -{ -#if __linux - //work around ubuntu appmenu-qt5 bug - //https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853 - putenv((char*)"QT_QPA_PLATFORMTHEME="); - putenv((char*)"QSG_RENDER_LOOP=threaded"); -#endif -#if (defined(_WIN32) || defined(_WIN64)) - if (!getenv("OPENSSL_CONF")) - putenv((char*)"OPENSSL_CONF=c:\\"); -#endif -#ifdef ETH_HAVE_WEBENGINE - qInitResources_js(); -#endif - - setOrganizationName(tr("Ethereum")); - setOrganizationDomain(tr("ethereum.org")); - setApplicationName(tr("Mix")); - setApplicationVersion("0.1"); - - qmlRegisterType("org.ethereum.qml.CodeModel", 1, 0, "CodeModel"); - qmlRegisterType("org.ethereum.qml.ClientModel", 1, 0, "ClientModel"); - qmlRegisterType("org.ethereum.qml.ApplicationService", 1, 0, "ApplicationService"); - qmlRegisterType("org.ethereum.qml.FileIo", 1, 0, "FileIo"); - qmlRegisterType("org.ethereum.qml.QEther", 1, 0, "QEther"); - qmlRegisterType("org.ethereum.qml.QBigInt", 1, 0, "QBigInt"); - qmlRegisterType("org.ethereum.qml.QVariableDeclaration", 1, 0, "QVariableDeclaration"); - qmlRegisterType("org.ethereum.qml.RecordLogEntry", 1, 0, "RecordLogEntry"); - qmlRegisterType("org.ethereum.qml.SortFilterProxyModel", 1, 0, "SortFilterProxyModel"); - qmlRegisterType("org.ethereum.qml.QSolidityType", 1, 0, "QSolidityType"); - qmlRegisterType("org.ethereum.qml.Clipboard", 1, 0, "Clipboard"); - qmlRegisterType("HttpServer", 1, 0, "HttpServer"); - qmlRegisterType("org.ethereum.qml.InverseMouseArea", 1, 0, "InverseMouseArea"); - qRegisterMetaType("CodeModel*"); - qRegisterMetaType("ClientModel*"); -} - -MixApplication::~MixApplication() -{ -} - -bool MixApplication::notify(QObject * receiver, QEvent * event) -{ - try - { - return QApplication::notify(receiver, event); - } - catch (...) - { - std::cerr << boost::current_exception_diagnostic_information(); - } - return false; -} diff --git a/mix/MixApplication.h b/mix/MixApplication.h deleted file mode 100644 index c1fd73d66..000000000 --- a/mix/MixApplication.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file MixApplication.h - * @author Yann yann@ethdev.com - * @date 2014 - * This class will be use instead of QApplication to launch the application. the method 'notify' allows to catch all exceptions. - * Not use for now: TODO. - */ - -#pragma once - -#include -#include - -class QQmlApplicationEngine; - -namespace dev -{ -namespace mix -{ - -class ApplicationService: public QObject -{ - Q_OBJECT - Q_PROPERTY(int systemPointSize READ systemPointSize CONSTANT) - Q_PROPERTY(bool haveWebEngine READ haveWebEngine CONSTANT) - -public: - ApplicationService(); - int systemPointSize() const { return m_systemPointSize; } -#ifdef ETH_HAVE_WEBENGINE - bool haveWebEngine() const { return true; } -#else - bool haveWebEngine() const { return false; } -#endif - -private: - int m_systemPointSize = 0; -}; - - -class MixApplication: public QApplication -{ - Q_OBJECT - -public: - MixApplication(int& _argc, char* _argv[]); - static void initialize(); - virtual ~MixApplication(); - QQmlApplicationEngine* engine() { return m_engine.get(); } - bool notify(QObject* _receiver, QEvent* _event) override; - -private: - std::unique_ptr m_engine; -}; - -} -} diff --git a/mix/MixClient.cpp b/mix/MixClient.cpp deleted file mode 100644 index 834ce27a9..000000000 --- a/mix/MixClient.cpp +++ /dev/null @@ -1,384 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file MixClient.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include "MixClient.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Exceptions.h" -using namespace std; -using namespace dev; -using namespace dev::eth; - -namespace dev -{ -namespace mix -{ - -u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow - -namespace -{ -} - -MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): - FullBlockChain(createGenesisBlock(_stateRoot), std::unordered_map(), _path, WithExisting::Kill) -{ -} - -bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) -{ - RLPStream block(3); - block.appendList(13) - << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie - << LogBloom() << c_mixGenesisDifficulty << 0 << 3141592 << 0 << (unsigned)0 - << std::string(); - block.appendRaw(RLPEmptyList); - block.appendRaw(RLPEmptyList); - return block.out(); -} - -MixClient::MixClient(std::string const& _dbPath): - m_dbPath(_dbPath) -{ - resetState(std::unordered_map()); -} - -MixClient::~MixClient() -{ -} - -void MixClient::resetState(std::unordered_map const& _accounts, Secret const& _miner) -{ - WriteGuard l(x_state); - Guard fl(x_filtersWatches); - - m_filters.clear(); - for (auto& i: m_specialFilters) - i.second.clear(); - m_watches.clear(); - - m_stateDB = OverlayDB(); - SecureTrieDB accountState(&m_stateDB); - accountState.init(); - - dev::eth::commit(_accounts, accountState); - h256 stateRoot = accountState.root(); - m_bc.reset(); - m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); - Block b(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); - b.sync(bc()); - m_preMine = b; - m_postMine = b; - WriteGuard lx(x_executions); - m_executions.clear(); -} - -Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) -{ - Transaction ret; - if (_secret) - { - if (_t.isCreation()) - ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); - else - ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); - } - else - { - if (_t.isCreation()) - ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); - else - ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); - ret.forceSender(_t.safeSender()); - } - return ret; -} - -// TODO: prototype changed - will need rejigging. -ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call) -{ - State execState = _state; - execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation - eth::ExecutionResult er; - Executive execution(execState, _envInfo); - execution.setResultRecipient(er); - - ExecutionResult d; - d.address = _t.receiveAddress(); - d.sender = _t.sender(); - d.value = _t.value(); - d.inputParameters = _t.data(); - d.executonIndex = m_executions.size(); - if (!_call) - d.transactionIndex = m_postMine.pending().size(); - - try - { - execution.initialize(_t); - execution.execute(); - } - catch (Exception const& _e) - { - d.excepted = toTransactionException(_e); - d.transactionData.push_back(_t.data()); - return d; - } - - std::vector machineStates; - std::vector levels; - std::vector codes; - std::map codeIndexes; - std::vector data; - std::map dataIndexes; - bytes const* lastCode = nullptr; - bytesConstRef const* lastData = nullptr; - unsigned codeIndex = 0; - unsigned dataIndex = 0; - auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) - { - VM& vm = *static_cast(voidVM); - ExtVM const& ext = *static_cast(voidExt); - if (lastCode == nullptr || lastCode != &ext.code) - { - auto const& iter = codeIndexes.find(&ext.code); - if (iter != codeIndexes.end()) - codeIndex = iter->second; - else - { - codeIndex = codes.size(); - codes.push_back(MachineCode({ext.myAddress, ext.code})); - codeIndexes[&ext.code] = codeIndex; - } - lastCode = &ext.code; - } - - if (lastData == nullptr || lastData != &ext.data) - { - auto const& iter = dataIndexes.find(&ext.data); - if (iter != dataIndexes.end()) - dataIndex = iter->second; - else - { - dataIndex = data.size(); - data.push_back(ext.data.toBytes()); - dataIndexes[&ext.data] = dataIndex; - } - lastData = &ext.data; - } - - if (levels.size() < ext.depth) - levels.push_back(machineStates.size() - 1); - else - levels.resize(ext.depth); - - machineStates.push_back(MachineState{ - steps, - vm.curPC(), - inst, - newMemSize, - static_cast(gas), - vm.stack(), - vm.memory(), - gasCost, - ext.state().storage(ext.myAddress), - std::move(levels), - codeIndex, - dataIndex - }); - }; - - execution.go(onOp); - execution.finalize(); - - d.excepted = er.excepted; - d.result = er; - d.machineStates = machineStates; - d.executionCode = std::move(codes); - d.transactionData = std::move(data); - d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; - if (_t.isCreation()) - d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); - return d; -} - - -void MixClient::executeTransaction(Transaction const& _t, Block& _block, bool _call, bool _gasAuto, Secret const& _secret) -{ - Transaction t = _gasAuto ? replaceGas(_t, m_postMine.gasLimitRemaining()) : _t; - - // do debugging run first - EnvInfo envInfo(bc().info(), bc().lastHashes()); - ExecutionResult d = debugTransaction(t, _block.state(), envInfo, _call); - - // execute on a state - if (!_call && d.excepted == TransactionException::None) - { - u256 useGas = min(d.gasUsed, _block.gasLimitRemaining()); - t = _gasAuto ? replaceGas(_t, useGas, _secret) : _t; - eth::ExecutionResult const& er = _block.execute(envInfo.lastHashes(), t); - if (t.isCreation() && _block.state().code(d.contractAddress).empty()) - BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); - d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; - LocalisedLogEntries logs; - TransactionReceipt const& tr = _block.receipt(_block.pending().size() - 1); - - LogEntries le = tr.log(); - if (le.size()) - for (unsigned j = 0; j < le.size(); ++j) - logs.insert(logs.begin(), LocalisedLogEntry(le[j])); - d.logs = logs; - } - WriteGuard l(x_executions); - m_executions.emplace_back(std::move(d)); -} - -void MixClient::mine() -{ - WriteGuard l(x_state); - m_postMine.commitToSeal(bc()); - - NoProof::BlockHeader h(m_postMine.info()); - RLPStream header; - h.streamRLP(header); - m_postMine.sealBlock(header.out()); - bc().import(m_postMine.blockData(), m_postMine.state().db(), (ImportRequirements::Everything & ~ImportRequirements::ValidSeal) != 0); - m_postMine.sync(bc()); - m_preMine = m_postMine; -} - -ExecutionResult MixClient::lastExecution() const -{ - ReadGuard l(x_executions); - return m_executions.empty() ? ExecutionResult() : m_executions.back(); -} - -ExecutionResult MixClient::execution(unsigned _index) const -{ - ReadGuard l(x_executions); - return m_executions.at(_index); -} - -Block MixClient::asOf(h256 const& _block) const -{ - ReadGuard l(x_state); - Block ret(m_stateDB); - ret.populateFromChain(bc(), _block); - return ret; -} - -pair MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) -{ - WriteGuard l(x_state); - TransactionSkeleton ts = _ts; - ts.from = toAddress(_secret); - ts.nonce = m_postMine.transactionsFrom(ts.from); - eth::Transaction t(ts, _secret); - executeTransaction(t, m_postMine, false, _gasAuto, _secret); - return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); -} - -dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) -{ - (void)_blockNumber; - Block block = asOf(eth::PendingBlock); - u256 n = block.transactionsFrom(_from); - Transaction t(_value, _gasPrice, _gas, _dest, _data, n); - t.forceSender(_from); - if (_ff == FudgeFactor::Lenient) - block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); - WriteGuard lw(x_state); //TODO: lock is required only for last execution state - executeTransaction(t, block, true, _gasAuto); - return lastExecution().result; -} - -dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) -{ - return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); -} - -dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) -{ - (void)_blockNumber; - u256 n; - Block temp; - { - ReadGuard lr(x_state); - temp = asOf(eth::PendingBlock); - n = temp.transactionsFrom(_from); - } - Transaction t(_value, _gasPrice, _gas, _data, n); - t.forceSender(_from); - if (_ff == FudgeFactor::Lenient) - temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); - WriteGuard lw(x_state); //TODO: lock is required only for last execution state - executeTransaction(t, temp, true, false); - return lastExecution().result; -} - -eth::BlockInfo MixClient::blockInfo() const -{ - ReadGuard l(x_state); - return BlockInfo(bc().block()); -} - -void MixClient::setBeneficiary(Address _us) -{ - WriteGuard l(x_state); - m_postMine.setBeneficiary(_us); -} - -void MixClient::startMining() -{ - //no-op -} - -void MixClient::stopMining() -{ - //no-op -} - -bool MixClient::isMining() const -{ - return false; -} - -u256 MixClient::hashrate() const -{ - return 0; -} - -eth::WorkingProgress MixClient::miningProgress() const -{ - return eth::WorkingProgress(); -} - -} -} diff --git a/mix/MixClient.h b/mix/MixClient.h deleted file mode 100644 index 8be9ec9cb..000000000 --- a/mix/MixClient.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file MixClient.h - * @author Yann yann@ethdev.com - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include "MachineStates.h" - -namespace dev -{ -namespace eth { class EnvInfo; } - -namespace mix -{ - -class NoProof -{ - class BlockHeaderRaw: public dev::eth::BlockInfo - { - public: - static const unsigned SealFields = 0; - - protected: - BlockHeaderRaw() = default; - BlockHeaderRaw(BlockInfo const& _bi): BlockInfo(_bi) {} - - void populateFromHeader(RLP const& _header, dev::eth::Strictness _s) { (void) _header; (void) _s; } - void populateFromParent(BlockHeaderRaw const& _parent) { (void)_parent; } - void streamRLPFields(RLPStream& _s) const { (void) _s; } - }; - -public: - - static std::string name() { return "NoProof"; } - static unsigned revision() { return 0; } - using BlockHeader = dev::eth::BlockHeaderPolished; - -private: - static AddressHash s_authorities; -}; - -class MixBlockChain: public dev::eth::FullBlockChain -{ -public: - MixBlockChain(std::string const& _path, h256 _stateRoot); - - static bytes createGenesisBlock(h256 _stateRoot); -}; - -class MixClient: public dev::eth::ClientBase -{ -public: - MixClient(std::string const& _dbPath); - virtual ~MixClient(); - /// Reset state to the empty state with given balance. - void resetState(std::unordered_map const& _accounts, Secret const& _miner = Secret()); - void mine(); - ExecutionResult lastExecution() const; - ExecutionResult execution(unsigned _index) const; - - dev::eth::ExecutionResult call(Address const& _secret, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, eth::BlockNumber _blockNumber = eth::PendingBlock, eth::FudgeFactor _ff = eth::FudgeFactor::Strict) override; - dev::eth::ExecutionResult create(Address const& _secret, u256 _value, bytes const& _data = bytes(), u256 _gas = 10000, u256 _gasPrice = 10 * eth::szabo, eth::BlockNumber _blockNumber = eth::PendingBlock, eth::FudgeFactor _ff = eth::FudgeFactor::Strict) override; - - using ClientBase::submitTransaction; - virtual std::pair submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret) override { return submitTransaction(_ts, _secret, false); } - std::pair submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto); - dev::eth::ExecutionResult call(Address const& _secret, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, eth::BlockNumber _blockNumber, bool _gasAuto, eth::FudgeFactor _ff = eth::FudgeFactor::Strict); - ExecutionResult debugTransaction(dev::eth::Transaction const& _t, eth:: State const& _state, eth::EnvInfo const& _envInfo, bool _call); - void setBeneficiary(Address _us) override; - void startMining() override; - void stopMining() override; - bool isMining() const override; - u256 hashrate() const override; - eth::WorkingProgress miningProgress() const override; - virtual void flushTransactions() override {} - - /// @returns the last mined block information - using Interface::blockInfo; // to remove warning about hiding virtual function - eth::BlockInfo blockInfo() const; - - /// return the new address generated by the last tr (if creation). returns empty address if other cases. - Address lastCreatedContractAddr() const; - -protected: - /// ClientBase methods - using ClientBase::asOf; - virtual dev::eth::Block asOf(h256 const& _block) const override; - virtual dev::eth::BlockChain& bc() override { return *m_bc; } - virtual dev::eth::BlockChain const& bc() const override { return *m_bc; } - virtual dev::eth::Block preMine() const override { ReadGuard l(x_state); return m_preMine; } - virtual dev::eth::Block postMine() const override { ReadGuard l(x_state); return m_postMine; } - virtual void prepareForTransaction() override {} - -private: - void executeTransaction(dev::eth::Transaction const& _t, eth::Block& _block, bool _call, bool _gasAuto, dev::Secret const& _secret = dev::Secret()); - dev::eth::Transaction replaceGas(dev::eth::Transaction const& _t, dev::u256 const& _gas, dev::Secret const& _secret = dev::Secret()); - - eth::Block m_preMine; - eth::Block m_postMine; - OverlayDB m_stateDB; - std::unique_ptr m_bc; - mutable boost::shared_mutex x_state; - mutable boost::shared_mutex x_executions; - ExecutionResults m_executions; - std::string m_dbPath; -}; - -} - -} diff --git a/mix/QBasicNodeDefinition.cpp b/mix/QBasicNodeDefinition.cpp deleted file mode 100644 index a38fc3c8c..000000000 --- a/mix/QBasicNodeDefinition.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QBasicNodeDefinition.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include "QBasicNodeDefinition.h" -#include - -namespace dev -{ -namespace mix -{ - -QBasicNodeDefinition::QBasicNodeDefinition(QObject* _parent, solidity::Declaration const* _d): - QObject(_parent), m_name(QString::fromStdString(_d->getName())), m_location(_d->getLocation()) -{ -} - -QBasicNodeDefinition::QBasicNodeDefinition(QObject* _parent, std::string const& _name): - QObject(_parent), m_name(QString::fromStdString(_name)) -{ -} - -} -} diff --git a/mix/QBasicNodeDefinition.h b/mix/QBasicNodeDefinition.h deleted file mode 100644 index 6a327b734..000000000 --- a/mix/QBasicNodeDefinition.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QBasicNodeDefinition.h - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#pragma once - -#include -#include -#include - -namespace dev -{ - -namespace solidity -{ -class Declaration; -} - -namespace mix -{ - -class QBasicNodeDefinition: public QObject -{ - Q_OBJECT - Q_PROPERTY(QString name READ name CONSTANT) - -public: - QBasicNodeDefinition(QObject* _parent = nullptr): QObject(_parent) {} - ~QBasicNodeDefinition() {} - QBasicNodeDefinition(QObject* _parent, solidity::Declaration const* _d); - QBasicNodeDefinition(QObject* _parent, std::string const& _name); - /// Get the name of the node. - QString name() const { return m_name; } - dev::SourceLocation const& location() { return m_location; } - -private: - QString m_name; - dev::SourceLocation m_location; -}; - -} -} diff --git a/mix/QBigInt.cpp b/mix/QBigInt.cpp deleted file mode 100644 index 7d7dd3857..000000000 --- a/mix/QBigInt.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QBigInt.cpp - * @author Yann yann@ethdev.com - * @date 2015 - */ - -#include -#include -#include -#include "QBigInt.h" - -using namespace dev; -using namespace dev::mix; - -QString QBigInt::value() const -{ - std::ostringstream s; - s << m_internalValue; - return QString::fromStdString(s.str()); -} - -QBigInt* QBigInt::subtract(QBigInt* const& _value) const -{ - BigIntVariant toSubtract = _value->internalValue(); - return new QBigInt(boost::apply_visitor(mix::subtract(), m_internalValue, toSubtract)); -} - -QBigInt* QBigInt::add(QBigInt* const& _value) const -{ - BigIntVariant toAdd = _value->internalValue(); - return new QBigInt(boost::apply_visitor(mix::add(), m_internalValue, toAdd)); -} - -QBigInt* QBigInt::multiply(QBigInt* const& _value) const -{ - BigIntVariant toMultiply = _value->internalValue(); - return new QBigInt(boost::apply_visitor(mix::multiply(), m_internalValue, toMultiply)); -} - -QBigInt* QBigInt::divide(QBigInt* const& _value) const -{ - BigIntVariant toDivide = _value->internalValue(); - return new QBigInt(boost::apply_visitor(mix::divide(), m_internalValue, toDivide)); -} - -QVariantMap QBigInt::checkAgainst(QString const& _type) const -{ - QVariantMap ret; - QString type = _type; - QString capacity = type.replace("uint", "").replace("int", ""); - if (capacity.isEmpty()) - capacity = "256"; - bigint range = 1; - for (int k = 0; k < capacity.toInt() / 8; ++k) - range = range * 256; - bigint value = boost::get(this->internalValue()); - ret.insert("valid", true); - if (_type.startsWith("uint") && value > range - 1) - { - ret.insert("minValue", "0"); - std::ostringstream s; - s << range - 1; - ret.insert("maxValue", QString::fromStdString(s.str())); - if (value > range) - ret["valid"] = false; - } - else if (_type.startsWith("int")) - { - range = range / 2; - std::ostringstream s; - s << -range; - ret.insert("minValue", QString::fromStdString(s.str())); - s.str(""); - s.clear(); - s << range - 1; - ret.insert("maxValue", QString::fromStdString(s.str())); - if (-range > value || value > range - 1) - ret["valid"] = false; - } - return ret; -} diff --git a/mix/QBigInt.h b/mix/QBigInt.h deleted file mode 100644 index a2dac8cf9..000000000 --- a/mix/QBigInt.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QBigInt.h - * @author Yann yann@ethdev.com - * @date 2015 - * Represent a big integer (u256, bigint) to be used in QML. - */ - -#pragma once - -#include "boost/variant.hpp" -#include "boost/variant/multivisitors.hpp" -#include -#include -#include -#include - -using namespace dev; - -namespace dev -{ -namespace mix -{ - -using BigIntVariant = boost::variant; - -struct add: public boost::static_visitor -{ - template - BigIntVariant operator()(T1 const& _value, T2 const& _otherValue) const { return _value + _otherValue; } -}; - -struct subtract: public boost::static_visitor -{ - template - BigIntVariant operator()(T1 const& _value, T2 const& _otherValue) const { return _value - _otherValue; } -}; - -struct multiply: public boost::static_visitor -{ - template - BigIntVariant operator()(T1 const& _value, T2 const& _otherValue) const { return _value * _otherValue; } -}; - -struct divide: public boost::static_visitor -{ - template - BigIntVariant operator()(T1 const& _value, T2 const& _otherValue) const { return _value / _otherValue; } -}; - -/* - * Represent big integer like big int and u256 in QML. - * The ownership is set by default to Javascript. - */ -class QBigInt: public QObject -{ - Q_OBJECT - -public: - QBigInt(QObject* _parent = 0): QObject(_parent), m_internalValue(dev::u256(0)) { QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } - QBigInt(dev::u256 const& _value, QObject* _parent = 0): QObject(_parent), m_internalValue(_value) { QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } - QBigInt(dev::bigint const& _value, QObject* _parent = 0): QObject(_parent), m_internalValue(_value) { QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } - QBigInt(BigIntVariant const& _value, QObject* _parent = 0): QObject(_parent), m_internalValue(_value){ QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } - QBigInt(dev::s256 const& _value, QObject* _parent = 0): QObject(_parent), m_internalValue(_value) { QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } - ~QBigInt() {} - - /// @returns the current used big integer. - BigIntVariant internalValue() const { return m_internalValue; } - /// @returns a string representation of the big integer used. Invokable from QML. - Q_INVOKABLE QString value() const; - /// hex value. - Q_INVOKABLE QString hexValue() const { return QString::fromStdString(dev::toHex(dev::u256(value().toStdString()))); } - /// Set the value of the BigInteger used. Will use u256 type. Invokable from QML. - Q_INVOKABLE void setValue(QString const& _value) { m_internalValue = dev::jsToU256(_value.toStdString()); } - Q_INVOKABLE void setBigInt(QString const& _value) { m_internalValue = bigint(_value.toStdString()); } - void setBigInt(u256 const& _value) { m_internalValue = _value; } - /// Subtract by @a _value. Invokable from QML. - Q_INVOKABLE QBigInt* subtract(QBigInt* const& _value) const; - /// Add @a _value to the current big integer. Invokable from QML. - Q_INVOKABLE QBigInt* add(QBigInt* const& _value) const; - /// Multiply by @a _value. Invokable from QML. - Q_INVOKABLE QBigInt* multiply(QBigInt* const& _value) const; - /// divide by @a _value. Invokable from QML. - Q_INVOKABLE QBigInt* divide(QBigInt* const& _value) const; - /// check if the current value satisfy the given type - Q_INVOKABLE QVariantMap checkAgainst(QString const& _type) const; - -protected: - BigIntVariant m_internalValue; -}; - -} -} - - diff --git a/mix/QContractDefinition.cpp b/mix/QContractDefinition.cpp deleted file mode 100644 index 254d04f27..000000000 --- a/mix/QContractDefinition.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QContractDefinition.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include - -#include "QContractDefinition.h" -#include -#include -#include -#include -#include -#include -using namespace dev::solidity; -using namespace dev::mix; - -QContractDefinition::QContractDefinition(QObject* _parent, dev::solidity::ContractDefinition const* _contract): QBasicNodeDefinition(_parent, _contract) -{ - QObject* parent = _parent ? _parent : this; - if (_contract->getConstructor() != nullptr) - m_constructor = new QFunctionDefinition(parent, ContractType(*_contract).getConstructorType()); - else - m_constructor = new QFunctionDefinition(parent); - - for (auto const& it: _contract->getInterfaceFunctions()) - m_functions.append(new QFunctionDefinition(parent, it.second)); - - for (auto const& it: _contract->getEvents()) - m_events.append(new QFunctionDefinition(parent, it)); - -} - -QFunctionDefinition const* QContractDefinition::getFunction(dev::FixedHash<4> _hash) const -{ - for (auto const& f: m_functions) - if (f->hash() == _hash) - return f; - - return nullptr; -} diff --git a/mix/QContractDefinition.h b/mix/QContractDefinition.h deleted file mode 100644 index f68133ab7..000000000 --- a/mix/QContractDefinition.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QContractDefinition.h - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#pragma once - -#include -#include -#include -#include "QFunctionDefinition.h" -#include "QBasicNodeDefinition.h" - -namespace dev -{ -namespace mix -{ - -class QContractDefinition: public QBasicNodeDefinition -{ - Q_OBJECT - Q_PROPERTY(QQmlListProperty functions READ functions CONSTANT) - Q_PROPERTY(dev::mix::QFunctionDefinition* constructor READ constructor CONSTANT) - Q_PROPERTY(QQmlListProperty events READ events CONSTANT) - -public: - QContractDefinition(QObject* _parent, solidity::ContractDefinition const* _contract); - /// Get all the functions of the contract. - QQmlListProperty functions() const { return QQmlListProperty(const_cast(this), const_cast(this)->m_functions); } - /// Get the constructor of the contract. - QFunctionDefinition* constructor() const { return m_constructor; } - /// Get all the functions of the contract. - QList const& functionsList() const { return m_functions; } - /// Find function by hash, returns nullptr if not found - QFunctionDefinition const* getFunction(dev::FixedHash<4> _hash) const; - /// Get events - QQmlListProperty events() const { return QQmlListProperty(const_cast(this), const_cast(this)->m_events); } - /// Get events - QList const& eventsList() const { return m_events; } - -private: - QList m_functions; - QFunctionDefinition* m_constructor; - QList m_events; -}; - -} -} - diff --git a/mix/QEther.cpp b/mix/QEther.cpp deleted file mode 100644 index 4eef1fbdb..000000000 --- a/mix/QEther.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QEther.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include -#include "QEther.h" - -using namespace dev::mix; - -QString QEther::format() const -{ - return QString::fromStdString(dev::eth::formatBalance(boost::get(toWei()->internalValue()))); -} - -QBigInt* QEther::toWei() const -{ - QMetaEnum units = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("EtherUnit")); - const char* key = units.valueToKey(m_currentUnit); - for (std::pair rawUnit: dev::eth::units()) - { - if (QString::fromStdString(rawUnit.second).toLower() == QString(key).toLower()) - return multiply(new QBigInt(rawUnit.first)); - } - return new QBigInt(dev::u256(0)); -} - -void QEther::setUnit(QString const& _unit) -{ - QMetaEnum units = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("EtherUnit")); - for (int k = 0; k < units.keyCount(); k++) - { - if (QString(units.key(k)).toLower() == _unit.toLower()) - { - m_currentUnit = static_cast(units.keysToValue(units.key(k))); - return; - } - } -} diff --git a/mix/QEther.h b/mix/QEther.h deleted file mode 100644 index f50c39e7c..000000000 --- a/mix/QEther.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QEther.h - * @author Yann yann@ethdev.com - * @date 2014 - * Represent an amount of Ether in QML (mapped to u256 in c++). - */ - -#pragma once - -#include -#include -#include "QBigInt.h" - -namespace dev -{ -namespace mix -{ - -class QEther: public QBigInt -{ - Q_OBJECT - Q_ENUMS(EtherUnit) - Q_PROPERTY(QString value READ value WRITE setValue NOTIFY valueChanged) - Q_PROPERTY(EtherUnit unit READ unit WRITE setUnit NOTIFY unitChanged) - -public: - enum EtherUnit - { - Uether, - Vether, - Dether, - Nether, - Yether, - Zether, - Eether, - Pether, - Tether, - Gether, - Mether, - Grand, - Ether, - Finney, - Szabo, - Gwei, - Mwei, - Kwei, - Wei - }; - - QEther(QObject* _parent = 0): QBigInt(dev::u256(0), _parent), m_currentUnit(EtherUnit::Wei) {} - QEther(dev::u256 _value, EtherUnit _unit, QObject* _parent = 0): QBigInt(_value, _parent), m_currentUnit(_unit) {} - ~QEther() {} - - /// @returns user-friendly string representation of the amount of ether. Invokable from QML. - Q_INVOKABLE QString format() const; - /// @returns the current amount of Ether in Wei. Invokable from QML. - Q_INVOKABLE QBigInt* toWei() const; - /// @returns the current unit used. Invokable from QML. - Q_INVOKABLE EtherUnit unit() const { return m_currentUnit; } - /// Set the unit to be used. Invokable from QML. - Q_INVOKABLE void setUnit(EtherUnit const& _unit) { m_currentUnit = _unit; } - /// Set the unit to be used. Invokable from QML. - Q_INVOKABLE void setUnit(QString const& _unit); - /// @returns the u256 value of the current amount of Ether in Wei. - dev::u256 toU256Wei() { return boost::get(toWei()->internalValue()); } - -private: - EtherUnit m_currentUnit; - -signals: - void valueChanged(); - void unitChanged(); -}; - -} -} - diff --git a/mix/QFunctionDefinition.cpp b/mix/QFunctionDefinition.cpp deleted file mode 100644 index 1a1dd8083..000000000 --- a/mix/QFunctionDefinition.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QFunctionDefinition.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include -#include -#include -#include "QVariableDeclaration.h" -#include "QFunctionDefinition.h" - -using namespace dev::solidity; -using namespace dev::mix; - -QFunctionDefinition::QFunctionDefinition(QObject* _parent, dev::solidity::FunctionTypePointer const& _f): QBasicNodeDefinition(_parent, &_f->getDeclaration()), m_hash(dev::sha3(_f->externalSignature())), - m_fullHash(dev::sha3(_f->externalSignature())) -{ - init(_f); -} - -QFunctionDefinition::QFunctionDefinition(QObject* _parent, ASTPointer const& _f): QBasicNodeDefinition(_parent, _f.get()), m_hash(dev::sha3(_f->externalSignature())), - m_fullHash(dev::sha3(_f->externalSignature())) -{ - for (unsigned i = 0; i < _f->getParameters().size(); ++i) - m_parameters.append(new QVariableDeclaration(parent(), _f->getParameters().at(i))); - - for (unsigned i = 0; i < _f->getReturnParameters().size(); ++i) - m_returnParameters.append(new QVariableDeclaration(parent(), _f->getReturnParameters().at(i))); -} - -QFunctionDefinition::QFunctionDefinition(QObject* _parent, ASTPointer const& _e): QBasicNodeDefinition(_parent, _e.get()) -{ - for (unsigned i = 0; i < _e->getParameters().size(); ++i) - m_parameters.append(new QVariableDeclaration(parent(), _e->getParameters().at(i))); - FunctionTypePointer _f = std::make_shared(*_e); - m_hash = (FixedHash<4>)dev::sha3(_f->externalSignature(_e->getName())); - m_fullHash = dev::sha3(_f->externalSignature(_e->getName())); -} - -void QFunctionDefinition::init(dev::solidity::FunctionTypePointer _f) -{ - auto paramNames = _f->getParameterNames(); - auto paramTypes = _f->getParameterTypes(); - auto returnNames = _f->getReturnParameterNames(); - auto returnTypes = _f->getReturnParameterTypes(); - for (unsigned i = 0; i < paramNames.size(); ++i) - m_parameters.append(new QVariableDeclaration(parent(), paramNames[i], paramTypes[i].get())); - - for (unsigned i = 0; i < returnNames.size(); ++i) - m_returnParameters.append(new QVariableDeclaration(parent(), returnNames[i], returnTypes[i].get())); -} diff --git a/mix/QFunctionDefinition.h b/mix/QFunctionDefinition.h deleted file mode 100644 index 5a056fa75..000000000 --- a/mix/QFunctionDefinition.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QFunctionDefinition.h - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#pragma once - -#include -#include -#include -#include "QVariableDeclaration.h" -#include "QBasicNodeDefinition.h" - -namespace dev -{ -namespace mix -{ - -class QFunctionDefinition: public QBasicNodeDefinition -{ - Q_OBJECT - Q_PROPERTY(QQmlListProperty parameters READ parameters) - -public: - QFunctionDefinition(){} - QFunctionDefinition(QObject* _parent): QBasicNodeDefinition(_parent) {} - QFunctionDefinition(QObject* _parent, solidity::FunctionTypePointer const& _f); - QFunctionDefinition(QObject* _parent, solidity::ASTPointer const& _f); - QFunctionDefinition(QObject* _parent, solidity::ASTPointer const& _f); - /// Init members - void init(dev::solidity::FunctionTypePointer _f); - /// Get all input parameters of this function. - QList const& parametersList() const { return m_parameters; } - /// Get all input parameters of this function as QML property. - QQmlListProperty parameters() const { return QQmlListProperty(const_cast(this), const_cast(this)->m_parameters); } - /// Get all return parameters of this function. - QList returnParameters() const { return m_returnParameters; } - /// Get the hash of this function declaration on the contract ABI. - FixedHash<4> hash() const { return m_hash; } - /// Get the full hash of this function declaration on the contract ABI. - FixedHash<32> fullHash() const { return m_fullHash; } - /// Get the hash of this function declaration on the contract ABI. returns QString - Q_INVOKABLE QString qhash() const { return QString::fromStdString(m_hash.hex()); } - -private: - int m_index; - FixedHash<4> m_hash; - FixedHash<32> m_fullHash; - QList m_parameters; - QList m_returnParameters; - void initQParameters(); -}; - -} -} diff --git a/mix/QVariableDeclaration.cpp b/mix/QVariableDeclaration.cpp deleted file mode 100644 index a086585cd..000000000 --- a/mix/QVariableDeclaration.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QVariableDeclaration.app - * @author Yann yann@ethdev.com - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - */ - -#include "QVariableDeclaration.h" -#include -#include "CodeModel.h" - -using namespace solidity; - -namespace dev -{ -namespace mix -{ - -QVariableDeclaration::QVariableDeclaration(QObject* _parent, ASTPointer const _v): - QBasicNodeDefinition(_parent, _v.get()), - m_type(new QSolidityType(this, CodeModel::nodeType(_v->getType().get()))), m_isIndexed(_v->isIndexed()) -{ -} - -QVariableDeclaration::QVariableDeclaration(QObject* _parent, std::string const& _name, SolidityType const& _type, bool _isIndexed): - QBasicNodeDefinition(_parent, _name), - m_type(new QSolidityType(_parent, _type)), m_isIndexed(_isIndexed) -{ -} - -QVariableDeclaration::QVariableDeclaration(QObject* _parent, std::string const& _name, solidity::Type const* _type, bool _isIndexed): - QBasicNodeDefinition(_parent, _name), - m_type(new QSolidityType(this, CodeModel::nodeType(_type))), m_isIndexed(_isIndexed) -{ -} - -QSolidityType::QSolidityType(QObject* _parent, SolidityType const& _type): - QObject(_parent), - m_type(_type) -{ -} - -QVariantList QSolidityType::members() const -{ - QVariantList members; - if (m_type.type == Type::Struct) - for (auto const& structMember: m_type.members) - members.push_back(QVariant::fromValue(new QVariableDeclaration(parent(), structMember.name.toStdString(), structMember.type))); - if (m_type.type == Type::Enum) - for (auto const& enumName: m_type.enumNames) - members.push_back(QVariant::fromValue(enumName)); - return members; -} - -} -} - diff --git a/mix/QVariableDeclaration.h b/mix/QVariableDeclaration.h deleted file mode 100644 index 0b6ab3bf2..000000000 --- a/mix/QVariableDeclaration.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QVariableDeclaration.h - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include -#include -#include -#include "QBasicNodeDefinition.h" -#include "SolidityType.h" - -#pragma once - -namespace dev -{ - -namespace solidity -{ -class Type; -class VariableDeclaration; -} - -namespace mix -{ - -/// UI wrapper around solidity type -class QSolidityType: public QObject -{ - Q_OBJECT - Q_PROPERTY(int category READ category CONSTANT) //qml does not support enum properties - Q_PROPERTY(int size READ size CONSTANT) - Q_PROPERTY(QString name READ name CONSTANT) - Q_PROPERTY(QVariantList members READ members CONSTANT) - Q_PROPERTY(bool array READ array CONSTANT) - -public: - QSolidityType() {} - QSolidityType(QObject* _parent, SolidityType const& _type); - using Type = SolidityType::Type; - enum QmlType //TODO: Q_ENUMS does not support enum forwarding. Keep in sync with SolidityType::Type - { - SignedInteger, - UnsignedInteger, - Hash, - Bool, - Address, - Bytes, - String, - Enum, - Struct - }; - - Q_ENUMS(QmlType) - SolidityType const& type() const { return m_type; } - Type category() const { return m_type.type; } - int size() const { return m_type.size; } - QString name() const { return m_type.name; } - QVariantList members() const; - bool array() const { return m_type.array; } - -private: - SolidityType m_type; -}; - -/// UI wrapper around declaration (name + type) -class QVariableDeclaration: public QBasicNodeDefinition -{ - Q_OBJECT - Q_PROPERTY(QSolidityType* type READ type CONSTANT) - -public: - QVariableDeclaration() {} - QVariableDeclaration(QObject* _parent, solidity::ASTPointer const _v); - QVariableDeclaration(QObject* _parent, std::string const& _name, SolidityType const& _type, bool _isIndexed = false); - QVariableDeclaration(QObject* _parent, std::string const& _name, solidity::Type const* _type, bool _isIndexed = false); - QSolidityType* type() const { return m_type; } - void setType(QSolidityType* _type) { m_type = _type; } - bool isIndexed() { return m_isIndexed; } - -private: - QSolidityType* m_type; - bool m_isIndexed; -}; - - -} -} diff --git a/mix/QVariableDefinition.cpp b/mix/QVariableDefinition.cpp deleted file mode 100644 index 4553ffad6..000000000 --- a/mix/QVariableDefinition.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QVariableDefinition.cpp - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#include "QVariableDefinition.h" -#include - -namespace dev -{ -namespace mix -{ - -QString QVariableDefinition::encodeValueAsString() -{ - return QString::fromStdString(dev::toHex(encodeValue())); -} - -} -} - diff --git a/mix/QVariableDefinition.h b/mix/QVariableDefinition.h deleted file mode 100644 index e6c38f971..000000000 --- a/mix/QVariableDefinition.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file QVariableDefinition.h - * @author Yann yann@ethdev.com - * @date 2014 - */ - -#pragma once - -#include -#include - -namespace dev -{ -namespace mix -{ -class QVariableDeclaration; - -class QVariableDefinition: public QObject -{ - Q_OBJECT - - Q_PROPERTY(QString value READ value CONSTANT) - Q_PROPERTY(QVariableDeclaration* declaration READ declaration CONSTANT) - -public: - QVariableDefinition() {} - QVariableDefinition(QVariableDeclaration* _def, QString _value): QObject(), m_value(_value), m_dec(_def) {} - - /// Return the associated declaration of this variable definition. Invokable from QML. - Q_INVOKABLE QVariableDeclaration* declaration() const { return m_dec; } - /// Return the variable value. - QString value() const { return m_value; } - /// Set a new value for this instance. Invokable from QML. - Q_INVOKABLE void setValue(QString _value) { m_value = _value; } - /// Set a new Declaration for this instance. Invokable from QML. - Q_INVOKABLE void setDeclaration(QVariableDeclaration* _dec) { m_dec = _dec; } - /// Encode the current value in order to be used as function parameter. - virtual bytes encodeValue() = 0; - /// Decode the return value @a _rawValue. - virtual void decodeValue(dev::bytes const& _rawValue) = 0; - /// returns String representation of the encoded value. - Q_INVOKABLE QString encodeValueAsString(); - -protected: - QString m_value; - -private: - QVariableDeclaration* m_dec; -}; - - - - -} -} - diff --git a/mix/SolidityType.h b/mix/SolidityType.h deleted file mode 100644 index 13f5c2ecd..000000000 --- a/mix/SolidityType.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -This file is part of cpp-ethereum. - -cpp-ethereum 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. - -cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file SolidityType.h -* @author Yann yann@ethdev.com -* @author Arkadiy Paronyan arkadiy@ethdev.com -* @date 2015 -* Ethereum IDE client. -*/ - -#pragma once - -#include -#include -#include - -namespace dev -{ -namespace mix -{ - -struct SolidityDeclaration; - -//Type info extracted from solidity AST -struct SolidityType -{ - enum Type //keep in sync with QSolidity::Type - { - SignedInteger, - UnsignedInteger, - Hash, //TODO: remove - Bool, - Address, - Bytes, - String, - Enum, - Struct - }; - Type type; - unsigned size; //in bytes, - unsigned count; - bool array; - bool dynamicSize; - QString name; - std::vector members; //for struct - std::vector enumNames; //for enum - std::shared_ptr baseType; -}; - -struct SolidityDeclaration -{ - QString name; - SolidityType type; - dev::u256 slot; - unsigned offset; -}; - -using SolidityDeclarations = std::vector; - -} -} diff --git a/mix/SortFilterProxyModel.cpp b/mix/SortFilterProxyModel.cpp deleted file mode 100644 index 6fb2cca0c..000000000 --- a/mix/SortFilterProxyModel.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Yann - * @date 2015 - * Proxy used to filter a QML TableView. - */ - - -#include "SortFilterProxyModel.h" -#include -#include - -using namespace dev::mix; - -SortFilterProxyModel::SortFilterProxyModel(QObject* _parent) : QSortFilterProxyModel(_parent) -{ - connect(this, &SortFilterProxyModel::rowsInserted, this, &SortFilterProxyModel::countChanged); - connect(this, &SortFilterProxyModel::rowsRemoved, this, &SortFilterProxyModel::countChanged); -} - -int SortFilterProxyModel::count() const -{ - return rowCount(); -} - -QObject* SortFilterProxyModel::source() const -{ - return sourceModel(); -} - -void SortFilterProxyModel::setSource(QObject* _source) -{ - setSourceModel(qobject_cast(_source)); -} - -QByteArray SortFilterProxyModel::sortRole() const -{ - return roleNames().value(QSortFilterProxyModel::sortRole()); -} - -void SortFilterProxyModel::setSortRole(QByteArray const& _role) -{ - QSortFilterProxyModel::setSortRole(roleKey(_role)); -} - -void SortFilterProxyModel::setSortOrder(Qt::SortOrder _order) -{ - QSortFilterProxyModel::sort(0, _order); -} - -QString SortFilterProxyModel::filterString() const -{ - return filterRegExp().pattern(); -} - -void SortFilterProxyModel::setFilterString(QString const& _filter) -{ - setFilterRegExp(QRegExp(_filter, filterCaseSensitivity(), static_cast(filterSyntax()))); -} - -SortFilterProxyModel::FilterSyntax SortFilterProxyModel::filterSyntax() const -{ - return static_cast(filterRegExp().patternSyntax()); -} - -void SortFilterProxyModel::setFilterSyntax(SortFilterProxyModel::FilterSyntax _syntax) -{ - setFilterRegExp(QRegExp(filterString(), filterCaseSensitivity(), static_cast(_syntax))); -} - -QJSValue SortFilterProxyModel::get(int _idx) const -{ - QJSEngine *engine = qmlEngine(this); - QJSValue value = engine->newObject(); - if (_idx >= 0 && _idx < count()) - { - QHash roles = roleNames(); - QHashIterator it(roles); - while (it.hasNext()) - { - it.next(); - value.setProperty(QString::fromUtf8(it.value()), data(index(_idx, 0), it.key()).toString()); - } - } - return value; -} - -int SortFilterProxyModel::roleKey(QByteArray const& _role) const -{ - QHash roles = roleNames(); - QHashIterator it(roles); - while (it.hasNext()) - { - it.next(); - if (it.value() == _role) - return it.key(); - } - return -1; -} - -QHash SortFilterProxyModel::roleNames() const -{ - if (QAbstractItemModel* source = sourceModel()) - return source->roleNames(); - return QHash(); -} - -bool SortFilterProxyModel::filterAcceptsRow(int _sourceRow, QModelIndex const& _sourceParent) const -{ - QAbstractItemModel* model = sourceModel(); - QModelIndex sourceIndex = model->index(_sourceRow, 0, _sourceParent); - if (!sourceIndex.isValid()) - return true; - - QString keyType = model->data(sourceIndex, roleKey(type.toUtf8())).toString(); - QString keyContent = model->data(sourceIndex, roleKey(content.toUtf8())).toString(); - return keyType.contains(m_filterType) && keyContent.contains(m_filterContent); -} - -void SortFilterProxyModel::setFilterType(QString const& _type) -{ - m_filterType = QRegExp(_type, filterCaseSensitivity(), static_cast(filterSyntax())); - setFilterRegExp(_type); -} - -QString SortFilterProxyModel::filterType() const -{ - return m_filterType.pattern(); -} - -void SortFilterProxyModel::setFilterContent(QString const& _content) -{ - m_filterContent = QRegExp(_content, filterCaseSensitivity(), static_cast(filterSyntax())); - setFilterRegExp(_content); -} - -QString SortFilterProxyModel::filterContent() const -{ - return m_filterContent.pattern(); -} - diff --git a/mix/SortFilterProxyModel.h b/mix/SortFilterProxyModel.h deleted file mode 100644 index de9a2005f..000000000 --- a/mix/SortFilterProxyModel.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Yann - * @date 2015 - * Proxy used to filter a QML TableView. - */ - - -#pragma once - -#include -#include - -namespace dev -{ -namespace mix -{ - -class SortFilterProxyModel: public QSortFilterProxyModel -{ - Q_OBJECT - Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(QObject* source READ source WRITE setSource) - - Q_PROPERTY(QByteArray sortRole READ sortRole WRITE setSortRole) - Q_PROPERTY(Qt::SortOrder sortOrder READ sortOrder WRITE setSortOrder) - - Q_PROPERTY(QString filterContent READ filterContent WRITE setFilterContent) - Q_PROPERTY(QString filterType READ filterType WRITE setFilterType) - Q_PROPERTY(QString filterString READ filterString WRITE setFilterString) - Q_PROPERTY(FilterSyntax filterSyntax READ filterSyntax WRITE setFilterSyntax) - - Q_ENUMS(FilterSyntax) - -public: - explicit SortFilterProxyModel(QObject* _parent = 0); - - QObject* source() const; - void setSource(QObject* _source); - - QByteArray sortRole() const; - void setSortRole(QByteArray const& _role); - - void setSortOrder(Qt::SortOrder _order); - - QString filterContent() const; - void setFilterContent(QString const& _content); - QString filterType() const; - void setFilterType(QString const& _type); - - QString filterString() const; - void setFilterString(QString const& _filter); - - enum FilterSyntax { - RegExp, - Wildcard, - FixedString - }; - - FilterSyntax filterSyntax() const; - void setFilterSyntax(FilterSyntax _syntax); - - int count() const; - Q_INVOKABLE QJSValue get(int _index) const; - -signals: - void countChanged(); - -protected: - int roleKey(QByteArray const& _role) const; - QHash roleNames() const; - bool filterAcceptsRow(int _sourceRow, QModelIndex const& _sourceParent) const; - -private: - QRegExp m_filterType; - QRegExp m_filterContent; - const QString type = "type"; - const QString content = "content"; -}; - -} -} diff --git a/mix/Web3Server.cpp b/mix/Web3Server.cpp deleted file mode 100644 index 94ed3f85c..000000000 --- a/mix/Web3Server.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Web3Server.h.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include -#include "Web3Server.h" - -using namespace dev::mix; -using namespace dev; - -namespace -{ -class EmptyNetwork : public dev::WebThreeNetworkFace -{ - std::vector peers() override - { - return std::vector(); - } - - size_t peerCount() const override - { - return 0; - } - - void addNode(p2p::NodeId const& _node, bi::tcp::endpoint const& _hostEndpoint) override - { - (void)_node; - (void)_hostEndpoint; - } - - void requirePeer(p2p::NodeId const& _node, bi::tcp::endpoint const& _endpoint) override - { - (void)_node; - (void)_endpoint; - } - - dev::bytes saveNetwork() override - { - return dev::bytes(); - } - - void setIdealPeerCount(size_t _n) override - { - (void)_n; - } - - bool haveNetwork() const override - { - return false; - } - - p2p::NetworkPreferences const& networkPreferences() const override - { - static const p2p::NetworkPreferences c_ret; - return c_ret; - } - - void setNetworkPreferences(p2p::NetworkPreferences const& _n, bool _dropPeers) override - { - (void)_n; - (void)_dropPeers; - } - - p2p::NodeInfo nodeInfo() const override { return p2p::NodeInfo(); } - - std::string enode() const override { return ""; } - - p2p::NodeId id() const override - { - return p2p::NodeId(); - } - - p2p::Peers nodes() const override - { - return p2p::Peers(); - } - - void startNetwork() override - { - } - - void stopNetwork() override - { - } - - bool isNetworkStarted() const override - { - return false; - } -}; - -} - -Web3Server::Web3Server(jsonrpc::AbstractServerConnector& _conn, std::shared_ptr const& _ethAccounts, std::vector const& _shhAccounts, dev::eth::Interface* _client): - WebThreeStubServerBase(_conn, _ethAccounts, _shhAccounts), - m_client(_client), - m_network(new EmptyNetwork()) -{ -} - -Web3Server::~Web3Server() -{ -} - -std::shared_ptr Web3Server::face() -{ - BOOST_THROW_EXCEPTION(InterfaceNotSupported("dev::shh::Interface")); -} - -dev::WebThreeNetworkFace* Web3Server::network() -{ - return m_network.get(); -} - -std::string Web3Server::get(std::string const& _name, std::string const& _key) -{ - std::string k(_name + "/" + _key); - return m_db[k]; -} - -void Web3Server::put(std::string const& _name, std::string const& _key, std::string const& _value) -{ - std::string k(_name + "/" + _key); - m_db[k] = _value; -} - -Json::Value Web3Server::eth_getFilterChanges(std::string const& _filterId) -{ - return WebThreeStubServerBase::eth_getFilterChanges(_filterId); -} - -std::string Web3Server::eth_sendTransaction(Json::Value const& _json) -{ - std::string ret = WebThreeStubServerBase::eth_sendTransaction(_json); - emit newTransaction(); - return ret; -} - -std::string Web3Server::eth_call(Json::Value const& _json, std::string const& _blockNumber) -{ - std::string ret = WebThreeStubServerBase::eth_call(_json, _blockNumber); - emit newTransaction(); - return ret; -} diff --git a/mix/Web3Server.h b/mix/Web3Server.h deleted file mode 100644 index 2383a0a3c..000000000 --- a/mix/Web3Server.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file Web3Server.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace dev -{ - -namespace mix -{ - -class Web3Server: public QObject, public dev::WebThreeStubServerBase, public dev::WebThreeStubDatabaseFace -{ - Q_OBJECT - -public: - Web3Server(jsonrpc::AbstractServerConnector& _conn, std::shared_ptr const& _ethAccounts, std::vector const& _shhAccounts, dev::eth::Interface* _client); - virtual ~Web3Server(); - -signals: - void newTransaction(); - -protected: - virtual Json::Value eth_getFilterChanges(std::string const& _filterId) override; - virtual std::string eth_sendTransaction(Json::Value const& _json) override; - virtual std::string eth_call(Json::Value const& _json, std::string const& _blockNumber) override; - -private: - dev::eth::Interface* client() override { return m_client; } - std::shared_ptr face() override; - dev::WebThreeNetworkFace* network() override; - dev::WebThreeStubDatabaseFace* db() override { return this; } - - std::string get(std::string const& _name, std::string const& _key) override; - void put(std::string const& _name, std::string const& _key, std::string const& _value) override; - -private: - dev::eth::Interface* m_client; - std::map m_db; - std::unique_ptr m_network; -}; - -} - -} diff --git a/mix/main.cpp b/mix/main.cpp deleted file mode 100644 index 78b5261ac..000000000 --- a/mix/main.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file main.cpp - * @author Yann yann@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include "MixApplication.h" - -using namespace dev::mix; - -int main(int _argc, char* _argv[]) -{ - try - { - MixApplication::initialize(); - MixApplication app(_argc, _argv); - return app.exec(); - } - catch (boost::exception const& _e) - { - std::cerr << boost::diagnostic_information(_e); - } - catch (std::exception const& _e) - { - std::cerr << _e.what(); - } -} diff --git a/mix/noweb.qrc b/mix/noweb.qrc deleted file mode 100644 index 9dc107942..000000000 --- a/mix/noweb.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - qml/WebPreviewStub.qml - qml/CodeEditor.qml - - diff --git a/mix/osx.qrc b/mix/osx.qrc deleted file mode 100644 index ef302c2d5..000000000 --- a/mix/osx.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - qml/MacFileDialog.qml - - diff --git a/mix/qml.qrc b/mix/qml.qrc deleted file mode 100644 index 50795d08b..000000000 --- a/mix/qml.qrc +++ /dev/null @@ -1,81 +0,0 @@ - - - qml/AlertMessageDialog.qml - qml/Application.qml - qml/BasicMessage.qml - qml/BigIntValue.qml - qml/CallStack.qml - qml/CodeEditorStyle.qml - qml/CodeEditorView.qml - qml/CommonSeparator.qml - qml/DebugBasicInfo.qml - qml/DebugInfoList.qml - qml/Debugger.qml - qml/DebuggerPaneStyle.qml - qml/DefaultLabel.qml - qml/DefaultTextField.qml - qml/DeploymentDialog.qml - qml/Ether.qml - qml/EtherValue.qml - qml/FilesSection.qml - qml/ItemDelegateDataDump.qml - qml/LogsPane.qml - qml/LogsPaneStyle.qml - qml/MainContent.qml - qml/ModalDialog.qml - qml/NewProjectDialog.qml - qml/ProjectFilesStyle.qml - qml/ProjectList.qml - qml/ProjectModel.qml - qml/QBoolTypeView.qml - qml/QHashTypeView.qml - qml/QIntTypeView.qml - qml/QRealTypeView.qml - qml/QStringTypeView.qml - qml/QVariableDeclaration.qml - qml/QVariableDefinition.qml - qml/QFileDialog.qml - qml/SourceSansProBold.qml - qml/SourceSansProLight.qml - qml/SourceSansProRegular.qml - qml/Splitter.qml - qml/StateDialog.qml - qml/StateDialogStyle.qml - qml/StateList.qml - qml/StateListModel.qml - qml/StateStyle.qml - qml/StatusPane.qml - qml/StatusPaneStyle.qml - qml/StepActionImage.qml - qml/StorageView.qml - qml/StatesComboBox.qml - qml/StructView.qml - qml/Style.qml - qml/TabStyle.qml - qml/TransactionDialog.qml - qml/TransactionLog.qml - qml/VariablesView.qml - qml/WebPreviewStyle.qml - qml/js/Debugger.js - qml/js/ErrorLocationFormater.js - qml/js/ProjectModel.js - qml/js/QEtherHelper.js - qml/js/TransactionHelper.js - qml/js/Printer.js - qml/js/ansi2html.js - qml/js/NetworkDeployment.js - qml/js/InputValidator.js - qml/Block.qml - qml/BlockChain.qml - qml/ScenarioExecution.qml - qml/ScenarioLoader.qml - qml/ScenarioButton.qml - qml/Watchers.qml - qml/KeyValuePanel.qml - qml/DeployContractStep.qml - qml/RegisteringStep.qml - qml/DeploymentDialogSteps.qml - qml/PackagingStep.qml - qml/DeploymentWorker.qml - - diff --git a/mix/qml/AlertMessageDialog.qml b/mix/qml/AlertMessageDialog.qml deleted file mode 100644 index 1d48f5474..000000000 --- a/mix/qml/AlertMessageDialog.qml +++ /dev/null @@ -1,30 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Window 2.0 - -Window -{ - id: alertMessageDialog - title: "" - modality: Qt.WindowModal - height: 150 - width: 200 - visible: false - Loader - { - focus: true - id: alertMessageDialogContent - objectName: "alertMessageDialogContent" - anchors.fill: parent - } - function open() - { - visible = true - } - function close() - { - visible = false; - alertMessageDialogContent.source = ""; - alertMessageDialogContent.sourceComponent = undefined; - alertMessageDialog.destroy(); - } -} diff --git a/mix/qml/Application.qml b/mix/qml/Application.qml deleted file mode 100644 index f75646e5b..000000000 --- a/mix/qml/Application.qml +++ /dev/null @@ -1,438 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.1 -import QtQuick.PrivateWidgets 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.QEther 1.0 -import org.ethereum.qml.CodeModel 1.0 -import org.ethereum.qml.ClientModel 1.0 -import org.ethereum.qml.FileIo 1.0 -import org.ethereum.qml.Clipboard 1.0 -import org.ethereum.qml.ApplicationService 1.0 - -ApplicationWindow { - - id: mainApplication - signal loaded; - visible: true - width: 1200 - height: 800 - minimumWidth: 400 - minimumHeight: 300 - title: qsTr("Mix") - property alias systemPointSize: appService.systemPointSize; - property alias mainContent: mainContent; - property alias codeModel: codeModel; - property alias clientModel: clientModel; - property alias projectModel: projectModel; - property alias appService: appService; - property bool trackLastProject: true; - - ApplicationService { - id: appService - } - - CodeModel { - id: codeModel - } - - ClientModel { - id: clientModel - codeModel: codeModel - Component.onCompleted: - { - init("/tmp") - } - } - - ProjectModel { - id: projectModel - } - - FileIo { - id: fileIo - } - - Clipboard { - id: clipboard - } - - Style { - id: appStyle - } - - Connections { - target: mainApplication - onClosing: - { - mainApplication.close(); - close.accepted = false; - } - } - - Component.onCompleted: { - loaded(); - } - - function close() { - projectModel.appIsClosing = true; - if (projectModel.projectPath !== "") - projectModel.closeProject(function() { Qt.quit(); }) - else - Qt.quit(); - } - - menuBar: MenuBar { - Menu { - title: qsTr("File") - MenuItem { action: createProjectAction } - MenuItem { action: openProjectAction } - MenuSeparator {} - MenuItem { action: saveAllFilesAction } - MenuItem { action: saveCurrentDocument } - MenuSeparator {} - MenuItem { action: addExistingFileAction } - MenuItem { action: addNewJsFileAction } - MenuItem { action: addNewHtmlFileAction } - MenuItem { action: addNewCssFileAction } - MenuSeparator {} - MenuItem { action: addNewContractAction } - MenuItem { action: closeProjectAction } - MenuSeparator {} - MenuItem { action: exitAppAction } - } - Menu { - title: qsTr("Deploy") - MenuItem { action: mineAction } - MenuSeparator {} - MenuItem { action: deployViaRpcAction } - MenuSeparator {} - MenuItem { action: toggleRunOnLoadAction } - } - Menu { - title: qsTr("Scenario") - MenuItem { action: editStatesAction } - } - Menu { - title: qsTr("Debug") - MenuItem { action: debugRunAction } - MenuSeparator {} - MenuItem { action: toggleAssemblyDebuggingAction } - } - Menu { - title: qsTr("Tools") - MenuItem { action: gasEstimationAction } - MenuItem { action: optimizeCodeAction } - } - Menu { - title: qsTr("Windows") - MenuItem { action: openNextDocumentAction } - MenuItem { action: openPrevDocumentAction } - MenuSeparator {} - MenuItem { action: toggleProjectNavigatorAction } - MenuItem { action: showHideRightPanelAction } - MenuItem { action: toggleWebPreviewAction } - MenuItem { action: toggleWebPreviewOrientationAction } - } - } - - MainContent { - id: mainContent; - anchors.fill: parent - } - - ModalDialog { - objectName: "dialog" - id: dialog - } - - AlertMessageDialog { - objectName: "alertMessageDialog" - id: messageDialog - } - - Settings { - id: mainWindowSettings - property alias mainWidth: mainApplication.width - property alias mainHeight: mainApplication.height - property alias mainX: mainApplication.x - property alias mainY: mainApplication.y - } - - Action { - id: exitAppAction - text: qsTr("Exit") - shortcut: "Ctrl+Q" - onTriggered: - { - mainApplication.close(); - } - } - - Action { - id: mineAction - text: qsTr("New Block") - shortcut: "Ctrl+M" - onTriggered: clientModel.mine(); - enabled: codeModel.hasContract && !clientModel.running && !clientModel.mining - } - - StateList { - id: stateList - } - - Action { - id: editStatesAction - text: qsTr("Edit Scenarii") - shortcut: "Ctrl+Alt+E" - onTriggered: stateList.open(); - } - - Connections { - target: projectModel.stateListModel - - function updateRunLabel() - { - debugRunAction.text = qsTr("Deploy") + " \"" + projectModel.stateListModel.defaultStateName() + "\""; - } - - onDefaultStateChanged: updateRunLabel() - onStateListModelReady: updateRunLabel() - } - - Action { - id: debugRunAction - text: qsTr("Deploy") - shortcut: "F5" - onTriggered: mainContent.startQuickDebugging() - enabled: codeModel.hasContract && !clientModel.running && projectModel.stateListModel.defaultStateName() !== "" - } - - Action { - id: toggleAssemblyDebuggingAction - text: qsTr("Show VM Code") - shortcut: "Ctrl+Alt+V" - onTriggered: mainContent.debuggerPanel.assemblyMode = !mainContent.debuggerPanel.assemblyMode; - checked: mainContent.debuggerPanel.assemblyMode; - checkable: true - enabled: true - } - - Action { - id: toggleWebPreviewAction - text: qsTr("Show Web View") - shortcut: "F2" - checkable: true - checked: mainContent.webViewVisible - onTriggered: mainContent.toggleWebPreview(); - } - - Action { - id: toggleProjectNavigatorAction - text: qsTr("Show Project Navigator") - shortcut: "Alt+0" - checkable: true - checked: mainContent.projectViewVisible - onTriggered: mainContent.toggleProjectView(); - } - - Action { - id: toggleWebPreviewOrientationAction - text: qsTr("Horizontal Web View") - shortcut: "" - checkable: true - checked: mainContent.webViewHorizontal - onTriggered: mainContent.toggleWebPreviewOrientation(); - } - - Action { - id: toggleRunOnLoadAction - text: qsTr("Load State on Startup") - shortcut: "" - checkable: true - checked: mainContent.runOnProjectLoad - onTriggered: mainContent.runOnProjectLoad = !mainContent.runOnProjectLoad - } - - Action { - id: showHideRightPanelAction - text: qsTr("Show Right View") - shortcut: "F7" - checkable: true - checked: mainContent.rightViewVisible - onTriggered: mainContent.toggleRightView(); - } - - Action { - id: createProjectAction - text: qsTr("&New Project") - shortcut: "Ctrl+N" - enabled: true; - onTriggered: projectModel.createProject(); - } - - Action { - id: openProjectAction - text: qsTr("&Open Project") - shortcut: "Ctrl+O" - enabled: true; - onTriggered: openProjectFileDialog.open() - } - - QFileDialog { - id: openProjectFileDialog - visible: false - title: qsTr("Open a Project") - selectFolder: true - selectExisting: true - onAccepted: { - var path = openProjectFileDialog.fileUrl.toString(); - path += "/"; - projectModel.loadProject(path); - } - } - - Action { - id: addNewJsFileAction - text: qsTr("New JavaScript File") - shortcut: "Ctrl+Alt+J" - enabled: !projectModel.isEmpty - onTriggered: projectModel.newJsFile(); - } - - Action { - id: addNewHtmlFileAction - text: qsTr("New HTML File") - shortcut: "Ctrl+Alt+H" - enabled: !projectModel.isEmpty - onTriggered: projectModel.newHtmlFile(); - } - - Action { - id: addNewCssFileAction - text: qsTr("New CSS File") - shortcut: "Ctrl+Alt+S" - enabled: !projectModel.isEmpty - onTriggered: projectModel.newCssFile(); - } - - Action { - id: addNewContractAction - text: qsTr("New Contract") - shortcut: "Ctrl+Alt+C" - enabled: !projectModel.isEmpty - onTriggered: projectModel.newContract(); - } - - Action { - id: addExistingFileAction - text: qsTr("Add Existing File") - shortcut: "Ctrl+Alt+A" - enabled: !projectModel.isEmpty - onTriggered: addExistingFileDialog.open() - } - - QFileDialog { - id: addExistingFileDialog - visible: false - title: qsTr("Add a File") - selectFolder: false - selectExisting: true - onAccepted: { - var paths = addExistingFileDialog.fileUrls; - projectModel.addExistingFiles(paths); - } - } - - Action { - id: saveAllFilesAction - text: qsTr("Save All") - shortcut: "Ctrl+Shift+A" - enabled: !projectModel.isEmpty - onTriggered: projectModel.saveAll(); - } - - Action { - id: saveCurrentDocument - text: qsTr("Save Current Document") - shortcut: "Ctrl+S" - enabled: !projectModel.isEmpty - onTriggered: projectModel.saveCurrentDocument(); - } - - Action { - id: closeProjectAction - text: qsTr("Close Project") - shortcut: "Ctrl+W" - enabled: !projectModel.isEmpty - onTriggered: projectModel.closeProject(); - } - - Action { - id: openNextDocumentAction - text: qsTr("Next Document") - shortcut: "Ctrl+Tab" - enabled: !projectModel.isEmpty - onTriggered: projectModel.openNextDocument(); - } - - Action { - id: openPrevDocumentAction - text: qsTr("Previous Document") - shortcut: "Ctrl+Shift+Tab" - enabled: !projectModel.isEmpty - onTriggered: projectModel.openPrevDocument(); - } - - Action { - id: toggleBreakpointAction - text: qsTr("Toggle Breakpoint") - shortcut: "F9" - enabled: mainContent.codeEditor.editingContract(); - onTriggered: mainContent.toggleBreakpoint(); - } - - Action { - id: deployViaRpcAction - text: qsTr("Deploy to Network") - shortcut: "Ctrl+Shift+D" - enabled: !projectModel.isEmpty && codeModel.hasContract - onTriggered: projectModel.deployProject(); - } - - Action { - id: goToCompilationError - text: qsTr("Go to compilation error") - shortcut: "F4" - onTriggered: - { - mainContent.codeEditor.goToCompilationError(); - } - } - - Action { - id: gasEstimationAction - text: qsTr("Display gas estimation") - shortcut: "Ctrl+G" - checkable: true - onTriggered: mainContent.codeEditor.displayGasEstimation(checked); - } - - Action { - id: optimizeCodeAction - text: qsTr("Enable optimized compilation") - shortcut: "Ctrl+Shift+O" - checkable: true - onTriggered: codeModel.setOptimizeCode(checked); - } - - Settings { - id: appSettings - property alias gasEstimation: gasEstimationAction.checked - property alias optimizeCode: optimizeCodeAction.checked - property string nodeAddress: "http://localhost:8545" - } -} diff --git a/mix/qml/BasicMessage.qml b/mix/qml/BasicMessage.qml deleted file mode 100644 index 7ab04d57c..000000000 --- a/mix/qml/BasicMessage.qml +++ /dev/null @@ -1,22 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 - -Rectangle { - anchors.fill: parent - color: "lightgrey" - Label - { - width: parent.width - height: parent.height - horizontalAlignment: "AlignHCenter" - verticalAlignment: "AlignVCenter" - objectName: "messageContent" - id: messageTxt - text: "" - wrapMode: "Wrap" - } -} - diff --git a/mix/qml/BigIntValue.qml b/mix/qml/BigIntValue.qml deleted file mode 100644 index 5e3262516..000000000 --- a/mix/qml/BigIntValue.qml +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Used to instanciate a QEther obj using Qt.createComponent function. -*/ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Controls.Styles 1.1 -import org.ethereum.qml.QBigInt 1.0 - -QBigInt -{ - id: bigInt -} diff --git a/mix/qml/Block.qml b/mix/qml/Block.qml deleted file mode 100644 index a533b7fd2..000000000 --- a/mix/qml/Block.qml +++ /dev/null @@ -1,378 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "." - -ColumnLayout -{ - id: root - property variant transactions - property variant transactionModel - property string status - property int number - property int blockWidth: Layout.preferredWidth - statusWidth - horizontalMargin - property int horizontalMargin: 10 - property int trHeight: 35 - spacing: 0 - property int openedTr: 0 - property int blockIndex - property variant scenario - property string labelColor: "#414141" - - - property string selectedBlockColor: "#accbf2" - property string selectedBlockForeground: "#445e7f" - - property int scenarioIndex - signal txSelected(var txIndex) - - function calculateHeight() - { - if (transactions) - { - if (index >= 0) - return trHeight + trHeight * transactions.count + openedTr - else - return trHeight - } - else - return trHeight - } - - function editTx(txIndex) - { - transactionDialog.stateAccounts = scenario.accounts - transactionDialog.execute = false - transactionDialog.editMode = true - transactionDialog.open(txIndex, blockIndex, transactions.get(txIndex)) - } - - function select(txIndex) - { - transactionRepeater.itemAt(txIndex).select() - } - - onOpenedTrChanged: - { - Layout.preferredHeight = calculateHeight() - height = calculateHeight() - } - - DebuggerPaneStyle { - id: dbgStyle - } - - Rectangle - { - id: top - Layout.preferredWidth: blockWidth - height: 10 - anchors.bottom: rowHeader.top - color: "#DEDCDC" - radius: 15 - anchors.left: parent.left - anchors.leftMargin: statusWidth - anchors.bottomMargin: -5 - } - - RowLayout - { - Layout.preferredHeight: trHeight - Layout.preferredWidth: blockWidth - id: rowHeader - spacing: 0 - Rectangle - { - Layout.preferredWidth: blockWidth - Layout.preferredHeight: trHeight - color: "#DEDCDC" - anchors.left: parent.left - anchors.leftMargin: statusWidth - Label { - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: horizontalMargin - font.pointSize: dbgStyle.absoluteSize(1) - color: "#adadad" - text: - { - if (number === -2) - return qsTr("GENESIS PARAMETERS") - else if (status === "mined") - return qsTr("BLOCK") + " " + number - else - return qsTr("PENDING TRANSACTIONS") - } - } - - Image { - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - anchors.rightMargin: 14 - visible: number === -2 - source: "qrc:/qml/img/edit_combox.png" - height: 15 - fillMode: Image.PreserveAspectFit - - MouseArea - { - anchors.fill: parent - onClicked: - { - // load edit block panel - projectModel.stateListModel.editState(scenarioIndex) - } - } - - } - } - } - - Repeater // List of transactions - { - id: transactionRepeater - model: transactions - RowLayout - { - id: rowTransaction - Layout.preferredHeight: trHeight - spacing: 0 - - function select() - { - rowContentTr.select() - } - - function displayContent() - { - logsText.text = "" - if (index >= 0 && transactions.get(index).logs && transactions.get(index).logs.count) - { - for (var k = 0; k < transactions.get(index).logs.count; k++) - { - var log = transactions.get(index).logs.get(k) - if (log.name) - logsText.text += log.name + ":\n" - else - logsText.text += "log:\n" - - if (log.param) - for (var i = 0; i < log.param.count; i++) - { - var p = log.param.get(i) - logsText.text += p.name + " = " + p.value + " - indexed:" + p.indexed + "\n" - } - else { - logsText.text += "From : " + log.address + "\n" - } - } - logsText.text += "\n\n" - } - rowDetailedContent.visible = !rowDetailedContent.visible - } - - Rectangle - { - id: trSaveStatus - Layout.preferredWidth: statusWidth - Layout.preferredHeight: parent.height - color: "transparent" - anchors.top: parent.top - property bool saveStatus - Image { - anchors.top: parent.top - anchors.left: parent.left - anchors.leftMargin: -4 - anchors.topMargin: 0 - id: saveStatusImage - source: "qrc:/qml/img/recyclediscard@2x.png" - width: statusWidth + 10 - fillMode: Image.PreserveAspectFit - } - - Component.onCompleted: - { - if (index >= 0) - saveStatus = transactions.get(index).saveStatus - } - - onSaveStatusChanged: - { - if (saveStatus) - saveStatusImage.source = "qrc:/qml/img/recyclekeep@2x.png" - else - saveStatusImage.source = "qrc:/qml/img/recyclediscard@2x.png" - - if (index >= 0) - transactions.get(index).saveStatus = saveStatus - transactionModel[index].saveStatus = saveStatus - } - - MouseArea { - id: statusMouseArea - anchors.fill: parent - onClicked: - { - parent.saveStatus = !parent.saveStatus - } - } - } - - Rectangle - { - Layout.preferredWidth: blockWidth - Layout.preferredHeight: trHeight - height: trHeight - color: "#DEDCDC" - id: rowContentTr - anchors.top: parent.top - - property bool selected: false - Connections - { - target: blockChainPanel - onTxSelected: { - if (root.blockIndex !== blockIndex || index !== txIndex) - rowContentTr.deselect() - } - } - - function select() - { - rowContentTr.selected = true - rowContentTr.color = selectedBlockColor - hash.color = selectedBlockForeground - func.color = selectedBlockForeground - txSelected(index) - - } - - function deselect() - { - rowContentTr.selected = false - rowContentTr.color = "#DEDCDC" - hash.color = labelColor - func.color = labelColor - } - - MouseArea - { - anchors.fill: parent - onClicked: { - if (!rowContentTr.selected) - rowContentTr.select() - else - rowContentTr.deselect() - - } - onDoubleClicked: - { - root.editTx(index) - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: trHeight - 10 - anchors.verticalCenter: parent.verticalCenter - Rectangle - { - Layout.preferredWidth: fromWidth - anchors.left: parent.left - anchors.leftMargin: horizontalMargin - Text - { - id: hash - width: parent.width - 30 - elide: Text.ElideRight - anchors.verticalCenter: parent.verticalCenter - maximumLineCount: 1 - color: labelColor - font.pointSize: dbgStyle.absoluteSize(1) - font.bold: true - text: { - if (index >= 0) - return clientModel.resolveAddress(transactions.get(index).sender) - else - return "" - } - } - } - - Rectangle - { - Layout.preferredWidth: toWidth - Text - { - id: func - text: { - if (index >= 0) - parent.parent.userFrienldyToken(transactions.get(index).label) - else - return "" - } - elide: Text.ElideRight - anchors.verticalCenter: parent.verticalCenter - color: labelColor - font.pointSize: dbgStyle.absoluteSize(1) - font.bold: true - maximumLineCount: 1 - width: parent.width - } - } - - function userFrienldyToken(value) - { - if (value && value.indexOf("<") === 0) - { - if (value.split("> ")[1] === " - ") - return value.split(" - ")[0].replace("<", "") - else - return value.split(" - ")[0].replace("<", "") + "." + value.split("> ")[1] + "()"; - } - else - return value - } - } - } - - Rectangle - { - width: debugActionWidth - height: trHeight - 10 - anchors.right: rowContentTr.right - anchors.top: rowContentTr.top - anchors.rightMargin: 10 - color: "transparent" - - Image { - id: debugImg - source: "qrc:/qml/img/rightarrowcircle.png" - width: debugActionWidth - fillMode: Image.PreserveAspectFit - anchors.horizontalCenter: parent.horizontalCenter - visible: transactions.get(index).recordIndex !== undefined - } - MouseArea - { - anchors.fill: parent - onClicked: - { - if (transactions.get(index).recordIndex !== undefined) - { - debugTrRequested = [ blockIndex, index ] - clientModel.debugRecord(transactions.get(index).recordIndex); - } - } - } - } - } - } -} - diff --git a/mix/qml/BlockChain.qml b/mix/qml/BlockChain.qml deleted file mode 100644 index 26a128e90..000000000 --- a/mix/qml/BlockChain.qml +++ /dev/null @@ -1,664 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.QEther 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "js/TransactionHelper.js" as TransactionHelper -import "js/QEtherHelper.js" as QEtherHelper -import "." - -ColumnLayout { - id: blockChainPanel - property alias trDialog: transactionDialog - property alias blockChainRepeater: blockChainRepeater - property variant model - property int scenarioIndex - property var states: ({}) - spacing: 0 - property int previousWidth - property variant debugTrRequested: [] - signal chainChanged(var blockIndex, var txIndex, var item) - signal chainReloaded - signal txSelected(var blockIndex, var txIndex) - signal rebuilding - signal accountAdded(string address, string amount) - - Connections - { - target: projectModel.stateListModel - onAccountsValidated: - { - if (rebuild.accountsSha3 !== codeModel.sha3(JSON.stringify(_accounts))) - rebuild.needRebuild("AccountsChanged") - else - rebuild.notNeedRebuild("AccountsChanged") - } - onContractsValidated: - { - if (rebuild.contractsSha3 !== codeModel.sha3(JSON.stringify(_contracts))) - rebuild.needRebuild("ContractsChanged") - else - rebuild.notNeedRebuild("ContractsChanged") - } - } - - Connections - { - target: codeModel - onContractRenamed: { - rebuild.needRebuild("ContractRenamed") - } - onNewContractCompiled: { - rebuild.needRebuild("NewContractCompiled") - } - onCompilationComplete: { - for (var c in rebuild.contractsHex) - { - if (codeModel.contracts[c] === undefined || codeModel.contracts[c].codeHex !== rebuild.contractsHex[c]) - { - if (!rebuild.containsRebuildCause("CodeChanged")) - { - rebuild.needRebuild("CodeChanged") - } - return - } - } - rebuild.notNeedRebuild("CodeChanged") - } - } - - - onChainChanged: { - if (rebuild.txSha3[blockIndex][txIndex] !== codeModel.sha3(JSON.stringify(model.blocks[blockIndex].transactions[txIndex]))) - { - rebuild.txChanged.push(rebuild.txSha3[blockIndex][txIndex]) - rebuild.needRebuild("txChanged") - } - else { - for (var k in rebuild.txChanged) - { - if (rebuild.txChanged[k] === rebuild.txSha3[blockIndex][txIndex]) - { - rebuild.txChanged.splice(k, 1) - break - } - } - if (rebuild.txChanged.length === 0) - rebuild.notNeedRebuild("txChanged") - } - } - - onWidthChanged: - { - var minWidth = scenarioMinWidth - 20 // margin - if (width <= minWidth || previousWidth <= minWidth) - { - fromWidth = 250 - toWidth = 240 - } - else - { - var diff = (width - previousWidth) / 3; - fromWidth = fromWidth + diff < 250 ? 250 : fromWidth + diff - toWidth = toWidth + diff < 240 ? 240 : toWidth + diff - } - previousWidth = width - } - - function getState(record) - { - return states[record] - } - - function load(scenario, index) - { - if (!scenario) - return; - if (model) - rebuild.startBlinking() - model = scenario - scenarioIndex = index - genesis.scenarioIndex = index - states = [] - blockModel.clear() - for (var b in model.blocks) - blockModel.append(model.blocks[b]) - previousWidth = width - } - - property int statusWidth: 30 - property int fromWidth: 250 - property int toWidth: 240 - property int debugActionWidth: 40 - property int horizontalMargin: 10 - property int cellSpacing: 10 - - RowLayout - { - Layout.preferredHeight: 10 - } - - Rectangle - { - Layout.preferredHeight: 500 - Layout.preferredWidth: parent.width - border.color: "#cccccc" - border.width: 2 - color: "white" - ScrollView - { - id: blockChainScrollView - anchors.fill: parent - anchors.topMargin: 8 - ColumnLayout - { - id: blockChainLayout - width: parent.width - spacing: 20 - - Block - { - id: genesis - scenario: blockChainPanel.model - scenarioIndex: scenarioIndex - Layout.preferredWidth: blockChainScrollView.width - Layout.preferredHeight: 60 - blockIndex: -1 - transactions: [] - status: "" - number: -2 - trHeight: 60 - } - - Repeater // List of blocks - { - id: blockChainRepeater - model: blockModel - - function editTx(blockIndex, txIndex) - { - itemAt(blockIndex).editTx(txIndex) - } - - function select(blockIndex, txIndex) - { - itemAt(blockIndex).select(txIndex) - } - - Block - { - Connections - { - target: block - onTxSelected: - { - blockChainPanel.txSelected(index, txIndex) - } - } - id: block - scenario: blockChainPanel.model - Layout.preferredWidth: blockChainScrollView.width - Layout.preferredHeight: - { - return calculateHeight() - } - blockIndex: index - transactions: - { - if (index >= 0) - return blockModel.get(index).transactions - else - return [] - } - transactionModel: - { - if (index >= 0) - return scenario.blocks[index].transactions - else - return [] - } - - status: - { - if (index >= 0) - return blockModel.get(index).status - else - return "" - } - - number: - { - if (index >= 0) - return blockModel.get(index).number - else - return 0 - } - } - } - } - } - } - - ListModel - { - id: blockModel - - function appendBlock(block) - { - blockModel.append(block); - } - - function appendTransaction(tr) - { - blockModel.get(blockModel.count - 1).transactions.append(tr) - } - - function removeTransaction(blockIndex, trIndex) - { - blockModel.get(blockIndex).transactions.remove(trIndex) - } - - function removeLastBlock() - { - blockModel.remove(blockModel.count - 1) - } - - function removeBlock(index) - { - blockModel.remove(index) - } - - function getTransaction(block, tr) - { - return blockModel.get(block).transactions.get(tr) - } - - function setTransaction(blockIndex, trIndex, tr) - { - blockModel.get(blockIndex).transactions.set(trIndex, tr) - } - - function setTransactionProperty(blockIndex, trIndex, propertyName, value) - { - blockModel.get(blockIndex).transactions.set(trIndex, { propertyName: value }) - } - } - - Rectangle - { - Layout.preferredWidth: parent.width - Layout.preferredHeight: 70 - color: "transparent" - RowLayout - { - anchors.horizontalCenter: parent.horizontalCenter - anchors.top: parent.top - anchors.topMargin: 10 - spacing: 20 - - Rectangle { - Layout.preferredWidth: 100 - Layout.preferredHeight: 30 - ScenarioButton { - id: rebuild - text: qsTr("Rebuild") - width: 100 - height: 30 - roundLeft: true - roundRight: true - property variant contractsHex: ({}) - property variant txSha3: ({}) - property variant accountsSha3 - property variant contractsSha3 - property variant txChanged: [] - property var blinkReasons: [] - - function needRebuild(reason) - { - rebuild.startBlinking() - blinkReasons.push(reason) - } - - function containsRebuildCause(reason) - { - for (var c in blinkReasons) - { - if (blinkReasons[c] === reason) - return true - } - return false - } - - - function notNeedRebuild(reason) - { - for (var c in blinkReasons) - { - if (blinkReasons[c] === reason) - { - blinkReasons.splice(c, 1) - break - } - } - if (blinkReasons.length === 0) - rebuild.stopBlinking() - } - - onClicked: - { - if (ensureNotFuturetime.running) - return; - rebuilding() - stopBlinking() - states = [] - var retBlocks = []; - var bAdded = 0; - for (var j = 0; j < model.blocks.length; j++) - { - var b = model.blocks[j]; - var block = { - hash: b.hash, - number: b.number, - transactions: [], - status: b.status - } - for (var k = 0; k < model.blocks[j].transactions.length; k++) - { - if (blockModel.get(j).transactions.get(k).saveStatus) - { - var tr = model.blocks[j].transactions[k] - tr.saveStatus = true - block.transactions.push(tr); - } - - } - if (block.transactions.length > 0) - { - bAdded++ - block.number = bAdded - block.status = "mined" - retBlocks.push(block) - } - } - if (retBlocks.length === 0) - retBlocks.push(projectModel.stateListModel.createEmptyBlock()) - else - { - var last = retBlocks[retBlocks.length - 1] - last.number = -1 - last.status = "pending" - } - - model.blocks = retBlocks - blockModel.clear() - for (var j = 0; j < model.blocks.length; j++) - blockModel.append(model.blocks[j]) - - ensureNotFuturetime.start() - takeCodeSnapshot() - takeTxSnaphot() - takeAccountsSnapshot() - takeContractsSnapShot() - blinkReasons = [] - clientModel.setupScenario(model); - } - - function takeContractsSnapShot() - { - contractsSha3 = codeModel.sha3(JSON.stringify(model.contracts)) - } - - function takeAccountsSnapshot() - { - accountsSha3 = codeModel.sha3(JSON.stringify(model.accounts)) - } - - function takeCodeSnapshot() - { - contractsHex = {} - for (var c in codeModel.contracts) - contractsHex[c] = codeModel.contracts[c].codeHex - } - - function takeTxSnaphot() - { - txSha3 = {} - txChanged = [] - for (var j = 0; j < model.blocks.length; j++) - { - for (var k = 0; k < model.blocks[j].transactions.length; k++) - { - if (txSha3[j] === undefined) - txSha3[j] = {} - txSha3[j][k] = codeModel.sha3(JSON.stringify(model.blocks[j].transactions[k])) - } - } - } - - buttonShortcut: "" - sourceImg: "qrc:/qml/img/recycleicon@2x.png" - } - } - - - Rectangle - { - Layout.preferredWidth: 200 - Layout.preferredHeight: 30 - color: "transparent" - - ScenarioButton { - id: addTransaction - text: qsTr("Add Tx") - onClicked: - { - if (model && model.blocks) - { - var lastBlock = model.blocks[model.blocks.length - 1]; - if (lastBlock.status === "mined") - { - var newblock = projectModel.stateListModel.createEmptyBlock() - blockModel.appendBlock(newblock) - model.blocks.push(newblock); - } - - var item = TransactionHelper.defaultTransaction() - transactionDialog.stateAccounts = model.accounts - transactionDialog.execute = true - transactionDialog.editMode = false - transactionDialog.open(model.blocks[model.blocks.length - 1].transactions.length, model.blocks.length - 1, item) - } - } - width: 100 - height: 30 - buttonShortcut: "" - sourceImg: "qrc:/qml/img/sendtransactionicon@2x.png" - roundLeft: true - roundRight: false - } - - Timer - { - id: ensureNotFuturetime - interval: 1000 - repeat: false - running: false - } - - Rectangle - { - width: 1 - height: parent.height - anchors.right: addBlockBtn.left - color: "#ededed" - } - - ScenarioButton { - id: addBlockBtn - text: qsTr("Add Block...") - anchors.left: addTransaction.right - roundLeft: false - roundRight: true - onClicked: - { - if (ensureNotFuturetime.running) - return - if (clientModel.mining || clientModel.running) - return - if (model.blocks.length > 0) - { - var lastBlock = model.blocks[model.blocks.length - 1] - if (lastBlock.status === "pending") - { - ensureNotFuturetime.start() - clientModel.mine() - } - else - addNewBlock() - } - else - addNewBlock() - } - - function addNewBlock() - { - var block = projectModel.stateListModel.createEmptyBlock() - model.blocks.push(block) - blockModel.appendBlock(block) - } - width: 100 - height: 30 - - buttonShortcut: "" - sourceImg: "qrc:/qml/img/newblock@2x.png" - } - } - - - Connections - { - target: clientModel - onNewBlock: - { - if (!clientModel.running) - { - var lastBlock = model.blocks[model.blocks.length - 1] - lastBlock.status = "mined" - lastBlock.number = model.blocks.length - var lastB = blockModel.get(model.blocks.length - 1) - lastB.status = "mined" - lastB.number = model.blocks.length - addBlockBtn.addNewBlock() - } - } - onStateCleared: - { - } - onNewRecord: - { - var blockIndex = parseInt(_r.transactionIndex.split(":")[0]) - 1 - var trIndex = parseInt(_r.transactionIndex.split(":")[1]) - if (blockIndex <= model.blocks.length - 1) - { - var item = model.blocks[blockIndex] - if (trIndex <= item.transactions.length - 1) - { - var tr = item.transactions[trIndex] - tr.returned = _r.returned - tr.recordIndex = _r.recordIndex - tr.logs = _r.logs - tr.sender = _r.sender - tr.returnParameters = _r.returnParameters - var trModel = blockModel.getTransaction(blockIndex, trIndex) - trModel.returned = _r.returned - trModel.recordIndex = _r.recordIndex - trModel.logs = _r.logs - trModel.sender = _r.sender - trModel.returnParameters = _r.returnParameters - blockModel.setTransaction(blockIndex, trIndex, trModel) - blockChainRepeater.select(blockIndex, trIndex) - return; - } - } - // tr is not in the list. - var itemTr = TransactionHelper.defaultTransaction() - itemTr.saveStatus = false - itemTr.functionId = _r.function - itemTr.contractId = _r.contract - itemTr.gasAuto = true - itemTr.parameters = _r.parameters - itemTr.isContractCreation = itemTr.functionId === itemTr.contractId - itemTr.label = _r.label - itemTr.isFunctionCall = itemTr.functionId !== "" && itemTr.functionId !== "" - itemTr.returned = _r.returned - itemTr.value = QEtherHelper.createEther(_r.value, QEther.Wei) - itemTr.sender = _r.sender - itemTr.recordIndex = _r.recordIndex - itemTr.logs = _r.logs - itemTr.returnParameters = _r.returnParameters - model.blocks[model.blocks.length - 1].transactions.push(itemTr) - blockModel.appendTransaction(itemTr) - blockChainRepeater.select(blockIndex, trIndex) - } - - onNewState: { - states[_record] = _accounts - } - - onMiningComplete: - { - } - } - - ScenarioButton { - id: newAccount - text: qsTr("New Account...") - onClicked: { - var ac = projectModel.stateListModel.newAccount("O", QEther.Wei) - model.accounts.push(ac) - clientModel.addAccount(ac.secret); - for (var k in Object.keys(blockChainPanel.states)) - blockChainPanel.states[k].accounts["0x" + ac.address] = "0 wei" // add the account in all the previous state (balance at O) - accountAdded("0x" + ac.address, "0") - } - Layout.preferredWidth: 100 - Layout.preferredHeight: 30 - buttonShortcut: "" - sourceImg: "qrc:/qml/img/newaccounticon@2x.png" - roundLeft: true - roundRight: true - } - } - } - - TransactionDialog { - id: transactionDialog - property bool execute - onAccepted: { - var item = transactionDialog.getItem() - if (execute) - { - var lastBlock = model.blocks[model.blocks.length - 1]; - if (lastBlock.status === "mined") - { - var newBlock = projectModel.stateListModel.createEmptyBlock(); - model.blocks.push(newBlock); - blockModel.appendBlock(newBlock) - } - if (!clientModel.running) - clientModel.executeTr(item) - } - else { - model.blocks[blockIndex].transactions[transactionIndex] = item - blockModel.setTransaction(blockIndex, transactionIndex, item) - chainChanged(blockIndex, transactionIndex, item) - } - } - } -} - - diff --git a/mix/qml/CallStack.qml b/mix/qml/CallStack.qml deleted file mode 100644 index 9a938078c..000000000 --- a/mix/qml/CallStack.qml +++ /dev/null @@ -1,73 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Layouts 1.1 - -DebugInfoList -{ - id: callStack - collapsible: true - title : qsTr("Call Stack") - enableSelection: true - itemDelegate: - Item { - anchors.fill: parent - - Rectangle { - anchors.fill: parent - color: "#4A90E2" - visible: styleData.selected; - } - - RowLayout - { - id: row - anchors.fill: parent - Rectangle - { - color: "#f7f7f7" - Layout.fillWidth: true - Layout.minimumWidth: 30 - Layout.maximumWidth: 30 - Text { - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - font.family: "monospace" - anchors.leftMargin: 5 - color: "#4a4a4a" - text: styleData.row; - font.pointSize: dbgStyle.general.basicFontSize - width: parent.width - 5 - elide: Text.ElideRight - } - } - Rectangle - { - color: "transparent" - Layout.fillWidth: true - Layout.minimumWidth: parent.width - 30 - Layout.maximumWidth: parent.width - 30 - Text { - anchors.leftMargin: 5 - width: parent.width - 5 - wrapMode: Text.NoWrap - anchors.left: parent.left - font.family: "monospace" - anchors.verticalCenter: parent.verticalCenter - color: "#4a4a4a" - text: styleData.value; - elide: Text.ElideRight - font.pointSize: dbgStyle.general.basicFontSize - } - } - } - - Rectangle { - anchors.top: row.bottom - width: parent.width; - height: 1; - color: "#cccccc" - anchors.bottom: parent.bottom - } - } -} diff --git a/mix/qml/CodeEditor.qml b/mix/qml/CodeEditor.qml deleted file mode 100644 index 25f76b701..000000000 --- a/mix/qml/CodeEditor.qml +++ /dev/null @@ -1,89 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Controls.Styles 1.1 -import "." - -Item { - signal editorTextChanged - - function setText(text) { - codeEditor.text = text; - } - - function getText() { - return codeEditor.text; - } - - function setFocus() { - codeEditor.forceActiveFocus(); - } - - anchors.fill: parent - id: contentView - width: parent.width - height: parent.height * 0.7 - - CodeEditorStyle { - id: style - } - - Rectangle { - id: lineColumn - property int rowHeight: codeEditor.font.pixelSize + 3 - color: "#202020" - width: 50 - height: parent.height - Column { - y: -codeEditor.flickableItem.contentY + 4 - width: parent.width - Repeater { - model: Math.max(codeEditor.lineCount + 2, (lineColumn.height/lineColumn.rowHeight)) - delegate: Text { - id: text - color: codeEditor.textColor - font: codeEditor.font - width: lineColumn.width - 4 - horizontalAlignment: Text.AlignRight - verticalAlignment: Text.AlignVCenter - height: lineColumn.rowHeight - renderType: Text.NativeRendering - text: index + 1 - } - } - } - } - - TextArea { - id: codeEditor - textColor: "#EEE8D5" - style: TextAreaStyle { - backgroundColor: "#002B36" - } - - anchors.left: lineColumn.right - anchors.right: parent.right - anchors.top: parent.top - anchors.bottom: parent.bottom - wrapMode: TextEdit.NoWrap - frameVisible: false - - height: parent.height - font.family: "Monospace" - font.pointSize: style.general.basicFontSize - width: parent.width - - tabChangesFocus: false - Keys.onPressed: { - if (event.key === Qt.Key_Tab) { - codeEditor.insert(codeEditor.cursorPosition, "\t"); - event.accepted = true; - } - } - onTextChanged: { - editorTextChanged(); - } - - } -} diff --git a/mix/qml/CodeEditorStyle.qml b/mix/qml/CodeEditorStyle.qml deleted file mode 100644 index 999054d55..000000000 --- a/mix/qml/CodeEditorStyle.qml +++ /dev/null @@ -1,13 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property int basicFontSize: absoluteSize(1) - } -} diff --git a/mix/qml/CodeEditorView.qml b/mix/qml/CodeEditorView.qml deleted file mode 100644 index 774a3b11f..000000000 --- a/mix/qml/CodeEditorView.qml +++ /dev/null @@ -1,387 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Dialogs 1.1 -import Qt.labs.settings 1.0 - -Item { - id: codeEditorView - property string currentDocumentId: "" - property string sourceInError - property int openDocCount: 0 - signal documentEdit(string documentId) - signal breakpointsChanged(string documentId) - signal isCleanChanged(var isClean, string documentId) - signal loadComplete - - function getDocumentText(documentId) { - for (var i = 0; i < openDocCount; i++) { - if (editorListModel.get(i).documentId === documentId) { - return editors.itemAt(i).item.getText(); - } - } - return ""; - } - - function getContracts() - { - var ctr = [] - for (var i = 0; i < openDocCount; i++) - { - if (editorListModel.get(i).isContract) - { - ctr.push(editors.itemAt(i).item) - } - } - return ctr; - } - - function isDocumentOpen(documentId) { - for (var i = 0; i < openDocCount; i++) - if (editorListModel.get(i).documentId === documentId && - editors.itemAt(i).item) - return true; - return false; - } - - function openDocument(document) { - loadDocument(document); - currentDocumentId = document.documentId; - } - - function loadDocument(document) { - for (var i = 0; i < openDocCount; i++) - if (editorListModel.get(i).documentId === document.documentId) - return; //already open - - if (editorListModel.count <= openDocCount) - editorListModel.append(document); - else - { - editorListModel.set(openDocCount, document); - doLoadDocument(editors.itemAt(openDocCount).item, editorListModel.get(openDocCount), false) - loadComplete(); - } - openDocCount++; - } - - function doLoadDocument(editor, document, create) { - var data = fileIo.readFile(document.path); - if (create) - { - editor.onLoadComplete.connect(function() { - codeEditorView.loadComplete(); - }); - editor.onEditorTextChanged.connect(function() { - documentEdit(editor.document.documentId); - if (editor.document.isContract) - codeModel.registerCodeChange(editor.document.documentId, editor.getText()); - }); - editor.onBreakpointsChanged.connect(function() { - if (editor.document.isContract) - breakpointsChanged(editor.document.documentId); - }); - editor.onIsCleanChanged.connect(function() { - isCleanChanged(editor.isClean, editor.document.documentId); - }); - } - editor.document = document; - editor.setFontSize(editorSettings.fontSize); - editor.sourceName = document.documentId; - editor.setText(data, document.syntaxMode); - editor.changeGeneration(); - } - - function getEditor(documentId) { - for (var i = 0; i < openDocCount; i++) - { - if (editorListModel.get(i).documentId === documentId) - return editors.itemAt(i).item; - } - return null; - } - - function highlightExecution(documentId, location) - { - var editor = getEditor(documentId); - if (editor) - { - if (documentId !== location.sourceName) - findAndHightlight(location.start, location.end, location.sourceName) - else - editor.highlightExecution(location); - } - } - - // Execution is not in the current document. Try: - // Open targeted document and hightlight (TODO) or - // Warn user that file is not available - function findAndHightlight(start, end, sourceName) - { - var editor = getEditor(currentDocumentId); - if (editor) - editor.showWarning(qsTr("Currently debugging in " + sourceName + ". Source not available.")); - } - - function editingContract() { - for (var i = 0; i < openDocCount; i++) - if (editorListModel.get(i).documentId === currentDocumentId) - return editorListModel.get(i).isContract; - return false; - } - - function getBreakpoints() { - var bpMap = {}; - for (var i = 0; i < openDocCount; i++) { - var documentId = editorListModel.get(i).documentId; - var editor = editors.itemAt(i).item; - if (editor) { - bpMap[documentId] = editor.getBreakpoints(); - } - } - return bpMap; - } - - function toggleBreakpoint() { - var editor = getEditor(currentDocumentId); - if (editor) - editor.toggleBreakpoint(); - } - - function resetEditStatus(docId) { - var editor = getEditor(docId); - if (editor) - editor.changeGeneration(); - } - - function goToCompilationError() { - if (sourceInError === "") - return; - if (currentDocumentId !== sourceInError) - projectModel.openDocument(sourceInError); - for (var i = 0; i < openDocCount; i++) - { - var doc = editorListModel.get(i); - if (doc.isContract && doc.documentId === sourceInError) - { - var editor = editors.itemAt(i).item; - if (editor) - editor.goToCompilationError(); - break; - } - } - } - - function setFontSize(size) { - if (size <= 10 || size >= 48) - return; - editorSettings.fontSize = size; - for (var i = 0; i < editors.count; i++) - editors.itemAt(i).item.setFontSize(size); - } - - function displayGasEstimation(checked) - { - var editor = getEditor(currentDocumentId); - if (editor) - editor.displayGasEstimation(checked); - } - - Component.onCompleted: projectModel.codeEditor = codeEditorView; - - Connections { - target: codeModel - onCompilationError: { - sourceInError = _firstErrorLoc.source; - } - onCompilationComplete: { - sourceInError = ""; - var gasCosts = codeModel.gasCostByDocumentId(currentDocumentId); - var editor = getEditor(currentDocumentId); - if (editor) - editor.setGasCosts(gasCosts); - } - } - - Connections { - target: projectModel - onDocumentOpened: { - openDocument(document); - } - - onProjectSaving: { - for (var i = 0; i < openDocCount; i++) - { - var doc = editorListModel.get(i); - if (editors.itemAt(i)) - { - var editor = editors.itemAt(i).item; - if (editor) - fileIo.writeFile(doc.path, editor.getText()); - } - } - } - - onProjectSaved: { - if (projectModel.appIsClosing || projectModel.projectIsClosing) - return; - for (var i = 0; i < openDocCount; i++) - { - var doc = editorListModel.get(i); - resetEditStatus(doc.documentId); - } - } - - onProjectClosed: { - currentDocumentId = ""; - openDocCount = 0; - } - - onDocumentSaved: { - resetEditStatus(documentId); - } - - onContractSaved: { - resetEditStatus(documentId); - } - - onDocumentSaving: { - for (var i = 0; i < editorListModel.count; i++) - { - var doc = editorListModel.get(i); - if (doc.path === document.path) - { - fileIo.writeFile(document.path, editors.itemAt(i).item.getText()); - break; - } - } - } - } - - CodeEditorStyle - { - id: style; - } - - MessageDialog - { - id: messageDialog - title: qsTr("File Changed") - text: qsTr("This file has been changed outside of the editor. Do you want to reload it?") - standardButtons: StandardButton.Yes | StandardButton.No - property variant item - property variant doc - onYes: { - doLoadDocument(item, doc, false); - resetEditStatus(doc.documentId); - } - } - - Repeater { - id: editors - model: editorListModel - onItemRemoved: { - item.item.unloaded = true; - } - delegate: Loader { - id: loader - active: false - asynchronous: true - anchors.fill: parent - source: appService.haveWebEngine ? "WebCodeEditor.qml" : "CodeEditor.qml" - visible: (index >= 0 && index < openDocCount && currentDocumentId === editorListModel.get(index).documentId) - property bool changed: false - onVisibleChanged: { - loadIfNotLoaded() - if (visible && item) - { - loader.item.setFocus(); - if (changed) - { - changed = false; - messageDialog.item = loader.item; - messageDialog.doc = editorListModel.get(index); - messageDialog.open(); - } - loader.item.displayGasEstimation(gasEstimationAction.checked); - } - } - Component.onCompleted: { - loadIfNotLoaded() - } - onLoaded: { - doLoadDocument(loader.item, editorListModel.get(index), true) - } - - Connections - { - target: projectModel - onDocumentChanged: { - if (!item) - return; - var current = editorListModel.get(index); - if (documentId === current.documentId) - { - if (currentDocumentId === current.documentId) - { - messageDialog.item = loader.item; - messageDialog.doc = editorListModel.get(index); - messageDialog.open(); - } - else - changed = true - } - } - - onDocumentUpdated: { - var document = projectModel.getDocument(documentId); - for (var i = 0; i < editorListModel.count; i++) - if (editorListModel.get(i).documentId === documentId) - { - editorListModel.set(i, document); - break; - } - } - - onDocumentRemoved: { - for (var i = 0; i < editorListModel.count; i++) - if (editorListModel.get(i).documentId === documentId) - { - editorListModel.remove(i); - openDocCount--; - break; - } - } - } - - function loadIfNotLoaded () { - if (visible && !active) { - active = true; - } - } - } - } - ListModel { - id: editorListModel - } - - Action { - id: increaseFontSize - text: qsTr("Increase Font Size") - shortcut: "Ctrl+=" - onTriggered: setFontSize(editorSettings.fontSize + 1) - } - - Action { - id: decreaseFontSize - text: qsTr("Decrease Font Size") - shortcut: "Ctrl+-" - onTriggered: setFontSize(editorSettings.fontSize - 1) - } - - Settings { - id: editorSettings - property int fontSize: 12; - } -} diff --git a/mix/qml/CommonSeparator.qml b/mix/qml/CommonSeparator.qml deleted file mode 100644 index 6644802c7..000000000 --- a/mix/qml/CommonSeparator.qml +++ /dev/null @@ -1,9 +0,0 @@ -import QtQuick 2.0 -import "." - -Rectangle -{ - height: 1 - color: appStyle.generic.layout.separatorColor -} - diff --git a/mix/qml/DebugBasicInfo.qml b/mix/qml/DebugBasicInfo.qml deleted file mode 100644 index d92390ec2..000000000 --- a/mix/qml/DebugBasicInfo.qml +++ /dev/null @@ -1,33 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 - -RowLayout { - property string titleStr - - function update(_value) - { - currentStepValue.text = _value; - } - - Rectangle { - width: 120 - height: parent.height - color: "#e5e5e5" - Text - { - id: title - font.pixelSize: 12 - anchors.centerIn: parent - color: "#a2a2a2" - font.family: "Sans Serif" - text: titleStr - } - } - Text - { - font.pixelSize: 13 - id: currentStepValue - } -} diff --git a/mix/qml/DebugInfoList.qml b/mix/qml/DebugInfoList.qml deleted file mode 100644 index 9adac7b5c..000000000 --- a/mix/qml/DebugInfoList.qml +++ /dev/null @@ -1,152 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 - -ColumnLayout { - id: root - property string title - property variant listModel; - property bool collapsible; - property bool collapsed; - property bool enableSelection: false; - property real storedHeight: 0; - property Component itemDelegate - property Component componentDelegate - property alias item: loader.item - signal rowActivated(int index) - spacing: 0 - - function collapse() - { - storedHeight = childrenRect.height; - storageContainer.collapse(); - } - - function show() - { - storageContainer.expand(); - } - - Component.onCompleted: - { - if (storageContainer.parent.parent.height === 25) - storageContainer.collapse(); - else - { - if (storageContainer.parent.parent.height === 0) - storageContainer.parent.parent.height = 200; - storageContainer.expand(); - } - } - - RowLayout { - height: 25 - id: header - Image { - source: "img/closedtriangleindicator.png" - width: 15 - height: 15 - id: storageImgArrow - } - - Text { - anchors.left: storageImgArrow.right - color: "#8b8b8b" - text: title - id: storageListTitle - } - - MouseArea - { - enabled: collapsible - anchors.fill: parent - onClicked: { - if (collapsible) - { - if (collapsed) - { - storageContainer.expand(); - if (storedHeight <= 25) - storedHeight = 200; - storageContainer.parent.parent.height = storedHeight; - } - else - { - storedHeight = root.childrenRect.height; - storageContainer.collapse(); - } - } - } - } - } - Rectangle - { - id: storageContainer - border.width: 3 - border.color: "#deddd9" - Layout.fillWidth: true - Layout.fillHeight: true - - function collapse() { - storageImgArrow.source = "qrc:/qml/img/closedtriangleindicator.png"; - if (storageContainer.parent.parent.height > 25) - storageContainer.parent.parent.height = 25; - collapsed = true; - } - - function expand() { - storageImgArrow.source = "qrc:/qml/img/opentriangleindicator.png"; - collapsed = false; - } - - Loader - { - id: loader - anchors.top: parent.top - anchors.left: parent.left - anchors.topMargin: 3 - anchors.leftMargin: 3 - width: parent.width - 3 - height: parent.height - 6 - onHeightChanged: { - if (height <= 0 && collapsible) { - storageContainer.collapse(); - } - else if (height > 0 && collapsed) { - storageContainer.expand(); - } - } - - sourceComponent: componentDelegate ? componentDelegate : table - } - Component - { - id: table - TableView - { - clip: true; - alternatingRowColors: false - anchors.fill: parent - model: listModel - selectionMode: enableSelection ? SelectionMode.SingleSelection : SelectionMode.NoSelection - headerDelegate: null - itemDelegate: root.itemDelegate - onActivated: rowActivated(row); - Keys.onPressed: { - if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_C && currentRow >=0 && currentRow < listModel.length) { - var str = ""; - for (var i = 0; i < listModel.length; i++) - str += listModel[i] + "\n"; - clipboard.text = str; - } - } - - TableViewColumn { - role: "modelData" - width: parent.width - } - } - } - } -} diff --git a/mix/qml/Debugger.qml b/mix/qml/Debugger.qml deleted file mode 100644 index 0b833c4de..000000000 --- a/mix/qml/Debugger.qml +++ /dev/null @@ -1,671 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "." - -Rectangle { - id: debugPanel - - property alias debugSlider: statesSlider - property alias solLocals: solLocals - property alias solStorage: solStorage - property alias solCallStack: solCallStack - property alias vmCallStack: callStack - property alias vmStorage: storage - property alias vmMemory: memoryDump - property alias vmCallData: callDataDump - signal debugExecuteLocation(string documentId, var location) - property string compilationErrorMessage - property bool assemblyMode: false - signal panelClosed - objectName: "debugPanel" - color: "#ededed" - clip: true - - onVisibleChanged: - { - if (visible) - forceActiveFocus(); - } - - onAssemblyModeChanged: - { - Debugger.updateMode(); - machineStates.updateHeight(); - } - - function setTr(tr) - { - trName.text = tr.label - } - - function displayCompilationErrorIfAny() - { - debugScrollArea.visible = false; - compilationErrorArea.visible = true; - machineStates.visible = false; - var errorInfo = ErrorLocationFormater.extractErrorInfo(compilationErrorMessage, false); - errorLocation.text = errorInfo.errorLocation; - errorDetail.text = errorInfo.errorDetail; - errorLine.text = errorInfo.line; - } - - function update(data, giveFocus) - { - if (data === null) - Debugger.init(null); - else if (data.states.length === 0) - Debugger.init(null); - else if (codeModel.hasContract) - { - Debugger.init(data); - debugScrollArea.visible = true; - machineStates.visible = true; - } - if (giveFocus) - forceActiveFocus(); - } - - function setBreakpoints(bp) - { - Debugger.setBreakpoints(bp); - } - - DebuggerPaneStyle { - id: dbgStyle - } - - Connections { - target: clientModel - onDebugDataReady: { - update(_debugData, false); - } - } - - Connections { - target: codeModel - onCompilationComplete: { - debugPanel.compilationErrorMessage = ""; - } - - onCompilationError: { - debugPanel.compilationErrorMessage = _error; - } - } - - Settings { - id: splitSettings - property alias callStackHeight: callStackRect.height - property alias storageHeightSettings: storageRect.height - property alias memoryDumpHeightSettings: memoryRect.height - property alias callDataHeightSettings: callDataRect.height - property alias solCallStackHeightSettings: solStackRect.height - property alias solStorageHeightSettings: solStorageRect.height - property alias solLocalsHeightSettings: solLocalsRect.height - } - - ColumnLayout { - id: debugScrollArea - anchors.fill: parent - spacing: 0 - RowLayout - { - Layout.preferredWidth: parent.width - Layout.preferredHeight: 30 - Rectangle - { - Layout.preferredWidth: parent.width - Layout.preferredHeight: parent.height - color: "transparent" - Text { - anchors.centerIn: parent - text: qsTr("Current Transaction") - } - - Rectangle - { - anchors.left: parent.left - anchors.leftMargin: 10 - width: 30 - height: parent.height - color: "transparent" - anchors.verticalCenter: parent.verticalCenter - Image { - source: "qrc:/qml/img/leftarrow@2x.png" - width: parent.width - fillMode: Image.PreserveAspectFit - anchors.centerIn: parent - } - MouseArea - { - anchors.fill: parent - onClicked: - { - Debugger.init(null); - panelClosed() - } - } - } - } - } - - RowLayout - { - Layout.preferredWidth: parent.width - Layout.preferredHeight: 30 - Rectangle - { - Layout.preferredWidth: parent.width - Layout.preferredHeight: parent.height - color: "#2C79D3" - Text { - id: trName - color: "white" - anchors.centerIn: parent - } - } - } - - ScrollView - { - property int sideMargin: 10 - id: machineStates - Layout.fillWidth: true - Layout.fillHeight: true - function updateHeight() { - var h = buttonRow.childrenRect.height; - if (assemblyMode) - h += assemblyCodeRow.childrenRect.height + callStackRect.childrenRect.height + storageRect.childrenRect.height + memoryRect.childrenRect.height + callDataRect.childrenRect.height; - else - h += solStackRect.childrenRect.height + solLocalsRect.childrenRect.height + solStorageRect.childrenRect.height; - statesLayout.height = h + 120; - } - - Component.onCompleted: updateHeight(); - - ColumnLayout { - id: statesLayout - anchors.top: parent.top - anchors.topMargin: 15 - anchors.left: parent.left; - anchors.leftMargin: machineStates.sideMargin - width: debugScrollArea.width - machineStates.sideMargin * 2 - 20 - spacing: machineStates.sideMargin - - Rectangle { - // step button + slider - id: buttonRow - height: 30 - Layout.fillWidth: true - color: "transparent" - - Rectangle { - anchors.fill: parent - color: "transparent" - RowLayout { - anchors.fill: parent - id: jumpButtons - spacing: 3 - layoutDirection: Qt.LeftToRight - - StepActionImage - { - id: runBackAction; - enabledStateImg: "qrc:/qml/img/jumpoutback.png" - disableStateImg: "qrc:/qml/img/jumpoutbackdisabled.png" - onClicked: Debugger.runBack() - width: 23 - buttonShortcut: "Ctrl+Shift+F5" - buttonTooltip: qsTr("Run Back") - visible: false - } - - StepActionImage - { - id: jumpOutBackAction; - enabledStateImg: "qrc:/qml/img/jumpoutback.png" - disableStateImg: "qrc:/qml/img/jumpoutbackdisabled.png" - onClicked: Debugger.stepOutBack() - width: 23 - buttonShortcut: "Ctrl+Shift+F11" - buttonTooltip: qsTr("Step Out Back") - } - - StepActionImage - { - id: jumpIntoBackAction - enabledStateImg: "qrc:/qml/img/jumpintoback.png" - disableStateImg: "qrc:/qml/img/jumpintobackdisabled.png" - onClicked: Debugger.stepIntoBack() - width: 23 - buttonShortcut: "Ctrl+F11" - buttonTooltip: qsTr("Step Into Back") - } - - StepActionImage - { - id: jumpOverBackAction - enabledStateImg: "qrc:/qml/img/jumpoverback.png" - disableStateImg: "qrc:/qml/img/jumpoverbackdisabled.png" - onClicked: Debugger.stepOverBack() - width: 23 - buttonShortcut: "Ctrl+F10" - buttonTooltip: qsTr("Step Over Back") - } - - StepActionImage - { - id: jumpOverForwardAction - enabledStateImg: "qrc:/qml/img/jumpoverforward.png" - disableStateImg: "qrc:/qml/img/jumpoverforwarddisabled.png" - onClicked: Debugger.stepOverForward() - width: 23 - buttonShortcut: "F10" - buttonTooltip: qsTr("Step Over Forward") - } - - StepActionImage - { - id: jumpIntoForwardAction - enabledStateImg: "qrc:/qml/img/jumpintoforward.png" - disableStateImg: "qrc:/qml/img/jumpintoforwarddisabled.png" - onClicked: Debugger.stepIntoForward() - width: 23 - buttonShortcut: "F11" - buttonTooltip: qsTr("Step Into Forward") - } - - StepActionImage - { - id: jumpOutForwardAction - enabledStateImg: "qrc:/qml/img/jumpoutforward.png" - disableStateImg: "qrc:/qml/img/jumpoutforwarddisabled.png" - onClicked: Debugger.stepOutForward() - width: 45 - buttonShortcut: "Shift+F11" - buttonTooltip: qsTr("Step Out Forward") - buttonRight: true - } - - StepActionImage - { - id: runForwardAction - enabledStateImg: "qrc:/qml/img/jumpoutforward.png" - disableStateImg: "qrc:/qml/img/jumpoutforwarddisabled.png" - onClicked: Debugger.runForward() - width: 45 - buttonShortcut: "Ctrl+F5" - buttonTooltip: qsTr("Run Forward") - visible: false - buttonRight: true - } - - Rectangle { - anchors.top: parent.top - anchors.bottom: parent.bottom - anchors.right: parent.right - color: "transparent" - Layout.fillWidth: true - Layout.minimumWidth: parent.width * 0.2 - Layout.alignment: Qt.AlignRight - - Slider { - id: statesSlider - anchors.fill: parent - tickmarksEnabled: true - stepSize: 1.0 - onValueChanged: Debugger.jumpTo(value); - style: SliderStyle { - groove: Rectangle { - implicitHeight: 3 - color: "#7da4cd" - radius: 8 - } - handle: Rectangle { - anchors.centerIn: parent - color: control.pressed ? "white" : "lightgray" - border.color: "gray" - border.width: 2 - implicitWidth: 10 - implicitHeight: 10 - radius: 12 - } - } - } - } - } - } - } - - Rectangle { - // Assembly code - id: assemblyCodeRow - Layout.fillWidth: true - height: 405 - implicitHeight: 405 - color: "transparent" - visible: assemblyMode - - Rectangle - { - id: stateListContainer - anchors.top : parent.top - anchors.bottom: parent.bottom - anchors.left: parent.left - width: parent.width * 0.4 - height: parent.height - border.width: 3 - border.color: "#deddd9" - color: "white" - TableView { - id: statesList - anchors.fill: parent - anchors.leftMargin: 3 - anchors.rightMargin: 3 - anchors.topMargin: 3 - anchors.bottomMargin: 3 - clip: true - headerDelegate: null - itemDelegate: renderDelegate - model: ListModel {} - TableViewColumn { - role: "line" - width: parent.width - 10 - } - - } - - Component { - id: highlightBar - Rectangle { - radius: 4 - anchors.fill: parent - y: statesList.currentItem.y - color: "#4A90E2" - } - } - - Component { - id: renderDelegate - Item { - Rectangle { - radius: 4 - anchors.fill: parent - color: "#4A90E2" - visible: styleData.selected; - } - - RowLayout { - id: wrapperItem - anchors.fill: parent - spacing: 5 - - - Text { - anchors.left: parent.left - anchors.leftMargin: 10 - width: 15 - color: "#b2b3ae" - text: styleData.value.split(' ')[0] - font.family: "monospace" - font.pointSize: dbgStyle.general.basicFontSize - wrapMode: Text.NoWrap - id: id - } - Text { - anchors.left: id.right; - wrapMode: Text.NoWrap - color: styleData.selected ? "white" : "black" - font.family: "monospace" - text: styleData.value.replace(styleData.value.split(' ')[0], '') - font.pointSize: dbgStyle.general.basicFontSize - } - } - } - } - } - - Rectangle { - id: debugInfoContainer - width: parent.width * 0.6 - machineStates.sideMargin - anchors.top : parent.top - anchors.bottom: parent.bottom - anchors.right: parent.right - height: parent.height - color: "transparent" - ColumnLayout - { - width: parent.width - anchors.fill: parent - spacing: 0 - DebugBasicInfo { - id: currentStep - titleStr: qsTr("Current Step") - Layout.fillWidth: true - height: 30 - } - DebugBasicInfo { - id: mem - titleStr: qsTr("Adding Memory") - Layout.fillWidth: true - height: 30 - } - DebugBasicInfo { - id: stepCost - titleStr: qsTr("Step Cost") - Layout.fillWidth: true - height: 30 - } - DebugBasicInfo { - id: gasSpent - titleStr: qsTr("Total Gas Spent") - Layout.fillWidth: true - height: 30 - } - DebugInfoList - { - Layout.fillHeight: true - Layout.fillWidth: true - id: stack - collapsible: false - title : qsTr("Stack") - itemDelegate: Item { - id: renderedItem - width: parent.width - RowLayout - { - anchors.fill: parent - Rectangle - { - id: indexColumn - color: "#f7f7f7" - Layout.fillWidth: true - Layout.minimumWidth: 30 - Layout.preferredWidth: 30 - Layout.maximumWidth: 30 - Layout.minimumHeight: parent.height - Text { - anchors.centerIn: parent - anchors.leftMargin: 5 - font.family: "monospace" - color: "#4a4a4a" - text: styleData.row; - font.pointSize: dbgStyle.general.basicFontSize - } - } - - Rectangle - { - anchors.left: indexColumn.right - Layout.fillWidth: true - Layout.minimumWidth: 15 - Layout.preferredWidth: 15 - Layout.minimumHeight: parent.height - Text { - anchors.left: parent.left - anchors.leftMargin: 5 - font.family: "monospace" - anchors.verticalCenter: parent.verticalCenter - color: "#4a4a4a" - text: styleData.value - font.pointSize: dbgStyle.general.basicFontSize - } - } - } - - Rectangle { - id: separator - width: parent.width; - height: 1; - color: "#cccccc" - anchors.bottom: parent.bottom - } - } - } - } - } - } - - SplitView - { - id: splitInfoList - Layout.fillHeight: true - Layout.fillWidth: true - orientation: Qt.Vertical - - Rectangle - { - id: solStackRect; - color: "transparent" - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: !assemblyMode - CallStack { - anchors.fill: parent - id: solCallStack - } - } - - Rectangle - { - id: solLocalsRect; - color: "transparent" - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: !assemblyMode - VariablesView { - title : qsTr("Locals") - anchors.fill: parent - id: solLocals - } - } - - Rectangle - { - id: solStorageRect; - color: "transparent" - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: !assemblyMode - VariablesView { - title : qsTr("Members") - anchors.fill: parent - id: solStorage - } - } - - Rectangle - { - id: callStackRect; - color: "transparent" - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: assemblyMode - CallStack { - anchors.fill: parent - id: callStack - onRowActivated: Debugger.displayFrame(index); - } - } - - Rectangle - { - id: storageRect - color: "transparent" - width: parent.width - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: assemblyMode - StorageView { - anchors.fill: parent - id: storage - } - } - - Rectangle - { - id: memoryRect; - color: "transparent" - width: parent.width - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: assemblyMode - DebugInfoList { - id: memoryDump - anchors.fill: parent - collapsible: true - title: qsTr("Memory Dump") - itemDelegate: - Item { - height: 29 - width: parent.width - 3; - ItemDelegateDataDump {} - } - } - } - - Rectangle - { - id: callDataRect - color: "transparent" - width: parent.width - Layout.minimumHeight: 25 - Layout.maximumHeight: 800 - onHeightChanged: machineStates.updateHeight(); - visible: assemblyMode - DebugInfoList { - id: callDataDump - anchors.fill: parent - collapsible: true - title: qsTr("Call Data") - itemDelegate: - Item { - height: 29 - width: parent.width - 3; - ItemDelegateDataDump {} - } - } - } - Rectangle - { - id: bottomRect; - width: parent.width - Layout.minimumHeight: 20 - color: "transparent" - } - } - } - } - } -} diff --git a/mix/qml/DebuggerPaneStyle.qml b/mix/qml/DebuggerPaneStyle.qml deleted file mode 100644 index 0087b466f..000000000 --- a/mix/qml/DebuggerPaneStyle.qml +++ /dev/null @@ -1,16 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property int basicFontSize: absoluteSize(-2) - property string basicColor: "#4a4a4a" - property string basicFont: "monospace" - property int dataDumpFontSize: absoluteSize(-3) - } -} diff --git a/mix/qml/DefaultLabel.qml b/mix/qml/DefaultLabel.qml deleted file mode 100644 index 5d00df137..000000000 --- a/mix/qml/DefaultLabel.qml +++ /dev/null @@ -1,10 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.1 - -Label { - text: text -} - - - - diff --git a/mix/qml/DefaultTextField.qml b/mix/qml/DefaultTextField.qml deleted file mode 100644 index de306fa5e..000000000 --- a/mix/qml/DefaultTextField.qml +++ /dev/null @@ -1,6 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.1 - -TextField { - id: titleField -} diff --git a/mix/qml/DeployContractStep.qml b/mix/qml/DeployContractStep.qml deleted file mode 100644 index 3bf5c217e..000000000 --- a/mix/qml/DeployContractStep.qml +++ /dev/null @@ -1,540 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.3 -import Qt.labs.settings 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/NetworkDeployment.js" as NetworkDeploymentCode -import "js/QEtherHelper.js" as QEtherHelper -import org.ethereum.qml.QEther 1.0 - -Rectangle { - property variant paramsModel: [] - property variant worker - property variant gas: [] - property alias gasPrice: gasPriceInput - color: "#E3E3E3E3" - signal deployed - anchors.fill: parent - id: root - - property int labelWidth: 150 - property bool verifyDeploy: true - - function show() - { - visible = true - contractList.currentIndex = 0 - contractList.change() - accountsModel.clear() - for (var k in worker.accounts) - accountsModel.append(worker.accounts[k]) - - if (worker.currentAccount === "" && worker.accounts.length > 0) - { - worker.currentAccount = worker.accounts[0].id - accountsList.currentIndex = 0 - } - - verifyDeployedContract() - deployedAddresses.refresh() - - worker.renewCtx() - verifyDeploy = true - worker.pooler.onTriggered.connect(function() { - if (root.visible && verifyDeploy) - verifyDeployedContract(); - }) - } - - function verifyDeployedContract() - { - if (projectModel.deployBlockNumber !== -1) - { - worker.verifyHashes(projectModel.deploymentTrHashes, function (bn, trLost) - { - root.updateVerification(bn, trLost) - }); - } - } - - function updateVerification(blockNumber, trLost) - { - var nb = parseInt(blockNumber - projectModel.deployBlockNumber) - verificationTextArea.visible = false - verificationLabel.visible = true - if (nb >= 10) - { - verificationLabel.text = qsTr("contracts deployment verified") - verificationLabel.color = "green" - } - else - { - verificationLabel.text = nb - if (trLost.length > 0) - { - verifyDeploy = false - verificationTextArea.visible = true - verificationLabel.visible = false - verificationTextArea.text = "" - deploymentStepChanged("following transactions are invalidated:") - verificationTextArea.text += "\n" + qsTr("Transactions lost") + "\n" - verificationTextArea.textColor = "red" - for (var k in trLost) - { - deploymentStepChanged(trLost[k]) - verificationTextArea.text += trLost[k] + "\n" - } - } - } - } - - RowLayout - { - anchors.fill: parent - anchors.margins: 10 - ColumnLayout - { - anchors.top: parent.top - Layout.preferredWidth: parent.width * 0.40 - 20 - Layout.fillHeight: true - id: scenarioList - - Label - { - Layout.fillWidth: true - text: qsTr("Pick Scenario to deploy") - } - - ComboBox - { - id: contractList - Layout.preferredWidth: parent.width - 20 - model: projectModel.stateListModel - textRole: "title" - onCurrentIndexChanged: - { - if (root.visible) - change() - } - - function change() - { - trListModel.clear() - if (currentIndex > -1) - { - for (var k = 0; k < projectModel.stateListModel.get(currentIndex).blocks.count; k++) - { - for (var j = 0; j < projectModel.stateListModel.get(currentIndex).blocks.get(k).transactions.count; j++) - trListModel.append(projectModel.stateListModel.get(currentIndex).blocks.get(k).transactions.get(j)); - } - for (var k = 0; k < trListModel.count; k++) - trList.itemAt(k).init() - ctrDeployCtrLabel.calculateContractDeployGas(); - } - } - } - - Rectangle - { - Layout.fillHeight: true - Layout.preferredWidth: parent.width - 20 - id: trContainer - color: "white" - border.color: "#cccccc" - border.width: 1 - ScrollView - { - anchors.fill: parent - horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff - ColumnLayout - { - spacing: 0 - - ListModel - { - id: trListModel - } - - Repeater - { - id: trList - model: trListModel - ColumnLayout - { - Layout.fillWidth: true - spacing: 5 - Layout.preferredHeight: - { - if (index > -1) - return 20 + trListModel.get(index)["parameters"].count * 20 - else - return 20 - } - - function init() - { - paramList.clear() - if (trListModel.get(index).parameters) - { - for (var k in trListModel.get(index).parameters) - paramList.append({ "name": k, "value": trListModel.get(index).parameters[k] }) - } - } - - Label - { - id: trLabel - Layout.preferredHeight: 20 - anchors.left: parent.left - anchors.top: parent.top - anchors.topMargin: 5 - anchors.leftMargin: 10 - text: - { - if (index > -1) - return trListModel.get(index).label - else - return "" - } - } - - ListModel - { - id: paramList - } - - Repeater - { - Layout.preferredHeight: - { - if (index > -1) - return trListModel.get(index)["parameters"].count * 20 - else - return 0 - } - model: paramList - Label - { - Layout.preferredHeight: 20 - anchors.left: parent.left - anchors.leftMargin: 20 - text: name + "=" + value - font.italic: true - } - } - - Rectangle - { - Layout.preferredWidth: scenarioList.width - Layout.preferredHeight: 1 - color: "#cccccc" - } - } - } - } - } - } - } - - ColumnLayout - { - anchors.top: parent.top - Layout.preferredHeight: parent.height - 25 - ColumnLayout - { - anchors.top: parent.top - Layout.preferredWidth: parent.width * 0.60 - Layout.fillHeight: true - id: deploymentOption - spacing: 8 - - Label - { - anchors.left: parent.left - anchors.leftMargin: 105 - text: qsTr("Deployment options") - } - - ListModel - { - id: accountsModel - } - - RowLayout - { - Layout.fillWidth: true - Rectangle - { - width: labelWidth - Label - { - text: qsTr("Account") - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - - ComboBox - { - id: accountsList - textRole: "id" - model: accountsModel - Layout.preferredWidth: 235 - onCurrentTextChanged: - { - worker.currentAccount = currentText - accountBalance.text = worker.balance(currentText).format() - } - } - - Label - { - id: accountBalance - } - } - - RowLayout - { - Layout.fillWidth: true - Rectangle - { - width: labelWidth - Label - { - text: qsTr("Gas Price") - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - - Ether - { - id: gasPriceInput - displayUnitSelection: true - displayFormattedValue: true - edit: true - - function toHexWei() - { - return "0x" + gasPriceInput.value.toWei().hexValue() - } - } - - Connections - { - target: gasPriceInput - onValueChanged: - { - ctrDeployCtrLabel.calculateContractDeployGas() - } - onAmountChanged: - { - ctrDeployCtrLabel.setCost() - } - onUnitChanged: - { - ctrDeployCtrLabel.setCost() - } - } - - Connections - { - target: worker - id: gasPriceLoad - property bool loaded: false - onGasPriceLoaded: - { - gasPriceInput.value = QEtherHelper.createEther(worker.gasPriceInt.value(), QEther.Wei) - gasPriceLoad.loaded = true - ctrDeployCtrLabel.calculateContractDeployGas() - } - } - } - - RowLayout - { - id: ctrDeployCtrLabel - Layout.fillWidth: true - property int cost - function calculateContractDeployGas() - { - if (!root.visible) - return; - var sce = projectModel.stateListModel.getState(contractList.currentIndex) - worker.estimateGas(sce, function(gas) { - if (gasPriceLoad.loaded) - { - root.gas = gas - cost = 0 - for (var k in gas) - cost += gas[k] - setCost() - } - }); - } - - function setCost() - { - var ether = QEtherHelper.createBigInt(cost); - var gasTotal = ether.multiply(gasPriceInput.value); - gasToUseInput.value = QEtherHelper.createEther(gasTotal.value(), QEther.Wei, parent); - } - - Rectangle - { - width: labelWidth - Label - { - text: qsTr("Deployment Cost") - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - - Ether - { - id: gasToUseInput - displayUnitSelection: false - displayFormattedValue: true - edit: false - Layout.preferredWidth: 350 - } - } - - Rectangle - { - border.color: "#cccccc" - border.width: 2 - Layout.fillWidth: true - Layout.preferredHeight: parent.height + 25 - color: "transparent" - id: rectDeploymentVariable - ScrollView - { - anchors.fill: parent - anchors.topMargin: 4 - anchors.bottomMargin: 4 - ColumnLayout - { - RowLayout - { - id: deployedRow - Layout.fillWidth: true - Rectangle - { - width: labelWidth - Label - { - id: labelAddresses - text: qsTr("Deployed Contracts") - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - - ColumnLayout - { - anchors.top: parent.top - anchors.topMargin: 1 - width: parent.width - id: deployedAddresses - function refresh() - { - textAddresses.text = "" - deployedRow.visible = Object.keys(projectModel.deploymentAddresses).length > 0 - textAddresses.text = JSON.stringify(projectModel.deploymentAddresses, null, ' ') - } - TextArea - { - anchors.fill: parent - id: textAddresses - } - } - } - - RowLayout - { - id: verificationRow - Layout.fillWidth: true - visible: Object.keys(projectModel.deploymentAddresses).length > 0 - Rectangle - { - width: labelWidth - Label - { - text: qsTr("Verifications") - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - - TextArea - { - id: verificationTextArea - visible: false - } - - Label - { - id: verificationLabel - visible: true - } - } - } - } - } - } - - Rectangle - { - Layout.preferredWidth: parent.width - Layout.alignment: Qt.BottomEdge - Button - { - Layout.preferredHeight: 22 - anchors.right: deployBtn.left - text: qsTr("Reset") - action: clearDeployAction - } - - Action { - id: clearDeployAction - onTriggered: { - worker.forceStopPooling() - if (projectModel.deploymentDir && projectModel.deploymentDir !== "") - fileIo.deleteDir(projectModel.deploymentDir) - projectModel.cleanDeploymentStatus() - deploymentDialog.steps.reset() - } - } - - Button - { - id: deployBtn - anchors.right: parent.right - text: qsTr("Deploy Contracts") - onClicked: - { - projectModel.deployedScenarioIndex = contractList.currentIndex - NetworkDeploymentCode.deployContracts(root.gas, gasPriceInput.toHexWei(), function(addresses, trHashes) - { - projectModel.deploymentTrHashes = trHashes - worker.verifyHashes(trHashes, function (nb, trLost) - { - projectModel.deployBlockNumber = nb - projectModel.saveProject() - root.updateVerification(nb, trLost) - root.deployed() - }) - projectModel.deploymentAddresses = addresses - projectModel.saveProject() - deployedAddresses.refresh() - }); - } - } - } - } - } -} - diff --git a/mix/qml/DeploymentDialog.qml b/mix/qml/DeploymentDialog.qml deleted file mode 100644 index b80a823f2..000000000 --- a/mix/qml/DeploymentDialog.qml +++ /dev/null @@ -1,187 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.0 -import QtQuick.Dialogs 1.2 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.QEther 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/NetworkDeployment.js" as NetworkDeploymentCode -import "js/QEtherHelper.js" as QEtherHelper -import "." - - -Dialog { - id: modalDeploymentDialog - modality: Qt.ApplicationModal - width: 1000 - height: 450 - visible: false - - property alias deployStep: deployStep - property alias packageStep: packageStep - property alias registerStep: registerStep - property alias worker: worker - property alias steps: steps - - function close() - { - visible = false; - worker.pooler.running = false - } - - function open() - { - deployStep.visible = false - packageStep.visible = false - registerStep.visible = false - steps.init() - worker.renewCtx() - worker.pooler.running = true - visible = true; - } - - DeploymentWorker - { - id: worker - } - - contentItem: Rectangle { - color: appStyle.generic.layout.backgroundColor - anchors.fill: parent - ColumnLayout - { - spacing: 5 - anchors.fill: parent - anchors.margins: 10 - - Rectangle - { - id: explanation - Layout.preferredWidth: parent.width - 50 - Layout.preferredHeight: 50 - color: "transparent" - Label - { - id: info - anchors.centerIn: parent - text: qsTr("Putting your dapp live is a multi step process. You can read more about it on the") - } - - Text { - anchors.left: info.right - anchors.leftMargin: 7 - id: linkText - text: 'guide to uploading' - onLinkActivated: Qt.openUrlExternally("https://github.com/ethereum/wiki/wiki/Mix:-The-DApp-IDE#deployment-to-network") - anchors.verticalCenter: parent.verticalCenter - MouseArea - { - anchors.fill: parent - cursorShape: Qt.PointingHandCursor - } - } - } - - RowLayout - { - ColumnLayout - { - Layout.preferredHeight: parent.height - 50 - Layout.preferredWidth: 200 - DeploymentDialogSteps - { - id: steps - worker: worker - } - } - - Connections - { - target: steps - property variant selected - onSelected: - { - if (selected) - selected.visible = false - switch (step) - { - case "deploy": - { - selected = deployStep - break; - } - case "package": - { - selected = packageStep - break; - } - case "register": - { - selected = registerStep - break; - } - } - selected.show() - } - } - - ColumnLayout - { - Layout.preferredHeight: parent.height - 50 - Layout.preferredWidth: parent.width - 200 - DeployContractStep - { - id: deployStep - visible: false - worker: worker - } - - PackagingStep - { - id: packageStep - visible: false - worker: worker - } - - RegisteringStep - { - id: registerStep - visible: false - worker: worker - } - } - } - - Rectangle - { - Layout.fillWidth: true - Layout.preferredHeight: 30 - color: "transparent" - Button - { - text: qsTr("Cancel") - anchors.right: parent.right - anchors.rightMargin: 10 - onClicked: - { - modalDeploymentDialog.close() - } - } - } - - } - } - - MessageDialog { - id: deployDialog - standardButtons: StandardButton.Ok - icon: StandardIcon.Warning - } - - MessageDialog { - id: errorDialog - standardButtons: StandardButton.Ok - icon: StandardIcon.Critical - } -} diff --git a/mix/qml/DeploymentDialogSteps.qml b/mix/qml/DeploymentDialogSteps.qml deleted file mode 100644 index 5874d54a8..000000000 --- a/mix/qml/DeploymentDialogSteps.qml +++ /dev/null @@ -1,292 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.3 - -Rectangle { - anchors.fill: parent - color: "white" - property var worker - property variant sel - signal selected(string step) - id: root - - function refreshCurrent() - { - menu.itemAt(sel).select() - } - - function init() - { - menu.itemAt(0).select() - } - - function itemClicked(step) - { - selected(step) - } - - function reset() - { - for (var k in deployLogs.logs) - { - deployLogs.logs[k] = "" - } - deployLogs.switchLogs() - refreshCurrent() - } - - border.color: "#cccccc" - border.width: 1 - - - Connections - { - id: deployStatus - target: deploymentDialog.deployStep - onDeployed: - { - console.log("deployed") - } - } - - Connections - { - id: packagedStatus - target: deploymentDialog.packageStep - onPackaged: - { - console.log("packaged") - } - } - - Connections - { - id: registerStatus - target: deploymentDialog.registerStep - onRegistered: - { - console.log("registered") - } - } - - ColumnLayout - { - anchors.fill: parent - anchors.margins: 1 - spacing: 0 - Repeater - { - id: menu - model: [ - { - step: 1, - type:"deploy", - label: qsTr("Deploy contracts") - }, - { - step: 2, - type:"package", - label: qsTr("Package Dapp") - }, - { - step: 3, - type:"register", - label: qsTr("Register Dapp") - } - ] - - Rectangle - { - Layout.preferredHeight: 50 - Layout.fillWidth: true - color: "white" - id: itemContainer - - function select() - { - if (sel !== undefined) - { - menu.itemAt(sel).unselect() - } - labelContainer.state = "selected" - sel = index - itemClicked(menu.model[index].type) - deployLogs.switchLogs() - } - - function unselect() - { - labelContainer.state = "" - } - - Rectangle { - width: 40 - height: 40 - color: "transparent" - border.color: "#cccccc" - border.width: 2 - radius: width*0.5 - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: 10 - id: labelContainer - Label - { - color: "#cccccc" - id: label - anchors.centerIn: parent - text: menu.model[index].step - } - states: [ - State { - name: "selected" - PropertyChanges { target: label; color: "white" } - PropertyChanges { target: labelContainer.border; color: "white" } - PropertyChanges { target: detail; color: "white" } - PropertyChanges { target: itemContainer; color: "#3395FE" } - } - ] - } - - Rectangle - { - anchors.verticalCenter: parent.verticalCenter - anchors.left: label.parent.right - width: parent.width - 40 - height: 40 - color: "transparent" - Label - { - id: detail - color: "black" - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: 10 - text: menu.model[index].label - } - } - - MouseArea - { - anchors.fill: parent - onClicked: - { - itemContainer.select() - } - } - } - } - - Connections { - property var logs: ({}) - id: deployLogs - - function switchLogs() - { - if (root.sel) - { - if (!logs[root.sel]) - logs[root.sel] = "" - log.text = logs[root.sel] - } - } - - target: projectModel - onDeploymentStarted: - { - if (!logs[root.sel]) - logs[root.sel] = "" - logs[root.sel] = logs[root.sel] + qsTr("Running deployment...") + "\n" - log.text = logs[root.sel] - } - - onDeploymentError: - { - if (!logs[root.sel]) - logs[root.sel] = "" - logs[root.sel] = logs[root.sel] + error + "\n" - log.text = logs[root.sel] - } - - onDeploymentComplete: - { - if (!logs[root.sel]) - logs[root.sel] = "" - logs[root.sel] = logs[root.sel] + qsTr("Deployment complete") + "\n" - log.text = logs[root.sel] - } - - onDeploymentStepChanged: - { - if (!logs[root.sel]) - logs[root.sel] = "" - logs[root.sel] = logs[root.sel] + message + "\n" - log.text = logs[root.sel] - } - } - - Rectangle - { - Layout.fillWidth: true - Layout.preferredHeight: 2 - color: "#cccccc" - } - - ScrollView - { - Layout.fillHeight: true - Layout.fillWidth: true - Text - { - anchors.left: parent.left - anchors.leftMargin: 2 - font.pointSize: 9 - font.italic: true - id: log - } - } - - Rectangle - { - Layout.preferredHeight: 20 - Layout.fillWidth: true - color: "#cccccc" - LogsPaneStyle - { - id: style - } - - Label - { - anchors.horizontalCenter: parent.horizontalCenter - anchors.verticalCenter: parent.verticalCenter - text: qsTr("Logs") - font.italic: true - font.pointSize: style.absoluteSize(-1) - } - - Button - { - height: 20 - width: 20 - anchors.right: parent.right - action: clearAction - iconSource: "qrc:/qml/img/cleariconactive.png" - tooltip: qsTr("Clear Messages") - } - - Action { - id: clearAction - enabled: log.text !== "" - tooltip: qsTr("Clear") - onTriggered: { - deployLogs.logs[root.sel] = "" - log.text = deployLogs.logs[root.sel] - } - } - } - - } -} - diff --git a/mix/qml/DeploymentWorker.qml b/mix/qml/DeploymentWorker.qml deleted file mode 100644 index cf29e3d25..000000000 --- a/mix/qml/DeploymentWorker.qml +++ /dev/null @@ -1,250 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.0 -import QtQuick.Dialogs 1.2 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.QEther 1.0 -import org.ethereum.qml.CodeModel 1.0 -import org.ethereum.qml.ClientModel 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/NetworkDeployment.js" as NetworkDeploymentCode -import "js/QEtherHelper.js" as QEtherHelper -import "." - -Item -{ - property string currentAccount - property string gasPrice - property alias gasPriceInt: gasPriceInt - property variant balances: ({}) - property variant accounts: [] - property alias pooler: pooler - signal gasPriceLoaded() - - function renewCtx() - { - accounts = [] - balances = {} - var requests = [{ - //accounts - jsonrpc: "2.0", - method: "eth_accounts", - params: null, - id: 0 - }]; - - TransactionHelper.rpcCall(requests, function(arg1, arg2) - { - - var ids = JSON.parse(arg2)[0].result; - requests = []; - accounts = [] - for (var k in ids) - { - requests.push({ - //accounts - jsonrpc: "2.0", - method: "eth_getBalance", - params: [ids[k], 'latest'], - id: k - }); - accounts.push({ "id": ids[k] }) - } - - TransactionHelper.rpcCall(requests, function (request, response){ - var balanceRet = JSON.parse(response); - balances = {} - for (var k in balanceRet) - { - var ether = QEtherHelper.createEther(balanceRet[k].result, QEther.Wei); - balances[accounts[k].id] = ether - } - }, function(){}); - }, function(){}); - - NetworkDeploymentCode.gasPrice(function(price) { - gasPrice = price; - gasPriceInt.setValue(price); - gasPriceLoaded() - }, function(){}); - } - - function balance(account) - { - for (var k in accounts) - { - if (accounts[k].id === account) - return balances[account] - } - return null - } - - function stopForInputError(inError) - { - errorDialog.text = ""; - if (inError.length > 0) - { - errorDialog.text = qsTr("The length of a string cannot exceed 32 characters.\nPlease verify the following value(s):\n\n") - for (var k in inError) - errorDialog.text += inError[k] + "\n"; - errorDialog.open(); - return true; - } - return false; - } - - function forceStopPooling() - { - poolLog.stop() - } - - function waitForTrReceipt(hash, callback) - { - poolLog.callBack = callback; - poolLog.hash = hash - poolLog.elapsed = 0; - poolLog.start(); - } - - function verifyHash(tr, hash, callBack) - { - var h = {} - h[tr] = hash - verifyHashes(h, function (bn, trLost) - { - callBack(bn, trLost) - }); - } - - function verifyHashes(trHashes, callback) - { - //trHashes : { "trLabel": 'hash' } - var requests = []; - var req = 0 - requests.push({ - jsonrpc: "2.0", - method: "eth_blockNumber", - params: [], - id: req - }); - var label = [] - for (var k in trHashes) - { - req++ - label[req] = k - requests.push({ - jsonrpc: "2.0", - method: "eth_getTransactionReceipt", - params: [trHashes[k]], - id: req - }); - } - - TransactionHelper.rpcCall(requests, function (httpRequest, response){ - var ret = JSON.parse(response) - var b = ret[0].result; - var trLost = [] - for (var k in ret) - { - if (!ret[k].result) - trLost.push(label[ret[k].id]) - } - callback(parseInt(b, 16), trLost) - }); - } - - Component.onCompleted: - { - renewCtx() - } - - BigIntValue - { - id: gasPriceInt - } - - function estimateGas(scenario, callback) - { - if (!clientModelGasEstimation.running) - { - for (var si = 0; si < projectModel.listModel.count; si++) - { - var document = projectModel.listModel.get(si); - if (document.isContract) - codeModelGasEstimation.registerCodeChange(document.documentId, fileIo.readFile(document.path)); - } - gasEstimationConnect.callback = callback - clientModelGasEstimation.setupScenario(scenario) - } - } - - Connections - { - id: gasEstimationConnect - target: clientModelGasEstimation - property var callback - onRunComplete: { - callback(clientModelGasEstimation.gasCosts) - } - } - - CodeModel { - id: codeModelGasEstimation - } - - ClientModel - { - id: clientModelGasEstimation - codeModel: codeModelGasEstimation - Component.onCompleted: - { - init("/tmp/bcgas/") - } - } - - Timer - { - id: pooler - interval: 5000 - repeat: true - running: false - } - - Timer - { - id: poolLog - property var callBack - property int elapsed - property string hash - interval: 2000 - running: false - repeat: true - onTriggered: { - elapsed += interval; - var requests = []; - var jsonRpcRequestId = 0; - requests.push({ - jsonrpc: "2.0", - method: "eth_getTransactionReceipt", - params: [ hash ], - id: jsonRpcRequestId++ - }); - TransactionHelper.rpcCall(requests, function (httpRequest, response){ - console.log(response) - var receipt = JSON.parse(response)[0].result - if (receipt) - { - stop(); - callBack(1, receipt); - } - else if (elapsed > 2500000) - { - stop(); - callBack(-1, null); - } - }) - } - } -} - diff --git a/mix/qml/Ether.qml b/mix/qml/Ether.qml deleted file mode 100644 index 593a54a3a..000000000 --- a/mix/qml/Ether.qml +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Display a row containing : - * - The amount of Ether. - * - The unit used. - * - User-friendly string representation of the amout of Ether (if displayFormattedValue == true). - * 'value' has to be a QEther obj. -*/ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Controls.Styles 1.1 - -RowLayout { - id: etherEdition - property bool displayFormattedValue; - property bool edit; - property variant value; - property bool displayUnitSelection - onValueChanged: update() - Component.onCompleted: update() - signal amountChanged - signal unitChanged - - - function update() - { - if (value) - { - etherValueEdit.text = value.value; - selectUnit(value.unit); - } - } - - function selectUnit(unit) - { - units.currentIndex = unit; - } - - - DefaultTextField - { - onTextChanged: - { - if (value !== undefined) - { - value.setValue(text) - formattedValue.text = value.format(); - amountChanged() - } - } - readOnly: !edit - visible: edit - id: etherValueEdit; - } - - ComboBox - { - id: units - visible: displayUnitSelection; - onCurrentTextChanged: - { - if (value) - { - value.setUnit(currentText); - formattedValue.text = value.format(); - unitChanged() - } - } - - model: ListModel { - id: unitsModel - ListElement { text: "Uether"; } - ListElement { text: "Vether"; } - ListElement { text: "Dether"; } - ListElement { text: "Nether"; } - ListElement { text: "Yether"; } - ListElement { text: "Zether"; } - ListElement { text: "Eether"; } - ListElement { text: "Pether"; } - ListElement { text: "Tether"; } - ListElement { text: "Gether"; } - ListElement { text: "Mether"; } - ListElement { text: "grand"; } - ListElement { text: "ether"; } - ListElement { text: "finney"; } - ListElement { text: "szabo"; } - ListElement { text: "Gwei"; } - ListElement { text: "Mwei"; } - ListElement { text: "Kwei"; } - ListElement { text: "wei"; } - } - } - - Text - { - visible: displayFormattedValue - id: formattedValue - } -} diff --git a/mix/qml/EtherValue.qml b/mix/qml/EtherValue.qml deleted file mode 100644 index 1217aade5..000000000 --- a/mix/qml/EtherValue.qml +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Used to instanciate a QEther obj using Qt.createComponent function. -*/ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Controls.Styles 1.1 -import org.ethereum.qml.QEther 1.0 - -QEther -{ - id: basicEther - value: "100000000000" - unit: QEther.Wei -} diff --git a/mix/qml/FilesSection.qml b/mix/qml/FilesSection.qml deleted file mode 100644 index 5e49143a7..000000000 --- a/mix/qml/FilesSection.qml +++ /dev/null @@ -1,302 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Controls.Styles 1.3 -import QtQuick.Dialogs 1.2 -import "." - - -Rectangle -{ - Layout.fillWidth: true - Layout.minimumHeight: hiddenHeightTopLevel() - height: hiddenHeightTopLevel() - Layout.maximumHeight: hiddenHeightTopLevel() - id: wrapperItem - signal documentSelected(string doc, string groupName) - property alias model: filesList.model - property string sectionName; - property variant selManager; - property int index; - color: index % 2 === 0 ? "transparent" : projectFilesStyle.title.background - - function hiddenHeightTopLevel() - { - return section.state === "hidden" ? projectFilesStyle.documentsList.height : projectFilesStyle.documentsList.fileNameHeight * model.count + projectFilesStyle.documentsList.height; - } - - function hiddenHeightRepeater() - { - return section.state === "hidden" ? 0 : projectFilesStyle.documentsList.fileNameHeight * wrapperItem.model.count; - } - - function hiddenHeightElement() - { - return section.state === "hidden" ? 0 : projectFilesStyle.documentsList.fileNameHeight; - } - - function getDocumentIndex(documentId) - { - for (var i = 0; i < model.count; i++) - if (model.get(i).documentId === documentId) - return i; - return -1; - } - - function removeDocument(documentId) - { - var i = getDocumentIndex(documentId); - if (i !== -1) - model.remove(i); - } - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - SourceSansProRegular - { - id: fileNameFont - } - - SourceSansProBold - { - id: boldFont - } - - RowLayout - { - anchors.top: parent.top - id: rowCol - height: projectFilesStyle.documentsList.height - Layout.fillWidth: true - - - Image { - source: "qrc:/qml/img/opentriangleindicator_filesproject.png" - width: 15 - sourceSize.width: 12 - id: imgArrow - anchors.right: section.left - anchors.rightMargin: 8 - anchors.top: parent.top - anchors.topMargin: 10 - } - - Text - { - id: section - text: sectionName - anchors.left: parent.left - anchors.leftMargin: projectFilesStyle.general.leftMargin - color: projectFilesStyle.documentsList.sectionColor - font.family: boldFont.name - font.pointSize: projectFilesStyle.documentsList.sectionFontSize - states: [ - State { - name: "hidden" - PropertyChanges { target: filesList; visible: false; } - PropertyChanges { target: rowCol; Layout.minimumHeight: projectFilesStyle.documentsList.height; Layout.maximumHeight: projectFilesStyle.documentsList.height; height: projectFilesStyle.documentsList.height; } - PropertyChanges { target: imgArrow; source: "qrc:/qml/img/closedtriangleindicator_filesproject.png" } - } - ] - } - - MouseArea { - id: titleMouseArea - anchors.fill: parent - hoverEnabled: true - z: 2 - onClicked: { - if (section.state === "hidden") - section.state = ""; - else - section.state = "hidden"; - } - } - } - - ColumnLayout { - height: wrapperItem.hiddenHeightRepeater() - Layout.minimumHeight: wrapperItem.hiddenHeightRepeater() - Layout.preferredHeight: wrapperItem.hiddenHeightRepeater() - Layout.maximumHeight: wrapperItem.hiddenHeightRepeater() - width: parent.width - visible: section.state !== "hidden" - spacing: 0 - - Repeater - { - id: filesList - visible: section.state !== "hidden" - Rectangle - { - visible: section.state !== "hidden" - id: rootItem - Layout.fillWidth: true - Layout.minimumHeight: wrapperItem.hiddenHeightElement() - Layout.preferredHeight: wrapperItem.hiddenHeightElement() - Layout.maximumHeight: wrapperItem.hiddenHeightElement() - height: wrapperItem.hiddenHeightElement() - color: isSelected ? projectFilesStyle.documentsList.highlightColor : "transparent" - property bool isSelected - property bool renameMode - - Row { - spacing: 3 - anchors.verticalCenter: parent.verticalCenter - anchors.fill: parent - anchors.left: parent.left - anchors.leftMargin: projectFilesStyle.general.leftMargin + 2 - Text { - id: nameText - height: parent.height - visible: !renameMode - color: rootItem.isSelected ? projectFilesStyle.documentsList.selectedColor : projectFilesStyle.documentsList.color - text: name; - font.family: fileNameFont.name - font.pointSize: projectFilesStyle.documentsList.fontSize - verticalAlignment: Text.AlignVCenter - - Connections - { - target: selManager - onSelected: { - if (groupName != sectionName) - rootItem.isSelected = false; - else if (doc === documentId) - rootItem.isSelected = true; - else - rootItem.isSelected = false; - - if (rootItem.isSelected && section.state === "hidden") - section.state = ""; - } - onIsCleanChanged: { - if (groupName === sectionName && doc === documentId) - editStatusLabel.visible = !isClean; - } - } - } - - DefaultLabel { - id: editStatusLabel - visible: false - color: rootItem.isSelected ? projectFilesStyle.documentsList.selectedColor : projectFilesStyle.documentsList.color - verticalAlignment: Text.AlignVCenter - text: "*" - width: 10 - height: parent.height - } - } - - TextInput { - id: textInput - text: nameText.text - visible: renameMode - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: projectFilesStyle.general.leftMargin - MouseArea { - id: textMouseArea - anchors.fill: parent - hoverEnabled: true - z: 2 - onClicked: { - textInput.forceActiveFocus(); - } - } - - onVisibleChanged: { - if (visible) { - selectAll(); - forceActiveFocus(); - } - } - - onAccepted: close(true); - onCursorVisibleChanged: { - if (!cursorVisible) - close(false); - } - onFocusChanged: { - if (!focus) - close(false); - } - function close(accept) { - rootItem.renameMode = false; - if (accept) - { - var i = getDocumentIndex(documentId); - projectModel.renameDocument(documentId, textInput.text); - wrapperItem.model.set(i, projectModel.getDocument(documentId)); - } - } - } - - MouseArea { - id: mouseArea - z: 1 - hoverEnabled: false - anchors.fill: parent - acceptedButtons: Qt.LeftButton | Qt.RightButton - onClicked:{ - if (mouse.button === Qt.RightButton) - { - if (isContract) - contextMenuContract.popup(); - else - contextMenu.popup(); - } - else if (mouse.button === Qt.LeftButton) - { - rootItem.isSelected = true; - projectModel.openDocument(documentId); - documentSelected(documentId, groupName); - } - } - } - - Menu { - id: contextMenu - MenuItem { - text: qsTr("Rename") - onTriggered: { - rootItem.renameMode = true; - } - } - MenuItem { - text: qsTr("Delete") - onTriggered: { - deleteConfirmation.open(); - } - } - } - - Menu { - id: contextMenuContract - MenuItem { - text: qsTr("Delete") - onTriggered: { - deleteConfirmation.open(); - } - } - } - - MessageDialog - { - id: deleteConfirmation - text: qsTr("Are you sure to delete this file ?") - standardButtons: StandardIcon.Ok | StandardIcon.Cancel - onAccepted: - { - projectModel.removeDocument(documentId); - wrapperItem.removeDocument(documentId); - } - } - } - } - } - } -} diff --git a/mix/qml/ItemDelegateDataDump.qml b/mix/qml/ItemDelegateDataDump.qml deleted file mode 100644 index 2c1419e61..000000000 --- a/mix/qml/ItemDelegateDataDump.qml +++ /dev/null @@ -1,61 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 -import "." - -Rectangle { - anchors.fill: parent - RowLayout - { - id: row; - anchors.fill: parent - spacing: 2 - Rectangle - { - id: firstCol; - color: "#f7f7f7" - Layout.fillWidth: true - Layout.minimumWidth: 35 - Layout.preferredWidth: 35 - Layout.maximumWidth: 35 - Layout.minimumHeight: parent.height - Text { - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: 3 - font.family: "monospace" - font.bold: true - color: "#4a4a4a" - text: modelData[0] - font.pointSize: dbgStyle.general.dataDumpFontSize; - } - } - - Rectangle - { - Layout.fillWidth: true - Layout.minimumWidth: 110 - Layout.preferredWidth: 110 - Layout.maximumWidth: 110 - Layout.minimumHeight: parent.height - Text { - font.family: "monospace" - font.bold: true - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - anchors.leftMargin: 4 - color: "#4a4a4a" - text: modelData[1] - font.pointSize: dbgStyle.general.dataDumpFontSize - } - } - } - - Rectangle { - width: parent.width; - height: 1; - color: "#cccccc" - anchors.bottom: parent.bottom - } -} diff --git a/mix/qml/KeyValuePanel.qml b/mix/qml/KeyValuePanel.qml deleted file mode 100644 index d19f4d3fa..000000000 --- a/mix/qml/KeyValuePanel.qml +++ /dev/null @@ -1,133 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.QEther 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "js/TransactionHelper.js" as TransactionHelper -import "js/QEtherHelper.js" as QEtherHelper -import "." - -ColumnLayout { - id: root - property alias title: titleLabel.text - property variant _data - property string role - property alias model: modelKeyValue - - function add(key, value) - { - modelKeyValue.append({ "key": key, "value": value }) - } - - function clear() - { - modelKeyValue.clear() - } - - function init() - { - modelKeyValue.clear() - if (typeof(computeData) !== "undefined" && computeData instanceof Function) - computeData() - else - { - if (_data !== undefined && _data[role] !== undefined) - { - var keys = Object.keys(_data[role]) - for (var k in keys) - { - modelKeyValue.append({ "key": keys[k] === "" ? "undefined" : keys[k], "value": _data[role][keys[k]] }) - } - } - } - } - - RowLayout - { - Layout.preferredHeight: 20 - Layout.fillWidth: true - Label - { - id: titleLabel - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - color: "white" - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 100 - ListModel - { - id: modelKeyValue - } - - Rectangle - { - Layout.fillWidth: true - Layout.fillHeight: true - color: "white" - radius: 2 - ScrollView - { - id: columnValues - horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff - anchors.fill: parent - clip: true - ColumnLayout - { - spacing: 0 - id: colValue - anchors.top: parent.top - anchors.topMargin: 5 - Repeater - { - id: repeaterKeyValue - model: modelKeyValue - Row - { - Layout.preferredHeight: 30 - spacing: 5 - anchors.left: colValue.left - anchors.leftMargin: 5 - Label - { - maximumLineCount: 1 - text: { - if (index >= 0 && repeaterKeyValue.model.get(index).key !== undefined) - return repeaterKeyValue.model.get(index).key - else - return "" - } - } - - Label - { - text: "=" - } - - Label - { - maximumLineCount: 1 - text: { - if (index >= 0 && repeaterKeyValue.model.get(index).value !== undefined) - return repeaterKeyValue.model.get(index).value - else - return "" - } - } - } - } - } - - } - } - } -} - diff --git a/mix/qml/LogsPane.qml b/mix/qml/LogsPane.qml deleted file mode 100644 index c9d0ef67e..000000000 --- a/mix/qml/LogsPane.qml +++ /dev/null @@ -1,648 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.SortFilterProxyModel 1.0 - -Rectangle -{ - property variant statusPane - property variant currentStatus - property int contentXPos: logStyle.generic.layout.dateWidth + logStyle.generic.layout.typeWidth - 70 - - function clear() - { - logsModel.clear(); - statusPane.clear(); - currentStatus = undefined; - } - - function push(_level, _type, _content) - { - _content = _content.replace(/\n/g, " ") - logsModel.insert(0, { "type": _type, "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": _content, "level": _level }); - } - - onVisibleChanged: - { - if (currentStatus && visible && (logsModel.count === 0 || logsModel.get(0).content !== currentStatus.content || logsModel.get(0).date !== currentStatus.date)) - logsModel.insert(0, { "type": currentStatus.type, "date": currentStatus.date, "content": currentStatus.content, "level": currentStatus.level }); - else if (!visible) - { - for (var k = 0; k < logsModel.count; k++) - { - if (logsModel.get(k).type === "Comp") //do not keep compilation logs. - logsModel.remove(k); - } - } - } - - anchors.fill: parent - radius: 10 - color: "transparent" - id: logsPane - Column { - z: 2 - height: parent.height - rowAction.height - width: parent.width - spacing: 0 - ListModel { - id: logsModel - } - - ScrollView - { - id: scrollView - height: parent.height - width: parent.width - horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff - Column - { - id: logsRect - spacing: 0 - Repeater { - id: logsRepeater - clip: true - property string frontColor: "transparent" - model: SortFilterProxyModel { - id: proxyModel - source: logsModel - property var roles: ["-", "javascript", "run", "state", "comp", "deployment"] - - Component.onCompleted: { - filterType = regEx(proxyModel.roles); - } - - function search(_value) - { - filterContent = _value; - } - - function toogleFilter(_value) - { - var count = roles.length; - for (var i in roles) - { - if (roles[i] === _value) - { - roles.splice(i, 1); - break; - } - } - if (count === roles.length) - roles.push(_value); - - filterType = regEx(proxyModel.roles); - } - - function regEx(_value) - { - return "(?:" + roles.join('|') + ")"; - } - - filterType: "(?:javascript|run|state|comp|deployment)" - filterContent: "" - filterSyntax: SortFilterProxyModel.RegExp - filterCaseSensitivity: Qt.CaseInsensitive - } - - Rectangle - { - width: logStyle.generic.layout.dateWidth + logStyle.generic.layout.contentWidth + logStyle.generic.layout.typeWidth - height: 30 - color: - { - var cl; - if (level === "warning" || level === "error") - cl = logStyle.generic.layout.errorColor; - else - cl = index % 2 === 0 ? "transparent" : logStyle.generic.layout.logAlternateColor; - if (index === 0) - logsRepeater.frontColor = cl; - return cl; - } - - Component.onCompleted: - { - logsPane.contentXPos = logContent.x - } - - MouseArea - { - anchors.fill: parent - onClicked: - { - if (logContent.elide === Text.ElideNone) - { - logContent.elide = Text.ElideRight; - logContent.wrapMode = Text.NoWrap - parent.height = 30; - } - else - { - logContent.elide = Text.ElideNone; - logContent.wrapMode = Text.WordWrap; - parent.height = logContent.lineCount * 30; - } - } - } - - - DefaultLabel { - id: dateLabel - text: date; - font.family: logStyle.generic.layout.logLabelFont - width: logStyle.generic.layout.dateWidth - font.pointSize: appStyle.absoluteSize(-1) - clip: true - elide: Text.ElideRight - anchors.left: parent.left - anchors.leftMargin: 15 - anchors.verticalCenter: parent.verticalCenter - color: { - parent.getColor(level); - } - } - - DefaultLabel { - text: type; - id: typeLabel - font.family: logStyle.generic.layout.logLabelFont - width: logStyle.generic.layout.typeWidth - clip: true - elide: Text.ElideRight - font.pointSize: appStyle.absoluteSize(-1) - anchors.left: dateLabel.right - anchors.leftMargin: 2 - anchors.verticalCenter: parent.verticalCenter - color: { - parent.getColor(level); - } - } - - Text { - id: logContent - text: content; - font.family: logStyle.generic.layout.logLabelFont - width: logStyle.generic.layout.contentWidth - font.pointSize: appStyle.absoluteSize(-1) - anchors.verticalCenter: parent.verticalCenter - elide: Text.ElideRight - anchors.left: typeLabel.right - anchors.leftMargin: 2 - color: { - parent.getColor(level); - } - } - - function getColor() - { - if (level === "error") - return "red"; - else if (level === "warning") - return "orange"; - else - return "#808080"; - } - } - } - } - } - - Component { - id: itemDelegate - DefaultLabel { - text: styleData.value; - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-1) - color: { - if (proxyModel.get(styleData.row).level === "error") - return "red"; - else if (proxyModel.get(styleData.row).level === "warning") - return "orange"; - else - return "#808080"; - } - } - } - } - - Rectangle - { - gradient: Gradient { - GradientStop { position: 0.0; color: "#f1f1f1" } - GradientStop { position: 1.0; color: "#d9d7da" } - } - Layout.preferredHeight: logStyle.generic.layout.headerHeight - height: logStyle.generic.layout.headerHeight - width: logsPane.width - anchors.bottom: parent.bottom - Row - { - id: rowAction - anchors.leftMargin: logStyle.generic.layout.leftMargin - anchors.left: parent.left - spacing: logStyle.generic.layout.headerButtonSpacing - height: parent.height - Rectangle - { - color: "transparent" - height: parent.height - width: 40 - DefaultLabel - { - width: 40 - elide: Text.ElideRight - anchors.verticalCenter: parent.verticalCenter - color: logStyle.generic.layout.logLabelColor - font.pointSize: appStyle.absoluteSize(-3) - font.family: logStyle.generic.layout.logLabelFont - text: qsTr("Show:") - } - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 1; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor1 - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 2; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor2 - } - - ToolButton { - id: javascriptButton - checkable: true - height: logStyle.generic.layout.headerButtonHeight - width: 30 - anchors.verticalCenter: parent.verticalCenter - checked: true - onCheckedChanged: { - proxyModel.toogleFilter("javascript") - } - tooltip: qsTr("JavaScript") - style: - ButtonStyle { - label: - Item { - Rectangle - { - width: labelJs.width - height: labelJs.height - anchors.centerIn: parent - color: "transparent" - DefaultLabel { - id: labelJs - width: 15 - elide: Text.ElideRight - anchors.horizontalCenter: parent.horizontalCenter - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-3) - color: logStyle.generic.layout.logLabelColor - text: qsTr("JS") - } - } - } - background: - Rectangle { - color: javascriptButton.checked ? logStyle.generic.layout.buttonSelected : "transparent" - } - } - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 1; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor1 - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 2; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor2 - } - - ToolButton { - id: runButton - checkable: true - height: logStyle.generic.layout.headerButtonHeight - width: 40 - anchors.verticalCenter: parent.verticalCenter - checked: true - onCheckedChanged: { - proxyModel.toogleFilter("run") - } - tooltip: qsTr("Run") - style: - ButtonStyle { - label: - Item { - Rectangle - { - width: labelRun.width - height: labelRun.height - anchors.centerIn: parent - color: "transparent" - DefaultLabel { - id: labelRun - width: 25 - anchors.horizontalCenter: parent.horizontalCenter - elide: Text.ElideRight - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-3) - color: logStyle.generic.layout.logLabelColor - text: qsTr("Run") - } - } - } - background: - Rectangle { - color: runButton.checked ? logStyle.generic.layout.buttonSelected : "transparent" - } - } - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 1; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor1 - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 2; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor2 - } - - ToolButton { - id: stateButton - checkable: true - height: logStyle.generic.layout.headerButtonHeight - anchors.verticalCenter: parent.verticalCenter - width: 40 - checked: true - onCheckedChanged: { - proxyModel.toogleFilter("state") - } - tooltip: qsTr("State") - style: - ButtonStyle { - label: - Item { - Rectangle - { - width: labelState.width - height: labelState.height - anchors.centerIn: parent - color: "transparent" - DefaultLabel { - id: labelState - width: 30 - anchors.horizontalCenter: parent.horizontalCenter - elide: Text.ElideRight - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-3) - color: logStyle.generic.layout.logLabelColor - text: qsTr("State") - } - } - } - background: - Rectangle { - color: stateButton.checked ? logStyle.generic.layout.buttonSelected : "transparent" - } - } - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 1; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor1 - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 2; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor2 - } - - ToolButton { - id: deloyButton - checkable: true - height: logStyle.generic.layout.headerButtonHeight - width: 50 - anchors.verticalCenter: parent.verticalCenter - checked: true - onCheckedChanged: { - proxyModel.toogleFilter("deployment") - } - tooltip: qsTr("Deployment") - style: - ButtonStyle { - label: - Item { - Rectangle - { - width: labelDeploy.width - height: labelDeploy.height - anchors.centerIn: parent - color: "transparent" - DefaultLabel { - width: 40 - id: labelDeploy - anchors.horizontalCenter: parent.horizontalCenter - elide: Text.ElideRight - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-3) - color: logStyle.generic.layout.logLabelColor - text: qsTr("Deploy.") - } - } - } - background: - Rectangle { - color: deloyButton.checked ? logStyle.generic.layout.buttonSelected : "transparent" - } - } - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 1; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor1 - } - - Rectangle { - anchors.verticalCenter: parent.verticalCenter - width: 2; - height: parent.height - color: logStyle.generic.layout.buttonSeparatorColor2 - } - } - - Row - { - height: parent.height - anchors.right: parent.right - anchors.rightMargin: 10 - spacing: 10 - Rectangle - { - height: logStyle.generic.layout.headerButtonHeight - anchors.verticalCenter: parent.verticalCenter - color: "transparent" - width: 20 - Button - { - id: clearButton - action: clearAction - anchors.fill: parent - anchors.verticalCenter: parent.verticalCenter - height: 25 - style: - ButtonStyle { - background: - Rectangle { - height: logStyle.generic.layout.headerButtonHeight - implicitHeight: logStyle.generic.layout.headerButtonHeight - color: "transparent" - } - } - } - - Image { - id: clearImage - source: clearAction.enabled ? "qrc:/qml/img/cleariconactive.png" : "qrc:/qml/img/clearicon.png" - anchors.centerIn: parent - fillMode: Image.PreserveAspectFit - width: 20 - height: 25 - } - - Action { - id: clearAction - enabled: logsModel.count > 0 - tooltip: qsTr("Clear") - onTriggered: { - logsPane.clear() - } - } - } - - Rectangle - { - height: logStyle.generic.layout.headerButtonHeight - anchors.verticalCenter: parent.verticalCenter - color: "transparent" - width: 20 - Button - { - id: copyButton - action: copyAction - anchors.fill: parent - anchors.verticalCenter: parent.verticalCenter - height: 25 - style: - ButtonStyle { - background: - Rectangle { - height: logStyle.generic.layout.headerButtonHeight - implicitHeight: logStyle.generic.layout.headerButtonHeight - color: "transparent" - } - } - } - - Image { - id: copyImage - source: copyAction.enabled ? "qrc:/qml/img/copyiconactive.png" : "qrc:/qml/img/copyicon.png" - anchors.centerIn: parent - fillMode: Image.PreserveAspectFit - width: 20 - height: 25 - } - - Action { - id: copyAction - enabled: logsModel.count > 0 - tooltip: qsTr("Copy to Clipboard") - onTriggered: { - var content = ""; - for (var k = 0; k < logsModel.count; k++) - { - var log = logsModel.get(k); - content += log.type + "\t" + log.level + "\t" + log.date + "\t" + log.content + "\n"; - } - clipboard.text = content; - } - } - } - - Rectangle - { - width: 120 - radius: 10 - height: 25 - color: "white" - anchors.verticalCenter: parent.verticalCenter - - Image - { - id: searchImg - source: "qrc:/qml/img/searchicon.png" - fillMode: Image.PreserveAspectFit - width: 20 - height: 25 - z: 3 - } - - DefaultTextField - { - id: searchBox - z: 2 - width: 100 - anchors.left: searchImg.right - anchors.leftMargin: -7 - font.family: logStyle.generic.layout.logLabelFont - font.pointSize: appStyle.absoluteSize(-3) - font.italic: true - text: qsTr(" - Search - ") - onFocusChanged: - { - if (!focus && text === "") - text = qsTr(" - Search - "); - else if (focus && text === qsTr(" - Search - ")) - text = ""; - } - - onTextChanged: { - if (text === qsTr(" - Search - ")) - proxyModel.search(""); - else - proxyModel.search(text); - } - - style: - TextFieldStyle { - background: Rectangle { - radius: 10 - } - } - } - } - } - } - -} diff --git a/mix/qml/LogsPaneStyle.qml b/mix/qml/LogsPaneStyle.qml deleted file mode 100644 index 31433def1..000000000 --- a/mix/qml/LogsPaneStyle.qml +++ /dev/null @@ -1,30 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject generic: QtObject { - property QtObject layout: QtObject { - property string backgroundColor: "#f7f7f7" - property int headerHeight: 30 - property int headerButtonSpacing: 0 - property int leftMargin: 10 - property int headerButtonHeight: 30 - property string logLabelColor: "#4a4a4a" - property string logLabelFont: "sans serif" - property int headerInputWidth: 200 - property int dateWidth: 100 - property int typeWidth: 100 - property int contentWidth: 560 - property string logAlternateColor: "#f6f5f6" - property string errorColor: "#fffcd5" - property string buttonSeparatorColor1: "#d3d0d0" - property string buttonSeparatorColor2: "#f2f1f2" - property string buttonSelected: "#dcdcdc" - } - } -} diff --git a/mix/qml/MacFileDialog.qml b/mix/qml/MacFileDialog.qml deleted file mode 100644 index f1995588f..000000000 --- a/mix/qml/MacFileDialog.qml +++ /dev/null @@ -1,298 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.2 -import QtQuick.Controls.Private 1.0 as ControlsPrivate -import QtQuick.Dialogs 1.2 -import QtQuick.Dialogs.Private 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.1 -import Qt.labs.folderlistmodel 2.1 -import Qt.labs.settings 1.0 - -AbstractDialog { - - id: root - - property string folder: view.model.folder - property var nameFilters: [] - property bool selectFolder: false - property bool selectExisting: true - property int selectedNameFilterIndex: -1 - property var selectedNameFilterExtensions: [] - property string selection: "" - property alias fileUrl: root.selection - - - function selectNameFilter(text) { - } - - function clearSelection(text) { - selection = ""; - } - - function addSelection(text) { - selection = text; - } - - onVisibleChanged: { - if (visible) { - view.needsWidthAdjustment = true - view.selection.clear() - view.focus = true - } - } - - Component.onCompleted: { - folder = fileIo.pathToUrl(fileIo.homePath); - view.model.nameFilters = root.selectedNameFilterExtensions - filterField.currentIndex = root.selectedNameFilterIndex - root.favoriteFolders = settings.favoriteFolders - } - - Component.onDestruction: { - settings.favoriteFolders = root.favoriteFolders - } - - property Settings settings: Settings { - category: "QQControlsFileDialog" - property alias width: root.width - property alias height: root.height - property variant favoriteFolders: [] - } - - property bool showFocusHighlight: false - property SystemPalette palette: SystemPalette { } - property var favoriteFolders: [] - - function dirDown(path) { - view.selection.clear() - root.folder = "file://" + path - } - function dirUp() { - view.selection.clear() - if (view.model.parentFolder != "") - root.folder = view.model.parentFolder - } - function acceptSelection() { - // transfer the view's selections to QQuickFileDialog - clearSelection() - if (selectFolder && view.selection.count === 0) - addSelection(folder) - else { - view.selection.forEach(function(idx) { - if (view.model.isFolder(idx)) { - if (selectFolder) - addSelection(view.model.get(idx, "fileURL")) - } else { - if (!selectFolder) - addSelection(view.model.get(idx, "fileURL")) - } - }) - } - accept() - } - - property Action dirUpAction: Action { - text: "\ue810" - shortcut: "Ctrl+U" - onTriggered: dirUp() - tooltip: qsTr("Go up to the folder containing this one") - } - - Rectangle { - id: window - implicitWidth: Math.min(root.__maximumDimension, Math.max(Screen.pixelDensity * 100, view.implicitWidth)) - implicitHeight: Math.min(root.__maximumDimension, Screen.pixelDensity * 80) - color: root.palette.window - - Binding { - target: view.model - property: "folder" - value: root.folder - } - Binding { - target: currentPathField - property: "text" - value: fileIo.urlToPath(root.folder) - } - Keys.onPressed: { - event.accepted = true - switch (event.key) { - case Qt.Key_Back: - case Qt.Key_Escape: - reject() - break - default: - event.accepted = false - break - } - } - Keys.forwardTo: [view.flickableItem] - - - TableView { - id: view - sortIndicatorVisible: true - width: parent.width - anchors.top: titleBar.bottom - anchors.bottom: bottomBar.top - - property bool needsWidthAdjustment: true - selectionMode: root.selectMultiple ? - (ControlsPrivate.Settings.hasTouchScreen ? SelectionMode.MultiSelection : SelectionMode.ExtendedSelection) : - SelectionMode.SingleSelection - onRowCountChanged: if (needsWidthAdjustment && rowCount > 0) { - resizeColumnsToContents() - needsWidthAdjustment = false - } - model: FolderListModel { - showFiles: !root.selectFolder - nameFilters: root.selectedNameFilterExtensions - sortField: (view.sortIndicatorColumn === 0 ? FolderListModel.Name : - (view.sortIndicatorColumn === 1 ? FolderListModel.Type : - (view.sortIndicatorColumn === 2 ? FolderListModel.Size : FolderListModel.LastModified))) - sortReversed: view.sortIndicatorOrder === Qt.DescendingOrder - } - - onActivated: if (view.focus) { - if (view.selection.count > 0 && view.model.isFolder(row)) { - dirDown(view.model.get(row, "filePath")) - } else { - root.acceptSelection() - } - } - onClicked: currentPathField.text = view.model.get(row, "filePath") - - - TableViewColumn { - id: fileNameColumn - role: "fileName" - title: qsTr("Filename") - delegate: Item { - implicitWidth: pathText.implicitWidth + pathText.anchors.leftMargin + pathText.anchors.rightMargin - - Text { - id: fileIcon - width: height - verticalAlignment: Text.AlignVCenter - font.family: iconFont.name - property alias unicode: fileIcon.text - FontLoader { id: iconFont; source: "qrc:/QtQuick/Dialogs/qml/icons.ttf"; onNameChanged: console.log("custom font" + name) } - x: 4 - height: parent.height - 2 - unicode: view.model.isFolder(styleData.row) ? "\ue804" : "\ue802" - } - Text { - id: pathText - text: styleData.value - anchors { - left: parent.left - right: parent.right - leftMargin: 36 + 6 - rightMargin: 4 - verticalCenter: parent.verticalCenter - } - color: styleData.textColor - elide: Text.ElideRight - renderType: ControlsPrivate.Settings.isMobile ? Text.QtRendering : Text.NativeRendering - } - } - } - TableViewColumn { - role: "fileSuffix" - title: qsTr("Type", "file type (extension)") - // TODO should not need to create a whole new component just to customize the text value - // something like textFormat: function(text) { return view.model.get(styleData.row, "fileIsDir") ? "folder" : text } - delegate: Item { - implicitWidth: sizeText.implicitWidth + sizeText.anchors.leftMargin + sizeText.anchors.rightMargin - Text { - id: sizeText - text: view.model.get(styleData.row, "fileIsDir") ? "folder" : styleData.value - anchors { - left: parent.left - right: parent.right - leftMargin: 4 - rightMargin: 4 - verticalCenter: parent.verticalCenter - } - color: styleData.textColor - elide: Text.ElideRight - renderType: ControlsPrivate.Settings.isMobile ? Text.QtRendering : Text.NativeRendering - } - } - } - TableViewColumn { - role: "fileSize" - title: qsTr("Size", "file size") - horizontalAlignment: Text.AlignRight - } - TableViewColumn { id: modifiedColumn; role: "fileModified" ; title: qsTr("Modified", "last-modified time") } - TableViewColumn { id: accessedColumn; role: "fileAccessed" ; title: qsTr("Accessed", "last-accessed time") } - } - - ToolBar { - id: titleBar - RowLayout { - anchors.fill: parent - ToolButton { - action: dirUpAction - //style: IconButtonStyle { } - Layout.maximumWidth: height * 1.5 - } - TextField { - id: currentPathField - Layout.fillWidth: true - function doAccept() { - root.clearSelection() - if (root.addSelection(fileIo.pathToUrl(text))) - root.accept() - else - root.folder = fileIo.pathFolder(text) - } - onAccepted: doAccept() - } - } - } - Item { - id: bottomBar - width: parent.width - height: buttonRow.height + buttonRow.spacing * 2 - anchors.bottom: parent.bottom - - Row { - id: buttonRow - anchors.right: parent.right - anchors.rightMargin: spacing - anchors.verticalCenter: parent.verticalCenter - spacing: 4 - ComboBox { - id: filterField - model: root.nameFilters - visible: !selectFolder - width: bottomBar.width - cancelButton.width - okButton.width - parent.spacing * 6 - anchors.verticalCenter: parent.verticalCenter - onCurrentTextChanged: { - root.selectNameFilter(currentText) - view.model.nameFilters = root.selectedNameFilterExtensions - } - } - Button { - id: cancelButton - text: qsTr("Cancel") - onClicked: root.reject() - } - Button { - id: okButton - text: root.selectFolder ? qsTr("Choose") : (selectExisting ? qsTr("Open") : qsTr("Save")) - onClicked: { - if (view.model.isFolder(view.currentIndex) && !selectFolder) - dirDown(view.model.get(view.currentIndex, "filePath")) - else if (!(root.selectExisting)) - currentPathField.doAccept() - else - root.acceptSelection() - } - } - } - } - } -} diff --git a/mix/qml/MainContent.qml b/mix/qml/MainContent.qml deleted file mode 100644 index 376135695..000000000 --- a/mix/qml/MainContent.qml +++ /dev/null @@ -1,246 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.QEther 1.0 -import "js/QEtherHelper.js" as QEtherHelper -import "js/TransactionHelper.js" as TransactionHelper -import "." - -Rectangle { - objectName: "mainContent" - signal keyPressed(variant event) - focus: true - Keys.enabled: true - Keys.onPressed: - { - root.keyPressed(event.key); - } - anchors.fill: parent - id: root - - property alias rightViewVisible: scenarioExe.visible - property alias webViewVisible: webPreview.visible - property alias webView: webPreview - property alias projectViewVisible: projectList.visible - property alias projectNavigator: projectList - property alias runOnProjectLoad: mainSettings.runOnProjectLoad - property alias rightPane: scenarioExe - property alias debuggerPanel: debugPanel - property alias codeEditor: codeEditor - property bool webViewHorizontal: codeWebSplitter.orientation === Qt.Vertical //vertical splitter positions elements vertically, splits screen horizontally - property bool firstCompile: true - property int scenarioMinWidth: 620 - - Connections { - target: codeModel - onCompilationComplete: { - if (firstCompile) { - firstCompile = false; - if (runOnProjectLoad) - startQuickDebugging(); - } - } - } - - Connections { - target: debugPanel - onDebugExecuteLocation: { - codeEditor.highlightExecution(documentId, location); - } - } - - Connections { - target: codeEditor - onBreakpointsChanged: { - debugPanel.setBreakpoints(codeEditor.getBreakpoints()); - } - } - - function startQuickDebugging() - { - ensureRightView(); - projectModel.stateListModel.debugDefaultState(); - } - - function toggleRightView() { - scenarioExe.visible = !scenarioExe.visible; - } - - function ensureRightView() { - scenarioExe.visible = true; - } - - function rightViewIsVisible() - { - return scenarioExe.visible; - } - - function hideRightView() { - scenarioExe.visible = lfalse; - } - - function toggleWebPreview() { - webPreview.visible = !webPreview.visible; - } - - function toggleProjectView() { - projectList.visible = !projectList.visible; - } - - function toggleWebPreviewOrientation() { - codeWebSplitter.orientation = (codeWebSplitter.orientation === Qt.Vertical ? Qt.Horizontal : Qt.Vertical); - } - - //TODO: move this to debugger.js after refactoring, introduce events - function toggleBreakpoint() { - codeEditor.toggleBreakpoint(); - } - - function displayCompilationErrorIfAny() - { - scenarioExe.visible = true; - scenarioExe.displayCompilationErrorIfAny(); - } - - Settings { - id: mainSettings - property alias codeWebOrientation: codeWebSplitter.orientation - property alias webWidth: webPreview.width - property alias webHeight: webPreview.height - property alias showProjectView: projectList.visible - property bool runOnProjectLoad: true - property int scenarioMinWidth: scenarioMinWidth - } - - ColumnLayout - { - id: mainColumn - anchors.fill: parent - spacing: 0 - Rectangle { - width: parent.width - height: 50 - Layout.row: 0 - Layout.fillWidth: true - Layout.preferredHeight: 50 - id: headerView - Rectangle - { - gradient: Gradient { - GradientStop { position: 0.0; color: "#f1f1f1" } - GradientStop { position: 1.0; color: "#d9d7da" } - } - id: headerPaneContainer - anchors.fill: parent - StatusPane - { - anchors.fill: parent - webPreview: webPreview - } - } - } - - Rectangle { - Layout.fillWidth: true - height: 1 - color: "#8c8c8c" - } - - Rectangle { - Layout.fillWidth: true - Layout.preferredHeight: root.height - headerView.height; - - Settings { - id: splitSettings - property alias projectWidth: projectList.width - property alias contentViewWidth: contentView.width - property alias rightViewWidth: scenarioExe.width - } - - Splitter - { - anchors.fill: parent - orientation: Qt.Horizontal - - ProjectList { - id: projectList - width: 350 - Layout.minimumWidth: 250 - Layout.fillHeight: true - Connections { - target: projectModel.codeEditor - } - } - - Rectangle { - id: contentView - Layout.fillHeight: true - Layout.fillWidth: true - - Splitter { - id: codeWebSplitter - anchors.fill: parent - orientation: Qt.Vertical - CodeEditorView { - id: codeEditor - height: parent.height * 0.6 - anchors.top: parent.top - Layout.fillWidth: true - Layout.fillHeight: true - } - WebPreview { - id: webPreview - height: parent.height * 0.4 - Layout.fillWidth: codeWebSplitter.orientation === Qt.Vertical - Layout.fillHeight: codeWebSplitter.orientation === Qt.Horizontal - Layout.minimumHeight: 200 - Layout.minimumWidth: 200 - } - } - } - - ScenarioExecution - { - id: scenarioExe; - visible: false; - Layout.fillHeight: true - Keys.onEscapePressed: visible = false - Layout.minimumWidth: scenarioMinWidth - anchors.right: parent.right - } - - Debugger - { - id: debugPanel - visible: false - Layout.fillHeight: true - Keys.onEscapePressed: visible = false - Layout.minimumWidth: scenarioMinWidth - anchors.right: parent.right - } - - Connections { - target: clientModel - onDebugDataReady: { - scenarioExe.visible = false - debugPanel.visible = true - debugPanel.width = scenarioExe.width - if (scenarioExe.bc.debugTrRequested) - debugPanel.setTr(scenarioExe.bc.model.blocks[scenarioExe.bc.debugTrRequested[0]].transactions[scenarioExe.bc.debugTrRequested[1]]) - } - } - - Connections { - target: debugPanel - onPanelClosed: { - debugPanel.visible = false - scenarioExe.visible = true - scenarioExe.width = debugPanel.width - } - } - } - } - } -} diff --git a/mix/qml/ModalDialog.qml b/mix/qml/ModalDialog.qml deleted file mode 100644 index d5b7f3dd3..000000000 --- a/mix/qml/ModalDialog.qml +++ /dev/null @@ -1,30 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Window 2.0 - -Window -{ - id: modalDialog - title: "" - modality: Qt.WindowModal - height: 400 - width: 700 - visible: false - Loader - { - focus: true - id: modalDialogContent - objectName: "modalDialogContent" - anchors.fill: parent - } - function open() - { - visible = true; - } - function close() - { - visible = false; - modalDialogContent.source = ""; - modalDialogContent.sourceComponent = undefined; - modalDialog.destroy(); - } -} diff --git a/mix/qml/NewProjectDialog.qml b/mix/qml/NewProjectDialog.qml deleted file mode 100644 index ab35d5c5e..000000000 --- a/mix/qml/NewProjectDialog.qml +++ /dev/null @@ -1,123 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Dialogs 1.2 -import QtQuick.Window 2.0 -import QtQuick.Dialogs 1.1 - -Item -{ - property alias projectTitle: titleField.text - readonly property string projectPath: "file://" + pathField.text - property alias pathFieldText: pathField.text - signal accepted - function open() { - newProjectWin.visible = true; - titleField.focus = true; - } - - function close() { - newProjectWin.visible = false; - } - - function acceptAndClose() { - close(); - accepted(); - } - - Dialog { - id: newProjectWin - modality: Qt.ApplicationModal - title: qsTr("New Project"); - - width: 640 - height: 120 - - visible: false - - contentItem: Rectangle { - anchors.fill: parent - GridLayout - { - id: dialogContent - columns: 2 - anchors.fill: parent - anchors.margins: 10 - rowSpacing: 10 - columnSpacing: 10 - - Label { - text: qsTr("Title") - } - TextField { - id: titleField - focus: true - Layout.fillWidth: true - Keys.onReturnPressed: { - if (okButton.enabled) - acceptAndClose(); - } - } - - Label { - text: qsTr("Path") - } - RowLayout { - TextField { - id: pathField - Layout.fillWidth: true - Keys.onReturnPressed: { - if (okButton.enabled) - acceptAndClose(); - } - } - Button { - text: qsTr("Browse") - onClicked: - { - newProjectWin.close() - createProjectFileDialog.open() - } - } - } - - RowLayout - { - anchors.bottom: parent.bottom - anchors.right: parent.right; - - Button { - id: okButton; - enabled: titleField.text != "" && pathField.text != "" - text: qsTr("OK"); - onClicked: { - acceptAndClose(); - } - } - Button { - text: qsTr("Cancel"); - onClicked: close(); - } - } - } - } - Component.onCompleted: pathField.text = fileIo.homePath - - } - - QFileDialog { - id: createProjectFileDialog - visible: false - title: qsTr("Please choose a path for the project") - selectFolder: true - onAccepted: { - var u = createProjectFileDialog.fileUrl.toString(); - if (u.indexOf("file://") == 0) - u = u.substring(7, u.length) - if (Qt.platform.os == "windows" && u.indexOf("/") == 0) - u = u.substring(1, u.length); - pathField.text = u; - newProjectWin.open() - } - } -} diff --git a/mix/qml/PackagingStep.qml b/mix/qml/PackagingStep.qml deleted file mode 100644 index 8ee383f56..000000000 --- a/mix/qml/PackagingStep.qml +++ /dev/null @@ -1,212 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.3 -import QtQuick.Dialogs 1.1 -import Qt.labs.settings 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/NetworkDeployment.js" as NetworkDeploymentCode -import "js/QEtherHelper.js" as QEtherHelper - -Rectangle { - property variant paramsModel: [] - property variant worker - color: "#E3E3E3E3" - anchors.fill: parent - id: root - property string packageHash - property string packageBase64 - property alias localPackageUrl: localPackageUrl.text - property alias lastDeployDate: lastDeployLabel.text - property string deploymentId - property string packageDir - signal packaged - - function show() - { - visible = true - } - - QFileDialog { - id: ressourcesFolder - visible: false - title: qsTr("Please choose a path") - selectFolder: true - selectExisting: true - property variant target - onAccepted: { - var u = ressourcesFolder.fileUrl.toString(); - if (u.indexOf("file://") == 0) - u = u.substring(7, u.length) - if (Qt.platform.os == "windows" && u.indexOf("/") == 0) - u = u.substring(1, u.length); - target.text = u; - } - } - - ColumnLayout - { - anchors.top: parent.top - anchors.topMargin: 10 - width: parent.width - - id: col - spacing: 20 - anchors.left: parent.left - anchors.leftMargin: 10 - - Label - { - anchors.top: parent.top - Layout.fillWidth: true - - text: qsTr("Upload and update your Dapp assets") - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Save Package to") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - DefaultTextField - { - id: packageFolder - visible: true - Layout.preferredWidth: 360 - text: projectPath + "package/" - } - - Button - { - text: qsTr("select") - onClicked: { - ressourcesFolder.target = packageFolder - ressourcesFolder.open() - } - } - } - - Rectangle - { - Layout.fillWidth: true - Layout.preferredHeight: 40 - color: "transparent" - Button - { - id: generatePackageBtn - anchors.left: parent.left - anchors.leftMargin: 10 - text: qsTr("Generate Package") - onClicked: - { - NetworkDeploymentCode.packageDapp(projectModel.deploymentAddresses); - projectModel.saveProject() - root.packaged() - } - } - - RowLayout - { - anchors.top: generatePackageBtn.bottom - anchors.topMargin: 10 - visible: root.lastDeployDate !== "" - Label - { - id: lastPackage - text: qsTr("Last Package") - } - - Label - { - id: lastDeployLabel - } - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Local package URL") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - DefaultTextField - { - id: localPackageUrl - Layout.preferredWidth: 450 - readOnly: true - } - } - - Label - { - Layout.preferredWidth: 300 - text: qsTr("You have to upload the package to a remote folder, or use a service like pastebin") - wrapMode: Text.WordWrap - clip: true - } - - Rectangle - { - color: "transparent" - Layout.fillWidth: true - Layout.preferredHeight: 20 - Button - { - Layout.preferredWidth: 200 - text: qsTr("Copy Base64") - anchors.left: parent.left - anchors.leftMargin: 10 - onClicked: - { - clipboard.text = deploymentDialog.packageStep.packageBase64; - } - } - } - - Rectangle - { - color: "transparent" - Layout.fillWidth: true - Layout.preferredHeight: 20 - Button - { - Layout.preferredWidth: 200 - text: qsTr("Open pastebin") - anchors.left: parent.left - anchors.leftMargin: 10 - onClicked: - { - Qt.openUrlExternally("http://pastebin.com/"); - } - } - } - } -} - - - - - - - - - diff --git a/mix/qml/ProjectFilesStyle.qml b/mix/qml/ProjectFilesStyle.qml deleted file mode 100644 index ca4499196..000000000 --- a/mix/qml/ProjectFilesStyle.qml +++ /dev/null @@ -1,32 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property int leftMargin: 45 - } - - property QtObject title: QtObject { - property string color: "#808080" - property string background: "#f0f0f0" - property int height: 55 - property int fontSize: absoluteSize(7);// 18 - } - - property QtObject documentsList: QtObject { - property string background: "#f7f7f7" - property string color: "#4d4d4d" - property string sectionColor: "#808080" - property string selectedColor: "white" - property string highlightColor: "#4a90e2" - property int height: 35 - property int fileNameHeight: 30 - property int fontSize: absoluteSize(2)// 13 - property int sectionFontSize: absoluteSize(2)// 13 - } -} diff --git a/mix/qml/ProjectList.qml b/mix/qml/ProjectList.qml deleted file mode 100644 index f3f844d71..000000000 --- a/mix/qml/ProjectList.qml +++ /dev/null @@ -1,225 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Controls.Styles 1.3 -import Qt.labs.settings 1.0 -import "." - -Item { - property bool renameMode: false; - property alias sections: sectionRepeater - - ProjectFilesStyle { - id: projectFilesStyle - } - - ColumnLayout { - anchors.fill: parent - id: filesCol - spacing: 0 - - SourceSansProLight - { - id: srcSansProLight - } - - Rectangle - { - color: projectFilesStyle.title.background - height: projectFilesStyle.title.height - Layout.fillWidth: true - Image { - id: projectIcon - source: "qrc:/qml/img/dappProjectIcon.png" - anchors.right: projectTitle.left - anchors.verticalCenter: parent.verticalCenter - anchors.rightMargin: 6 - fillMode: Image.PreserveAspectFit - width: 32 - height: 32 - } - - Text - { - id: projectTitle - color: projectFilesStyle.title.color - text: projectModel.projectTitle - anchors.verticalCenter: parent.verticalCenter - visible: !projectModel.isEmpty; - anchors.left: parent.left - anchors.leftMargin: projectFilesStyle.general.leftMargin - font.family: srcSansProLight.name - font.pointSize: projectFilesStyle.title.fontSize - font.weight: Font.Light - } - - Text - { - text: "-" - anchors.right: parent.right - anchors.rightMargin: 15 - font.family: srcSansProLight.name - font.pointSize: projectFilesStyle.title.fontSize - anchors.verticalCenter: parent.verticalCenter - font.weight: Font.Light - } - } - - Rectangle - { - Layout.fillWidth: true - height: 3 - color: projectFilesStyle.documentsList.background - } - - Rectangle - { - Layout.fillWidth: true - Layout.fillHeight: true - color: projectFilesStyle.documentsList.background - - ColumnLayout - { - anchors.top: parent.top - width: parent.width - spacing: 0 - Repeater { - model: [qsTr("Contracts"), qsTr("Javascript"), qsTr("Web Pages"), qsTr("Styles"), qsTr("Images"), qsTr("Misc")]; - signal selected(string doc, string groupName) - signal isCleanChanged(string doc, string groupName, var isClean) - property int incr: -1; - id: sectionRepeater - FilesSection - { - id: section; - sectionName: modelData - index: - { - for (var k in sectionRepeater.model) - { - if (sectionRepeater.model[k] === modelData) - return k; - } - } - - model: sectionModel - selManager: sectionRepeater - - onDocumentSelected: { - selManager.selected(doc, groupName); - } - - ListModel - { - id: sectionModel - } - - Connections { - target: codeModel - onContractRenamed: { - if (modelData === "Contracts") - { - var ci = 0; - for (var si = 0; si < projectModel.listModel.count; si++) { - var document = projectModel.listModel.get(si); - if (document.isContract) { - var compiledDoc = codeModel.contractByDocumentId(document.documentId); - if (_documentId === document.documentId && _newName !== document.name) { - document.name = _newName; - projectModel.listModel.set(si, document); - sectionModel.set(ci, document); - } - ci++; - } - } - } - } - - onCompilationComplete: { - if (modelData === "Contracts") { - var ci = 0; - for (var si = 0; si < projectModel.listModel.count; si++) { - var document = projectModel.listModel.get(si); - if (document.isContract) { - var compiledDoc = codeModel.contractByDocumentId(document.documentId); - if (compiledDoc && compiledDoc.documentId === document.documentId && compiledDoc.contract.name !== document.name) { - document.name = compiledDoc.contract.name; - projectModel.listModel.set(si, document); - sectionModel.set(ci, document); - } - ci++; - } - } - } - } - } - - Connections { - id: projectModelConnection - target: projectModel - - function addDocToSubModel() - { - for (var k = 0; k < projectModel.listModel.count; k++) - { - var item = projectModel.listModel.get(k); - if (item.groupName === modelData) - sectionModel.append(item); - } - } - - onIsCleanChanged: { - for (var si = 0; si < sectionModel.count; si++) { - var document = sectionModel.get(si); - if (documentId === document.documentId && document.groupName === modelData) - { - selManager.isCleanChanged(documentId, modelData, isClean); - break; - } - } - } - - onDocumentOpened: { - if (document.groupName === modelData) - sectionRepeater.selected(document.documentId, modelData); - } - - onNewProject: { - sectionModel.clear(); - } - - onProjectClosed: { - sectionModel.clear(); - } - - onProjectLoaded: { - sectionModel.clear(); - addDocToSubModel(); - if (modelData === "Contracts") - { - var selItem = projectModel.listModel.get(0); - projectModel.openDocument(selItem.documentId); - sectionRepeater.selected(selItem.documentId, modelData); - } - } - - onDocumentAdded: - { - var newDoc = projectModel.getDocument(documentId); - if (newDoc.groupName === modelData) - { - sectionModel.append(newDoc); - projectModel.openDocument(newDoc.documentId); - sectionRepeater.selected(newDoc.documentId, modelData); - } - } - } - } - - } - } - } - } -} - diff --git a/mix/qml/ProjectModel.qml b/mix/qml/ProjectModel.qml deleted file mode 100644 index 14cc4ec39..000000000 --- a/mix/qml/ProjectModel.qml +++ /dev/null @@ -1,230 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Dialogs 1.1 -import Qt.labs.settings 1.0 -import "js/ProjectModel.js" as ProjectModelCode -import "js/NetworkDeployment.js" as NetworkDeploymentCode - -Item { - id: projectModel - - signal projectClosed - signal projectLoading(var projectData) - signal projectLoaded() - signal documentSaving(var document) - signal documentChanged(var documentId) - signal documentOpened(var document) - signal documentRemoved(var documentId) - signal documentUpdated(var documentId) //renamed - signal documentAdded(var documentId) - signal projectSaving() - signal projectFileSaving(var projectData) - signal projectSaved() - signal projectFileSaved() - signal newProject(var projectData) - signal documentSaved(var documentId) - signal contractSaved(var documentId) - signal deploymentStarted() - signal deploymentStepChanged(string message) - signal deploymentComplete() - signal deploymentError(string error) - signal isCleanChanged(var isClean, string documentId) - - property bool isEmpty: (projectPath === "") - readonly property string projectFileName: ".mix" - - property bool appIsClosing: false - property bool projectIsClosing: false - property string projectPath: "" - property string projectTitle: "" - property string currentDocumentId: "" - property var deploymentAddresses: ({}) - property string deploymentDir - property var listModel: projectListModel - property var stateListModel: projectStateListModel.model - property alias stateDialog: projectStateListModel.stateDialog - property CodeEditorView codeEditor: null - property var unsavedFiles: [] - property alias newProjectDialog: newProjectDialog - property int deployedScenarioIndex - property string applicationUrlEth - property string applicationUrlHttp - property string deployBlockNumber - property var deploymentTrHashes - property string registerContentHashTrHash - property string registerUrlTrHash - property int registerContentHashBlockNumber: -1 - property int registerUrlBlockNumber: -1 - - //interface - function saveAll() { ProjectModelCode.saveAll(); } - function saveCurrentDocument() { ProjectModelCode.saveCurrentDocument(); } - function createProject() { ProjectModelCode.createProject(); } - function closeProject(callBack) { ProjectModelCode.closeProject(callBack); } - function saveProject() { ProjectModelCode.saveProject(); } - function saveProjectFile() { ProjectModelCode.saveProjectFile(); } - function loadProject(path) { ProjectModelCode.loadProject(path); } - function newHtmlFile() { ProjectModelCode.newHtmlFile(); } - function newJsFile() { ProjectModelCode.newJsFile(); } - function newCssFile() { ProjectModelCode.newCssFile(); } - function newContract() { ProjectModelCode.newContract(); } - function openDocument(documentId) { ProjectModelCode.openDocument(documentId); } - function openNextDocument() { ProjectModelCode.openNextDocument(); } - function openPrevDocument() { ProjectModelCode.openPrevDocument(); } - function renameDocument(documentId, newName) { ProjectModelCode.renameDocument(documentId, newName); } - function removeDocument(documentId) { ProjectModelCode.removeDocument(documentId); } - function getDocument(documentId) { return ProjectModelCode.getDocument(documentId); } - function getDocumentIdByName(documentName) { return ProjectModelCode.getDocumentIdByName(documentName); } - function getDocumentIndex(documentId) { return ProjectModelCode.getDocumentIndex(documentId); } - function addExistingFiles(paths) { ProjectModelCode.doAddExistingFiles(paths); } - function deployProject() { NetworkDeploymentCode.deployProject(false); } - function registerToUrlHint(url, gasPrice, callback) { NetworkDeploymentCode.registerToUrlHint(url, gasPrice, callback); } - function formatAppUrl() { NetworkDeploymentCode.formatAppUrl(url); } - - function cleanDeploymentStatus() - { - deployedScenarioIndex = 0 - deployBlockNumber = "" - deploymentTrHashes = {} - deploymentAddresses = {} - deploymentDir = "" - deploymentDialog.packageStep.packageHash = "" - deploymentDialog.packageStep.packageBase64 = "" - deploymentDialog.packageStep.packageDir = "" - deploymentDialog.packageStep.lastDeployDate = "" - deploymentDialog.packageStep.localPackageUrl = "" - saveProject() - cleanRegisteringStatus() - } - - function cleanRegisteringStatus() - { - applicationUrlEth = "" - applicationUrlHttp = "" - registerContentHashTrHash = "" - registerUrlTrHash = "" - registerContentHashBlockNumber = -1 - registerUrlBlockNumber = -1 - saveProject() - } - - Connections { - target: mainApplication - onLoaded: { - if (mainApplication.trackLastProject && projectSettings.lastProjectPath && projectSettings.lastProjectPath !== "") - projectModel.loadProject(projectSettings.lastProjectPath) - } - } - - Connections { - target: codeEditor - onIsCleanChanged: { - for (var i in unsavedFiles) - { - if (unsavedFiles[i] === documentId && isClean) - unsavedFiles.splice(i, 1); - } - if (!isClean) - unsavedFiles.push(documentId); - isCleanChanged(isClean, documentId); - } - } - - NewProjectDialog { - id: newProjectDialog - visible: false - onAccepted: { - var title = newProjectDialog.projectTitle; - var path = newProjectDialog.projectPath; - ProjectModelCode.doCreateProject(title, path); - } - } - - Connections - { - target: fileIo - property bool saving: false - onFileChanged: - { - fileIo.watchFileChanged(_filePath); - var documentId = ProjectModelCode.getDocumentByPath(_filePath); - documentChanged(documentId); - } - } - - MessageDialog { - id: saveMessageDialog - title: qsTr("Project") - text: qsTr("Some files require to be saved. Do you want to save changes?"); - standardButtons: StandardButton.Yes | StandardButton.No | StandardButton.Cancel - icon: StandardIcon.Question - property var callBack; - onYes: { - projectIsClosing = true; - projectModel.saveAll(); - unsavedFiles = []; - ProjectModelCode.doCloseProject(); - if (callBack) - callBack(); - } - onRejected: {} - onNo: { - projectIsClosing = true; - unsavedFiles = []; - ProjectModelCode.doCloseProject(); - if (callBack) - callBack(); - } - } - - MessageDialog { - id: deployWarningDialog - title: qsTr("Project") - text: - { - if (Object.keys(projectModel.deploymentAddresses).length > 0) - return qsTr("This project has been already deployed to the network. Do you want to redeploy it? (Contract state will be reset)") - else - return qsTr("This action will deploy to the network. Do you want to deploy it?") - } - icon: StandardIcon.Question - standardButtons: StandardButton.Ok | StandardButton.Abort - onAccepted: { - NetworkDeploymentCode.startDeployProject(true); - } - } - - MessageDialog { - id: deployResourcesDialog - title: qsTr("Project") - standardButtons: StandardButton.Ok - } - - DeploymentDialog - { - id: deploymentDialog - } - - ListModel { - id: projectListModel - } - - StateListModel { - id: projectStateListModel - } - - Connections - { - target: projectModel - onProjectClosed: { - projectPath = ""; - } - } - - Settings { - id: projectSettings - property string lastProjectPath; - } -} diff --git a/mix/qml/QAddressView.qml b/mix/qml/QAddressView.qml deleted file mode 100644 index 0a8d09056..000000000 --- a/mix/qml/QAddressView.qml +++ /dev/null @@ -1,226 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.3 -import QtQuick.Controls.Styles 1.3 -import QtQuick.Layouts 1.1 -import "js/InputValidator.js" as InputValidator - -ColumnLayout -{ - property alias value: textinput.text - property alias accountRef: ctrModel - property string subType - property bool readOnly - property alias currentIndex: trCombobox.currentIndex - property alias displayInput: textInputRect.visible - property variant accounts - signal indexChanged() - spacing: 0 - id: editRoot - height: - { - if (isArray() && !readOnly) - return 60 - else - return 30 - } - - width: 320 - - SourceSansProBold - { - id: boldFont - } - - function isArray() - { - InputValidator.init() - return InputValidator.isArray(subType) - } - - function currentValue() { - return value; - } - - function currentType() - { - return accountRef.get(trCombobox.currentIndex).type; - } - - function current() - { - return accountRef.get(trCombobox.currentIndex); - } - - function load() - { - accountRef.clear(); - if (subType.indexOf("contract") !== -1 || subType.indexOf("address") !== -1) - { - var trCr = 0; - if (blockChainPanel) - for (var k = 0; k < blockChainPanel.model.blocks.length; k++) - { - if (k > blockIndex) - break; - for (var i = 0; i < blockChainPanel.model.blocks[k].transactions.length; i++) - { - if (i > transactionIndex) - break; - var tr = blockChainPanel.model.blocks[k].transactions[i] - if (tr.functionId === tr.contractId) - { - accountRef.append({ "itemid": tr.contractId + " - " + trCr, "value": "<" + tr.contractId + " - " + trCr + ">", "type": "contract" }); - trCr++; - } - } - } - } - if (subType.indexOf("address") !== -1) - { - for (k = 0; k < accounts.length; k++) - { - if (accounts[k].address === undefined) - accounts[k].address = clientModel.address(accounts[k].secret); - accountRef.append({ "itemid": accounts[k].name, "value": "0x" + accounts[k].address, "type": "address" }); - } - } - } - - function init() - { - btnAdd.visible = isArray() - textinput.readOnly = readOnly - if (isArray() || readOnly) - displayInput = true - else - displayInput = false - - if (isArray() || !readOnly) - trCombobox.visible = true - else - trCombobox.visible = false - - if (!trCombobox.visible) - { - rowCombobox.visible = false - rowCombobox.height = 0 - trCombobox.height = 0 - textinput.anchors.top = textinput.parent.top - } - - if (!readOnly) - { - trCombobox.currentIndex = 0 - for (var k = 0; k < ctrModel.count; k++) - { - if (ctrModel.get(k).value === value) - { - trCombobox.currentIndex = k - break - } - } - } - if (!isArray()) - trCombobox.update() - else if (value === "") - textinput.text = "[]" - } - - function select(address) - { - for (var k = 0; k < accountRef.count; k++) - { - if (accountRef.get(k).value === address) - { - trCombobox.currentIndex = k; - break; - } - } - } - - ListModel - { - id: ctrModel - } - - Row - { - anchors.top: parent.top - height: 30 - id: rowCombobox - ComboBox - { - property bool selected: false - id: trCombobox - model: ctrModel - width: 265 - textRole: "itemid" - function update() - { - trCombobox.selected = false; - if (currentText === "") - return; - else if (currentText !== " - ") - { - if (model.get(currentIndex).type === "contract") - textinput.text = "<" + currentText + ">"; - else - textinput.text = model.get(currentIndex).value; //address - trCombobox.selected = true; - } - else if (textinput.text.indexOf("<") === 0) - { - textinput.text = ""; - } - indexChanged(); - } - - onCurrentIndexChanged: { - if (!isArray()) - update() - } - } - - Button - { - id: btnAdd - text: qsTr("Add") - visible: false - onClicked: - { - var ar = JSON.parse(textinput.text) - ar.push(trCombobox.model.get(currentIndex).value) - textinput.text = JSON.stringify(ar) - } - } - } - - - Rectangle { - radius: 4 - width: 350 - height: 30 - id: textInputRect - TextField { - id: textinput - text: value - anchors.fill: parent - clip: true - font.family: boldFont.name - MouseArea { - id: mouseArea - anchors.fill: parent - hoverEnabled: true - onClicked: textinput.forceActiveFocus() - } - onTextChanged: - { - if (trCombobox.selected) - { - trCombobox.currentIndex = 0; - trCombobox.selected = false; - } - } - } - } -} diff --git a/mix/qml/QBoolTypeView.qml b/mix/qml/QBoolTypeView.qml deleted file mode 100644 index 25577b1ea..000000000 --- a/mix/qml/QBoolTypeView.qml +++ /dev/null @@ -1,109 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.3 -import "js/InputValidator.js" as InputValidator - -Item -{ - id: editRoot - property string value - property string defaultValue - property bool readOnly: !boolCombo.enabled - property string subType - height: 20 - width: 150 - - onReadOnlyChanged: { - boolCombo.enabled = !readOnly; - } - - function isArray() - { - InputValidator.init() - return InputValidator.isArray(subType) - } - - function init() - { - if (!isArray()) - { - boolArray.visible = false - boolCombo.visible = true - - value = format(value) - - var setValue = "1" - if (value === "") - setValue = parseInt(defaultValue); - else - setValue = parseInt(value); - boolCombo.checked = setValue === "1" ? true: false - boolCombo.enabled = !readOnly; - } - else - { - boolArray.visible = true - boolCombo.visible = false - if (value === "") - boolArray.text = "[]" - else - boolArray.text = value - - var formattedparam = [] - var param = JSON.parse(boolArray.text) - for (var k in JSON.parse(boolArray.text)) - formattedparam.push(parseInt(format(param[k]))) - boolArray.text = JSON.stringify(formattedparam) - } - } - - function finalize() - { - if (isArray()) - value = boolArray.text - } - - function format(value) - { - value = value === true ? "1" : value - value = value === false ? "0" : value; - value = value === "true" ? "1" : value - value = value === "false" ? "0" : value; - return value - } - - Rectangle { - color: "transparent" - anchors.fill: parent - CheckBox - { - property bool inited; - Component.onCompleted: - { - init(); - inited = true; - } - - id: boolCombo - anchors.fill: parent - onCheckedChanged: - { - if (inited) - value = checked ? "1" : "0" - - } - text: qsTr("True") - } - - TextField - { - id: boolArray - onTextChanged: - { - value = text - } - } - } -} - - - diff --git a/mix/qml/QFileDialog.qml b/mix/qml/QFileDialog.qml deleted file mode 100644 index 5ce2ad41c..000000000 --- a/mix/qml/QFileDialog.qml +++ /dev/null @@ -1,5 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.2 -import QtQuick.Dialogs 1.2 - -FileDialog { } diff --git a/mix/qml/QHashTypeView.qml b/mix/qml/QHashTypeView.qml deleted file mode 100644 index 6811dd43f..000000000 --- a/mix/qml/QHashTypeView.qml +++ /dev/null @@ -1,27 +0,0 @@ -import QtQuick 2.0 - -Item -{ - property alias value: textinput.text - property alias readOnly: textinput.readOnly - id: editRoot - height: 20 - width: 150 - - SourceSansProBold - { - id: boldFont - } - - TextInput { - id: textinput - text: value - wrapMode: Text.WrapAnywhere - MouseArea { - id: mouseArea - anchors.fill: parent - hoverEnabled: true - onClicked: textinput.forceActiveFocus() - } - } -} diff --git a/mix/qml/QIntTypeView.qml b/mix/qml/QIntTypeView.qml deleted file mode 100644 index 65e029ad5..000000000 --- a/mix/qml/QIntTypeView.qml +++ /dev/null @@ -1,26 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.1 -Item -{ - property alias value: textinput.text - property alias readOnly: textinput.readOnly - id: editRoot - width: 350 - DebuggerPaneStyle { - id: dbgStyle - } - - TextField { - anchors.verticalCenter: parent.verticalCenter - id: textinput - selectByMouse: true - text: value - implicitWidth: 350 - MouseArea { - id: mouseArea - anchors.fill: parent - hoverEnabled: true - onClicked: textinput.forceActiveFocus() - } - } -} diff --git a/mix/qml/QRealTypeView.qml b/mix/qml/QRealTypeView.qml deleted file mode 100644 index 96db4de75..000000000 --- a/mix/qml/QRealTypeView.qml +++ /dev/null @@ -1,15 +0,0 @@ -import QtQuick 2.0 - -Component -{ - Rectangle { - anchors.fill: parent - Text{ - anchors.fill: parent - text: qsTr("Real") - } - } -} - - - diff --git a/mix/qml/QStringTypeView.qml b/mix/qml/QStringTypeView.qml deleted file mode 100644 index e8b798784..000000000 --- a/mix/qml/QStringTypeView.qml +++ /dev/null @@ -1,31 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.1 - -Item -{ - property alias value: textinput.text - property alias readOnly: textinput.readOnly - id: editRoot - width: 350 - - DebuggerPaneStyle { - id: dbgStyle - } - - TextField { - anchors.verticalCenter: parent.verticalCenter - id: textinput - selectByMouse: true - text: value - width: 350 - MouseArea { - id: mouseArea - anchors.fill: parent - hoverEnabled: true - onClicked: textinput.forceActiveFocus() - } - } -} - - - diff --git a/mix/qml/QVariableDeclaration.qml b/mix/qml/QVariableDeclaration.qml deleted file mode 100644 index dc21d40a7..000000000 --- a/mix/qml/QVariableDeclaration.qml +++ /dev/null @@ -1,7 +0,0 @@ -import QtQuick 2.0 -import org.ethereum.qml.QVariableDeclaration 1.0 - -QVariableDeclaration -{ -} - diff --git a/mix/qml/QVariableDefinition.qml b/mix/qml/QVariableDefinition.qml deleted file mode 100644 index af0cd4ea0..000000000 --- a/mix/qml/QVariableDefinition.qml +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Used to instanciate a QVariableDefinition obj using Qt.createComponent function. -*/ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Controls.Styles 1.1 -import org.ethereum.qml.QVariableDefinition 1.0 - -QVariableDefinition -{ - id: qVariableDefinition -} diff --git a/mix/qml/RegisteringStep.qml b/mix/qml/RegisteringStep.qml deleted file mode 100644 index 5ea83efd8..000000000 --- a/mix/qml/RegisteringStep.qml +++ /dev/null @@ -1,352 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.QEther 1.0 -import Qt.labs.settings 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/NetworkDeployment.js" as NetworkDeploymentCode -import "js/QEtherHelper.js" as QEtherHelper -import "." - -Rectangle { - property variant worker - property string eth: registrarAddr.text - property int ownedRegistrarDeployGas: 1179075 // TODO: Use sol library to calculate gas requirement for each tr. - property int ownedRegistrarSetSubRegistrarGas: 50000 - property int ownedRegistrarSetContentHashGas: 50000 - property int urlHintSuggestUrlGas: 70000 - id: root - color: "#E3E3E3E3" - anchors.fill: parent - signal registered - - function show() - { - ctrRegisterLabel.calculateRegisterGas() - if (applicationUrlHttpCtrl.text === "") - applicationUrlHttpCtrl.text = projectModel.applicationUrlHttp - - if (applicationUrlEthCtrl.text === "") - applicationUrlEthCtrl.text = projectModel.applicationUrlEth - - visible = true - - worker.pooler.onTriggered.connect(function() { - if (root.visible) - verifyRegistering(); - }) - } - - function verifyRegistering() - { - verificationEthUrl.text = "" - if (projectModel.registerContentHashTrHash !== "" && projectModel.registerContentHashBlockNumber !== -1) - { - worker.verifyHash("registerHash", projectModel.registerContentHashTrHash, function(bn, trLost) - { - updateVerification(projectModel.registerContentHashBlockNumber, bn, trLost, verificationEthUrl, "registerHash") - }); - } - else if (projectModel.registerContentHashTrHash !== "" && projectModel.registerContentHashBlockNumber === -1) - verificationEthUrl.text = qsTr("waiting verifications") - - verificationUrl.text = "" - if (projectModel.registerUrlTrHash !== "" && projectModel.registerUrlBlockNumber !== -1) - { - worker.verifyHash("registerUrl", projectModel.registerUrlTrHash, function(bn, trLost) - { - updateVerification(projectModel.registerUrlBlockNumber, bn, trLost, verificationUrl, "registerUrl") - }); - } - else if (projectModel.registerUrlTrHash !== "" && projectModel.registerUrlBlockNumber === -1) - verificationUrl.text = qsTr("waiting verifications") - } - - function updateVerification(originbn, bn, trLost, ctrl, trContext) - { - if (trLost.length === 0) - { - ctrl.text = bn - originbn - if (parseInt(bn - originbn) >= 10) - { - ctrl.color= "green" - ctrl.text= qsTr("verified") - } - else - ctrl.text += qsTr(" verifications") - } - else - { - deploymentStepChanged(trContext + qsTr(" has been invalidated.") + trLost[0] + " " + qsTr("no longer present") ) - ctrl.text = qsTr("invalidated") - } - } - - ColumnLayout - { - anchors.top: parent.top - width: parent.width - anchors.topMargin: 10 - id: col - spacing: 20 - anchors.left: parent.left - anchors.leftMargin: 10 - Label - { - anchors.top: parent.top - Layout.fillWidth: true - text: qsTr("Register your Dapp on the Name registrar Contract") - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Root Registrar address") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - DefaultTextField - { - id: registrarAddr - text: "c6d9d2cd449a754c494264e1809c50e34d64562b" - visible: true - Layout.preferredWidth: 450 - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Http URL") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - DefaultTextField - { - id: applicationUrlHttpCtrl - Layout.preferredWidth: 450 - } - - Label - { - id: verificationUrl - anchors.verticalCenter: parent.verticalCenter - font.italic: true - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Registration Cost") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - id: ctrRegisterLabel - function calculateRegisterGas() - { - if (!modalDeploymentDialog.visible) - return; - appUrlFormatted.text = NetworkDeploymentCode.formatAppUrl(applicationUrlEthCtrl.text).join('/'); - NetworkDeploymentCode.checkPathCreationCost(applicationUrlEthCtrl.text, function(pathCreationCost) - { - var ether = QEtherHelper.createBigInt(pathCreationCost); - if (deploymentDialog.deployStep.gasPrice.value) - { - var gasTotal = ether.multiply(deploymentDialog.deployStep.gasPrice.value.toWei()); - gasToUseDeployInput.value = QEtherHelper.createEther(gasTotal.value(), QEther.Wei, parent); - gasToUseDeployInput.update(); - } - }); - } - } - } - - Ether - { - id: gasToUseDeployInput - displayUnitSelection: false - displayFormattedValue: true - edit: false - Layout.preferredWidth: 235 - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 5 - Label - { - text: qsTr("Ethereum URL") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - Rectangle - { - height: 25 - color: "transparent" - Layout.preferredWidth: 450 - DefaultTextField - { - width: 450 - id: applicationUrlEthCtrl - onTextChanged: { - ctrRegisterLabel.calculateRegisterGas(); - } - } - } - } - - RowLayout - { - Layout.fillWidth: true - Layout.preferredHeight: 20 - Rectangle - { - Layout.preferredWidth: col.width / 4 - Label - { - text: qsTr("Formatted Ethereum URL") - anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - } - } - - DefaultLabel - { - id: appUrlFormatted - anchors.verticalCenter: parent.verticalCenter; - anchors.topMargin: 10 - font.italic: true - font.pointSize: appStyle.absoluteSize(-1) - } - - Label - { - id: verificationEthUrl - anchors.verticalCenter: parent.verticalCenter; - anchors.topMargin: 10 - font.italic: true - font.pointSize: appStyle.absoluteSize(-1) - } - } - } - - RowLayout - { - anchors.bottom: parent.bottom - anchors.bottomMargin: 10 - width: parent.width - - function registerHash(gasPrice, callback) - { - var inError = []; - var ethUrl = NetworkDeploymentCode.formatAppUrl(applicationUrlEthCtrl.text); - for (var k in ethUrl) - { - if (ethUrl[k].length > 32) - inError.push(qsTr("Member too long: " + ethUrl[k]) + "\n"); - } - if (!worker.stopForInputError(inError)) - { - NetworkDeploymentCode.registerDapp(ethUrl, gasPrice, function(){ - projectModel.applicationUrlEth = applicationUrlEthCtrl.text - projectModel.saveProject() - verificationEthUrl.text = qsTr("waiting verifications") - worker.waitForTrReceipt(projectModel.registerContentHashTrHash, function(status, receipt) - { - worker.verifyHash("registerHash", projectModel.registerContentHashTrHash, function(bn, trLost) - { - projectModel.registerContentHashBlockNumber = bn - projectModel.saveProject() - root.updateVerification(bn, bn, trLost, verificationEthUrl) - callback() - }); - }); - }) - } - } - - function registerUrl(gasPrice, callback) - { - if (applicationUrlHttp.text === "" || deploymentDialog.packageHash === "") - { - deployDialog.title = text; - deployDialog.text = qsTr("Please provide the link where the resources are stored and ensure the package is aleary built using the deployment step.") - deployDialog.open(); - return; - } - var inError = []; - if (applicationUrlHttpCtrl.text.length > 32) - inError.push(qsTr(applicationUrlHttpCtrl.text)); - if (!worker.stopForInputError(inError)) - { - var url = applicationUrlHttpCtrl.text - url = url.replace("http://", "").replace("https://", "") - registerToUrlHint(url, gasPrice, function(){ - projectModel.applicationUrlHttp = applicationUrlHttpCtrl.text - projectModel.saveProject() - verificationUrl.text = qsTr("waiting verifications") - worker.waitForTrReceipt(projectModel.registerUrlTrHash, function(status, receipt) - { - worker.verifyHash("registerUrl", projectModel.registerUrlTrHash, function(bn, trLost) - { - projectModel.registerUrlBlockNumber = bn - projectModel.saveProject() - root.updateVerification(bn, bn, trLost, verificationUrl) - root.registered() - callback() - }); - }) - }) - } - } - - Button - { - anchors.right: parent.right - anchors.rightMargin: 10 - text: qsTr("Register Dapp") - width: 30 - onClicked: - { - verificationEthUrl.text = "" - verificationUrl.text = "" - projectModel.cleanRegisteringStatus() - var gasPrice = deploymentDialog.deployStep.gasPrice.toHexWei() - parent.registerHash(gasPrice, function(){ - parent.registerUrl(gasPrice, function(){}) - }) - } - } - } -} - diff --git a/mix/qml/ScenarioButton.qml b/mix/qml/ScenarioButton.qml deleted file mode 100644 index 4c60682ca..000000000 --- a/mix/qml/ScenarioButton.qml +++ /dev/null @@ -1,130 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 -import QtGraphicalEffects 1.0 - -Rectangle { - id: buttonActionContainer - property string text - property string buttonShortcut - property string sourceImg - property string fillColor - property alias roundLeft: left.visible - property alias roundRight: right.visible - signal clicked - - function startBlinking() - { - if (!blinkTimer.running) - blinkTimer.start() - } - - function stopBlinking() - { - blinkTimer.stop() - } - - Rectangle - { - id: left - width: 10 - height: parent.height - anchors.left: contentRectangle.left - anchors.leftMargin: -4 - radius: 15 - } - - Rectangle { - id: contentRectangle - anchors.fill: parent - color: "white" - property variant colorGradient: ["#FFFFFF", "#FFFEFC", "#FFFDF9", "#FFFCF7", "#FFFBF4", "#FFFAF2", "#FFF9EF", "#FFF8EC", "#FFF7EA", "#FFF6E7", "#FFF5E5", "#FFF5E2", "#FFF4E0", "#FFF3DD", "#FFF2DA", "#FFF1D8", "#FFF0D5", "#FFEFD3", "#FFEED0", "#FFEDCE", "#FFECCB", "#FFEBC8", "#FFEBC6", "#FFEAC3", "#FFE9C1", "#FFE8BE", "#FFE7BC", "#FFE6B9", "#FFE5B6", "#FFE4B4", "#FFE3B1", "#FFE2AF", "#FFE1AC", "#FFE1AA", "#FFE0A7", "#FFDFA4", "#FFDEA2", "#FFDD9F", "#FFDC9D", "#FFDB9A", "#FFDA97", "#FFD995", "#FFD892", "#FFD790", "#FFD78D", "#FFD68B", "#FFD588", "#FFD485", "#FFD383", "#FFD280", "#FFD17E", "#FFD07B", "#FFCF79", "#FFCE76", "#FFCD73", "#FFCD71", "#FFCC6E", "#FFCB6C", "#FFCA69", "#FFC967", "#FFC864", "#FFC761", "#FFC65F", "#FFC55C", "#FFC45A", "#FFC357", "#FFC355", "#FFC252", "#FFC14F", "#FFC04D", "#FFBF4A", "#FFBE48", "#FFBD45", "#FFBC42", "#FFBB40", "#FFBA3D", "#FFB93B", "#FFB938", "#FFB836", "#FFB733", "#FFB630", "#FFB52E", "#FFB42B", "#FFB329", "#FFB226", "#FFB124", "#FFB021", "#FFAF1E", "#FFAF1C", "#FFAE19", "#FFAD17", "#FFAC14", "#FFAB12", "#FFAA0F", "#FFA90C", "#FFA80A", "#FFA707", "#FFA605", "#FFA502", "#FFA500"] - - Timer - { - id: blinkTimer - repeat: true - interval: 40 - running: false - property int index: 0 - property int direction: 1 - onTriggered: { - index = index + direction - var color = parent.colorGradient[index] - left.color = color - right.color = color - parent.color = parent.colorGradient[index] - if (index >= parent.colorGradient.length - 1) - direction = -1 - else if (index <= 0) - direction = 1 - } - onRunningChanged: { - if (!running) - { - left.color = "white" - right.color = "white" - parent.color = "white" - index = 0 - direction = 1 - } - } - } - - Image { - id: debugImage - anchors { - left: parent.left - right: parent.right - top: parent.top - bottom: parent.bottom - bottomMargin: debugImg.pressed ? -2 : 0; - topMargin: debugImg.pressed ? 2 : 0; - } - source: sourceImg - fillMode: Image.PreserveAspectFit - } - - Button { - anchors.fill: parent - id: debugImg - action: buttonAction - style: ButtonStyle { - background: Rectangle { - color: "transparent" - } - } - } - - Action { - id: buttonAction - shortcut: buttonShortcut - onTriggered: { - buttonActionContainer.clicked(); - } - } - } - - Rectangle - { - id: right - width: 10 - height: parent.height - anchors.right: contentRectangle.right - anchors.rightMargin: -4 - radius: 15 - } - - Rectangle - { - anchors.top: contentRectangle.bottom - anchors.topMargin: 15 - width: parent.width - Label - { - text: buttonActionContainer.text - anchors.centerIn: parent - } - } -} diff --git a/mix/qml/ScenarioExecution.qml b/mix/qml/ScenarioExecution.qml deleted file mode 100644 index dde32fa97..000000000 --- a/mix/qml/ScenarioExecution.qml +++ /dev/null @@ -1,128 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "." - - -Rectangle { - color: "#ededed" - property alias bc: blockChain - - Connections - { - target: projectModel - onProjectLoaded: { - loader.init() - } - } - - ScrollView - { - anchors.fill: parent - onWidthChanged: { - columnExe.width = width - 40 - } - - ColumnLayout - { - id: columnExe - Layout.preferredWidth: parent.width - anchors.left: parent.left - anchors.leftMargin: 15 - ColumnLayout - { - id: scenarioColumn - width: parent.width - spacing: 10 - ScenarioLoader - { - anchors.horizontalCenter: parent.horizontalCenter - height: 100 - Layout.preferredWidth: 400 - width: 400 - id: loader - } - - Connections - { - target: blockChain - onChainChanged: - { - loader.needSaveOrReload() - } - } - - Rectangle - { - Layout.preferredWidth: parent.width - height: 1 - color: "#cccccc" - } - - Connections - { - target: loader - onLoaded: - { - watchers.clear() - blockChain.load(scenario, loader.selectedScenarioIndex) - } - } - - BlockChain - { - id: blockChain - width: parent.width - } - - Connections - { - target: blockChain - property var currentSelectedBlock - property var currentSelectedTx - onTxSelected: - { - currentSelectedBlock = blockIndex - currentSelectedTx = txIndex - updateWatchers(blockIndex, txIndex) - } - - function updateWatchers(blockIndex, txIndex) - { - var tx = blockChain.model.blocks[blockIndex].transactions[txIndex] - var state = blockChain.getState(tx.recordIndex) - watchers.updateWidthTx(tx, state, blockIndex, txIndex) - } - - onRebuilding: { - watchers.clear() - } - - onAccountAdded: { - watchers.addAccount(address, "0 wei") - } - } - } - - Watchers - { - id: watchers - bc: blockChain - Layout.fillWidth: true - Layout.preferredHeight: 740 - } - - Rectangle - { - color: "transparent" - Layout.preferredHeight: 50 - Layout.fillWidth: true - } - } - } -} diff --git a/mix/qml/ScenarioLoader.qml b/mix/qml/ScenarioLoader.qml deleted file mode 100644 index f47296514..000000000 --- a/mix/qml/ScenarioLoader.qml +++ /dev/null @@ -1,386 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Dialogs 1.2 -import QtQuick.Window 2.0 -import QtQuick.Dialogs 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.InverseMouseArea 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "." - -ColumnLayout -{ - id: blockChainSelector - signal restored(variant scenario) - signal saved(variant scenario) - signal duplicated(variant scenario) - signal loaded(variant scenario) - signal renamed(variant scenario) - signal deleted() - property alias selectedScenarioIndex: scenarioList.currentIndex - spacing: 0 - function init() - { - scenarioList.load() - } - - function needSaveOrReload() - { - } - - RowLayout - { - Layout.preferredWidth: 560 - anchors.horizontalCenter: parent.horizontalCenter - Layout.preferredHeight: 75 - spacing: 0 - anchors.top: parent.top - anchors.topMargin: 10 - - Row - { - Layout.preferredWidth: 100 * 5 + 30 - Layout.preferredHeight: 50 - spacing: 25 - - Rectangle - { - color: "white" - width: 251 + 30 - height: 30 - - Rectangle - { - id: left - width: 10 - height: parent.height - anchors.left: parent.left - anchors.leftMargin: -5 - radius: 15 - } - - Image { - source: "qrc:/qml/img/edittransaction.png" - height: parent.height - 10 - fillMode: Image.PreserveAspectFit - anchors.left: parent.left - anchors.top: parent.top - anchors.topMargin: 4 - id: editImg - MouseArea - { - anchors.fill: parent - onClicked: - { - scenarioNameEdit.toggleEdit() - } - } - } - - Image { - source: "qrc:/qml/img/delete_sign.png" - height: parent.height - 16 - fillMode: Image.PreserveAspectFit - id: deleteImg - anchors.left: editImg.right - anchors.top: parent.top - anchors.topMargin: 8 - visible: projectModel.stateListModel.count > 1 - MouseArea - { - anchors.fill: parent - onClicked: - { - if (projectModel.stateListModel.count > 1) - { - projectModel.stateListModel.deleteState(scenarioList.currentIndex) - scenarioList.init() - } - } - } - } - - Label - { - - MouseArea - { - anchors.fill: parent - onClicked: - { - if (projectModel.stateListModel.count > 1) - { - projectModel.stateListModel.deleteState(scenarioList.currentIndex) - scenarioList.init() - } - } - } - } - - Connections - { - target: projectModel.stateListModel - onStateDeleted: { - scenarioList.init() - } - } - - ComboBox - { - id: scenarioList - anchors.left: deleteImg.right - anchors.leftMargin: 2 - model: projectModel.stateListModel - anchors.top: parent.top - textRole: "title" - height: parent.height - width: 150 - signal updateView() - - onCurrentIndexChanged: - { - restoreScenario.restore() - } - - function init() - { - scenarioList.currentIndex = 0 - deleted() - } - - function load() - { - var state = projectModel.stateListModel.getState(currentIndex) - if (state) - loaded(state) - } - - style: ComboBoxStyle { - id: style - background: Rectangle { - color: "white" - anchors.fill: parent - } - label: Rectangle { - property alias label: comboLabel - anchors.fill: parent - color: "white" - Label { - id: comboLabel - maximumLineCount: 1 - elide: Text.ElideRight - width: parent.width - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - Component.onCompleted: - { - comboLabel.updateLabel() - } - - function updateLabel() - { - comboLabel.text = "" - if (scenarioList.currentIndex > - 1 && scenarioList.currentIndex < projectModel.stateListModel.count) - comboLabel.text = projectModel.stateListModel.getState(scenarioList.currentIndex).title - } - - Connections { - target: blockChainSelector - onLoaded: { - if (projectModel.stateListModel.count > 0) - comboLabel.text = projectModel.stateListModel.getState(scenarioList.currentIndex).title - else - return "" - } - onRenamed: { - comboLabel.text = scenario.title - scenarioNameEdit.text = scenario.title - } - onDeleted: { - comboLabel.updateLabel() - } - } - } - } - } - } - - TextField - { - id: scenarioNameEdit - anchors.left: deleteImg.right - anchors.leftMargin: 2 - height: parent.height - z: 5 - visible: false - width: 150 - Keys.onEnterPressed: - { - toggleEdit() - } - - Keys.onReturnPressed: - { - toggleEdit() - } - - function toggleEdit() - { - scenarioList.visible = !scenarioList.visible - scenarioNameEdit.visible = !scenarioNameEdit.visible - if (!scenarioNameEdit.visible) - scenarioNameEdit.save() - else - { - scenarioNameEdit.text = projectModel.stateListModel.getState(scenarioList.currentIndex).title - scenarioNameEdit.forceActiveFocus() - outsideClick.active = true - } - } - - function save() - { - outsideClick.active = false - projectModel.stateListModel.getState(scenarioList.currentIndex).title = scenarioNameEdit.text - projectModel.saveProjectFile() - saved(state) - scenarioList.model.get(scenarioList.currentIndex).title = scenarioNameEdit.text - scenarioList.currentIndex = scenarioList.currentIndex - renamed(projectModel.stateListModel.getState(scenarioList.currentIndex)) - } - - style: TextFieldStyle { - background: Rectangle { - radius: 2 - implicitWidth: 100 - implicitHeight: 30 - color: "white" - border.color: "#cccccc" - border.width: 1 - } - } - - InverseMouseArea { - id: outsideClick - anchors.fill: parent - active: false - onClickedOutside: { - scenarioNameEdit.toggleEdit() - } - } - } - - Rectangle - { - width: 1 - height: parent.height - anchors.right: addScenario.left - color: "#ededed" - } - - ScenarioButton { - id: addScenario - anchors.left: scenarioList.right - width: 100 - height: parent.height - buttonShortcut: "" - sourceImg: "qrc:/qml/img/restoreicon@2x.png" - onClicked: { - var item = projectModel.stateListModel.createDefaultState(); - item.title = qsTr("New Scenario") - projectModel.stateListModel.appendState(item) - projectModel.stateListModel.save() - scenarioList.currentIndex = projectModel.stateListModel.count - 1 - clientModel.setupScenario(item); - } - text: qsTr("New...") - roundRight: true - roundLeft: false - } - } - - - Rectangle - { - width: 100 * 3 - height: 30 - color: "transparent" - - ScenarioButton { - id: restoreScenario - width: 100 - height: parent.height - buttonShortcut: "" - sourceImg: "qrc:/qml/img/restoreicon@2x.png" - onClicked: { - restore() - } - text: qsTr("Restore") - function restore() - { - var state = projectModel.stateListModel.reloadStateFromProject(scenarioList.currentIndex) - if (state) - { - restored(state) - loaded(state) - } - } - roundRight: false - roundLeft: true - } - - Rectangle - { - width: 1 - height: parent.height - anchors.right: saveScenario.left - color: "#ededed" - } - - ScenarioButton { - id: saveScenario - anchors.left: restoreScenario.right - text: qsTr("Save") - onClicked: { - projectModel.saveProjectFile() - saved(state) - } - width: 100 - height: parent.height - buttonShortcut: "" - sourceImg: "qrc:/qml/img/saveicon@2x.png" - roundRight: false - roundLeft: false - } - - Rectangle - { - width: 1 - height: parent.height - anchors.right: duplicateScenario.left - color: "#ededed" - } - - ScenarioButton - { - id: duplicateScenario - anchors.left: saveScenario.right - text: qsTr("Duplicate") - onClicked: { - projectModel.stateListModel.duplicateState(scenarioList.currentIndex) - duplicated(state) - } - width: 100 - height: parent.height - buttonShortcut: "" - sourceImg: "qrc:/qml/img/duplicateicon@2x.png" - roundRight: true - roundLeft: false - } - } - } - } -} diff --git a/mix/qml/SourceSansProBold.qml b/mix/qml/SourceSansProBold.qml deleted file mode 100644 index 39c99cc8d..000000000 --- a/mix/qml/SourceSansProBold.qml +++ /dev/null @@ -1,6 +0,0 @@ -import QtQuick 2.0 - -FontLoader -{ - source: "qrc:/qml/fonts/SourceSansPro-Bold.ttf" -} diff --git a/mix/qml/SourceSansProLight.qml b/mix/qml/SourceSansProLight.qml deleted file mode 100644 index f46abedd5..000000000 --- a/mix/qml/SourceSansProLight.qml +++ /dev/null @@ -1,7 +0,0 @@ -import QtQuick 2.0 - -FontLoader -{ - source: "qrc:/qml/fonts/SourceSansPro-Light.ttf" -} - diff --git a/mix/qml/SourceSansProRegular.qml b/mix/qml/SourceSansProRegular.qml deleted file mode 100644 index d9ce908e0..000000000 --- a/mix/qml/SourceSansProRegular.qml +++ /dev/null @@ -1,8 +0,0 @@ -import QtQuick 2.0 - -FontLoader -{ - source: "qrc:/qml/fonts/SourceSansPro-Regular.ttf" -} - - diff --git a/mix/qml/Splitter.qml b/mix/qml/Splitter.qml deleted file mode 100644 index 012379700..000000000 --- a/mix/qml/Splitter.qml +++ /dev/null @@ -1,11 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.3 - -SplitView -{ - handleDelegate: Rectangle { - width: 4 - height: 4 - color: "#cccccc" - } -} diff --git a/mix/qml/StateDialog.qml b/mix/qml/StateDialog.qml deleted file mode 100644 index a2d384b3d..000000000 --- a/mix/qml/StateDialog.qml +++ /dev/null @@ -1,380 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Dialogs 1.2 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.0 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.QEther 1.0 -import "js/QEtherHelper.js" as QEtherHelper -import "js/TransactionHelper.js" as TransactionHelper -import "." - -Dialog { - id: modalStateDialog - modality: Qt.ApplicationModal - - width: 630 - height: 660 - title: qsTr("Edit Genesis Parameters") - visible: false - - property alias isDefault: defaultCheckBox.checked - property alias minerComboBox: comboMiner - property int stateIndex - property var stateTransactions: [] - property var stateAccounts: [] - property var stateContracts: [] - signal accepted - - StateDialogStyle { - id: stateDialogStyle - } - - function open(index, item, setDefault) { - stateIndex = index - accountsModel.clear() - stateAccounts = [] - var miner = 0 - for (var k = 0; k < item.accounts.length; k++) { - accountsModel.append(item.accounts[k]) - stateAccounts.push(item.accounts[k]) - if (item.miner && item.accounts[k].name === item.miner.name) - miner = k - } - - stateContracts = [] - if (item.contracts) { - for (k = 0; k < item.contracts.length; k++) { - contractsModel.append(item.contracts[k]) - stateContracts.push(item.contracts[k]) - } - } - - visible = true - isDefault = setDefault - console.log(isDefault) - defaultCheckBox.checked = isDefault - comboMiner.model = stateAccounts - comboMiner.currentIndex = miner - forceActiveFocus() - } - - function acceptAndClose() { - close() - accepted() - } - - function close() { - visible = false - } - - function getItem() { - var item = { - accounts: stateAccounts, - contracts: stateContracts - } - for (var k = 0; k < stateAccounts.length; k++) { - if (stateAccounts[k].name === comboMiner.currentText) { - item.miner = stateAccounts[k] - break - } - } - item.defaultState = defaultCheckBox.checked - return item - } - - contentItem: Rectangle { - color: stateDialogStyle.generic.backgroundColor - Rectangle { - color: stateDialogStyle.generic.backgroundColor - anchors.top: parent.top - anchors.margins: 10 - anchors.fill: parent - ColumnLayout { - anchors.fill: parent - anchors.margins: 10 - ColumnLayout { - id: dialogContent - anchors.top: parent.top - - RowLayout { - Layout.fillWidth: true - - Rectangle { - Layout.preferredWidth: 85 - DefaultLabel { - id: contractsLabel - Layout.preferredWidth: 85 - wrapMode: Text.WrapAnywhere - text: qsTr("Genesis\nContracts") - } - - Button { - id: importStateButton - anchors.top: contractsLabel.bottom - anchors.topMargin: 10 - action: importStateAction - } - - Action { - id: importStateAction - tooltip: qsTr("Import genesis state from JSON file") - text: qsTr("Import...") - onTriggered: { - importJsonFileDialog.open() - } - } - QFileDialog { - id: importJsonFileDialog - visible: false - title: qsTr("Select State File") - nameFilters: Qt.platform.os === "osx" ? [] : [qsTr("JSON files (*.json)", "All files (*)")] //qt 5.4 segfaults with filter string on OSX - onAccepted: { - var path = importJsonFileDialog.fileUrl.toString() - var jsonData = fileIo.readFile(path) - if (jsonData) { - var json = JSON.parse(jsonData) - for (var address in json) { - var account = { - address: address, - name: (json[address].name ? json[address].name : address), - balance: QEtherHelper.createEther(json[address].wei, QEther.Wei), - code: json[address].code, - storage: json[address].storage - } - if (account.code) { - contractsModel.append(account) - stateContracts.push(account) - } else { - accountsModel.append(account) - stateAccounts.push(account) - } - } - } - } - } - } - - TableView { - id: genesisContractsView - Layout.fillWidth: true - model: contractsModel - headerVisible: false - TableViewColumn { - role: "name" - title: qsTr("Name") - width: 230 - delegate: Item { - RowLayout { - height: 25 - width: parent.width - anchors.verticalCenter: parent.verticalCenter - Button { - iconSource: "qrc:/qml/img/delete_sign.png" - action: deleteContractAction - } - - Action { - id: deleteContractAction - tooltip: qsTr("Delete Contract") - onTriggered: { - stateContracts.splice(styleData.row, 1) - contractsModel.remove(styleData.row) - } - } - - DefaultTextField { - anchors.verticalCenter: parent.verticalCenter - onTextChanged: { - if (styleData.row > -1) - stateContracts[styleData.row].name = text - } - text: styleData.value - } - } - } - } - - TableViewColumn { - role: "balance" - title: qsTr("Balance") - width: 200 - delegate: Item { - Ether { - edit: true - displayFormattedValue: false - value: styleData.value - } - } - } - rowDelegate: Rectangle { - color: styleData.alternate ? "transparent" : "#f0f0f0" - height: 30 - } - } - } - - CommonSeparator { - Layout.fillWidth: true - } - - RowLayout { - Layout.fillWidth: true - - Rectangle { - Layout.preferredWidth: 85 - DefaultLabel { - id: accountsLabel - Layout.preferredWidth: 85 - text: qsTr("Accounts") - } - } - - MessageDialog { - id: alertAlreadyUsed - text: qsTr("This account is in use. You cannot remove it. The first account is used to deploy config contract and cannot be removed.") - icon: StandardIcon.Warning - standardButtons: StandardButton.Ok - } - - TableView { - id: accountsView - Layout.fillWidth: true - model: accountsModel - headerVisible: false - TableViewColumn { - role: "name" - title: qsTr("Name") - width: 230 - delegate: Item { - RowLayout { - height: 25 - width: parent.width - Button { - iconSource: "qrc:/qml/img/delete_sign.png" - action: deleteAccountAction - } - - Action { - id: deleteAccountAction - tooltip: qsTr("Delete Account") - onTriggered: { - stateAccounts.splice(styleData.row, 1) - accountsView.model.remove(styleData.row) - } - } - - DefaultTextField { - anchors.verticalCenter: parent.verticalCenter - onTextChanged: { - if (styleData.row > -1) { - stateAccounts[styleData.row].name = text - var index = comboMiner.currentIndex - comboMiner.model = stateAccounts - comboMiner.currentIndex = index - } - } - text: { - return styleData.value - } - } - } - } - } - - TableViewColumn { - role: "balance" - title: qsTr("Balance") - width: 200 - delegate: Item { - Ether { - edit: true - displayFormattedValue: false - value: styleData.value - } - } - } - rowDelegate: Rectangle { - color: styleData.alternate ? "transparent" : "#f0f0f0" - height: 30 - } - } - } - - CommonSeparator { - Layout.fillWidth: true - } - - RowLayout { - Layout.fillWidth: true - DefaultLabel { - Layout.preferredWidth: 85 - text: qsTr("Miner") - } - ComboBox { - id: comboMiner - textRole: "name" - Layout.fillWidth: true - } - } - - CommonSeparator { - Layout.fillWidth: true - } - - RowLayout { - Layout.fillWidth: true - DefaultLabel { - Layout.preferredWidth: 85 - text: qsTr("Default") - } - CheckBox { - id: defaultCheckBox - Layout.fillWidth: true - } - } - - CommonSeparator { - Layout.fillWidth: true - } - - } - - RowLayout { - anchors.bottom: parent.bottom - anchors.right: parent.right - - Button { - text: qsTr("OK") - onClicked: { - close() - accepted() - } - } - Button { - text: qsTr("Cancel") - onClicked: close() - } - } - - ListModel { - id: contractsModel - - function removeContract(_i) { - contractsModel.remove(_i) - stateContracts.splice(_i, 1) - } - } - - ListModel { - id: accountsModel - - function removeAccount(_i) { - accountsModel.remove(_i) - stateAccounts.splice(_i, 1) - } - } - } - } - } -} diff --git a/mix/qml/StateDialogStyle.qml b/mix/qml/StateDialogStyle.qml deleted file mode 100644 index 993e6a1c3..000000000 --- a/mix/qml/StateDialogStyle.qml +++ /dev/null @@ -1,16 +0,0 @@ -import QtQuick 2.0 - -QtObject { - property QtObject generic: QtObject - { - property string backgroundColor: "#ededed" - } - - property QtObject stateDialog: QtObject - { - } - - property QtObject transactionDialog: QtObject - { - } -} diff --git a/mix/qml/StateList.qml b/mix/qml/StateList.qml deleted file mode 100644 index b12aa2fb2..000000000 --- a/mix/qml/StateList.qml +++ /dev/null @@ -1,84 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.2 -import QtQuick.Layouts 1.1 -import QtQuick.Window 2.0 -import "." - -Dialog { - id: stateListContainer - modality: Qt.WindowModal - width: 640 - height: 480 - visible: false - contentItem: Rectangle { - anchors.fill: parent - ColumnLayout - { - anchors.fill: parent - anchors.margins: 10 - TableView { - id: list - Layout.fillHeight: true - Layout.fillWidth: true - model: projectModel.stateListModel - itemDelegate: renderDelegate - headerDelegate: null - frameVisible: false - TableViewColumn { - role: "title" - title: qsTr("Scenario") - width: list.width - } - } - - Row{ - spacing: 5 - anchors.bottom: parent.bottom - anchors.right: parent.right - anchors.rightMargin: 10 - Button { - action: closeAction - } - } - } - } - - Component { - id: renderDelegate - Item { - RowLayout { - anchors.fill: parent - Text { - Layout.fillWidth: true - Layout.fillHeight: true - text: styleData.value - font.pointSize: StateStyle.general.basicFontSize - verticalAlignment: Text.AlignBottom - } - ToolButton { - text: qsTr("Edit Genesis"); - Layout.fillHeight: true - onClicked: list.model.editState(styleData.row); - } - ToolButton { - visible: list.model.defaultStateIndex !== styleData.row - text: qsTr("Delete"); - Layout.fillHeight: true - onClicked: list.model.deleteState(styleData.row); - } - } - } - } - - Row - { - Action { - id: closeAction - text: qsTr("Close") - onTriggered: stateListContainer.close(); - } - } -} - diff --git a/mix/qml/StateListModel.qml b/mix/qml/StateListModel.qml deleted file mode 100644 index 51521ac86..000000000 --- a/mix/qml/StateListModel.qml +++ /dev/null @@ -1,446 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Window 2.2 -import QtQuick.Layouts 1.1 -import org.ethereum.qml.QEther 1.0 -import "js/QEtherHelper.js" as QEtherHelper -import "js/TransactionHelper.js" as TransactionHelper - -Item { - - property alias model: stateListModel - property var stateList: [] - property alias stateDialog: stateDialog - property string defaultAccount: "cb73d9408c4720e230387d956eb0f829d8a4dd2c1055f96257167e14e7169074" //support for old project - - function fromPlainStateItem(s) { - if (!s.accounts) - s.accounts = [stateListModel.newAccount("1000000", QEther.Ether, defaultAccount)]; //support for old project - if (!s.contracts) - s.contracts = []; - - var ret = {}; - ret.title = s.title; - ret.transactions = s.transactions.filter(function(t) { return !t.stdContract; }).map(fromPlainTransactionItem); //support old projects by filtering std contracts - if (s.blocks) - ret.blocks = s.blocks.map(fromPlainBlockItem); - ret.accounts = s.accounts.map(fromPlainAccountItem); - ret.contracts = s.contracts.map(fromPlainAccountItem); - ret.miner = s.miner; - - // support old projects - if (!ret.blocks) - { - ret.blocks = [{ - hash: "", - number: -1, - transactions: [], - status: "pending" - }] - for (var j in ret.transactions) - ret.blocks[0].transactions.push(fromPlainTransactionItem(toPlainTransactionItem(ret.transactions[j]))) - } - return ret; - } - - function fromPlainAccountItem(t) - { - return { - name: t.name, - address: t.address, - secret: t.secret, - balance: QEtherHelper.createEther(t.balance.value, t.balance.unit), - storage: t.storage, - code: t.code, - }; - } - - function fromPlainTransactionItem(t) { - if (!t.sender) - t.sender = defaultAccount; //support for old project - - var r = { - type: t.type, - contractId: t.contractId, - functionId: t.functionId, - url: t.url, - value: QEtherHelper.createEther(t.value.value, t.value.unit), - gas: QEtherHelper.createBigInt(t.gas.value), - gasPrice: QEtherHelper.createEther(t.gasPrice.value, t.gasPrice.unit), - gasAuto: t.gasAuto, - parameters: {}, - sender: t.sender, - isContractCreation: t.isContractCreation, - label: t.label, - isFunctionCall: t.isFunctionCall, - saveStatus: t.saveStatus - }; - - if (r.saveStatus === undefined) - r.saveStatus = true - - if (r.isFunctionCall === undefined) - r.isFunctionCall = true; - - if (!r.label) - r.label = r.contractId + " - " + r.functionId; - - if (r.isContractCreation === undefined) - r.isContractCreation = r.functionId === r.contractId; - - for (var key in t.parameters) - r.parameters[key] = t.parameters[key]; - - return r; - } - - function fromPlainBlockItem(b) - { - var r = { - hash: b.hash, - number: b.number, - transactions: b.transactions.filter(function(t) { return !t.stdContract; }).map(fromPlainTransactionItem), //support old projects by filtering std contracts - status: b.status - } - return r; - } - - function toPlainStateItem(s) { - return { - title: s.title, - blocks: s.blocks.map(toPlainBlockItem), - transactions: s.transactions.map(toPlainTransactionItem), - accounts: s.accounts.map(toPlainAccountItem), - contracts: s.contracts.map(toPlainAccountItem), - miner: s.miner - }; - } - - function getParamType(param, params) - { - for (var k in params) - { - if (params[k].declaration.name === param) - return params[k].declaration.type; - } - return ''; - } - - function toPlainBlockItem(b) - { - var r = { - hash: b.hash, - number: b.number, - transactions: b.transactions.map(toPlainTransactionItem), - status: b.status - } - return r; - } - - function toPlainAccountItem(t) - { - return { - name: t.name, - secret: t.secret, - balance: { - value: t.balance.value, - unit: t.balance.unit - }, - address: t.address, - storage: t.storage, - code: t.code, - }; - } - - function toPlainTransactionItem(t) { - var r = { - type: t.type, - contractId: t.contractId, - functionId: t.functionId, - url: t.url, - value: { value: t.value.value, unit: t.value.unit }, - gas: { value: t.gas.value() }, - gasAuto: t.gasAuto, - gasPrice: { value: t.gasPrice.value, unit: t.gasPrice.unit }, - sender: t.sender, - parameters: {}, - isContractCreation: t.isContractCreation, - label: t.label, - isFunctionCall: t.isFunctionCall, - saveStatus: t.saveStatus - }; - for (var key in t.parameters) - r.parameters[key] = t.parameters[key]; - return r; - } - - Connections { - target: projectModel - onProjectClosed: { - stateListModel.clear(); - stateList = []; - codeModel.reset(); - } - onProjectLoading: stateListModel.loadStatesFromProject(projectData); - onProjectFileSaving: { - projectData.states = [] - for(var i = 0; i < stateListModel.count; i++) - { - projectData.states.push(toPlainStateItem(stateList[i])); - stateListModel.set(i, stateList[i]); - } - projectData.defaultStateIndex = stateListModel.defaultStateIndex; - stateListModel.data = projectData - } - onNewProject: { - var state = toPlainStateItem(stateListModel.createDefaultState()); - state.title = qsTr("Default"); - projectData.states = [ state ]; - projectData.defaultStateIndex = 0; - stateListModel.loadStatesFromProject(projectData); - } - } - - Connections { - target: codeModel - onNewContractCompiled: { - stateListModel.addNewContracts(); - } - onContractRenamed: { - stateListModel.renameContracts(_oldName, _newName); - } - } - - StateDialog { - id: stateDialog - onAccepted: { - var item = stateDialog.getItem(); - saveState(item); - } - - function saveState(item) - { - stateList[stateDialog.stateIndex].accounts = item.accounts - stateList[stateDialog.stateIndex].contracts = item.contracts - stateListModel.get(stateDialog.stateIndex).accounts = item.accounts - stateListModel.get(stateDialog.stateIndex).contracts = item.contracts - stateListModel.accountsValidated(item.accounts) - stateListModel.contractsValidated(item.contracts) - stateListModel.get(stateDialog.stateIndex).miner = item.miner - stateList[stateDialog.stateIndex].miner = item.miner - if (item.defaultState) - { - stateListModel.defaultStateIndex = stateDialog.stateIndex - stateListModel.defaultStateChanged() - } - } - } - - ListModel { - id: stateListModel - property int defaultStateIndex: 0 - property variant data - signal accountsValidated(var _accounts) - signal contractsValidated(var _contracts) - signal defaultStateChanged; - signal stateListModelReady; - signal stateRun(int index) - signal stateDeleted(int index) - - function defaultTransactionItem() - { - return TransactionHelper.defaultTransaction(); - } - - function newAccount(_balance, _unit, _secret) - { - if (!_secret) - _secret = clientModel.newSecret(); - var address = clientModel.address(_secret); - var name = qsTr("Account") + "-" + address.substring(0, 4); - var amount = QEtherHelper.createEther(_balance, _unit) - return { name: name, secret: _secret, balance: amount, address: address }; - } - - function duplicateState(index) - { - var state = stateList[index] - var item = fromPlainStateItem(toPlainStateItem(state)) - item.title = qsTr("Copy of") + " " + state.title - appendState(item) - save() - } - - function createEmptyBlock() - { - return { - hash: "", - number: -1, - transactions: [], - status: "pending" - } - } - - function createDefaultState() { - var item = { - title: "", - transactions: [], - accounts: [], - contracts: [], - blocks: [{ status: "pending", number: -1, hash: "", transactions: []}] - }; - - var account = newAccount("1000000", QEther.Ether, defaultAccount) - item.accounts.push(account); - item.miner = account; - - //add constructors, //TODO: order by dependencies - for(var c in codeModel.contracts) { - var ctorTr = defaultTransactionItem(); - ctorTr.functionId = c; - ctorTr.contractId = c; - ctorTr.label = ctorTr.contractId + "." + ctorTr.contractId + "()" - ctorTr.sender = item.accounts[0].secret; - item.transactions.push(ctorTr); - item.blocks[0].transactions.push(ctorTr) - } - return item; - } - - function renameContracts(oldName, newName) { - var changed = false; - for(var c in codeModel.contracts) { - for (var s = 0; s < stateListModel.count; s++) { - var state = stateList[s]; - for (var t = 0; t < state.transactions.length; t++) { - var transaction = state.transactions[t]; - if (transaction.contractId === oldName) { - transaction.contractId = newName; - if (transaction.functionId === oldName) - transaction.functionId = newName; - changed = true; - state.transactions[t] = transaction; - } - } - stateListModel.set(s, state); - stateList[s] = state; - } - } - if (changed) - save(); - } - - function addNewContracts() { - //add new contracts to empty states - var changed = false; - for (var c in codeModel.contracts) { - for (var s = 0; s < stateListModel.count; s++) { - var state = stateList[s]; - if (state.transactions.length === 0) { - //append this contract - var ctorTr = defaultTransactionItem(); - ctorTr.functionId = c; - ctorTr.contractId = c; - ctorTr.label = ctorTr.contractId + "." + ctorTr.contractId + "()"; - ctorTr.sender = state.accounts[0].secret; - state.transactions.push(ctorTr); - changed = true; - stateListModel.set(s, state); - stateList[s] = state; - } - } - } - if (changed) - save(); - } - - function addState() { - var item = createDefaultState(); - stateDialog.open(stateListModel.count, item, false); - } - - function appendState(item) - { - stateListModel.append(item); - stateList.push(item); - } - - function editState(index) { - stateDialog.open(index, stateList[index], defaultStateIndex === index); - } - - function getState(index) { - return stateList[index]; - } - - function debugDefaultState() { - if (defaultStateIndex >= 0 && defaultStateIndex < stateList.length) - runState(defaultStateIndex); - } - - function runState(index) { - var item = stateList[index]; - clientModel.setupScenario(item); - stateRun(index); - } - - function deleteState(index) { - stateListModel.remove(index); - stateList.splice(index, 1); - if (index === defaultStateIndex) - { - defaultStateIndex = 0; - defaultStateChanged(); - } - else if (defaultStateIndex > index) - defaultStateIndex--; - save(); - stateDeleted(index); - } - - function save() { - projectModel.saveProject(); - } - - function defaultStateName() - { - if (stateList.length > 0) - return stateList[defaultStateIndex].title; - else - return "" - } - - function reloadStateFromProject(index) - { - if (data) - { - var item = fromPlainStateItem(data.states[index]) - stateListModel.set(index, item) - stateList[index] = item - return item - } - } - - function loadStatesFromProject(projectData) - { - data = projectData - if (!projectData.states) - projectData.states = []; - if (projectData.defaultStateIndex !== undefined) - defaultStateIndex = projectData.defaultStateIndex; - else - defaultStateIndex = 0; - var items = projectData.states; - stateListModel.clear(); - stateList = []; - for(var i = 0; i < items.length; i++) { - var item = fromPlainStateItem(items[i]); - stateListModel.append(item); - stateList.push(item); - } - stateListModelReady(); - } - } -} diff --git a/mix/qml/StateStyle.qml b/mix/qml/StateStyle.qml deleted file mode 100644 index c9740957c..000000000 --- a/mix/qml/StateStyle.qml +++ /dev/null @@ -1,14 +0,0 @@ -pragma Singleton -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property int basicFontSize: absoluteSize(1) - } -} diff --git a/mix/qml/StatesComboBox.qml b/mix/qml/StatesComboBox.qml deleted file mode 100644 index 3d2b08eef..000000000 --- a/mix/qml/StatesComboBox.qml +++ /dev/null @@ -1,281 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file StatesComboBox.qml - * @author Ali Mashatan ali@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -import QtQuick 2.0 -import QtQuick.Controls 1.0 -import QtQuick.Layouts 1.1 -import org.ethereum.qml.InverseMouseArea 1.0 - -Rectangle { - id: statesComboBox - - width: 200 - height: 23 - Component.onCompleted: { - var top = dropDownList - while (top.parent) { - top = top.parent - if (top.objectName == "debugPanel") - break - } - var coordinates = dropDownList.mapToItem(top, 0, 0) - //the order is important - dropDownShowdowList.parent = top - dropDownList.parent = top - - dropDownShowdowList.x = coordinates.x - dropDownShowdowList.y = coordinates.y - - dropDownList.x = coordinates.x - dropDownList.y = coordinates.y - } - - signal selectItem(real item) - signal editItem(real item) - signal selectCreate - property int rowHeight: 25 - property variant items - property alias selectedItem: chosenItemText.text - property alias selectedIndex: listView.currentRow - function setSelectedIndex(index) { - listView.currentRow = index - chosenItemText.text = statesComboBox.items.get(index).title - } - - function hideDropDown() - { - if (statesComboBox.state === "dropDown") - statesComboBox.state = ""; - } - - signal comboClicked - - property variant colorItem - property variant colorSelect - - SourceSansProRegular - { - id: regularFont - } - - SourceSansProBold - { - id: boldFont - } - smooth: true - Rectangle { - id: chosenItem - width: parent.width - height: statesComboBox.height - color: statesComboBox.color - Text { - id: chosenItemText - anchors.left: parent.left - anchors.leftMargin: 10 - anchors.verticalCenter: parent.verticalCenter - color: statesComboBox.colorItem - text: "" - font.family: regularFont.name - } - - MouseArea { - id: selectorArea - anchors.fill: parent - onClicked: { - if (statesCombo.state === "") - statesCombo.state = "dropDown"; - } - } - } - - Rectangle { - id: dropDownShowdowList - width: statesComboBox.width - opacity: 0.3 - height: 0 - clip: true - radius: 4 - anchors.top: chosenItem.top - anchors.margins: 2 - color: "gray" - } - //ToDo: We need scrollbar for items - Rectangle { - id: dropDownList - width: statesComboBox.width - height: 0 - clip: true - radius: 4 - anchors.top: chosenItem.top - anchors.topMargin: 23 - color: statesComboBox.color - - InverseMouseArea - { - id: outsideClick - anchors.fill: parent - active: false - onClickedOutside: { - var p = selectorArea.mapFromItem(null, _point.x, _point.y); - if (!selectorArea.contains(Qt.point(p.x, p.y))) - statesCombo.hideDropDown() - } - } - - ColumnLayout { - spacing: 2 - TableView { - id: listView - height: 20 - implicitHeight: 0 - width: statesComboBox.width - model: statesComboBox.items - horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff - currentRow: -1 - headerVisible: false - backgroundVisible: false - alternatingRowColors: false - frameVisible: false - - TableViewColumn { - role: "title" - title: "" - width: statesComboBox.width - delegate: mainItemDelegate - } - rowDelegate: Rectangle { - width: statesComboBox.width - height: statesComboBox.rowHeight - } - Component { - id: mainItemDelegate - Rectangle { - id: itemDelegate - width: statesComboBox.width - height: statesComboBox.height - Text { - id: textItemid - text: styleData.value - color: statesComboBox.colorItem - anchors.top: parent.top - anchors.left: parent.left - anchors.leftMargin: 10 - anchors.topMargin: 5 - font.family: regularFont.name - } - Image { - id: imageItemid - height: 20 - width: 20 - anchors.right: parent.right - anchors.top: parent.top - anchors.margins: 5 - visible: false - fillMode: Image.PreserveAspectFit - source: "img/edit_combox.png" - } - - MouseArea { - anchors.fill: parent - hoverEnabled: true - - onEntered: { - imageItemid.visible = true - textItemid.color = statesComboBox.colorSelect - } - onExited: { - imageItemid.visible = false - textItemid.color = statesComboBox.colorItem - } - onClicked: { - if (mouseX > imageItemid.x - && mouseX < imageItemid.x + imageItemid.width - && mouseY > imageItemid.y - && mouseY < imageItemid.y + imageItemid.height) - statesComboBox.editItem(styleData.row) - else { - statesComboBox.state = "" - var prevSelection = chosenItemText.text - chosenItemText.text = styleData.value - listView.currentRow = styleData.row - statesComboBox.selectItem(styleData.row) - } - } - } - } //Item - } //Component - } //Table View - - RowLayout { - anchors.top: listView.bottom - anchors.topMargin: 4 - anchors.left: parent.left - anchors.leftMargin: 10 - Text { - id: createStateText - width: statesComboBox.width - height: statesComboBox.height - font.family: boldFont.name - color: "#808080" - text: qsTr("Create State ...") - font.weight: Font.DemiBold - MouseArea { - anchors.fill: parent - hoverEnabled: true - - onEntered: { - createStateText.color = statesComboBox.colorSelect - } - onExited: { - createStateText.color = statesComboBox.colorItem - } - onClicked: { - statesComboBox.state = "" - statesComboBox.selectCreate() - } - } - } - } - } - } - states: State { - name: "dropDown" - PropertyChanges { - target: dropDownList - height: (statesComboBox.rowHeight * (statesComboBox.items.count + 1)) - } - PropertyChanges { - target: dropDownShowdowList - width: statesComboBox.width + 3 - height: (statesComboBox.rowHeight * (statesComboBox.items.count + 1)) + 3 - } - PropertyChanges { - target: listView - height: 20 - implicitHeight: (statesComboBox.rowHeight * (statesComboBox.items.count)) - } - PropertyChanges { - target: outsideClick - active: true - } - } -} diff --git a/mix/qml/StatusPane.qml b/mix/qml/StatusPane.qml deleted file mode 100644 index 23a39d126..000000000 --- a/mix/qml/StatusPane.qml +++ /dev/null @@ -1,417 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.InverseMouseArea 1.0 -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "." - -Rectangle { - id: statusHeader - objectName: "statusPane" - property variant webPreview - property alias currentStatus: logPane.currentStatus - function updateStatus(message) - { - if (!message) - { - status.state = ""; - status.text = qsTr("Compile successfully."); - debugImg.state = "active"; - currentStatus = { "type": "Comp", "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": status.text, "level": "info" } - } - else - { - status.state = "error"; - var errorInfo = ErrorLocationFormater.extractErrorInfo(message, true); - status.text = errorInfo.errorLocation + " " + errorInfo.errorDetail; - debugImg.state = ""; - currentStatus = { "type": "Comp", "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": status.text, "level": "error" } - } - } - - function infoMessage(text, type) - { - status.state = ""; - status.text = text - logPane.push("info", type, text); - currentStatus = { "type": type, "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": text, "level": "info" } - } - - function warningMessage(text, type) - { - status.state = "warning"; - status.text = text - logPane.push("warning", type, text); - currentStatus = { "type": type, "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": text, "level": "warning" } - } - - function errorMessage(text, type) - { - status.state = "error"; - status.text = text; - logPane.push("error", type, text); - currentStatus = { "type": type, "date": Qt.formatDateTime(new Date(), "hh:mm:ss"), "content": text, "level": "error" } - } - - function clear() - { - status.state = ""; - status.text = ""; - } - - StatusPaneStyle { - id: statusPaneStyle - } - - Connections { - target: webPreview - onJavaScriptMessage: - { - if (_level === 0) - infoMessage(_content, "JavaScript") - else - { - var message = _sourceId.substring(_sourceId.lastIndexOf("/") + 1) + " - " + qsTr("line") + " " + _lineNb + " - " + _content; - if (_level === 1) - warningMessage(message, "JavaScript") - else - errorMessage(message, "JavaScript") - } - } - } - - Connections { - target:clientModel - onRunStarted: - { - logPane.clear() - infoMessage(qsTr("Running transactions..."), "Run"); - } - onRunFailed: errorMessage(format(_message), "Run"); - onRunComplete: infoMessage(qsTr("Run complete"), "Run"); - onNewBlock: infoMessage(qsTr("New block created"), "State"); - - function format(_message) - { - var formatted = _message.match(/(?:)/); - if (!formatted) - formatted = _message.match(/(?:)/); - if (formatted && formatted.length > 1) - formatted = formatted[1]; - else - return _message; - var exceptionInfos = _message.match(/(?:tag_)(.+)/g); - if (exceptionInfos !== null && exceptionInfos.length > 0) - formatted += ": " - for (var k in exceptionInfos) - formatted += " " + exceptionInfos[k].replace("*]", "").replace("tag_", "").replace("=", ""); - return formatted; - } - } - - Connections { - target: codeModel - onCompilationComplete: - { - goToLine.visible = false; - updateStatus(); - } - - onCompilationError: - { - goToLine.visible = true - updateStatus(_error); - } - } - - color: "transparent" - anchors.fill: parent - - Rectangle { - id: statusContainer - anchors.horizontalCenter: parent.horizontalCenter - anchors.verticalCenter: parent.verticalCenter - radius: 3 - width: 600 - height: 30 - color: "#fcfbfc" - Text { - anchors.verticalCenter: parent.verticalCenter - anchors.horizontalCenter: parent.horizontalCenter - font.pointSize: appStyle.absoluteSize(-1) - font.family: "sans serif" - objectName: "status" - wrapMode: Text.WrapAnywhere - elide: Text.ElideRight - maximumLineCount: 1 - clip: true - id: status - states: [ - State { - name: "error" - PropertyChanges { - target: status - color: "red" - } - PropertyChanges { - target: statusContainer - color: "#fffcd5" - } - }, - State { - name: "warning" - PropertyChanges { - target: status - color: "orange" - } - PropertyChanges { - target: statusContainer - color: "#fffcd5" - } - } - ] - onTextChanged: - { - updateWidth() - toolTipInfo.tooltip = text; - } - - function updateWidth() - { - if (text.length > 100) - width = parent.width - 10 - else - width = undefined - } - } - - Button - { - anchors.fill: parent - id: toolTip - action: toolTipInfo - text: "" - z: 3; - style: - ButtonStyle { - background:Rectangle { - color: "transparent" - } - } - MouseArea { - anchors.fill: parent - onClicked: { - var globalCoord = goToLineBtn.mapToItem(statusContainer, 0, 0); - if (mouseX > globalCoord.x - && mouseX < globalCoord.x + goToLineBtn.width - && mouseY > globalCoord.y - && mouseY < globalCoord.y + goToLineBtn.height) - goToCompilationError.trigger(goToLineBtn); - else - logsContainer.toggle(); - } - } - } - - Rectangle - { - visible: false - color: "transparent" - width: 40 - height: parent.height - anchors.top: parent.top - anchors.left: status.right - anchors.leftMargin: 15 - id: goToLine - RowLayout - { - anchors.fill: parent - Rectangle - { - color: "transparent" - anchors.fill: parent - Button - { - z: 4 - anchors.centerIn: parent - id: goToLineBtn - text: "" - width: 30 - height: 30 - action: goToCompilationError - style: ButtonStyle { - background: Rectangle { - color: "transparent" - - Image { - source: "qrc:/qml/img/warningicon.png" - height: 30 - width: 30 - sourceSize.width: 30 - sourceSize.height: 30 - anchors.centerIn: parent - } - } - } - } - } - } - } - - Action { - id: toolTipInfo - tooltip: "" - } - - Rectangle - { - id: logsShadow - width: logsContainer.width + 5 - height: 0 - opacity: 0.3 - clip: true - anchors.top: logsContainer.top - anchors.margins: 4 - Rectangle { - color: "gray" - anchors.top: parent.top - radius: 10 - id: roundRect - height: 400 - width: parent.width - } - } - - - - Rectangle - { - InverseMouseArea - { - id: outsideClick - anchors.fill: parent - active: false - onClickedOutside: { - logsContainer.toggle(); - } - } - - function toggle() - { - if (logsContainer.state === "opened") - { - statusContainer.visible = true - logsContainer.state = "closed" - } - else - { - statusContainer.visible = false - logsContainer.state = "opened"; - logsContainer.focus = true; - forceActiveFocus(); - calCoord() - move() - } - } - - id: logsContainer - width: 750 - anchors.top: statusContainer.bottom - anchors.topMargin: 4 - visible: false - radius: 10 - - function calCoord() - { - if (!logsContainer.parent.parent) - return - var top = logsContainer; - while (top.parent) - top = top.parent - var coordinates = logsContainer.mapToItem(top, 0, 0); - logsContainer.parent = top; - logsShadow.parent = top; - top.onWidthChanged.connect(move) - top.onHeightChanged.connect(move) - } - - function move() - { - var statusGlobalCoord = status.mapToItem(null, 0, 0); - logsContainer.x = statusGlobalCoord.x - logPane.contentXPos - logsShadow.x = statusGlobalCoord.x - logPane.contentXPos - logsShadow.z = 1 - logsContainer.z = 2 - if (Qt.platform.os === "osx") - { - logsContainer.y = statusGlobalCoord.y; - logsShadow.y = statusGlobalCoord.y; - } - } - - LogsPaneStyle { - id: logStyle - } - - LogsPane - { - id: logPane; - statusPane: statusHeader - onContentXPosChanged: - { - parent.move(); - } - } - - states: [ - State { - name: "opened"; - PropertyChanges { target: logsContainer; height: 500; visible: true } - PropertyChanges { target: logsShadow; height: 500; visible: true } - PropertyChanges { target: outsideClick; active: true } - - }, - State { - name: "closed"; - PropertyChanges { target: logsContainer; height: 0; visible: false } - PropertyChanges { target: statusContainer; width: 600; height: 30 } - PropertyChanges { target: outsideClick; active: false } - PropertyChanges { target: logsShadow; height: 0; visible: false } - } - ] - transitions: Transition { - NumberAnimation { properties: "height"; easing.type: Easing.InOutQuad; duration: 200 } - NumberAnimation { target: logsContainer; properties: "visible"; easing.type: Easing.InOutQuad; duration: 200 } - } - } - } - - Rectangle - { - color: "transparent" - width: 100 - height: parent.height - anchors.top: parent.top - anchors.right: parent.right - RowLayout - { - anchors.fill: parent - Rectangle - { - color: "transparent" - anchors.fill: parent - Button - { - anchors.right: parent.right - anchors.rightMargin: 9 - anchors.verticalCenter: parent.verticalCenter - id: debugImg - text: "" - iconSource: "qrc:/qml/img/bugiconactive.png" - action: showHideRightPanelAction - } - } - } - } -} diff --git a/mix/qml/StatusPaneStyle.qml b/mix/qml/StatusPaneStyle.qml deleted file mode 100644 index 1eb11b48e..000000000 --- a/mix/qml/StatusPaneStyle.qml +++ /dev/null @@ -1,14 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property int statusFontSize: absoluteSize(-1) - property int logLinkFontSize: absoluteSize(-2) - } -} diff --git a/mix/qml/StepActionImage.qml b/mix/qml/StepActionImage.qml deleted file mode 100644 index e2a1ab8e9..000000000 --- a/mix/qml/StepActionImage.qml +++ /dev/null @@ -1,124 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 - -Rectangle { - id: buttonActionContainer - property string disableStateImg - property string enabledStateImg - property string buttonTooltip - property string buttonShortcut - property bool buttonLeft - property bool buttonRight - signal clicked - - color: "transparent" - width: 35 - height: 24 - - function enabled(state) - { - buttonAction.enabled = state; - if (state) - debugImage.source = enabledStateImg; - else - debugImage.source = disableStateImg; - } - - Rectangle { - color: "#DCDADA" - width: 10 - height: 24 - radius: 4 - x: 0 - visible: buttonLeft - - Rectangle { - anchors { - left: parent.left - right: parent.right - top: parent.top - bottom: parent.bottom - bottomMargin: debugImg.pressed ? 0 : 1; - topMargin: debugImg.pressed ? 1 : 0; - } - color: "#FCFBFC" - radius: 3 - } - } - - Rectangle { - color: "#DCDADA" - width: 10 - height: 24 - radius: 4 - x: 25 - visible: buttonRight - - Rectangle { - anchors { - left: parent.left - right: parent.right - top: parent.top - bottom: parent.bottom - bottomMargin: debugImg.pressed ? 0 : 1; - topMargin: debugImg.pressed? 1 : 0; - } - color: "#FCFBFC" - radius: 3 - } - } - - Rectangle { - id: contentRectangle - width: 25 - height: 24 - color: "#DCDADA" - x: 5 - - Rectangle { - anchors { - left: parent.left - right: parent.right - top: parent.top - bottom: parent.bottom - bottomMargin: debugImg.pressed ? 0 : 1; - topMargin: debugImg.pressed ? 1 : 0; - } - color: "#FCFBFC" - - Image { - id: debugImage - source: enabledStateImg - anchors.centerIn: parent - anchors.topMargin: debugImg.pressed ? 1 : 0; - - fillMode: Image.PreserveAspectFit - width: 15 - height: 15 - } - - } - - Button { - anchors.fill: parent - id: debugImg - action: buttonAction - style: ButtonStyle { - background: Rectangle { - color: "transparent" - } - } - } - - Action { - tooltip: buttonTooltip - id: buttonAction - shortcut: buttonShortcut - onTriggered: { - buttonActionContainer.clicked(); - } - } - } -} diff --git a/mix/qml/StorageView.qml b/mix/qml/StorageView.qml deleted file mode 100644 index ecd64ccf8..000000000 --- a/mix/qml/StorageView.qml +++ /dev/null @@ -1,69 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Layouts 1.1 -import "." - -DebugInfoList -{ - id: storage - collapsible: true - title : qsTr("Storage") - itemDelegate: - Item { - anchors.fill: parent - RowLayout - { - id: row - anchors.fill: parent - Rectangle - { - color: "#f7f7f7" - Layout.fillWidth: true - Layout.minimumWidth: parent.width / 2 - Layout.maximumWidth: parent.width / 2 - Text { - anchors.verticalCenter: parent.verticalCenter - anchors.left: parent.left - font.family: "monospace" - anchors.leftMargin: 5 - color: "#4a4a4a" - text: styleData.value.split('\t')[0]; - font.pointSize: dbgStyle.general.basicFontSize - width: parent.width - 5 - elide: Text.ElideRight - } - } - Rectangle - { - color: "transparent" - Layout.fillWidth: true - Layout.minimumWidth: parent.width / 2 - Layout.maximumWidth: parent.width / 2 - Text { - maximumLineCount: 1 - clip: true - anchors.leftMargin: 5 - width: parent.width - 5 - wrapMode: Text.WrapAnywhere - anchors.left: parent.left - font.family: "monospace" - anchors.verticalCenter: parent.verticalCenter - color: "#4a4a4a" - text: styleData.value.split('\t')[1]; - elide: Text.ElideRight - font.pointSize: dbgStyle.general.basicFontSize - } - } - } - - Rectangle { - anchors.top: row.bottom - width: parent.width; - height: 1; - color: "#cccccc" - anchors.bottom: parent.bottom - } - } -} - diff --git a/mix/qml/StructView.qml b/mix/qml/StructView.qml deleted file mode 100644 index 97c2d27b8..000000000 --- a/mix/qml/StructView.qml +++ /dev/null @@ -1,156 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import org.ethereum.qml.QSolidityType 1.0 - -Column -{ - id: root - property alias members: repeater.model //js array - property variant accounts - property var value: ({}) - property int blockIndex - property int transactionIndex - property string context - property bool readOnly - Layout.fillWidth: true - spacing: 0 - property int colHeight - - function clear() - { - value = {} - members = [] - colHeight = 0 - } - - Repeater - { - id: repeater - visible: members.length > 0 - RowLayout - { - id: row - Layout.fillWidth: true - - Component.onCompleted: - { - if (QSolidityType.Address === members[index].type.category && members[index].type.array && context === "parameter") - height = 60 - else - height = 30 + (members[index].type.category === QSolidityType.Struct ? (30 * members[index].type.members.length) : 0) - root.colHeight += height - } - - Rectangle - { - Layout.preferredWidth: 150 - Row - { - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - Label - { - id: nameLabel - text: modelData.name - } - - Label - { - id: typeLabel - text: " (" + modelData.type.name + ")" - font.italic: true - font.weight: Font.Light - } - } - } - - Loader - { - id: typeLoader - sourceComponent: - { - var t = modelData.type.category; - if (t === QSolidityType.SignedInteger || t === QSolidityType.UnsignedInteger) - return Qt.createComponent("qrc:/qml/QIntTypeView.qml"); - else if (t === QSolidityType.Bool) - return Qt.createComponent("qrc:/qml/QBoolTypeView.qml"); - else if (t === QSolidityType.Bytes || t === QSolidityType.String) - return Qt.createComponent("qrc:/qml/QStringTypeView.qml"); - else if (t === QSolidityType.Hash) - return Qt.createComponent("qrc:/qml/QHashTypeView.qml"); - else if (t === QSolidityType.Struct) - return Qt.createComponent("qrc:/qml/StructView.qml"); - else if (t === QSolidityType.Enum) - return Qt.createComponent("qrc:/qml/QIntTypeView.qml"); - else if (t === QSolidityType.Address) - return Qt.createComponent("qrc:/qml/QAddressView.qml"); - else - return undefined; - } - onLoaded: - { - var ptype = members[index].type; - var pname = members[index].name; - var vals = value; - - item.readOnly = context === "variable"; - if (ptype.category === QSolidityType.Address) - { - item.accounts = accounts - item.value = getValue(); - if (context === "parameter") - { - var dec = modelData.type.name.split(" "); - item.subType = dec[0]; - item.load(); - } - item.init(); - } - else if (ptype.category === QSolidityType.Struct && !item.members) - { - item.value = getValue(); - item.members = ptype.members; - } - else - item.value = getValue(); - - if (ptype.category === QSolidityType.Bool) - { - item.subType = modelData.type.name - item.init(); - } - - item.onValueChanged.connect(function() { - syncValue(vals, pname) - }); - - var newWidth = nameLabel.width + typeLabel.width + item.width + 108; - if (root.width < newWidth) - root.width = newWidth; - - syncValue(vals, pname) - } - - function syncValue(vals, pname) - { - vals[pname] = item.value; - valueChanged(); - } - - - function getValue() - { - var r = ""; - if (value && value[modelData.name] !== undefined) - r = value[modelData.name]; - else if (modelData.type.category === QSolidityType.Struct) - r = {}; - if (Array.isArray(r)) - r = r.join(", "); - return r; - } - } - } - } -} diff --git a/mix/qml/Style.qml b/mix/qml/Style.qml deleted file mode 100644 index 422831c78..000000000 --- a/mix/qml/Style.qml +++ /dev/null @@ -1,19 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject generic: QtObject { - property QtObject layout: QtObject { - property string separatorColor: "#808080" - property string backgroundColor: "#ededed" - } - property QtObject size: QtObject { - property string titlePointSize: absoluteSize(0) - } - } -} diff --git a/mix/qml/TabStyle.qml b/mix/qml/TabStyle.qml deleted file mode 100644 index cbae6e25e..000000000 --- a/mix/qml/TabStyle.qml +++ /dev/null @@ -1,23 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 - -TabViewStyle { - frameOverlap: 1 - tabBar: Rectangle { - color: "lightgray" - } - tab: Rectangle { - color: "lightsteelblue" - implicitWidth: Math.max(text.width + 4, 80) - implicitHeight: 20 - radius: 2 - Text { - id: text - anchors.centerIn: parent - text: styleData.title - color: styleData.selected ? "white" : "black" - } - } - frame: Rectangle { color: "steelblue" } -} diff --git a/mix/qml/TransactionDialog.qml b/mix/qml/TransactionDialog.qml deleted file mode 100644 index f0440101b..000000000 --- a/mix/qml/TransactionDialog.qml +++ /dev/null @@ -1,730 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.1 -import QtQuick.Dialogs 1.2 -import QtQuick.Window 2.0 -import QtQuick.Controls.Styles 1.3 -import org.ethereum.qml.QEther 1.0 -import "js/TransactionHelper.js" as TransactionHelper -import "js/InputValidator.js" as InputValidator -import "js/NetworkDeployment.js" as NetworkDeployment -import "js/QEtherHelper.js" as QEtherHelper -import "." - -Dialog { - id: modalTransactionDialog - modality: Qt.ApplicationModal - width: 580 - height: 500 - visible: false - title: editMode ? qsTr("Edit Transaction") : qsTr("Add Transaction") - property bool editMode - property int transactionIndex - property int blockIndex - property alias gas: gasValueEdit.gasValue; - property alias gasAuto: gasAutoCheck.checked; - property alias gasPrice: gasPriceField.value; - property alias transactionValue: valueField.value; - property string contractId: contractCreationComboBox.currentValue(); - property alias functionId: functionComboBox.currentText; - property var paramValues; - property var paramsModel: []; - property bool useTransactionDefaultValue: false - property alias stateAccounts: senderComboBox.model - property bool saveStatus - signal accepted; - property int rowWidth: 500 - StateDialogStyle { - id: transactionDialogStyle - } - - function open(index, blockIdx, item) { - transactionIndex = index - blockIndex = blockIdx - paramScroll.transactionIndex = index - paramScroll.blockIndex = blockIdx - saveStatus = item.saveStatus - gasValueEdit.gasValue = item.gas; - gasAutoCheck.checked = item.gasAuto ? true : false; - gasPriceField.value = item.gasPrice; - valueField.value = item.value; - var contractId = item.contractId; - var functionId = item.functionId; - - paramValues = item.parameters !== undefined ? item.parameters : {}; - if (item.sender) - senderComboBox.select(item.sender); - - trTypeCreate.checked = item.isContractCreation - trTypeSend.checked = !item.isFunctionCall - trTypeExecute.checked = item.isFunctionCall && !item.isContractCreation - - load(item.isContractCreation, item.isFunctionCall, functionId, contractId) - - estimatedGas.updateView() - visible = true; - } - - function loadCtorParameters(contractId) - { - paramsModel = []; - var contract = codeModel.contracts[contractId]; - if (contract) { - var params = contract.contract.constructor.parameters; - for (var p = 0; p < params.length; p++) - loadParameter(params[p]); - } - initTypeLoader(); - } - - function loadFunctions(contractId) - { - functionsModel.clear(); - var contract = codeModel.contracts[contractId]; - if (contract) { - var functions = codeModel.contracts[contractId].contract.functions; - for (var f = 0; f < functions.length; f++) { - if (functions[f].name !== contractId) - functionsModel.append({ text: functions[f].name }); - } - } - } - - function selectContract(contractName) - { - for (var k = 0; k < contractsModel.count; k++) - { - if (contractsModel.get(k).cid === contractName) - { - contractComboBox.currentIndex = k; - break; - } - } - } - - function selectFunction(functionId) - { - var functionIndex = -1; - for (var f = 0; f < functionsModel.count; f++) - if (functionsModel.get(f).text === functionId) - functionIndex = f; - - if (functionIndex == -1 && functionsModel.count > 0) - functionIndex = 0; //@todo suggest unused function - - functionComboBox.currentIndex = functionIndex; - } - - function loadParameter(parameter) - { - var type = parameter.type; - var pname = parameter.name; - paramsModel.push({ name: pname, type: type }); - } - - function loadParameters() { - paramsModel = [] - if (functionComboBox.currentIndex >= 0 && functionComboBox.currentIndex < functionsModel.count) { - var contract = codeModel.contracts[TransactionHelper.contractFromToken(recipientsAccount.currentValue())]; - if (contract) { - var func = getFunction(functionComboBox.currentText, contract); - if (func) { - var parameters = func.parameters; - for (var p = 0; p < parameters.length; p++) - loadParameter(parameters[p]); - } - } - } - initTypeLoader(); - } - - function getFunction(name, contract) - { - for (var k in contract.contract.functions) - { - if (contract.contract.functions[k].name === name) - { - return contract.contract.functions[k] - } - } - return null - } - - function initTypeLoader() - { - paramScroll.clear() - paramScroll.value = paramValues; - paramScroll.members = paramsModel; - paramScroll.updateView() - } - - function acceptAndClose() - { - close(); - accepted(); - } - - function close() - { - visible = false; - } - - function getItem() - { - var item; - if (!useTransactionDefaultValue) - { - item = { - contractId: transactionDialog.contractId, - functionId: transactionDialog.functionId, - gas: transactionDialog.gas, - gasAuto: transactionDialog.gasAuto, - gasPrice: transactionDialog.gasPrice, - value: transactionDialog.transactionValue, - parameters: {}, - }; - } - else - { - item = TransactionHelper.defaultTransaction(); - item.contractId = transactionDialog.contractId; - item.functionId = transactionDialog.functionId; - } - - item.isContractCreation = trTypeCreate.checked; - if (item.isContractCreation) - item.functionId = item.contractId; - item.isFunctionCall = trTypeExecute.checked - - if (!item.isContractCreation) - { - item.contractId = recipientsAccount.currentValue(); - item.label = TransactionHelper.contractFromToken(item.contractId) + "." + item.functionId + "()"; - if (recipientsAccount.current().type === "address") - { - item.functionId = ""; - item.isFunctionCall = false; - } - } - else - { - item.isFunctionCall = true - item.functionId = item.contractId; - item.label = item.contractId + "." + item.contractId + "()"; - } - item.saveStatus = saveStatus - item.sender = senderComboBox.model[senderComboBox.currentIndex].secret; - item.parameters = paramValues; - return item; - } - - function load(isContractCreation, isFunctionCall, functionId, contractId) - { - if (!isContractCreation) - { - contractCreationComboBox.visible = false - recipientsAccount.visible = true - recipientsAccount.accounts = senderComboBox.model; - amountLabel.text = qsTr("Amount") - if (!isFunctionCall) - recipientsAccount.subType = "address" - else - recipientsAccount.subType = "contract"; - recipientsAccount.load(); - recipientsAccount.init(); - if (contractId) - recipientsAccount.select(contractId); - if (functionId) - selectFunction(functionId); - else - functionComboBox.currentIndex = 0 - if (isFunctionCall) - { - labelRecipient.text = qsTr("Recipient Contract") - functionRect.show() - loadFunctions(TransactionHelper.contractFromToken(recipientsAccount.currentValue())) - loadParameters(); - paramScroll.updateView() - } - else - { - paramsModel = [] - paramScroll.updateView() - labelRecipient.text = qsTr("Recipient Account") - functionRect.hide() - } - } - else - { - //contract creation - contractsModel.clear(); - var contractIndex = -1; - var contracts = codeModel.contracts; - for (var c in contracts) { - contractsModel.append({ cid: c, text: contracts[c].contract.name }); - if (contracts[c].contract.name === contractId) - contractIndex = contractsModel.count - 1; - } - - if (contractIndex == -1 && contractsModel.count > 0) - contractIndex = 0; //@todo suggest unused contract - contractCreationComboBox.currentIndex = contractIndex; - contractCreationComboBox.visible = true - labelRecipient.text = qsTr("Contract") - amountLabel.text = qsTr("Endownment") - functionRect.hide() - recipientsAccount.visible = false - loadCtorParameters(contractCreationComboBox.currentValue()); - paramScroll.updateView() - } - } - - contentItem: Rectangle { - id: containerRect - color: transactionDialogStyle.generic.backgroundColor - anchors.fill: parent - ScrollView - { - anchors.top: parent.top - anchors.fill: parent - ColumnLayout { - Layout.preferredWidth: rowWidth - anchors.top: parent.top - anchors.topMargin: 10 - anchors.left: parent.left - width: 500 - anchors.leftMargin: - { - return (containerRect.width - 530) /2 - } - - RowLayout - { - Rectangle - { - Layout.preferredWidth: 150 - Label { - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - text: qsTr("Sender Account") - } - } - - ComboBox { - function select(secret) - { - for (var i in model) - if (model[i].secret === secret) - { - currentIndex = i; - break; - } - } - Layout.preferredWidth: 350 - id: senderComboBox - currentIndex: 0 - textRole: "name" - editable: false - } - } - - RowLayout - { - Rectangle - { - Layout.preferredWidth: 150 - Layout.preferredHeight: 80 - color: "transparent" - Label - { - anchors.verticalCenter: parent.verticalCenter - anchors.top: parent.top - anchors.right: parent.right - text: qsTr("Type of Transaction") - } - } - - Column - { - Layout.preferredWidth: 350 - Layout.preferredHeight: 90 - ExclusiveGroup { - id: rbbuttonList - onCurrentChanged: { - if (current) - { - if (current.objectName === "trTypeSend") - { - recipientsAccount.visible = true - contractCreationComboBox.visible = false - modalTransactionDialog.load(false, false) - } - else if (current.objectName === "trTypeCreate") - { - contractCreationComboBox.visible = true - recipientsAccount.visible = false - modalTransactionDialog.load(true, true) - } - else if (current.objectName === "trTypeExecute") - { - recipientsAccount.visible = true - contractCreationComboBox.visible = false - modalTransactionDialog.load(false, true) - } - } - } - } - - RadioButton { - id: trTypeSend - objectName: "trTypeSend" - exclusiveGroup: rbbuttonList - height: 30 - text: qsTr("Send ether to account") - - } - - RadioButton { - id: trTypeCreate - objectName: "trTypeCreate" - exclusiveGroup: rbbuttonList - height: 30 - text: qsTr("Create Contract") - } - - RadioButton { - id: trTypeExecute - objectName: "trTypeExecute" - exclusiveGroup: rbbuttonList - height: 30 - text: qsTr("Transact with Contract") - } - } - } - - RowLayout - { - Rectangle - { - Layout.preferredWidth: 150 - Label { - id: labelRecipient - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - text: qsTr("Recipient Account") - } - } - - QAddressView - { - id: recipientsAccount - displayInput: false - onIndexChanged: - { - if (rbbuttonList.current.objectName === "trTypeExecute") - loadFunctions(TransactionHelper.contractFromToken(currentValue())) - } - } - - ComboBox { - id: contractCreationComboBox - function currentValue() { - return (currentIndex >=0 && currentIndex < contractsModel.count) ? contractsModel.get(currentIndex).cid : ""; - } - Layout.preferredWidth: 350 - currentIndex: -1 - textRole: "text" - editable: false - model: ListModel { - id: contractsModel - } - onCurrentIndexChanged: { - loadCtorParameters(currentValue()); - } - } - } - - RowLayout - { - Rectangle - { - Layout.preferredWidth: 150 - id: functionRect - - function hide() - { - parent.visible = false - functionRect.visible = false - functionComboBox.visible = false - } - - function show() - { - parent.visible = true - functionRect.visible = true - functionComboBox.visible = true - } - - Label { - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - text: qsTr("Function") - } - } - - ComboBox { - id: functionComboBox - Layout.preferredWidth: 350 - currentIndex: -1 - textRole: "text" - editable: false - model: ListModel { - id: functionsModel - } - onCurrentIndexChanged: { - loadParameters(); - } - } - } - - StructView - { - id: paramScroll - members: paramsModel - accounts: senderComboBox.model - context: "parameter" - Layout.fillWidth: true - function updateView() - { - paramScroll.visible = paramsModel.length > 0 - paramScroll.Layout.preferredHeight = paramScroll.colHeight - if (paramsModel.length === 0) - paramScroll.height = 0 - } - } - - RowLayout - { - Rectangle - { - Layout.preferredWidth: 150 - Label { - id: amountLabel - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - text: qsTr("Amount") - } - } - - Ether { - Layout.preferredWidth: 350 - id: valueField - edit: true - displayFormattedValue: true - displayUnitSelection: true - } - } - - Rectangle - { - Layout.preferredHeight: 30 - Layout.fillWidth: true - color: "transparent" - Rectangle - { - color: "#cccccc" - height: 1 - width: parent.width - anchors.verticalCenter: parent.verticalCenter - } - } - - Rectangle - { - height: 20 - color: "transparent" - Layout.preferredWidth: 500 - Rectangle - { - - anchors.horizontalCenter: parent.horizontalCenter - Label { - text: qsTr("Transaction fees") - anchors.horizontalCenter: parent.horizontalCenter - } - } - - } - - RowLayout - { - Layout.preferredHeight: 45 - Rectangle - { - Layout.preferredWidth: 150 - Label { - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - text: qsTr("Gas") - } - } - - Row - { - Layout.preferredWidth: 350 - DefaultTextField - { - property variant gasValue - onGasValueChanged: text = gasValue.value(); - onTextChanged: gasValue.setValue(text); - implicitWidth: 200 - enabled: !gasAutoCheck.checked - id: gasValueEdit; - - Label - { - id: estimatedGas - anchors.top: parent.bottom - text: "" - Connections - { - target: functionComboBox - onCurrentIndexChanged: - { - estimatedGas.displayGas(TransactionHelper.contractFromToken(recipientsAccount.currentValue()), functionComboBox.currentText) - } - } - - function displayGas(contractName, functionName) - { - var gasCost = codeModel.gasCostBy(contractName, functionName); - if (gasCost && gasCost.length > 0) - { - var gas = codeModel.txGas + codeModel.callStipend + parseInt(gasCost[0].gas) - estimatedGas.text = qsTr("Estimated cost: ") + gasCost[0].gas + " gas" - } - } - - function updateView() - { - if (rbbuttonList.current.objectName === "trTypeExecute") - estimatedGas.displayGas(TransactionHelper.contractFromToken(recipientsAccount.currentValue()), functionComboBox.currentText) - else if (rbbuttonList.current.objectName === "trTypeCreate") - { - var contractName = contractCreationComboBox.currentValue() - estimatedGas.displayGas(contractName, contractName) - } - else if (rbbuttonList.current.objectName === "trTypeSend") - { - var gas = codeModel.txGas + codeModel.callStipend - estimatedGas.text = qsTr("Estimated cost: ") + gas + " gas" - } - } - - Connections - { - target: rbbuttonList - onCurrentChanged: { - estimatedGas.updateView() - } - } - } - } - - CheckBox - { - id: gasAutoCheck - checked: true - text: qsTr("Auto"); - } - } - } - - RowLayout - { - Layout.preferredWidth: 500 - Layout.preferredHeight: 45 - Rectangle - { - Layout.preferredWidth: 150 - Label { - id: gasPriceLabel - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.right - text: qsTr("Gas Price") - - Label { - id: gasPriceMarket - anchors.top: gasPriceLabel.bottom - anchors.topMargin: 10 - Component.onCompleted: - { - NetworkDeployment.gasPrice(function(result) - { - gasPriceMarket.text = qsTr("Current market: ") + " " + QEtherHelper.createEther(result, QEther.Wei).format() - }, function (){}); - } - } - } - } - - Ether { - Layout.preferredWidth: 400 - id: gasPriceField - edit: true - displayFormattedValue: false - displayUnitSelection: true - } - } - - - RowLayout - { - - Layout.preferredWidth: 500 - Row - { - width: parent.width - anchors.right: parent.right - Button { - id: updateBtn - text: qsTr("Cancel"); - onClicked: close(); - } - - Button { - text: editMode ? qsTr("Update") : qsTr("Ok") - onClicked: { - var invalid = InputValidator.validate(paramsModel, paramValues); - if (invalid.length === 0) - { - close(); - accepted(); - } - else - { - errorDialog.text = qsTr("Some parameters are invalid:\n"); - for (var k in invalid) - errorDialog.text += invalid[k].message + "\n"; - errorDialog.open(); - } - } - } - } - - MessageDialog { - id: errorDialog - standardButtons: StandardButton.Ok - icon: StandardIcon.Critical - } - } - - RowLayout - { - Layout.preferredHeight: 30 - anchors.bottom: parent.bottom - } - } - } - } -} diff --git a/mix/qml/TransactionLog.qml b/mix/qml/TransactionLog.qml deleted file mode 100644 index d31fe0786..000000000 --- a/mix/qml/TransactionLog.qml +++ /dev/null @@ -1,200 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import org.ethereum.qml.RecordLogEntry 1.0 -import org.ethereum.qml.InverseMouseArea 1.0 - -Item { - property ListModel fullModel: ListModel{} - property ListModel transactionModel: ListModel{} - property ListModel callModel: ListModel{} - property int selectedStateIndex: statesCombo.selectedIndex - - ColumnLayout { - anchors.fill: parent - RowLayout { - anchors.right: parent.right - anchors.left: parent.left - Connections - { - id: compilationStatus - target: codeModel - property bool compilationComplete: false - onCompilationComplete: compilationComplete = true - onCompilationError: compilationComplete = false - } - - Connections - { - target: projectModel - onProjectSaved: - { - if (projectModel.appIsClosing || projectModel.projectIsClosing) - return; - if (compilationStatus.compilationComplete && codeModel.hasContract && !clientModel.running) - projectModel.stateListModel.debugDefaultState(); - } - onProjectClosed: - { - fullModel.clear(); - transactionModel.clear(); - callModel.clear(); - } - onContractSaved: { - if (compilationStatus.compilationComplete && codeModel.hasContract && !clientModel.running) - projectModel.stateListModel.debugDefaultState(); - } - } - - StatesComboBox - { - id: statesCombo - items: projectModel.stateListModel - onSelectCreate: projectModel.stateListModel.addState() - onEditItem: projectModel.stateListModel.editState(item) - colorItem: "#808080" - colorSelect: "#4a90e2" - color: "white" - Connections { - target: projectModel.stateListModel - onStateRun: { - if (statesCombo.selectedIndex !== index) - statesCombo.setSelectedIndex(index) - } - onStateListModelReady: { - statesCombo.setSelectedIndex(projectModel.stateListModel.defaultStateIndex) - } - onStateDeleted: { - if (index === statesCombo.selectedIndex) - statesCombo.setSelectedIndex(0); - } - } - } - - CheckBox - { - text: qsTr("Mine") - onCheckedChanged: { - mineAction.enabled = !checked; - mineTimer.running = checked; - } - } - - Timer - { - id: mineTimer - repeat: true; - interval: 12000 - running: false - onTriggered: - { - clientModel.mine(); - } - } - - Button - { - id: mineBtn - anchors.rightMargin: 9 - anchors.verticalCenter: parent.verticalCenter - action: mineAction - } - - ComboBox { - id: itemFilter - - function getCurrentModel() - { - return currentIndex === 0 ? fullModel : currentIndex === 1 ? transactionModel : currentIndex === 2 ? callModel : fullModel; - } - - model: ListModel { - ListElement { text: qsTr("Calls and Transactions"); value: 0; } - ListElement { text: qsTr("Only Transactions"); value: 1; } - ListElement { text: qsTr("Only Calls"); value: 2; } - } - - onCurrentIndexChanged: - { - logTable.model = itemFilter.getCurrentModel(); - } - } - } - TableView { - id: logTable - Layout.fillWidth: true - Layout.fillHeight: true - model: fullModel - - TableViewColumn { - role: "transactionIndex" - title: qsTr("#") - width: 40 - } - TableViewColumn { - role: "contract" - title: qsTr("Contract") - width: 100 - } - TableViewColumn { - role: "function" - title: qsTr("Function") - width: 120 - } - TableViewColumn { - role: "value" - title: qsTr("Value") - width: 60 - } - TableViewColumn { - role: "address" - title: qsTr("Destination") - width: 130 - } - TableViewColumn { - role: "returned" - title: qsTr("Returned") - width: 120 - } - TableViewColumn { - role: "gasUsed" - title: qsTr("Gas Used") - width: 120 - } - onActivated: { - var item = logTable.model.get(row); - if (item.type === RecordLogEntry.Transaction) - clientModel.debugRecord(item.recordIndex); - else - clientModel.emptyRecord(); - } - Keys.onPressed: { - if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_C && currentRow >=0 && currentRow < logTable.model.count) { - var item = logTable.model.get(currentRow); - clipboard.text = item.returned; - } - } - } - } - Connections { - target: clientModel - onStateCleared: { - fullModel.clear(); - transactionModel.clear(); - callModel.clear(); - } - onNewRecord: { - fullModel.append(_r); - if (!_r.call) - transactionModel.append(_r); - else - callModel.append(_r); - } - onMiningComplete: { - fullModel.append(clientModel.lastBlock); - transactionModel.append(clientModel.lastBlock); - } - } -} diff --git a/mix/qml/VariablesView.qml b/mix/qml/VariablesView.qml deleted file mode 100644 index 517204877..000000000 --- a/mix/qml/VariablesView.qml +++ /dev/null @@ -1,40 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Layouts 1.1 - -DebugInfoList -{ - id: storage - collapsible: true - title : qsTr("Storage") - componentDelegate: structComp - - Component - { - id: structComp - ScrollView - { - property alias members: typeLoader.members; - property alias value: typeLoader.value; - anchors.fill: parent - anchors.leftMargin: 10 - StructView - { - id: typeLoader - members: [] - value: {} - context: "variable" - width: parent.width - } - } - } - - function setData(members, values) { - storage.item.value = {}; - storage.item.members = []; - storage.item.value = values; //TODO: use a signal for this? - storage.item.members = members; - } -} - diff --git a/mix/qml/Watchers.qml b/mix/qml/Watchers.qml deleted file mode 100644 index fc3c25bba..000000000 --- a/mix/qml/Watchers.qml +++ /dev/null @@ -1,205 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Controls.Styles 1.1 -import QtQuick.Dialogs 1.1 -import QtQuick.Layouts 1.1 -import Qt.labs.settings 1.0 -import org.ethereum.qml.QEther 1.0 -import "js/Debugger.js" as Debugger -import "js/ErrorLocationFormater.js" as ErrorLocationFormater -import "js/TransactionHelper.js" as TransactionHelper -import "js/QEtherHelper.js" as QEtherHelper -import "." - -Rectangle { - color: selectedBlockColor - property variant tx - property variant currentState - property variant bc - property var blockIndex - property var txIndex - - property string selectedBlockColor: "#accbf2" - property string selectedBlockForeground: "#445e7f" - - function clear() - { - from.text = "" - to.text = "" - value.text = "" - inputParams.clear() - returnParams.clear() - accounts.clear() - events.clear() - } - - function addAccount(address, amount) - { - accounts.add(address, amount) - } - - function updateWidthTx(_tx, _state, _blockIndex, _txIndex) - { - from.text = clientModel.resolveAddress(_tx.sender) - to.text = _tx.label - value.text = _tx.value.format() - tx = _tx - blockIndex = _blockIndex - txIndex = _txIndex - currentState = _state - inputParams.init() - if (_tx.isContractCreation) - { - returnParams.role = "creationAddr" - returnParams._data = { - creationAddr : { - } - } - returnParams._data.creationAddr[qsTr("contract address")] = _tx.returned - } - else - { - returnParams.role = "returnParameters" - returnParams._data = tx - } - returnParams.init() - accounts.init() - events.init() - } - - Column { - anchors.fill: parent - spacing: 15 - Rectangle - { - height: 15 - width: parent.width - 30 - color: "transparent" - Row - { - id: rowHeader - anchors.horizontalCenter: parent.horizontalCenter - anchors.top: rowHeader.parent.top - anchors.topMargin: 6 - spacing: 5 - Label { - id: fromLabel - text: qsTr("from") - visible: false - color: selectedBlockForeground - } - Label { - id: from - color: selectedBlockForeground - elide: Text.ElideRight - maximumLineCount: 1 - clip: true - width: 200 - } - Label { - id: toLabel - text: qsTr("to") - visible: false - color: selectedBlockForeground - } - Label { - id: to - color: selectedBlockForeground - elide: Text.ElideRight - maximumLineCount: 1 - clip: true - width: 100 - } - Label { - id: value - color: selectedBlockForeground - font.italic: true - clip: true - } - } - - Image { - anchors.right: rowHeader.parent.right - anchors.top: rowHeader.parent.top - anchors.topMargin: 5 - source: "qrc:/qml/img/edit_combox.png" - height: 15 - fillMode: Image.PreserveAspectFit - visible: from.text !== "" - MouseArea - { - anchors.fill: parent - onClicked: - { - bc.blockChainRepeater.editTx(blockIndex, txIndex) - } - } - } - } - - Rectangle { - height: 1 - width: parent.width - 30 - anchors.horizontalCenter: parent.horizontalCenter - border.color: "#cccccc" - border.width: 1 - } - - KeyValuePanel - { - height: 150 - width: parent.width - 30 - anchors.horizontalCenter: parent.horizontalCenter - id: inputParams - title: qsTr("INPUT PARAMETERS") - role: "parameters" - _data: tx - } - - KeyValuePanel - { - height: 150 - width: parent.width - 30 - anchors.horizontalCenter: parent.horizontalCenter - id: returnParams - title: qsTr("RETURN PARAMETERS") - role: "returnParameters" - _data: tx - } - - KeyValuePanel - { - height: 150 - width: parent.width - 30 - anchors.horizontalCenter: parent.horizontalCenter - id: accounts - title: qsTr("ACCOUNTS") - role: "accounts" - _data: currentState - } - - KeyValuePanel - { - height: 150 - width: parent.width - 30 - anchors.horizontalCenter: parent.horizontalCenter - id: events - title: qsTr("EVENTS") - function computeData() - { - model.clear() - var ret = [] - for (var k in tx.logs) - { - var param = "" - for (var p in tx.logs[k].param) - { - param += " " + tx.logs[k].param[p].value + " " - } - param = "(" + param + ")" - model.append({ "key": tx.logs[k].name, "value": param }) - } - } - } - } -} diff --git a/mix/qml/WebCodeEditor.qml b/mix/qml/WebCodeEditor.qml deleted file mode 100644 index 054a63bd7..000000000 --- a/mix/qml/WebCodeEditor.qml +++ /dev/null @@ -1,204 +0,0 @@ -import QtQuick 2.2 -import QtQuick.Controls 1.1 -import QtQuick.Layouts 1.0 -import QtQuick.Controls.Styles 1.1 -import QtWebEngine 1.0 -import QtWebEngine.experimental 1.0 -import org.ethereum.qml.Clipboard 1.0 -import "js/ErrorLocationFormater.js" as ErrorLocationFormater - -Item { - signal breakpointsChanged - signal editorTextChanged - signal loadComplete - property bool isClean: true - property string currentText: "" - property string currentMode: "" - property bool initialized: false - property bool unloaded: false - property var currentBreakpoints: [] - property string sourceName - property var document - property int fontSize: 0 - - function setText(text, mode) { - currentText = text; - if (mode !== undefined) - currentMode = mode; - if (initialized && editorBrowser) { - editorBrowser.runJavaScript("setTextBase64(\"" + Qt.btoa(text) + "\")"); - editorBrowser.runJavaScript("setMode(\"" + currentMode + "\")"); - } - setFocus(); - } - - function setFocus() { - if (editorBrowser) - editorBrowser.forceActiveFocus(); - } - - function getText() { - return currentText; - } - - function syncClipboard() { - if (Qt.platform.os == "osx" && editorBrowser) { - var text = clipboard.text; - editorBrowser.runJavaScript("setClipboardBase64(\"" + Qt.btoa(text) + "\")"); - } - } - - function highlightExecution(location) { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("highlightExecution(" + location.start + "," + location.end + ")"); - } - - function showWarning(content) { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("showWarning('" + content + "')"); - } - - function getBreakpoints() { - return currentBreakpoints; - } - - function toggleBreakpoint() { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("toggleBreakpoint()"); - } - - function changeGeneration() { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("changeGeneration()", function(result) {}); - } - - function goToCompilationError() { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("goToCompilationError()", function(result) {}); - } - - function setFontSize(size) { - fontSize = size; - if (initialized && editorBrowser) - editorBrowser.runJavaScript("setFontSize(" + size + ")", function(result) {}); - } - - function setGasCosts(gasCosts) { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("setGasCosts('" + JSON.stringify(gasCosts) + "')", function(result) {}); - } - - function displayGasEstimation(show) { - if (initialized && editorBrowser) - editorBrowser.runJavaScript("displayGasEstimation('" + show + "')", function(result) {}); - } - - Clipboard - { - id: clipboard - } - - Connections { - target: clipboard - onClipboardChanged: syncClipboard() - } - - anchors.top: parent.top - id: codeEditorView - anchors.fill: parent - WebEngineView { - id: editorBrowser - url: "qrc:///qml/html/codeeditor.html" - anchors.fill: parent - experimental.settings.javascriptCanAccessClipboard: true - onJavaScriptConsoleMessage: { - console.log("editor: " + sourceID + ":" + lineNumber + ":" + message); - } - - Component.onDestruction: - { - codeModel.onCompilationComplete.disconnect(compilationComplete); - codeModel.onCompilationError.disconnect(compilationError); - } - - onLoadingChanged: - { - if (!loading && editorBrowser) { - initialized = true; - setFontSize(fontSize); - setText(currentText, currentMode); - runJavaScript("getTextChanged()", function(result) { }); - pollTimer.running = true; - syncClipboard(); - if (currentMode === "solidity") - { - codeModel.onCompilationComplete.connect(compilationComplete); - codeModel.onCompilationError.connect(compilationError); - } - parent.changeGeneration(); - loadComplete(); - } - } - - - function compilationComplete() - { - if (editorBrowser) - { - editorBrowser.runJavaScript("compilationComplete()", function(result) { }); - parent.displayGasEstimation(gasEstimationAction.checked); - } - - - } - - function compilationError(error, firstLocation, secondLocations) - { - if (!editorBrowser || !error) - return; - var detail = error.split('\n')[0]; - var reg = detail.match(/:\d+:\d+:/g); - if (reg !== null) - detail = detail.replace(reg[0], ""); - displayErrorAnnotations(detail, firstLocation, secondLocations); - } - - function displayErrorAnnotations(detail, location, secondaryErrors) - { - editorBrowser.runJavaScript("compilationError('" + sourceName + "', '" + JSON.stringify(location) + "', '" + detail + "', '" + JSON.stringify(secondaryErrors) + "')", function(result){}); - } - - Timer - { - id: pollTimer - interval: 30 - running: false - repeat: true - onTriggered: { - if (!editorBrowser) - return; - editorBrowser.runJavaScript("getTextChanged()", function(result) { - if (result === true && editorBrowser) { - editorBrowser.runJavaScript("getText()" , function(textValue) { - currentText = textValue; - editorTextChanged(); - }); - } - }); - editorBrowser.runJavaScript("getBreakpointsChanged()", function(result) { - if (result === true && editorBrowser) { - editorBrowser.runJavaScript("getBreakpoints()" , function(bp) { - if (currentBreakpoints !== bp) { - currentBreakpoints = bp; - breakpointsChanged(); - } - }); - } - }); - editorBrowser.runJavaScript("isClean()", function(result) { - isClean = result; - }); - } - } - } -} diff --git a/mix/qml/WebPreview.qml b/mix/qml/WebPreview.qml deleted file mode 100644 index 616bb92a8..000000000 --- a/mix/qml/WebPreview.qml +++ /dev/null @@ -1,463 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Controls.Styles 1.1 -import QtWebEngine 1.0 -import QtWebEngine.experimental 1.0 -import HttpServer 1.0 -import "." - -Item { - id: webPreview - property string pendingPageUrl: "" - property bool initialized: false - property alias urlInput: urlInput - property alias webView: webView - property string webContent; //for testing - signal javaScriptMessage(var _level, string _sourceId, var _lineNb, string _content) - signal webContentReady - signal ready - - function setPreviewUrl(url) { - if (!initialized) - pendingPageUrl = url; - else { - pendingPageUrl = ""; - updateContract(); - webView.runJavaScript("loadPage(\"" + url + "\")"); - } - } - - function reload() { - if (initialized) { - updateContract(); - //webView.runJavaScript("reloadPage()"); - setPreviewUrl(urlInput.text); - } - } - - function updateContract() { - var contracts = {}; - for (var c in codeModel.contracts) { - var contract = codeModel.contracts[c]; - var address = clientModel.contractAddresses[contract.contract.name]; - if (address) { - contracts[c] = { - name: contract.contract.name, - address: address, - interface: JSON.parse(contract.contractInterface), - }; - } - } - webView.runJavaScript("updateContracts(" + JSON.stringify(contracts) + ")"); - } - - function reloadOnSave() { - if (autoReloadOnSave.checked) - reload(); - } - - function updateDocument(documentId, action) { - for (var i = 0; i < pageListModel.count; i++) - if (pageListModel.get(i).documentId === documentId) - action(i); - } - - function getContent() { - webView.runJavaScript("getContent()", function(result) { - webContent = result; - webContentReady(); - }); - } - - function changePage() { - setPreviewUrl(urlInput.text); - } - - WebPreviewStyle { - id: webPreviewStyle - } - - Connections { - target: mainApplication - onLoaded: { - //We need to load the container using file scheme so that web security would allow loading local files in iframe - var containerPage = fileIo.readFile("qrc:///qml/html/WebContainer.html"); - webView.loadHtml(containerPage, httpServer.url + "/WebContainer.html") - - } - } - - Connections { - target: codeModel - onContractInterfaceChanged: reload(); - } - - Connections { - target: clientModel - onRunComplete: reload(); - } - - Connections { - target: projectModel - - onDocumentAdded: { - var document = projectModel.getDocument(documentId) - if (document.isHtml) - pageListModel.append(document); - } - onDocumentRemoved: { - updateDocument(documentId, function(i) { pageListModel.remove(i) } ) - } - - onDocumentUpdated: { - var document = projectModel.getDocument(documentId); - for (var i = 0; i < pageListModel.count; i++) - if (pageListModel.get(i).documentId === documentId) - { - pageListModel.set(i, document); - break; - } - } - - onProjectLoading: { - for (var i = 0; i < target.listModel.count; i++) { - var document = target.listModel.get(i); - if (document.isHtml) { - pageListModel.append(document); - if (pageListModel.count === 1) //first page added - { - urlInput.text = httpServer.url + "/" + document.documentId; - setPreviewUrl(httpServer.url + "/" + document.documentId); - } - } - } - } - - onDocumentSaved: - { - if (!projectModel.getDocument(documentId).isContract) - reloadOnSave(); - } - - onProjectClosed: { - pageListModel.clear(); - } - } - - ListModel { - id: pageListModel - } - - HttpServer { - id: httpServer - listen: true - accept: true - onClientConnected: { - var urlPath = _request.url.toString(); - if (urlPath.indexOf("/rpc/") === 0) - { - //jsonrpc request - //filter polling requests //TODO: do it properly - var log = _request.content.indexOf("eth_changed") < 0; - if (log) - console.log(_request.content); - var response = clientModel.apiCall(_request.content); - if (log) - console.log(response); - _request.setResponse(response); - } - else - { - //document request - if (urlPath === "/") - urlPath = "/index.html"; - var documentName = urlPath.substr(urlPath.lastIndexOf("/") + 1); - var documentId = projectModel.getDocumentIdByName(documentName); - var content = ""; - if (projectModel.codeEditor.isDocumentOpen(documentId)) - content = projectModel.codeEditor.getDocumentText(documentId); - else - { - var doc = projectModel.getDocument(documentId); - if (doc) - content = fileIo.readFile(doc.path); - } - - var accept = _request.headers["accept"]; - if (accept && accept.indexOf("text/html") >= 0 && !_request.headers["http_x_requested_with"]) - { - //navigate to page request, inject deployment script - content = "\n" + content; - _request.setResponseContentType("text/html"); - } - _request.setResponse(content); - } - } - } - - ColumnLayout { - anchors.fill: parent - spacing: 0 - Rectangle - { - anchors.leftMargin: 4 - color: webPreviewStyle.general.headerBackgroundColor - Layout.preferredWidth: parent.width - Layout.preferredHeight: 32 - Row { - anchors.top: parent.top - anchors.fill: parent - anchors.leftMargin: 3 - spacing: 3 - - DefaultTextField - { - id: urlInput - anchors.verticalCenter: parent.verticalCenter - height: 21 - width: 300 - Keys.onEnterPressed: - { - setPreviewUrl(text); - } - Keys.onReturnPressed: - { - setPreviewUrl(text); - } - focus: true - } - - Action { - tooltip: qsTr("Reload") - id: buttonReloadAction - onTriggered: { - reload(); - } - } - - Button { - iconSource: "qrc:/qml/img/available_updates.png" - action: buttonReloadAction - anchors.verticalCenter: parent.verticalCenter - width: 21 - height: 21 - focus: true - } - - Rectangle - { - width: 1 - height: parent.height - 10 - color: webPreviewStyle.general.separatorColor - anchors.verticalCenter: parent.verticalCenter - } - - CheckBox { - id: autoReloadOnSave - checked: true - height: 21 - anchors.verticalCenter: parent.verticalCenter - style: CheckBoxStyle { - label: DefaultLabel { - text: qsTr("Auto reload on save") - } - } - focus: true - } - - Rectangle - { - width: 1 - height: parent.height - 10 - color: webPreviewStyle.general.separatorColor - anchors.verticalCenter: parent.verticalCenter - } - - Button - { - height: 22 - width: 22 - anchors.verticalCenter: parent.verticalCenter - action: expressionAction - iconSource: "qrc:/qml/img/console.png" - } - - Action { - id: expressionAction - tooltip: qsTr("Expressions") - onTriggered: - { - expressionPanel.visible = !expressionPanel.visible; - if (expressionPanel.visible) - { - webView.width = webView.parent.width - 350 - expressionInput.forceActiveFocus(); - } - else - webView.width = webView.parent.width - } - } - } - } - - Rectangle - { - Layout.preferredHeight: 1 - Layout.preferredWidth: parent.width - color: webPreviewStyle.general.separatorColor - } - - Splitter - { - Layout.preferredWidth: parent.width - Layout.fillHeight: true - WebEngineView { - Layout.fillHeight: true - width: parent.width - Layout.preferredWidth: parent.width - id: webView - onJavaScriptConsoleMessage: { - console.log(sourceID + ":" + lineNumber + ": " + message); - webPreview.javaScriptMessage(level, sourceID, lineNumber - 1, message); - } - onLoadingChanged: { - if (!loading) { - initialized = true; - webView.runJavaScript("init(\"" + httpServer.url + "/rpc/\")"); - if (pendingPageUrl) - setPreviewUrl(pendingPageUrl); - ready(); - } - } - } - - Column { - id: expressionPanel - width: 350 - Layout.preferredWidth: 350 - Layout.fillHeight: true - spacing: 0 - visible: false - function addExpression() - { - if (expressionInput.text === "") - return; - expressionInput.history.unshift(expressionInput.text); - expressionInput.index = -1; - webView.runJavaScript("executeJavaScript(\"" + expressionInput.text.replace(/"/g, '\\"') + "\")", function(result) { - resultTextArea.text = "> " + result + "\n\n" + resultTextArea.text; - expressionInput.text = ""; - }); - } - - Row - { - id: rowConsole - width: parent.width - Button - { - height: 22 - width: 22 - action: clearAction - iconSource: "qrc:/qml/img/cleariconactive.png" - } - - Action { - id: clearAction - enabled: resultTextArea.text !== "" - tooltip: qsTr("Clear") - onTriggered: { - resultTextArea.text = ""; - } - } - - DefaultTextField { - id: expressionInput - width: parent.width - 15 - height: 20 - font.family: webPreviewStyle.general.fontName - font.italic: true - font.pointSize: appStyle.absoluteSize(-3) - anchors.verticalCenter: parent.verticalCenter - property bool active: false - property var history: [] - property int index: -1 - - function displayCache(incr) - { - index = index + incr; - if (history.length - 1 < index || index < 0) - { - if (incr === 1) - index = 0; - else - index = history.length - 1; - } - expressionInput.text = history[index]; - } - - onTextChanged: { - active = text !== ""; - if (!active) - index = -1; - } - - Keys.onDownPressed: { - if (active) - displayCache(-1); - } - - Keys.onUpPressed: { - displayCache(1); - active = true; - } - - Keys.onEnterPressed: - { - expressionPanel.addExpression(); - } - - Keys.onReturnPressed: - { - expressionPanel.addExpression(); - } - - onFocusChanged: - { - if (!focus && text == "") - text = qsTr("Expression"); - if (focus && text === qsTr("Expression")) - text = ""; - } - - style: TextFieldStyle { - background: Rectangle { - color: "transparent" - } - } - } - } - - TextArea { - Layout.fillHeight: true - height: parent.height - rowConsole.height - readOnly: true - id: resultTextArea - width: expressionPanel.width - wrapMode: Text.Wrap - textFormat: Text.RichText - font.family: webPreviewStyle.general.fontName - font.pointSize: appStyle.absoluteSize(-3) - backgroundVisible: true - style: TextAreaStyle { - backgroundColor: "#f0f0f0" - } - } - } - } - } -} - - diff --git a/mix/qml/WebPreviewStub.qml b/mix/qml/WebPreviewStub.qml deleted file mode 100644 index d2d797ffc..000000000 --- a/mix/qml/WebPreviewStub.qml +++ /dev/null @@ -1,15 +0,0 @@ -import QtQuick 2.0 -import QtQuick.Window 2.0 -import QtQuick.Layouts 1.0 -import QtQuick.Controls 1.0 -import QtQuick.Controls.Styles 1.1 - -Item { - id: webPreview - Text { - anchors.fill: parent - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - text: qsTr("Web preview is not supported in this build"); - } -} diff --git a/mix/qml/WebPreviewStyle.qml b/mix/qml/WebPreviewStyle.qml deleted file mode 100644 index 1fc0c8b99..000000000 --- a/mix/qml/WebPreviewStyle.qml +++ /dev/null @@ -1,15 +0,0 @@ -import QtQuick 2.0 - -QtObject { - - function absoluteSize(rel) - { - return systemPointSize + rel; - } - - property QtObject general: QtObject { - property string headerBackgroundColor: "#f0f0f0" - property string separatorColor: "#808080" - property string fontName: "sans serif" - } -} diff --git a/mix/qml/fonts/SourceSansPro-Black.ttf b/mix/qml/fonts/SourceSansPro-Black.ttf deleted file mode 100644 index be1a3108e..000000000 Binary files a/mix/qml/fonts/SourceSansPro-Black.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-BlackIt.ttf b/mix/qml/fonts/SourceSansPro-BlackIt.ttf deleted file mode 100644 index ac5c4ef7c..000000000 Binary files a/mix/qml/fonts/SourceSansPro-BlackIt.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-Bold.ttf b/mix/qml/fonts/SourceSansPro-Bold.ttf deleted file mode 100644 index f47161c6b..000000000 Binary files a/mix/qml/fonts/SourceSansPro-Bold.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-BoldIt.ttf b/mix/qml/fonts/SourceSansPro-BoldIt.ttf deleted file mode 100644 index 6b3db698b..000000000 Binary files a/mix/qml/fonts/SourceSansPro-BoldIt.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-ExtraLight.ttf b/mix/qml/fonts/SourceSansPro-ExtraLight.ttf deleted file mode 100644 index 0a3e51fdb..000000000 Binary files a/mix/qml/fonts/SourceSansPro-ExtraLight.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-ExtraLightIt.ttf b/mix/qml/fonts/SourceSansPro-ExtraLightIt.ttf deleted file mode 100644 index a0eb86aca..000000000 Binary files a/mix/qml/fonts/SourceSansPro-ExtraLightIt.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-It.ttf b/mix/qml/fonts/SourceSansPro-It.ttf deleted file mode 100644 index fcc95fc7c..000000000 Binary files a/mix/qml/fonts/SourceSansPro-It.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-Light.ttf b/mix/qml/fonts/SourceSansPro-Light.ttf deleted file mode 100644 index 9cae13c97..000000000 Binary files a/mix/qml/fonts/SourceSansPro-Light.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-LightIt.ttf b/mix/qml/fonts/SourceSansPro-LightIt.ttf deleted file mode 100644 index 2ed784284..000000000 Binary files a/mix/qml/fonts/SourceSansPro-LightIt.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-Regular.ttf b/mix/qml/fonts/SourceSansPro-Regular.ttf deleted file mode 100644 index 8e8255e17..000000000 Binary files a/mix/qml/fonts/SourceSansPro-Regular.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-Semibold.ttf b/mix/qml/fonts/SourceSansPro-Semibold.ttf deleted file mode 100644 index 121ee9bbf..000000000 Binary files a/mix/qml/fonts/SourceSansPro-Semibold.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSansPro-SemiboldIt.ttf b/mix/qml/fonts/SourceSansPro-SemiboldIt.ttf deleted file mode 100644 index 6ceaa885f..000000000 Binary files a/mix/qml/fonts/SourceSansPro-SemiboldIt.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSerifPro-Bold.ttf b/mix/qml/fonts/SourceSerifPro-Bold.ttf deleted file mode 100644 index ac7837fd9..000000000 Binary files a/mix/qml/fonts/SourceSerifPro-Bold.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSerifPro-Regular.ttf b/mix/qml/fonts/SourceSerifPro-Regular.ttf deleted file mode 100644 index 7201a8890..000000000 Binary files a/mix/qml/fonts/SourceSerifPro-Regular.ttf and /dev/null differ diff --git a/mix/qml/fonts/SourceSerifPro-Semibold.ttf b/mix/qml/fonts/SourceSerifPro-Semibold.ttf deleted file mode 100644 index db2fc804b..000000000 Binary files a/mix/qml/fonts/SourceSerifPro-Semibold.ttf and /dev/null differ diff --git a/mix/qml/html/WebContainer.html b/mix/qml/html/WebContainer.html deleted file mode 100644 index cd92852a7..000000000 --- a/mix/qml/html/WebContainer.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - diff --git a/mix/qml/html/cm/acorn.js b/mix/qml/html/cm/acorn.js deleted file mode 100644 index 2e3305062..000000000 --- a/mix/qml/html/cm/acorn.js +++ /dev/null @@ -1,2864 +0,0 @@ -// Acorn is a tiny, fast JavaScript parser written in JavaScript. -// -// Acorn was written by Marijn Haverbeke and various contributors and -// released under an MIT license. The Unicode regexps (for identifiers -// and whitespace) were taken from [Esprima](http://esprima.org) by -// Ariya Hidayat. -// -// Git repositories for Acorn are available at -// -// http://marijnhaverbeke.nl/git/acorn -// https://github.com/marijnh/acorn.git -// -// Please use the [github bug tracker][ghbt] to report issues. -// -// [ghbt]: https://github.com/marijnh/acorn/issues -// -// This file defines the main parser interface. The library also comes -// with a [error-tolerant parser][dammit] and an -// [abstract syntax tree walker][walk], defined in other files. -// -// [dammit]: acorn_loose.js -// [walk]: util/walk.js - -(function(root, mod) { - if (typeof exports == "object" && typeof module == "object") return mod(exports); // CommonJS - if (typeof define == "function" && define.amd) return define(["exports"], mod); // AMD - mod(root.acorn || (root.acorn = {})); // Plain browser env -})(this, function(exports) { - "use strict"; - - exports.version = "0.12.1"; - - // The main exported interface (under `self.acorn` when in the - // browser) is a `parse` function that takes a code string and - // returns an abstract syntax tree as specified by [Mozilla parser - // API][api], with the caveat that inline XML is not recognized. - // - // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API - - var options, input, inputLen, sourceFile; - - exports.parse = function(inpt, opts) { - input = String(inpt); inputLen = input.length; - setOptions(opts); - initTokenState(); - var startPos = options.locations ? [tokPos, curPosition()] : tokPos; - initParserState(); - return parseTopLevel(options.program || startNodeAt(startPos)); - }; - - // A second optional argument can be given to further configure - // the parser process. These options are recognized: - - var defaultOptions = exports.defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must - // be either 3, or 5, or 6. This influences support for strict - // mode, the set of reserved words, support for getters and - // setters and other features. - ecmaVersion: 5, - // Turn on `strictSemicolons` to prevent the parser from doing - // automatic semicolon insertion. - strictSemicolons: false, - // When `allowTrailingCommas` is false, the parser will not allow - // trailing commas in array and object literals. - allowTrailingCommas: true, - // By default, reserved words are not enforced. Enable - // `forbidReserved` to enforce them. When this option has the - // value "everywhere", reserved words and keywords can also not be - // used as property names. - forbidReserved: false, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokenize() returns. Note that you are not - // allowed to call the parser from the callback—that will - // corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false - }; - - // This function tries to parse a single expression at a given - // offset in a string. Useful for parsing mixed-language formats - // that embed JavaScript expressions. - - exports.parseExpressionAt = function(inpt, pos, opts) { - input = String(inpt); inputLen = input.length; - setOptions(opts); - initTokenState(pos); - initParserState(); - return parseExpression(); - }; - - var isArray = function (obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - - function setOptions(opts) { - options = {}; - for (var opt in defaultOptions) - options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; - sourceFile = options.sourceFile || null; - if (isArray(options.onToken)) { - var tokens = options.onToken; - options.onToken = function (token) { - tokens.push(token); - }; - } - if (isArray(options.onComment)) { - var comments = options.onComment; - options.onComment = function (block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? 'Block' : 'Line', - value: text, - start: start, - end: end - }; - if (options.locations) { - comment.loc = new SourceLocation(); - comment.loc.start = startLoc; - comment.loc.end = endLoc; - } - if (options.ranges) - comment.range = [start, end]; - comments.push(comment); - }; - } - isKeyword = options.ecmaVersion >= 6 ? isEcma6Keyword : isEcma5AndLessKeyword; - } - - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. - - var getLineInfo = exports.getLineInfo = function(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreak.lastIndex = cur; - var match = lineBreak.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else break; - } - return {line: line, column: offset - cur}; - }; - - function Token() { - this.type = tokType; - this.value = tokVal; - this.start = tokStart; - this.end = tokEnd; - if (options.locations) { - this.loc = new SourceLocation(); - this.loc.end = tokEndLoc; - } - if (options.ranges) - this.range = [tokStart, tokEnd]; - } - - exports.Token = Token; - - // Acorn is organized as a tokenizer and a recursive-descent parser. - // The `tokenize` export provides an interface to the tokenizer. - // Because the tokenizer is optimized for being efficiently used by - // the Acorn parser itself, this interface is somewhat crude and not - // very modular. Performing another parse or call to `tokenize` will - // reset the internal state, and invalidate existing tokenizers. - - exports.tokenize = function(inpt, opts) { - input = String(inpt); inputLen = input.length; - setOptions(opts); - initTokenState(); - skipSpace(); - - function getToken() { - lastEnd = tokEnd; - readToken(); - return new Token(); - } - getToken.jumpTo = function(pos, exprAllowed) { - tokPos = pos; - if (options.locations) { - tokCurLine = 1; - tokLineStart = lineBreak.lastIndex = 0; - var match; - while ((match = lineBreak.exec(input)) && match.index < pos) { - ++tokCurLine; - tokLineStart = match.index + match[0].length; - } - } - tokExprAllowed = !!exprAllowed; - skipSpace(); - }; - getToken.current = function() { return new Token(); }; - if (typeof Symbol !== 'undefined') { - getToken[Symbol.iterator] = function () { - return { - next: function () { - var token = getToken(); - return { - done: token.type === _eof, - value: token - }; - } - }; - }; - } - getToken.options = options; - return getToken; - }; - - // State is kept in (closure-)global variables. We already saw the - // `options`, `input`, and `inputLen` variables above. - - // The current position of the tokenizer in the input. - - var tokPos; - - // The start and end offsets of the current token. - - var tokStart, tokEnd; - - // When `options.locations` is true, these hold objects - // containing the tokens start and end line/column pairs. - - var tokStartLoc, tokEndLoc; - - // The type and value of the current token. Token types are objects, - // named by variables against which they can be compared, and - // holding properties that describe them (indicating, for example, - // the precedence of an infix operator, and the original name of a - // keyword token). The kind of value that's held in `tokVal` depends - // on the type of the token. For literals, it is the literal value, - // for operators, the operator name, and so on. - - var tokType, tokVal; - - // Internal state for the tokenizer. To distinguish between division - // operators and regular expressions, it remembers whether the last - // token was one that is allowed to be followed by an expression. In - // some cases, notably after ')' or '}' tokens, the situation - // depends on the context before the matching opening bracket, so - // tokContext keeps a stack of information about current bracketed - // forms. - - var tokContext, tokExprAllowed; - - // When `options.locations` is true, these are used to keep - // track of the current line, and know when a new line has been - // entered. - - var tokCurLine, tokLineStart; - - // These store the position of the previous token, which is useful - // when finishing a node and assigning its `end` position. - - var lastStart, lastEnd, lastEndLoc; - - // This is the parser's state. `inFunction` is used to reject - // `return` statements outside of functions, `inGenerator` to - // reject `yield`s outside of generators, `labels` to verify - // that `break` and `continue` have somewhere to jump to, and - // `strict` indicates whether strict mode is on. - - var inFunction, inGenerator, labels, strict; - - function initParserState() { - lastStart = lastEnd = tokPos; - if (options.locations) lastEndLoc = curPosition(); - inFunction = inGenerator = false; - labels = []; - skipSpace(); - readToken(); - } - - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - - function raise(pos, message) { - var loc = getLineInfo(input, pos); - message += " (" + loc.line + ":" + loc.column + ")"; - var err = new SyntaxError(message); - err.pos = pos; err.loc = loc; err.raisedAt = tokPos; - throw err; - } - - function fullCharCodeAtPos() { - var code = input.charCodeAt(tokPos); - if (code <= 0xd7ff || code >= 0xe000) return code; - var next = input.charCodeAt(tokPos + 1); - return (code << 10) + next - 0x35fdc00; - } - - function skipChar(code) { - if (code <= 0xffff) tokPos++; - else tokPos += 2; - } - - // Reused empty array added for node fields that are always empty. - - var empty = []; - - // ## Token types - - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. - - // All token type variables start with an underscore, to make them - // easy to recognize. - - // These are the general types. The `type` property is only used to - // make them recognizeable when debugging. - - var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"}; - var _name = {type: "name"}, _eof = {type: "eof"}; - - // Keyword tokens. The `keyword` property (also used in keyword-like - // operators) indicates that the token originated from an - // identifier-like word, which is used when parsing property names. - // - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. - - var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"}; - var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"}; - var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true}; - var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"}; - var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"}; - var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"}; - var _let = {keyword: "let"}, _const = {keyword: "const"}; - var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true}; - var _this = {keyword: "this"}; - var _class = {keyword: "class"}, _extends = {keyword: "extends", beforeExpr: true}; - var _export = {keyword: "export"}, _import = {keyword: "import"}; - var _yield = {keyword: "yield", beforeExpr: true}; - - // The keywords that denote values. - - var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true}; - var _false = {keyword: "false", atomValue: false}; - - // Some keywords are treated as regular operators. `in` sometimes - // (when parsing `for`) needs to be tested against specifically, so - // we assign a variable name to it for quick comparing. - - var _in = {keyword: "in", binop: 7, beforeExpr: true}; - - // Map keyword names to token types. - - var keywordTypes = {"break": _break, "case": _case, "catch": _catch, - "continue": _continue, "debugger": _debugger, "default": _default, - "do": _do, "else": _else, "finally": _finally, "for": _for, - "function": _function, "if": _if, "return": _return, "switch": _switch, - "throw": _throw, "try": _try, "var": _var, "let": _let, "const": _const, - "while": _while, "with": _with, - "null": _null, "true": _true, "false": _false, "new": _new, "in": _in, - "instanceof": {keyword: "instanceof", binop: 7, beforeExpr: true}, "this": _this, - "typeof": {keyword: "typeof", prefix: true, beforeExpr: true}, - "void": {keyword: "void", prefix: true, beforeExpr: true}, - "delete": {keyword: "delete", prefix: true, beforeExpr: true}, - "class": _class, "extends": _extends, - "export": _export, "import": _import, "yield": _yield}; - - // Punctuation token types. Again, the `type` property is purely for debugging. - - var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true}; - var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"}; - var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true}; - var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true}; - var _arrow = {type: "=>", beforeExpr: true}, _template = {type: "template"}; - var _ellipsis = {type: "...", beforeExpr: true}; - var _backQuote = {type: "`"}, _dollarBraceL = {type: "${", beforeExpr: true}; - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. `isUpdate` specifies that the node produced by - // the operator should be of type UpdateExpression rather than - // simply UnaryExpression (`++` and `--`). - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true}; - var _assign = {isAssign: true, beforeExpr: true}; - var _incDec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true}; - var _logicalOR = {binop: 1, beforeExpr: true}; - var _logicalAND = {binop: 2, beforeExpr: true}; - var _bitwiseOR = {binop: 3, beforeExpr: true}; - var _bitwiseXOR = {binop: 4, beforeExpr: true}; - var _bitwiseAND = {binop: 5, beforeExpr: true}; - var _equality = {binop: 6, beforeExpr: true}; - var _relational = {binop: 7, beforeExpr: true}; - var _bitShift = {binop: 8, beforeExpr: true}; - var _plusMin = {binop: 9, prefix: true, beforeExpr: true}; - var _modulo = {binop: 10, beforeExpr: true}; - - // '*' may be multiply or have special meaning in ES6 - var _star = {binop: 10, beforeExpr: true}; - - // Provide access to the token types for external users of the - // tokenizer. - - exports.tokTypes = {bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR, - parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon, - dot: _dot, ellipsis: _ellipsis, question: _question, slash: _slash, eq: _eq, - name: _name, eof: _eof, num: _num, regexp: _regexp, string: _string, - arrow: _arrow, template: _template, star: _star, assign: _assign, - backQuote: _backQuote, dollarBraceL: _dollarBraceL}; - for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw]; - - // This is a trick taken from Esprima. It turns out that, on - // non-Chrome browsers, to check whether a string is in a set, a - // predicate containing a big ugly `switch` statement is faster than - // a regular expression, and on Chrome the two are about on par. - // This function uses `eval` (non-lexical) to produce such a - // predicate from a space-separated string of words. - // - // It starts by sorting the words by length. - - function makePredicate(words) { - words = words.split(" "); - var f = "", cats = []; - out: for (var i = 0; i < words.length; ++i) { - for (var j = 0; j < cats.length; ++j) - if (cats[j][0].length == words[i].length) { - cats[j].push(words[i]); - continue out; - } - cats.push([words[i]]); - } - function compareTo(arr) { - if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; - f += "switch(str){"; - for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; - f += "return true}return false;"; - } - - // When there are more than three length categories, an outer - // switch first dispatches on the lengths, to save on comparisons. - - if (cats.length > 3) { - cats.sort(function(a, b) {return b.length - a.length;}); - f += "switch(str.length){"; - for (var i = 0; i < cats.length; ++i) { - var cat = cats[i]; - f += "case " + cat[0].length + ":"; - compareTo(cat); - } - f += "}"; - - // Otherwise, simply generate a flat `switch` statement. - - } else { - compareTo(words); - } - return new Function("str", f); - } - - // The ECMAScript 3 reserved word list. - - var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"); - - // ECMAScript 5 reserved words. - - var isReservedWord5 = makePredicate("class enum extends super const export import"); - - // The additional reserved words in strict mode. - - var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield"); - - // The forbidden variable names in strict mode. - - var isStrictBadIdWord = makePredicate("eval arguments"); - - // And the keywords. - - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; - - var isEcma5AndLessKeyword = makePredicate(ecma5AndLessKeywords); - - var isEcma6Keyword = makePredicate(ecma5AndLessKeywords + " let const class extends export import yield"); - - var isKeyword = isEcma5AndLessKeyword; - - // ## Character categories - - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `tools/generate-identifier-regex.js`. - - var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b2\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2d\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; - - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by tools/generate-identifier-regex.js - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541]; - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239]; - - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) return false; - pos += set[i + 1]; - if (pos >= code) return true; - } - } - - // Whether a single character denotes a newline. - - var newline = /[\n\r\u2028\u2029]/; - - function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code == 0x2029; - } - - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. - - var lineBreak = /\r\n|[\n\r\u2028\u2029]/g; - - // Test whether a given character code starts an identifier. - - var isIdentifierStart = exports.isIdentifierStart = function(code, astral) { - if (code < 65) return code === 36; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - if (astral === false) return false; - return isInAstralSet(code, astralIdentifierStartCodes); - }; - - // Test whether a given character is part of an identifier. - - var isIdentifierChar = exports.isIdentifierChar = function(code, astral) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - if (astral === false) return false; - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); - }; - - // ## Tokenizer - - // These are used when `options.locations` is on, for the - // `tokStartLoc` and `tokEndLoc` properties. - - function Position(line, col) { - this.line = line; - this.column = col; - } - - Position.prototype.offset = function(n) { - return new Position(this.line, this.column + n); - }; - - function curPosition() { - return new Position(tokCurLine, tokPos - tokLineStart); - } - - // Reset the token state. Used at the start of a parse. - - function initTokenState(pos) { - if (pos) { - tokPos = pos; - tokLineStart = Math.max(0, input.lastIndexOf("\n", pos)); - tokCurLine = input.slice(0, tokLineStart).split(newline).length; - } else { - tokCurLine = 1; - tokPos = tokLineStart = 0; - } - tokType = _eof; - tokContext = [b_stat]; - tokExprAllowed = true; - strict = false; - if (tokPos === 0 && options.allowHashBang && input.slice(0, 2) === '#!') { - skipLineComment(2); - } - } - - // The algorithm used to determine whether a regexp can appear at a - // given point in the program is loosely based on sweet.js' approach. - // See https://github.com/mozilla/sweet.js/wiki/design - - var b_stat = {token: "{", isExpr: false}, b_expr = {token: "{", isExpr: true}, b_tmpl = {token: "${", isExpr: true}; - var p_stat = {token: "(", isExpr: false}, p_expr = {token: "(", isExpr: true}; - var q_tmpl = {token: "`", isExpr: true}, f_expr = {token: "function", isExpr: true}; - - function curTokContext() { - return tokContext[tokContext.length - 1]; - } - - function braceIsBlock(prevType) { - var parent; - if (prevType === _colon && (parent = curTokContext()).token == "{") - return !parent.isExpr; - if (prevType === _return) - return newline.test(input.slice(lastEnd, tokStart)); - if (prevType === _else || prevType === _semi || prevType === _eof) - return true; - if (prevType == _braceL) - return curTokContext() === b_stat; - return !tokExprAllowed; - } - - // Called at the end of every token. Sets `tokEnd`, `tokVal`, and - // maintains `tokContext` and `tokExprAllowed`, and skips the space - // after the token, so that the next one's `tokStart` will point at - // the right position. - - function finishToken(type, val) { - tokEnd = tokPos; - if (options.locations) tokEndLoc = curPosition(); - var prevType = tokType, preserveSpace = false; - tokType = type; - tokVal = val; - - // Update context info - if (type === _parenR || type === _braceR) { - var out = tokContext.pop(); - if (out === b_tmpl) { - preserveSpace = true; - } else if (out === b_stat && curTokContext() === f_expr) { - tokContext.pop(); - tokExprAllowed = false; - } else { - tokExprAllowed = !(out && out.isExpr); - } - } else if (type === _braceL) { - tokContext.push(braceIsBlock(prevType) ? b_stat : b_expr); - tokExprAllowed = true; - } else if (type === _dollarBraceL) { - tokContext.push(b_tmpl); - tokExprAllowed = true; - } else if (type == _parenL) { - var statementParens = prevType === _if || prevType === _for || prevType === _with || prevType === _while; - tokContext.push(statementParens ? p_stat : p_expr); - tokExprAllowed = true; - } else if (type == _incDec) { - // tokExprAllowed stays unchanged - } else if (type.keyword && prevType == _dot) { - tokExprAllowed = false; - } else if (type == _function) { - if (curTokContext() !== b_stat) { - tokContext.push(f_expr); - } - tokExprAllowed = false; - } else if (type === _backQuote) { - if (curTokContext() === q_tmpl) { - tokContext.pop(); - } else { - tokContext.push(q_tmpl); - preserveSpace = true; - } - tokExprAllowed = false; - } else { - tokExprAllowed = type.beforeExpr; - } - - if (!preserveSpace) skipSpace(); - } - - function skipBlockComment() { - var startLoc = options.onComment && options.locations && curPosition(); - var start = tokPos, end = input.indexOf("*/", tokPos += 2); - if (end === -1) raise(tokPos - 2, "Unterminated comment"); - tokPos = end + 2; - if (options.locations) { - lineBreak.lastIndex = start; - var match; - while ((match = lineBreak.exec(input)) && match.index < tokPos) { - ++tokCurLine; - tokLineStart = match.index + match[0].length; - } - } - if (options.onComment) - options.onComment(true, input.slice(start + 2, end), start, tokPos, - startLoc, options.locations && curPosition()); - } - - function skipLineComment(startSkip) { - var start = tokPos; - var startLoc = options.onComment && options.locations && curPosition(); - var ch = input.charCodeAt(tokPos+=startSkip); - while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++tokPos; - ch = input.charCodeAt(tokPos); - } - if (options.onComment) - options.onComment(false, input.slice(start + startSkip, tokPos), start, tokPos, - startLoc, options.locations && curPosition()); - } - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - function skipSpace() { - while (tokPos < inputLen) { - var ch = input.charCodeAt(tokPos); - if (ch === 32) { // ' ' - ++tokPos; - } else if (ch === 13) { - ++tokPos; - var next = input.charCodeAt(tokPos); - if (next === 10) { - ++tokPos; - } - if (options.locations) { - ++tokCurLine; - tokLineStart = tokPos; - } - } else if (ch === 10 || ch === 8232 || ch === 8233) { - ++tokPos; - if (options.locations) { - ++tokCurLine; - tokLineStart = tokPos; - } - } else if (ch > 8 && ch < 14) { - ++tokPos; - } else if (ch === 47) { // '/' - var next = input.charCodeAt(tokPos + 1); - if (next === 42) { // '*' - skipBlockComment(); - } else if (next === 47) { // '/' - skipLineComment(2); - } else break; - } else if (ch === 160) { // '\xa0' - ++tokPos; - } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++tokPos; - } else { - break; - } - } - } - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - function readToken_dot() { - var next = input.charCodeAt(tokPos + 1); - if (next >= 48 && next <= 57) return readNumber(true); - var next2 = input.charCodeAt(tokPos + 2); - if (options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - tokPos += 3; - return finishToken(_ellipsis); - } else { - ++tokPos; - return finishToken(_dot); - } - } - - function readToken_slash() { // '/' - var next = input.charCodeAt(tokPos + 1); - if (tokExprAllowed) {++tokPos; return readRegexp();} - if (next === 61) return finishOp(_assign, 2); - return finishOp(_slash, 1); - } - - function readToken_mult_modulo(code) { // '%*' - var next = input.charCodeAt(tokPos + 1); - if (next === 61) return finishOp(_assign, 2); - return finishOp(code === 42 ? _star : _modulo, 1); - } - - function readToken_pipe_amp(code) { // '|&' - var next = input.charCodeAt(tokPos + 1); - if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2); - if (next === 61) return finishOp(_assign, 2); - return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1); - } - - function readToken_caret() { // '^' - var next = input.charCodeAt(tokPos + 1); - if (next === 61) return finishOp(_assign, 2); - return finishOp(_bitwiseXOR, 1); - } - - function readToken_plus_min(code) { // '+-' - var next = input.charCodeAt(tokPos + 1); - if (next === code) { - if (next == 45 && input.charCodeAt(tokPos + 2) == 62 && - newline.test(input.slice(lastEnd, tokPos))) { - // A `-->` line comment - skipLineComment(3); - skipSpace(); - return readToken(); - } - return finishOp(_incDec, 2); - } - if (next === 61) return finishOp(_assign, 2); - return finishOp(_plusMin, 1); - } - - function readToken_lt_gt(code) { // '<>' - var next = input.charCodeAt(tokPos + 1); - var size = 1; - if (next === code) { - size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2; - if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1); - return finishOp(_bitShift, size); - } - if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 && - input.charCodeAt(tokPos + 3) == 45) { - // `")) { - stream.match("-->"); - state.tokenize = null; - } else { - stream.skipToEnd(); - } - return ["comment", "comment"]; - } - - CodeMirror.defineMIME("text/css", { - mediaTypes: mediaTypes, - mediaFeatures: mediaFeatures, - propertyKeywords: propertyKeywords, - nonStandardPropertyKeywords: nonStandardPropertyKeywords, - colorKeywords: colorKeywords, - valueKeywords: valueKeywords, - fontProperties: fontProperties, - tokenHooks: { - "<": function(stream, state) { - if (!stream.match("!--")) return false; - state.tokenize = tokenSGMLComment; - return tokenSGMLComment(stream, state); - }, - "/": function(stream, state) { - if (!stream.eat("*")) return false; - state.tokenize = tokenCComment; - return tokenCComment(stream, state); - } - }, - name: "css" - }); - - CodeMirror.defineMIME("text/x-scss", { - mediaTypes: mediaTypes, - mediaFeatures: mediaFeatures, - propertyKeywords: propertyKeywords, - nonStandardPropertyKeywords: nonStandardPropertyKeywords, - colorKeywords: colorKeywords, - valueKeywords: valueKeywords, - fontProperties: fontProperties, - allowNested: true, - tokenHooks: { - "/": function(stream, state) { - if (stream.eat("/")) { - stream.skipToEnd(); - return ["comment", "comment"]; - } else if (stream.eat("*")) { - state.tokenize = tokenCComment; - return tokenCComment(stream, state); - } else { - return ["operator", "operator"]; - } - }, - ":": function(stream) { - if (stream.match(/\s*\{/)) - return [null, "{"]; - return false; - }, - "$": function(stream) { - stream.match(/^[\w-]+/); - if (stream.match(/^\s*:/, false)) - return ["variable-2", "variable-definition"]; - return ["variable-2", "variable"]; - }, - "#": function(stream) { - if (!stream.eat("{")) return false; - return [null, "interpolation"]; - } - }, - name: "css", - helperType: "scss" - }); - - CodeMirror.defineMIME("text/x-less", { - mediaTypes: mediaTypes, - mediaFeatures: mediaFeatures, - propertyKeywords: propertyKeywords, - nonStandardPropertyKeywords: nonStandardPropertyKeywords, - colorKeywords: colorKeywords, - valueKeywords: valueKeywords, - fontProperties: fontProperties, - allowNested: true, - tokenHooks: { - "/": function(stream, state) { - if (stream.eat("/")) { - stream.skipToEnd(); - return ["comment", "comment"]; - } else if (stream.eat("*")) { - state.tokenize = tokenCComment; - return tokenCComment(stream, state); - } else { - return ["operator", "operator"]; - } - }, - "@": function(stream) { - if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; - stream.eatWhile(/[\w\\\-]/); - if (stream.match(/^\s*:/, false)) - return ["variable-2", "variable-definition"]; - return ["variable-2", "variable"]; - }, - "&": function() { - return ["atom", "atom"]; - } - }, - name: "css", - helperType: "less" - }); - -}); diff --git a/mix/qml/html/cm/def.js b/mix/qml/html/cm/def.js deleted file mode 100644 index 6cad09245..000000000 --- a/mix/qml/html/cm/def.js +++ /dev/null @@ -1,547 +0,0 @@ -// Type description parser -// -// Type description JSON files (such as ecma5.json and browser.json) -// are used to -// -// A) describe types that come from native code -// -// B) to cheaply load the types for big libraries, or libraries that -// can't be inferred well - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - return exports.init = mod; - if (typeof define == "function" && define.amd) // AMD - return define({init: mod}); - tern.def = {init: mod}; -})(function(exports, infer) { - "use strict"; - - function hop(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var TypeParser = exports.TypeParser = function(spec, start, base, forceNew) { - this.pos = start || 0; - this.spec = spec; - this.base = base; - this.forceNew = forceNew; - }; - TypeParser.prototype = { - eat: function(str) { - if (str.length == 1 ? this.spec.charAt(this.pos) == str : this.spec.indexOf(str, this.pos) == this.pos) { - this.pos += str.length; - return true; - } - }, - word: function(re) { - var word = "", ch, re = re || /[\w$]/; - while ((ch = this.spec.charAt(this.pos)) && re.test(ch)) { word += ch; ++this.pos; } - return word; - }, - error: function() { - throw new Error("Unrecognized type spec: " + this.spec + " (at " + this.pos + ")"); - }, - parseFnType: function(name, top) { - var args = [], names = []; - if (!this.eat(")")) for (var i = 0; ; ++i) { - var colon = this.spec.indexOf(": ", this.pos), argname; - if (colon != -1) { - argname = this.spec.slice(this.pos, colon); - if (/^[$\w?]+$/.test(argname)) - this.pos = colon + 2; - else - argname = null; - } - names.push(argname); - args.push(this.parseType()); - if (!this.eat(", ")) { - this.eat(")") || this.error(); - break; - } - } - var retType, computeRet, computeRetStart, fn; - if (this.eat(" -> ")) { - if (top && this.spec.indexOf("!", this.pos) > -1) { - retType = infer.ANull; - computeRetStart = this.pos; - computeRet = this.parseRetType(); - } else retType = this.parseType(); - } else retType = infer.ANull; - if (top && (fn = this.base)) - infer.Fn.call(this.base, name, infer.ANull, args, names, retType); - else - fn = new infer.Fn(name, infer.ANull, args, names, retType); - if (computeRet) fn.computeRet = computeRet; - if (computeRetStart != null) fn.computeRetSource = this.spec.slice(computeRetStart, this.pos); - return fn; - }, - parseType: function(name, top) { - var type, union = false; - for (;;) { - var inner = this.parseTypeInner(name, top); - if (union) inner.propagate(union); - else type = inner; - if (!this.eat("|")) break; - if (!union) { - union = new infer.AVal; - type.propagate(union); - type = union; - } - } - return type; - }, - parseTypeInner: function(name, top) { - if (this.eat("fn(")) { - return this.parseFnType(name, top); - } else if (this.eat("[")) { - var inner = this.parseType(); - this.eat("]") || this.error(); - if (top && this.base) { - infer.Arr.call(this.base, inner); - return this.base; - } - return new infer.Arr(inner); - } else if (this.eat("+")) { - var path = this.word(/[\w$<>\.!]/); - var base = parsePath(path + ".prototype"); - if (!(base instanceof infer.Obj)) base = parsePath(path); - if (!(base instanceof infer.Obj)) return base; - if (top && this.forceNew) return new infer.Obj(base); - return infer.getInstance(base); - } else if (this.eat("?")) { - return infer.ANull; - } else { - return this.fromWord(this.word(/[\w$<>\.!`]/)); - } - }, - fromWord: function(spec) { - var cx = infer.cx(); - switch (spec) { - case "number": return cx.num; - case "string": return cx.str; - case "bool": return cx.bool; - case "": return cx.topScope; - } - if (cx.localDefs && spec in cx.localDefs) return cx.localDefs[spec]; - return parsePath(spec); - }, - parseBaseRetType: function() { - if (this.eat("[")) { - var inner = this.parseRetType(); - this.eat("]") || this.error(); - return function(self, args) { return new infer.Arr(inner(self, args)); }; - } else if (this.eat("+")) { - var base = this.parseRetType(); - var result = function(self, args) { - var proto = base(self, args); - if (proto instanceof infer.Fn && proto.hasProp("prototype")) - proto = proto.getProp("prototype").getObjType(); - if (!(proto instanceof infer.Obj)) return proto; - return new infer.Obj(proto); - }; - if (this.eat("[")) return this.parsePoly(result); - return result; - } else if (this.eat("!")) { - var arg = this.word(/\d/); - if (arg) { - arg = Number(arg); - return function(_self, args) {return args[arg] || infer.ANull;}; - } else if (this.eat("this")) { - return function(self) {return self;}; - } else if (this.eat("custom:")) { - var fname = this.word(/[\w$]/); - return customFunctions[fname] || function() { return infer.ANull; }; - } else { - return this.fromWord("!" + arg + this.word(/[\w$<>\.!]/)); - } - } - var t = this.parseType(); - return function(){return t;}; - }, - extendRetType: function(base) { - var propName = this.word(/[\w<>$!]/) || this.error(); - if (propName == "!ret") return function(self, args) { - var lhs = base(self, args); - if (lhs.retval) return lhs.retval; - var rv = new infer.AVal; - lhs.propagate(new infer.IsCallee(infer.ANull, [], null, rv)); - return rv; - }; - return function(self, args) {return base(self, args).getProp(propName);}; - }, - parsePoly: function(base) { - var propName = "", match; - if (match = this.spec.slice(this.pos).match(/^\s*(\w+)\s*=\s*/)) { - propName = match[1]; - this.pos += match[0].length; - } - var value = this.parseRetType(); - if (!this.eat("]")) this.error(); - return function(self, args) { - var instance = base(self, args); - if (instance instanceof infer.Obj) - value(self, args).propagate(instance.defProp(propName)); - return instance; - }; - }, - parseRetType: function() { - var tp = this.parseBaseRetType(); - while (this.eat(".")) tp = this.extendRetType(tp); - return tp; - } - }; - - function parseType(spec, name, base, forceNew) { - var type = new TypeParser(spec, null, base, forceNew).parseType(name, true); - if (/^fn\(/.test(spec)) for (var i = 0; i < type.args.length; ++i) (function(i) { - var arg = type.args[i]; - if (arg instanceof infer.Fn && arg.args && arg.args.length) addEffect(type, function(_self, fArgs) { - var fArg = fArgs[i]; - if (fArg) fArg.propagate(new infer.IsCallee(infer.cx().topScope, arg.args, null, infer.ANull)); - }); - })(i); - return type; - } - - function addEffect(fn, handler, replaceRet) { - var oldCmp = fn.computeRet, rv = fn.retval; - fn.computeRet = function(self, args, argNodes) { - var handled = handler(self, args, argNodes); - var old = oldCmp ? oldCmp(self, args, argNodes) : rv; - return replaceRet ? handled : old; - }; - } - - var parseEffect = exports.parseEffect = function(effect, fn) { - var m; - if (effect.indexOf("propagate ") == 0) { - var p = new TypeParser(effect, 10); - var getOrigin = p.parseRetType(); - if (!p.eat(" ")) p.error(); - var getTarget = p.parseRetType(); - addEffect(fn, function(self, args) { - getOrigin(self, args).propagate(getTarget(self, args)); - }); - } else if (effect.indexOf("call ") == 0) { - var andRet = effect.indexOf("and return ", 5) == 5; - var p = new TypeParser(effect, andRet ? 16 : 5); - var getCallee = p.parseRetType(), getSelf = null, getArgs = []; - if (p.eat(" this=")) getSelf = p.parseRetType(); - while (p.eat(" ")) getArgs.push(p.parseRetType()); - addEffect(fn, function(self, args) { - var callee = getCallee(self, args); - var slf = getSelf ? getSelf(self, args) : infer.ANull, as = []; - for (var i = 0; i < getArgs.length; ++i) as.push(getArgs[i](self, args)); - var result = andRet ? new infer.AVal : infer.ANull; - callee.propagate(new infer.IsCallee(slf, as, null, result)); - return result; - }, andRet); - } else if (m = effect.match(/^custom (\S+)\s*(.*)/)) { - var customFunc = customFunctions[m[1]]; - if (customFunc) addEffect(fn, m[2] ? customFunc(m[2]) : customFunc); - } else if (effect.indexOf("copy ") == 0) { - var p = new TypeParser(effect, 5); - var getFrom = p.parseRetType(); - p.eat(" "); - var getTo = p.parseRetType(); - addEffect(fn, function(self, args) { - var from = getFrom(self, args), to = getTo(self, args); - from.forAllProps(function(prop, val, local) { - if (local && prop != "") - to.propagate(new infer.PropHasSubset(prop, val)); - }); - }); - } else { - throw new Error("Unknown effect type: " + effect); - } - }; - - var currentTopScope; - - var parsePath = exports.parsePath = function(path, scope) { - var cx = infer.cx(), cached = cx.paths[path], origPath = path; - if (cached != null) return cached; - cx.paths[path] = infer.ANull; - - var base = scope || currentTopScope || cx.topScope; - - if (cx.localDefs) for (var name in cx.localDefs) { - if (path.indexOf(name) == 0) { - if (path == name) return cx.paths[path] = cx.localDefs[path]; - if (path.charAt(name.length) == ".") { - base = cx.localDefs[name]; - path = path.slice(name.length + 1); - break; - } - } - } - - var parts = path.split("."); - for (var i = 0; i < parts.length && base != infer.ANull; ++i) { - var prop = parts[i]; - if (prop.charAt(0) == "!") { - if (prop == "!proto") { - base = (base instanceof infer.Obj && base.proto) || infer.ANull; - } else { - var fn = base.getFunctionType(); - if (!fn) { - base = infer.ANull; - } else if (prop == "!ret") { - base = fn.retval && fn.retval.getType(false) || infer.ANull; - } else { - var arg = fn.args && fn.args[Number(prop.slice(1))]; - base = (arg && arg.getType(false)) || infer.ANull; - } - } - } else if (base instanceof infer.Obj) { - var propVal = (prop == "prototype" && base instanceof infer.Fn) ? base.getProp(prop) : base.props[prop]; - if (!propVal || propVal.isEmpty()) - base = infer.ANull; - else - base = propVal.types[0]; - } - } - // Uncomment this to get feedback on your poorly written .json files - // if (base == infer.ANull) console.error("bad path: " + origPath + " (" + cx.curOrigin + ")"); - cx.paths[origPath] = base == infer.ANull ? null : base; - return base; - }; - - function emptyObj(ctor) { - var empty = Object.create(ctor.prototype); - empty.props = Object.create(null); - empty.isShell = true; - return empty; - } - - function isSimpleAnnotation(spec) { - if (!spec["!type"] || /^(fn\(|\[)/.test(spec["!type"])) return false; - for (var prop in spec) - if (prop != "!type" && prop != "!doc" && prop != "!url" && prop != "!span" && prop != "!data") - return false; - return true; - } - - function passOne(base, spec, path) { - if (!base) { - var tp = spec["!type"]; - if (tp) { - if (/^fn\(/.test(tp)) base = emptyObj(infer.Fn); - else if (tp.charAt(0) == "[") base = emptyObj(infer.Arr); - else throw new Error("Invalid !type spec: " + tp); - } else if (spec["!stdProto"]) { - base = infer.cx().protos[spec["!stdProto"]]; - } else { - base = emptyObj(infer.Obj); - } - base.name = path; - } - - for (var name in spec) if (hop(spec, name) && name.charCodeAt(0) != 33) { - var inner = spec[name]; - if (typeof inner == "string" || isSimpleAnnotation(inner)) continue; - var prop = base.defProp(name); - passOne(prop.getObjType(), inner, path ? path + "." + name : name).propagate(prop); - } - return base; - } - - function passTwo(base, spec, path) { - if (base.isShell) { - delete base.isShell; - var tp = spec["!type"]; - if (tp) { - parseType(tp, path, base); - } else { - var proto = spec["!proto"] && parseType(spec["!proto"]); - infer.Obj.call(base, proto instanceof infer.Obj ? proto : true, path); - } - } - - var effects = spec["!effects"]; - if (effects && base instanceof infer.Fn) for (var i = 0; i < effects.length; ++i) - parseEffect(effects[i], base); - copyInfo(spec, base); - - for (var name in spec) if (hop(spec, name) && name.charCodeAt(0) != 33) { - var inner = spec[name], known = base.defProp(name), innerPath = path ? path + "." + name : name; - if (typeof inner == "string") { - if (known.isEmpty()) parseType(inner, innerPath).propagate(known); - } else { - if (!isSimpleAnnotation(inner)) - passTwo(known.getObjType(), inner, innerPath); - else if (known.isEmpty()) - parseType(inner["!type"], innerPath, null, true).propagate(known); - else - continue; - if (inner["!doc"]) known.doc = inner["!doc"]; - if (inner["!url"]) known.url = inner["!url"]; - if (inner["!span"]) known.span = inner["!span"]; - } - } - return base; - } - - function copyInfo(spec, type) { - if (spec["!doc"]) type.doc = spec["!doc"]; - if (spec["!url"]) type.url = spec["!url"]; - if (spec["!span"]) type.span = spec["!span"]; - if (spec["!data"]) type.metaData = spec["!data"]; - } - - function runPasses(type, arg) { - var parent = infer.cx().parent, pass = parent && parent.passes && parent.passes[type]; - if (pass) for (var i = 0; i < pass.length; i++) pass[i](arg); - } - - function doLoadEnvironment(data, scope) { - var cx = infer.cx(); - - infer.addOrigin(cx.curOrigin = data["!name"] || "env#" + cx.origins.length); - cx.localDefs = cx.definitions[cx.curOrigin] = Object.create(null); - - runPasses("preLoadDef", data); - - passOne(scope, data); - - var def = data["!define"]; - if (def) { - for (var name in def) { - var spec = def[name]; - cx.localDefs[name] = typeof spec == "string" ? parsePath(spec) : passOne(null, spec, name); - } - for (var name in def) { - var spec = def[name]; - if (typeof spec != "string") passTwo(cx.localDefs[name], def[name], name); - } - } - - passTwo(scope, data); - - runPasses("postLoadDef", data); - - cx.curOrigin = cx.localDefs = null; - } - - exports.load = function(data, scope) { - if (!scope) scope = infer.cx().topScope; - var oldScope = currentTopScope; - currentTopScope = scope; - try { - doLoadEnvironment(data, scope); - } finally { - currentTopScope = oldScope; - } - }; - - exports.parse = function(data, origin, path) { - var cx = infer.cx(); - if (origin) { - cx.origin = origin; - cx.localDefs = cx.definitions[origin]; - } - - try { - if (typeof data == "string") - return parseType(data, path); - else - return passTwo(passOne(null, data, path), data, path); - } finally { - if (origin) cx.origin = cx.localDefs = null; - } - }; - - // Used to register custom logic for more involved effect or type - // computation. - var customFunctions = Object.create(null); - infer.registerFunction = function(name, f) { customFunctions[name] = f; }; - - var IsCreated = infer.constraint("created, target, spec", { - addType: function(tp) { - if (tp instanceof infer.Obj && this.created++ < 5) { - var derived = new infer.Obj(tp), spec = this.spec; - if (spec instanceof infer.AVal) spec = spec.getObjType(false); - if (spec instanceof infer.Obj) for (var prop in spec.props) { - var cur = spec.props[prop].types[0]; - var p = derived.defProp(prop); - if (cur && cur instanceof infer.Obj && cur.props.value) { - var vtp = cur.props.value.getType(false); - if (vtp) p.addType(vtp); - } - } - this.target.addType(derived); - } - } - }); - - infer.registerFunction("Object_create", function(_self, args, argNodes) { - if (argNodes && argNodes.length && argNodes[0].type == "Literal" && argNodes[0].value == null) - return new infer.Obj(); - - var result = new infer.AVal; - if (args[0]) args[0].propagate(new IsCreated(0, result, args[1])); - return result; - }); - - var PropSpec = infer.constraint("target", { - addType: function(tp) { - if (!(tp instanceof infer.Obj)) return; - if (tp.hasProp("value")) - tp.getProp("value").propagate(this.target); - else if (tp.hasProp("get")) - tp.getProp("get").propagate(new infer.IsCallee(infer.ANull, [], null, this.target)); - } - }); - - infer.registerFunction("Object_defineProperty", function(_self, args, argNodes) { - if (argNodes && argNodes.length >= 3 && argNodes[1].type == "Literal" && - typeof argNodes[1].value == "string") { - var obj = args[0], connect = new infer.AVal; - obj.propagate(new infer.PropHasSubset(argNodes[1].value, connect, argNodes[1])); - args[2].propagate(new PropSpec(connect)); - } - return infer.ANull; - }); - - var IsBound = infer.constraint("self, args, target", { - addType: function(tp) { - if (!(tp instanceof infer.Fn)) return; - this.target.addType(new infer.Fn(tp.name, tp.self, tp.args.slice(this.args.length), - tp.argNames.slice(this.args.length), tp.retval)); - this.self.propagate(tp.self); - for (var i = 0; i < Math.min(tp.args.length, this.args.length); ++i) - this.args[i].propagate(tp.args[i]); - } - }); - - infer.registerFunction("Function_bind", function(self, args) { - if (!args.length) return infer.ANull; - var result = new infer.AVal; - self.propagate(new IsBound(args[0], args.slice(1), result)); - return result; - }); - - infer.registerFunction("Array_ctor", function(_self, args) { - var arr = new infer.Arr; - if (args.length != 1 || !args[0].hasType(infer.cx().num)) { - var content = arr.getProp(""); - for (var i = 0; i < args.length; ++i) args[i].propagate(content); - } - return arr; - }); - - infer.registerFunction("Promise_ctor", function(_self, args, argNodes) { - if (args.length < 1) return infer.ANull; - var self = new infer.Obj(infer.cx().definitions.ecma6["Promise.prototype"]); - var valProp = self.defProp("value", argNodes && argNodes[0]); - var valArg = new infer.AVal; - valArg.propagate(valProp); - var exec = new infer.Fn("execute", infer.ANull, [valArg], ["value"], infer.ANull); - var reject = infer.cx().definitions.ecma6.promiseReject; - args[0].propagate(new infer.IsCallee(infer.ANull, [exec, reject], null, infer.ANull)); - return self; - }); - - return exports; -}); diff --git a/mix/qml/html/cm/dialog.css b/mix/qml/html/cm/dialog.css deleted file mode 100644 index 2e7c0fc9b..000000000 --- a/mix/qml/html/cm/dialog.css +++ /dev/null @@ -1,32 +0,0 @@ -.CodeMirror-dialog { - position: absolute; - left: 0; right: 0; - background: white; - z-index: 15; - padding: .1em .8em; - overflow: hidden; - color: #333; -} - -.CodeMirror-dialog-top { - border-bottom: 1px solid #eee; - top: 0; -} - -.CodeMirror-dialog-bottom { - border-top: 1px solid #eee; - bottom: 0; -} - -.CodeMirror-dialog input { - border: none; - outline: none; - background: transparent; - width: 20em; - color: inherit; - font-family: monospace; -} - -.CodeMirror-dialog button { - font-size: 70%; -} diff --git a/mix/qml/html/cm/dialog.js b/mix/qml/html/cm/dialog.js deleted file mode 100644 index e0e8ad4eb..000000000 --- a/mix/qml/html/cm/dialog.js +++ /dev/null @@ -1,155 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// Open simple dialogs on top of an editor. Relies on dialog.css. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - function dialogDiv(cm, template, bottom) { - var wrap = cm.getWrapperElement(); - var dialog; - dialog = wrap.appendChild(document.createElement("div")); - if (bottom) - dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom"; - else - dialog.className = "CodeMirror-dialog CodeMirror-dialog-top"; - - if (typeof template == "string") { - dialog.innerHTML = template; - } else { // Assuming it's a detached DOM element. - dialog.appendChild(template); - } - return dialog; - } - - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) - cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - - CodeMirror.defineExtension("openDialog", function(template, callback, options) { - if (!options) options = {}; - - closeNotification(this, null); - - var dialog = dialogDiv(this, template, options.bottom); - var closed = false, me = this; - function close(newVal) { - if (typeof newVal == 'string') { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - me.focus(); - - if (options.onClose) options.onClose(dialog); - } - } - - var inp = dialog.getElementsByTagName("input")[0], button; - if (inp) { - if (options.value) { - inp.value = options.value; - inp.select(); - } - - if (options.onInput) - CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); - if (options.onKeyUp) - CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); - - CodeMirror.on(inp, "keydown", function(e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } - if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value, e); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); - - inp.focus(); - } else if (button = dialog.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function() { - close(); - me.focus(); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - - button.focus(); - } - return close; - }); - - CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) { - closeNotification(this, null); - var dialog = dialogDiv(this, template, options && options.bottom); - var buttons = dialog.getElementsByTagName("button"); - var closed = false, me = this, blurring = 1; - function close() { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - me.focus(); - } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function(callback) { - CodeMirror.on(b, "click", function(e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.on(b, "blur", function() { - --blurring; - setTimeout(function() { if (blurring <= 0) close(); }, 200); - }); - CodeMirror.on(b, "focus", function() { ++blurring; }); - } - }); - - /* - * openNotification - * Opens a notification, that can be closed with an optional timer - * (default 5000ms timer) and always closes on click. - * - * If a notification is opened while another is opened, it will close the - * currently opened one and open the new one immediately. - */ - CodeMirror.defineExtension("openNotification", function(template, options) { - closeNotification(this, close); - var dialog = dialogDiv(this, template, options && options.bottom); - var closed = false, doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; - - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - dialog.parentNode.removeChild(dialog); - } - - CodeMirror.on(dialog, 'click', function(e) { - CodeMirror.e_preventDefault(e); - close(); - }); - - if (duration) - doneTimer = setTimeout(close, duration); - - return close; - }); -}); diff --git a/mix/qml/html/cm/doc_comment.js b/mix/qml/html/cm/doc_comment.js deleted file mode 100644 index ed461ea97..000000000 --- a/mix/qml/html/cm/doc_comment.js +++ /dev/null @@ -1,402 +0,0 @@ -// Parses comments above variable declarations, function declarations, -// and object properties as docstrings and JSDoc-style type -// annotations. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - return mod(require("../lib/infer"), require("../lib/tern"), require("../lib/comment"), - require("acorn/acorn"), require("acorn/util/walk")); - if (typeof define == "function" && define.amd) // AMD - return define(["../lib/infer", "../lib/tern", "../lib/comment", "acorn/acorn", "acorn/util/walk"], mod); - mod(tern, tern, tern.comment, acorn, acorn.walk); -})(function(infer, tern, comment, acorn, walk) { - "use strict"; - - var WG_MADEUP = 1, WG_STRONG = 101; - - tern.registerPlugin("doc_comment", function(server, options) { - server.jsdocTypedefs = Object.create(null); - server.on("reset", function() { - server.jsdocTypedefs = Object.create(null); - }); - server._docComment = { - weight: options && options.strong ? WG_STRONG : undefined, - fullDocs: options && options.fullDocs - }; - - return { - passes: { - postParse: postParse, - postInfer: postInfer, - postLoadDef: postLoadDef - } - }; - }); - - function postParse(ast, text) { - function attachComments(node) { comment.ensureCommentsBefore(text, node); } - - walk.simple(ast, { - VariableDeclaration: attachComments, - FunctionDeclaration: attachComments, - AssignmentExpression: function(node) { - if (node.operator == "=") attachComments(node); - }, - ObjectExpression: function(node) { - for (var i = 0; i < node.properties.length; ++i) - attachComments(node.properties[i]); - }, - CallExpression: function(node) { - if (isDefinePropertyCall(node)) attachComments(node); - } - }); - } - - function isDefinePropertyCall(node) { - return node.callee.type == "MemberExpression" && - node.callee.object.name == "Object" && - node.callee.property.name == "defineProperty" && - node.arguments.length >= 3 && - typeof node.arguments[1].value == "string"; - } - - function postInfer(ast, scope) { - jsdocParseTypedefs(ast.sourceFile.text, scope); - - walk.simple(ast, { - VariableDeclaration: function(node, scope) { - if (node.commentsBefore) - interpretComments(node, node.commentsBefore, scope, - scope.getProp(node.declarations[0].id.name)); - }, - FunctionDeclaration: function(node, scope) { - if (node.commentsBefore) - interpretComments(node, node.commentsBefore, scope, - scope.getProp(node.id.name), - node.body.scope.fnType); - }, - AssignmentExpression: function(node, scope) { - if (node.commentsBefore) - interpretComments(node, node.commentsBefore, scope, - infer.expressionType({node: node.left, state: scope})); - }, - ObjectExpression: function(node, scope) { - for (var i = 0; i < node.properties.length; ++i) { - var prop = node.properties[i]; - if (prop.commentsBefore) - interpretComments(prop, prop.commentsBefore, scope, - node.objType.getProp(prop.key.name)); - } - }, - CallExpression: function(node, scope) { - if (node.commentsBefore && isDefinePropertyCall(node)) { - var type = infer.expressionType({node: node.arguments[0], state: scope}).getObjType(); - if (type && type instanceof infer.Obj) { - var prop = type.props[node.arguments[1].value]; - if (prop) interpretComments(node, node.commentsBefore, scope, prop); - } - } - } - }, infer.searchVisitor, scope); - } - - function postLoadDef(data) { - var defs = data["!typedef"]; - var cx = infer.cx(), orig = data["!name"]; - if (defs) for (var name in defs) - cx.parent.jsdocTypedefs[name] = - maybeInstance(infer.def.parse(defs[name], orig, name), name); - } - - // COMMENT INTERPRETATION - - function interpretComments(node, comments, scope, aval, type) { - jsdocInterpretComments(node, scope, aval, comments); - var cx = infer.cx(); - - if (!type && aval instanceof infer.AVal && aval.types.length) { - type = aval.types[aval.types.length - 1]; - if (!(type instanceof infer.Obj) || type.origin != cx.curOrigin || type.doc) - type = null; - } - - var result = comments[comments.length - 1]; - if (cx.parent._docComment.fullDocs) { - result = result.trim().replace(/\n[ \t]*\* ?/g, "\n"); - } else { - var dot = result.search(/\.\s/); - if (dot > 5) result = result.slice(0, dot + 1); - result = result.trim().replace(/\s*\n\s*\*\s*|\s{1,}/g, " "); - } - result = result.replace(/^\s*\*+\s*/, ""); - - if (aval instanceof infer.AVal) aval.doc = result; - if (type) type.doc = result; - } - - // Parses a subset of JSDoc-style comments in order to include the - // explicitly defined types in the analysis. - - function skipSpace(str, pos) { - while (/\s/.test(str.charAt(pos))) ++pos; - return pos; - } - - function isIdentifier(string) { - if (!acorn.isIdentifierStart(string.charCodeAt(0))) return false; - for (var i = 1; i < string.length; i++) - if (!acorn.isIdentifierChar(string.charCodeAt(i))) return false; - return true; - } - - function parseLabelList(scope, str, pos, close) { - var labels = [], types = [], madeUp = false; - for (var first = true; ; first = false) { - pos = skipSpace(str, pos); - if (first && str.charAt(pos) == close) break; - var colon = str.indexOf(":", pos); - if (colon < 0) return null; - var label = str.slice(pos, colon); - if (!isIdentifier(label)) return null; - labels.push(label); - pos = colon + 1; - var type = parseType(scope, str, pos); - if (!type) return null; - pos = type.end; - madeUp = madeUp || type.madeUp; - types.push(type.type); - pos = skipSpace(str, pos); - var next = str.charAt(pos); - ++pos; - if (next == close) break; - if (next != ",") return null; - } - return {labels: labels, types: types, end: pos, madeUp: madeUp}; - } - - function parseType(scope, str, pos) { - var type, union = false, madeUp = false; - for (;;) { - var inner = parseTypeInner(scope, str, pos); - if (!inner) return null; - madeUp = madeUp || inner.madeUp; - if (union) inner.type.propagate(union); - else type = inner.type; - pos = skipSpace(str, inner.end); - if (str.charAt(pos) != "|") break; - pos++; - if (!union) { - union = new infer.AVal; - type.propagate(union); - type = union; - } - } - var isOptional = false; - if (str.charAt(pos) == "=") { - ++pos; - isOptional = true; - } - return {type: type, end: pos, isOptional: isOptional, madeUp: madeUp}; - } - - function parseTypeInner(scope, str, pos) { - pos = skipSpace(str, pos); - var type, madeUp = false; - - if (str.indexOf("function(", pos) == pos) { - var args = parseLabelList(scope, str, pos + 9, ")"), ret = infer.ANull; - if (!args) return null; - pos = skipSpace(str, args.end); - if (str.charAt(pos) == ":") { - ++pos; - var retType = parseType(scope, str, pos + 1); - if (!retType) return null; - pos = retType.end; - ret = retType.type; - madeUp = retType.madeUp; - } - type = new infer.Fn(null, infer.ANull, args.types, args.labels, ret); - } else if (str.charAt(pos) == "[") { - var inner = parseType(scope, str, pos + 1); - if (!inner) return null; - pos = skipSpace(str, inner.end); - madeUp = inner.madeUp; - if (str.charAt(pos) != "]") return null; - ++pos; - type = new infer.Arr(inner.type); - } else if (str.charAt(pos) == "{") { - var fields = parseLabelList(scope, str, pos + 1, "}"); - if (!fields) return null; - type = new infer.Obj(true); - for (var i = 0; i < fields.types.length; ++i) { - var field = type.defProp(fields.labels[i]); - field.initializer = true; - fields.types[i].propagate(field); - } - pos = fields.end; - madeUp = fields.madeUp; - } else if (str.charAt(pos) == "(") { - var inner = parseType(scope, str, pos + 1); - if (!inner) return null; - pos = skipSpace(str, inner.end); - if (str.charAt(pos) != ")") return null; - ++pos; - type = inner.type; - } else { - var start = pos; - if (!acorn.isIdentifierStart(str.charCodeAt(pos))) return null; - while (acorn.isIdentifierChar(str.charCodeAt(pos))) ++pos; - if (start == pos) return null; - var word = str.slice(start, pos); - if (/^(number|integer)$/i.test(word)) type = infer.cx().num; - else if (/^bool(ean)?$/i.test(word)) type = infer.cx().bool; - else if (/^string$/i.test(word)) type = infer.cx().str; - else if (/^(null|undefined)$/i.test(word)) type = infer.ANull; - else if (/^array$/i.test(word)) { - var inner = null; - if (str.charAt(pos) == "." && str.charAt(pos + 1) == "<") { - var inAngles = parseType(scope, str, pos + 2); - if (!inAngles) return null; - pos = skipSpace(str, inAngles.end); - madeUp = inAngles.madeUp; - if (str.charAt(pos++) != ">") return null; - inner = inAngles.type; - } - type = new infer.Arr(inner); - } else if (/^object$/i.test(word)) { - type = new infer.Obj(true); - if (str.charAt(pos) == "." && str.charAt(pos + 1) == "<") { - var key = parseType(scope, str, pos + 2); - if (!key) return null; - pos = skipSpace(str, key.end); - madeUp = madeUp || key.madeUp; - if (str.charAt(pos++) != ",") return null; - var val = parseType(scope, str, pos); - if (!val) return null; - pos = skipSpace(str, val.end); - madeUp = key.madeUp || val.madeUp; - if (str.charAt(pos++) != ">") return null; - val.type.propagate(type.defProp("")); - } - } else { - while (str.charCodeAt(pos) == 46 || - acorn.isIdentifierChar(str.charCodeAt(pos))) ++pos; - var path = str.slice(start, pos); - var cx = infer.cx(), defs = cx.parent && cx.parent.jsdocTypedefs, found; - if (defs && (path in defs)) { - type = defs[path]; - } else if (found = infer.def.parsePath(path, scope).getObjType()) { - type = maybeInstance(found, path); - } else { - if (!cx.jsdocPlaceholders) cx.jsdocPlaceholders = Object.create(null); - if (!(path in cx.jsdocPlaceholders)) - type = cx.jsdocPlaceholders[path] = new infer.Obj(null, path); - else - type = cx.jsdocPlaceholders[path]; - madeUp = true; - } - } - } - - return {type: type, end: pos, madeUp: madeUp}; - } - - function maybeInstance(type, path) { - if (type instanceof infer.Fn && /^[A-Z]/.test(path)) { - var proto = type.getProp("prototype").getObjType(); - if (proto instanceof infer.Obj) return infer.getInstance(proto); - } - return type; - } - - function parseTypeOuter(scope, str, pos) { - pos = skipSpace(str, pos || 0); - if (str.charAt(pos) != "{") return null; - var result = parseType(scope, str, pos + 1); - if (!result) return null; - var end = skipSpace(str, result.end); - if (str.charAt(end) != "}") return null; - result.end = end + 1; - return result; - } - - function jsdocInterpretComments(node, scope, aval, comments) { - var type, args, ret, foundOne, self, parsed; - - for (var i = 0; i < comments.length; ++i) { - var comment = comments[i]; - var decl = /(?:\n|$|\*)\s*@(type|param|arg(?:ument)?|returns?|this)\s+(.*)/g, m; - while (m = decl.exec(comment)) { - if (m[1] == "this" && (parsed = parseType(scope, m[2], 0))) { - self = parsed; - foundOne = true; - continue; - } - - if (!(parsed = parseTypeOuter(scope, m[2]))) continue; - foundOne = true; - - switch(m[1]) { - case "returns": case "return": - ret = parsed; break; - case "type": - type = parsed; break; - case "param": case "arg": case "argument": - var name = m[2].slice(parsed.end).match(/^\s*(\[?)\s*([^\]\s=]+)\s*(?:=[^\]]+\s*)?(\]?).*/); - if (!name) continue; - var argname = name[2] + (parsed.isOptional || (name[1] === '[' && name[3] === ']') ? "?" : ""); - (args || (args = Object.create(null)))[argname] = parsed; - break; - } - } - } - - if (foundOne) applyType(type, self, args, ret, node, aval); - }; - - function jsdocParseTypedefs(text, scope) { - var cx = infer.cx(); - - var re = /\s@typedef\s+(.*)/g, m; - while (m = re.exec(text)) { - var parsed = parseTypeOuter(scope, m[1]); - var name = parsed && m[1].slice(parsed.end).match(/^\s*(\S+)/); - if (name) - cx.parent.jsdocTypedefs[name[1]] = parsed.type; - } - } - - function propagateWithWeight(type, target) { - var weight = infer.cx().parent._docComment.weight; - type.type.propagate(target, weight || (type.madeUp ? WG_MADEUP : undefined)); - } - - function applyType(type, self, args, ret, node, aval) { - var fn; - if (node.type == "VariableDeclaration") { - var decl = node.declarations[0]; - if (decl.init && decl.init.type == "FunctionExpression") fn = decl.init.body.scope.fnType; - } else if (node.type == "FunctionDeclaration") { - fn = node.body.scope.fnType; - } else if (node.type == "AssignmentExpression") { - if (node.right.type == "FunctionExpression") - fn = node.right.body.scope.fnType; - } else if (node.type == "CallExpression") { - } else { // An object property - if (node.value.type == "FunctionExpression") fn = node.value.body.scope.fnType; - } - - if (fn && (args || ret || self)) { - if (args) for (var i = 0; i < fn.argNames.length; ++i) { - var name = fn.argNames[i], known = args[name]; - if (!known && (known = args[name + "?"])) - fn.argNames[i] += "?"; - if (known) propagateWithWeight(known, fn.args[i]); - } - if (ret) propagateWithWeight(ret, fn.retval); - if (self) propagateWithWeight(self, fn.self); - } else if (type) { - propagateWithWeight(type, aval); - } - }; -}); diff --git a/mix/qml/html/cm/ecma5spec.js b/mix/qml/html/cm/ecma5spec.js deleted file mode 100644 index 509d3ac83..000000000 --- a/mix/qml/html/cm/ecma5spec.js +++ /dev/null @@ -1,969 +0,0 @@ -function ecma5Spec() -{ -return { - "!name": "ecma5", - "!define": {"Error.prototype": "Error.prototype"}, - "Infinity": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Infinity", - "!doc": "A numeric value representing infinity." - }, - "undefined": { - "!type": "?", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined", - "!doc": "The value undefined." - }, - "NaN": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/NaN", - "!doc": "A value representing Not-A-Number." - }, - "Object": { - "!type": "fn()", - "getPrototypeOf": { - "!type": "fn(obj: ?) -> ?", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/getPrototypeOf", - "!doc": "Returns the prototype (i.e. the internal prototype) of the specified object." - }, - "create": { - "!type": "fn(proto: ?) -> !custom:Object_create", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create", - "!doc": "Creates a new object with the specified prototype object and properties." - }, - "defineProperty": { - "!type": "fn(obj: ?, prop: string, desc: ?) -> !custom:Object_defineProperty", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty", - "!doc": "Defines a new property directly on an object, or modifies an existing property on an object, and returns the object. If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see this article." - }, - "defineProperties": { - "!type": "fn(obj: ?, props: ?)", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty", - "!doc": "Defines a new property directly on an object, or modifies an existing property on an object, and returns the object. If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see this article." - }, - "getOwnPropertyDescriptor": { - "!type": "fn(obj: ?, prop: string) -> ?", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor", - "!doc": "Returns a property descriptor for an own property (that is, one directly present on an object, not present by dint of being along an object's prototype chain) of a given object." - }, - "keys": { - "!type": "fn(obj: ?) -> [string]", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys", - "!doc": "Returns an array of a given object's own enumerable properties, in the same order as that provided by a for-in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well)." - }, - "getOwnPropertyNames": { - "!type": "fn(obj: ?) -> [string]", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames", - "!doc": "Returns an array of all properties (enumerable or not) found directly upon a given object." - }, - "seal": { - "!type": "fn(obj: ?)", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/seal", - "!doc": "Seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable." - }, - "isSealed": { - "!type": "fn(obj: ?) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/isSealed", - "!doc": "Determine if an object is sealed." - }, - "freeze": { - "!type": "fn(obj: ?)", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/freeze", - "!doc": "Freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen." - }, - "isFrozen": { - "!type": "fn(obj: ?) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/isFrozen", - "!doc": "Determine if an object is frozen." - }, - "preventExtensions": { - "!type": "fn(obj: ?)", - "!url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions", - "!doc": "Prevents new properties from ever being added to an object." - }, - "isExtensible": { - "!type": "fn(obj: ?) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible", - "!doc": "The Object.isExtensible() method determines if an object is extensible (whether it can have new properties added to it)." - }, - "prototype": { - "!stdProto": "Object", - "toString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/toString", - "!doc": "Returns a string representing the object." - }, - "toLocaleString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/toLocaleString", - "!doc": "Returns a string representing the object. This method is meant to be overriden by derived objects for locale-specific purposes." - }, - "valueOf": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/valueOf", - "!doc": "Returns the primitive value of the specified object" - }, - "hasOwnProperty": { - "!type": "fn(prop: string) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty", - "!doc": "Returns a boolean indicating whether the object has the specified property." - }, - "propertyIsEnumerable": { - "!type": "fn(prop: string) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable", - "!doc": "Returns a Boolean indicating whether the specified property is enumerable." - }, - "isPrototypeOf": { - "!type": "fn(obj: ?) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf", - "!doc": "Tests for an object in another object's prototype chain." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object", - "!doc": "Creates an object wrapper." - }, - "Function": { - "!type": "fn(body: string) -> fn()", - "prototype": { - "!stdProto": "Function", - "apply": { - "!type": "fn(this: ?, args: [?])", - "!effects": [ - "call and return !this this=!0 !1. !1. !1." - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply", - "!doc": "Calls a function with a given this value and arguments provided as an array (or an array like object)." - }, - "call": { - "!type": "fn(this: ?, args?: ?) -> !this.!ret", - "!effects": [ - "call and return !this this=!0 !1 !2 !3 !4" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call", - "!doc": "Calls a function with a given this value and arguments provided individually." - }, - "bind": { - "!type": "fn(this: ?, args?: ?) -> !custom:Function_bind", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind", - "!doc": "Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function was called." - }, - "prototype": "?" - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function", - "!doc": "Every function in JavaScript is actually a Function object." - }, - "Array": { - "!type": "fn(size: number) -> !custom:Array_ctor", - "isArray": { - "!type": "fn(value: ?) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray", - "!doc": "Returns true if an object is an array, false if it is not." - }, - "prototype": { - "!stdProto": "Array", - "length": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/length", - "!doc": "An unsigned, 32-bit integer that specifies the number of elements in an array." - }, - "concat": { - "!type": "fn(other: [?]) -> !this", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat", - "!doc": "Returns a new array comprised of this array joined with other array(s) and/or value(s)." - }, - "join": { - "!type": "fn(separator?: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/join", - "!doc": "Joins all elements of an array into a string." - }, - "splice": { - "!type": "fn(pos: number, amount: number)", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice", - "!doc": "Changes the content of an array, adding new elements while removing old elements." - }, - "pop": { - "!type": "fn() -> !this.", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/pop", - "!doc": "Removes the last element from an array and returns that element." - }, - "push": { - "!type": "fn(newelt: ?) -> number", - "!effects": [ - "propagate !0 !this." - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push", - "!doc": "Mutates an array by appending the given elements and returning the new length of the array." - }, - "shift": { - "!type": "fn() -> !this.", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift", - "!doc": "Removes the first element from an array and returns that element. This method changes the length of the array." - }, - "unshift": { - "!type": "fn(newelt: ?) -> number", - "!effects": [ - "propagate !0 !this." - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/unshift", - "!doc": "Adds one or more elements to the beginning of an array and returns the new length of the array." - }, - "slice": { - "!type": "fn(from: number, to?: number) -> !this", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice", - "!doc": "Returns a shallow copy of a portion of an array." - }, - "reverse": { - "!type": "fn()", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/reverse", - "!doc": "Reverses an array in place. The first array element becomes the last and the last becomes the first." - }, - "sort": { - "!type": "fn(compare?: fn(a: ?, b: ?) -> number)", - "!effects": [ - "call !0 !this. !this." - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort", - "!doc": "Sorts the elements of an array in place and returns the array." - }, - "indexOf": { - "!type": "fn(elt: ?, from?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf", - "!doc": "Returns the first index at which a given element can be found in the array, or -1 if it is not present." - }, - "lastIndexOf": { - "!type": "fn(elt: ?, from?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf", - "!doc": "Returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex." - }, - "every": { - "!type": "fn(test: fn(elt: ?, i: number) -> bool, context?: ?) -> bool", - "!effects": [ - "call !0 this=!1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every", - "!doc": "Tests whether all elements in the array pass the test implemented by the provided function." - }, - "some": { - "!type": "fn(test: fn(elt: ?, i: number) -> bool, context?: ?) -> bool", - "!effects": [ - "call !0 this=!1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some", - "!doc": "Tests whether some element in the array passes the test implemented by the provided function." - }, - "filter": { - "!type": "fn(test: fn(elt: ?, i: number) -> bool, context?: ?) -> !this", - "!effects": [ - "call !0 this=!1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter", - "!doc": "Creates a new array with all elements that pass the test implemented by the provided function." - }, - "forEach": { - "!type": "fn(f: fn(elt: ?, i: number), context?: ?)", - "!effects": [ - "call !0 this=!1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach", - "!doc": "Executes a provided function once per array element." - }, - "map": { - "!type": "fn(f: fn(elt: ?, i: number) -> ?, context?: ?) -> [!0.!ret]", - "!effects": [ - "call !0 this=!1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map", - "!doc": "Creates a new array with the results of calling a provided function on every element in this array." - }, - "reduce": { - "!type": "fn(combine: fn(sum: ?, elt: ?, i: number) -> ?, init?: ?) -> !0.!ret", - "!effects": [ - "call !0 !1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce", - "!doc": "Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value." - }, - "reduceRight": { - "!type": "fn(combine: fn(sum: ?, elt: ?, i: number) -> ?, init?: ?) -> !0.!ret", - "!effects": [ - "call !0 !1 !this. number" - ], - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/ReduceRight", - "!doc": "Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array", - "!doc": "The JavaScript Array global object is a constructor for arrays, which are high-level, list-like objects." - }, - "String": { - "!type": "fn(value: ?) -> string", - "fromCharCode": { - "!type": "fn(code: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode", - "!doc": "Returns a string created by using the specified sequence of Unicode values." - }, - "prototype": { - "!stdProto": "String", - "length": { - "!type": "number", - "!url": "https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/String/length", - "!doc": "Represents the length of a string." - }, - "": "string", - "charAt": { - "!type": "fn(i: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/charAt", - "!doc": "Returns the specified character from a string." - }, - "charCodeAt": { - "!type": "fn(i: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt", - "!doc": "Returns the numeric Unicode value of the character at the given index (except for unicode codepoints > 0x10000)." - }, - "indexOf": { - "!type": "fn(char: string, from?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf", - "!doc": "Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,\nreturns -1 if the value is not found." - }, - "lastIndexOf": { - "!type": "fn(char: string, from?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf", - "!doc": "Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. The calling string is searched backward, starting at fromIndex." - }, - "substring": { - "!type": "fn(from: number, to?: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring", - "!doc": "Returns a subset of a string between one index and another, or through the end of the string." - }, - "substr": { - "!type": "fn(from: number, length?: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substr", - "!doc": "Returns the characters in a string beginning at the specified location through the specified number of characters." - }, - "slice": { - "!type": "fn(from: number, to?: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/slice", - "!doc": "Extracts a section of a string and returns a new string." - }, - "trim": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim", - "!doc": "Removes whitespace from both ends of the string." - }, - "toUpperCase": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase", - "!doc": "Returns the calling string value converted to uppercase." - }, - "toLowerCase": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase", - "!doc": "Returns the calling string value converted to lowercase." - }, - "toLocaleUpperCase": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase", - "!doc": "Returns the calling string value converted to upper case, according to any locale-specific case mappings." - }, - "toLocaleLowerCase": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase", - "!doc": "Returns the calling string value converted to lower case, according to any locale-specific case mappings." - }, - "split": { - "!type": "fn(pattern: string) -> [string]", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split", - "!doc": "Splits a String object into an array of strings by separating the string into substrings." - }, - "concat": { - "!type": "fn(other: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/concat", - "!doc": "Combines the text of two or more strings and returns a new string." - }, - "localeCompare": { - "!type": "fn(other: string) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare", - "!doc": "Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order." - }, - "match": { - "!type": "fn(pattern: +RegExp) -> [string]", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match", - "!doc": "Used to retrieve the matches when matching a string against a regular expression." - }, - "replace": { - "!type": "fn(pattern: +RegExp, replacement: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace", - "!doc": "Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match." - }, - "search": { - "!type": "fn(pattern: +RegExp) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/search", - "!doc": "Executes the search for a match between a regular expression and this String object." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String", - "!doc": "The String global object is a constructor for strings, or a sequence of characters." - }, - "Number": { - "!type": "fn(value: ?) -> number", - "MAX_VALUE": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/MAX_VALUE", - "!doc": "The maximum numeric value representable in JavaScript." - }, - "MIN_VALUE": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/MIN_VALUE", - "!doc": "The smallest positive numeric value representable in JavaScript." - }, - "POSITIVE_INFINITY": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY", - "!doc": "A value representing the positive Infinity value." - }, - "NEGATIVE_INFINITY": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY", - "!doc": "A value representing the negative Infinity value." - }, - "prototype": { - "!stdProto": "Number", - "toString": { - "!type": "fn(radix?: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString", - "!doc": "Returns a string representing the specified Number object" - }, - "toFixed": { - "!type": "fn(digits: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed", - "!doc": "Formats a number using fixed-point notation" - }, - "toExponential": { - "!type": "fn(digits: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toExponential", - "!doc": "Returns a string representing the Number object in exponential notation" - }, - "toPrecision": { - "!type": "fn(digits: number) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toPrecision", - "!doc": "The toPrecision() method returns a string representing the number to the specified precision." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number", - "!doc": "The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor." - }, - "Boolean": { - "!type": "fn(value: ?) -> bool", - "prototype": { - "!stdProto": "Boolean" - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean", - "!doc": "The Boolean object is an object wrapper for a boolean value." - }, - "RegExp": { - "!type": "fn(source: string, flags?: string)", - "prototype": { - "!stdProto": "RegExp", - "exec": { - "!type": "fn(input: string) -> [string]", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec", - "!doc": "Executes a search for a match in a specified string. Returns a result array, or null." - }, - "test": { - "!type": "fn(input: string) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test", - "!doc": "Executes the search for a match between a regular expression and a specified string. Returns true or false." - }, - "global": { - "!type": "bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp", - "!doc": "Creates a regular expression object for matching text with a pattern." - }, - "ignoreCase": { - "!type": "bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp", - "!doc": "Creates a regular expression object for matching text with a pattern." - }, - "multiline": { - "!type": "bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/multiline", - "!doc": "Reflects whether or not to search in strings across multiple lines.\n" - }, - "source": { - "!type": "string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/source", - "!doc": "A read-only property that contains the text of the pattern, excluding the forward slashes.\n" - }, - "lastIndex": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/lastIndex", - "!doc": "A read/write integer property that specifies the index at which to start the next match." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp", - "!doc": "Creates a regular expression object for matching text with a pattern." - }, - "Date": { - "!type": "fn(ms: number)", - "parse": { - "!type": "fn(source: string) -> +Date", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/parse", - "!doc": "Parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC." - }, - "UTC": { - "!type": "fn(year: number, month: number, date: number, hour?: number, min?: number, sec?: number, ms?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/UTC", - "!doc": "Accepts the same parameters as the longest form of the constructor, and returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time." - }, - "now": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now", - "!doc": "Returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC." - }, - "prototype": { - "toUTCString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toUTCString", - "!doc": "Converts a date to a string, using the universal time convention." - }, - "toISOString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString", - "!doc": "JavaScript provides a direct way to convert a date object into a string in ISO format, the ISO 8601 Extended Format." - }, - "toDateString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toDateString", - "!doc": "Returns the date portion of a Date object in human readable form in American English." - }, - "toTimeString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toTimeString", - "!doc": "Returns the time portion of a Date object in human readable form in American English." - }, - "toLocaleDateString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString", - "!doc": "Converts a date to a string, returning the \"date\" portion using the operating system's locale's conventions.\n" - }, - "toLocaleTimeString": { - "!type": "fn() -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString", - "!doc": "Converts a date to a string, returning the \"time\" portion using the current locale's conventions." - }, - "getTime": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime", - "!doc": "Returns the numeric value corresponding to the time for the specified date according to universal time." - }, - "getFullYear": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getFullYear", - "!doc": "Returns the year of the specified date according to local time." - }, - "getYear": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getYear", - "!doc": "Returns the year in the specified date according to local time." - }, - "getMonth": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMonth", - "!doc": "Returns the month in the specified date according to local time." - }, - "getUTCMonth": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCMonth", - "!doc": "Returns the month of the specified date according to universal time.\n" - }, - "getDate": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDate", - "!doc": "Returns the day of the month for the specified date according to local time." - }, - "getUTCDate": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCDate", - "!doc": "Returns the day (date) of the month in the specified date according to universal time.\n" - }, - "getDay": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay", - "!doc": "Returns the day of the week for the specified date according to local time." - }, - "getUTCDay": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCDay", - "!doc": "Returns the day of the week in the specified date according to universal time.\n" - }, - "getHours": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getHours", - "!doc": "Returns the hour for the specified date according to local time." - }, - "getUTCHours": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCHours", - "!doc": "Returns the hours in the specified date according to universal time.\n" - }, - "getMinutes": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMinutes", - "!doc": "Returns the minutes in the specified date according to local time." - }, - "getUTCMinutes": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date", - "!doc": "Creates JavaScript Date instances which let you work with dates and times." - }, - "getSeconds": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getSeconds", - "!doc": "Returns the seconds in the specified date according to local time." - }, - "getUTCSeconds": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCSeconds", - "!doc": "Returns the seconds in the specified date according to universal time.\n" - }, - "getMilliseconds": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMilliseconds", - "!doc": "Returns the milliseconds in the specified date according to local time." - }, - "getUTCMilliseconds": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds", - "!doc": "Returns the milliseconds in the specified date according to universal time.\n" - }, - "getTimezoneOffset": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset", - "!doc": "Returns the time-zone offset from UTC, in minutes, for the current locale." - }, - "setTime": { - "!type": "fn(date: +Date) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime", - "!doc": "Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.\n" - }, - "setFullYear": { - "!type": "fn(year: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setFullYear", - "!doc": "Sets the full year for a specified date according to local time.\n" - }, - "setUTCFullYear": { - "!type": "fn(year: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCFullYear", - "!doc": "Sets the full year for a specified date according to universal time.\n" - }, - "setMonth": { - "!type": "fn(month: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setMonth", - "!doc": "Set the month for a specified date according to local time." - }, - "setUTCMonth": { - "!type": "fn(month: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCMonth", - "!doc": "Sets the month for a specified date according to universal time.\n" - }, - "setDate": { - "!type": "fn(day: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setDate", - "!doc": "Sets the day of the month for a specified date according to local time." - }, - "setUTCDate": { - "!type": "fn(day: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCDate", - "!doc": "Sets the day of the month for a specified date according to universal time.\n" - }, - "setHours": { - "!type": "fn(hour: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setHours", - "!doc": "Sets the hours for a specified date according to local time, and returns the number of milliseconds since 1 January 1970 00:00:00 UTC until the time represented by the updated Date instance." - }, - "setUTCHours": { - "!type": "fn(hour: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCHours", - "!doc": "Sets the hour for a specified date according to universal time.\n" - }, - "setMinutes": { - "!type": "fn(min: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setMinutes", - "!doc": "Sets the minutes for a specified date according to local time." - }, - "setUTCMinutes": { - "!type": "fn(min: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCMinutes", - "!doc": "Sets the minutes for a specified date according to universal time.\n" - }, - "setSeconds": { - "!type": "fn(sec: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setSeconds", - "!doc": "Sets the seconds for a specified date according to local time." - }, - "setUTCSeconds": { - "!type": "fn(sec: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCSeconds", - "!doc": "Sets the seconds for a specified date according to universal time.\n" - }, - "setMilliseconds": { - "!type": "fn(ms: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setMilliseconds", - "!doc": "Sets the milliseconds for a specified date according to local time.\n" - }, - "setUTCMilliseconds": { - "!type": "fn(ms: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds", - "!doc": "Sets the milliseconds for a specified date according to universal time.\n" - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date", - "!doc": "Creates JavaScript Date instances which let you work with dates and times." - }, - "Error": { - "!type": "fn(message: string)", - "prototype": { - "name": { - "!type": "string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error/name", - "!doc": "A name for the type of error." - }, - "message": { - "!type": "string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error/message", - "!doc": "A human-readable description of the error." - } - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error", - "!doc": "Creates an error object." - }, - "SyntaxError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/SyntaxError", - "!doc": "Represents an error when trying to interpret syntactically invalid code." - }, - "ReferenceError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError", - "!doc": "Represents an error when a non-existent variable is referenced." - }, - "URIError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/URIError", - "!doc": "Represents an error when a malformed URI is encountered." - }, - "EvalError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/EvalError", - "!doc": "Represents an error regarding the eval function." - }, - "RangeError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RangeError", - "!doc": "Represents an error when a number is not within the correct range allowed." - }, - "TypeError": { - "!type": "fn(message: string)", - "prototype": "Error.prototype", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/TypeError", - "!doc": "Represents an error an error when a value is not of the expected type." - }, - "parseInt": { - "!type": "fn(string: string, radix?: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt", - "!doc": "Parses a string argument and returns an integer of the specified radix or base." - }, - "parseFloat": { - "!type": "fn(string: string) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat", - "!doc": "Parses a string argument and returns a floating point number." - }, - "isNaN": { - "!type": "fn(value: number) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN", - "!doc": "Determines whether a value is NaN or not. Be careful, this function is broken. You may be interested in ECMAScript 6 Number.isNaN." - }, - "isFinite": { - "!type": "fn(value: number) -> bool", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isFinite", - "!doc": "Determines whether the passed value is a finite number." - }, - "eval": { - "!type": "fn(code: string) -> ?", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval", - "!doc": "Evaluates JavaScript code represented as a string." - }, - "encodeURI": { - "!type": "fn(uri: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI", - "!doc": "Encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two \"surrogate\" characters)." - }, - "encodeURIComponent": { - "!type": "fn(uri: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent", - "!doc": "Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two \"surrogate\" characters)." - }, - "decodeURI": { - "!type": "fn(uri: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/decodeURI", - "!doc": "Decodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routine." - }, - "decodeURIComponent": { - "!type": "fn(uri: string) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/decodeURIComponent", - "!doc": "Decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine." - }, - "Math": { - "E": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/E", - "!doc": "The base of natural logarithms, e, approximately 2.718." - }, - "LN2": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/LN2", - "!doc": "The natural logarithm of 2, approximately 0.693." - }, - "LN10": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/LN10", - "!doc": "The natural logarithm of 10, approximately 2.302." - }, - "LOG2E": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/LOG2E", - "!doc": "The base 2 logarithm of E (approximately 1.442)." - }, - "LOG10E": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/LOG10E", - "!doc": "The base 10 logarithm of E (approximately 0.434)." - }, - "SQRT1_2": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/SQRT1_2", - "!doc": "The square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707." - }, - "SQRT2": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/SQRT2", - "!doc": "The square root of 2, approximately 1.414." - }, - "PI": { - "!type": "number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/PI", - "!doc": "The ratio of the circumference of a circle to its diameter, approximately 3.14159." - }, - "abs": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/abs", - "!doc": "Returns the absolute value of a number." - }, - "cos": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/cos", - "!doc": "Returns the cosine of a number." - }, - "sin": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/sin", - "!doc": "Returns the sine of a number." - }, - "tan": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/tan", - "!doc": "Returns the tangent of a number." - }, - "acos": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/acos", - "!doc": "Returns the arccosine (in radians) of a number." - }, - "asin": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/asin", - "!doc": "Returns the arcsine (in radians) of a number." - }, - "atan": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/atan", - "!doc": "Returns the arctangent (in radians) of a number." - }, - "atan2": { - "!type": "fn(y: number, x: number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/atan2", - "!doc": "Returns the arctangent of the quotient of its arguments." - }, - "ceil": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/ceil", - "!doc": "Returns the smallest integer greater than or equal to a number." - }, - "floor": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/floor", - "!doc": "Returns the largest integer less than or equal to a number." - }, - "round": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/round", - "!doc": "Returns the value of a number rounded to the nearest integer." - }, - "exp": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/exp", - "!doc": "Returns Ex, where x is the argument, and E is Euler's constant, the base of the natural logarithms." - }, - "log": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/log", - "!doc": "Returns the natural logarithm (base E) of a number." - }, - "sqrt": { - "!type": "fn(number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/sqrt", - "!doc": "Returns the square root of a number." - }, - "pow": { - "!type": "fn(number, number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/pow", - "!doc": "Returns base to the exponent power, that is, baseexponent." - }, - "max": { - "!type": "fn(number, number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/max", - "!doc": "Returns the largest of zero or more numbers." - }, - "min": { - "!type": "fn(number, number) -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/min", - "!doc": "Returns the smallest of zero or more numbers." - }, - "random": { - "!type": "fn() -> number", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random", - "!doc": "Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range." - }, - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math", - "!doc": "A built-in object that has properties and methods for mathematical constants and functions." - }, - "JSON": { - "parse": { - "!type": "fn(json: string) -> ?", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse", - "!doc": "Parse a string as JSON, optionally transforming the value produced by parsing." - }, - "stringify": { - "!type": "fn(value: ?) -> string", - "!url": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify", - "!doc": "Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified." - }, - "!url": "https://developer.mozilla.org/en-US/docs/JSON", - "!doc": "JSON (JavaScript Object Notation) is a data-interchange format. It closely resembles a subset of JavaScript syntax, although it is not a strict subset. (See JSON in the JavaScript Reference for full details.) It is useful when writing any kind of JavaScript-based application, including websites and browser extensions. For example, you might store user information in JSON format in a cookie, or you might store extension preferences in JSON in a string-valued browser preference." - } -} -} diff --git a/mix/qml/html/cm/errorannotation.js b/mix/qml/html/cm/errorannotation.js deleted file mode 100644 index 33837ed37..000000000 --- a/mix/qml/html/cm/errorannotation.js +++ /dev/null @@ -1,46 +0,0 @@ -function ErrorAnnotation(editor, location, content) -{ - this.location = location; - this.opened = false; - this.rawContent = content; - this.content = content.replace("Contract Error:", ""); - this.editor = editor; - this.errorMark = null; - this.lineWidget = null; - this.init(); - if (this.content) - this.open(); -} - -ErrorAnnotation.prototype.init = function() -{ - this.errorMark = editor.markText({ line: this.location.start.line, ch: this.location.start.column }, { line: this.location.end.line, ch: this.location.end.column }, { className: "CodeMirror-errorannotation", inclusiveRight: true }); -} - -ErrorAnnotation.prototype.open = function() -{ - if (this.location.start.line) - { - var node = document.createElement("div"); - node.id = "annotation" - node.innerHTML = this.content; - node.className = "CodeMirror-errorannotation-context"; - this.lineWidget = this.editor.addLineWidget(this.location.start.line, node, { coverGutter: false }); - this.opened = true; - } -} - -ErrorAnnotation.prototype.close = function() -{ - if (this.lineWidget) - this.lineWidget.clear(); - this.opened = false; -} - -ErrorAnnotation.prototype.destroy = function() -{ - if (this.opened) - this.close(); - if (this.errorMark) - this.errorMark.clear(); -} diff --git a/mix/qml/html/cm/fullscreen.css b/mix/qml/html/cm/fullscreen.css deleted file mode 100644 index 437acd89b..000000000 --- a/mix/qml/html/cm/fullscreen.css +++ /dev/null @@ -1,6 +0,0 @@ -.CodeMirror-fullscreen { - position: fixed; - top: 0; left: 0; right: 0; bottom: 0; - height: auto; - z-index: 9; -} diff --git a/mix/qml/html/cm/fullscreen.js b/mix/qml/html/cm/fullscreen.js deleted file mode 100644 index cd3673b96..000000000 --- a/mix/qml/html/cm/fullscreen.js +++ /dev/null @@ -1,41 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { - if (old == CodeMirror.Init) old = false; - if (!old == !val) return; - if (val) setFullscreen(cm); - else setNormal(cm); - }); - - function setFullscreen(cm) { - var wrap = cm.getWrapperElement(); - cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, - width: wrap.style.width, height: wrap.style.height}; - wrap.style.width = ""; - wrap.style.height = "auto"; - wrap.className += " CodeMirror-fullscreen"; - document.documentElement.style.overflow = "hidden"; - cm.refresh(); - } - - function setNormal(cm) { - var wrap = cm.getWrapperElement(); - wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); - document.documentElement.style.overflow = ""; - var info = cm.state.fullScreenRestore; - wrap.style.width = info.width; wrap.style.height = info.height; - window.scrollTo(info.scrollLeft, info.scrollTop); - cm.refresh(); - } -}); diff --git a/mix/qml/html/cm/htmlmixed.js b/mix/qml/html/cm/htmlmixed.js deleted file mode 100644 index 1cc438f01..000000000 --- a/mix/qml/html/cm/htmlmixed.js +++ /dev/null @@ -1,121 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { - var htmlMode = CodeMirror.getMode(config, {name: "xml", - htmlMode: true, - multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, - multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag}); - var cssMode = CodeMirror.getMode(config, "css"); - - var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes; - scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, - mode: CodeMirror.getMode(config, "javascript")}); - if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) { - var conf = scriptTypesConf[i]; - scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)}); - } - scriptTypes.push({matches: /./, - mode: CodeMirror.getMode(config, "text/plain")}); - - function html(stream, state) { - var tagName = state.htmlState.tagName; - if (tagName) tagName = tagName.toLowerCase(); - var style = htmlMode.token(stream, state.htmlState); - if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") { - // Script block: mode to change to depends on type attribute - var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i); - scriptType = scriptType ? scriptType[1] : ""; - if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1); - for (var i = 0; i < scriptTypes.length; ++i) { - var tp = scriptTypes[i]; - if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) { - if (tp.mode) { - state.token = script; - state.localMode = tp.mode; - state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, "")); - } - break; - } - } - } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") { - state.token = css; - state.localMode = cssMode; - state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); - } - return style; - } - function maybeBackup(stream, pat, style) { - var cur = stream.current(); - var close = cur.search(pat), m; - if (close > -1) stream.backUp(cur.length - close); - else if (m = cur.match(/<\/?$/)) { - stream.backUp(cur.length); - if (!stream.match(pat, false)) stream.match(cur); - } - return style; - } - function script(stream, state) { - if (stream.match(/^<\/\s*script\s*>/i, false)) { - state.token = html; - state.localState = state.localMode = null; - return null; - } - return maybeBackup(stream, /<\/\s*script\s*>/, - state.localMode.token(stream, state.localState)); - } - function css(stream, state) { - if (stream.match(/^<\/\s*style\s*>/i, false)) { - state.token = html; - state.localState = state.localMode = null; - return null; - } - return maybeBackup(stream, /<\/\s*style\s*>/, - cssMode.token(stream, state.localState)); - } - - return { - startState: function() { - var state = htmlMode.startState(); - return {token: html, localMode: null, localState: null, htmlState: state}; - }, - - copyState: function(state) { - if (state.localState) - var local = CodeMirror.copyState(state.localMode, state.localState); - return {token: state.token, localMode: state.localMode, localState: local, - htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; - }, - - token: function(stream, state) { - return state.token(stream, state); - }, - - indent: function(state, textAfter) { - if (!state.localMode || /^\s*<\//.test(textAfter)) - return htmlMode.indent(state.htmlState, textAfter); - else if (state.localMode.indent) - return state.localMode.indent(state.localState, textAfter); - else - return CodeMirror.Pass; - }, - - innerMode: function(state) { - return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; - } - }; -}, "xml", "javascript", "css"); - -CodeMirror.defineMIME("text/html", "htmlmixed"); - -}); diff --git a/mix/qml/html/cm/infer.js b/mix/qml/html/cm/infer.js deleted file mode 100644 index a29832d38..000000000 --- a/mix/qml/html/cm/infer.js +++ /dev/null @@ -1,1615 +0,0 @@ -// Main type inference engine - -// Walks an AST, building up a graph of abstract values and constraints -// that cause types to flow from one node to another. Also defines a -// number of utilities for accessing ASTs and scopes. - -// Analysis is done in a context, which is tracked by the dynamically -// bound cx variable. Use withContext to set the current context. - -// For memory-saving reasons, individual types export an interface -// similar to abstract values (which can hold multiple types), and can -// thus be used in place abstract values that only ever contain a -// single type. - -(function(root, mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - return mod(exports, require("acorn/acorn"), require("acorn/acorn_loose"), require("acorn/util/walk"), - require("./def"), require("./signal")); - if (typeof define == "function" && define.amd) // AMD - return define(["exports", "acorn/acorn", "acorn/acorn_loose", "acorn/util/walk", "./def", "./signal"], mod); - mod(root.tern || (root.tern = {}), acorn, acorn, acorn.walk, tern.def, tern.signal); // Plain browser env -})(this, function(exports, acorn, acorn_loose, walk, def, signal) { - "use strict"; - - var toString = exports.toString = function(type, maxDepth, parent) { - return !type || type == parent ? "?": type.toString(maxDepth, parent); - }; - - // A variant of AVal used for unknown, dead-end values. Also serves - // as prototype for AVals, Types, and Constraints because it - // implements 'empty' versions of all the methods that the code - // expects. - var ANull = exports.ANull = signal.mixin({ - addType: function() {}, - propagate: function() {}, - getProp: function() { return ANull; }, - forAllProps: function() {}, - hasType: function() { return false; }, - isEmpty: function() { return true; }, - getFunctionType: function() {}, - getObjType: function() {}, - getType: function() {}, - gatherProperties: function() {}, - propagatesTo: function() {}, - typeHint: function() {}, - propHint: function() {}, - toString: function() { return "?"; } - }); - - function extend(proto, props) { - var obj = Object.create(proto); - if (props) for (var prop in props) obj[prop] = props[prop]; - return obj; - } - - // ABSTRACT VALUES - - var WG_DEFAULT = 100, WG_NEW_INSTANCE = 90, WG_MADEUP_PROTO = 10, WG_MULTI_MEMBER = 5, - WG_CATCH_ERROR = 5, WG_GLOBAL_THIS = 90, WG_SPECULATIVE_THIS = 2; - - var AVal = exports.AVal = function() { - this.types = []; - this.forward = null; - this.maxWeight = 0; - }; - AVal.prototype = extend(ANull, { - addType: function(type, weight) { - weight = weight || WG_DEFAULT; - if (this.maxWeight < weight) { - this.maxWeight = weight; - if (this.types.length == 1 && this.types[0] == type) return; - this.types.length = 0; - } else if (this.maxWeight > weight || this.types.indexOf(type) > -1) { - return; - } - - this.signal("addType", type); - this.types.push(type); - var forward = this.forward; - if (forward) withWorklist(function(add) { - for (var i = 0; i < forward.length; ++i) add(type, forward[i], weight); - }); - }, - - propagate: function(target, weight) { - if (target == ANull || (target instanceof Type)) return; - if (weight && weight != WG_DEFAULT) target = new Muffle(target, weight); - (this.forward || (this.forward = [])).push(target); - var types = this.types; - if (types.length) withWorklist(function(add) { - for (var i = 0; i < types.length; ++i) add(types[i], target, weight); - }); - }, - - getProp: function(prop) { - if (prop == "__proto__" || prop == "✖") return ANull; - var found = (this.props || (this.props = Object.create(null)))[prop]; - if (!found) { - found = this.props[prop] = new AVal; - this.propagate(new PropIsSubset(prop, found)); - } - return found; - }, - - forAllProps: function(c) { - this.propagate(new ForAllProps(c)); - }, - - hasType: function(type) { - return this.types.indexOf(type) > -1; - }, - isEmpty: function() { return this.types.length === 0; }, - getFunctionType: function() { - for (var i = this.types.length - 1; i >= 0; --i) - if (this.types[i] instanceof Fn) return this.types[i]; - }, - getObjType: function() { - var seen = null; - for (var i = this.types.length - 1; i >= 0; --i) { - var type = this.types[i]; - if (!(type instanceof Obj)) continue; - if (type.name) return type; - if (!seen) seen = type; - } - return seen; - }, - - getType: function(guess) { - if (this.types.length === 0 && guess !== false) return this.makeupType(); - if (this.types.length === 1) return this.types[0]; - return canonicalType(this.types); - }, - - toString: function(maxDepth, parent) { - if (this.types.length == 0) return toString(this.makeupType(), maxDepth, parent); - if (this.types.length == 1) return toString(this.types[0], maxDepth, parent); - var simplified = simplifyTypes(this.types); - if (simplified.length > 2) return "?"; - return simplified.map(function(tp) { return toString(tp, maxDepth, parent); }).join("|"); - }, - - computedPropType: function() { - if (!this.propertyOf || !this.propertyOf.hasProp("")) return null; - var computedProp = this.propertyOf.getProp(""); - if (computedProp == this) return null; - return computedProp.getType(); - }, - - makeupType: function() { - var computed = this.computedPropType(); - if (computed) return computed; - - if (!this.forward) return null; - for (var i = this.forward.length - 1; i >= 0; --i) { - var hint = this.forward[i].typeHint(); - if (hint && !hint.isEmpty()) {guessing = true; return hint;} - } - - var props = Object.create(null), foundProp = null; - for (var i = 0; i < this.forward.length; ++i) { - var prop = this.forward[i].propHint(); - if (prop && prop != "length" && prop != "" && prop != "✖" && prop != cx.completingProperty) { - props[prop] = true; - foundProp = prop; - } - } - if (!foundProp) return null; - - var objs = objsWithProp(foundProp); - if (objs) { - var matches = []; - search: for (var i = 0; i < objs.length; ++i) { - var obj = objs[i]; - for (var prop in props) if (!obj.hasProp(prop)) continue search; - if (obj.hasCtor) obj = getInstance(obj); - matches.push(obj); - } - var canon = canonicalType(matches); - if (canon) {guessing = true; return canon;} - } - }, - - typeHint: function() { return this.types.length ? this.getType() : null; }, - propagatesTo: function() { return this; }, - - gatherProperties: function(f, depth) { - for (var i = 0; i < this.types.length; ++i) - this.types[i].gatherProperties(f, depth); - }, - - guessProperties: function(f) { - if (this.forward) for (var i = 0; i < this.forward.length; ++i) { - var prop = this.forward[i].propHint(); - if (prop) f(prop, null, 0); - } - var guessed = this.makeupType(); - if (guessed) guessed.gatherProperties(f); - } - }); - - function similarAVal(a, b, depth) { - var typeA = a.getType(false), typeB = b.getType(false); - if (!typeA || !typeB) return true; - return similarType(typeA, typeB, depth); - } - - function similarType(a, b, depth) { - if (!a || depth >= 5) return b; - if (!a || a == b) return a; - if (!b) return a; - if (a.constructor != b.constructor) return false; - if (a.constructor == Arr) { - var innerA = a.getProp("").getType(false); - if (!innerA) return b; - var innerB = b.getProp("").getType(false); - if (!innerB || similarType(innerA, innerB, depth + 1)) return b; - } else if (a.constructor == Obj) { - var propsA = 0, propsB = 0, same = 0; - for (var prop in a.props) { - propsA++; - if (prop in b.props && similarAVal(a.props[prop], b.props[prop], depth + 1)) - same++; - } - for (var prop in b.props) propsB++; - if (propsA && propsB && same < Math.max(propsA, propsB) / 2) return false; - return propsA > propsB ? a : b; - } else if (a.constructor == Fn) { - if (a.args.length != b.args.length || - !a.args.every(function(tp, i) { return similarAVal(tp, b.args[i], depth + 1); }) || - !similarAVal(a.retval, b.retval, depth + 1) || !similarAVal(a.self, b.self, depth + 1)) - return false; - return a; - } else { - return false; - } - } - - var simplifyTypes = exports.simplifyTypes = function(types) { - var found = []; - outer: for (var i = 0; i < types.length; ++i) { - var tp = types[i]; - for (var j = 0; j < found.length; j++) { - var similar = similarType(tp, found[j], 0); - if (similar) { - found[j] = similar; - continue outer; - } - } - found.push(tp); - } - return found; - }; - - function canonicalType(types) { - var arrays = 0, fns = 0, objs = 0, prim = null; - for (var i = 0; i < types.length; ++i) { - var tp = types[i]; - if (tp instanceof Arr) ++arrays; - else if (tp instanceof Fn) ++fns; - else if (tp instanceof Obj) ++objs; - else if (tp instanceof Prim) { - if (prim && tp.name != prim.name) return null; - prim = tp; - } - } - var kinds = (arrays && 1) + (fns && 1) + (objs && 1) + (prim && 1); - if (kinds > 1) return null; - if (prim) return prim; - - var maxScore = 0, maxTp = null; - for (var i = 0; i < types.length; ++i) { - var tp = types[i], score = 0; - if (arrays) { - score = tp.getProp("").isEmpty() ? 1 : 2; - } else if (fns) { - score = 1; - for (var j = 0; j < tp.args.length; ++j) if (!tp.args[j].isEmpty()) ++score; - if (!tp.retval.isEmpty()) ++score; - } else if (objs) { - score = tp.name ? 100 : 2; - } - if (score >= maxScore) { maxScore = score; maxTp = tp; } - } - return maxTp; - } - - // PROPAGATION STRATEGIES - - function Constraint() {} - Constraint.prototype = extend(ANull, { - init: function() { this.origin = cx.curOrigin; } - }); - - var constraint = exports.constraint = function(props, methods) { - var body = "this.init();"; - props = props ? props.split(", ") : []; - for (var i = 0; i < props.length; ++i) - body += "this." + props[i] + " = " + props[i] + ";"; - var ctor = Function.apply(null, props.concat([body])); - ctor.prototype = Object.create(Constraint.prototype); - for (var m in methods) if (methods.hasOwnProperty(m)) ctor.prototype[m] = methods[m]; - return ctor; - }; - - var PropIsSubset = constraint("prop, target", { - addType: function(type, weight) { - if (type.getProp) - type.getProp(this.prop).propagate(this.target, weight); - }, - propHint: function() { return this.prop; }, - propagatesTo: function() { - if (this.prop == "" || !/[^\w_]/.test(this.prop)) - return {target: this.target, pathExt: "." + this.prop}; - } - }); - - var PropHasSubset = exports.PropHasSubset = constraint("prop, type, originNode", { - addType: function(type, weight) { - if (!(type instanceof Obj)) return; - var prop = type.defProp(this.prop, this.originNode); - prop.origin = this.origin; - this.type.propagate(prop, weight); - }, - propHint: function() { return this.prop; } - }); - - var ForAllProps = constraint("c", { - addType: function(type) { - if (!(type instanceof Obj)) return; - type.forAllProps(this.c); - } - }); - - function withDisabledComputing(fn, body) { - cx.disabledComputing = {fn: fn, prev: cx.disabledComputing}; - try { - return body(); - } finally { - cx.disabledComputing = cx.disabledComputing.prev; - } - } - var IsCallee = exports.IsCallee = constraint("self, args, argNodes, retval", { - init: function() { - Constraint.prototype.init.call(this); - this.disabled = cx.disabledComputing; - }, - addType: function(fn, weight) { - if (!(fn instanceof Fn)) return; - for (var i = 0; i < this.args.length; ++i) { - if (i < fn.args.length) this.args[i].propagate(fn.args[i], weight); - if (fn.arguments) this.args[i].propagate(fn.arguments, weight); - } - this.self.propagate(fn.self, this.self == cx.topScope ? WG_GLOBAL_THIS : weight); - var compute = fn.computeRet; - if (compute) for (var d = this.disabled; d; d = d.prev) - if (d.fn == fn || fn.originNode && d.fn.originNode == fn.originNode) compute = null; - if (compute) - compute(this.self, this.args, this.argNodes).propagate(this.retval, weight); - else - fn.retval.propagate(this.retval, weight); - }, - typeHint: function() { - var names = []; - for (var i = 0; i < this.args.length; ++i) names.push("?"); - return new Fn(null, this.self, this.args, names, ANull); - }, - propagatesTo: function() { - return {target: this.retval, pathExt: ".!ret"}; - } - }); - - var HasMethodCall = constraint("propName, args, argNodes, retval", { - init: function() { - Constraint.prototype.init.call(this); - this.disabled = cx.disabledComputing; - }, - addType: function(obj, weight) { - var callee = new IsCallee(obj, this.args, this.argNodes, this.retval); - callee.disabled = this.disabled; - obj.getProp(this.propName).propagate(callee, weight); - }, - propHint: function() { return this.propName; } - }); - - var IsCtor = exports.IsCtor = constraint("target, noReuse", { - addType: function(f, weight) { - if (!(f instanceof Fn)) return; - if (cx.parent && !cx.parent.options.reuseInstances) this.noReuse = true; - f.getProp("prototype").propagate(new IsProto(this.noReuse ? false : f, this.target), weight); - } - }); - - var getInstance = exports.getInstance = function(obj, ctor) { - if (ctor === false) return new Obj(obj); - - if (!ctor) ctor = obj.hasCtor; - if (!obj.instances) obj.instances = []; - for (var i = 0; i < obj.instances.length; ++i) { - var cur = obj.instances[i]; - if (cur.ctor == ctor) return cur.instance; - } - var instance = new Obj(obj, ctor && ctor.name); - instance.origin = obj.origin; - obj.instances.push({ctor: ctor, instance: instance}); - return instance; - }; - - var IsProto = exports.IsProto = constraint("ctor, target", { - addType: function(o, _weight) { - if (!(o instanceof Obj)) return; - if ((this.count = (this.count || 0) + 1) > 8) return; - if (o == cx.protos.Array) - this.target.addType(new Arr); - else - this.target.addType(getInstance(o, this.ctor)); - } - }); - - var FnPrototype = constraint("fn", { - addType: function(o, _weight) { - if (o instanceof Obj && !o.hasCtor) { - o.hasCtor = this.fn; - var adder = new SpeculativeThis(o, this.fn); - adder.addType(this.fn); - o.forAllProps(function(_prop, val, local) { - if (local) val.propagate(adder); - }); - } - } - }); - - var IsAdded = constraint("other, target", { - addType: function(type, weight) { - if (type == cx.str) - this.target.addType(cx.str, weight); - else if (type == cx.num && this.other.hasType(cx.num)) - this.target.addType(cx.num, weight); - }, - typeHint: function() { return this.other; } - }); - - var IfObj = exports.IfObj = constraint("target", { - addType: function(t, weight) { - if (t instanceof Obj) this.target.addType(t, weight); - }, - propagatesTo: function() { return this.target; } - }); - - var SpeculativeThis = constraint("obj, ctor", { - addType: function(tp) { - if (tp instanceof Fn && tp.self && tp.self.isEmpty()) - tp.self.addType(getInstance(this.obj, this.ctor), WG_SPECULATIVE_THIS); - } - }); - - var Muffle = constraint("inner, weight", { - addType: function(tp, weight) { - this.inner.addType(tp, Math.min(weight, this.weight)); - }, - propagatesTo: function() { return this.inner.propagatesTo(); }, - typeHint: function() { return this.inner.typeHint(); }, - propHint: function() { return this.inner.propHint(); } - }); - - // TYPE OBJECTS - - var Type = exports.Type = function() {}; - Type.prototype = extend(ANull, { - constructor: Type, - propagate: function(c, w) { c.addType(this, w); }, - hasType: function(other) { return other == this; }, - isEmpty: function() { return false; }, - typeHint: function() { return this; }, - getType: function() { return this; } - }); - - var Prim = exports.Prim = function(proto, name) { this.name = name; this.proto = proto; }; - Prim.prototype = extend(Type.prototype, { - constructor: Prim, - toString: function() { return this.name; }, - getProp: function(prop) {return this.proto.hasProp(prop) || ANull;}, - gatherProperties: function(f, depth) { - if (this.proto) this.proto.gatherProperties(f, depth); - } - }); - - var Obj = exports.Obj = function(proto, name) { - if (!this.props) this.props = Object.create(null); - this.proto = proto === true ? cx.protos.Object : proto; - if (proto && !name && proto.name && !(this instanceof Fn)) { - var match = /^(.*)\.prototype$/.exec(this.proto.name); - if (match) name = match[1]; - } - this.name = name; - this.maybeProps = null; - this.origin = cx.curOrigin; - }; - Obj.prototype = extend(Type.prototype, { - constructor: Obj, - toString: function(maxDepth) { - if (!maxDepth && this.name) return this.name; - var props = [], etc = false; - for (var prop in this.props) if (prop != "") { - if (props.length > 5) { etc = true; break; } - if (maxDepth) - props.push(prop + ": " + toString(this.props[prop], maxDepth - 1)); - else - props.push(prop); - } - props.sort(); - if (etc) props.push("..."); - return "{" + props.join(", ") + "}"; - }, - hasProp: function(prop, searchProto) { - var found = this.props[prop]; - if (searchProto !== false) - for (var p = this.proto; p && !found; p = p.proto) found = p.props[prop]; - return found; - }, - defProp: function(prop, originNode) { - var found = this.hasProp(prop, false); - if (found) { - if (originNode && !found.originNode) found.originNode = originNode; - return found; - } - if (prop == "__proto__" || prop == "✖") return ANull; - - var av = this.maybeProps && this.maybeProps[prop]; - if (av) { - delete this.maybeProps[prop]; - this.maybeUnregProtoPropHandler(); - } else { - av = new AVal; - av.propertyOf = this; - } - - this.props[prop] = av; - av.originNode = originNode; - av.origin = cx.curOrigin; - this.broadcastProp(prop, av, true); - return av; - }, - getProp: function(prop) { - var found = this.hasProp(prop, true) || (this.maybeProps && this.maybeProps[prop]); - if (found) return found; - if (prop == "__proto__" || prop == "✖") return ANull; - var av = this.ensureMaybeProps()[prop] = new AVal; - av.propertyOf = this; - return av; - }, - broadcastProp: function(prop, val, local) { - if (local) { - this.signal("addProp", prop, val); - // If this is a scope, it shouldn't be registered - if (!(this instanceof Scope)) registerProp(prop, this); - } - - if (this.onNewProp) for (var i = 0; i < this.onNewProp.length; ++i) { - var h = this.onNewProp[i]; - h.onProtoProp ? h.onProtoProp(prop, val, local) : h(prop, val, local); - } - }, - onProtoProp: function(prop, val, _local) { - var maybe = this.maybeProps && this.maybeProps[prop]; - if (maybe) { - delete this.maybeProps[prop]; - this.maybeUnregProtoPropHandler(); - this.proto.getProp(prop).propagate(maybe); - } - this.broadcastProp(prop, val, false); - }, - ensureMaybeProps: function() { - if (!this.maybeProps) { - if (this.proto) this.proto.forAllProps(this); - this.maybeProps = Object.create(null); - } - return this.maybeProps; - }, - removeProp: function(prop) { - var av = this.props[prop]; - delete this.props[prop]; - this.ensureMaybeProps()[prop] = av; - av.types.length = 0; - }, - forAllProps: function(c) { - if (!this.onNewProp) { - this.onNewProp = []; - if (this.proto) this.proto.forAllProps(this); - } - this.onNewProp.push(c); - for (var o = this; o; o = o.proto) for (var prop in o.props) { - if (c.onProtoProp) - c.onProtoProp(prop, o.props[prop], o == this); - else - c(prop, o.props[prop], o == this); - } - }, - maybeUnregProtoPropHandler: function() { - if (this.maybeProps) { - for (var _n in this.maybeProps) return; - this.maybeProps = null; - } - if (!this.proto || this.onNewProp && this.onNewProp.length) return; - this.proto.unregPropHandler(this); - }, - unregPropHandler: function(handler) { - for (var i = 0; i < this.onNewProp.length; ++i) - if (this.onNewProp[i] == handler) { this.onNewProp.splice(i, 1); break; } - this.maybeUnregProtoPropHandler(); - }, - gatherProperties: function(f, depth) { - for (var prop in this.props) if (prop != "") - f(prop, this, depth); - if (this.proto) this.proto.gatherProperties(f, depth + 1); - }, - getObjType: function() { return this; } - }); - - var Fn = exports.Fn = function(name, self, args, argNames, retval) { - Obj.call(this, cx.protos.Function, name); - this.self = self; - this.args = args; - this.argNames = argNames; - this.retval = retval; - }; - Fn.prototype = extend(Obj.prototype, { - constructor: Fn, - toString: function(maxDepth) { - if (maxDepth) maxDepth--; - var str = "fn("; - for (var i = 0; i < this.args.length; ++i) { - if (i) str += ", "; - var name = this.argNames[i]; - if (name && name != "?") str += name + ": "; - str += toString(this.args[i], maxDepth, this); - } - str += ")"; - if (!this.retval.isEmpty()) - str += " -> " + toString(this.retval, maxDepth, this); - return str; - }, - getProp: function(prop) { - if (prop == "prototype") { - var known = this.hasProp(prop, false); - if (!known) { - known = this.defProp(prop); - var proto = new Obj(true, this.name && this.name + ".prototype"); - proto.origin = this.origin; - known.addType(proto, WG_MADEUP_PROTO); - } - return known; - } - return Obj.prototype.getProp.call(this, prop); - }, - defProp: function(prop, originNode) { - if (prop == "prototype") { - var found = this.hasProp(prop, false); - if (found) return found; - found = Obj.prototype.defProp.call(this, prop, originNode); - found.origin = this.origin; - found.propagate(new FnPrototype(this)); - return found; - } - return Obj.prototype.defProp.call(this, prop, originNode); - }, - getFunctionType: function() { return this; } - }); - - var Arr = exports.Arr = function(contentType) { - Obj.call(this, cx.protos.Array); - var content = this.defProp(""); - if (contentType) contentType.propagate(content); - }; - Arr.prototype = extend(Obj.prototype, { - constructor: Arr, - toString: function(maxDepth) { - return "[" + toString(this.getProp(""), maxDepth, this) + "]"; - } - }); - - // THE PROPERTY REGISTRY - - function registerProp(prop, obj) { - var data = cx.props[prop] || (cx.props[prop] = []); - data.push(obj); - } - - function objsWithProp(prop) { - return cx.props[prop]; - } - - // INFERENCE CONTEXT - - exports.Context = function(defs, parent) { - this.parent = parent; - this.props = Object.create(null); - this.protos = Object.create(null); - this.origins = []; - this.curOrigin = "ecma5"; - this.paths = Object.create(null); - this.definitions = Object.create(null); - this.purgeGen = 0; - this.workList = null; - this.disabledComputing = null; - - exports.withContext(this, function() { - cx.protos.Object = new Obj(null, "Object.prototype"); - cx.topScope = new Scope(); - cx.topScope.name = ""; - cx.protos.Array = new Obj(true, "Array.prototype"); - cx.protos.Function = new Obj(true, "Function.prototype"); - cx.protos.RegExp = new Obj(true, "RegExp.prototype"); - cx.protos.String = new Obj(true, "String.prototype"); - cx.protos.Number = new Obj(true, "Number.prototype"); - cx.protos.Boolean = new Obj(true, "Boolean.prototype"); - cx.str = new Prim(cx.protos.String, "string"); - cx.bool = new Prim(cx.protos.Boolean, "bool"); - cx.num = new Prim(cx.protos.Number, "number"); - cx.curOrigin = null; - - if (defs) for (var i = 0; i < defs.length; ++i) - def.load(defs[i]); - }); - }; - - var cx = null; - exports.cx = function() { return cx; }; - - exports.withContext = function(context, f) { - var old = cx; - cx = context; - try { return f(); } - finally { cx = old; } - }; - - exports.TimedOut = function() { - this.message = "Timed out"; - this.stack = (new Error()).stack; - }; - exports.TimedOut.prototype = Object.create(Error.prototype); - exports.TimedOut.prototype.name = "infer.TimedOut"; - - var timeout; - exports.withTimeout = function(ms, f) { - var end = +new Date + ms; - var oldEnd = timeout; - if (oldEnd && oldEnd < end) return f(); - timeout = end; - try { return f(); } - finally { timeout = oldEnd; } - }; - - exports.addOrigin = function(origin) { - if (cx.origins.indexOf(origin) < 0) cx.origins.push(origin); - }; - - var baseMaxWorkDepth = 20, reduceMaxWorkDepth = 0.0001; - function withWorklist(f) { - if (cx.workList) return f(cx.workList); - - var list = [], depth = 0; - var add = cx.workList = function(type, target, weight) { - if (depth < baseMaxWorkDepth - reduceMaxWorkDepth * list.length) - list.push(type, target, weight, depth); - }; - try { - var ret = f(add); - for (var i = 0; i < list.length; i += 4) { - if (timeout && +new Date >= timeout) - throw new exports.TimedOut(); - depth = list[i + 3] + 1; - list[i + 1].addType(list[i], list[i + 2]); - } - return ret; - } finally { - cx.workList = null; - } - } - - // SCOPES - - var Scope = exports.Scope = function(prev) { - Obj.call(this, prev || true); - this.prev = prev; - }; - Scope.prototype = extend(Obj.prototype, { - constructor: Scope, - defVar: function(name, originNode) { - for (var s = this; ; s = s.proto) { - var found = s.props[name]; - if (found) return found; - if (!s.prev) return s.defProp(name, originNode); - } - } - }); - - // RETVAL COMPUTATION HEURISTICS - - function maybeInstantiate(scope, score) { - if (scope.fnType) - scope.fnType.instantiateScore = (scope.fnType.instantiateScore || 0) + score; - } - - var NotSmaller = {}; - function nodeSmallerThan(node, n) { - try { - walk.simple(node, {Expression: function() { if (--n <= 0) throw NotSmaller; }}); - return true; - } catch(e) { - if (e == NotSmaller) return false; - throw e; - } - } - - function maybeTagAsInstantiated(node, scope) { - var score = scope.fnType.instantiateScore; - if (!cx.disabledComputing && score && scope.fnType.args.length && nodeSmallerThan(node, score * 5)) { - maybeInstantiate(scope.prev, score / 2); - setFunctionInstantiated(node, scope); - return true; - } else { - scope.fnType.instantiateScore = null; - } - } - - function setFunctionInstantiated(node, scope) { - var fn = scope.fnType; - // Disconnect the arg avals, so that we can add info to them without side effects - for (var i = 0; i < fn.args.length; ++i) fn.args[i] = new AVal; - fn.self = new AVal; - fn.computeRet = function(self, args) { - // Prevent recursion - return withDisabledComputing(fn, function() { - var oldOrigin = cx.curOrigin; - cx.curOrigin = fn.origin; - var scopeCopy = new Scope(scope.prev); - scopeCopy.originNode = scope.originNode; - for (var v in scope.props) { - var local = scopeCopy.defProp(v, scope.props[v].originNode); - for (var i = 0; i < args.length; ++i) if (fn.argNames[i] == v && i < args.length) - args[i].propagate(local); - } - var argNames = fn.argNames.length != args.length ? fn.argNames.slice(0, args.length) : fn.argNames; - while (argNames.length < args.length) argNames.push("?"); - scopeCopy.fnType = new Fn(fn.name, self, args, argNames, ANull); - scopeCopy.fnType.originNode = fn.originNode; - if (fn.arguments) { - var argset = scopeCopy.fnType.arguments = new AVal; - scopeCopy.defProp("arguments").addType(new Arr(argset)); - for (var i = 0; i < args.length; ++i) args[i].propagate(argset); - } - node.body.scope = scopeCopy; - walk.recursive(node.body, scopeCopy, null, scopeGatherer); - walk.recursive(node.body, scopeCopy, null, inferWrapper); - cx.curOrigin = oldOrigin; - return scopeCopy.fnType.retval; - }); - }; - } - - function maybeTagAsGeneric(scope) { - var fn = scope.fnType, target = fn.retval; - if (target == ANull) return; - var targetInner, asArray; - if (!target.isEmpty() && (targetInner = target.getType()) instanceof Arr) - target = asArray = targetInner.getProp(""); - - function explore(aval, path, depth) { - if (depth > 3 || !aval.forward) return; - for (var i = 0; i < aval.forward.length; ++i) { - var prop = aval.forward[i].propagatesTo(); - if (!prop) continue; - var newPath = path, dest; - if (prop instanceof AVal) { - dest = prop; - } else if (prop.target instanceof AVal) { - newPath += prop.pathExt; - dest = prop.target; - } else continue; - if (dest == target) return newPath; - var found = explore(dest, newPath, depth + 1); - if (found) return found; - } - } - - var foundPath = explore(fn.self, "!this", 0); - for (var i = 0; !foundPath && i < fn.args.length; ++i) - foundPath = explore(fn.args[i], "!" + i, 0); - - if (foundPath) { - if (asArray) foundPath = "[" + foundPath + "]"; - var p = new def.TypeParser(foundPath); - fn.computeRet = p.parseRetType(); - fn.computeRetSource = foundPath; - return true; - } - } - - // SCOPE GATHERING PASS - - function addVar(scope, nameNode) { - return scope.defProp(nameNode.name, nameNode); - } - - var scopeGatherer = walk.make({ - Function: function(node, scope, c) { - var inner = node.body.scope = new Scope(scope); - inner.originNode = node; - var argVals = [], argNames = []; - for (var i = 0; i < node.params.length; ++i) { - var param = node.params[i]; - argNames.push(param.name); - argVals.push(addVar(inner, param)); - } - inner.fnType = new Fn(node.id && node.id.name, new AVal, argVals, argNames, ANull); - inner.fnType.originNode = node; - if (node.id) { - var decl = node.type == "FunctionDeclaration"; - addVar(decl ? scope : inner, node.id); - } - c(node.body, inner, "ScopeBody"); - }, - TryStatement: function(node, scope, c) { - c(node.block, scope, "Statement"); - if (node.handler) { - var v = addVar(scope, node.handler.param); - c(node.handler.body, scope, "ScopeBody"); - var e5 = cx.definitions.ecma5; - if (e5 && v.isEmpty()) getInstance(e5["Error.prototype"]).propagate(v, WG_CATCH_ERROR); - } - if (node.finalizer) c(node.finalizer, scope, "Statement"); - }, - VariableDeclaration: function(node, scope, c) { - for (var i = 0; i < node.declarations.length; ++i) { - var decl = node.declarations[i]; - addVar(scope, decl.id); - if (decl.init) c(decl.init, scope, "Expression"); - } - } - }); - - // CONSTRAINT GATHERING PASS - - function propName(node, scope, c) { - var prop = node.property; - if (!node.computed) return prop.name; - if (prop.type == "Literal" && typeof prop.value == "string") return prop.value; - if (c) infer(prop, scope, c, ANull); - return ""; - } - - function unopResultType(op) { - switch (op) { - case "+": case "-": case "~": return cx.num; - case "!": return cx.bool; - case "typeof": return cx.str; - case "void": case "delete": return ANull; - } - } - function binopIsBoolean(op) { - switch (op) { - case "==": case "!=": case "===": case "!==": case "<": case ">": case ">=": case "<=": - case "in": case "instanceof": return true; - } - } - function literalType(node) { - if (node.regex) return getInstance(cx.protos.RegExp); - switch (typeof node.value) { - case "boolean": return cx.bool; - case "number": return cx.num; - case "string": return cx.str; - case "object": - case "function": - if (!node.value) return ANull; - return getInstance(cx.protos.RegExp); - } - } - - function ret(f) { - return function(node, scope, c, out, name) { - var r = f(node, scope, c, name); - if (out) r.propagate(out); - return r; - }; - } - function fill(f) { - return function(node, scope, c, out, name) { - if (!out) out = new AVal; - f(node, scope, c, out, name); - return out; - }; - } - - var inferExprVisitor = { - ArrayExpression: ret(function(node, scope, c) { - var eltval = new AVal; - for (var i = 0; i < node.elements.length; ++i) { - var elt = node.elements[i]; - if (elt) infer(elt, scope, c, eltval); - } - return new Arr(eltval); - }), - ObjectExpression: ret(function(node, scope, c, name) { - var obj = node.objType = new Obj(true, name); - obj.originNode = node; - - for (var i = 0; i < node.properties.length; ++i) { - var prop = node.properties[i], key = prop.key, name; - if (prop.value.name == "✖") continue; - - if (key.type == "Identifier") { - name = key.name; - } else if (typeof key.value == "string") { - name = key.value; - } - if (!name || prop.kind == "set") { - infer(prop.value, scope, c, ANull); - continue; - } - - var val = obj.defProp(name, key), out = val; - val.initializer = true; - if (prop.kind == "get") - out = new IsCallee(obj, [], null, val); - infer(prop.value, scope, c, out, name); - } - return obj; - }), - FunctionExpression: ret(function(node, scope, c, name) { - var inner = node.body.scope, fn = inner.fnType; - if (name && !fn.name) fn.name = name; - c(node.body, scope, "ScopeBody"); - maybeTagAsInstantiated(node, inner) || maybeTagAsGeneric(inner); - if (node.id) inner.getProp(node.id.name).addType(fn); - return fn; - }), - SequenceExpression: ret(function(node, scope, c) { - for (var i = 0, l = node.expressions.length - 1; i < l; ++i) - infer(node.expressions[i], scope, c, ANull); - return infer(node.expressions[l], scope, c); - }), - UnaryExpression: ret(function(node, scope, c) { - infer(node.argument, scope, c, ANull); - return unopResultType(node.operator); - }), - UpdateExpression: ret(function(node, scope, c) { - infer(node.argument, scope, c, ANull); - return cx.num; - }), - BinaryExpression: ret(function(node, scope, c) { - if (node.operator == "+") { - var lhs = infer(node.left, scope, c); - var rhs = infer(node.right, scope, c); - if (lhs.hasType(cx.str) || rhs.hasType(cx.str)) return cx.str; - if (lhs.hasType(cx.num) && rhs.hasType(cx.num)) return cx.num; - var result = new AVal; - lhs.propagate(new IsAdded(rhs, result)); - rhs.propagate(new IsAdded(lhs, result)); - return result; - } else { - infer(node.left, scope, c, ANull); - infer(node.right, scope, c, ANull); - return binopIsBoolean(node.operator) ? cx.bool : cx.num; - } - }), - AssignmentExpression: ret(function(node, scope, c) { - var rhs, name, pName; - if (node.left.type == "MemberExpression") { - pName = propName(node.left, scope, c); - if (node.left.object.type == "Identifier") - name = node.left.object.name + "." + pName; - } else { - name = node.left.name; - } - - if (node.operator != "=" && node.operator != "+=") { - infer(node.right, scope, c, ANull); - rhs = cx.num; - } else { - rhs = infer(node.right, scope, c, null, name); - } - - if (node.left.type == "MemberExpression") { - var obj = infer(node.left.object, scope, c); - if (pName == "prototype") maybeInstantiate(scope, 20); - if (pName == "") { - // This is a hack to recognize for/in loops that copy - // properties, and do the copying ourselves, insofar as we - // manage, because such loops tend to be relevant for type - // information. - var v = node.left.property.name, local = scope.props[v], over = local && local.iteratesOver; - if (over) { - maybeInstantiate(scope, 20); - var fromRight = node.right.type == "MemberExpression" && node.right.computed && node.right.property.name == v; - over.forAllProps(function(prop, val, local) { - if (local && prop != "prototype" && prop != "") - obj.propagate(new PropHasSubset(prop, fromRight ? val : ANull)); - }); - return rhs; - } - } - obj.propagate(new PropHasSubset(pName, rhs, node.left.property)); - } else { // Identifier - rhs.propagate(scope.defVar(node.left.name, node.left)); - } - return rhs; - }), - LogicalExpression: fill(function(node, scope, c, out) { - infer(node.left, scope, c, out); - infer(node.right, scope, c, out); - }), - ConditionalExpression: fill(function(node, scope, c, out) { - infer(node.test, scope, c, ANull); - infer(node.consequent, scope, c, out); - infer(node.alternate, scope, c, out); - }), - NewExpression: fill(function(node, scope, c, out, name) { - if (node.callee.type == "Identifier" && node.callee.name in scope.props) - maybeInstantiate(scope, 20); - - for (var i = 0, args = []; i < node.arguments.length; ++i) - args.push(infer(node.arguments[i], scope, c)); - var callee = infer(node.callee, scope, c); - var self = new AVal; - callee.propagate(new IsCtor(self, name && /\.prototype$/.test(name))); - self.propagate(out, WG_NEW_INSTANCE); - callee.propagate(new IsCallee(self, args, node.arguments, new IfObj(out))); - }), - CallExpression: fill(function(node, scope, c, out) { - for (var i = 0, args = []; i < node.arguments.length; ++i) - args.push(infer(node.arguments[i], scope, c)); - if (node.callee.type == "MemberExpression") { - var self = infer(node.callee.object, scope, c); - var pName = propName(node.callee, scope, c); - if ((pName == "call" || pName == "apply") && - scope.fnType && scope.fnType.args.indexOf(self) > -1) - maybeInstantiate(scope, 30); - self.propagate(new HasMethodCall(pName, args, node.arguments, out)); - } else { - var callee = infer(node.callee, scope, c); - if (scope.fnType && scope.fnType.args.indexOf(callee) > -1) - maybeInstantiate(scope, 30); - var knownFn = callee.getFunctionType(); - if (knownFn && knownFn.instantiateScore && scope.fnType) - maybeInstantiate(scope, knownFn.instantiateScore / 5); - callee.propagate(new IsCallee(cx.topScope, args, node.arguments, out)); - } - }), - MemberExpression: fill(function(node, scope, c, out) { - var name = propName(node, scope); - var obj = infer(node.object, scope, c); - var prop = obj.getProp(name); - if (name == "") { - var propType = infer(node.property, scope, c); - if (!propType.hasType(cx.num)) - return prop.propagate(out, WG_MULTI_MEMBER); - } - prop.propagate(out); - }), - Identifier: ret(function(node, scope) { - if (node.name == "arguments" && scope.fnType && !(node.name in scope.props)) - scope.defProp(node.name, scope.fnType.originNode) - .addType(new Arr(scope.fnType.arguments = new AVal)); - return scope.getProp(node.name); - }), - ThisExpression: ret(function(_node, scope) { - return scope.fnType ? scope.fnType.self : cx.topScope; - }), - Literal: ret(function(node) { - return literalType(node); - }) - }; - - function infer(node, scope, c, out, name) { - return inferExprVisitor[node.type](node, scope, c, out, name); - } - - var inferWrapper = walk.make({ - Expression: function(node, scope, c) { - infer(node, scope, c, ANull); - }, - - FunctionDeclaration: function(node, scope, c) { - var inner = node.body.scope, fn = inner.fnType; - c(node.body, scope, "ScopeBody"); - maybeTagAsInstantiated(node, inner) || maybeTagAsGeneric(inner); - var prop = scope.getProp(node.id.name); - prop.addType(fn); - }, - - VariableDeclaration: function(node, scope, c) { - for (var i = 0; i < node.declarations.length; ++i) { - var decl = node.declarations[i], prop = scope.getProp(decl.id.name); - if (decl.init) - infer(decl.init, scope, c, prop, decl.id.name); - } - }, - - ReturnStatement: function(node, scope, c) { - if (!node.argument) return; - var output = ANull; - if (scope.fnType) { - if (scope.fnType.retval == ANull) scope.fnType.retval = new AVal; - output = scope.fnType.retval; - } - infer(node.argument, scope, c, output); - }, - - ForInStatement: function(node, scope, c) { - var source = infer(node.right, scope, c); - if ((node.right.type == "Identifier" && node.right.name in scope.props) || - (node.right.type == "MemberExpression" && node.right.property.name == "prototype")) { - maybeInstantiate(scope, 5); - var varName; - if (node.left.type == "Identifier") { - varName = node.left.name; - } else if (node.left.type == "VariableDeclaration") { - varName = node.left.declarations[0].id.name; - } - if (varName && varName in scope.props) - scope.getProp(varName).iteratesOver = source; - } - c(node.body, scope, "Statement"); - }, - - ScopeBody: function(node, scope, c) { c(node, node.scope || scope); } - }); - - // PARSING - - function runPasses(passes, pass) { - var arr = passes && passes[pass]; - var args = Array.prototype.slice.call(arguments, 2); - if (arr) for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); - } - - var parse = exports.parse = function(text, passes, options) { - var ast; - try { ast = acorn.parse(text, options); } - catch(e) { ast = acorn_loose.parse_dammit(text, options); } - runPasses(passes, "postParse", ast, text); - return ast; - }; - - // ANALYSIS INTERFACE - - exports.analyze = function(ast, name, scope, passes) { - if (typeof ast == "string") ast = parse(ast); - - if (!name) name = "file#" + cx.origins.length; - exports.addOrigin(cx.curOrigin = name); - - if (!scope) scope = cx.topScope; - walk.recursive(ast, scope, null, scopeGatherer); - runPasses(passes, "preInfer", ast, scope); - walk.recursive(ast, scope, null, inferWrapper); - runPasses(passes, "postInfer", ast, scope); - - cx.curOrigin = null; - }; - - // PURGING - - exports.purge = function(origins, start, end) { - var test = makePredicate(origins, start, end); - ++cx.purgeGen; - cx.topScope.purge(test); - for (var prop in cx.props) { - var list = cx.props[prop]; - for (var i = 0; i < list.length; ++i) { - var obj = list[i], av = obj.props[prop]; - if (!av || test(av, av.originNode)) list.splice(i--, 1); - } - if (!list.length) delete cx.props[prop]; - } - }; - - function makePredicate(origins, start, end) { - var arr = Array.isArray(origins); - if (arr && origins.length == 1) { origins = origins[0]; arr = false; } - if (arr) { - if (end == null) return function(n) { return origins.indexOf(n.origin) > -1; }; - return function(n, pos) { return pos && pos.start >= start && pos.end <= end && origins.indexOf(n.origin) > -1; }; - } else { - if (end == null) return function(n) { return n.origin == origins; }; - return function(n, pos) { return pos && pos.start >= start && pos.end <= end && n.origin == origins; }; - } - } - - AVal.prototype.purge = function(test) { - if (this.purgeGen == cx.purgeGen) return; - this.purgeGen = cx.purgeGen; - for (var i = 0; i < this.types.length; ++i) { - var type = this.types[i]; - if (test(type, type.originNode)) - this.types.splice(i--, 1); - else - type.purge(test); - } - if (this.forward) for (var i = 0; i < this.forward.length; ++i) { - var f = this.forward[i]; - if (test(f)) { - this.forward.splice(i--, 1); - if (this.props) this.props = null; - } else if (f.purge) { - f.purge(test); - } - } - }; - ANull.purge = function() {}; - Obj.prototype.purge = function(test) { - if (this.purgeGen == cx.purgeGen) return true; - this.purgeGen = cx.purgeGen; - for (var p in this.props) { - var av = this.props[p]; - if (test(av, av.originNode)) - this.removeProp(p); - av.purge(test); - } - }; - Fn.prototype.purge = function(test) { - if (Obj.prototype.purge.call(this, test)) return; - this.self.purge(test); - this.retval.purge(test); - for (var i = 0; i < this.args.length; ++i) this.args[i].purge(test); - }; - - // EXPRESSION TYPE DETERMINATION - - function findByPropertyName(name) { - guessing = true; - var found = objsWithProp(name); - if (found) for (var i = 0; i < found.length; ++i) { - var val = found[i].getProp(name); - if (!val.isEmpty()) return val; - } - return ANull; - } - - var typeFinder = { - ArrayExpression: function(node, scope) { - var eltval = new AVal; - for (var i = 0; i < node.elements.length; ++i) { - var elt = node.elements[i]; - if (elt) findType(elt, scope).propagate(eltval); - } - return new Arr(eltval); - }, - ObjectExpression: function(node) { - return node.objType; - }, - FunctionExpression: function(node) { - return node.body.scope.fnType; - }, - SequenceExpression: function(node, scope) { - return findType(node.expressions[node.expressions.length-1], scope); - }, - UnaryExpression: function(node) { - return unopResultType(node.operator); - }, - UpdateExpression: function() { - return cx.num; - }, - BinaryExpression: function(node, scope) { - if (binopIsBoolean(node.operator)) return cx.bool; - if (node.operator == "+") { - var lhs = findType(node.left, scope); - var rhs = findType(node.right, scope); - if (lhs.hasType(cx.str) || rhs.hasType(cx.str)) return cx.str; - } - return cx.num; - }, - AssignmentExpression: function(node, scope) { - return findType(node.right, scope); - }, - LogicalExpression: function(node, scope) { - var lhs = findType(node.left, scope); - return lhs.isEmpty() ? findType(node.right, scope) : lhs; - }, - ConditionalExpression: function(node, scope) { - var lhs = findType(node.consequent, scope); - return lhs.isEmpty() ? findType(node.alternate, scope) : lhs; - }, - NewExpression: function(node, scope) { - var f = findType(node.callee, scope).getFunctionType(); - var proto = f && f.getProp("prototype").getObjType(); - if (!proto) return ANull; - return getInstance(proto, f); - }, - CallExpression: function(node, scope) { - var f = findType(node.callee, scope).getFunctionType(); - if (!f) return ANull; - if (f.computeRet) { - for (var i = 0, args = []; i < node.arguments.length; ++i) - args.push(findType(node.arguments[i], scope)); - var self = ANull; - if (node.callee.type == "MemberExpression") - self = findType(node.callee.object, scope); - return f.computeRet(self, args, node.arguments); - } else { - return f.retval; - } - }, - MemberExpression: function(node, scope) { - var propN = propName(node, scope), obj = findType(node.object, scope).getType(); - if (obj) return obj.getProp(propN); - if (propN == "") return ANull; - return findByPropertyName(propN); - }, - Identifier: function(node, scope) { - return scope.hasProp(node.name) || ANull; - }, - ThisExpression: function(_node, scope) { - return scope.fnType ? scope.fnType.self : cx.topScope; - }, - Literal: function(node) { - return literalType(node); - } - }; - - function findType(node, scope) { - return typeFinder[node.type](node, scope); - } - - var searchVisitor = exports.searchVisitor = walk.make({ - Function: function(node, _st, c) { - var scope = node.body.scope; - if (node.id) c(node.id, scope); - for (var i = 0; i < node.params.length; ++i) - c(node.params[i], scope); - c(node.body, scope, "ScopeBody"); - }, - TryStatement: function(node, st, c) { - if (node.handler) - c(node.handler.param, st); - walk.base.TryStatement(node, st, c); - }, - VariableDeclaration: function(node, st, c) { - for (var i = 0; i < node.declarations.length; ++i) { - var decl = node.declarations[i]; - c(decl.id, st); - if (decl.init) c(decl.init, st, "Expression"); - } - } - }); - exports.fullVisitor = walk.make({ - MemberExpression: function(node, st, c) { - c(node.object, st, "Expression"); - c(node.property, st, node.computed ? "Expression" : null); - }, - ObjectExpression: function(node, st, c) { - for (var i = 0; i < node.properties.length; ++i) { - c(node.properties[i].value, st, "Expression"); - c(node.properties[i].key, st); - } - } - }, searchVisitor); - - exports.findExpressionAt = function(ast, start, end, defaultScope, filter) { - var test = filter || function(_t, node) { - if (node.type == "Identifier" && node.name == "✖") return false; - return typeFinder.hasOwnProperty(node.type); - }; - return walk.findNodeAt(ast, start, end, test, searchVisitor, defaultScope || cx.topScope); - }; - - exports.findExpressionAround = function(ast, start, end, defaultScope, filter) { - var test = filter || function(_t, node) { - if (start != null && node.start > start) return false; - if (node.type == "Identifier" && node.name == "✖") return false; - return typeFinder.hasOwnProperty(node.type); - }; - return walk.findNodeAround(ast, end, test, searchVisitor, defaultScope || cx.topScope); - }; - - exports.expressionType = function(found) { - return findType(found.node, found.state); - }; - - // Finding the expected type of something, from context - - exports.parentNode = function(child, ast) { - var stack = []; - function c(node, st, override) { - if (node.start <= child.start && node.end >= child.end) { - var top = stack[stack.length - 1]; - if (node == child) throw {found: top}; - if (top != node) stack.push(node); - walk.base[override || node.type](node, st, c); - if (top != node) stack.pop(); - } - } - try { - c(ast, null); - } catch (e) { - if (e.found) return e.found; - throw e; - } - }; - - var findTypeFromContext = { - ArrayExpression: function(parent, _, get) { return get(parent, true).getProp(""); }, - ObjectExpression: function(parent, node, get) { - for (var i = 0; i < parent.properties.length; ++i) { - var prop = node.properties[i]; - if (prop.value == node) - return get(parent, true).getProp(prop.key.name); - } - }, - UnaryExpression: function(parent) { return unopResultType(parent.operator); }, - UpdateExpression: function() { return cx.num; }, - BinaryExpression: function(parent) { return binopIsBoolean(parent.operator) ? cx.bool : cx.num; }, - AssignmentExpression: function(parent, _, get) { return get(parent.left); }, - LogicalExpression: function(parent, _, get) { return get(parent, true); }, - ConditionalExpression: function(parent, node, get) { - if (parent.consequent == node || parent.alternate == node) return get(parent, true); - }, - NewExpression: function(parent, node, get) { - return this.CallExpression(parent, node, get); - }, - CallExpression: function(parent, node, get) { - for (var i = 0; i < parent.arguments.length; i++) { - var arg = parent.arguments[i]; - if (arg == node) { - var calleeType = get(parent.callee).getFunctionType(); - if (calleeType instanceof Fn) - return calleeType.args[i]; - break; - } - } - }, - ReturnStatement: function(_parent, node, get) { - var fnNode = walk.findNodeAround(node.sourceFile.ast, node.start, "Function"); - if (fnNode) { - var fnType = get(fnNode.node, true).getFunctionType(); - if (fnType) return fnType.retval.getType(); - } - } - }; - - exports.typeFromContext = function(ast, found) { - var parent = exports.parentNode(found.node, ast); - var type = null; - if (findTypeFromContext.hasOwnProperty(parent.type)) { - type = findTypeFromContext[parent.type](parent, found.node, function(node, fromContext) { - var obj = {node: node, state: found.state}; - var tp = fromContext ? exports.typeFromContext(ast, obj) : exports.expressionType(obj); - return tp || ANull; - }); - } - return type || exports.expressionType(found); - }; - - // Flag used to indicate that some wild guessing was used to produce - // a type or set of completions. - var guessing = false; - - exports.resetGuessing = function(val) { guessing = val; }; - exports.didGuess = function() { return guessing; }; - - exports.forAllPropertiesOf = function(type, f) { - type.gatherProperties(f, 0); - }; - - var refFindWalker = walk.make({}, searchVisitor); - - exports.findRefs = function(ast, baseScope, name, refScope, f) { - refFindWalker.Identifier = function(node, scope) { - if (node.name != name) return; - for (var s = scope; s; s = s.prev) { - if (s == refScope) f(node, scope); - if (name in s.props) return; - } - }; - walk.recursive(ast, baseScope, null, refFindWalker); - }; - - var simpleWalker = walk.make({ - Function: function(node, _st, c) { c(node.body, node.body.scope, "ScopeBody"); } - }); - - exports.findPropRefs = function(ast, scope, objType, propName, f) { - walk.simple(ast, { - MemberExpression: function(node, scope) { - if (node.computed || node.property.name != propName) return; - if (findType(node.object, scope).getType() == objType) f(node.property); - }, - ObjectExpression: function(node, scope) { - if (findType(node, scope).getType() != objType) return; - for (var i = 0; i < node.properties.length; ++i) - if (node.properties[i].key.name == propName) f(node.properties[i].key); - } - }, simpleWalker, scope); - }; - - // LOCAL-VARIABLE QUERIES - - var scopeAt = exports.scopeAt = function(ast, pos, defaultScope) { - var found = walk.findNodeAround(ast, pos, function(tp, node) { - return tp == "ScopeBody" && node.scope; - }); - if (found) return found.node.scope; - else return defaultScope || cx.topScope; - }; - - exports.forAllLocalsAt = function(ast, pos, defaultScope, f) { - var scope = scopeAt(ast, pos, defaultScope); - scope.gatherProperties(f, 0); - }; - - // INIT DEF MODULE - - // Delayed initialization because of cyclic dependencies. - def = exports.def = def.init({}, exports); -}); diff --git a/mix/qml/html/cm/inkpot.css b/mix/qml/html/cm/inkpot.css deleted file mode 100644 index 4a2197cfc..000000000 --- a/mix/qml/html/cm/inkpot.css +++ /dev/null @@ -1,78 +0,0 @@ -/* -Inkpot theme for code-mirror -https://github.com/ciaranm/inkpot -*/ - -/* Color scheme for code-mirror */ - -.cm-s-inkpot.CodeMirror { - color: #cfbfad; - text-shadow: #1e1e27 0 1px; - background-color: #1e1e27; - line-height: 1.45em; - color-profile: sRGB; - rendering-intent: auto; -} - -.cm-s-inkpot .CodeMirror-gutters { background: #2e2e2e; border-right: 0px solid #aaa; } -.cm-s-inkpot .CodeMirror-linenumber { color: #8b8bcd; } -.cm-s-inkpot .CodeMirror-cursor { border-left: 1px solid white !important; } - -.cm-s-inkpot span.cm-comment { color: #cd8b00; } -.cm-s-inkpot span.cm-def { color: #cfbfad; font-weight:bold; } -.cm-s-inkpot span.cm-keyword { color: #808bed; } -.cm-s-inkpot span.cm-builtin { color: #efac6d; } -.cm-s-inkpot span.cm-variable { color: #cfbfad; } -.cm-s-inkpot span.cm-string { color: #ffcd8b; } -.cm-s-inkpot span.cm-number { color: #f0ad6d; } -.cm-s-inkpot span.cm-atom { color: #cb6ecb; } -.cm-s-inkpot span.cm-variable-2 { color: #ffb8ff; } - -.cm-s-inkpot span.cm-meta { color: #409090; } -.cm-s-inkpot span.cm-qualifier { color: #808bed; } -.cm-s-inkpot span.cm-tag { color: #808bed; } -.cm-s-inkpot span.cm-attribute { color: #FF5555; } -.cm-s-inkpot span.cm-error { color: #f00; } - -.cm-s-inkpot .cm-bracket { color: #cb4b16; } -.cm-s-inkpot .CodeMirror-matchingbracket { color: #859900; } -.cm-s-inkpot .CodeMirror-nonmatchingbracket { color: #dc322f; } - -.cm-s-inkpot .CodeMirror-selected { background: #4e4e8f !important; } -span.CodeMirror-selectedtext { color: #ffffff !important; } - - -/* Code execution */ -.CodeMirror-exechighlight { - border-bottom: double 1px #94A2A2; -} - - -/* Error annotation */ -.CodeMirror-errorannotation { - border-bottom: 1px solid #DD3330; - margin-bottom: 4px; - } - -.CodeMirror-errorannotation-context { - font-family: monospace; - color: #EEE9D5; - background: #b58900; - padding: 2px; - text-shadow: none !important; - border-top: solid 2px #063742; -} - -.CodeMirror-search-field -{ - font-size: 12px; -} - -.CodeMirror-gasCost -{ - font-family: monospace; - font-size: 14px; - color: #409090; - text-shadow: none !important; - margin-left: 5px; -} diff --git a/mix/qml/html/cm/javascript-hint.js b/mix/qml/html/cm/javascript-hint.js deleted file mode 100644 index 7bcbf4a05..000000000 --- a/mix/qml/html/cm/javascript-hint.js +++ /dev/null @@ -1,146 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var Pos = CodeMirror.Pos; - - function forEach(arr, f) { - for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); - } - - function arrayContains(arr, item) { - if (!Array.prototype.indexOf) { - var i = arr.length; - while (i--) { - if (arr[i] === item) { - return true; - } - } - return false; - } - return arr.indexOf(item) != -1; - } - - function scriptHint(editor, keywords, getToken, options) { - // Find the token at the cursor - var cur = editor.getCursor(), token = getToken(editor, cur); - if (/\b(?:string|comment)\b/.test(token.type)) return; - token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; - - // If it's not a 'word-style' token, ignore the token. - if (!/^[\w$_]*$/.test(token.string)) { - token = {start: cur.ch, end: cur.ch, string: "", state: token.state, - type: token.string == "." ? "property" : null}; - } else if (token.end > cur.ch) { - token.end = cur.ch; - token.string = token.string.slice(0, cur.ch - token.start); - } - - var tprop = token; - // If it is a property, find out what it is a property of. - while (tprop.type == "property") { - tprop = getToken(editor, Pos(cur.line, tprop.start)); - if (tprop.string != ".") return; - tprop = getToken(editor, Pos(cur.line, tprop.start)); - if (!context) var context = []; - context.push(tprop); - } - return {list: getCompletions(token, context, keywords, options), - from: Pos(cur.line, token.start), - to: Pos(cur.line, token.end)}; - } - - function javascriptHint(editor, options) { - return scriptHint(editor, javascriptKeywords, - function (e, cur) {return e.getTokenAt(cur);}, - options); - }; - CodeMirror.registerHelper("hint", "javascript", javascriptHint); - - function getCoffeeScriptToken(editor, cur) { - // This getToken, it is for coffeescript, imitates the behavior of - // getTokenAt method in javascript.js, that is, returning "property" - // type and treat "." as indepenent token. - var token = editor.getTokenAt(cur); - if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { - token.end = token.start; - token.string = '.'; - token.type = "property"; - } - else if (/^\.[\w$_]*$/.test(token.string)) { - token.type = "property"; - token.start++; - token.string = token.string.replace(/\./, ''); - } - return token; - } - - function coffeescriptHint(editor, options) { - return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); - } - CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint); - - var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + - "toUpperCase toLowerCase split concat match replace search").split(" "); - var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + - "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); - var funcProps = "prototype apply call bind".split(" "); - var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + - "if in instanceof new null return switch throw true try typeof var void while with").split(" "); - var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + - "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); - - function getCompletions(token, context, keywords, options) { - var found = [], start = token.string, global = options && options.globalScope || window; - function maybeAdd(str) { - if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str); - } - function gatherCompletions(obj) { - if (typeof obj == "string") forEach(stringProps, maybeAdd); - else if (obj instanceof Array) forEach(arrayProps, maybeAdd); - else if (obj instanceof Function) forEach(funcProps, maybeAdd); - for (var name in obj) maybeAdd(name); - } - - if (context && context.length) { - // If this is a property, see if it belongs to some object we can - // find in the current environment. - var obj = context.pop(), base; - if (obj.type && obj.type.indexOf("variable") === 0) { - if (options && options.additionalContext) - base = options.additionalContext[obj.string]; - if (!options || options.useGlobalScope !== false) - base = base || global[obj.string]; - } else if (obj.type == "string") { - base = ""; - } else if (obj.type == "atom") { - base = 1; - } else if (obj.type == "function") { - if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && - (typeof global.jQuery == 'function')) - base = global.jQuery(); - else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function')) - base = global._(); - } - while (base != null && context.length) - base = base[context.pop().string]; - if (base != null) gatherCompletions(base); - } else { - // If not, just look in the global object and any local scope - // (reading into JS mode internals to get at the local and global variables) - for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); - for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name); - if (!options || options.useGlobalScope !== false) - gatherCompletions(global); - forEach(keywords, maybeAdd); - } - return found; - } -}); diff --git a/mix/qml/html/cm/javascript.js b/mix/qml/html/cm/javascript.js deleted file mode 100644 index fac8d5776..000000000 --- a/mix/qml/html/cm/javascript.js +++ /dev/null @@ -1,686 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// TODO actually recognize syntax of TypeScript constructs - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("javascript", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - - // Tokenizer - - var keywords = function(){ - function kw(type) {return {type: type, style: "keyword"};} - var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); - var operator = kw("operator"), atom = {type: "atom", style: "atom"}; - - var jsKeywords = { - "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C, - "var": kw("var"), "const": kw("var"), "let": kw("var"), - "function": kw("function"), "catch": kw("catch"), - "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), - "in": operator, "typeof": operator, "instanceof": operator, - "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, - "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), - "yield": C, "export": kw("export"), "import": kw("import"), "extends": C - }; - - // Extend the 'normal' keywords with the TypeScript language extensions - if (isTS) { - var type = {type: "variable", style: "variable-3"}; - var tsKeywords = { - // object-like things - "interface": kw("interface"), - "extends": kw("extends"), - "constructor": kw("constructor"), - - // scope modifiers - "public": kw("public"), - "private": kw("private"), - "protected": kw("protected"), - "static": kw("static"), - - // types - "string": type, "number": type, "bool": type, "any": type - }; - - for (var attr in tsKeywords) { - jsKeywords[attr] = tsKeywords[attr]; - } - } - - return jsKeywords; - }(); - - var isOperatorChar = /[+\-*&%=<>!?|~^]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - - function readRegexp(stream) { - var escaped = false, next, inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true; - else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - - // Used as scratch variables to communicate multiple values without - // consing up tons of objects. - var type, content; - function ret(tp, style, cont) { - type = tp; content = cont; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.eat(/x/i)) { - stream.eatWhile(/[\da-f]/i); - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (state.lastType == "operator" || state.lastType == "keyword c" || - state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { - readRegexp(stream); - stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla - return ret("regexp", "string-2"); - } else { - stream.eatWhile(isOperatorChar); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#") { - stream.skipToEnd(); - return ret("error", "error"); - } else if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; - return (known && state.lastType != ".") ? ret(known.type, known.style, word) : - ret("variable", "variable", word); - } - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return ret("comment", "comment"); - } - - function tokenQuasi(stream, state) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - - var brackets = "([{}])"; - // This is a crude lookahead trick to try and notice that we're - // parsing the argument patterns for a fat-arrow function before we - // actually hit the arrow token. It only works if the arrow is on - // the same line as the arguments and there's no strange noise - // (comments) in between. Fallback is to only notice when we hit the - // arrow, and not declare the arguments as locals for the arrow - // body. - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - - var depth = 0, sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { ++pos; break; } - if (--depth == 0) break; - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/]/.test(ch)) { - return; - } else if (sawSomething && !depth) { - ++pos; - break; - } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - - // Parser - - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; - - function JSLexical(indented, column, type, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - - function inScope(state, varname) { - for (var v = state.localVars; v; v = v.next) - if (v.name == varname) return true; - for (var cx = state.context; cx; cx = cx.prev) { - for (var v = cx.vars; v; v = v.next) - if (v.name == varname) return true; - } - } - - function parseJS(state, style, type, content, stream) { - var cc = state.cc; - // Communicate our context to the combinators. - // (Less wasteful than consing up a hundred closures on every call.) - cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; - - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = true; - - while(true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type, content)) { - while(cc.length && cc[cc.length - 1].lex) - cc.pop()(); - if (cx.marked) return cx.marked; - if (type == "variable" && inScope(state, content)) return "variable-2"; - return style; - } - } - } - - // Combinator utils - - var cx = {state: null, column: null, marked: null, cc: null}; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function register(varname) { - function inList(list) { - for (var v = list; v; v = v.next) - if (v.name == varname) return true; - return false; - } - var state = cx.state; - if (state.context) { - cx.marked = "def"; - if (inList(state.localVars)) return; - state.localVars = {name: varname, next: state.localVars}; - } else { - if (inList(state.globalVars)) return; - if (parserConfig.globalVars) - state.globalVars = {name: varname, next: state.globalVars}; - } - } - - // Combinators - - var defaultVars = {name: "this", next: {name: "arguments"}}; - function pushcontext() { - cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; - cx.state.localVars = defaultVars; - } - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - function pushlex(type, info) { - var result = function() { - var state = cx.state, indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented; - else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) - indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); - }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") - state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - - function expect(wanted) { - function exp(type) { - if (type == wanted) return cont(); - else if (wanted == ";") return pass(); - else return cont(exp); - }; - return exp; - } - - function statement(type, value) { - if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); - if (type == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type == "{") return cont(pushlex("}"), block, poplex); - if (type == ";") return cont(); - if (type == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) - cx.state.cc.pop()(); - return cont(pushlex("form"), expression, statement, poplex, maybeelse); - } - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); - if (type == "variable") return cont(pushlex("stat"), maybelabel); - if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), - block, poplex, poplex); - if (type == "case") return cont(expression, expect(":")); - if (type == "default") return cont(expect(":")); - if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), - statement, poplex, popcontext); - if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); - if (type == "class") return cont(pushlex("form"), className, poplex); - if (type == "export") return cont(pushlex("form"), afterExport, poplex); - if (type == "import") return cont(pushlex("form"), afterImport, poplex); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function expression(type) { - return expressionInner(type, false); - } - function expressionNoComma(type) { - return expressionInner(type, true); - } - function expressionInner(type, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); - else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef, maybeop); - if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); - if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); - if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); - if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type == "{") return contCommasep(objprop, "}", null, maybeop); - if (type == "quasi") { return pass(quasi, maybeop); } - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - function maybeexpressionNoComma(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expressionNoComma); - } - - function maybeoperatorComma(type, value) { - if (type == ",") return cont(expression); - return maybeoperatorNoComma(type, value, false); - } - function maybeoperatorNoComma(type, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type == "operator") { - if (/\+\+|--/.test(value)) return cont(me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type == "quasi") { return pass(quasi, me); } - if (type == ";") return; - if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type == ".") return cont(property, me); - if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - } - function quasi(type, value) { - if (type != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(expression, continueQuasi); - } - function continueQuasi(type) { - if (type == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expression); - } - function arrowBodyNoComma(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expressionNoComma); - } - function maybelabel(type) { - if (type == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type) { - if (type == "variable") {cx.marked = "property"; return cont();} - } - function objprop(type, value) { - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - return cont(afterprop); - } else if (type == "number" || type == "string") { - cx.marked = jsonldMode ? "property" : (cx.style + " property"); - return cont(afterprop); - } else if (type == "jsonld-keyword") { - return cont(afterprop); - } else if (type == "[") { - return cont(expression, expect("]"), afterprop); - } - } - function getterSetter(type) { - if (type != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type) { - if (type == ":") return cont(expressionNoComma); - if (type == "(") return pass(functiondef); - } - function commasep(what, end) { - function proceed(type) { - if (type == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(what, proceed); - } - if (type == end) return cont(); - return cont(expect(end)); - } - return function(type) { - if (type == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) - cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type) { - if (type == "}") return cont(); - return pass(statement, block); - } - function maybetype(type) { - if (isTS && type == ":") return cont(typedef); - } - function typedef(type) { - if (type == "variable"){cx.marked = "variable-3"; return cont();} - } - function vardef() { - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type, value) { - if (type == "variable") { register(value); return cont(); } - if (type == "[") return contCommasep(pattern, "]"); - if (type == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type, value) { - if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type == "variable") cx.marked = "property"; - return cont(expect(":"), pattern, maybeAssign); - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type) { - if (type == ",") return cont(vardef); - } - function maybeelse(type, value) { - if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type) { - if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); - } - function forspec1(type) { - if (type == "var") return cont(vardef, expect(";"), forspec2); - if (type == ";") return cont(forspec2); - if (type == "variable") return cont(formaybeinof); - return pass(expression, expect(";"), forspec2); - } - function formaybeinof(_type, value) { - if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } - return cont(maybeoperatorComma, forspec2); - } - function forspec2(type, value) { - if (type == ";") return cont(forspec3); - if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } - return pass(expression, expect(";"), forspec3); - } - function forspec3(type) { - if (type != ")") cont(expression); - } - function functiondef(type, value) { - if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} - if (type == "variable") {register(value); return cont(functiondef);} - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext); - } - function funarg(type) { - if (type == "spread") return cont(funarg); - return pass(pattern, maybetype); - } - function className(type, value) { - if (type == "variable") {register(value); return cont(classNameAfter);} - } - function classNameAfter(type, value) { - if (value == "extends") return cont(expression, classNameAfter); - if (type == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type, value) { - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); - return cont(functiondef, classBody); - } - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (type == ";") return cont(classBody); - if (type == "}") return cont(); - } - function classGetterSetter(type) { - if (type != "variable") return pass(); - cx.marked = "property"; - return cont(); - } - function afterModule(type, value) { - if (type == "string") return cont(statement); - if (type == "variable") { register(value); return cont(maybeFrom); } - } - function afterExport(_type, value) { - if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } - if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } - return pass(statement); - } - function afterImport(type) { - if (type == "string") return cont(); - return pass(importSpec, maybeFrom); - } - function importSpec(type, value) { - if (type == "{") return contCommasep(importSpec, "}"); - if (type == "variable") register(value); - return cont(); - } - function maybeFrom(_type, value) { - if (value == "from") { cx.marked = "keyword"; return cont(expression); } - } - function arrayLiteral(type) { - if (type == "]") return cont(); - return pass(expressionNoComma, maybeArrayComprehension); - } - function maybeArrayComprehension(type) { - if (type == "for") return pass(comprehension, expect("]")); - if (type == ",") return cont(commasep(maybeexpressionNoComma, "]")); - return pass(commasep(expressionNoComma, "]")); - } - function comprehension(type) { - if (type == "for") return cont(forspec, comprehension); - if (type == "if") return cont(expression, comprehension); - } - - // Interface - - return { - startState: function(basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && {vars: parserConfig.localVars}, - indented: 0 - }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") - state.globalVars = parserConfig.globalVars; - return state; - }, - - token: function(stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - - indent: function(state, textAfter) { - if (state.tokenize == tokenComment) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; - // Kludge to prevent 'maybelse' from blocking lexical scope pops - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev; - else if (c != maybeelse) break; - } - if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") - lexical = lexical.prev; - var type = lexical.type, closing = firstChar == type; - - if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); - else if (type == "form" && firstChar == "{") return lexical.indented; - else if (type == "form") return lexical.indented + indentUnit; - else if (type == "stat") - return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); - else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) - return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); - else if (lexical.align) return lexical.column + (closing ? 0 : 1); - else return lexical.indented + (closing ? 0 : indentUnit); - }, - - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - lineComment: jsonMode ? null : "//", - fold: "brace", - - helperType: jsonMode ? "json" : "javascript", - jsonldMode: jsonldMode, - jsonMode: jsonMode - }; -}); - -CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - -CodeMirror.defineMIME("text/javascript", "javascript"); -CodeMirror.defineMIME("text/ecmascript", "javascript"); -CodeMirror.defineMIME("application/javascript", "javascript"); -CodeMirror.defineMIME("application/x-javascript", "javascript"); -CodeMirror.defineMIME("application/ecmascript", "javascript"); -CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); -CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); -CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); - -}); diff --git a/mix/qml/html/cm/mark-selection.js b/mix/qml/html/cm/mark-selection.js deleted file mode 100644 index 22e46ef32..000000000 --- a/mix/qml/html/cm/mark-selection.js +++ /dev/null @@ -1,118 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// Because sometimes you need to mark the selected *text*. -// -// Adds an option 'styleSelectedText' which, when enabled, gives -// selected text the CSS class given as option value, or -// "CodeMirror-selectedtext" when the value is not a string. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) { - var prev = old && old != CodeMirror.Init; - if (val && !prev) { - cm.state.markedSelection = []; - cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext"; - reset(cm); - cm.on("cursorActivity", onCursorActivity); - cm.on("change", onChange); - } else if (!val && prev) { - cm.off("cursorActivity", onCursorActivity); - cm.off("change", onChange); - clear(cm); - cm.state.markedSelection = cm.state.markedSelectionStyle = null; - } - }); - - function onCursorActivity(cm) { - cm.operation(function() { update(cm); }); - } - - function onChange(cm) { - if (cm.state.markedSelection.length) - cm.operation(function() { clear(cm); }); - } - - var CHUNK_SIZE = 8; - var Pos = CodeMirror.Pos; - var cmp = CodeMirror.cmpPos; - - function coverRange(cm, from, to, addAt) { - if (cmp(from, to) == 0) return; - var array = cm.state.markedSelection; - var cls = cm.state.markedSelectionStyle; - for (var line = from.line;;) { - var start = line == from.line ? from : Pos(line, 0); - var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line; - var end = atEnd ? to : Pos(endLine, 0); - var mark = cm.markText(start, end, {className: cls}); - if (addAt == null) array.push(mark); - else array.splice(addAt++, 0, mark); - if (atEnd) break; - line = endLine; - } - } - - function clear(cm) { - var array = cm.state.markedSelection; - for (var i = 0; i < array.length; ++i) array[i].clear(); - array.length = 0; - } - - function reset(cm) { - clear(cm); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) - coverRange(cm, ranges[i].from(), ranges[i].to()); - } - - function update(cm) { - if (!cm.somethingSelected()) return clear(cm); - if (cm.listSelections().length > 1) return reset(cm); - - var from = cm.getCursor("start"), to = cm.getCursor("end"); - - var array = cm.state.markedSelection; - if (!array.length) return coverRange(cm, from, to); - - var coverStart = array[0].find(), coverEnd = array[array.length - 1].find(); - if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE || - cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0) - return reset(cm); - - while (cmp(from, coverStart.from) > 0) { - array.shift().clear(); - coverStart = array[0].find(); - } - if (cmp(from, coverStart.from) < 0) { - if (coverStart.to.line - from.line < CHUNK_SIZE) { - array.shift().clear(); - coverRange(cm, from, coverStart.to, 0); - } else { - coverRange(cm, from, coverStart.from, 0); - } - } - - while (cmp(to, coverEnd.to) < 0) { - array.pop().clear(); - coverEnd = array[array.length - 1].find(); - } - if (cmp(to, coverEnd.to) > 0) { - if (to.line - coverEnd.from.line < CHUNK_SIZE) { - array.pop().clear(); - coverRange(cm, coverEnd.from, to); - } else { - coverRange(cm, coverEnd.to, to); - } - } - } -}); diff --git a/mix/qml/html/cm/matchbrackets.js b/mix/qml/html/cm/matchbrackets.js deleted file mode 100644 index fa1ae030a..000000000 --- a/mix/qml/html/cm/matchbrackets.js +++ /dev/null @@ -1,120 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && - (document.documentMode == null || document.documentMode < 8); - - var Pos = CodeMirror.Pos; - - var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; - - function findMatchingBracket(cm, where, strict, config) { - var line = cm.getLineHandle(where.line), pos = where.ch - 1; - var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (strict && (dir > 0) != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config); - if (found == null) return null; - return {from: Pos(where.line, pos), to: found && found.pos, - match: found && found.ch == match.charAt(0), forward: dir > 0}; - } - - // bracketRegex is used to specify which type of bracket to scan - // should be a regexp, e.g. /[[\]]/ - // - // Note: If "where" is on an open bracket, then this bracket is ignored. - // - // Returns false when no bracket was found, null when it reached - // maxScanLines and gave up - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = (config && config.maxScanLineLength) || 10000; - var maxScanLines = (config && config.maxScanLines) || 1000; - - var stack = []; - var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/; - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) - : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) { - var match = matching[ch]; - if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch); - else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch}; - else stack.pop(); - } - } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - - function matchBrackets(cm, autoclear, config) { - // Disable brace matching in long lines, since it'll cause hugely slow updates - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; - var marks = [], ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config); - if (match && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style})); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) - marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style})); - } - } - - if (marks.length) { - // Kludge to work around the IE bug from issue #1193, where text - // input stops going to the textare whever this fires. - if (ie_lt8 && cm.state.focused) cm.display.input.focus(); - - var clear = function() { - cm.operation(function() { - for (var i = 0; i < marks.length; i++) marks[i].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800); - else return clear; - } - } - - var currentlyHighlighted = null; - function doMatchBrackets(cm) { - cm.operation(function() { - if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} - currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - - CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) - cm.off("cursorActivity", doMatchBrackets); - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - } - }); - - CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); - CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){ - return findMatchingBracket(this, pos, strict, config); - }); - CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){ - return scanForBracket(this, pos, dir, style, config); - }); -}); diff --git a/mix/qml/html/cm/search.js b/mix/qml/html/cm/search.js deleted file mode 100644 index 0251067a7..000000000 --- a/mix/qml/html/cm/search.js +++ /dev/null @@ -1,164 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// Define search commands. Depends on dialog.js or another -// implementation of the openDialog method. - -// Replace works a little oddly -- it will do the replace on the next -// Ctrl-G (or whatever is bound to findNext) press. You prevent a -// replace by making sure the match is no longer selected when hitting -// Ctrl-G. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - function searchOverlay(query, caseInsensitive) { - if (typeof query == "string") - query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g"); - else if (!query.global) - query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); - - return {token: function(stream) { - query.lastIndex = stream.pos; - var match = query.exec(stream.string); - if (match && match.index == stream.pos) { - stream.pos += match[0].length; - return "searching"; - } else if (match) { - stream.pos = match.index; - } else { - stream.skipToEnd(); - } - }}; - } - - function SearchState() { - this.posFrom = this.posTo = this.query = null; - this.overlay = null; - } - function getSearchState(cm) { - return cm.state.search || (cm.state.search = new SearchState()); - } - function queryCaseInsensitive(query) { - return typeof query == "string" && query == query.toLowerCase(); - } - function getSearchCursor(cm, query, pos) { - // Heuristic: if the query string is all lowercase, do a case insensitive search. - return cm.getSearchCursor(query, pos, queryCaseInsensitive(query)); - } - function dialog(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, {value: deflt}); - else f(prompt(shortText, deflt)); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs); - else if (confirm(shortText)) fs[0](); - } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/([a-z]*)$/); - if (isRE) { - try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); } - catch(e) {} // Not a regular expression after all, do a string search - } - if (typeof query == "string" ? query == "" : query.test("")) - query = /x^/; - return query; - } - var queryDialog = - 'Search: (Use /re/ syntax for regexp search)'; - function doSearch(cm, rev) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - dialog(cm, queryDialog, "Search for:", cm.getSelection(), function(query) { - cm.operation(function() { - if (!query || state.query) return; - state.query = parseQuery(query); - cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); - state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); - cm.addOverlay(state.overlay); - if (cm.showMatchesOnScrollbar) { - if (state.annotate) { state.annotate.clear(); state.annotate = null; } - state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); - } - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); - }); - } - function findNext(cm, rev) {cm.operation(function() { - var state = getSearchState(cm); - var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); - if (!cursor.find(rev)) { - cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); - state.posFrom = cursor.from(); state.posTo = cursor.to(); - });} - function clearSearch(cm) {cm.operation(function() { - var state = getSearchState(cm); - if (!state.query) return; - state.query = null; - cm.removeOverlay(state.overlay); - if (state.annotate) { state.annotate.clear(); state.annotate = null; } - });} - - var replaceQueryDialog = - 'Replace: (Use /re/ syntax for regexp search)'; - var replacementQueryDialog = 'With: '; - var doReplaceConfirm = "Replace? "; - function replace(cm, all) { - if (cm.getOption("readOnly")) return; - dialog(cm, replaceQueryDialog, "Replace:", cm.getSelection(), function(query) { - if (!query) return; - query = parseQuery(query); - dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) { - if (all) { - cm.operation(function() { - for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { - if (typeof query != "string") { - var match = cm.getRange(cursor.from(), cursor.to()).match(query); - cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];})); - } else cursor.replace(text); - } - }); - } else { - clearSearch(cm); - var cursor = getSearchCursor(cm, query, cm.getCursor()); - var advance = function() { - var start = cursor.from(), match; - if (!(match = cursor.findNext())) { - cursor = getSearchCursor(cm, query); - if (!(match = cursor.findNext()) || - (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); - confirmDialog(cm, doReplaceConfirm, "Replace?", - [function() {doReplace(match);}, advance]); - }; - var doReplace = function(match) { - cursor.replace(typeof query == "string" ? text : - text.replace(/\$(\d)/g, function(_, i) {return match[i];})); - advance(); - }; - advance(); - } - }); - }); - } - - CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);}; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);}; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);}; -}); diff --git a/mix/qml/html/cm/searchcursor.js b/mix/qml/html/cm/searchcursor.js deleted file mode 100644 index 55c108b5a..000000000 --- a/mix/qml/html/cm/searchcursor.js +++ /dev/null @@ -1,189 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - var Pos = CodeMirror.Pos; - - function SearchCursor(doc, query, pos, caseFold) { - this.atOccurrence = false; this.doc = doc; - if (caseFold == null && typeof query == "string") caseFold = false; - - pos = pos ? doc.clipPos(pos) : Pos(0, 0); - this.pos = {from: pos, to: pos}; - - // The matches method is filled in based on the type of query. - // It takes a position and a direction, and returns an object - // describing the next occurrence of the query, or null if no - // more matches were found. - if (typeof query != "string") { // Regexp match - if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g"); - this.matches = function(reverse, pos) { - if (reverse) { - query.lastIndex = 0; - var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start; - for (;;) { - query.lastIndex = cutOff; - var newMatch = query.exec(line); - if (!newMatch) break; - match = newMatch; - start = match.index; - cutOff = match.index + (match[0].length || 1); - if (cutOff == line.length) break; - } - var matchLen = (match && match[0].length) || 0; - if (!matchLen) { - if (start == 0 && line.length == 0) {match = undefined;} - else if (start != doc.getLine(pos.line).length) { - matchLen++; - } - } - } else { - query.lastIndex = pos.ch; - var line = doc.getLine(pos.line), match = query.exec(line); - var matchLen = (match && match[0].length) || 0; - var start = match && match.index; - if (start + matchLen != line.length && !matchLen) matchLen = 1; - } - if (match && matchLen) - return {from: Pos(pos.line, start), - to: Pos(pos.line, start + matchLen), - match: match}; - }; - } else { // String query - var origQuery = query; - if (caseFold) query = query.toLowerCase(); - var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;}; - var target = query.split("\n"); - // Different methods for single-line and multi-line queries - if (target.length == 1) { - if (!query.length) { - // Empty string would match anything and never progress, so - // we define it to match nothing instead. - this.matches = function() {}; - } else { - this.matches = function(reverse, pos) { - if (reverse) { - var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig); - var match = line.lastIndexOf(query); - if (match > -1) { - match = adjustPos(orig, line, match); - return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)}; - } - } else { - var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig); - var match = line.indexOf(query); - if (match > -1) { - match = adjustPos(orig, line, match) + pos.ch; - return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)}; - } - } - }; - } - } else { - var origTarget = origQuery.split("\n"); - this.matches = function(reverse, pos) { - var last = target.length - 1; - if (reverse) { - if (pos.line - (target.length - 1) < doc.firstLine()) return; - if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return; - var to = Pos(pos.line, origTarget[last].length); - for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln) - if (target[i] != fold(doc.getLine(ln))) return; - var line = doc.getLine(ln), cut = line.length - origTarget[0].length; - if (fold(line.slice(cut)) != target[0]) return; - return {from: Pos(ln, cut), to: to}; - } else { - if (pos.line + (target.length - 1) > doc.lastLine()) return; - var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length; - if (fold(line.slice(cut)) != target[0]) return; - var from = Pos(pos.line, cut); - for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln) - if (target[i] != fold(doc.getLine(ln))) return; - if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return; - return {from: from, to: Pos(ln, origTarget[last].length)}; - } - }; - } - } - } - - SearchCursor.prototype = { - findNext: function() {return this.find(false);}, - findPrevious: function() {return this.find(true);}, - - find: function(reverse) { - var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); - function savePosAndFail(line) { - var pos = Pos(line, 0); - self.pos = {from: pos, to: pos}; - self.atOccurrence = false; - return false; - } - - for (;;) { - if (this.pos = this.matches(reverse, pos)) { - this.atOccurrence = true; - return this.pos.match || true; - } - if (reverse) { - if (!pos.line) return savePosAndFail(0); - pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length); - } - else { - var maxLine = this.doc.lineCount(); - if (pos.line == maxLine - 1) return savePosAndFail(maxLine); - pos = Pos(pos.line + 1, 0); - } - } - }, - - from: function() {if (this.atOccurrence) return this.pos.from;}, - to: function() {if (this.atOccurrence) return this.pos.to;}, - - replace: function(newText) { - if (!this.atOccurrence) return; - var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange(lines, this.pos.from, this.pos.to); - this.pos.to = Pos(this.pos.from.line + lines.length - 1, - lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); - } - }; - - // Maps a position in a case-folded line back to a position in the original line - // (compensating for codepoints increasing in number during folding) - function adjustPos(orig, folded, pos) { - if (orig.length == folded.length) return pos; - for (var pos1 = Math.min(pos, orig.length);;) { - var len1 = orig.slice(0, pos1).toLowerCase().length; - if (len1 < pos) ++pos1; - else if (len1 > pos) --pos1; - else return pos1; - } - } - - CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold); - }); - CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - }); - - CodeMirror.defineExtension("selectMatches", function(query, caseFold) { - var ranges = [], next; - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); - while (next = cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; - ranges.push({anchor: cur.from(), head: cur.to()}); - } - if (ranges.length) - this.setSelections(ranges, 0); - }); -}); diff --git a/mix/qml/html/cm/show-hint.css b/mix/qml/html/cm/show-hint.css deleted file mode 100644 index 479acf024..000000000 --- a/mix/qml/html/cm/show-hint.css +++ /dev/null @@ -1,59 +0,0 @@ -.CodeMirror-hints { - position: absolute; - z-index: 10; - overflow: hidden; - list-style: none; - - margin: 0; - padding: 2px; - - -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - box-shadow: 2px 3px 5px rgba(0,0,0,.2); - border-radius: 3px; - border: 1px solid silver; - - background: white; - font-size: 90%; - font-family: monospace; - - max-height: 20em; - overflow-y: auto; - width: 22em; -} - -.CodeMirror-hint { - margin: 0; - padding: 0 4px; - border-radius: 2px; - max-width: 30em; - overflow: hidden; - white-space: pre; - color: black; - cursor: pointer; - padding-left: 20px; - padding-top: 3px; - padding-bottom: 3px; -} - -.CodeMirror-hint-active { - background: #4a90e2; - color: white !important; -} - -.CodeMirror-hint-active .solToken, -.CodeMirror-hint-active .solTokenType -{ - color: white !important; -} - -.solToken { - float: left; -} - -.solTokenType -{ - font-style: italic; - color: #808080; - float: right; -} diff --git a/mix/qml/html/cm/show-hint.js b/mix/qml/html/cm/show-hint.js deleted file mode 100644 index 4d8661265..000000000 --- a/mix/qml/html/cm/show-hint.js +++ /dev/null @@ -1,394 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; - - // This is the old interface, kept around for now to stay - // backwards-compatible. - CodeMirror.showHint = function(cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = {hint: getHints}; - if (options) for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; - - var asyncRunID = 0; - function retrieveHints(getter, cm, options, then) { - if (getter.async) { - var id = ++asyncRunID; - getter(cm, function(hints) { - if (asyncRunID == id) then(hints); - }, options); - } else { - then(getter(cm, options)); - } - } - - CodeMirror.defineExtension("showHint", function(options) { - // We want a single cursor position. - if (this.listSelections().length > 1 || this.somethingSelected()) return; - - if (this.state.completionActive) this.state.completionActive.close(); - var completion = this.state.completionActive = new Completion(this, options); - var getHints = completion.options.hint; - if (!getHints) return; - - CodeMirror.signal(this, "startCompletion", this); - return retrieveHints(getHints, this, completion.options, function(hints) { completion.showHints(hints); }); - }); - - function Completion(cm, options) { - this.cm = cm; - this.options = this.buildOptions(options); - this.widget = this.onClose = null; - } - - Completion.prototype = { - close: function() { - if (!this.active()) return; - this.cm.state.completionActive = null; - - if (this.widget) this.widget.close(); - if (this.onClose) this.onClose(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); - }, - - active: function() { - return this.cm.state.completionActive == this; - }, - - pick: function(data, i) { - var completion = data.list[i]; - if (completion.hint) completion.hint(this.cm, data, completion); - else this.cm.replaceRange(getText(completion), completion.from || data.from, - completion.to || data.to, "complete"); - CodeMirror.signal(data, "pick", completion); - this.close(); - }, - - showHints: function(data) { - if (!data || !data.list.length || !this.active()) return this.close(); - - if (this.options.completeSingle && data.list.length == 1) - this.pick(data, 0); - else - this.showWidget(data); - }, - - showWidget: function(data) { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); - - var debounce = 0, completion = this, finished; - var closeOn = this.options.closeCharacters; - var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length; - - var requestAnimationFrame = window.requestAnimationFrame || function(fn) { - return setTimeout(fn, 1000/60); - }; - var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; - - function done() { - if (finished) return; - finished = true; - completion.close(); - completion.cm.off("cursorActivity", activity); - if (data) CodeMirror.signal(data, "close"); - } - - function update() { - if (finished) return; - CodeMirror.signal(data, "update"); - retrieveHints(completion.options.hint, completion.cm, completion.options, finishUpdate); - } - function finishUpdate(data_) { - data = data_; - if (finished) return; - if (!data || !data.list.length) return done(); - if (completion.widget) completion.widget.close(); - completion.widget = new Widget(completion, data); - } - - function clearDebounce() { - if (debounce) { - cancelAnimationFrame(debounce); - debounce = 0; - } - } - - function activity() { - clearDebounce(); - var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line); - if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch || - pos.ch < startPos.ch || completion.cm.somethingSelected() || - (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) { - completion.close(); - } else { - debounce = requestAnimationFrame(update); - if (completion.widget) completion.widget.close(); - } - } - this.cm.on("cursorActivity", activity); - this.onClose = done; - }, - - buildOptions: function(options) { - var editor = this.cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) for (var prop in editor) - if (editor[prop] !== undefined) out[prop] = editor[prop]; - if (options) for (var prop in options) - if (options[prop] !== undefined) out[prop] = options[prop]; - return out; - } - }; - - function getText(completion) { - if (typeof completion == "string") return completion; - else return completion.text; - } - - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function() {handle.moveFocus(-1);}, - Down: function() {handle.moveFocus(1);}, - PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);}, - PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);}, - Home: function() {handle.setFocus(0);}, - End: function() {handle.setFocus(handle.length - 1);}, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close - }; - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; - function addBinding(key, val) { - var bound; - if (typeof val != "string") - bound = function(cm) { return val(cm, handle); }; - // This mechanism is deprecated - else if (baseMap.hasOwnProperty(val)) - bound = baseMap[val]; - else - bound = val; - ourMap[key] = bound; - } - if (custom) - for (var key in custom) if (custom.hasOwnProperty(key)) - addBinding(key, custom[key]); - var extra = completion.options.extraKeys; - if (extra) - for (var key in extra) if (extra.hasOwnProperty(key)) - addBinding(key, extra[key]); - return ourMap; - } - - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; - el = el.parentNode; - } - } - - function Widget(completion, data) { - this.completion = completion; - this.data = data; - var widget = this, cm = completion.cm; - - var hints = this.hints = document.createElement("ul"); - hints.className = "CodeMirror-hints"; - this.selectedHint = data.selectedHint || 0; - - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; - var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) className = cur.className + " " + className; - elt.className = className; - if (cur.render) cur.render(elt, data, cur); - else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); - elt.hintId = i; - } - - var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); - var left = pos.left, top = pos.bottom, below = true; - hints.style.left = left + "px"; - hints.style.top = top + "px"; - // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. - var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); - var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); - (completion.options.container || document.body).appendChild(hints); - var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { // Fits above cursor - hints.style.top = (top = pos.top - height) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = (winH - 5) + "px"; - hints.style.top = (top = pos.bottom - box.top) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left) + "px"; - box = hints.getBoundingClientRect(); - } - } - } - var overlapX = box.right - winW; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = (winW - 5) + "px"; - overlapX -= (box.right - box.left) - winW; - } - hints.style.left = (left = pos.left - overlapX) + "px"; - } - - cm.addKeyMap(this.keyMap = buildKeyMap(completion, { - moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, - setFocus: function(n) { widget.changeActive(n); }, - menuSize: function() { return widget.screenAmount(); }, - length: completions.length, - close: function() { completion.close(); }, - pick: function() { widget.pick(); }, - data: data - })); - - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); - cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); - } - - var startScroll = cm.getScrollInfo(); - cm.on("scroll", this.onScroll = function() { - var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); - var newTop = top + startScroll.top - curScroll.top; - var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = (left + startScroll.left - curScroll.left) + "px"; - }); - - CodeMirror.on(hints, "dblclick", function(e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} - }); - - CodeMirror.on(hints, "click", function(e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); - } - }); - - CodeMirror.on(hints, "mousedown", function() { - setTimeout(function(){cm.focus();}, 20); - }); - - CodeMirror.signal(data, "select", completions[0], hints.firstChild); - return true; - } - - Widget.prototype = { - close: function() { - if (this.completion.widget != this) return; - this.completion.widget = null; - this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); - - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, - - pick: function() { - this.completion.pick(this.data, this.selectedHint); - }, - - changeActive: function(i, avoidWrap) { - if (i >= this.data.list.length) - i = avoidWrap ? this.data.list.length - 1 : 0; - else if (i < 0) - i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); - node = this.hints.childNodes[this.selectedHint = i]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - if (node.offsetTop < this.hints.scrollTop) - this.hints.scrollTop = node.offsetTop - 3; - else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) - this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; - CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); - }, - - screenAmount: function() { - return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; - } - }; - - CodeMirror.registerHelper("hint", "auto", function(cm, options) { - var helpers = cm.getHelpers(cm.getCursor(), "hint"), words; - if (helpers.length) { - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, options); - if (cur && cur.list.length) return cur; - } - } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { - if (words) return CodeMirror.hint.fromList(cm, {words: words}); - } else if (CodeMirror.hint.anyword) { - return CodeMirror.hint.anyword(cm, options); - } - }); - - CodeMirror.registerHelper("hint", "fromList", function(cm, options) { - var cur = cm.getCursor(), token = cm.getTokenAt(cur); - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, token.string.length) == token.string) - found.push(word); - } - - if (found.length) return { - list: found, - from: CodeMirror.Pos(cur.line, token.start), - to: CodeMirror.Pos(cur.line, token.end) - }; - }); - - CodeMirror.commands.autocomplete = CodeMirror.showHint; - - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnUnfocus: true, - completeOnSingleClick: false, - container: null, - customKeys: null, - extraKeys: null - }; - - CodeMirror.defineOption("hintOptions", null); -}); diff --git a/mix/qml/html/cm/signal.js b/mix/qml/html/cm/signal.js deleted file mode 100644 index 1148ed1ef..000000000 --- a/mix/qml/html/cm/signal.js +++ /dev/null @@ -1,26 +0,0 @@ -(function(root, mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - return mod(exports); - if (typeof define == "function" && define.amd) // AMD - return define(["exports"], mod); - mod((root.tern || (root.tern = {})).signal = {}); // Plain browser env -})(this, function(exports) { - function on(type, f) { - var handlers = this._handlers || (this._handlers = Object.create(null)); - (handlers[type] || (handlers[type] = [])).push(f); - } - function off(type, f) { - var arr = this._handlers && this._handlers[type]; - if (arr) for (var i = 0; i < arr.length; ++i) - if (arr[i] == f) { arr.splice(i, 1); break; } - } - function signal(type, a1, a2, a3, a4) { - var arr = this._handlers && this._handlers[type]; - if (arr) for (var i = 0; i < arr.length; ++i) arr[i].call(this, a1, a2, a3, a4); - } - - exports.mixin = function(obj) { - obj.on = on; obj.off = off; obj.signal = signal; - return obj; - }; -}); diff --git a/mix/qml/html/cm/solarized.css b/mix/qml/html/cm/solarized.css deleted file mode 100644 index df0859d25..000000000 --- a/mix/qml/html/cm/solarized.css +++ /dev/null @@ -1,196 +0,0 @@ -/* -Solarized theme for code-mirror -http://ethanschoonover.com/solarized -*/ - -/* -Solarized color pallet -http://ethanschoonover.com/solarized/img/solarized-palette.png -*/ - -.solarized.base03 { color: #002b36; } -.solarized.base02 { color: #073642; } -.solarized.base01 { color: #586e75; } -.solarized.base00 { color: #657b83; } -.solarized.base0 { color: #839496; } -.solarized.base1 { color: #93a1a1; } -.solarized.base2 { color: #eee8d5; } -.solarized.base3 { color: #fdf6e3; } -.solarized.solar-yellow, .solcurrency { color: #b58900; } -.solarized.solar-orange, .solkeywords { color: #cb4b16; } -.solarized.solar-red { color: #dc322f; } -.solarized.solar-magenta, .solstdcontract { color: #d33682; } -.solarized.solar-violet { color: #6c71c4; } -.solarized.solar-blue, .soltime { color: #268bd2; } -.solarized.solar-cyan, .soltypes { color: #2aa198; } -.solarized.solar-green, .solMisc { color: #859900; } - -/* Color scheme for code-mirror */ - -.cm-s-solarized { - line-height: 1.45em; - color-profile: sRGB; - rendering-intent: auto; -} -.cm-s-solarized.cm-s-dark { - color: #839496; - background-color: #002b36; - text-shadow: #002b36 0 1px; -} -.cm-s-solarized.cm-s-light { - background-color: #fdf6e3; - color: #657b83; - text-shadow: #eee8d5 0 1px; -} - -.cm-s-solarized .CodeMirror-widget { - text-shadow: none; -} - - -.cm-s-solarized .cm-keyword { color: #cb4b16 } -.cm-s-solarized .cm-atom { color: #d33682; } -.cm-s-solarized .cm-number { color: #d33682; } -.cm-s-solarized .cm-def { color: #2aa198; } - -.cm-s-solarized .cm-variable { color: #268bd2; } -.cm-s-solarized .cm-variable-2 { color: #b58900; } -.cm-s-solarized .cm-variable-3 { color: #6c71c4; } - -.cm-s-solarized .cm-property { color: #2aa198; } -.cm-s-solarized .cm-operator {color: #6c71c4;} - -.cm-s-solarized .cm-comment { color: #586e75; font-style:italic; } - -.cm-s-solarized .cm-string { color: #859900; } -.cm-s-solarized .cm-string-2 { color: #b58900; } - -.cm-s-solarized .cm-meta { color: #859900; } -.cm-s-solarized .cm-qualifier { color: #b58900; } -.cm-s-solarized .cm-builtin { color: #d33682; } -.cm-s-solarized .cm-bracket { color: #cb4b16; } -.cm-s-solarized .CodeMirror-matchingbracket { color: #859900; } -.cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; } -.cm-s-solarized .cm-tag { color: #93a1a1 } -.cm-s-solarized .cm-attribute { color: #2aa198; } -.cm-s-solarized .cm-header { color: #586e75; } -.cm-s-solarized .cm-quote { color: #93a1a1; } -.cm-s-solarized .cm-hr { - color: transparent; - border-top: 1px solid #586e75; - display: block; -} -.cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; } -.cm-s-solarized .cm-special { color: #6c71c4; } -.cm-s-solarized .cm-em { - color: #999; - text-decoration: underline; - text-decoration-style: dotted; -} -.cm-s-solarized .cm-strong { color: #eee; } -.cm-s-solarized .cm-error, -.cm-s-solarized .cm-invalidchar { - color: #586e75; - border-bottom: 1px dotted #dc322f; -} - -.cm-s-solarized.cm-s-dark .CodeMirror-selected { - background: #073642; -} - -.cm-s-solarized.cm-s-light .CodeMirror-selected { - background: #eee8d5; -} - -/* Editor styling */ - - - -/* Little shadow on the view-port of the buffer view */ -.cm-s-solarized.CodeMirror { - -moz-box-shadow: inset 7px 0 12px -6px #000; - -webkit-box-shadow: inset 7px 0 12px -6px #000; - box-shadow: inset 7px 0 12px -6px #000; -} - -/* Gutter border and some shadow from it */ -.cm-s-solarized .CodeMirror-gutters { - border-right: 1px solid; -} - -/* Gutter colors and line number styling based of color scheme (dark / light) */ - -/* Dark */ -.cm-s-solarized.cm-s-dark .CodeMirror-gutters { - background-color: #002b36; - border-color: #00232c; -} - -.cm-s-solarized.cm-s-dark .CodeMirror-linenumber { - text-shadow: #021014 0 -1px; -} - -/* Light */ -.cm-s-solarized.cm-s-light .CodeMirror-gutters { - background-color: #fdf6e3; - border-color: #eee8d5; -} - -/* Common */ -.cm-s-solarized .CodeMirror-linenumber { - color: #586e75; - padding: 0 5px; -} -.cm-s-solarized .CodeMirror-guttermarker-subtle { color: #586e75; } -.cm-s-solarized.cm-s-dark .CodeMirror-guttermarker { color: #ddd; } -.cm-s-solarized.cm-s-light .CodeMirror-guttermarker { color: #cb4b16; } - -.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text { - color: #586e75; -} - -.cm-s-solarized .CodeMirror-lines .CodeMirror-cursor { - border-left: 1px solid #819090; -} - -/* - -Active line. Negative margin compensates left padding of the text in the -view-port - -*/ -.cm-s-solarized.cm-s-dark .CodeMirror-activeline-background { - background: rgba(255, 255, 255, 0.10); -} -.cm-s-solarized.cm-s-light .CodeMirror-activeline-background { - background: rgba(0, 0, 0, 0.10); -} - -/* Code execution */ -.CodeMirror-exechighlight { - border-bottom: double 1px #94A2A2; -} - - -/* Error annotation */ -.CodeMirror-errorannotation { - border-bottom: 1px solid #DD3330; - margin-bottom: 4px; -} - -.CodeMirror-errorannotation-context { - font-family: monospace; - font-size: small; - color: #EEE9D5; - background: #b58900; - padding: 2px; - text-shadow: none !important; - border-top: solid 2px #063742; -} - -span.CodeMirror-selectedtext { color: #586e75 !important; } - -/* Gas Costs */ -.CodeMirror-gasCosts { - border-bottom: double 1px #2aa198; -} diff --git a/mix/qml/html/cm/solidity.js b/mix/qml/html/cm/solidity.js deleted file mode 100644 index 23f1e460c..000000000 --- a/mix/qml/html/cm/solidity.js +++ /dev/null @@ -1,172 +0,0 @@ -// based on go module -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("solidity", function(config) { - var indentUnit = config.indentUnit; - - var types = solTypes(); - var stdContract = solStdContract(); - var keywords = solKeywords(); - var atoms = solMisc(); - var builtins = solBuiltIn(); - - var isOperatorChar = /[+\-*&^%:=<>!|\/]/; - - var curPunc; - - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'" || ch == "`") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } - if (/[\d\.]/.test(ch)) { - if (ch == ".") { - stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); - } else if (ch == "0") { - stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); - } else { - stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); - } - return "number"; - } - if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - curPunc = ch; - return null; - } - if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } - if (stream.eat("/")) { - stream.skipToEnd(); - return "comment"; - } - } - if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return "operator"; - } - stream.eatWhile(/[\w\$_\xa1-\uffff]/); - var cur = stream.current(); - if (keywords.propertyIsEnumerable(cur)) { - if (cur == "case" || cur == "default") curPunc = "case"; - return "keyword"; - } - if (atoms.propertyIsEnumerable(cur)) return "atom"; - if (types.propertyIsEnumerable(cur)) return "variable-2"; - if (stdContract.propertyIsEnumerable(cur)) return "variable-3"; - if (builtins.propertyIsEnumerable(cur)) return "builtin"; - return "variable"; - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next, end = false; - while ((next = stream.next()) != null) { - if (next == quote && !escaped) {end = true; break;} - escaped = !escaped && next == "\\"; - } - if (end || !(escaped || quote == "`")) - state.tokenize = tokenBase; - return "string"; - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return "comment"; - } - - function Context(indented, column, type, align, prev) { - this.indented = indented; - this.column = column; - this.type = type; - this.align = align; - this.prev = prev; - } - function pushContext(state, col, type) { - return state.context = new Context(state.indented, col, type, null, state.context); - } - function popContext(state) { - var t = state.context.type; - if (t == ")" || t == "]" || t == "}") - state.indented = state.context.indented; - return state.context = state.context.prev; - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: null, - context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), - indented: 0, - startOfLine: true - }; - }, - - token: function(stream, state) { - var ctx = state.context; - if (stream.sol()) { - if (ctx.align == null) ctx.align = false; - state.indented = stream.indentation(); - state.startOfLine = true; - if (ctx.type == "case") ctx.type = "}"; - } - if (stream.eatSpace()) return null; - curPunc = null; - var style = (state.tokenize || tokenBase)(stream, state); - if (style == "comment") return style; - if (ctx.align == null) ctx.align = true; - - if (curPunc == "{") pushContext(state, stream.column(), "}"); - else if (curPunc == "[") pushContext(state, stream.column(), "]"); - else if (curPunc == "(") pushContext(state, stream.column(), ")"); - else if (curPunc == "case") ctx.type = "case"; - else if (curPunc == "}" && ctx.type == "}") ctx = popContext(state); - else if (curPunc == ctx.type) popContext(state); - state.startOfLine = false; - return style; - }, - - indent: function(state, textAfter) { - if (state.tokenize != tokenBase && state.tokenize != null) return 0; - var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); - if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) { - state.context.type = "}"; - return ctx.indented; - } - var closing = firstChar == ctx.type; - if (ctx.align) return ctx.column + (closing ? 0 : 1); - else return ctx.indented + (closing ? 0 : indentUnit); - }, - - electricChars: "{}):", - fold: "brace", - blockCommentStart: "/*", - blockCommentEnd: "*/", - lineComment: "//" - }; -}); - -CodeMirror.defineMIME("text/x-solidity", "solidity"); - -}); diff --git a/mix/qml/html/cm/solidityToken.js b/mix/qml/html/cm/solidityToken.js deleted file mode 100644 index fbed0287e..000000000 --- a/mix/qml/html/cm/solidityToken.js +++ /dev/null @@ -1,65 +0,0 @@ -function solCurrency() -{ - return { "wei": true, "szabo": true, "finney": true, "ether": true }; -} - -function solKeywords() -{ - return { "break": true, "case": true, "constant": true, "continue": true, "contract": true, "default": true, "delete": true, "do": true, "else": true, "event": true, "external": true, "is": true, "indexed": true, "for": true, "function": true, "if": true, "import": true, "mapping": true, "modifier": true, "new": true, "public": true, "private": true, "internal": true, "return": true, "returns": true, "struct": true, "switch": true, "var": true, "while": true, "enum": true }; -} - -function solStdContract() -{ - return { "Config": true, "NameReg": true, "CoinReg": true, "owned": true, "onlyowner": true, "named": true, "mortal": true, "coin": true }; -} - -function solTime() -{ - return { "seconds": true, "minutes": true, "hours": true, "days": true, "weeks": true, "years": true, "after": true }; -} - -function solTypes() -{ - return { "int": true, "int8": true, "int16": true, "int24": true, "int32": true, "int40": true, "int48": true, "int56": true, "int64": true, "int72": true, "int80": true, "int88": true, "int96": true, "int104": true, "int112": true, "int120": true, "int128": true, "int136": true, "int144": true, "int152": true, "int160": true, "int168": true, "int178": true, "int184": true, "int192": true, "int200": true, "int208": true, "int216": true, "int224": true, "int232": true, "int240": true, "int248": true, "int256": true, "uint": true, "uint8": true, "uint16": true, "uint24": true, "uint32": true, "uint40": true, "uint48": true, "uint56": true, "uint64": true, "uint72": true, "uint80": true, "uint88": true, "uint96": true, "uint104": true, "uint112": true, "uint120": true, "uint128": true, "uint136": true, "uint144": true, "uint152": true, "uint160": true, "uint168": true, "uint178": true, "uint184": true, "uint192": true, "uint200": true, "uint208": true, "uint216": true, "uint224": true, "uint232": true, "uint240": true, "uint248": true, "uint256": true, "bytes0": true, "bytes1": true, "bytes2": true, "bytes3": true, "bytes4": true, "bytes5": true, "bytes6": true, "bytes7": true, "bytes8": true, "bytes9": true, "bytes10": true, "bytes11": true, "bytes12": true, "bytes13": true, "bytes14": true, "bytes15": true, "bytes16": true, "bytes17": true, "bytes18": true, "bytes19": true, "bytes20": true, "bytes21": true, "bytes22": true, "bytes23": true, "bytes24": true, "bytes25": true, "bytes26": true, "bytes27": true, "bytes28": true, "bytes29": true, "bytes30": true, "bytes31": true, "bytes32": true, "bytes": true, "byte": true, "address": true, "bool": true, "string": true, "real": true, "ureal": true }; -} - -function solMisc() -{ - return { "true": true, "false": true, "null": true }; -} - -function solBuiltIn() -{ - return { "msg": true, "tx": true, "block": true, "now": true }; -} - -function solBlock() -{ - return { "coinbase": true, "difficulty": true, "gaslimit": true, "number": true, "blockhash": true, "timestamp":true }; -} - -function solMsg() -{ - return { "data": true, "gas": true, "sender": true, "sig": true, "value": true }; -} - -function solTx() -{ - return { "gasprice": true, "origin": true } -} - -function keywordsName() -{ - var keywords = {}; - keywords[solCurrency.name.toLowerCase()] = "Currency"; - keywords[solKeywords.name.toLowerCase()] = "Keyword"; - keywords[solStdContract.name.toLowerCase()] = "Contract"; - keywords[solTime.name.toLowerCase()] = "Time"; - keywords[solTypes.name.toLowerCase()] = "Type"; - keywords[solMisc.name.toLowerCase()] = "Misc"; - keywords[solBuiltIn.name.toLowerCase()] = "BuiltIn"; - keywords[solBlock.name.toLowerCase()] = "Block"; - keywords[solMsg.name.toLowerCase()] = "Message"; - keywords[solTx.name.toLowerCase()] = "Transaction"; - return keywords; -} diff --git a/mix/qml/html/cm/tern.js b/mix/qml/html/cm/tern.js deleted file mode 100644 index 78fa3bbbc..000000000 --- a/mix/qml/html/cm/tern.js +++ /dev/null @@ -1,697 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// Glue code between CodeMirror and Tern. -// -// Create a CodeMirror.TernServer to wrap an actual Tern server, -// register open documents (CodeMirror.Doc instances) with it, and -// call its methods to activate the assisting functions that Tern -// provides. -// -// Options supported (all optional): -// * defs: An array of JSON definition data structures. -// * plugins: An object mapping plugin names to configuration -// options. -// * getFile: A function(name, c) that can be used to access files in -// the project that haven't been loaded yet. Simply do c(null) to -// indicate that a file is not available. -// * fileFilter: A function(value, docName, doc) that will be applied -// to documents before passing them on to Tern. -// * switchToDoc: A function(name, doc) that should, when providing a -// multi-file view, switch the view or focus to the named file. -// * showError: A function(editor, message) that can be used to -// override the way errors are displayed. -// * completionTip: Customize the content in tooltips for completions. -// Is passed a single argument—the completion's data as returned by -// Tern—and may return a string, DOM node, or null to indicate that -// no tip should be shown. By default the docstring is shown. -// * typeTip: Like completionTip, but for the tooltips shown for type -// queries. -// * responseFilter: A function(doc, query, request, error, data) that -// will be applied to the Tern responses before treating them -// -// -// It is possible to run the Tern server in a web worker by specifying -// these additional options: -// * useWorker: Set to true to enable web worker mode. You'll probably -// want to feature detect the actual value you use here, for example -// !!window.Worker. -// * workerScript: The main script of the worker. Point this to -// wherever you are hosting worker.js from this directory. -// * workerDeps: An array of paths pointing (relative to workerScript) -// to the Acorn and Tern libraries and any Tern plugins you want to -// load. Or, if you minified those into a single script and included -// them in the workerScript, simply leave this undefined. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - // declare global: tern - - CodeMirror.TernServer = function(options) { - var self = this; - this.options = options || {}; - var plugins = this.options.plugins || (this.options.plugins = {}); - if (!plugins.doc_comment) plugins.doc_comment = true; - if (this.options.useWorker) { - this.server = new WorkerServer(this); - } else { - this.server = new tern.Server({ - getFile: function(name, c) { return getFile(self, name, c); }, - async: true, - defs: this.options.defs || [], - plugins: plugins - }); - } - this.docs = Object.create(null); - this.trackChange = function(doc, change) { trackChange(self, doc, change); }; - - this.cachedArgHints = null; - this.activeArgHints = null; - this.jumpStack = []; - - this.getHint = function(cm, c) { return hint(self, cm, c); }; - this.getHint.async = true; - }; - - CodeMirror.TernServer.prototype = { - addDoc: function(name, doc) { - var data = {doc: doc, name: name, changed: null}; - this.server.addFile(name, docValue(this, data)); - CodeMirror.on(doc, "change", this.trackChange); - return this.docs[name] = data; - }, - - delDoc: function(id) { - var found = resolveDoc(this, id); - if (!found) return; - CodeMirror.off(found.doc, "change", this.trackChange); - delete this.docs[found.name]; - this.server.delFile(found.name); - }, - - hideDoc: function(id) { - closeArgHints(this); - var found = resolveDoc(this, id); - if (found && found.changed) sendDoc(this, found); - }, - - complete: function(cm) { - cm.showHint({hint: this.getHint}); - }, - - showType: function(cm, pos, c) { showContextInfo(this, cm, pos, "type", c); }, - - showDocs: function(cm, pos, c) { showContextInfo(this, cm, pos, "documentation", c); }, - - updateArgHints: function(cm) { updateArgHints(this, cm); }, - - jumpToDef: function(cm) { jumpToDef(this, cm); }, - - jumpBack: function(cm) { jumpBack(this, cm); }, - - rename: function(cm) { rename(this, cm); }, - - selectName: function(cm) { selectName(this, cm); }, - - request: function (cm, query, c, pos) { - var self = this; - var doc = findDoc(this, cm.getDoc()); - var request = buildRequest(this, doc, query, pos); - - this.server.request(request, function (error, data) { - if (!error && self.options.responseFilter) - data = self.options.responseFilter(doc, query, request, error, data); - c(error, data); - }); - }, - - destroy: function () { - if (this.worker) { - this.worker.terminate(); - this.worker = null; - } - } - }; - - var Pos = CodeMirror.Pos; - var cls = "CodeMirror-Tern-"; - var bigDoc = 250; - - function getFile(ts, name, c) { - var buf = ts.docs[name]; - if (buf) - c(docValue(ts, buf)); - else if (ts.options.getFile) - ts.options.getFile(name, c); - else - c(null); - } - - function findDoc(ts, doc, name) { - for (var n in ts.docs) { - var cur = ts.docs[n]; - if (cur.doc == doc) return cur; - } - if (!name) for (var i = 0;; ++i) { - n = "[doc" + (i || "") + "]"; - if (!ts.docs[n]) { name = n; break; } - } - return ts.addDoc(name, doc); - } - - function resolveDoc(ts, id) { - if (typeof id == "string") return ts.docs[id]; - if (id instanceof CodeMirror) id = id.getDoc(); - if (id instanceof CodeMirror.Doc) return findDoc(ts, id); - } - - function trackChange(ts, doc, change) { - var data = findDoc(ts, doc); - - var argHints = ts.cachedArgHints; - if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0) - ts.cachedArgHints = null; - - var changed = data.changed; - if (changed == null) - data.changed = changed = {from: change.from.line, to: change.from.line}; - var end = change.from.line + (change.text.length - 1); - if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end); - if (end >= changed.to) changed.to = end + 1; - if (changed.from > change.from.line) changed.from = change.from.line; - - if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() { - if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data); - }, 200); - } - - function sendDoc(ts, doc) { - ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) { - if (error) window.console.error(error); - else doc.changed = null; - }); - } - - // Completion - - function hint(ts, cm, c) { - ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) { - if (error) return showError(ts, cm, error); - var completions = [], after = ""; - var from = data.start, to = data.end; - if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" && - cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]") - after = "\"]"; - - for (var i = 0; i < data.completions.length; ++i) { - var completion = data.completions[i], className = typeToIcon(completion.type); - if (data.guess) className += " " + cls + "guess"; - completions.push({text: completion.name + after, - displayText: completion.name, - className: className, - data: completion}); - } - - var obj = {from: from, to: to, list: completions}; - var tooltip = null; - CodeMirror.on(obj, "close", function() { remove(tooltip); }); - CodeMirror.on(obj, "update", function() { remove(tooltip); }); - CodeMirror.on(obj, "select", function(cur, node) { - remove(tooltip); - var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc; - if (content) { - tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset, - node.getBoundingClientRect().top + window.pageYOffset, content); - tooltip.className += " " + cls + "hint-doc"; - } - }); - c(obj); - }); - } - - function typeToIcon(type) { - var suffix; - if (type == "?") suffix = "unknown"; - else if (type == "number" || type == "string" || type == "bool") suffix = type; - else if (/^fn\(/.test(type)) suffix = "fn"; - else if (/^\[/.test(type)) suffix = "array"; - else suffix = "object"; - return cls + "completion " + cls + "completion-" + suffix; - } - - // Type queries - - function showContextInfo(ts, cm, pos, queryName, c) { - ts.request(cm, queryName, function(error, data) { - if (error) return showError(ts, cm, error); - if (ts.options.typeTip) { - var tip = ts.options.typeTip(data); - } else { - var tip = elt("span", null, elt("strong", null, data.type || "not found")); - if (data.doc) - tip.appendChild(document.createTextNode(" — " + data.doc)); - if (data.url) { - tip.appendChild(document.createTextNode(" ")); - var child = tip.appendChild(elt("a", null, "[docs]")); - child.href = data.url; - child.target = "_blank"; - } - } - tempTooltip(cm, tip); - if (c) c(); - }, pos); - } - - // Maintaining argument hints - - function updateArgHints(ts, cm) { - closeArgHints(ts); - - if (cm.somethingSelected()) return; - var state = cm.getTokenAt(cm.getCursor()).state; - var inner = CodeMirror.innerMode(cm.getMode(), state); - if (inner.mode.name != "javascript") return; - var lex = inner.state.lexical; - if (lex.info != "call") return; - - var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize"); - for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) { - var str = cm.getLine(line), extra = 0; - for (var pos = 0;;) { - var tab = str.indexOf("\t", pos); - if (tab == -1) break; - extra += tabSize - (tab + extra) % tabSize - 1; - pos = tab + 1; - } - ch = lex.column - extra; - if (str.charAt(ch) == "(") {found = true; break;} - } - if (!found) return; - - var start = Pos(line, ch); - var cache = ts.cachedArgHints; - if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0) - return showArgHints(ts, cm, argPos); - - ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) { - if (error || !data.type || !(/^fn\(/).test(data.type)) return; - ts.cachedArgHints = { - start: pos, - type: parseFnType(data.type), - name: data.exprName || data.name || "fn", - guess: data.guess, - doc: cm.getDoc() - }; - showArgHints(ts, cm, argPos); - }); - } - - function showArgHints(ts, cm, pos) { - closeArgHints(ts); - - var cache = ts.cachedArgHints, tp = cache.type; - var tip = elt("span", cache.guess ? cls + "fhint-guess" : null, - elt("span", cls + "fname", cache.name), "("); - for (var i = 0; i < tp.args.length; ++i) { - if (i) tip.appendChild(document.createTextNode(", ")); - var arg = tp.args[i]; - tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?")); - if (arg.type != "?") { - tip.appendChild(document.createTextNode(":\u00a0")); - tip.appendChild(elt("span", cls + "type", arg.type)); - } - } - tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")")); - if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype)); - var place = cm.cursorCoords(null, "page"); - ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip); - } - - function parseFnType(text) { - var args = [], pos = 3; - - function skipMatching(upto) { - var depth = 0, start = pos; - for (;;) { - var next = text.charAt(pos); - if (upto.test(next) && !depth) return text.slice(start, pos); - if (/[{\[\(]/.test(next)) ++depth; - else if (/[}\]\)]/.test(next)) --depth; - ++pos; - } - } - - // Parse arguments - if (text.charAt(pos) != ")") for (;;) { - var name = text.slice(pos).match(/^([^, \(\[\{]+): /); - if (name) { - pos += name[0].length; - name = name[1]; - } - args.push({name: name, type: skipMatching(/[\),]/)}); - if (text.charAt(pos) == ")") break; - pos += 2; - } - - var rettype = text.slice(pos).match(/^\) -> (.*)$/); - - return {args: args, rettype: rettype && rettype[1]}; - } - - // Moving to the definition of something - - function jumpToDef(ts, cm) { - function inner(varName) { - var req = {type: "definition", variable: varName || null}; - var doc = findDoc(ts, cm.getDoc()); - ts.server.request(buildRequest(ts, doc, req), function(error, data) { - if (error) return showError(ts, cm, error); - if (!data.file && data.url) { window.open(data.url); return; } - - if (data.file) { - var localDoc = ts.docs[data.file], found; - if (localDoc && (found = findContext(localDoc.doc, data))) { - ts.jumpStack.push({file: doc.name, - start: cm.getCursor("from"), - end: cm.getCursor("to")}); - moveTo(ts, doc, localDoc, found.start, found.end); - return; - } - } - showError(ts, cm, "Could not find a definition."); - }); - } - - if (!atInterestingExpression(cm)) - dialog(cm, "Jump to variable", function(name) { if (name) inner(name); }); - else - inner(); - } - - function jumpBack(ts, cm) { - var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file]; - if (!doc) return; - moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end); - } - - function moveTo(ts, curDoc, doc, start, end) { - doc.doc.setSelection(start, end); - if (curDoc != doc && ts.options.switchToDoc) { - closeArgHints(ts); - ts.options.switchToDoc(doc.name, doc.doc); - } - } - - // The {line,ch} representation of positions makes this rather awkward. - function findContext(doc, data) { - var before = data.context.slice(0, data.contextOffset).split("\n"); - var startLine = data.start.line - (before.length - 1); - var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length); - - var text = doc.getLine(startLine).slice(start.ch); - for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur) - text += "\n" + doc.getLine(cur); - if (text.slice(0, data.context.length) == data.context) return data; - - var cursor = doc.getSearchCursor(data.context, 0, false); - var nearest, nearestDist = Infinity; - while (cursor.findNext()) { - var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000; - if (!dist) dist = Math.abs(from.ch - start.ch); - if (dist < nearestDist) { nearest = from; nearestDist = dist; } - } - if (!nearest) return null; - - if (before.length == 1) - nearest.ch += before[0].length; - else - nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length); - if (data.start.line == data.end.line) - var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch)); - else - var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch); - return {start: nearest, end: end}; - } - - function atInterestingExpression(cm) { - var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos); - if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false; - return /[\w)\]]/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1)); - } - - // Variable renaming - - function rename(ts, cm) { - var token = cm.getTokenAt(cm.getCursor()); - if (!/\w/.test(token.string)) return showError(ts, cm, "Not at a variable"); - dialog(cm, "New name for " + token.string, function(newName) { - ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) { - if (error) return showError(ts, cm, error); - applyChanges(ts, data.changes); - }); - }); - } - - function selectName(ts, cm) { - var name = findDoc(ts, cm.doc).name; - ts.request(cm, {type: "refs"}, function(error, data) { - if (error) return showError(ts, cm, error); - var ranges = [], cur = 0; - for (var i = 0; i < data.refs.length; i++) { - var ref = data.refs[i]; - if (ref.file == name) { - ranges.push({anchor: ref.start, head: ref.end}); - if (cmpPos(cur, ref.start) >= 0 && cmpPos(cur, ref.end) <= 0) - cur = ranges.length - 1; - } - } - cm.setSelections(ranges, cur); - }); - } - - var nextChangeOrig = 0; - function applyChanges(ts, changes) { - var perFile = Object.create(null); - for (var i = 0; i < changes.length; ++i) { - var ch = changes[i]; - (perFile[ch.file] || (perFile[ch.file] = [])).push(ch); - } - for (var file in perFile) { - var known = ts.docs[file], chs = perFile[file];; - if (!known) continue; - chs.sort(function(a, b) { return cmpPos(b.start, a.start); }); - var origin = "*rename" + (++nextChangeOrig); - for (var i = 0; i < chs.length; ++i) { - var ch = chs[i]; - known.doc.replaceRange(ch.text, ch.start, ch.end, origin); - } - } - } - - // Generic request-building helper - - function buildRequest(ts, doc, query, pos) { - var files = [], offsetLines = 0, allowFragments = !query.fullDocs; - if (!allowFragments) delete query.fullDocs; - if (typeof query == "string") query = {type: query}; - query.lineCharPositions = true; - if (query.end == null) { - query.end = pos || doc.doc.getCursor("end"); - if (doc.doc.somethingSelected()) - query.start = doc.doc.getCursor("start"); - } - var startPos = query.start || query.end; - - if (doc.changed) { - if (doc.doc.lineCount() > bigDoc && allowFragments !== false && - doc.changed.to - doc.changed.from < 100 && - doc.changed.from <= startPos.line && doc.changed.to > query.end.line) { - files.push(getFragmentAround(doc, startPos, query.end)); - query.file = "#0"; - var offsetLines = files[0].offsetLines; - if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch); - query.end = Pos(query.end.line - offsetLines, query.end.ch); - } else { - files.push({type: "full", - name: doc.name, - text: docValue(ts, doc)}); - query.file = doc.name; - doc.changed = null; - } - } else { - query.file = doc.name; - } - for (var name in ts.docs) { - var cur = ts.docs[name]; - if (cur.changed && cur != doc) { - files.push({type: "full", name: cur.name, text: docValue(ts, cur)}); - cur.changed = null; - } - } - - return {query: query, files: files}; - } - - function getFragmentAround(data, start, end) { - var doc = data.doc; - var minIndent = null, minLine = null, endLine, tabSize = 4; - for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) { - var line = doc.getLine(p), fn = line.search(/\bfunction\b/); - if (fn < 0) continue; - var indent = CodeMirror.countColumn(line, null, tabSize); - if (minIndent != null && minIndent <= indent) continue; - minIndent = indent; - minLine = p; - } - if (minLine == null) minLine = min; - var max = Math.min(doc.lastLine(), end.line + 20); - if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize)) - endLine = max; - else for (endLine = end.line + 1; endLine < max; ++endLine) { - var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize); - if (indent <= minIndent) break; - } - var from = Pos(minLine, 0); - - return {type: "part", - name: data.name, - offsetLines: from.line, - text: doc.getRange(from, Pos(endLine, 0))}; - } - - // Generic utilities - - var cmpPos = CodeMirror.cmpPos; - - function elt(tagname, cls /*, ... elts*/) { - var e = document.createElement(tagname); - if (cls) e.className = cls; - for (var i = 2; i < arguments.length; ++i) { - var elt = arguments[i]; - if (typeof elt == "string") elt = document.createTextNode(elt); - e.appendChild(elt); - } - return e; - } - - function dialog(cm, text, f) { - if (cm.openDialog) - cm.openDialog(text + ": ", f); - else - f(prompt(text, "")); - } - - // Tooltips - - function tempTooltip(cm, content) { - if (cm.state.ternTooltip) remove(cm.state.ternTooltip); - var where = cm.cursorCoords(); - var tip = cm.state.ternTooltip = makeTooltip(where.right + 1, where.bottom, content); - function maybeClear() { - old = true; - if (!mouseOnTip) clear(); - } - function clear() { - cm.state.ternTooltip = null; - if (!tip.parentNode) return; - cm.off("cursorActivity", clear); - cm.off('blur', clear); - cm.off('scroll', clear); - fadeOut(tip); - } - var mouseOnTip = false, old = false; - CodeMirror.on(tip, "mousemove", function() { mouseOnTip = true; }); - CodeMirror.on(tip, "mouseout", function(e) { - if (!CodeMirror.contains(tip, e.relatedTarget || e.toElement)) { - if (old) clear(); - else mouseOnTip = false; - } - }); - setTimeout(maybeClear, 1700); - cm.on("cursorActivity", clear); - cm.on('blur', clear); - cm.on('scroll', clear); - } - - function makeTooltip(x, y, content) { - var node = elt("div", cls + "tooltip", content); - node.style.left = x + "px"; - node.style.top = y + "px"; - document.body.appendChild(node); - return node; - } - - function remove(node) { - var p = node && node.parentNode; - if (p) p.removeChild(node); - } - - function fadeOut(tooltip) { - tooltip.style.opacity = "0"; - setTimeout(function() { remove(tooltip); }, 1100); - } - - function showError(ts, cm, msg) { - if (ts.options.showError) - ts.options.showError(cm, msg); - else - tempTooltip(cm, String(msg)); - } - - function closeArgHints(ts) { - if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; } - } - - function docValue(ts, doc) { - var val = doc.doc.getValue(); - if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc); - return val; - } - - // Worker wrapper - - function WorkerServer(ts) { - var worker = ts.worker = new Worker(ts.options.workerScript); - worker.postMessage({type: "init", - defs: ts.options.defs, - plugins: ts.options.plugins, - scripts: ts.options.workerDeps}); - var msgId = 0, pending = {}; - - function send(data, c) { - if (c) { - data.id = ++msgId; - pending[msgId] = c; - } - worker.postMessage(data); - } - worker.onmessage = function(e) { - var data = e.data; - if (data.type == "getFile") { - getFile(ts, data.name, function(err, text) { - send({type: "getFile", err: String(err), text: text, id: data.id}); - }); - } else if (data.type == "debug") { - window.console.log(data.message); - } else if (data.id && pending[data.id]) { - pending[data.id](data.err, data.body); - delete pending[data.id]; - } - }; - worker.onerror = function(e) { - for (var id in pending) pending[id](e); - pending = {}; - }; - - this.addFile = function(name, text) { send({type: "add", name: name, text: text}); }; - this.delFile = function(name) { send({type: "del", name: name}); }; - this.request = function(body, c) { send({type: "req", body: body}, c); }; - } -}); diff --git a/mix/qml/html/cm/ternserver.js b/mix/qml/html/cm/ternserver.js deleted file mode 100644 index 439ae3f3b..000000000 --- a/mix/qml/html/cm/ternserver.js +++ /dev/null @@ -1,994 +0,0 @@ -// The Tern server object - -// A server is a stateful object that manages the analysis for a -// project, and defines an interface for querying the code in the -// project. - -(function(root, mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - return mod(exports, require("./infer"), require("./signal"), - require("acorn/acorn"), require("acorn/util/walk")); - if (typeof define == "function" && define.amd) // AMD - return define(["exports", "./infer", "./signal", "acorn/acorn", "acorn/util/walk"], mod); - mod(root.tern || (root.tern = {}), tern, tern.signal, acorn, acorn.walk); // Plain browser env -})(this, function(exports, infer, signal, acorn, walk) { - "use strict"; - - var plugins = Object.create(null); - exports.registerPlugin = function(name, init) { plugins[name] = init; }; - - var defaultOptions = exports.defaultOptions = { - debug: false, - async: false, - getFile: function(_f, c) { if (this.async) c(null, null); }, - defs: [], - plugins: {}, - fetchTimeout: 1000, - dependencyBudget: 20000, - reuseInstances: true, - stripCRs: false - }; - - var queryTypes = { - completions: { - takesFile: true, - run: findCompletions - }, - properties: { - run: findProperties - }, - type: { - takesFile: true, - run: findTypeAt - }, - documentation: { - takesFile: true, - run: findDocs - }, - definition: { - takesFile: true, - run: findDef - }, - refs: { - takesFile: true, - fullFile: true, - run: findRefs - }, - rename: { - takesFile: true, - fullFile: true, - run: buildRename - }, - files: { - run: listFiles - } - }; - - exports.defineQueryType = function(name, desc) { queryTypes[name] = desc; }; - - function File(name, parent) { - this.name = name; - this.parent = parent; - this.scope = this.text = this.ast = this.lineOffsets = null; - } - File.prototype.asLineChar = function(pos) { return asLineChar(this, pos); }; - - function updateText(file, text, srv) { - file.text = srv.options.stripCRs ? text.replace(/\r\n/g, "\n") : text; - infer.withContext(srv.cx, function() { - file.ast = infer.parse(file.text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); - }); - file.lineOffsets = null; - } - - var Server = exports.Server = function(options) { - this.cx = null; - this.options = options || {}; - for (var o in defaultOptions) if (!options.hasOwnProperty(o)) - options[o] = defaultOptions[o]; - - this.handlers = Object.create(null); - this.files = []; - this.fileMap = Object.create(null); - this.needsPurge = []; - this.budgets = Object.create(null); - this.uses = 0; - this.pending = 0; - this.asyncError = null; - this.passes = Object.create(null); - - this.defs = options.defs.slice(0); - for (var plugin in options.plugins) if (options.plugins.hasOwnProperty(plugin) && plugin in plugins) { - var init = plugins[plugin](this, options.plugins[plugin]); - if (init && init.defs) { - if (init.loadFirst) this.defs.unshift(init.defs); - else this.defs.push(init.defs); - } - if (init && init.passes) for (var type in init.passes) if (init.passes.hasOwnProperty(type)) - (this.passes[type] || (this.passes[type] = [])).push(init.passes[type]); - } - - this.reset(); - }; - Server.prototype = signal.mixin({ - addFile: function(name, /*optional*/ text, parent) { - // Don't crash when sloppy plugins pass non-existent parent ids - if (parent && !(parent in this.fileMap)) parent = null; - ensureFile(this, name, parent, text); - }, - delFile: function(name) { - var file = this.findFile(name); - if (file) { - this.needsPurge.push(file.name); - this.files.splice(this.files.indexOf(file), 1); - delete this.fileMap[name]; - } - }, - reset: function() { - this.signal("reset"); - this.cx = new infer.Context(this.defs, this); - this.uses = 0; - this.budgets = Object.create(null); - for (var i = 0; i < this.files.length; ++i) { - var file = this.files[i]; - file.scope = null; - } - }, - - request: function(doc, c) { - var inv = invalidDoc(doc); - if (inv) return c(inv); - - var self = this; - doRequest(this, doc, function(err, data) { - c(err, data); - if (self.uses > 40) { - self.reset(); - analyzeAll(self, null, function(){}); - } - }); - }, - - findFile: function(name) { - return this.fileMap[name]; - }, - - flush: function(c) { - var cx = this.cx; - analyzeAll(this, null, function(err) { - if (err) return c(err); - infer.withContext(cx, c); - }); - }, - - startAsyncAction: function() { - ++this.pending; - }, - finishAsyncAction: function(err) { - if (err) this.asyncError = err; - if (--this.pending === 0) this.signal("everythingFetched"); - } - }); - - function doRequest(srv, doc, c) { - if (doc.query && !queryTypes.hasOwnProperty(doc.query.type)) - return c("No query type '" + doc.query.type + "' defined"); - - var query = doc.query; - // Respond as soon as possible when this just uploads files - if (!query) c(null, {}); - - var files = doc.files || []; - if (files.length) ++srv.uses; - for (var i = 0; i < files.length; ++i) { - var file = files[i]; - if (file.type == "delete") - srv.delFile(file.name); - else - ensureFile(srv, file.name, null, file.type == "full" ? file.text : null); - } - - var timeBudget = typeof doc.timeout == "number" ? [doc.timeout] : null; - if (!query) { - analyzeAll(srv, timeBudget, function(){}); - return; - } - - var queryType = queryTypes[query.type]; - if (queryType.takesFile) { - if (typeof query.file != "string") return c(".query.file must be a string"); - if (!/^#/.test(query.file)) ensureFile(srv, query.file, null); - } - - analyzeAll(srv, timeBudget, function(err) { - if (err) return c(err); - var file = queryType.takesFile && resolveFile(srv, files, query.file); - if (queryType.fullFile && file.type == "part") - return c("Can't run a " + query.type + " query on a file fragment"); - - function run() { - var result; - try { - result = queryType.run(srv, query, file); - } catch (e) { - if (srv.options.debug && e.name != "TernError") console.error(e.stack); - return c(e); - } - c(null, result); - } - infer.withContext(srv.cx, timeBudget ? function() { infer.withTimeout(timeBudget[0], run); } : run); - }); - } - - function analyzeFile(srv, file) { - infer.withContext(srv.cx, function() { - file.scope = srv.cx.topScope; - srv.signal("beforeLoad", file); - infer.analyze(file.ast, file.name, file.scope, srv.passes); - srv.signal("afterLoad", file); - }); - return file; - } - - function ensureFile(srv, name, parent, text) { - var known = srv.findFile(name); - if (known) { - if (text != null) { - if (known.scope) { - srv.needsPurge.push(name); - known.scope = null; - } - updateText(known, text, srv); - } - if (parentDepth(srv, known.parent) > parentDepth(srv, parent)) { - known.parent = parent; - if (known.excluded) known.excluded = null; - } - return; - } - - var file = new File(name, parent); - srv.files.push(file); - srv.fileMap[name] = file; - if (text != null) { - updateText(file, text, srv); - } else if (srv.options.async) { - srv.startAsyncAction(); - srv.options.getFile(name, function(err, text) { - updateText(file, text || "", srv); - srv.finishAsyncAction(err); - }); - } else { - updateText(file, srv.options.getFile(name) || "", srv); - } - } - - function fetchAll(srv, c) { - var done = true, returned = false; - srv.files.forEach(function(file) { - if (file.text != null) return; - if (srv.options.async) { - done = false; - srv.options.getFile(file.name, function(err, text) { - if (err && !returned) { returned = true; return c(err); } - updateText(file, text || "", srv); - fetchAll(srv, c); - }); - } else { - try { - updateText(file, srv.options.getFile(file.name) || "", srv); - } catch (e) { return c(e); } - } - }); - if (done) c(); - } - - function waitOnFetch(srv, timeBudget, c) { - var done = function() { - srv.off("everythingFetched", done); - clearTimeout(timeout); - analyzeAll(srv, timeBudget, c); - }; - srv.on("everythingFetched", done); - var timeout = setTimeout(done, srv.options.fetchTimeout); - } - - function analyzeAll(srv, timeBudget, c) { - if (srv.pending) return waitOnFetch(srv, timeBudget, c); - - var e = srv.fetchError; - if (e) { srv.fetchError = null; return c(e); } - - if (srv.needsPurge.length > 0) infer.withContext(srv.cx, function() { - infer.purge(srv.needsPurge); - srv.needsPurge.length = 0; - }); - - var done = true; - // The second inner loop might add new files. The outer loop keeps - // repeating both inner loops until all files have been looked at. - for (var i = 0; i < srv.files.length;) { - var toAnalyze = []; - for (; i < srv.files.length; ++i) { - var file = srv.files[i]; - if (file.text == null) done = false; - else if (file.scope == null && !file.excluded) toAnalyze.push(file); - } - toAnalyze.sort(function(a, b) { - return parentDepth(srv, a.parent) - parentDepth(srv, b.parent); - }); - for (var j = 0; j < toAnalyze.length; j++) { - var file = toAnalyze[j]; - if (file.parent && !chargeOnBudget(srv, file)) { - file.excluded = true; - } else if (timeBudget) { - var startTime = +new Date; - infer.withTimeout(timeBudget[0], function() { analyzeFile(srv, file); }); - timeBudget[0] -= +new Date - startTime; - } else { - analyzeFile(srv, file); - } - } - } - if (done) c(); - else waitOnFetch(srv, timeBudget, c); - } - - function firstLine(str) { - var end = str.indexOf("\n"); - if (end < 0) return str; - return str.slice(0, end); - } - - function findMatchingPosition(line, file, near) { - var pos = Math.max(0, near - 500), closest = null; - if (!/^\s*$/.test(line)) for (;;) { - var found = file.indexOf(line, pos); - if (found < 0 || found > near + 500) break; - if (closest == null || Math.abs(closest - near) > Math.abs(found - near)) - closest = found; - pos = found + line.length; - } - return closest; - } - - function scopeDepth(s) { - for (var i = 0; s; ++i, s = s.prev) {} - return i; - } - - function ternError(msg) { - var err = new Error(msg); - err.name = "TernError"; - return err; - } - - function resolveFile(srv, localFiles, name) { - var isRef = name.match(/^#(\d+)$/); - if (!isRef) return srv.findFile(name); - - var file = localFiles[isRef[1]]; - if (!file || file.type == "delete") throw ternError("Reference to unknown file " + name); - if (file.type == "full") return srv.findFile(file.name); - - // This is a partial file - - var realFile = file.backing = srv.findFile(file.name); - var offset = file.offset; - if (file.offsetLines) offset = {line: file.offsetLines, ch: 0}; - file.offset = offset = resolvePos(realFile, file.offsetLines == null ? file.offset : {line: file.offsetLines, ch: 0}, true); - var line = firstLine(file.text); - var foundPos = findMatchingPosition(line, realFile.text, offset); - var pos = foundPos == null ? Math.max(0, realFile.text.lastIndexOf("\n", offset)) : foundPos; - var inObject, atFunction; - - infer.withContext(srv.cx, function() { - infer.purge(file.name, pos, pos + file.text.length); - - var text = file.text, m; - if (m = text.match(/(?:"([^"]*)"|([\w$]+))\s*:\s*function\b/)) { - var objNode = walk.findNodeAround(file.backing.ast, pos, "ObjectExpression"); - if (objNode && objNode.node.objType) - inObject = {type: objNode.node.objType, prop: m[2] || m[1]}; - } - if (foundPos && (m = line.match(/^(.*?)\bfunction\b/))) { - var cut = m[1].length, white = ""; - for (var i = 0; i < cut; ++i) white += " "; - text = white + text.slice(cut); - atFunction = true; - } - - var scopeStart = infer.scopeAt(realFile.ast, pos, realFile.scope); - var scopeEnd = infer.scopeAt(realFile.ast, pos + text.length, realFile.scope); - var scope = file.scope = scopeDepth(scopeStart) < scopeDepth(scopeEnd) ? scopeEnd : scopeStart; - file.ast = infer.parse(text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); - infer.analyze(file.ast, file.name, scope, srv.passes); - - // This is a kludge to tie together the function types (if any) - // outside and inside of the fragment, so that arguments and - // return values have some information known about them. - tieTogether: if (inObject || atFunction) { - var newInner = infer.scopeAt(file.ast, line.length, scopeStart); - if (!newInner.fnType) break tieTogether; - if (inObject) { - var prop = inObject.type.getProp(inObject.prop); - prop.addType(newInner.fnType); - } else if (atFunction) { - var inner = infer.scopeAt(realFile.ast, pos + line.length, realFile.scope); - if (inner == scopeStart || !inner.fnType) break tieTogether; - var fOld = inner.fnType, fNew = newInner.fnType; - if (!fNew || (fNew.name != fOld.name && fOld.name)) break tieTogether; - for (var i = 0, e = Math.min(fOld.args.length, fNew.args.length); i < e; ++i) - fOld.args[i].propagate(fNew.args[i]); - fOld.self.propagate(fNew.self); - fNew.retval.propagate(fOld.retval); - } - } - }); - return file; - } - - // Budget management - - function astSize(node) { - var size = 0; - walk.simple(node, {Expression: function() { ++size; }}); - return size; - } - - function parentDepth(srv, parent) { - var depth = 0; - while (parent) { - parent = srv.findFile(parent).parent; - ++depth; - } - return depth; - } - - function budgetName(srv, file) { - for (;;) { - var parent = srv.findFile(file.parent); - if (!parent.parent) break; - file = parent; - } - return file.name; - } - - function chargeOnBudget(srv, file) { - var bName = budgetName(srv, file); - var size = astSize(file.ast); - var known = srv.budgets[bName]; - if (known == null) - known = srv.budgets[bName] = srv.options.dependencyBudget; - if (known < size) return false; - srv.budgets[bName] = known - size; - return true; - } - - // Query helpers - - function isPosition(val) { - return typeof val == "number" || typeof val == "object" && - typeof val.line == "number" && typeof val.ch == "number"; - } - - // Baseline query document validation - function invalidDoc(doc) { - if (doc.query) { - if (typeof doc.query.type != "string") return ".query.type must be a string"; - if (doc.query.start && !isPosition(doc.query.start)) return ".query.start must be a position"; - if (doc.query.end && !isPosition(doc.query.end)) return ".query.end must be a position"; - } - if (doc.files) { - if (!Array.isArray(doc.files)) return "Files property must be an array"; - for (var i = 0; i < doc.files.length; ++i) { - var file = doc.files[i]; - if (typeof file != "object") return ".files[n] must be objects"; - else if (typeof file.name != "string") return ".files[n].name must be a string"; - else if (file.type == "delete") continue; - else if (typeof file.text != "string") return ".files[n].text must be a string"; - else if (file.type == "part") { - if (!isPosition(file.offset) && typeof file.offsetLines != "number") - return ".files[n].offset must be a position"; - } else if (file.type != "full") return ".files[n].type must be \"full\" or \"part\""; - } - } - } - - var offsetSkipLines = 25; - - function findLineStart(file, line) { - var text = file.text, offsets = file.lineOffsets || (file.lineOffsets = [0]); - var pos = 0, curLine = 0; - var storePos = Math.min(Math.floor(line / offsetSkipLines), offsets.length - 1); - var pos = offsets[storePos], curLine = storePos * offsetSkipLines; - - while (curLine < line) { - ++curLine; - pos = text.indexOf("\n", pos) + 1; - if (pos === 0) return null; - if (curLine % offsetSkipLines === 0) offsets.push(pos); - } - return pos; - } - - var resolvePos = exports.resolvePos = function(file, pos, tolerant) { - if (typeof pos != "number") { - var lineStart = findLineStart(file, pos.line); - if (lineStart == null) { - if (tolerant) pos = file.text.length; - else throw ternError("File doesn't contain a line " + pos.line); - } else { - pos = lineStart + pos.ch; - } - } - if (pos > file.text.length) { - if (tolerant) pos = file.text.length; - else throw ternError("Position " + pos + " is outside of file."); - } - return pos; - }; - - function asLineChar(file, pos) { - if (!file) return {line: 0, ch: 0}; - var offsets = file.lineOffsets || (file.lineOffsets = [0]); - var text = file.text, line, lineStart; - for (var i = offsets.length - 1; i >= 0; --i) if (offsets[i] <= pos) { - line = i * offsetSkipLines; - lineStart = offsets[i]; - } - for (;;) { - var eol = text.indexOf("\n", lineStart); - if (eol >= pos || eol < 0) break; - lineStart = eol + 1; - ++line; - } - return {line: line, ch: pos - lineStart}; - } - - var outputPos = exports.outputPos = function(query, file, pos) { - if (query.lineCharPositions) { - var out = asLineChar(file, pos); - if (file.type == "part") - out.line += file.offsetLines != null ? file.offsetLines : asLineChar(file.backing, file.offset).line; - return out; - } else { - return pos + (file.type == "part" ? file.offset : 0); - } - }; - - // Delete empty fields from result objects - function clean(obj) { - for (var prop in obj) if (obj[prop] == null) delete obj[prop]; - return obj; - } - function maybeSet(obj, prop, val) { - if (val != null) obj[prop] = val; - } - - // Built-in query types - - function compareCompletions(a, b) { - if (typeof a != "string") { a = a.name; b = b.name; } - var aUp = /^[A-Z]/.test(a), bUp = /^[A-Z]/.test(b); - if (aUp == bUp) return a < b ? -1 : a == b ? 0 : 1; - else return aUp ? 1 : -1; - } - - function isStringAround(node, start, end) { - return node.type == "Literal" && typeof node.value == "string" && - node.start == start - 1 && node.end <= end + 1; - } - - function pointInProp(objNode, point) { - for (var i = 0; i < objNode.properties.length; i++) { - var curProp = objNode.properties[i]; - if (curProp.key.start <= point && curProp.key.end >= point) - return curProp; - } - } - - var jsKeywords = ("break do instanceof typeof case else new var " + - "catch finally return void continue for switch while debugger " + - "function this with default if throw delete in try").split(" "); - - function findCompletions(srv, query, file) { - if (query.end == null) throw ternError("missing .query.end field"); - if (srv.passes.completion) for (var i = 0; i < srv.passes.completion.length; i++) { - var result = srv.passes.completion[i](file, query); - if (result) return result; - } - - var wordStart = resolvePos(file, query.end), wordEnd = wordStart, text = file.text; - while (wordStart && acorn.isIdentifierChar(text.charCodeAt(wordStart - 1))) --wordStart; - if (query.expandWordForward !== false) - while (wordEnd < text.length && acorn.isIdentifierChar(text.charCodeAt(wordEnd))) ++wordEnd; - var word = text.slice(wordStart, wordEnd), completions = [], ignoreObj; - if (query.caseInsensitive) word = word.toLowerCase(); - var wrapAsObjs = query.types || query.depths || query.docs || query.urls || query.origins; - - function gather(prop, obj, depth, addInfo) { - // 'hasOwnProperty' and such are usually just noise, leave them - // out when no prefix is provided. - if (query.omitObjectPrototype !== false && obj == srv.cx.protos.Object && !word) return; - if (query.filter !== false && word && - (query.caseInsensitive ? prop.toLowerCase() : prop).indexOf(word) !== 0) return; - if (ignoreObj && ignoreObj.props[prop]) return; - for (var i = 0; i < completions.length; ++i) { - var c = completions[i]; - if ((wrapAsObjs ? c.name : c) == prop) return; - } - var rec = wrapAsObjs ? {name: prop} : prop; - completions.push(rec); - - if (obj && (query.types || query.docs || query.urls || query.origins)) { - var val = obj.props[prop]; - infer.resetGuessing(); - var type = val.getType(); - rec.guess = infer.didGuess(); - if (query.types) - rec.type = infer.toString(val); - if (query.docs) - maybeSet(rec, "doc", val.doc || type && type.doc); - if (query.urls) - maybeSet(rec, "url", val.url || type && type.url); - if (query.origins) - maybeSet(rec, "origin", val.origin || type && type.origin); - } - if (query.depths) rec.depth = depth; - if (wrapAsObjs && addInfo) addInfo(rec); - } - - var hookname, prop, objType, isKey; - - var exprAt = infer.findExpressionAround(file.ast, null, wordStart, file.scope); - var memberExpr, objLit; - // Decide whether this is an object property, either in a member - // expression or an object literal. - if (exprAt) { - if (exprAt.node.type == "MemberExpression" && exprAt.node.object.end < wordStart) { - memberExpr = exprAt; - } else if (isStringAround(exprAt.node, wordStart, wordEnd)) { - var parent = infer.parentNode(exprAt.node, file.ast); - if (parent.type == "MemberExpression" && parent.property == exprAt.node) - memberExpr = {node: parent, state: exprAt.state}; - } else if (exprAt.node.type == "ObjectExpression") { - var objProp = pointInProp(exprAt.node, wordEnd); - if (objProp) { - objLit = exprAt; - prop = isKey = objProp.key.name; - } else if (!word && !/:\s*$/.test(file.text.slice(0, wordStart))) { - objLit = exprAt; - prop = isKey = true; - } - } - } - - if (objLit) { - // Since we can't use the type of the literal itself to complete - // its properties (it doesn't contain the information we need), - // we have to try asking the surrounding expression for type info. - objType = infer.typeFromContext(file.ast, objLit); - ignoreObj = objLit.node.objType; - } else if (memberExpr) { - prop = memberExpr.node.property; - prop = prop.type == "Literal" ? prop.value.slice(1) : prop.name; - memberExpr.node = memberExpr.node.object; - objType = infer.expressionType(memberExpr); - } else if (text.charAt(wordStart - 1) == ".") { - var pathStart = wordStart - 1; - while (pathStart && (text.charAt(pathStart - 1) == "." || acorn.isIdentifierChar(text.charCodeAt(pathStart - 1)))) pathStart--; - var path = text.slice(pathStart, wordStart - 1); - if (path) { - objType = infer.def.parsePath(path, file.scope).getObjType(); - prop = word; - } - } - - if (prop != null) { - srv.cx.completingProperty = prop; - - if (objType) infer.forAllPropertiesOf(objType, gather); - - if (!completions.length && query.guess !== false && objType && objType.guessProperties) - objType.guessProperties(function(p, o, d) {if (p != prop && p != "✖") gather(p, o, d);}); - if (!completions.length && word.length >= 2 && query.guess !== false) - for (var prop in srv.cx.props) gather(prop, srv.cx.props[prop][0], 0); - hookname = "memberCompletion"; - } else { - infer.forAllLocalsAt(file.ast, wordStart, file.scope, gather); - if (query.includeKeywords) jsKeywords.forEach(function(kw) { - gather(kw, null, 0, function(rec) { rec.isKeyword = true; }); - }); - hookname = "variableCompletion"; - } - if (srv.passes[hookname]) - srv.passes[hookname].forEach(function(hook) {hook(file, wordStart, wordEnd, gather);}); - - if (query.sort !== false) completions.sort(compareCompletions); - srv.cx.completingProperty = null; - - return {start: outputPos(query, file, wordStart), - end: outputPos(query, file, wordEnd), - isProperty: !!prop, - isObjectKey: !!isKey, - completions: completions}; - } - - function findProperties(srv, query) { - var prefix = query.prefix, found = []; - for (var prop in srv.cx.props) - if (prop != "" && (!prefix || prop.indexOf(prefix) === 0)) found.push(prop); - if (query.sort !== false) found.sort(compareCompletions); - return {completions: found}; - } - - var findExpr = exports.findQueryExpr = function(file, query, wide) { - if (query.end == null) throw ternError("missing .query.end field"); - - if (query.variable) { - var scope = infer.scopeAt(file.ast, resolvePos(file, query.end), file.scope); - return {node: {type: "Identifier", name: query.variable, start: query.end, end: query.end + 1}, - state: scope}; - } else { - var start = query.start && resolvePos(file, query.start), end = resolvePos(file, query.end); - var expr = infer.findExpressionAt(file.ast, start, end, file.scope); - if (expr) return expr; - expr = infer.findExpressionAround(file.ast, start, end, file.scope); - if (expr && (expr.node.type == "ObjectExpression" || wide || - (start == null ? end : start) - expr.node.start < 20 || expr.node.end - end < 20)) - return expr; - return null; - } - }; - - function findExprOrThrow(file, query, wide) { - var expr = findExpr(file, query, wide); - if (expr) return expr; - throw ternError("No expression at the given position."); - } - - function ensureObj(tp) { - if (!tp || !(tp = tp.getType()) || !(tp instanceof infer.Obj)) return null; - return tp; - } - - function findExprType(srv, query, file, expr) { - var type; - if (expr) { - infer.resetGuessing(); - type = infer.expressionType(expr); - } - if (srv.passes["typeAt"]) { - var pos = resolvePos(file, query.end); - srv.passes["typeAt"].forEach(function(hook) { - type = hook(file, pos, expr, type); - }); - } - if (!type) throw ternError("No type found at the given position."); - - var objProp; - if (expr.node.type == "ObjectExpression" && query.end != null && - (objProp = pointInProp(expr.node, resolvePos(file, query.end)))) { - var name = objProp.key.name; - var fromCx = ensureObj(infer.typeFromContext(file.ast, expr)); - if (fromCx && fromCx.hasProp(name)) { - type = fromCx.hasProp(name); - } else { - var fromLocal = ensureObj(type); - if (fromLocal && fromLocal.hasProp(name)) - type = fromLocal.hasProp(name); - } - } - return type; - }; - - function findTypeAt(srv, query, file) { - var expr = findExpr(file, query), exprName; - var type = findExprType(srv, query, file, expr), exprType = type; - if (query.preferFunction) - type = type.getFunctionType() || type.getType(); - else - type = type.getType(); - - if (expr) { - if (expr.node.type == "Identifier") - exprName = expr.node.name; - else if (expr.node.type == "MemberExpression" && !expr.node.computed) - exprName = expr.node.property.name; - } - - if (query.depth != null && typeof query.depth != "number") - throw ternError(".query.depth must be a number"); - - var result = {guess: infer.didGuess(), - type: infer.toString(exprType, query.depth), - name: type && type.name, - exprName: exprName}; - if (type) storeTypeDocs(type, result); - if (!result.doc && exprType.doc) result.doc = exprType.doc; - - return clean(result); - } - - function findDocs(srv, query, file) { - var expr = findExpr(file, query); - var type = findExprType(srv, query, file, expr); - var result = {url: type.url, doc: type.doc, type: infer.toString(type)}; - var inner = type.getType(); - if (inner) storeTypeDocs(inner, result); - return clean(result); - } - - function storeTypeDocs(type, out) { - if (!out.url) out.url = type.url; - if (!out.doc) out.doc = type.doc; - if (!out.origin) out.origin = type.origin; - var ctor, boring = infer.cx().protos; - if (!out.url && !out.doc && type.proto && (ctor = type.proto.hasCtor) && - type.proto != boring.Object && type.proto != boring.Function && type.proto != boring.Array) { - out.url = ctor.url; - out.doc = ctor.doc; - } - } - - var getSpan = exports.getSpan = function(obj) { - if (!obj.origin) return; - if (obj.originNode) { - var node = obj.originNode; - if (/^Function/.test(node.type) && node.id) node = node.id; - return {origin: obj.origin, node: node}; - } - if (obj.span) return {origin: obj.origin, span: obj.span}; - }; - - var storeSpan = exports.storeSpan = function(srv, query, span, target) { - target.origin = span.origin; - if (span.span) { - var m = /^(\d+)\[(\d+):(\d+)\]-(\d+)\[(\d+):(\d+)\]$/.exec(span.span); - target.start = query.lineCharPositions ? {line: Number(m[2]), ch: Number(m[3])} : Number(m[1]); - target.end = query.lineCharPositions ? {line: Number(m[5]), ch: Number(m[6])} : Number(m[4]); - } else { - var file = srv.findFile(span.origin); - target.start = outputPos(query, file, span.node.start); - target.end = outputPos(query, file, span.node.end); - } - }; - - function findDef(srv, query, file) { - var expr = findExpr(file, query); - var type = findExprType(srv, query, file, expr); - if (infer.didGuess()) return {}; - - var span = getSpan(type); - var result = {url: type.url, doc: type.doc, origin: type.origin}; - - if (type.types) for (var i = type.types.length - 1; i >= 0; --i) { - var tp = type.types[i]; - storeTypeDocs(tp, result); - if (!span) span = getSpan(tp); - } - - if (span && span.node) { // refers to a loaded file - var spanFile = span.node.sourceFile || srv.findFile(span.origin); - var start = outputPos(query, spanFile, span.node.start), end = outputPos(query, spanFile, span.node.end); - result.start = start; result.end = end; - result.file = span.origin; - var cxStart = Math.max(0, span.node.start - 50); - result.contextOffset = span.node.start - cxStart; - result.context = spanFile.text.slice(cxStart, cxStart + 50); - } else if (span) { // external - result.file = span.origin; - storeSpan(srv, query, span, result); - } - return clean(result); - } - - function findRefsToVariable(srv, query, file, expr, checkShadowing) { - var name = expr.node.name; - - for (var scope = expr.state; scope && !(name in scope.props); scope = scope.prev) {} - if (!scope) throw ternError("Could not find a definition for " + name + " " + !!srv.cx.topScope.props.x); - - var type, refs = []; - function storeRef(file) { - return function(node, scopeHere) { - if (checkShadowing) for (var s = scopeHere; s != scope; s = s.prev) { - var exists = s.hasProp(checkShadowing); - if (exists) - throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would make a variable at line " + - (asLineChar(file, node.start).line + 1) + " point to the definition at line " + - (asLineChar(file, exists.name.start).line + 1)); - } - refs.push({file: file.name, - start: outputPos(query, file, node.start), - end: outputPos(query, file, node.end)}); - }; - } - - if (scope.originNode) { - type = "local"; - if (checkShadowing) { - for (var prev = scope.prev; prev; prev = prev.prev) - if (checkShadowing in prev.props) break; - if (prev) infer.findRefs(scope.originNode, scope, checkShadowing, prev, function(node) { - throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would shadow the definition used at line " + - (asLineChar(file, node.start).line + 1)); - }); - } - infer.findRefs(scope.originNode, scope, name, scope, storeRef(file)); - } else { - type = "global"; - for (var i = 0; i < srv.files.length; ++i) { - var cur = srv.files[i]; - infer.findRefs(cur.ast, cur.scope, name, scope, storeRef(cur)); - } - } - - return {refs: refs, type: type, name: name}; - } - - function findRefsToProperty(srv, query, expr, prop) { - var objType = infer.expressionType(expr).getObjType(); - if (!objType) throw ternError("Couldn't determine type of base object."); - - var refs = []; - function storeRef(file) { - return function(node) { - refs.push({file: file.name, - start: outputPos(query, file, node.start), - end: outputPos(query, file, node.end)}); - }; - } - for (var i = 0; i < srv.files.length; ++i) { - var cur = srv.files[i]; - infer.findPropRefs(cur.ast, cur.scope, objType, prop.name, storeRef(cur)); - } - - return {refs: refs, name: prop.name}; - } - - function findRefs(srv, query, file) { - var expr = findExprOrThrow(file, query, true); - if (expr && expr.node.type == "Identifier") { - return findRefsToVariable(srv, query, file, expr); - } else if (expr && expr.node.type == "MemberExpression" && !expr.node.computed) { - var p = expr.node.property; - expr.node = expr.node.object; - return findRefsToProperty(srv, query, expr, p); - } else if (expr && expr.node.type == "ObjectExpression") { - var pos = resolvePos(file, query.end); - for (var i = 0; i < expr.node.properties.length; ++i) { - var k = expr.node.properties[i].key; - if (k.start <= pos && k.end >= pos) - return findRefsToProperty(srv, query, expr, k); - } - } - throw ternError("Not at a variable or property name."); - } - - function buildRename(srv, query, file) { - if (typeof query.newName != "string") throw ternError(".query.newName should be a string"); - var expr = findExprOrThrow(file, query); - if (!expr || expr.node.type != "Identifier") throw ternError("Not at a variable."); - - var data = findRefsToVariable(srv, query, file, expr, query.newName), refs = data.refs; - delete data.refs; - data.files = srv.files.map(function(f){return f.name;}); - - var changes = data.changes = []; - for (var i = 0; i < refs.length; ++i) { - var use = refs[i]; - use.text = query.newName; - changes.push(use); - } - - return data; - } - - function listFiles(srv) { - return {files: srv.files.map(function(f){return f.name;})}; - } - - exports.version = "0.9.1"; -}); diff --git a/mix/qml/html/cm/walk.js b/mix/qml/html/cm/walk.js deleted file mode 100644 index 9dcddaa3e..000000000 --- a/mix/qml/html/cm/walk.js +++ /dev/null @@ -1,359 +0,0 @@ -// AST walker module for Mozilla Parser API compatible trees - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") return mod(exports); // CommonJS - if (typeof define == "function" && define.amd) return define(["exports"], mod); // AMD - mod((this.acorn || (this.acorn = {})).walk = {}); // Plain browser env -})(function(exports) { - "use strict"; - - // A simple walk is one where you simply specify callbacks to be - // called on specific nodes. The last two arguments are optional. A - // simple use would be - // - // walk.simple(myTree, { - // Expression: function(node) { ... } - // }); - // - // to do something with all expressions. All Parser API node types - // can be used to identify node types, as well as Expression, - // Statement, and ScopeBody, which denote categories of nodes. - // - // The base argument can be used to pass a custom (recursive) - // walker, and state can be used to give this walked an initial - // state. - exports.simple = function(node, visitors, base, state) { - if (!base) base = exports.base; - function c(node, st, override) { - var type = override || node.type, found = visitors[type]; - base[type](node, st, c); - if (found) found(node, st); - } - c(node, state); - }; - - // An ancestor walk builds up an array of ancestor nodes (including - // the current node) and passes them to the callback as the state parameter. - exports.ancestor = function(node, visitors, base, state) { - if (!base) base = exports.base; - if (!state) state = []; - function c(node, st, override) { - var type = override || node.type, found = visitors[type]; - if (node != st[st.length - 1]) { - st = st.slice(); - st.push(node); - } - base[type](node, st, c); - if (found) found(node, st); - } - c(node, state); - }; - - // A recursive walk is one where your functions override the default - // walkers. They can modify and replace the state parameter that's - // threaded through the walk, and can opt how and whether to walk - // their child nodes (by calling their third argument on these - // nodes). - exports.recursive = function(node, state, funcs, base) { - var visitor = funcs ? exports.make(funcs, base) : base; - function c(node, st, override) { - visitor[override || node.type](node, st, c); - } - c(node, state); - }; - - function makeTest(test) { - if (typeof test == "string") - return function(type) { return type == test; }; - else if (!test) - return function() { return true; }; - else - return test; - } - - function Found(node, state) { this.node = node; this.state = state; } - - // Find a node with a given start, end, and type (all are optional, - // null can be used as wildcard). Returns a {node, state} object, or - // undefined when it doesn't find a matching node. - exports.findNodeAt = function(node, start, end, test, base, state) { - test = makeTest(test); - try { - if (!base) base = exports.base; - var c = function(node, st, override) { - var type = override || node.type; - if ((start == null || node.start <= start) && - (end == null || node.end >= end)) - base[type](node, st, c); - if (test(type, node) && - (start == null || node.start == start) && - (end == null || node.end == end)) - throw new Found(node, st); - }; - c(node, state); - } catch (e) { - if (e instanceof Found) return e; - throw e; - } - }; - - // Find the innermost node of a given type that contains the given - // position. Interface similar to findNodeAt. - exports.findNodeAround = function(node, pos, test, base, state) { - test = makeTest(test); - try { - if (!base) base = exports.base; - var c = function(node, st, override) { - var type = override || node.type; - if (node.start > pos || node.end < pos) return; - base[type](node, st, c); - if (test(type, node)) throw new Found(node, st); - }; - c(node, state); - } catch (e) { - if (e instanceof Found) return e; - throw e; - } - }; - - // Find the outermost matching node after a given position. - exports.findNodeAfter = function(node, pos, test, base, state) { - test = makeTest(test); - try { - if (!base) base = exports.base; - var c = function(node, st, override) { - if (node.end < pos) return; - var type = override || node.type; - if (node.start >= pos && test(type, node)) throw new Found(node, st); - base[type](node, st, c); - }; - c(node, state); - } catch (e) { - if (e instanceof Found) return e; - throw e; - } - }; - - // Find the outermost matching node before a given position. - exports.findNodeBefore = function(node, pos, test, base, state) { - test = makeTest(test); - if (!base) base = exports.base; - var max; - var c = function(node, st, override) { - if (node.start > pos) return; - var type = override || node.type; - if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) - max = new Found(node, st); - base[type](node, st, c); - }; - c(node, state); - return max; - }; - - // Used to create a custom walker. Will fill in all missing node - // type properties with the defaults. - exports.make = function(funcs, base) { - if (!base) base = exports.base; - var visitor = {}; - for (var type in base) visitor[type] = base[type]; - for (var type in funcs) visitor[type] = funcs[type]; - return visitor; - }; - - function skipThrough(node, st, c) { c(node, st); } - function ignore(_node, _st, _c) {} - - // Node walkers. - - var base = exports.base = {}; - base.Program = base.BlockStatement = function(node, st, c) { - for (var i = 0; i < node.body.length; ++i) - c(node.body[i], st, "Statement"); - }; - base.Statement = skipThrough; - base.EmptyStatement = ignore; - base.ExpressionStatement = base.ParenthesizedExpression = function(node, st, c) { - c(node.expression, st, "Expression"); - }; - base.IfStatement = function(node, st, c) { - c(node.test, st, "Expression"); - c(node.consequent, st, "Statement"); - if (node.alternate) c(node.alternate, st, "Statement"); - }; - base.LabeledStatement = function(node, st, c) { - c(node.body, st, "Statement"); - }; - base.BreakStatement = base.ContinueStatement = ignore; - base.WithStatement = function(node, st, c) { - c(node.object, st, "Expression"); - c(node.body, st, "Statement"); - }; - base.SwitchStatement = function(node, st, c) { - c(node.discriminant, st, "Expression"); - for (var i = 0; i < node.cases.length; ++i) { - var cs = node.cases[i]; - if (cs.test) c(cs.test, st, "Expression"); - for (var j = 0; j < cs.consequent.length; ++j) - c(cs.consequent[j], st, "Statement"); - } - }; - base.ReturnStatement = base.YieldExpression = function(node, st, c) { - if (node.argument) c(node.argument, st, "Expression"); - }; - base.ThrowStatement = base.SpreadElement = base.RestElement = function(node, st, c) { - c(node.argument, st, "Expression"); - }; - base.TryStatement = function(node, st, c) { - c(node.block, st, "Statement"); - if (node.handler) c(node.handler.body, st, "ScopeBody"); - if (node.finalizer) c(node.finalizer, st, "Statement"); - }; - base.WhileStatement = function(node, st, c) { - c(node.test, st, "Expression"); - c(node.body, st, "Statement"); - }; - base.DoWhileStatement = base.WhileStatement; - base.ForStatement = function(node, st, c) { - if (node.init) c(node.init, st, "ForInit"); - if (node.test) c(node.test, st, "Expression"); - if (node.update) c(node.update, st, "Expression"); - c(node.body, st, "Statement"); - }; - base.ForInStatement = base.ForOfStatement = function(node, st, c) { - c(node.left, st, "ForInit"); - c(node.right, st, "Expression"); - c(node.body, st, "Statement"); - }; - base.ForInit = function(node, st, c) { - if (node.type == "VariableDeclaration") c(node, st); - else c(node, st, "Expression"); - }; - base.DebuggerStatement = ignore; - - base.FunctionDeclaration = function(node, st, c) { - c(node, st, "Function"); - }; - base.VariableDeclaration = function(node, st, c) { - for (var i = 0; i < node.declarations.length; ++i) { - var decl = node.declarations[i]; - if (decl.init) c(decl.init, st, "Expression"); - } - }; - - base.Function = function(node, st, c) { - c(node.body, st, "ScopeBody"); - }; - base.ScopeBody = function(node, st, c) { - c(node, st, "Statement"); - }; - - base.Expression = skipThrough; - base.ThisExpression = ignore; - base.ArrayExpression = base.ArrayPattern = function(node, st, c) { - for (var i = 0; i < node.elements.length; ++i) { - var elt = node.elements[i]; - if (elt) c(elt, st, "Expression"); - } - }; - base.ObjectExpression = base.ObjectPattern = function(node, st, c) { - for (var i = 0; i < node.properties.length; ++i) - c(node.properties[i], st); - }; - base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; - base.SequenceExpression = base.TemplateLiteral = function(node, st, c) { - for (var i = 0; i < node.expressions.length; ++i) - c(node.expressions[i], st, "Expression"); - }; - base.UnaryExpression = base.UpdateExpression = function(node, st, c) { - c(node.argument, st, "Expression"); - }; - base.BinaryExpression = base.AssignmentExpression = base.AssignmentPattern = base.LogicalExpression = function(node, st, c) { - c(node.left, st, "Expression"); - c(node.right, st, "Expression"); - }; - base.ConditionalExpression = function(node, st, c) { - c(node.test, st, "Expression"); - c(node.consequent, st, "Expression"); - c(node.alternate, st, "Expression"); - }; - base.NewExpression = base.CallExpression = function(node, st, c) { - c(node.callee, st, "Expression"); - if (node.arguments) for (var i = 0; i < node.arguments.length; ++i) - c(node.arguments[i], st, "Expression"); - }; - base.MemberExpression = function(node, st, c) { - c(node.object, st, "Expression"); - if (node.computed) c(node.property, st, "Expression"); - }; - base.ExportDeclaration = function (node, st, c) { - c(node.declaration, st); - }; - base.ImportDeclaration = function (node, st, c) { - node.specifiers.forEach(function (specifier) { - c(specifier, st); - }); - }; - base.ImportSpecifier = base.ImportBatchSpecifier = base.Identifier = base.Literal = ignore; - - base.TaggedTemplateExpression = function(node, st, c) { - c(node.tag, st, "Expression"); - c(node.quasi, st); - }; - base.ClassDeclaration = base.ClassExpression = function(node, st, c) { - if (node.superClass) c(node.superClass, st, "Expression"); - for (var i = 0; i < node.body.body.length; i++) - c(node.body.body[i], st); - }; - base.MethodDefinition = base.Property = function(node, st, c) { - if (node.computed) c(node.key, st, "Expression"); - c(node.value, st, "Expression"); - }; - base.ComprehensionExpression = function(node, st, c) { - for (var i = 0; i < node.blocks.length; i++) - c(node.blocks[i].right, st, "Expression"); - c(node.body, st, "Expression"); - }; - - // NOTE: the stuff below is deprecated, and will be removed when 1.0 is released - - // A custom walker that keeps track of the scope chain and the - // variables defined in it. - function makeScope(prev, isCatch) { - return {vars: Object.create(null), prev: prev, isCatch: isCatch}; - } - function normalScope(scope) { - while (scope.isCatch) scope = scope.prev; - return scope; - } - exports.scopeVisitor = exports.make({ - Function: function(node, scope, c) { - var inner = makeScope(scope); - for (var i = 0; i < node.params.length; ++i) - inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]}; - if (node.id) { - var decl = node.type == "FunctionDeclaration"; - (decl ? normalScope(scope) : inner).vars[node.id.name] = - {type: decl ? "function" : "function name", node: node.id}; - } - c(node.body, inner, "ScopeBody"); - }, - TryStatement: function(node, scope, c) { - c(node.block, scope, "Statement"); - if (node.handler) { - var inner = makeScope(scope, true); - inner.vars[node.handler.param.name] = {type: "catch clause", node: node.handler.param}; - c(node.handler.body, inner, "ScopeBody"); - } - if (node.finalizer) c(node.finalizer, scope, "Statement"); - }, - VariableDeclaration: function(node, scope, c) { - var target = normalScope(scope); - for (var i = 0; i < node.declarations.length; ++i) { - var decl = node.declarations[i]; - target.vars[decl.id.name] = {type: "var", node: decl.id}; - if (decl.init) c(decl.init, scope, "Expression"); - } - } - }); - -}); diff --git a/mix/qml/html/cm/xml.js b/mix/qml/html/cm/xml.js deleted file mode 100644 index 2f3b8f87a..000000000 --- a/mix/qml/html/cm/xml.js +++ /dev/null @@ -1,384 +0,0 @@ -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("xml", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1; - var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag; - if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true; - - var Kludges = parserConfig.htmlMode ? { - autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, - 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, - 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, - 'track': true, 'wbr': true, 'menuitem': true}, - implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, - 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, - 'th': true, 'tr': true}, - contextGrabbers: { - 'dd': {'dd': true, 'dt': true}, - 'dt': {'dd': true, 'dt': true}, - 'li': {'li': true}, - 'option': {'option': true, 'optgroup': true}, - 'optgroup': {'optgroup': true}, - 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, - 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, - 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, - 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, - 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, - 'rp': {'rp': true, 'rt': true}, - 'rt': {'rp': true, 'rt': true}, - 'tbody': {'tbody': true, 'tfoot': true}, - 'td': {'td': true, 'th': true}, - 'tfoot': {'tbody': true}, - 'th': {'td': true, 'th': true}, - 'thead': {'tbody': true, 'tfoot': true}, - 'tr': {'tr': true} - }, - doNotIndent: {"pre": true}, - allowUnquoted: true, - allowMissing: true, - caseFold: true - } : { - autoSelfClosers: {}, - implicitlyClosed: {}, - contextGrabbers: {}, - doNotIndent: {}, - allowUnquoted: false, - allowMissing: false, - caseFold: false - }; - var alignCDATA = parserConfig.alignCDATA; - - // Return variables for tokenizers - var type, setStyle; - - function inText(stream, state) { - function chain(parser) { - state.tokenize = parser; - return parser(stream, state); - } - - var ch = stream.next(); - if (ch == "<") { - if (stream.eat("!")) { - if (stream.eat("[")) { - if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); - else return null; - } else if (stream.match("--")) { - return chain(inBlock("comment", "-->")); - } else if (stream.match("DOCTYPE", true, true)) { - stream.eatWhile(/[\w\._\-]/); - return chain(doctype(1)); - } else { - return null; - } - } else if (stream.eat("?")) { - stream.eatWhile(/[\w\._\-]/); - state.tokenize = inBlock("meta", "?>"); - return "meta"; - } else { - type = stream.eat("/") ? "closeTag" : "openTag"; - state.tokenize = inTag; - return "tag bracket"; - } - } else if (ch == "&") { - var ok; - if (stream.eat("#")) { - if (stream.eat("x")) { - ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); - } else { - ok = stream.eatWhile(/[\d]/) && stream.eat(";"); - } - } else { - ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); - } - return ok ? "atom" : "error"; - } else { - stream.eatWhile(/[^&<]/); - return null; - } - } - - function inTag(stream, state) { - var ch = stream.next(); - if (ch == ">" || (ch == "/" && stream.eat(">"))) { - state.tokenize = inText; - type = ch == ">" ? "endTag" : "selfcloseTag"; - return "tag bracket"; - } else if (ch == "=") { - type = "equals"; - return null; - } else if (ch == "<") { - state.tokenize = inText; - state.state = baseState; - state.tagName = state.tagStart = null; - var next = state.tokenize(stream, state); - return next ? next + " tag error" : "tag error"; - } else if (/[\'\"]/.test(ch)) { - state.tokenize = inAttribute(ch); - state.stringStartCol = stream.column(); - return state.tokenize(stream, state); - } else { - stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); - return "word"; - } - } - - function inAttribute(quote) { - var closure = function(stream, state) { - while (!stream.eol()) { - if (stream.next() == quote) { - state.tokenize = inTag; - break; - } - } - return "string"; - }; - closure.isInAttribute = true; - return closure; - } - - function inBlock(style, terminator) { - return function(stream, state) { - while (!stream.eol()) { - if (stream.match(terminator)) { - state.tokenize = inText; - break; - } - stream.next(); - } - return style; - }; - } - function doctype(depth) { - return function(stream, state) { - var ch; - while ((ch = stream.next()) != null) { - if (ch == "<") { - state.tokenize = doctype(depth + 1); - return state.tokenize(stream, state); - } else if (ch == ">") { - if (depth == 1) { - state.tokenize = inText; - break; - } else { - state.tokenize = doctype(depth - 1); - return state.tokenize(stream, state); - } - } - } - return "meta"; - }; - } - - function Context(state, tagName, startOfLine) { - this.prev = state.context; - this.tagName = tagName; - this.indent = state.indented; - this.startOfLine = startOfLine; - if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) - this.noIndent = true; - } - function popContext(state) { - if (state.context) state.context = state.context.prev; - } - function maybePopContext(state, nextTagName) { - var parentTagName; - while (true) { - if (!state.context) { - return; - } - parentTagName = state.context.tagName; - if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || - !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { - return; - } - popContext(state); - } - } - - function baseState(type, stream, state) { - if (type == "openTag") { - state.tagStart = stream.column(); - return tagNameState; - } else if (type == "closeTag") { - return closeTagNameState; - } else { - return baseState; - } - } - function tagNameState(type, stream, state) { - if (type == "word") { - state.tagName = stream.current(); - setStyle = "tag"; - return attrState; - } else { - setStyle = "error"; - return tagNameState; - } - } - function closeTagNameState(type, stream, state) { - if (type == "word") { - var tagName = stream.current(); - if (state.context && state.context.tagName != tagName && - Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName)) - popContext(state); - if (state.context && state.context.tagName == tagName) { - setStyle = "tag"; - return closeState; - } else { - setStyle = "tag error"; - return closeStateErr; - } - } else { - setStyle = "error"; - return closeStateErr; - } - } - - function closeState(type, _stream, state) { - if (type != "endTag") { - setStyle = "error"; - return closeState; - } - popContext(state); - return baseState; - } - function closeStateErr(type, stream, state) { - setStyle = "error"; - return closeState(type, stream, state); - } - - function attrState(type, _stream, state) { - if (type == "word") { - setStyle = "attribute"; - return attrEqState; - } else if (type == "endTag" || type == "selfcloseTag") { - var tagName = state.tagName, tagStart = state.tagStart; - state.tagName = state.tagStart = null; - if (type == "selfcloseTag" || - Kludges.autoSelfClosers.hasOwnProperty(tagName)) { - maybePopContext(state, tagName); - } else { - maybePopContext(state, tagName); - state.context = new Context(state, tagName, tagStart == state.indented); - } - return baseState; - } - setStyle = "error"; - return attrState; - } - function attrEqState(type, stream, state) { - if (type == "equals") return attrValueState; - if (!Kludges.allowMissing) setStyle = "error"; - return attrState(type, stream, state); - } - function attrValueState(type, stream, state) { - if (type == "string") return attrContinuedState; - if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;} - setStyle = "error"; - return attrState(type, stream, state); - } - function attrContinuedState(type, stream, state) { - if (type == "string") return attrContinuedState; - return attrState(type, stream, state); - } - - return { - startState: function() { - return {tokenize: inText, - state: baseState, - indented: 0, - tagName: null, tagStart: null, - context: null}; - }, - - token: function(stream, state) { - if (!state.tagName && stream.sol()) - state.indented = stream.indentation(); - - if (stream.eatSpace()) return null; - type = null; - var style = state.tokenize(stream, state); - if ((style || type) && style != "comment") { - setStyle = null; - state.state = state.state(type || style, stream, state); - if (setStyle) - style = setStyle == "error" ? style + " error" : setStyle; - } - return style; - }, - - indent: function(state, textAfter, fullLine) { - var context = state.context; - // Indent multi-line strings (e.g. css). - if (state.tokenize.isInAttribute) { - if (state.tagStart == state.indented) - return state.stringStartCol + 1; - else - return state.indented + indentUnit; - } - if (context && context.noIndent) return CodeMirror.Pass; - if (state.tokenize != inTag && state.tokenize != inText) - return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; - // Indent the starts of attribute names. - if (state.tagName) { - if (multilineTagIndentPastTag) - return state.tagStart + state.tagName.length + 2; - else - return state.tagStart + indentUnit * multilineTagIndentFactor; - } - if (alignCDATA && /$/, - blockCommentStart: "", - - configuration: parserConfig.htmlMode ? "html" : "xml", - helperType: parserConfig.htmlMode ? "html" : "xml" - }; -}); - -CodeMirror.defineMIME("text/xml", "xml"); -CodeMirror.defineMIME("application/xml", "xml"); -if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) - CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); - -}); diff --git a/mix/qml/html/codeeditor.html b/mix/qml/html/codeeditor.html deleted file mode 100644 index f368404fe..000000000 --- a/mix/qml/html/codeeditor.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mix/qml/html/codeeditor.js b/mix/qml/html/codeeditor.js deleted file mode 100644 index 68172200f..000000000 --- a/mix/qml/html/codeeditor.js +++ /dev/null @@ -1,338 +0,0 @@ -var editor = CodeMirror(document.body, { - lineNumbers: true, - //styleActiveLine: true, - matchBrackets: true, - autofocus: true, - gutters: ["CodeMirror-linenumbers", "breakpoints"], - autoCloseBrackets: true, - styleSelectedText: true - }); -var ternServer; - -editor.setOption("theme", "inkpot"); -editor.setOption("indentUnit", 4); -editor.setOption("indentWithTabs", true); -editor.setOption("fullScreen", true); - -editor.changeRegistered = false; -editor.breakpointsChangeRegistered = false; - -editor.on("change", function(eMirror, object) { - editor.changeRegistered = true; -}); - -var mac = /Mac/.test(navigator.platform); -var extraKeys = {}; -if (mac === true) { - extraKeys["Cmd-V"] = function(cm) { cm.replaceSelection(clipboard); }; - extraKeys["Cmd-X"] = function(cm) { window.document.execCommand("cut"); }; - extraKeys["Cmd-C"] = function(cm) { window.document.execCommand("copy"); }; -} - -makeMarker = function() { - var marker = document.createElement("div"); - marker.style.color = "#822"; - marker.innerHTML = "●"; - return marker; -}; - -toggleBreakpointLine = function(n) { - var info = editor.lineInfo(n); - editor.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker()); - editor.breakpointsChangeRegistered = true; -} - -editor.on("gutterClick", function(cm, n) { - toggleBreakpointLine(n); -}); - -toggleBreakpoint = function() { - var line = editor.getCursor().line; - toggleBreakpointLine(line); -} - -getTextChanged = function() { - return editor.changeRegistered; -}; - -getText = function() { - editor.changeRegistered = false; - return editor.getValue(); -}; - -getBreakpointsChanged = function() { - return editor.changeRegistered || editor.breakpointsChangeRegistered; //TODO: track new lines -}; - -getBreakpoints = function() { - var locations = []; - editor.breakpointsChangeRegistered = false; - var doc = editor.doc; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers["breakpoints"]) { - var l = doc.getLineNumber(line); - locations.push({ - start: editor.indexFromPos({ line: l, ch: 0}), - end: editor.indexFromPos({ line: l + 1, ch: 0}) - });; - } - }); - return locations; -}; - -setTextBase64 = function(text) { - editor.setValue(window.atob(text)); - editor.getDoc().clearHistory(); - editor.focus(); -}; - -setText = function(text) { - editor.setValue(text); -}; - -setMode = function(mode) { - this.editor.setOption("mode", mode); - - if (mode === "javascript") - { - ternServer = new CodeMirror.TernServer({defs: [ ecma5Spec() ]}); - extraKeys["Ctrl-Space"] = function(cm) { ternServer.complete(cm); }; - extraKeys["Ctrl-I"] = function(cm) { ternServer.showType(cm); }; - extraKeys["Ctrl-O"] = function(cm) { ternServer.showDocs(cm); }; - extraKeys["Alt-."] = function(cm) { ternServer.jumpToDef(cm); }; - extraKeys["Alt-,"] = function(cm) { ternServer.jumpBack(cm); }; - extraKeys["Ctrl-Q"] = function(cm) { ternServer.rename(cm); }; - extraKeys["Ctrl-."] = function(cm) { ternServer.selectName(cm); }; - extraKeys["'.'"] = function(cm) { setTimeout(function() { ternServer.complete(cm); }, 100); throw CodeMirror.Pass; }; - editor.on("cursorActivity", function(cm) { ternServer.updateArgHints(cm); }); - } - else if (mode === "solidity") - { - CodeMirror.commands.autocomplete = function(cm) { - CodeMirror.showHint(cm, CodeMirror.hint.anyword); - } - extraKeys["Ctrl-Space"] = "autocomplete"; - } - editor.setOption("extraKeys", extraKeys); -}; - -setClipboardBase64 = function(text) { - clipboard = window.atob(text); -}; - -var executionMark; -highlightExecution = function(start, end) { - if (executionMark) - executionMark.clear(); - if (debugWarning) - debugWarning.clear(); - if (start > 0 && end > start) { - executionMark = editor.markText(editor.posFromIndex(start), editor.posFromIndex(end), { className: "CodeMirror-exechighlight" }); - editor.scrollIntoView(editor.posFromIndex(start)); - } -} - -var changeId; -changeGeneration = function() -{ - changeId = editor.changeGeneration(true); -} - -isClean = function() -{ - return editor.isClean(changeId); -} - -var debugWarning = null; -showWarning = function(content) -{ - if (executionMark) - executionMark.clear(); - if (debugWarning) - debugWarning.clear(); - var node = document.createElement("div"); - node.id = "annotation" - node.innerHTML = content; - node.className = "CodeMirror-errorannotation-context"; - debugWarning = editor.addLineWidget(0, node, { coverGutter: false, above: true }); -} - -var annotations = []; -var compilationCompleteBool = true; -compilationError = function(currentSourceName, location, error, secondaryErrors) -{ - compilationCompleteBool = false; - if (compilationCompleteBool) - return; - clearAnnotations(); - location = JSON.parse(location); - if (location.source === currentSourceName) - ensureAnnotation(location, error, "first"); - var lineError = location.start.line + 1; - var errorOrigin = "Source " + location.contractName + " line " + lineError; - secondaryErrors = JSON.parse(secondaryErrors); - for(var i in secondaryErrors) - { - if (secondaryErrors[i].source === currentSourceName) - ensureAnnotation(secondaryErrors[i], errorOrigin, "second"); - } -} - -ensureAnnotation = function(location, error, type) -{ - annotations.push({ "type": type, "annotation": new ErrorAnnotation(editor, location, error)}); -} - -clearAnnotations = function() -{ - for (var k in annotations) - annotations[k].annotation.destroy(); - annotations.length = 0; -} - -compilationComplete = function() -{ - clearAnnotations(); - compilationCompleteBool = true; -} - -goToCompilationError = function() -{ - if (annotations.length > 0) - editor.setCursor(annotations[0].annotation.location.start.line, annotations[0].annotation.location.start.column) -} - -setFontSize = function(size) -{ - editor.getWrapperElement().style["font-size"] = size + "px"; - editor.refresh(); -} - -makeGasCostMarker = function(value) { - var marker = document.createElement("div"); - marker.innerHTML = value; - marker.className = "CodeMirror-gasCost"; - return marker; -}; - -var gasCosts = null; -setGasCosts = function(_gasCosts) -{ - gasCosts = JSON.parse(_gasCosts); - if (showingGasEstimation) - { - displayGasEstimation(false); - displayGasEstimation(true); - } -} - -var showingGasEstimation = false; -var gasMarkText = []; -var gasMarkRef = {}; -displayGasEstimation = function(show) -{ - show = JSON.parse(show); - showingGasEstimation = show; - if (show) - { - var maxGas = 20000; - var step = colorGradient.length / maxGas; // 20000 max gas - clearGasMark(); - gasMarkText = []; - gasMarkRef = {}; - for (var i in gasCosts) - { - if (gasCosts[i].gas !== "0") - { - var color; - var colorIndex = Math.round(step * gasCosts[i].gas); - if (gasCosts[i].isInfinite || colorIndex >= colorGradient.length) - color = colorGradient[colorGradient.length - 1]; - else - color = colorGradient[colorIndex]; - var className = "CodeMirror-gasCosts" + i; - var line = editor.posFromIndex(gasCosts[i].start); - var endChar; - if (gasCosts[i].codeBlockType === "statement" || gasCosts[i].codeBlockType === "") - { - endChar = editor.posFromIndex(gasCosts[i].end); - gasMarkText.push({ line: line, markText: editor.markText(line, endChar, { inclusiveLeft: true, inclusiveRight: true, handleMouseEvents: true, className: className, css: "background-color:" + color })}); - } - else if (gasCosts[i].codeBlockType === "function" || gasCosts[i].codeBlockType === "constructor") - { - var l = editor.getLine(line.line); - endChar = { line: line.line, ch: line.ch + l.length }; - var marker = document.createElement("div"); - marker.innerHTML = " max execution cost: " + gasCosts[i].gas + " gas"; - marker.className = "CodeMirror-gasCost"; - editor.addWidget(endChar, marker, false, "over"); - gasMarkText.push({ line: line.line, widget: marker }); - } - gasMarkRef[className] = { line: line.line, value: gasCosts[i] }; - } - } - CodeMirror.on(editor.getWrapperElement(), "mouseover", listenMouseOver); - } - else - { - CodeMirror.off(editor.getWrapperElement(), "mouseover", listenMouseOver); - clearGasMark(); - if (gasAnnotation) - { - gasAnnotation.clear(); - gasAnnotation = null; - } - } -} - -function clearGasMark() -{ - if (gasMarkText) - for (var k in gasMarkText) - { - if (gasMarkText[k] && gasMarkText[k].markText) - gasMarkText[k].markText.clear(); - if (gasMarkText[k] && gasMarkText[k].widget) - gasMarkText[k].widget.remove(); - } -} - -var gasAnnotation; -function listenMouseOver(e) -{ - var node = e.target || e.srcElement; - if (node) - { - if (node.className && node.className.indexOf("CodeMirror-gasCosts") !== -1) - { - if (gasAnnotation) - gasAnnotation.clear(); - var cl = getGasCostClass(node); - var gasTitle = gasMarkRef[cl].value.isInfinite ? "infinite" : gasMarkRef[cl].value.gas; - gasTitle = " execution cost: " + gasTitle + " gas"; - gasAnnotation = editor.addLineWidget(gasMarkRef[cl].line + 1, makeGasCostMarker(gasTitle), { coverGutter: false, above: true }); - } - else if (gasAnnotation) - { - gasAnnotation.clear(); - gasAnnotation = null; - } - } -} - -function getGasCostClass(node) -{ - var classes = node.className.split(" "); - for (var k in classes) - { - if (classes[k].indexOf("CodeMirror-gasCosts") !== -1) - return classes[k]; - } - return ""; -} - -// blue => red ["#1515ED", "#1714EA", "#1914E8", "#1B14E6", "#1D14E4", "#1F14E2", "#2214E0", "#2414DE", "#2614DC", "#2813DA", "#2A13D8", "#2D13D6", "#2F13D4", "#3113D2", "#3313D0", "#3513CE", "#3713CC", "#3A12CA", "#3C12C8", "#3E12C6", "#4012C4", "#4212C2", "#4512C0", "#4712BE", "#4912BC", "#4B11BA", "#4D11B8", "#4F11B6", "#5211B4", "#5411B2", "#5611B0", "#5811AE", "#5A11AC", "#5D11AA", "#5F10A7", "#6110A5", "#6310A3", "#6510A1", "#67109F", "#6A109D", "#6C109B", "#6E1099", "#700F97", "#720F95", "#750F93", "#770F91", "#790F8F", "#7B0F8D", "#7D0F8B", "#7F0F89", "#820E87", "#840E85", "#860E83", "#880E81", "#8A0E7F", "#8D0E7D", "#8F0E7B", "#910E79", "#930D77", "#950D75", "#970D73", "#9A0D71", "#9C0D6F", "#9E0D6D", "#A00D6B", "#A20D69", "#A50D67", "#A70C64", "#A90C62", "#AB0C60", "#AD0C5E", "#AF0C5C", "#B20C5A", "#B40C58", "#B60C56", "#B80B54", "#BA0B52", "#BD0B50", "#BF0B4E", "#C10B4C", "#C30B4A", "#C50B48", "#C70B46", "#CA0A44", "#CC0A42", "#CE0A40", "#D00A3E", "#D20A3C", "#D50A3A", "#D70A38", "#D90A36", "#DB0934", "#DD0932", "#DF0930", "#E2092E", "#E4092C", "#E6092A", "#E80928", "#EA0926", "#ED0924"] -/* green => red */ var colorGradient = ["#429C27", "#439A26", "#449926", "#469726", "#479626", "#489525", "#4A9325", "#4B9225", "#4D9025", "#4E8F25", "#4F8E24", "#518C24", "#528B24", "#548924", "#558824", "#568723", "#588523", "#598423", "#5B8223", "#5C8122", "#5D8022", "#5F7E22", "#607D22", "#627B22", "#637A21", "#647921", "#667721", "#677621", "#697421", "#6A7320", "#6B7220", "#6D7020", "#6E6F20", "#706E20", "#716C1F", "#726B1F", "#74691F", "#75681F", "#76671E", "#78651E", "#79641E", "#7B621E", "#7C611E", "#7D601D", "#7F5E1D", "#805D1D", "#825B1D", "#835A1D", "#84591C", "#86571C", "#87561C", "#89541C", "#8A531B", "#8B521B", "#8D501B", "#8E4F1B", "#904D1B", "#914C1A", "#924B1A", "#94491A", "#95481A", "#97461A", "#984519", "#994419", "#9B4219", "#9C4119", "#9E4019", "#9F3E18", "#A03D18", "#A23B18", "#A33A18", "#A43917", "#A63717", "#A73617", "#A93417", "#AA3317", "#AB3216", "#AD3016", "#AE2F16", "#B02D16", "#B12C16", "#B22B15", "#B42915", "#B52815", "#B72615", "#B82514", "#B92414", "#BB2214", "#BC2114", "#BE1F14", "#BF1E13", "#C01D13", "#C21B13", "#C31A13", "#C51813", "#C61712", "#C71612", "#C91412", "#CA1312", "#CC1212"] - -editor.setOption("extraKeys", extraKeys); - diff --git a/mix/qml/img/addblock.png b/mix/qml/img/addblock.png deleted file mode 100644 index 016d0ddbb..000000000 Binary files a/mix/qml/img/addblock.png and /dev/null differ diff --git a/mix/qml/img/addblock@2x.png b/mix/qml/img/addblock@2x.png deleted file mode 100644 index 085fcb686..000000000 Binary files a/mix/qml/img/addblock@2x.png and /dev/null differ diff --git a/mix/qml/img/available_updates.png b/mix/qml/img/available_updates.png deleted file mode 100644 index fa08c1d80..000000000 Binary files a/mix/qml/img/available_updates.png and /dev/null differ diff --git a/mix/qml/img/b64.png b/mix/qml/img/b64.png deleted file mode 100644 index 2089c948e..000000000 Binary files a/mix/qml/img/b64.png and /dev/null differ diff --git a/mix/qml/img/bugiconactive.png b/mix/qml/img/bugiconactive.png deleted file mode 100644 index ec72938a4..000000000 Binary files a/mix/qml/img/bugiconactive.png and /dev/null differ diff --git a/mix/qml/img/bugiconinactive.png b/mix/qml/img/bugiconinactive.png deleted file mode 100644 index 976175b06..000000000 Binary files a/mix/qml/img/bugiconinactive.png and /dev/null differ diff --git a/mix/qml/img/clearicon.png b/mix/qml/img/clearicon.png deleted file mode 100644 index 9760ff27b..000000000 Binary files a/mix/qml/img/clearicon.png and /dev/null differ diff --git a/mix/qml/img/cleariconactive.png b/mix/qml/img/cleariconactive.png deleted file mode 100644 index dfd829d5d..000000000 Binary files a/mix/qml/img/cleariconactive.png and /dev/null differ diff --git a/mix/qml/img/closedtriangleindicator.png b/mix/qml/img/closedtriangleindicator.png deleted file mode 100644 index ccf6c66d4..000000000 Binary files a/mix/qml/img/closedtriangleindicator.png and /dev/null differ diff --git a/mix/qml/img/closedtriangleindicator@2x.png b/mix/qml/img/closedtriangleindicator@2x.png deleted file mode 100644 index b12cfef9c..000000000 Binary files a/mix/qml/img/closedtriangleindicator@2x.png and /dev/null differ diff --git a/mix/qml/img/closedtriangleindicator_filesproject.png b/mix/qml/img/closedtriangleindicator_filesproject.png deleted file mode 100644 index 840f500e4..000000000 Binary files a/mix/qml/img/closedtriangleindicator_filesproject.png and /dev/null differ diff --git a/mix/qml/img/console.png b/mix/qml/img/console.png deleted file mode 100644 index 6958d5309..000000000 Binary files a/mix/qml/img/console.png and /dev/null differ diff --git a/mix/qml/img/copy.png b/mix/qml/img/copy.png deleted file mode 100644 index 72a1e62bc..000000000 Binary files a/mix/qml/img/copy.png and /dev/null differ diff --git a/mix/qml/img/copyicon.png b/mix/qml/img/copyicon.png deleted file mode 100644 index 836f08b0b..000000000 Binary files a/mix/qml/img/copyicon.png and /dev/null differ diff --git a/mix/qml/img/copyiconactive.png b/mix/qml/img/copyiconactive.png deleted file mode 100644 index 387d7f1fa..000000000 Binary files a/mix/qml/img/copyiconactive.png and /dev/null differ diff --git a/mix/qml/img/dappProjectIcon.png b/mix/qml/img/dappProjectIcon.png deleted file mode 100644 index eea9025d0..000000000 Binary files a/mix/qml/img/dappProjectIcon.png and /dev/null differ diff --git a/mix/qml/img/delete_sign.png b/mix/qml/img/delete_sign.png deleted file mode 100644 index 5c00a20ba..000000000 Binary files a/mix/qml/img/delete_sign.png and /dev/null differ diff --git a/mix/qml/img/duplicateicon.png b/mix/qml/img/duplicateicon.png deleted file mode 100644 index b3a255420..000000000 Binary files a/mix/qml/img/duplicateicon.png and /dev/null differ diff --git a/mix/qml/img/duplicateicon@2x.png b/mix/qml/img/duplicateicon@2x.png deleted file mode 100644 index d0f5274d3..000000000 Binary files a/mix/qml/img/duplicateicon@2x.png and /dev/null differ diff --git a/mix/qml/img/edit.png b/mix/qml/img/edit.png deleted file mode 100644 index 0530fd192..000000000 Binary files a/mix/qml/img/edit.png and /dev/null differ diff --git a/mix/qml/img/edit_combox.png b/mix/qml/img/edit_combox.png deleted file mode 100644 index be3b35942..000000000 Binary files a/mix/qml/img/edit_combox.png and /dev/null differ diff --git a/mix/qml/img/edittransaction.png b/mix/qml/img/edittransaction.png deleted file mode 100644 index fac8954ef..000000000 Binary files a/mix/qml/img/edittransaction.png and /dev/null differ diff --git a/mix/qml/img/edittransaction2.png b/mix/qml/img/edittransaction2.png deleted file mode 100644 index 55ffe2ad8..000000000 Binary files a/mix/qml/img/edittransaction2.png and /dev/null differ diff --git a/mix/qml/img/edittransaction2@2x.png b/mix/qml/img/edittransaction2@2x.png deleted file mode 100644 index e925679a9..000000000 Binary files a/mix/qml/img/edittransaction2@2x.png and /dev/null differ diff --git a/mix/qml/img/edittransaction@2x.png b/mix/qml/img/edittransaction@2x.png deleted file mode 100644 index 9f440fe14..000000000 Binary files a/mix/qml/img/edittransaction@2x.png and /dev/null differ diff --git a/mix/qml/img/exit.png b/mix/qml/img/exit.png deleted file mode 100644 index 1233765ae..000000000 Binary files a/mix/qml/img/exit.png and /dev/null differ diff --git a/mix/qml/img/help.png b/mix/qml/img/help.png deleted file mode 100644 index 06fffe9f8..000000000 Binary files a/mix/qml/img/help.png and /dev/null differ diff --git a/mix/qml/img/jumpintoback.png b/mix/qml/img/jumpintoback.png deleted file mode 100644 index 1b4454777..000000000 Binary files a/mix/qml/img/jumpintoback.png and /dev/null differ diff --git a/mix/qml/img/jumpintobackdisabled.png b/mix/qml/img/jumpintobackdisabled.png deleted file mode 100644 index d4d33a3a9..000000000 Binary files a/mix/qml/img/jumpintobackdisabled.png and /dev/null differ diff --git a/mix/qml/img/jumpintoforward.png b/mix/qml/img/jumpintoforward.png deleted file mode 100644 index eeedeada9..000000000 Binary files a/mix/qml/img/jumpintoforward.png and /dev/null differ diff --git a/mix/qml/img/jumpintoforwarddisabled.png b/mix/qml/img/jumpintoforwarddisabled.png deleted file mode 100644 index 933fcf333..000000000 Binary files a/mix/qml/img/jumpintoforwarddisabled.png and /dev/null differ diff --git a/mix/qml/img/jumpoutback.png b/mix/qml/img/jumpoutback.png deleted file mode 100644 index a1c4c0a40..000000000 Binary files a/mix/qml/img/jumpoutback.png and /dev/null differ diff --git a/mix/qml/img/jumpoutbackdisabled.png b/mix/qml/img/jumpoutbackdisabled.png deleted file mode 100644 index c3e58478c..000000000 Binary files a/mix/qml/img/jumpoutbackdisabled.png and /dev/null differ diff --git a/mix/qml/img/jumpoutforward.png b/mix/qml/img/jumpoutforward.png deleted file mode 100644 index 10c58c53a..000000000 Binary files a/mix/qml/img/jumpoutforward.png and /dev/null differ diff --git a/mix/qml/img/jumpoutforwarddisabled.png b/mix/qml/img/jumpoutforwarddisabled.png deleted file mode 100644 index f1104b4a8..000000000 Binary files a/mix/qml/img/jumpoutforwarddisabled.png and /dev/null differ diff --git a/mix/qml/img/jumpoverback.png b/mix/qml/img/jumpoverback.png deleted file mode 100644 index 358ac29e8..000000000 Binary files a/mix/qml/img/jumpoverback.png and /dev/null differ diff --git a/mix/qml/img/jumpoverbackdisabled.png b/mix/qml/img/jumpoverbackdisabled.png deleted file mode 100644 index 1742d80ac..000000000 Binary files a/mix/qml/img/jumpoverbackdisabled.png and /dev/null differ diff --git a/mix/qml/img/jumpoverforward.png b/mix/qml/img/jumpoverforward.png deleted file mode 100644 index bee403957..000000000 Binary files a/mix/qml/img/jumpoverforward.png and /dev/null differ diff --git a/mix/qml/img/jumpoverforwarddisabled.png b/mix/qml/img/jumpoverforwarddisabled.png deleted file mode 100644 index 973474098..000000000 Binary files a/mix/qml/img/jumpoverforwarddisabled.png and /dev/null differ diff --git a/mix/qml/img/leftarrow.png b/mix/qml/img/leftarrow.png deleted file mode 100644 index 2ce4936ef..000000000 Binary files a/mix/qml/img/leftarrow.png and /dev/null differ diff --git a/mix/qml/img/leftarrow@2x.png b/mix/qml/img/leftarrow@2x.png deleted file mode 100644 index 8602b02ea..000000000 Binary files a/mix/qml/img/leftarrow@2x.png and /dev/null differ diff --git a/mix/qml/img/newIcon.png b/mix/qml/img/newIcon.png deleted file mode 100644 index 016d0ddbb..000000000 Binary files a/mix/qml/img/newIcon.png and /dev/null differ diff --git a/mix/qml/img/newIcon@2x.png b/mix/qml/img/newIcon@2x.png deleted file mode 100644 index 085fcb686..000000000 Binary files a/mix/qml/img/newIcon@2x.png and /dev/null differ diff --git a/mix/qml/img/newaccounticon.png b/mix/qml/img/newaccounticon.png deleted file mode 100644 index 16bb66fcd..000000000 Binary files a/mix/qml/img/newaccounticon.png and /dev/null differ diff --git a/mix/qml/img/newaccounticon@2x.png b/mix/qml/img/newaccounticon@2x.png deleted file mode 100644 index 925dad67d..000000000 Binary files a/mix/qml/img/newaccounticon@2x.png and /dev/null differ diff --git a/mix/qml/img/newblock.png b/mix/qml/img/newblock.png deleted file mode 100644 index 04694412c..000000000 Binary files a/mix/qml/img/newblock.png and /dev/null differ diff --git a/mix/qml/img/newblock@2x.png b/mix/qml/img/newblock@2x.png deleted file mode 100644 index 42ea02f5f..000000000 Binary files a/mix/qml/img/newblock@2x.png and /dev/null differ diff --git a/mix/qml/img/note.png b/mix/qml/img/note.png deleted file mode 100644 index e44e94744..000000000 Binary files a/mix/qml/img/note.png and /dev/null differ diff --git a/mix/qml/img/openedfolder.png b/mix/qml/img/openedfolder.png deleted file mode 100644 index 728839de4..000000000 Binary files a/mix/qml/img/openedfolder.png and /dev/null differ diff --git a/mix/qml/img/opentriangleindicator.png b/mix/qml/img/opentriangleindicator.png deleted file mode 100644 index 5da188206..000000000 Binary files a/mix/qml/img/opentriangleindicator.png and /dev/null differ diff --git a/mix/qml/img/opentriangleindicator@2x.png b/mix/qml/img/opentriangleindicator@2x.png deleted file mode 100644 index 320749684..000000000 Binary files a/mix/qml/img/opentriangleindicator@2x.png and /dev/null differ diff --git a/mix/qml/img/opentriangleindicator_filesproject.png b/mix/qml/img/opentriangleindicator_filesproject.png deleted file mode 100644 index ee351b05c..000000000 Binary files a/mix/qml/img/opentriangleindicator_filesproject.png and /dev/null differ diff --git a/mix/qml/img/pause_button.png b/mix/qml/img/pause_button.png deleted file mode 100755 index e87889551..000000000 Binary files a/mix/qml/img/pause_button.png and /dev/null differ diff --git a/mix/qml/img/pause_button2x.png b/mix/qml/img/pause_button2x.png deleted file mode 100755 index 6f45b3236..000000000 Binary files a/mix/qml/img/pause_button2x.png and /dev/null differ diff --git a/mix/qml/img/play_button.png b/mix/qml/img/play_button.png deleted file mode 100755 index 01a5c85cb..000000000 Binary files a/mix/qml/img/play_button.png and /dev/null differ diff --git a/mix/qml/img/play_button2x.png b/mix/qml/img/play_button2x.png deleted file mode 100755 index 24eaa0659..000000000 Binary files a/mix/qml/img/play_button2x.png and /dev/null differ diff --git a/mix/qml/img/plus.png b/mix/qml/img/plus.png deleted file mode 100644 index fa8f5b9df..000000000 Binary files a/mix/qml/img/plus.png and /dev/null differ diff --git a/mix/qml/img/projecticon.png b/mix/qml/img/projecticon.png deleted file mode 100644 index 58b8b6f60..000000000 Binary files a/mix/qml/img/projecticon.png and /dev/null differ diff --git a/mix/qml/img/recyclediscard.png b/mix/qml/img/recyclediscard.png deleted file mode 100644 index 587d9ece3..000000000 Binary files a/mix/qml/img/recyclediscard.png and /dev/null differ diff --git a/mix/qml/img/recyclediscard@2x.png b/mix/qml/img/recyclediscard@2x.png deleted file mode 100644 index 8392198cb..000000000 Binary files a/mix/qml/img/recyclediscard@2x.png and /dev/null differ diff --git a/mix/qml/img/recycleicon.png b/mix/qml/img/recycleicon.png deleted file mode 100644 index a4bacb21f..000000000 Binary files a/mix/qml/img/recycleicon.png and /dev/null differ diff --git a/mix/qml/img/recycleicon@2x.png b/mix/qml/img/recycleicon@2x.png deleted file mode 100644 index 00f42abd8..000000000 Binary files a/mix/qml/img/recycleicon@2x.png and /dev/null differ diff --git a/mix/qml/img/recyclekeep.png b/mix/qml/img/recyclekeep.png deleted file mode 100644 index 8f7232334..000000000 Binary files a/mix/qml/img/recyclekeep.png and /dev/null differ diff --git a/mix/qml/img/recyclekeep@2x.png b/mix/qml/img/recyclekeep@2x.png deleted file mode 100644 index 37891ce5a..000000000 Binary files a/mix/qml/img/recyclekeep@2x.png and /dev/null differ diff --git a/mix/qml/img/restoreicon.png b/mix/qml/img/restoreicon.png deleted file mode 100644 index 9fc6e8f22..000000000 Binary files a/mix/qml/img/restoreicon.png and /dev/null differ diff --git a/mix/qml/img/restoreicon@2x.png b/mix/qml/img/restoreicon@2x.png deleted file mode 100644 index 3160b0bf3..000000000 Binary files a/mix/qml/img/restoreicon@2x.png and /dev/null differ diff --git a/mix/qml/img/rightarrow.png b/mix/qml/img/rightarrow.png deleted file mode 100644 index 54f2b401f..000000000 Binary files a/mix/qml/img/rightarrow.png and /dev/null differ diff --git a/mix/qml/img/rightarrow@2x.png b/mix/qml/img/rightarrow@2x.png deleted file mode 100644 index 6ed1e6d1b..000000000 Binary files a/mix/qml/img/rightarrow@2x.png and /dev/null differ diff --git a/mix/qml/img/rightarrowcircle.png b/mix/qml/img/rightarrowcircle.png deleted file mode 100644 index 0e2259dfd..000000000 Binary files a/mix/qml/img/rightarrowcircle.png and /dev/null differ diff --git a/mix/qml/img/run.png b/mix/qml/img/run.png deleted file mode 100644 index 37ac04689..000000000 Binary files a/mix/qml/img/run.png and /dev/null differ diff --git a/mix/qml/img/saveicon.png b/mix/qml/img/saveicon.png deleted file mode 100644 index 46e17522b..000000000 Binary files a/mix/qml/img/saveicon.png and /dev/null differ diff --git a/mix/qml/img/saveicon@2x.png b/mix/qml/img/saveicon@2x.png deleted file mode 100644 index 0f77a1af8..000000000 Binary files a/mix/qml/img/saveicon@2x.png and /dev/null differ diff --git a/mix/qml/img/search_filled.png b/mix/qml/img/search_filled.png deleted file mode 100644 index c459e7cbd..000000000 Binary files a/mix/qml/img/search_filled.png and /dev/null differ diff --git a/mix/qml/img/searchicon.png b/mix/qml/img/searchicon.png deleted file mode 100644 index c10dc9228..000000000 Binary files a/mix/qml/img/searchicon.png and /dev/null differ diff --git a/mix/qml/img/sendtransactionicon.png b/mix/qml/img/sendtransactionicon.png deleted file mode 100644 index 02f359122..000000000 Binary files a/mix/qml/img/sendtransactionicon.png and /dev/null differ diff --git a/mix/qml/img/sendtransactionicon@2x.png b/mix/qml/img/sendtransactionicon@2x.png deleted file mode 100644 index bb30b0b08..000000000 Binary files a/mix/qml/img/sendtransactionicon@2x.png and /dev/null differ diff --git a/mix/qml/img/stop_button2x.png b/mix/qml/img/stop_button2x.png deleted file mode 100644 index 1727b729a..000000000 Binary files a/mix/qml/img/stop_button2x.png and /dev/null differ diff --git a/mix/qml/img/warningicon.png b/mix/qml/img/warningicon.png deleted file mode 100644 index 0215030da..000000000 Binary files a/mix/qml/img/warningicon.png and /dev/null differ diff --git a/mix/qml/img/warningicon@2x.png b/mix/qml/img/warningicon@2x.png deleted file mode 100644 index e41615f37..000000000 Binary files a/mix/qml/img/warningicon@2x.png and /dev/null differ diff --git a/mix/qml/js/Debugger.js b/mix/qml/js/Debugger.js deleted file mode 100644 index f6900489a..000000000 --- a/mix/qml/js/Debugger.js +++ /dev/null @@ -1,325 +0,0 @@ -//debugData => contain all debug states. -//statesList => ListView - -var currentSelectedState = null; -var currentDisplayedState = null; -var debugData = null; -var locations = []; -var locationMap = {}; -var breakpoints = {}; - -function init(data) -{ - jumpOutBackAction.enabled(false); - jumpIntoBackAction.enabled(false); - jumpIntoForwardAction.enabled(false); - jumpOutForwardAction.enabled(false); - jumpOverBackAction.enabled(false); - jumpOverForwardAction.enabled(false); - - if (data === null) { - statesList.model.clear(); - statesSlider.maximumValue = 0; - statesSlider.value = 0; - currentSelectedState = null; - currentDisplayedState = null; - debugData = null; - locations = []; - locationMap = {}; - return; - } - - debugData = data; - currentSelectedState = 0; - currentDisplayedState = 0; - setupInstructions(currentSelectedState); - setupCallData(currentSelectedState); - initLocations(); - initSlider(); - selectState(currentSelectedState); -} - -function updateMode() -{ - initSlider(); -} - -function initLocations() -{ - locations = []; - if (debugData.states.length === 0) - return; - - var nullLocation = { start: -1, end: -1, documentId: "", state: 0 }; - var prevLocation = nullLocation; - - for (var i = 0; i < debugData.states.length - 1; i++) { - var code = debugData.states[i].code; - var location = code.documentId ? debugData.states[i].solidity : nullLocation; - if (location.start !== prevLocation.start || location.end !== prevLocation.end || code.documentId !== prevLocation.documentId) - { - prevLocation = { start: location.start, end: location.end, documentId: code.documentId, state: i }; - locations.push(prevLocation); - } - locationMap[i] = locations.length - 1; - } - locations.push({ start: -1, end: -1, documentId: code.documentId, state: i }); - - locationMap[debugData.states.length - 1] = locations.length - 1; -} - -function setBreakpoints(bp) -{ - breakpoints = bp; -} - -function srcMode() -{ - return !assemblyMode && locations.length; -} - -function initSlider() -{ - if (!debugData) - statesSlider.maximumValue = 0; - else if (srcMode()) { - statesSlider.maximumValue = locations.length - 1; - } else { - statesSlider.maximumValue = debugData.states.length - 1; - } - statesSlider.value = 0; -} - -function setupInstructions(stateIndex) -{ - var instructions = debugData.states[stateIndex].code.instructions; - statesList.model.clear(); - for (var i = 0; i < instructions.length; i++) - statesList.model.append(instructions[i]); - - callDataDump.listModel = debugData.states[stateIndex].callData.items; -} - -function setupCallData(stateIndex) -{ - callDataDump.listModel = debugData.states[stateIndex].callData.items; -} - -function moveSelection(incr) -{ - if (srcMode()) { - var locationIndex = locationMap[currentSelectedState]; - if (locationIndex + incr >= 0 && locationIndex + incr < locations.length) - selectState(locations[locationIndex + incr].state); - } else { - if (currentSelectedState + incr >= 0 && currentSelectedState + incr < debugData.states.length) - selectState(currentSelectedState + incr); - } -} - -function display(stateIndex) -{ - if (stateIndex < 0) - stateIndex = 0; - if (stateIndex >= debugData.states.length) - stateIndex = debugData.states.length - 1; - if (debugData.states[stateIndex].codeIndex !== debugData.states[currentDisplayedState].codeIndex) - setupInstructions(stateIndex); - if (debugData.states[stateIndex].dataIndex !== debugData.states[currentDisplayedState].dataIndex) - setupCallData(stateIndex); - var state = debugData.states[stateIndex]; - var codeLine = state.instructionIndex; - highlightSelection(codeLine); - completeCtxInformation(state); - currentDisplayedState = stateIndex; - var docId = debugData.states[stateIndex].code.documentId; - if (docId) - debugExecuteLocation(docId, debugData.states[stateIndex].solidity); -} - -function displayFrame(frameIndex) -{ - var state = debugData.states[currentSelectedState]; - if (frameIndex === 0) - display(currentSelectedState); - else - display(state.levels[frameIndex - 1]); -} - -function select(index) -{ - if (srcMode()) - selectState(locations[index].state); - else - selectState(index); -} - -function selectState(stateIndex) -{ - display(stateIndex); - currentSelectedState = stateIndex; - var state = debugData.states[stateIndex]; - jumpIntoForwardAction.enabled(stateIndex < debugData.states.length - 1) - jumpIntoBackAction.enabled(stateIndex > 0); - jumpOverForwardAction.enabled(stateIndex < debugData.states.length - 1); - jumpOverBackAction.enabled(stateIndex > 0); - jumpOutBackAction.enabled(state.levels.length > 1); - jumpOutForwardAction.enabled(state.levels.length > 1); - runForwardAction.enabled(stateIndex < debugData.states.length - 1) - runBackAction.enabled(stateIndex > 0); - - var callStackData = []; - for (var l = 0; l < state.levels.length; l++) { - var address = debugData.states[state.levels[l] + 1].code.address; - callStackData.push(address); - } - callStackData.push(debugData.states[0].code.address); - callStack.listModel = callStackData; - if (srcMode()) - statesSlider.value = locationMap[stateIndex]; - else - statesSlider.value = stateIndex; -} - -function highlightSelection(index) -{ - if (statesList.visible) - statesList.positionViewAtRow(index, ListView.Visible); - statesList.selection.clear(); - statesList.selection.select(index); -} - -function completeCtxInformation(state) -{ - currentStep.update(state.step); - mem.update(state.newMemSize.value() + " " + qsTr("words")); - stepCost.update(state.gasCost.value()); - gasSpent.update(debugData.states[0].gas.subtract(state.gas).value()); - - stack.listModel = state.debugStack; - storage.listModel = state.debugStorage; - memoryDump.listModel = state.debugMemory; - if (state.solidity) { - solLocals.setData(state.solidity.locals.variables, state.solidity.locals.values); - solStorage.setData(state.solidity.storage.variables, state.solidity.storage.values); - solCallStack.listModel = state.solidity.callStack; - } else { - solLocals.setData([], {}); - solStorage.setData([], {}); - solCallStack.listModel = []; - } -} - -function isCallInstruction(index) -{ - var state = debugData.states[index]; - return state.instruction === "CALL" || state.instruction === "CREATE"; -} - -function isReturnInstruction(index) -{ - var state = debugData.states[index]; - return state.instruction === "RETURN" -} - -function locationsIntersect(l1, l2) -{ - return l1.start <= l2.end && l1.end >= l2.start; -} - -function breakpointHit(i) -{ - var bpLocations = breakpoints[debugData.states[i].code.documentId]; - if (bpLocations) { - var location = debugData.states[i].solidity; - if (location.start >= 0 && location.end >= location.start) - for (var b = 0; b < bpLocations.length; b++) - if (locationsIntersect(location, bpLocations[b])) - return true; - } - return false; -} - -function stepIntoBack() -{ - moveSelection(-1); -} - -function stepOverBack() -{ - if (currentSelectedState > 0 && isReturnInstruction(currentSelectedState - 1)) - stepOutBack(); - else - moveSelection(-1); -} - -function stepOverForward() -{ - if (isCallInstruction(currentSelectedState)) - stepOutForward(); - else - moveSelection(1); -} - -function stepIntoForward() -{ - moveSelection(1); -} - -function runBack() -{ - var i = currentSelectedState - 1; - while (i > 0 && !breakpointHit(i)) { - --i; - } - selectState(i); -} - -function runForward() -{ - var i = currentSelectedState + 1; - while (i < debugData.states.length - 1 && !breakpointHit(i)) { - ++i; - } - selectState(i); -} - -function stepOutBack() -{ - var i = currentSelectedState - 1; - var depth = 0; - while (--i >= 0) { - if (breakpointHit(i)) - break; - if (isCallInstruction(i)) - if (depth == 0) - break; - else depth--; - else if (isReturnInstruction(i)) - depth++; - } - selectState(i); -} - -function stepOutForward() -{ - var i = currentSelectedState; - var depth = 0; - while (++i < debugData.states.length) { - if (breakpointHit(i)) - break; - if (isReturnInstruction(i)) - if (depth == 0) - break; - else - depth--; - else if (isCallInstruction(i)) - depth++; - } - selectState(i + 1); -} - -function jumpTo(value) -{ - select(value); -} diff --git a/mix/qml/js/ErrorLocationFormater.js b/mix/qml/js/ErrorLocationFormater.js deleted file mode 100644 index cb92f298b..000000000 --- a/mix/qml/js/ErrorLocationFormater.js +++ /dev/null @@ -1,30 +0,0 @@ -function formatLocation(raw, shortMessage) -{ - var splitted = raw.split(':'); - if (!shortMessage) - return qsTr("Error in line ") + splitted[1] + ", " + qsTr("character ") + splitted[2]; - else - return "L" + splitted[1] + "," + "C" + splitted[2]; -} - -function extractErrorInfo(raw, shortMessage) -{ - var _return = {}; - var detail = raw.split('\n')[0]; - var reg = detail.match(/:\d+:\d+:/g); - if (reg !== null) - { - _return.errorLocation = ErrorLocationFormater.formatLocation(reg[0], shortMessage); - _return.errorDetail = detail.replace(reg[0], ""); - _return.line = reg[0].split(':')[1]; - _return.column = reg[0].split(':')[2]; - } - else - { - _return.errorLocation = ""; - _return.errorDetail = detail; - _return.line = ""; - _return.column = ""; - } - return _return; -} diff --git a/mix/qml/js/InputValidator.js b/mix/qml/js/InputValidator.js deleted file mode 100644 index ea8d6dad5..000000000 --- a/mix/qml/js/InputValidator.js +++ /dev/null @@ -1,211 +0,0 @@ -Qt.include("QEtherHelper.js") - -var nbRegEx; -var arrayRegEx; -var capturenbRegEx; - -function validate(model, values) -{ - var inError = []; - for (var k in model) - { - init() - if (values[model[k].name]) - { - var type = model[k].type.name; - var value = values[model[k].name]; - var res = check(type, value) - if (!res.valid) - inError.push({ type: type, value: values, message: res.message }); - } - } - return inError; -} - -function init() -{ - nbRegEx = new RegExp('^[0-9]+$'); - arrayRegEx = new RegExp('\\[[^\\]]*\\]', "g"); - capturenbRegEx = new RegExp("[0-9]+"); -} - -function check(type, value) -{ - var res = { valid: true, message : "" } - - if (isArray(type)) - res = validateArray(type, value); - else if (isContractType(type)) - res = validateAddress(type, value); - else if (type.indexOf("int") !== -1) - res = validateInt(type, value); - else if (type.indexOf("enum") !== -1) - res = validateInt(type, value); - else if (type.indexOf("bytes") !== -1) - res = validateBytes(type, value); - else if (type.indexOf("bool") !== -1) - res = validateBool(type, value); - else if (type.indexOf("address") !== -1) - res = validateAddress(type, value); - else - { - res.valid = true - res.message = "" - } - return res; -} - -function isArray(_type) -{ - return arrayRegEx.test(_type); -} - -function checkArrayRecursively(_type, _dim, _array) -{ - if (_array instanceof Array) - { - if (_dim.length === 0) - return { valid: false, message: "Your input contains too many dimensions" } - var size = -1 - var infinite = false - if (_dim === "[]") - infinite = true - else - size = parseInt(capturenbRegEx.exec(_dim[0])) - if (_array.length > size && !infinite) - return { valid: false, message: "Array size does not correspond. Should be " + _dim[0] } - if (_array.length > 0) - { - var _newdim = _dim.slice(0) - _newdim.splice(0, 1) - for (var i = 0; i < _array.length; i++) - { - var ret = checkArrayRecursively(_type, _newdim, _array[i]) - if (!ret.valid) - return ret - } - } - return { valid: true, message: "" } - } - else - { - if (_dim.length > 0) - return { valid: false, message: "Your input contains too few dimensions" } - if (typeof(_array) === "number") - _array = '' + _array + '' - return check(_type, _array) - } -} - -function validateArray(_type, _value) -{ - try - { - _value = JSON.parse(_value) - } - catch (e) - { - return { valid: false, message: "Input must be JSON formatted like [1,5,3,9] or [[4,9],[4,9],[4,9],[4,9]]" } - } - var dim = _type.match(arrayRegEx) - dim.reverse(); - for (var k = 0; k < dim.length; k++) - _type = _type.replace(dim[k], "") - _type = _type.replace(/calldata/g, "") - return checkArrayRecursively(_type, dim, _value) -} - -function isContractType(_type) -{ - for (var k in Object.keys(codeModel.contracts)) - { - if ("contract " + Object.keys(codeModel.contracts)[k] === _type) - return true; - } - return false; -} - -function validateInt(_type, _value) -{ - var ret = { valid: true, message: "" } - if (_value.indexOf("-") === 0) - { - _value = _value.substring(1); - if (_type.indexOf("uint") === -1) - { - ret.valid = false; - ret.message = "uint type cannot represent negative number"; - } - } - ret.valid = nbRegEx.test(_value); - if (!ret.valid) - ret.message = _value + " does not represent " + _type + " type."; - else - { - var bigInt = createBigInt(_value); - bigInt.setBigInt(_value); - var result = bigInt.checkAgainst(_type); - if (!result.valid) - { - ret.valid = false; - ret.message = _type + " should be between " + result.minValue + " and " + result.maxValue; - } - } - return ret; -} - -function validateAddress(_type, _value) -{ - var ret = { valid: true, message: "" } - if (_value.indexOf("<") === 0 && _value.indexOf(">") === _value.length - 1) - { - var v = _value.split(' - '); - if (v.length !== 2 || !nbRegEx.test(v[1].replace(">", ""))) // - { - ret.valid = false; - ret.message = _value + " is not a valid token for address type."; - } - } - else if (_value.indexOf("0x") !== 0) - { - ret.valid = false - ret.message = "Address type should start with 0x."; - } - else - { - _value = _value.substring(2); - if (_value.length !== 40) - { - ret.valid = false - ret.message = "Address type should contain 40 characters."; - } - } - return ret; -} - -function validateBytes(_type, _value) -{ - var ret = { valid: true, message: "" } - if (_type !== "bytes" && _value.length > parseInt(_type.replace("bytes", "")) ) - { - ret.valid = false; - ret.message = _type + " should not contains more than " + _type.replace("bytes", "") + " characters"; - } - return ret; -} - -function validateBool(_type, _value) -{ - var ret = { valid: true, message: "" } - if (!(_value === "1" || _value === "0" || _value === 1 || _value === 0)) - { - ret.valid = false; - ret.message = _value + " is not in the correct bool format"; - } - return ret; -} - -function validateEnum(_type, _value) -{ -} - diff --git a/mix/qml/js/NetworkDeployment.js b/mix/qml/js/NetworkDeployment.js deleted file mode 100644 index ce2cd38c8..000000000 --- a/mix/qml/js/NetworkDeployment.js +++ /dev/null @@ -1,617 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file NetworkDeployment.js - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @author Yann yann@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ -.import org.ethereum.qml.QSolidityType 1.0 as QSolidityType - -Qt.include("TransactionHelper.js") -Qt.include("QEtherHelper.js") - - -var jsonRpcRequestId = 1; -function deployProject(force) { - saveAll(); //TODO: ask user - deploymentDialog.open(); -} - -function deployContracts(gas, gasPrice, callback) -{ - deploymentGas = gas; - deploymentGasPrice = gasPrice - deploymentStarted(); - - var ctrAddresses = {}; - var state = retrieveState(projectModel.deployedScenarioIndex); - if (!state) - { - var txt = qsTr("Unable to find this scenario"); - deploymentError(txt); - console.log(txt); - return; - } - var trHashes = {} - executeTr(0, 0, state, ctrAddresses, trHashes, function(){ - projectModel.deploymentAddresses = ctrAddresses; - deploymentStepChanged(qsTr("Scenario deployed. Please wait for verifications")) - if (callback) - callback(ctrAddresses, trHashes) - }); -} - -function checkPathCreationCost(ethUrl, callBack) -{ - var dappUrl = formatAppUrl(ethUrl); - checkEthPath(dappUrl, true, function(success, cause) { - if (!success) - { - switch (cause) - { - case "rootownedregistrar_notexist": - deploymentError(qsTr("Owned registrar does not exist under the global registrar. Please create one using DApp registration.")); - break; - case "ownedregistrar_creationfailed": - deploymentError(qsTr("The creation of your new owned registrar fails. Please use DApp registration to create one.")); - break; - case "ownedregistrar_notowner": - deploymentError(qsTr("You are not the owner of this registrar. You cannot register your Dapp here.")); - break; - default: - break; - } - } - else - callBack((dappUrl.length - 1) * (deploymentDialog.registerStep.ownedRegistrarDeployGas + deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas) + deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); - }); -} - -function gasUsed() -{ - var gas = 0; - var gasCosts = clientModel.gasCosts; - for (var g in gasCosts) - { - gas += gasCosts[g]; - } - return gas; -} - -function retrieveState(stateIndex) -{ - return projectModel.stateListModel.get(stateIndex); -} - -function replaceParamToken(paramsDef, params, ctrAddresses) -{ - var retParams = {}; - for (var k in paramsDef) - { - var value = ""; - if (params[paramsDef[k].name] !== undefined) - { - value = params[paramsDef[k].name]; - if (paramsDef[k].type.category === 4 && value.indexOf("<") === 0) - { - value = value.replace("<", "").replace(">", ""); - value = ctrAddresses[value]; - } - } - retParams[paramsDef[k].name] = value; - } - return retParams; -} - -function getFunction(ctrName, functionId) -{ - ctrName = contractFromToken(ctrName) - if (codeModel.contracts[ctrName] === undefined) - return null; - if (ctrName === functionId) - return codeModel.contracts[ctrName].contract.constructor; - else - { - for (var j in codeModel.contracts[ctrName].contract.functions) - { - if (codeModel.contracts[ctrName].contract.functions[j].name === functionId) - return codeModel.contracts[ctrName].contract.functions[j]; - } - } -} - -var deploymentGas -var deploymentGasPrice -var trRealIndex = -1 -function executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) -{ - trRealIndex++; - var tr = state.blocks.get(blockIndex).transactions.get(trIndex); - if (!tr) - callBack() - var func = getFunction(tr.contractId, tr.functionId); - if (!func) - executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); - else - { - var gasCost = clientModel.toHex(deploymentGas[trRealIndex]); - var rpcParams = { "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "gasPrice": deploymentGasPrice }; - var params = replaceParamToken(func.parameters, tr.parameters, ctrAddresses); - var encodedParams = clientModel.encodeParams(params, contractFromToken(tr.contractId), tr.functionId); - - if (tr.contractId === tr.functionId) - rpcParams.code = codeModel.contracts[tr.contractId].codeHex + encodedParams.join(""); - else - { - rpcParams.data = "0x" + func.qhash() + encodedParams.join(""); - rpcParams.to = ctrAddresses[tr.contractId]; - } - - var requests = [{ - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ rpcParams ], - id: jsonRpcRequestId - }]; - - rpcCall(requests, function (httpCall, response){ - var txt = qsTr(tr.contractId + "." + tr.functionId + "() ...") - deploymentStepChanged(txt); - console.log(txt); - var hash = JSON.parse(response)[0].result - trHashes[tr.contractId + "." + tr.functionId + "()"] = hash - deploymentDialog.worker.waitForTrReceipt(hash, function(status, receipt){ - if (status === -1) - trCountIncrementTimeOut(); - else - { - if (tr.contractId === tr.functionId) - { - ctrAddresses[tr.contractId] = receipt.contractAddress - ctrAddresses["<" + tr.contractId + " - " + trIndex + ">"] = receipt.contractAddress //get right ctr address if deploy more than one contract of same type. - } - executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) - } - }) - }); - } -} - -function retrieveContractAddress(trHash, callback) -{ - var requests = [{ - jsonrpc: "2.0", - method: "eth_getTransactionReceipt", - params: [ trHash ], - id: jsonRpcRequestId - }]; - rpcCall(requests, function (httpCall, response){ - callback(JSON.parse(response)[0].contractAddress) - }) -} - -function executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) -{ - trIndex++; - if (trIndex < state.blocks.get(blockIndex).transactions.count) - executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); - else - { - blockIndex++ - if (blockIndex < state.blocks.count) - executeTr(blockIndex, 0, state, ctrAddresses, trHashes, callBack); - else - callBack(); - } -} - -function gasPrice(callBack, error) -{ - var requests = [{ - jsonrpc: "2.0", - method: "eth_gasPrice", - params: [], - id: jsonRpcRequestId - }]; - rpcCall(requests, function (httpCall, response){ - callBack(JSON.parse(response)[0].result) - }, function(message){ - error(message) - }); -} - -function packageDapp(addresses) -{ - var date = new Date(); - var deploymentId = date.toLocaleString(Qt.locale(), "ddMMyyHHmmsszzz"); - deploymentDialog.packageStep.deploymentId = deploymentId - - deploymentStepChanged(qsTr("Packaging application ...")); - var deploymentDir = projectPath + deploymentId + "/"; - - if (deploymentDialog.packageStep.packageDir !== "") - deploymentDir = deploymentDialog.packageStep.packageDir - else - deploymentDir = projectPath + "package/" - - projectModel.deploymentDir = deploymentDir; - fileIo.makeDir(deploymentDir); - for (var i = 0; i < projectListModel.count; i++) { - var doc = projectListModel.get(i); - if (doc.isContract) - continue; - if (doc.isHtml) { - //inject the script to access contract API - //TODO: use a template - var html = fileIo.readFile(doc.path); - var insertAt = html.indexOf("") - if (insertAt < 0) - insertAt = 0; - else - insertAt += 6; - html = html.substr(0, insertAt) + - "" + - html.substr(insertAt); - fileIo.writeFile(deploymentDir + doc.fileName, html); - } - else - fileIo.copyFile(doc.path, deploymentDir + doc.fileName); - } - //write deployment js - var deploymentJs = - "// Autogenerated by Mix\n" + - "contracts = {};\n"; - for (var c in codeModel.contracts) { - var contractAccessor = "contracts[\"" + codeModel.contracts[c].contract.name + "\"]"; - deploymentJs += contractAccessor + " = {\n" + - "\tinterface: " + codeModel.contracts[c].contractInterface + ",\n" + - "\taddress: \"" + addresses[c] + "\"\n" + - "};\n" + - contractAccessor + ".contractClass = web3.eth.contract(" + contractAccessor + ".interface);\n" + - contractAccessor + ".contract = " + contractAccessor + ".contractClass.at(" + contractAccessor + ".address);\n"; - } - fileIo.writeFile(deploymentDir + "deployment.js", deploymentJs); - deploymentAddresses = addresses; - saveProject(); - - var packageRet = fileIo.makePackage(deploymentDir); - deploymentDialog.packageStep.packageHash = packageRet[0]; - deploymentDialog.packageStep.packageBase64 = packageRet[1]; - deploymentDialog.packageStep.localPackageUrl = packageRet[2] + "?hash=" + packageRet[0]; - deploymentDialog.packageStep.lastDeployDate = date - deploymentStepChanged(qsTr("Dapp is Packaged")) -} - -function registerDapp(url, gasPrice, callback) -{ - deploymentGasPrice = gasPrice - deploymentStepChanged(qsTr("Registering application on the Ethereum network ...")); - checkEthPath(url, false, function (success) { - if (!success) - return; - deploymentStepChanged(qsTr("Dapp has been registered. Please wait for verifications.")); - if (callback) - callback() - }); -} - -function checkEthPath(dappUrl, checkOnly, callBack) -{ - if (dappUrl.length === 1) - { - // convenient for dev purpose, should not be possible in normal env. - if (!checkOnly) - reserve(deploymentDialog.registerStep.eth, function() { - registerContentHash(deploymentDialog.registerStep.eth, callBack); // we directly create a dapp under the root registrar. - }); - else - callBack(true); - } - else - { - // the first owned registrar must have been created to follow the path. - var str = clientModel.encodeStringParam(dappUrl[0]); - var requests = []; - requests.push({ - //subRegistrar() - jsonrpc: "2.0", - method: "eth_call", - params: [ { "gas": "0xffff", "from": deploymentDialog.worker.currentAccount, "to": '0x' + deploymentDialog.registerStep.eth, "data": "0xe1fa8e84" + str }, "pending" ], - id: jsonRpcRequestId++ - }); - rpcCall(requests, function (httpRequest, response) { - var res = JSON.parse(response); - var addr = normalizeAddress(res[0].result); - if (addr.replace(/0+/g, "") === "") - { - var errorTxt = qsTr("Path does not exists " + JSON.stringify(dappUrl) + ". Please register using Registration Dapp. Aborting."); - deploymentError(errorTxt); - console.log(errorTxt); - callBack(false, "rootownedregistrar_notexist"); - } - else - { - dappUrl.splice(0, 1); - checkRegistration(dappUrl, addr, callBack, checkOnly); - } - }); - } -} - -function isOwner(addr, callBack) -{ - var requests = []; - requests.push({ - //getOwner() - jsonrpc: "2.0", - method: "eth_call", - params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0xb387ef92" }, "pending" ], - id: jsonRpcRequestId++ - }); - rpcCall(requests, function (httpRequest, response) { - var res = JSON.parse(response); - callBack(normalizeAddress(deploymentDialog.worker.currentAccount) === normalizeAddress(res[0].result)); - }); -} - -function checkRegistration(dappUrl, addr, callBack, checkOnly) -{ - isOwner(addr, function(ret){ - if (!ret) - { - var errorTxt = qsTr("You are not the owner of " + dappUrl[0] + ". Aborting"); - deploymentError(errorTxt); - console.log(errorTxt); - callBack(false, "ownedregistrar_notowner"); - } - else - continueRegistration(dappUrl, addr, callBack, checkOnly); - }); -} - -function continueRegistration(dappUrl, addr, callBack, checkOnly) -{ - if (dappUrl.length === 1) - { - if (!checkOnly) - registerContentHash(addr, callBack); // We do not create the register for the last part, just registering the content hash. - else - callBack(true); - } - else - { - var txt = qsTr("Checking " + JSON.stringify(dappUrl)); - deploymentStepChanged(txt); - console.log(txt); - var requests = []; - var registrar = {} - var str = clientModel.encodeStringParam(dappUrl[0]); - - - requests.push({ - //register() - jsonrpc: "2.0", - method: "eth_call", - params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0x5a3a05bd" + str }, "pending" ], - id: jsonRpcRequestId++ - }); - - rpcCall(requests, function (httpRequest, response) { - var res = JSON.parse(response); - var nextAddr = normalizeAddress(res[0].result); - var errorTxt; - if (res[0].result === "0x") - { - errorTxt = qsTr("Error when creating new owned registrar. Please use the registration Dapp. Aborting"); - deploymentError(errorTxt); - console.log(errorTxt); - callBack(false, "ownedregistrar_creationfailed"); - } - else if (nextAddr.replace(/0+/g, "") !== "") - { - dappUrl.splice(0, 1); - checkRegistration(dappUrl, nextAddr, callBack, checkOnly); - } - else - { - if (checkOnly) - { - callBack(true); - return; - } - var txt = qsTr("Registering sub domain " + dappUrl[0] + " ..."); - console.log(txt); - deploymentStepChanged(txt); - //current registrar is owned => ownedregistrar creation and continue. - requests = []; - var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarDeployGas); - requests.push({ - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "code": "0x600080547fffffffffffffffffffffffff000000000000000000000000000000000000000016331781556105cd90819061003990396000f3007c010000000000000000000000000000000000000000000000000000000060003504630198489281146100b257806321f8a721146100e45780632dff6941146100ee5780633b3b57de1461010e5780635a3a05bd1461013e5780635fd4b08a146101715780637dd564111461017d57806389a69c0e14610187578063b387ef92146101bb578063b5c645bd146101f4578063be99a98014610270578063c3d014d6146102a8578063d93e7573146102dc57005b73ffffffffffffffffffffffffffffffffffffffff600435166000908152600160205260409020548060005260206000f35b6000808052602081f35b600435600090815260026020819052604090912001548060005260206000f35b600435600090815260026020908152604082205473ffffffffffffffffffffffffffffffffffffffff1680835291f35b600435600090815260026020908152604082206001015473ffffffffffffffffffffffffffffffffffffffff1680835291f35b60008060005260206000f35b6000808052602081f35b60005461030c9060043590602435903373ffffffffffffffffffffffffffffffffffffffff908116911614610569576105c9565b60005473ffffffffffffffffffffffffffffffffffffffff168073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b600435600090815260026020819052604090912080546001820154919092015473ffffffffffffffffffffffffffffffffffffffff9283169291909116908273ffffffffffffffffffffffffffffffffffffffff166000528173ffffffffffffffffffffffffffffffffffffffff166020528060405260606000f35b600054610312906004359060243590604435903373ffffffffffffffffffffffffffffffffffffffff90811691161461045457610523565b6000546103189060043590602435903373ffffffffffffffffffffffffffffffffffffffff90811691161461052857610565565b60005461031e90600435903373ffffffffffffffffffffffffffffffffffffffff90811691161461032457610451565b60006000f35b60006000f35b60006000f35b60006000f35b60008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091529020548114610361576103e1565b6000818152600260205260408082205473ffffffffffffffffffffffffffffffffffffffff169183917ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a85459190a360008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091528120555b600081815260026020819052604080832080547fffffffffffffffffffffffff00000000000000000000000000000000000000009081168255600182018054909116905590910182905582917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b50565b600083815260026020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001683179055806104bb57827fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc60006040a2610522565b73ffffffffffffffffffffffffffffffffffffffff8216837ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a854560006040a373ffffffffffffffffffffffffffffffffffffffff821660009081526001602052604090208390555b5b505050565b600082815260026020819052604080832090910183905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b5050565b60008281526002602052604080822060010180547fffffffffffffffffffffffff0000000000000000000000000000000000000000168417905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b505056" } ], - id: jsonRpcRequestId++ - }); - - rpcCall(requests, function(httpRequest, response) { - var newCtrAddress = normalizeAddress(JSON.parse(response)[0].result); - requests = []; - var txt = qsTr("Please wait " + dappUrl[0] + " is registering ..."); - deploymentStepChanged(txt); - console.log(txt); - deploymentDialog.worker.waitForTrCountToIncrement(function(status) { - if (status === -1) - { - trCountIncrementTimeOut(); - return; - } - var crLevel = clientModel.encodeStringParam(dappUrl[0]); - var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas); - requests.push({ - //setRegister() - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + addr, "data": "0x89a69c0e" + crLevel + newCtrAddress } ], - id: jsonRpcRequestId++ - }); - - rpcCall(requests, function(request, response){ - dappUrl.splice(0, 1); - checkRegistration(dappUrl, newCtrAddress, callBack); - }); - }); - }); - } - }); - } -} - -function trCountIncrementTimeOut() -{ - var error = qsTr("Something went wrong during the deployment. Please verify the amount of gas for this transaction and check your balance.") - console.log(error); - deploymentError(error); -} - -function reserve(registrar, callBack) -{ - var txt = qsTr("Making reservation in the root registrar..."); - deploymentStepChanged(txt); - console.log(txt); - var requests = []; - var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); - requests.push({ - //reserve() - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0xfffff", "to": '0x' + registrar, "data": "0x432ced04" + paramTitle } ], - id: jsonRpcRequestId++ - }); - rpcCall(requests, function (httpRequest, response) { - callBack(); - }); -} - - -function registerContentHash(registrar, callBack) -{ - var txt = qsTr("Finalizing Dapp registration ..."); - deploymentStepChanged(txt); - console.log(txt); - console.log("register url " + deploymentDialog.packageStep.packageHash + " " + projectModel.projectTitle) - projectModel.registerContentHashTrHash = "" - var requests = []; - var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); - var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); - requests.push({ - //setContent() - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + registrar, "data": "0xc3d014d6" + paramTitle + deploymentDialog.packageStep.packageHash } ], - id: jsonRpcRequestId++ - }); - rpcCall(requests, function (httpRequest, response) { - projectModel.registerContentHashTrHash = JSON.parse(response)[0].result - callBack(true); - }); -} - -function registerToUrlHint(url, gasPrice, callback) -{ - console.log("register url " + deploymentDialog.packageStep.packageHash + " " + url) - deploymentGasPrice = gasPrice - deploymentStepChanged(qsTr("Registering application Resources...")) - urlHintAddress(function(urlHint){ - var requests = []; - var paramUrlHttp = clientModel.encodeStringParam(url) - var gasCost = clientModel.toHex(deploymentDialog.registerStep.urlHintSuggestUrlGas); - requests.push({ - //urlHint => suggestUrl - jsonrpc: "2.0", - method: "eth_sendTransaction", - params: [ { "to": '0x' + urlHint, "gasPrice": deploymentGasPrice, "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "data": "0x584e86ad" + deploymentDialog.packageStep.packageHash + paramUrlHttp } ], - id: jsonRpcRequestId++ - }); - - rpcCall(requests, function (httpRequest, response) { - projectModel.registerUrlTrHash = JSON.parse(response)[0].result - deploymentStepChanged(qsTr("Dapp resources has been registered. Please wait for verifications.")); - if (callback) - callback() - }); - }); -} - -function urlHintAddress(callBack) -{ - var requests = []; - var urlHint = clientModel.encodeStringParam("urlhint"); - requests.push({ - //registrar: get UrlHint addr - jsonrpc: "2.0", - method: "eth_call", - params: [ { "to": '0x' + deploymentDialog.registerStep.eth, "from": deploymentDialog.worker.currentAccount, "data": "0x3b3b57de" + urlHint }, "pending" ], - id: jsonRpcRequestId++ - }); - - rpcCall(requests, function (httpRequest, response) { - var res = JSON.parse(response); - callBack(normalizeAddress(res[0].result)); - }); -} - -function normalizeAddress(addr) -{ - addr = addr.replace('0x', ''); - if (addr.length <= 40) - return addr; - var left = addr.length - 40; - return addr.substring(left); -} - -function formatAppUrl(url) -{ - if (!url) - return [projectModel.projectTitle]; - if (url.toLowerCase().lastIndexOf("/") === url.length - 1) - url = url.substring(0, url.length - 1); - if (url.toLowerCase().indexOf("eth://") === 0) - url = url.substring(6); - if (url.toLowerCase().indexOf(projectModel.projectTitle + ".") === 0) - url = url.substring(projectModel.projectTitle.length + 1); - if (url === "") - return [projectModel.projectTitle]; - - var ret; - if (url.indexOf("/") === -1) - ret = url.split('.').reverse(); - else - { - var slash = url.indexOf("/"); - var left = url.substring(0, slash); - var leftA = left.split("."); - leftA.reverse(); - - var right = url.substring(slash + 1); - var rightA = right.split('/'); - ret = leftA.concat(rightA); - } - if (ret[0].toLowerCase() === "eth") - ret.splice(0, 1); - ret.push(projectModel.projectTitle); - return ret; -} diff --git a/mix/qml/js/Printer.js b/mix/qml/js/Printer.js deleted file mode 100644 index 2c53fe573..000000000 --- a/mix/qml/js/Printer.js +++ /dev/null @@ -1,90 +0,0 @@ -var prettyPrint = (function () { - function pp(object, indent) { - try { - JSON.stringify(object, null, 2); - } catch (e) { - return pp(e, indent); - } - - var str = ""; - if(object instanceof Array) { - str += "["; - for(var i = 0, l = object.length; i < l; i++) { - str += pp(object[i], indent); - if(i < l-1) { - str += ", "; - } - } - str += " ]"; - } else if (object instanceof Error) { - str += "\e[31m" + "Error:\e[0m " + object.message; - } else if (isBigNumber(object)) { - str += "\e[32m'" + object.toString(10) + "'"; - } else if(typeof(object) === "object") { - str += "{\n"; - indent += " "; - var last = getFields(object).pop() - getFields(object).forEach(function (k) { - str += indent + k + ": "; - try { - str += pp(object[k], indent); - } catch (e) { - str += pp(e, indent); - } - if(k !== last) { - str += ","; - } - str += "\n"; - }); - str += indent.substr(2, indent.length) + "}"; - } else if(typeof(object) === "string") { - str += "\e[32m'" + object + "'"; - } else if(typeof(object) === "undefined") { - str += "\e[1m\e[30m" + object; - } else if(typeof(object) === "number") { - str += "\e[31m" + object; - } else if(typeof(object) === "function") { - str += "\e[35m[Function]"; - } else { - str += object; - } - str += "\e[0m"; - return str; - } - var redundantFields = [ - 'valueOf', - 'toString', - 'toLocaleString', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor', - '__defineGetter__', - '__defineSetter__', - '__lookupGetter__', - '__lookupSetter__', - '__proto__' - ]; - var getFields = function (object) { - var result = Object.getOwnPropertyNames(object); - if (object.constructor && object.constructor.prototype) { - result = result.concat(Object.getOwnPropertyNames(object.constructor.prototype)); - } - return result.filter(function (field) { - return redundantFields.indexOf(field) === -1; - }); - }; - var isBigNumber = function (object) { - return typeof BigNumber !== 'undefined' && object instanceof BigNumber; - }; - function prettyPrintI(/* */) { - var args = arguments; - var ret = ""; - for (var i = 0, l = args.length; i < l; i++) { - ret += pp(args[i], "") + "\n"; - } - return ret; - } - return prettyPrintI; -})(); - diff --git a/mix/qml/js/ProjectModel.js b/mix/qml/js/ProjectModel.js deleted file mode 100644 index c482ac427..000000000 --- a/mix/qml/js/ProjectModel.js +++ /dev/null @@ -1,387 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file ProjectModel.js - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -var htmlTemplate = "\n\n\n\n\n\n\n"; -var contractTemplate = "contract Contract {\n}\n"; - -function saveCurrentDocument() -{ - var doc = projectListModel.get(getDocumentIndex(currentDocumentId)); - documentSaving(doc); - if (doc.isContract) - contractSaved(currentDocumentId); - else - documentSaved(currentDocumentId); -} - -function saveAll() { - saveProject(); -} - -function createProject() { - newProjectDialog.open(); -} - -function closeProject(callBack) { - if (!isEmpty && unsavedFiles.length > 0) - { - saveMessageDialog.callBack = callBack; - saveMessageDialog.open(); - } - else - { - projectIsClosing = true; - doCloseProject(); - if (callBack) - callBack(); - } -} - -function saveProject() { - if (!isEmpty) { - projectSaving(); - var projectData = saveProjectFile(); - if (projectData !== null) - { - projectSaved(); - } - } -} - -function saveProjectFile() -{ - if (!isEmpty) { - var projectData = { - files: [], - title: projectTitle, - deploymentAddresses: deploymentAddresses, - applicationUrlEth: projectModel.applicationUrlEth, - applicationUrlHttp: projectModel.applicationUrlHttp, - packageHash: deploymentDialog.packageStep.packageHash, - packageBase64: deploymentDialog.packageStep.packageBase64, - deploymentDir: deploymentDialog.packageStep.packageDir, - lastPackageDate: deploymentDialog.packageStep.lastDeployDate, - deployBlockNumber: projectModel.deployBlockNumber, - localPackageUrl: deploymentDialog.packageStep.localPackageUrl, - deploymentTrHashes: JSON.stringify(projectModel.deploymentTrHashes), - registerContentHashTrHash: projectModel.registerContentHashTrHash, - registerUrlTrHash: projectModel.registerUrlTrHash, - registerContentHashBlockNumber: projectModel.registerContentHashBlockNumber, - registerUrlBlockNumber: projectModel.registerUrlBlockNumber - }; - for (var i = 0; i < projectListModel.count; i++) - projectData.files.push({ - title: projectListModel.get(i).name, - fileName: projectListModel.get(i).fileName, - }); - - projectFileSaving(projectData); - var json = JSON.stringify(projectData, null, "\t"); - var projectFile = projectPath + projectFileName; - fileIo.writeFile(projectFile, json); - projectFileSaved(projectData); - return projectData; - } - return null; -} - -function loadProject(path) { - closeProject(function() { - console.log("Loading project at " + path); - var projectFile = path + projectFileName; - var json = fileIo.readFile(projectFile); - if (!json) - return; - var projectData = JSON.parse(json); - if (projectData.deploymentDir) - projectModel.deploymentDir = projectData.deploymentDir - if (projectData.packageHash) - deploymentDialog.packageStep.packageHash = projectData.packageHash - if (projectData.packageBase64) - deploymentDialog.packageStep.packageBase64 = projectData.packageBase64 - if (projectData.applicationUrlEth) - projectModel.applicationUrlEth = projectData.applicationUrlEth - if (projectData.applicationUrlHttp) - projectModel.applicationUrlHttp = projectData.applicationUrlHttp - if (projectData.lastPackageDate) - deploymentDialog.packageStep.lastDeployDate = projectData.lastPackageDate - if (projectData.deployBlockNumber) - projectModel.deployBlockNumber = projectData.deployBlockNumber - if (projectData.localPackageUrl) - deploymentDialog.packageStep.localPackageUrl = projectData.localPackageUrl - if (projectData.deploymentTrHashes) - projectModel.deploymentTrHashes = JSON.parse(projectData.deploymentTrHashes) - if (projectData.registerUrlTrHash) - projectModel.registerUrlTrHash = projectData.registerUrlTrHash - if (projectData.registerContentHashTrHash) - projectModel.registerContentHashTrHash = projectData.registerContentHashTrHash - if (projectData.registerContentHashBlockNumber) - projectModel.registerContentHashBlockNumber = projectData.registerContentHashBlockNumber - if (projectData.registerUrlBlockNumber) - projectModel.registerUrlBlockNumber = projectData.registerUrlBlockNumber - if (!projectData.title) { - var parts = path.split("/"); - projectData.title = parts[parts.length - 2]; - } - deploymentAddresses = projectData.deploymentAddresses ? projectData.deploymentAddresses : {}; - projectTitle = projectData.title; - projectPath = path; - if (!projectData.files) - projectData.files = []; - - for(var i = 0; i < projectData.files.length; i++) { - var entry = projectData.files[i]; - if (typeof(entry) === "string") - addFile(entry); //TODO: remove old project file support - else - addFile(entry.fileName, entry.title); - } - if (mainApplication.trackLastProject) - projectSettings.lastProjectPath = path; - projectLoading(projectData); - projectLoaded() - - //TODO: move this to codemodel - var contractSources = {}; - for (var d = 0; d < listModel.count; d++) { - var doc = listModel.get(d); - if (doc.isContract) - contractSources[doc.documentId] = fileIo.readFile(doc.path); - } - codeModel.reset(contractSources); - }); -} - -function addFile(fileName, title) { - var p = projectPath + fileName; - var extension = fileName.substring(fileName.lastIndexOf("."), fileName.length); - var isContract = extension === ".sol"; - var isHtml = extension === ".html"; - var isCss = extension === ".css"; - var isJs = extension === ".js"; - var isImg = extension === ".png" || extension === ".gif" || extension === ".jpg" || extension === ".svg"; - var syntaxMode = isContract ? "solidity" : isJs ? "javascript" : isHtml ? "htmlmixed" : isCss ? "css" : ""; - var groupName = isContract ? qsTr("Contracts") : isJs ? qsTr("Javascript") : isHtml ? qsTr("Web Pages") : isCss ? qsTr("Styles") : isImg ? qsTr("Images") : qsTr("Misc"); - var docData = { - contract: false, - path: p, - fileName: fileName, - name: title !== undefined ? title : fileName, - documentId: fileName, - syntaxMode: syntaxMode, - isText: isContract || isHtml || isCss || isJs, - isContract: isContract, - isHtml: isHtml, - groupName: groupName - }; - - projectListModel.append(docData); - fileIo.watchFileChanged(p); - return docData.documentId; -} - -function getDocumentIndex(documentId) -{ - for (var i = 0; i < projectListModel.count; i++) - if (projectListModel.get(i).documentId === documentId) - return i; - console.error("Can't find document " + documentId); - return -1; -} - -function getDocumentByPath(_path) -{ - for (var i = 0; i < projectListModel.count; i++) - { - var doc = projectListModel.get(i); - if (doc.path.indexOf(_path) !== -1) - return doc.documentId; - } - return null; -} - -function openDocument(documentId) { - if (documentId !== currentDocumentId) { - documentOpened(projectListModel.get(getDocumentIndex(documentId))); - currentDocumentId = documentId; - } -} - -function openNextDocument() { - var docIndex = getDocumentIndex(currentDocumentId); - var nextDocId = ""; - while (nextDocId === "") { - docIndex++; - if (docIndex >= projectListModel.count) - docIndex = 0; - var document = projectListModel.get(docIndex); - if (document.isText) - nextDocId = document.documentId; - } - openDocument(nextDocId); -} - -function openPrevDocument() { - var docIndex = getDocumentIndex(currentDocumentId); - var prevDocId = ""; - while (prevDocId === "") { - docIndex--; - if (docIndex < 0) - docIndex = projectListModel.count - 1; - var document = projectListModel.get(docIndex); - if (document.isText) - prevDocId = document.documentId; - } - openDocument(prevDocId); -} - -function doCloseProject() { - console.log("Closing project"); - projectListModel.clear(); - projectPath = ""; - currentDocumentId = ""; - projectClosed(); -} - -function doCreateProject(title, path) { - closeProject(function() { - console.log("Creating project " + title + " at " + path); - if (path[path.length - 1] !== "/") - path += "/"; - var dirPath = path + title + "/"; - fileIo.makeDir(dirPath); - var projectFile = dirPath + projectFileName; - - var indexFile = "index.html"; - var contractsFile = "contract.sol"; - var projectData = { - title: title, - files: [ contractsFile, indexFile ] - }; - //TODO: copy from template - if (!fileIo.fileExists(dirPath + indexFile)) - fileIo.writeFile(dirPath + indexFile, htmlTemplate); - if (!fileIo.fileExists(dirPath + contractsFile)) - fileIo.writeFile(dirPath + contractsFile, contractTemplate); - newProject(projectData); - var json = JSON.stringify(projectData, null, "\t"); - fileIo.writeFile(projectFile, json); - loadProject(dirPath); - }); -} - -function doAddExistingFiles(files) { - for(var i = 0; i < files.length; i++) { - var sourcePath = files[i]; - var sourceFileName = sourcePath.substring(sourcePath.lastIndexOf("/") + 1, sourcePath.length); - var destPath = projectPath + sourceFileName; - if (sourcePath !== destPath) - fileIo.copyFile(sourcePath, destPath); - var id = addFile(sourceFileName); - saveProjectFile(); - documentAdded(id) - } -} - -function renameDocument(documentId, newName) { - var i = getDocumentIndex(documentId); - var document = projectListModel.get(i); - if (!document.isContract) { - fileIo.stopWatching(document.path); - var sourcePath = document.path; - var destPath = projectPath + newName; - fileIo.moveFile(sourcePath, destPath); - document.path = destPath; - document.name = newName; - document.fileName = newName; - projectListModel.set(i, document); - fileIo.watchFileChanged(destPath); - saveProjectFile(); - documentUpdated(documentId); - } -} - -function getDocument(documentId) { - var i = getDocumentIndex(documentId); - if (i === -1) - return undefined; - else - return projectListModel.get(i); -} - -function getDocumentIdByName(fileName) -{ - for (var i = 0; i < projectListModel.count; i++) - if (projectListModel.get(i).fileName === fileName) - return projectListModel.get(i).documentId; - return null; -} - -function removeDocument(documentId) { - var i = getDocumentIndex(documentId); - var document = projectListModel.get(i); - fileIo.stopWatching(document.path); - fileIo.deleteFile(document.path); - if (document.isContract) - codeModel.unregisterContractSrc(documentId); - projectListModel.remove(i); - saveProjectFile(); - documentRemoved(documentId); -} - -function newHtmlFile() { - createAndAddFile("page", "html", htmlTemplate); -} - -function newCssFile() { - createAndAddFile("style", "css", "body {\n}\n"); -} - -function newJsFile() { - createAndAddFile("script", "js", "function foo() {\n}\n"); -} - -function newContract() { - createAndAddFile("contract", "sol", contractTemplate); -} - - -function createAndAddFile(name, extension, content) { - var fileName = generateFileName(name, extension); - var filePath = projectPath + fileName; - if (!fileIo.fileExists(filePath)) - fileIo.writeFile(filePath, content); - var id = addFile(fileName); - saveProjectFile(); - documentAdded(id); -} - -function generateFileName(name, extension) { - var i = 1; - do { - var fileName = name + i + "." + extension; - var filePath = projectPath + fileName; - i++; - } while (fileIo.fileExists(filePath)); - return fileName -} - diff --git a/mix/qml/js/QEtherHelper.js b/mix/qml/js/QEtherHelper.js deleted file mode 100644 index 7563941d2..000000000 --- a/mix/qml/js/QEtherHelper.js +++ /dev/null @@ -1,17 +0,0 @@ -function createEther(_value, _unit, _parent) -{ - var etherComponent = Qt.createComponent("qrc:/qml/EtherValue.qml"); - var ether = etherComponent.createObject(); - ether.setValue(_value); - ether.setUnit(_unit); - return ether; -} - -function createBigInt(_value) -{ - var bigintComponent = Qt.createComponent("qrc:/qml/BigIntValue.qml"); - var bigint = bigintComponent.createObject(); - bigint.setValue(_value); - return bigint; -} - diff --git a/mix/qml/js/TransactionHelper.js b/mix/qml/js/TransactionHelper.js deleted file mode 100644 index 7287c2fba..000000000 --- a/mix/qml/js/TransactionHelper.js +++ /dev/null @@ -1,55 +0,0 @@ -Qt.include("QEtherHelper.js") - -function defaultTransaction() -{ - return { - value: createEther("0", QEther.Wei), - functionId: "", - gas: createBigInt("250000"), - gasAuto: true, - gasPrice: createEther("100000", QEther.Wei), - parameters: {}, - stdContract: false, - isContractCreation: true, - label: "", - isFunctionCall: true, - saveStatus: true - }; -} - -function rpcCall(requests, callBack, error) -{ - var jsonRpcUrl = appSettings.nodeAddress; - var rpcRequest = JSON.stringify(requests); - console.log(rpcRequest); - var httpRequest = new XMLHttpRequest(); - httpRequest.open("POST", jsonRpcUrl, true); - httpRequest.setRequestHeader("Content-type", "application/json"); - httpRequest.setRequestHeader("Content-length", rpcRequest.length); - httpRequest.setRequestHeader("Connection", "close"); - httpRequest.onreadystatechange = function() { - if (httpRequest.readyState === XMLHttpRequest.DONE) { - if (httpRequest.status !== 200 || httpRequest.responseText === "") - { - var errorText = qsTr("Unable to initiate request to the live network. Please verify your ethereum node is up.") + qsTr(" Error status: ") + httpRequest.status; - console.log(errorText); - if (error) - error(errorText); - } - else - { - console.log(httpRequest.responseText); - callBack(httpRequest.status, httpRequest.responseText) - } - } - } - httpRequest.send(rpcRequest); -} - -function contractFromToken(token) -{ - if (token.indexOf('<') === 0) - return token.replace("<", "").replace(">", "").split(" - ")[0]; - return token; -} - diff --git a/mix/qml/js/ansi2html.js b/mix/qml/js/ansi2html.js deleted file mode 100644 index 8f53fab24..000000000 --- a/mix/qml/js/ansi2html.js +++ /dev/null @@ -1,106 +0,0 @@ -var ansi2html = (function(){ - - function ansi2htmlI(str) { - // this lib do not support \e - str = str.replace(/e\[/g, '['); - // nor line breaks - str = '
' + str.replace(/\n/g, '
') + '
'; - var props = {} - , open = false - - var stylemap = - { bold: "font-weight" - , underline: "text-decoration" - , color: "color" - , background: "background" - } - - function style() { - var key, val, style = [] - for (var key in props) { - val = props[key] - if (!val) continue - if (val == true) { - style.push(stylemap[key] + ':' + key) - } else { - style.push(stylemap[key] + ':' + val) - } - } - return style.join(';') - } - - - function tag(code) { - var i - , tag = '' - , n = ansi2htmlI.table[code] - - if (open) tag += '' - open = false - - if (n) { - for (i in n) props[i] = n[i] - tag += '' - open = true - } else { - props = {} - } - - return tag - } - - return str.replace(/\[(\d+;)?(\d+)*m/g, function(match, b1, b2) { - var i, code, res = '' - if (b2 == '' || b2 == null) b2 = '0' - for (i = 1; i < arguments.length - 2; i++) { - if (!arguments[i]) continue - code = parseInt(arguments[i]) - res += tag(code) - } - return res - }) + tag() - } - - /* not implemented: - * italic - * blink - * invert - * strikethrough - */ - ansi2htmlI.table = - { 0: null - , 1: { bold: true } - , 3: { italic: true } - , 4: { underline: true } - , 5: { blink: true } - , 6: { blink: true } - , 7: { invert: true } - , 9: { strikethrough: true } - , 23: { italic: false } - , 24: { underline: false } - , 25: { blink: false } - , 27: { invert: false } - , 29: { strikethrough: false } - , 30: { color: 'black' } - , 31: { color: 'red' } - , 32: { color: 'green' } - , 33: { color: 'yellow' } - , 34: { color: 'blue' } - , 35: { color: 'magenta' } - , 36: { color: 'cyan' } - , 37: { color: 'white' } - , 39: { color: null } - , 40: { background: 'black' } - , 41: { background: 'red' } - , 42: { background: 'green' } - , 43: { background: 'yellow' } - , 44: { background: 'blue' } - , 45: { background: 'magenta' } - , 46: { background: 'cyan' } - , 47: { background: 'white' } - , 49: { background: null } - } - - return ansi2htmlI; -})(); - diff --git a/mix/res.qrc b/mix/res.qrc deleted file mode 100644 index 6b6641d1c..000000000 --- a/mix/res.qrc +++ /dev/null @@ -1,100 +0,0 @@ - - - qml/fonts/SourceSansPro-Black.ttf - qml/fonts/SourceSansPro-BlackIt.ttf - qml/fonts/SourceSansPro-Bold.ttf - qml/fonts/SourceSansPro-BoldIt.ttf - qml/fonts/SourceSansPro-ExtraLight.ttf - qml/fonts/SourceSansPro-ExtraLightIt.ttf - qml/fonts/SourceSansPro-It.ttf - qml/fonts/SourceSansPro-Light.ttf - qml/fonts/SourceSansPro-LightIt.ttf - qml/fonts/SourceSansPro-Regular.ttf - qml/fonts/SourceSansPro-Semibold.ttf - qml/fonts/SourceSansPro-SemiboldIt.ttf - qml/fonts/SourceSerifPro-Bold.ttf - qml/fonts/SourceSerifPro-Regular.ttf - qml/fonts/SourceSerifPro-Semibold.ttf - qml/img/available_updates.png - qml/img/b64.png - qml/img/bugiconactive.png - qml/img/bugiconinactive.png - qml/img/closedtriangleindicator.png - qml/img/closedtriangleindicator@2x.png - qml/img/closedtriangleindicator_filesproject.png - qml/img/console.png - qml/img/copy.png - qml/img/dappProjectIcon.png - qml/img/delete_sign.png - qml/img/edit.png - qml/img/exit.png - qml/img/help.png - qml/img/jumpintoback.png - qml/img/jumpintobackdisabled.png - qml/img/jumpintoforward.png - qml/img/jumpintoforwarddisabled.png - qml/img/jumpoutback.png - qml/img/jumpoutbackdisabled.png - qml/img/jumpoutforward.png - qml/img/jumpoutforwarddisabled.png - qml/img/jumpoverback.png - qml/img/jumpoverbackdisabled.png - qml/img/jumpoverforward.png - qml/img/jumpoverforwarddisabled.png - qml/img/note.png - qml/img/openedfolder.png - qml/img/opentriangleindicator.png - qml/img/opentriangleindicator@2x.png - qml/img/opentriangleindicator_filesproject.png - qml/img/plus.png - qml/img/projecticon.png - qml/img/run.png - qml/img/search_filled.png - qml/img/play_button2x.png - qml/img/play_button.png - qml/img/pause_button2x.png - qml/img/pause_button.png - res/mix_256x256x32.png - stdc/config.sol - stdc/namereg.sol - stdc/std.sol - qml/img/edit_combox.png - qml/img/clearicon.png - qml/img/cleariconactive.png - qml/img/copyicon.png - qml/img/copyiconactive.png - qml/img/searchicon.png - qml/img/stop_button2x.png - qml/img/warningicon.png - qml/img/warningicon@2x.png - qml/QAddressView.qml - qml/img/addblock.png - qml/img/addblock@2x.png - qml/img/duplicateicon.png - qml/img/duplicateicon@2x.png - qml/img/leftarrow.png - qml/img/leftarrow@2x.png - qml/img/newaccounticon.png - qml/img/newaccounticon@2x.png - qml/img/recyclediscard.png - qml/img/recyclediscard@2x.png - qml/img/recycleicon.png - qml/img/recycleicon@2x.png - qml/img/recyclekeep.png - qml/img/recyclekeep@2x.png - qml/img/restoreicon.png - qml/img/restoreicon@2x.png - qml/img/rightarrow.png - qml/img/rightarrow@2x.png - qml/img/rightarrowcircle.png - qml/img/saveicon.png - qml/img/saveicon@2x.png - qml/img/sendtransactionicon.png - qml/img/sendtransactionicon@2x.png - qml/img/edittransaction@2x.png - qml/img/newblock@2x.png - qml/img/edittransaction2@2x.png - qml/img/edittransaction.png - qml/img/edittransaction2.png - - diff --git a/mix/res/mix_256x256x32.png b/mix/res/mix_256x256x32.png deleted file mode 100644 index 722b6b9bc..000000000 Binary files a/mix/res/mix_256x256x32.png and /dev/null differ diff --git a/mix/stdc/config.sol b/mix/stdc/config.sol deleted file mode 100644 index f05412f25..000000000 --- a/mix/stdc/config.sol +++ /dev/null @@ -1,45 +0,0 @@ -//sol Config -// Simple global configuration registrar. -// @authors: -// Gav Wood -#require mortal -contract Config is mortal { - function register(uint id, address service) { - if (tx.origin != owner) - return; - services[id] = service; - log1(0, id); - } - - function unregister(uint id) { - if (msg.sender != owner && services[id] != msg.sender) - return; - services[id] = address(0); - log1(0, id); - } - - function lookup(uint service) constant returns(address a) { - return services[service]; - } - - mapping (uint => address) services; -} - -/* - -// Solidity Interface: -contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}} - -// Example Solidity use: -address addrConfig = 0xf025d81196b72fba60a1d4dddad12eeb8360d828; -address addrNameReg = Config(addrConfig).lookup(1); - -// JS Interface: -var abiConfig = [{"constant":false,"inputs":[],"name":"kill","outputs":[]},{"constant":true,"inputs":[{"name":"service","type":"uint256"}],"name":"lookup","outputs":[{"name":"a","type":"address"}]},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"service","type":"address"}],"name":"register","outputs":[]},{"constant":false,"inputs":[{"name":"id","type":"uint256"}],"name":"unregister","outputs":[]}]; - -// Example JS use: -var addrConfig = "0x661005d2720d855f1d9976f88bb10c1a3398c77f"; -var addrNameReg; -web3.eth.contract(addrConfig, abiConfig).lookup(1).call().then(function(r){ addrNameReg = r; }) - -*/ diff --git a/mix/stdc/namereg.sol b/mix/stdc/namereg.sol deleted file mode 100644 index 0886f5f71..000000000 --- a/mix/stdc/namereg.sol +++ /dev/null @@ -1,74 +0,0 @@ -//sol NameReg -// Simple global name registrar. -// @authors: -// kobigurk (from #ethereum-dev) -// Gav Wood - -contract NameRegister { - function getAddress(string32 _name) constant returns (address o_owner) {} - function getName(address _owner) constant returns (string32 o_name) {} -} - -#require Config, owned -contract NameReg is owned, NameRegister { - function NameReg() { - address addrConfig = 0xf025d81196b72fba60a1d4dddad12eeb8360d828; - toName[addrConfig] = "Config"; - toAddress["Config"] = addrConfig; - toName[this] = "NameReg"; - toAddress["NameReg"] = this; - Config(addrConfig).register(1, this); - log1(0, hash256(Config())); - log1(0, hash256(this)); - } - - function register(string32 name) { - // Don't allow the same name to be overwritten. - if (toAddress[name] != address(0)) - return; - // Unregister previous name if there was one. - if (toName[msg.sender] != "") - toAddress[toName[msg.sender]] = 0; - - toName[msg.sender] = name; - toAddress[name] = msg.sender; - log1(0, hash256(msg.sender)); - } - - function unregister() { - string32 n = toName[msg.sender]; - if (n == "") - return; - log1(0, hash256(toAddress[n])); - toName[msg.sender] = ""; - toAddress[n] = address(0); - } - - function addressOf(string32 name) constant returns (address addr) { - return toAddress[name]; - } - - function nameOf(address addr) constant returns (string32 name) { - return toName[addr]; - } - - mapping (address => string32) toName; - mapping (string32 => address) toAddress; -} - - -/* - -// Solidity Interface: -contract NameReg{function kill(){}function register(string32 name){}function addressOf(string32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(string32 name){}} - -// Example Solidity use: -NameReg(addrNameReg).register("Some Contract"); - -// JS Interface: -var abiNameReg = [{"constant":true,"inputs":[{"name":"name","type":"string32"}],"name":"addressOf","outputs":[{"name":"addr","type":"address"}]},{"constant":false,"inputs":[],"name":"kill","outputs":[]},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"nameOf","outputs":[{"name":"name","type":"string32"}]},{"constant":false,"inputs":[{"name":"name","type":"string32"}],"name":"register","outputs":[]},{"constant":false,"inputs":[],"name":"unregister","outputs":[]}]; - -// Example JS use: -web3.eth.contract(addrNameReg, abiNameReg).register("My Name").transact(); - -*/ diff --git a/mix/stdc/std.sol b/mix/stdc/std.sol deleted file mode 100644 index 3e9755e6a..000000000 --- a/mix/stdc/std.sol +++ /dev/null @@ -1,118 +0,0 @@ -//TODO: use imports -contract owned{function owned(){owner = msg.sender;}modifier onlyowner(){if(msg.sender==owner)_}address owner;} -contract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }} - -//sol Config -// Simple global configuration registrar. -// @authors: -// Gav Wood - - -contract Config is mortal { - function register(uint id, address service) { - if (tx.origin != owner) - return; - services[id] = service; - } - - function unregister(uint id) { - if (msg.sender != owner && services[id] != msg.sender) - return; - services[id] = address(0); - } - - function lookup(uint service) constant returns(address a) { - return services[service]; - } - - mapping (uint => address) services; -} - -/* - -// Solidity Interface: -contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}} - -// Example Solidity use: -address addrConfig = 0xf025d81196b72fba60a1d4dddad12eeb8360d828; -address addrNameReg = Config(addrConfig).lookup(1); - -// JS Interface: -var abiConfig = [{"constant":false,"inputs":[],"name":"kill","outputs":[]},{"constant":true,"inputs":[{"name":"service","type":"uint256"}],"name":"lookup","outputs":[{"name":"a","type":"address"}]},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"service","type":"address"}],"name":"register","outputs":[]},{"constant":false,"inputs":[{"name":"id","type":"uint256"}],"name":"unregister","outputs":[]}]; - -// Example JS use: -var addrConfig = "0x661005d2720d855f1d9976f88bb10c1a3398c77f"; -var addrNameReg; -web3.eth.contract(addrConfig, abiConfig).lookup(1).call().then(function(r){ addrNameReg = r; }) - -*/ - -//sol NameReg -// Simple global name registrar. -// @authors: -// kobigurk (from #ethereum-dev) -// Gav Wood - -contract NameRegister { - function getAddress(bytes32 _name) constant returns (address o_owner) {} - function getName(address _owner) constant returns (bytes32 o_name) {} -} - -contract NameReg is owned, NameRegister { - function NameReg() { - address addrConfig = 0xf025d81196b72fba60a1d4dddad12eeb8360d828; - toName[addrConfig] = "Config"; - toAddress["Config"] = addrConfig; - toName[this] = "NameReg"; - toAddress["NameReg"] = this; - Config(addrConfig).register(1, this); - } - - function register(bytes32 name) { - // Don't allow the same name to be overwritten. - if (toAddress[name] != address(0)) - return; - // Unregister previous name if there was one. - if (toName[msg.sender] != "") - toAddress[toName[msg.sender]] = 0; - - toName[msg.sender] = name; - toAddress[name] = msg.sender; - } - - function unregister() { - bytes32 n = toName[msg.sender]; - if (n == "") - return; - toName[msg.sender] = ""; - toAddress[n] = address(0); - } - - function addressOf(bytes32 name) constant returns (address addr) { - return toAddress[name]; - } - - function nameOf(address addr) constant returns (bytes32 name) { - return toName[addr]; - } - - mapping (address => bytes32) toName; - mapping (bytes32 => address) toAddress; -} - - -/* - -// Solidity Interface: -contract NameReg{function kill(){}function register(bytes32 name){}function addressOf(bytes32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(bytes32 name){}} - -// Example Solidity use: -NameReg(addrNameReg).register("Some Contract"); - -// JS Interface: -var abiNameReg = [{"constant":true,"inputs":[{"name":"name","type":"bytes32"}],"name":"addressOf","outputs":[{"name":"addr","type":"address"}]},{"constant":false,"inputs":[],"name":"kill","outputs":[]},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"nameOf","outputs":[{"name":"name","type":"bytes32"}]},{"constant":false,"inputs":[{"name":"name","type":"bytes32"}],"name":"register","outputs":[]},{"constant":false,"inputs":[],"name":"unregister","outputs":[]}]; - -// Example JS use: -web3.eth.contract(addrNameReg, abiNameReg).register("My Name").transact(); - -*/ diff --git a/mix/style.xml b/mix/style.xml deleted file mode 100644 index 75626ac24..000000000 --- a/mix/style.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - CodeStyleData - - false - 4 - 2 - false - 4 - - - - DisplayName - Eth - - diff --git a/mix/test.qrc b/mix/test.qrc deleted file mode 100644 index e7d2271a4..000000000 --- a/mix/test.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - test/TestMain.qml - test/TestTransactionDebug.qml - - diff --git a/mix/test/TestMain.cpp b/mix/test/TestMain.cpp deleted file mode 100644 index f21319004..000000000 --- a/mix/test/TestMain.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file main.cpp - * @author Yann yann@ethdev.com - * @date 2014 - * Ethereum IDE client. - */ - -#include -#include -#include -#include -#include "MixApplication.h" -#include "Exceptions.h" -#include "TestService.h" - -using namespace dev::mix; - -int main(int _argc, char* _argv[]) -{ - try - { - MixApplication::initialize(); - qmlRegisterType("org.ethereum.qml.TestService", 1, 0, "TestService"); - - return quick_test_main(_argc, _argv, "mix", _argv[1]); - } - catch (boost::exception const& _e) - { - std::cerr << boost::diagnostic_information(_e); - } - catch (std::exception const& _e) - { - std::cerr << _e.what(); - } -} diff --git a/mix/test/TestService.cpp b/mix/test/TestService.cpp deleted file mode 100644 index 487dac880..000000000 --- a/mix/test/TestService.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file TestService.cpp - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#include "TestService.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace mix -{ - -enum MouseAction { MousePress, MouseRelease, MouseClick, MouseDoubleClick, MouseMove }; - -static void mouseEvent(MouseAction _action, QWindow* _window, QObject* _item, Qt::MouseButton _button, Qt::KeyboardModifiers _stateKey, QPointF _pos, int _delay = -1) -{ - if (_delay == -1 || _delay < 30) - _delay = 30; - if (_delay > 0) - QTest::qWait(_delay); - - if (_action == MouseClick) - { - mouseEvent(MousePress, _window, _item, _button, _stateKey, _pos); - mouseEvent(MouseRelease, _window, _item, _button, _stateKey, _pos); - return; - } - - QPoint pos = _pos.toPoint(); - QQuickItem* sgitem = qobject_cast(_item); - if (sgitem) - pos = sgitem->mapToScene(_pos).toPoint(); - - _stateKey &= static_cast(Qt::KeyboardModifierMask); - - QMouseEvent me(QEvent::User, QPoint(), Qt::LeftButton, _button, _stateKey); - switch (_action) - { - case MousePress: - me = QMouseEvent(QEvent::MouseButtonPress, pos, _window->mapToGlobal(pos), _button, _button, _stateKey); - break; - case MouseRelease: - me = QMouseEvent(QEvent::MouseButtonRelease, pos, _window->mapToGlobal(pos), _button, 0, _stateKey); - break; - case MouseDoubleClick: - me = QMouseEvent(QEvent::MouseButtonDblClick, pos, _window->mapToGlobal(pos), _button, _button, _stateKey); - break; - case MouseMove: - // with move event the _button is NoButton, but 'buttons' holds the currently pressed buttons - me = QMouseEvent(QEvent::MouseMove, pos, _window->mapToGlobal(pos), Qt::NoButton, _button, _stateKey); - break; - default: - break; - } - QSpontaneKeyEvent::setSpontaneous(&me); - if (!qApp->notify(_window, &me)) - { - static const char* mouseActionNames[] = { "MousePress", "MouseRelease", "MouseClick", "MouseDoubleClick", "MouseMove" }; - QString warning = QString::fromLatin1("Mouse event \"%1\" not accepted by receiving window"); - QWARN(warning.arg(QString::fromLatin1(mouseActionNames[static_cast(_action)])).toLatin1().data()); - } -} - -bool TestService::waitForSignal(QObject* _item, QString _signalName, int _timeout) -{ - QSignalSpy spy(_item, ("2" + _signalName.toStdString()).c_str()); - QMetaObject const* mo = _item->metaObject(); - - QStringList methods; - - for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) - if (mo->method(i).methodType() == QMetaMethod::Signal) - methods << QString::fromLatin1(mo->method(i).methodSignature()); - - QElapsedTimer timer; - timer.start(); - - while (!spy.size()) - { - int remaining = _timeout - int(timer.elapsed()); - if (remaining <= 0) - break; - QCoreApplication::processEvents(QEventLoop::AllEvents, remaining); - QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete); - QTest::qSleep(10); - } - - return spy.size(); -} - -bool TestService::waitForRendering(QObject* _item, int timeout) -{ - QWindow* window = eventWindow(_item); - return waitForSignal(window, "frameSwapped()", timeout); -} - -bool TestService::keyPress(QObject* _item, int _key, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyPress(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::keyRelease(QObject* _item, int _key, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyRelease(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::keyClick(QObject* _item, int _key, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyClick(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::keyPressChar(QObject* _item, QString const& _character, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyPress(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::keyReleaseChar(QObject* _item, QString const& _character, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyRelease(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::keyClickChar(QObject* _item, QString const& _character, int _modifiers, int _delay) -{ - QWindow* window = eventWindow(_item); - QTest::keyClick(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay); - return true; -} - -bool TestService::mouseClick(QObject* _item, qreal _x, qreal _y, int _button, int _modifiers, int _delay) -{ - QWindow* window = qobject_cast(_item); - if (!window) - window = eventWindow(_item); - mouseEvent(MouseClick, window, _item, Qt::MouseButton(_button), Qt::KeyboardModifiers(_modifiers), QPointF(_x, _y), _delay); - return true; -} - -void TestService::setTargetWindow(QObject* _window) -{ - QQuickWindow* window = qobject_cast(_window); - if (window) - m_targetWindow = window; - window->requestActivate(); -} - -QWindow* TestService::eventWindow(QObject* _item) -{ - QQuickItem* item = qobject_cast(_item); - if (item && item->window()) - return item->window(); - - QWindow* window = qobject_cast(_item); - if (!window && _item->parent()) - window = eventWindow(_item->parent()); - if (!window) - window = qobject_cast(m_targetWindow); - if (window) - { - window->requestActivate(); - std::cout << window->title().toStdString(); - return window; - } - item = qobject_cast(m_targetWindow); - if (item) - return item->window(); - return 0; -} - -QString TestService::createUuid() const -{ - return QUuid::createUuid().toString(); -} - -} -} diff --git a/mix/test/TestService.h b/mix/test/TestService.h deleted file mode 100644 index 55f02479f..000000000 --- a/mix/test/TestService.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** @file TestService.h - * @author Arkadiy Paronyan arkadiy@ethdev.com - * @date 2015 - * Ethereum IDE client. - */ - -#pragma once - -#include - -class QWindow; - -namespace dev -{ -namespace mix -{ - -class TestService: public QObject -{ - Q_OBJECT - Q_PROPERTY(QObject* targetWindow READ targetWindow WRITE setTargetWindow) - -public: - QObject* targetWindow() const { return m_targetWindow; } - void setTargetWindow(QObject* _window); - -public slots: - QString createUuid() const; - bool waitForSignal(QObject* _item, QString _signalName, int _timeout); - bool waitForRendering(QObject* _item, int timeout); - bool keyPress(QObject* _item, int _key, int _modifiers, int _delay); - bool keyRelease(QObject* _item, int _key, int _modifiers, int _delay); - bool keyClick(QObject* _item, int _key, int _modifiers, int _delay); - bool keyPressChar(QObject* _item, QString const& _character, int _modifiers, int _delay); - bool keyReleaseChar(QObject* _item, QString const& _character, int _modifiers, int _delay); - bool keyClickChar(QObject* _item, QString const& _character, int _modifiers, int _delay); - bool mouseClick(QObject* _item, qreal _x, qreal _y, int _button, int _modifiers, int _delay); - -private: - QWindow* eventWindow(QObject* _item); - QObject* m_targetWindow; -}; - -} -} diff --git a/mix/test/qml/TestMain.qml b/mix/test/qml/TestMain.qml deleted file mode 100644 index 727d90b25..000000000 --- a/mix/test/qml/TestMain.qml +++ /dev/null @@ -1,118 +0,0 @@ -import QtQuick 2.2 -import QtTest 1.1 -import org.ethereum.qml.TestService 1.0 -import "../../qml" -import "js/TestDebugger.js" as TestDebugger -import "js/TestTutorial.js" as TestTutorial -import "js/TestMiner.js" as TestMiner -import "js/TestProject.js" as TestProject - -TestCase -{ - id: tc - TestService - { - id: ts - targetWindow: mainApplication - function typeString(str, el) - { - if (el === undefined) - el = mainApplication; - if (el.contentItem) //for dialgos - el = el.contentItem - - for (var c in str) - { - ts.keyPressChar(el, str[c], Qt.NoModifier, 0); - ts.keyReleaseChar(el, str[c], Qt.NoModifier, 0); - } - } - } - - Application - { - id: mainApplication - trackLastProject: false - } - - function newProject() - { - mainApplication.projectModel.createProject(); - var projectDlg = mainApplication.projectModel.newProjectDialog; - wait(30); - projectDlg.projectTitle = "TestProject"; - projectDlg.pathFieldText = "/tmp/MixTest/" + ts.createUuid(); //TODO: get platform temp path - projectDlg.acceptAndClose(); - wait(1); - if (!ts.waitForSignal(mainApplication.codeModel, "compilationComplete()", 5000)) - fail("new contract not compiled"); - } - - function editContract(c) - { - if (mainApplication.codeModel.compiling) - ts.waitForSignal(mainApplication.codeModel, "compilationComplete()", 5000); - mainApplication.mainContent.codeEditor.getEditor("contract.sol").setText(c); - if (!ts.waitForSignal(mainApplication.codeModel, "compilationComplete()", 5000)) - fail("not compiled"); - ts.keyPressChar(mainApplication, "S", Qt.ControlModifier, 200); //Ctrl+S - } - - function waitForMining() - { - while (mainApplication.clientModel.mining) - ts.waitForSignal(mainApplication.clientModel, "miningComplete()", 5000); - wait(1); //allow events to propagate 2 times for transaction log to be updated - wait(1); - } - - function waitForExecution() - { - while (mainApplication.clientModel.running) - ts.waitForSignal(mainApplication.clientModel, "runComplete()", 5000); - wait(1); //allow events to propagate 2 times for transaction log to be updated - wait(1); - } - - function editHtml(c) - { - mainApplication.projectModel.openDocument("index.html"); - ts.waitForSignal(mainApplication.mainContent.codeEditor, "loadComplete()", 5000); - mainApplication.mainContent.codeEditor.getEditor("index.html").setText(c); - ts.keyPressChar(mainApplication, "S", Qt.ControlModifier, 200); //Ctrl+S - } - - function createHtml(name, c) - { - mainApplication.projectModel.newHtmlFile(); - ts.waitForSignal(mainApplication.mainContent.codeEditor, "loadComplete()", 5000); - var doc = mainApplication.projectModel.listModel.get(mainApplication.projectModel.listModel.count - 1); - mainApplication.projectModel.renameDocument(doc.documentId, name); - mainApplication.mainContent.codeEditor.getEditor(doc.documentId).setText(c); - ts.keyPressChar(mainApplication, "S", Qt.ControlModifier, 200); //Ctrl+S - } - - function clickElement(el, x, y) - { - if (el.contentItem) - el = el.contentItem; - ts.mouseClick(el, x, y, Qt.LeftButton, Qt.NoModifier, 10) - } - - function test_tutorial() { TestTutorial.test_tutorial(); } - function test_dbg_defaultTransactionSequence() { TestDebugger.test_defaultTransactionSequence(); } - function test_dbg_transactionWithParameter() { TestDebugger.test_transactionWithParameter(); } - function test_dbg_constructorParameters() { TestDebugger.test_constructorParameters(); } - function test_dbg_arrayParametersAndStorage() { TestDebugger.test_arrayParametersAndStorage(); } - function test_dbg_solidity() { TestDebugger.test_solidityDebugging(); } - function test_dbg_vm() { TestDebugger.test_vmDebugging(); } - function test_dbg_ctrTypeAsParam() { TestDebugger.test_ctrTypeAsParam(); } - function test_miner_getDefaultiner() { TestMiner.test_getDefaultMiner(); } - function test_miner_selectMiner() { TestMiner.test_selectMiner(); } - function test_miner_mine() { TestMiner.test_mine(); } - function test_project_contractRename() { TestProject.test_contractRename(); } - function test_project_multipleWebPages() { TestProject.test_multipleWebPages(); } - function test_project_multipleContractsSameFile() { TestProject.test_multipleContractsSameFile(); } - function test_project_deleteFile() { TestProject.test_deleteFile(); } -} - diff --git a/mix/test/qml/js/TestDebugger.js b/mix/test/qml/js/TestDebugger.js deleted file mode 100644 index 4e295c46f..000000000 --- a/mix/test/qml/js/TestDebugger.js +++ /dev/null @@ -1,243 +0,0 @@ -function test_defaultTransactionSequence() -{ - newProject(); - editContract( - "contract Contract {\r" + - " function Contract() {\r" + - " uint x = 69;\r" + - " uint y = 5;\r" + - " for (uint i = 0; i < y; ++i) {\r" + - " x += 42;\r" + - " z += x;\r" + - " }\r" + - " }\r" + - " uint z;\r" + - "}\r" - ); - waitForExecution(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel, "count", 3); -} - -function test_transactionWithParameter() -{ - newProject(); - editContract( - "contract Contract {\r" + - " function setZ(uint256 x) {\r" + - " z = x;\r" + - " }\r" + - " function getZ() returns(uint256) {\r" + - " return z;\r" + - " }\r" + - " uint z;\r" + - "}\r" - ); - mainApplication.projectModel.stateListModel.editState(0); - mainApplication.projectModel.stateDialog.model.addTransaction(); - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectFunction("setZ"); - clickElement(transactionDialog, 140, 300); - ts.typeString("442", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.model.addTransaction(); - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectFunction("getZ"); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.acceptAndClose(); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel, "count", 5); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(4), "returned", "(442)"); -} - -function test_constructorParameters() -{ - newProject(); - editContract( - "contract Contract {\r" + - " function Contract(uint256 x) {\r" + - " z = x;\r" + - " }\r" + - " function getZ() returns(uint256) {\r" + - " return z;\r" + - " }\r" + - " uint z;\r" + - "}\r" - ); - mainApplication.projectModel.stateListModel.editState(0); - mainApplication.projectModel.stateDialog.model.editTransaction(2); - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - ts.waitForRendering(transactionDialog, 3000); - clickElement(transactionDialog, 140, 300); - ts.typeString("442", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.model.addTransaction(); - transactionDialog.selectFunction("getZ"); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.acceptAndClose(); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel, "count", 4); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(3), "returned", "(442)"); -} - -function test_arrayParametersAndStorage() -{ - newProject(); - editContract( - " contract ArrayTest {\r" + - " function setM(uint256[] x) external\r" + - " {\r" + - " m = x;\r" + - " s = 5;\r" + - " signed = 6534;\r" + - " }\r" + - " \r" + - " function setMV(uint72[5] x) external\r" + - " {\r" + - " mv = x;\r" + - " s = 42;\r" + - " signed = -534;\r" + - " }\r" + - " \r" + - " uint256[] m;\r" + - " uint72[5] mv;\r" + - " uint256 s;\r" + - " int48 signed;\r" + - " }\r"); - - mainApplication.projectModel.stateListModel.editState(0); - mainApplication.projectModel.stateDialog.model.addTransaction(); - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectFunction("setM"); - clickElement(transactionDialog, 140, 300); - ts.typeString("4,5,6,2,10", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.model.addTransaction(); - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectFunction("setMV"); - clickElement(transactionDialog, 140, 300); - ts.typeString("13,35,1,4", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.acceptAndClose(); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - //debug setM - mainApplication.clientModel.debugRecord(3); - mainApplication.mainContent.rightPane.debugSlider.value = mainApplication.mainContent.rightPane.debugSlider.maximumValue; - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "m", ["4","5","6","2","10"]); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "s", "5"); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "signed", "6534"); - //debug setMV - mainApplication.clientModel.debugRecord(4); - mainApplication.mainContent.rightPane.debugSlider.value = mainApplication.mainContent.rightPane.debugSlider.maximumValue - 1; - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "mv", ["13","35","1","4","0"]); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "s", "42"); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "signed", "-534"); - tryCompare(mainApplication.mainContent.rightPane.solCallStack.listModel, 0, "setMV"); -} - -function test_solidityDebugging() -{ - newProject(); - editContract( - "contract Contract {\r " + - " function add(uint256 a, uint256 b) returns (uint256)\r " + - " {\r " + - " return a + b;\r " + - " }\r " + - " function Contract()\r " + - " {\r " + - " uint256 local = add(42, 34);\r " + - " storage = local;\r " + - " }\r " + - " uint256 storage;\r " + - "}"); - - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - - tryCompare(mainApplication.mainContent.rightPane.debugSlider, "maximumValue", 20); - tryCompare(mainApplication.mainContent.rightPane.debugSlider, "value", 0); - mainApplication.mainContent.rightPane.debugSlider.value = 13; - tryCompare(mainApplication.mainContent.rightPane.solCallStack.listModel, 0, "add"); - tryCompare(mainApplication.mainContent.rightPane.solCallStack.listModel, 1, "Contract"); - tryCompare(mainApplication.mainContent.rightPane.solLocals.item.value, "local", "0"); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "storage", undefined); - mainApplication.mainContent.rightPane.debugSlider.value = 19; - tryCompare(mainApplication.mainContent.rightPane.solLocals.item.value, "local", "76"); - tryCompare(mainApplication.mainContent.rightPane.solStorage.item.value, "storage", "76"); -} - -function test_vmDebugging() -{ - newProject(); - editContract( - "contract Contract {\r " + - " function add(uint256 a, uint256 b) returns (uint256)\r " + - " {\r " + - " return a + b;\r " + - " }\r " + - " function Contract()\r " + - " {\r " + - " uint256 local = add(42, 34);\r " + - " storage = local;\r " + - " }\r " + - " uint256 storage;\r " + - "}"); - - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - - mainApplication.mainContent.rightPane.assemblyMode = !mainApplication.mainContent.rightPane.assemblyMode; - tryCompare(mainApplication.mainContent.rightPane.debugSlider, "maximumValue", 41); - tryCompare(mainApplication.mainContent.rightPane.debugSlider, "value", 0); - mainApplication.mainContent.rightPane.debugSlider.value = 35; - tryCompare(mainApplication.mainContent.rightPane.vmCallStack.listModel, 0, mainApplication.clientModel.contractAddresses["Contract"].substring(2)); - tryCompare(mainApplication.mainContent.rightPane.vmStorage.listModel, 0, "@ 0 (0x0) 76 (0x4c)"); - tryCompare(mainApplication.mainContent.rightPane.vmMemory.listModel, "length", 0); -} - -function test_ctrTypeAsParam() -{ - newProject(); - editContract( - "contract C1 {\r " + - " function get() returns (uint256)\r " + - " {\r " + - " return 159;\r " + - " }\r " + - "}\r" + - "contract C2 {\r " + - " C1 c1;\r " + - " function getFromC1() returns (uint256)\r " + - " {\r " + - " return c1.get();\r " + - " }\r " + - " function C2(C1 _c1)\r" + - " {\r " + - " c1 = _c1;\r" + - " }\r " + - "}"); - mainApplication.projectModel.stateListModel.editState(0); //C1 ctor already added - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - mainApplication.projectModel.stateDialog.model.editTransaction(3); - ts.waitForRendering(transactionDialog, 3000); - clickElement(transactionDialog, 200, 300); - ts.typeString("", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.model.addTransaction(); - transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectContract("C2"); - transactionDialog.selectFunction("getFromC1"); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.acceptAndClose(); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(4), "returned", "(159)"); -} - diff --git a/mix/test/qml/js/TestMiner.js b/mix/test/qml/js/TestMiner.js deleted file mode 100644 index 3824f988e..000000000 --- a/mix/test/qml/js/TestMiner.js +++ /dev/null @@ -1,34 +0,0 @@ -function test_getDefaultMiner() -{ - newProject(); - var state = mainApplication.projectModel.stateListModel.get(0); - compare(state.miner.secret, "cb73d9408c4720e230387d956eb0f829d8a4dd2c1055f96257167e14e7169074"); -} - -function test_selectMiner() -{ - newProject(); - mainApplication.projectModel.stateListModel.editState(0); - var account = mainApplication.projectModel.stateDialog.newAccAction.add(); - account = mainApplication.projectModel.stateDialog.newAccAction.add(); - mainApplication.projectModel.stateDialog.minerComboBox.currentIndex = 2; - ts.waitForRendering(mainApplication.projectModel.stateDialog.minerComboBox, 3000); - mainApplication.projectModel.stateDialog.acceptAndClose(); - var state = mainApplication.projectModel.stateListModel.get(0); - compare(state.miner.secret, account.secret); -} - -function test_mine() -{ - newProject(); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - mainApplication.clientModel.mine(); - waitForMining(); - wait(1000); //there need to be at least 1 sec diff between block times - mainApplication.clientModel.mine(); - waitForMining(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(3), "contract", " - Block - "); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(4), "contract", " - Block - "); -} - diff --git a/mix/test/qml/js/TestProject.js b/mix/test/qml/js/TestProject.js deleted file mode 100644 index fe1023f05..000000000 --- a/mix/test/qml/js/TestProject.js +++ /dev/null @@ -1,60 +0,0 @@ -function test_contractRename() -{ - newProject(); - waitForExecution(); - tryCompare(mainApplication.mainContent.projectNavigator.sections.itemAt(0).model.get(0), "name", "Contract"); - editContract("contract Renamed {}"); - mainApplication.mainContent.startQuickDebugging(); - waitForExecution(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(2), "contract", "Renamed"); - tryCompare(mainApplication.mainContent.projectNavigator.sections.itemAt(0).model.get(0), "name", "Renamed"); - mainApplication.projectModel.stateListModel.editState(0); - mainApplication.projectModel.stateDialog.model.editTransaction(2); - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - tryCompare(transactionDialog, "contractId", "Renamed"); - tryCompare(transactionDialog, "functionId", "Renamed"); - transactionDialog.close(); - mainApplication.projectModel.stateDialog.close(); -} - -function test_multipleWebPages() -{ - newProject(); - editHtml("page1"); - createHtml("page1.html", "
Fail
"); - clickElement(mainApplication.mainContent.webView.webView, 1, 1); - ts.typeString("\t\r"); - wait(300); //TODO: use a signal in qt 5.5 - mainApplication.mainContent.webView.getContent(); - ts.waitForSignal(mainApplication.mainContent.webView, "webContentReady()", 5000); - var body = mainApplication.mainContent.webView.webContent; - verify(body.indexOf("
OK
") != -1, "Web content not updated") -} - -function test_multipleContractsSameFile() -{ - newProject(); - editContract( - "contract C1 {}\r" + - "contract C2 {}\r" + - "contract C3 {}\r"); - waitForExecution(); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel, "count", 5); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(2), "contract", "C1"); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(3), "contract", "C2"); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.transactionModel.get(4), "contract", "C3"); -} - -function test_deleteFile() -{ - newProject(); - var path = mainApplication.projectModel.projectPath; - createHtml("page1.html", "
Fail
"); - createHtml("page2.html", "
Fail
"); - createHtml("page3.html", "
Fail
"); - mainApplication.projectModel.removeDocument("page2.html"); - mainApplication.projectModel.closeProject(function(){}); - mainApplication.projectModel.loadProject(path); - var doc = mainApplication.projectModel.getDocument("page2.html"); - verify(!doc, "page2.html has not been removed"); -} diff --git a/mix/test/qml/js/TestTutorial.js b/mix/test/qml/js/TestTutorial.js deleted file mode 100644 index 895b5c9c1..000000000 --- a/mix/test/qml/js/TestTutorial.js +++ /dev/null @@ -1,71 +0,0 @@ -//Test case to cover Mix tutorial - -function test_tutorial() -{ - newProject(); - editContract( - "contract Rating {\r" + - " function setRating(bytes32 _key, uint256 _value) {\r" + - " ratings[_key] = _value;\r" + - " }\r" + - " mapping (bytes32 => uint256) public ratings;\r" + - "}\r" - ); - editHtml( - "\r" + - "\r" + - "\r" + - "\r" + - "\r" + - "\r" + - "

Ratings

\r" + - "
\r" + - " Store:\r" + - " \r" + - " \r" + - " \r" + - "
\r" + - "
\r" + - " Query:\r" + - " \r" + - "
\r" + - "
\r" + - "\r" + - "\r" - ); - - mainApplication.projectModel.stateListModel.editState(0); - mainApplication.projectModel.stateDialog.model.addTransaction(); - var transactionDialog = mainApplication.projectModel.stateDialog.transactionDialog; - ts.waitForRendering(transactionDialog, 3000); - transactionDialog.selectFunction("setRating"); - clickElement(transactionDialog, 200, 310); - ts.typeString("Titanic", transactionDialog); - clickElement(transactionDialog, 200, 330); - ts.typeString("2", transactionDialog); - transactionDialog.acceptAndClose(); - mainApplication.projectModel.stateDialog.acceptAndClose(); - mainApplication.mainContent.startQuickDebugging(); - if (!ts.waitForSignal(mainApplication.clientModel, "debugDataReady(QObject*)", 5000)) - fail("Error running transaction"); - wait(1); - clickElement(mainApplication.mainContent.webView.webView, 1, 1); - ts.typeString("\t\t\t\t"); - ts.typeString("Titanic"); - tryCompare(mainApplication.mainContent.rightPane.transactionLog.callModel, "count", 8); //wait for 8 calls - mainApplication.mainContent.webView.getContent(); - ts.waitForSignal(mainApplication.mainContent.webView, "webContentReady()", 5000); - var body = mainApplication.mainContent.webView.webContent; - verify(body.indexOf("
2
") != -1, "Web content not updated") -} diff --git a/mix/web.qrc b/mix/web.qrc deleted file mode 100644 index a34fd0b67..000000000 --- a/mix/web.qrc +++ /dev/null @@ -1,45 +0,0 @@ - - - qml/WebCodeEditor.qml - qml/WebPreview.qml - qml/html/WebContainer.html - qml/html/cm/acorn.js - qml/html/cm/acorn_loose.js - qml/html/cm/active-line.js - qml/html/cm/anyword-hint.js - qml/html/cm/closebrackets.js - qml/html/cm/codemirror.css - qml/html/cm/codemirror.js - qml/html/cm/comment.js - qml/html/cm/css.js - qml/html/cm/def.js - qml/html/cm/dialog.css - qml/html/cm/dialog.js - qml/html/cm/doc_comment.js - qml/html/cm/ecma5spec.js - qml/html/cm/errorannotation.js - qml/html/cm/fullscreen.css - qml/html/cm/fullscreen.js - qml/html/cm/htmlmixed.js - qml/html/cm/infer.js - qml/html/cm/javascript-hint.js - qml/html/cm/javascript.js - qml/html/cm/mark-selection.js - qml/html/cm/matchbrackets.js - qml/html/cm/search.js - qml/html/cm/searchcursor.js - qml/html/cm/show-hint.css - qml/html/cm/show-hint.js - qml/html/cm/signal.js - qml/html/cm/solarized.css - qml/html/cm/inkpot.css - qml/html/cm/solidity.js - qml/html/cm/solidityToken.js - qml/html/cm/tern.js - qml/html/cm/ternserver.js - qml/html/cm/walk.js - qml/html/cm/xml.js - qml/html/codeeditor.html - qml/html/codeeditor.js - -