repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
deepak-rathi/WPF-Prism-MVVM-Sample
abc/Source/Modules/abc.ModuleSection2/ViewModels/StockDetailViewModel.cs
4357
using abc.Domain; using abc.Domain.Exceptions; using abc.Domain.Interfaces; using abc.infrastructure.Base; using abc.infrastructure.Constants; using abc.infrastructure.Events; using abc.Infrastructure.Events; using Prism.Commands; using Prism.Logging; using Prism.Unity; using System; using System.Windows; namespace abc.ModuleSection2.ViewModels { internal class StockDetailViewModel : ViewModelBase { private readonly IStockService _stockService; #region SelectedStock private Stock _selectedStock = new Stock(); public Stock SelectedStock { get { return _selectedStock; } set { if (SetProperty(ref _selectedStock, value)) { UpdateStockCommand.RaiseCanExecuteChanged(); } } } #endregion #region Constructor public StockDetailViewModel() { _stockService = (IStockService)Container.Resolve(typeof(IStockService), ServiceNames.StockService); Container.TryResolve<ILoggerFacade>().Log("StockDetailViewModel Created", Category.Info, Priority.None); EventAggregator.GetEvent<SelectedStockChanged>().Subscribe(StockChanged); } #endregion #region EventHandler private void StockChanged(Stock stock) { if (stock == null) return; SelectedStock = new Stock { CurrentPrice = stock.CurrentPrice, Id = stock.Id, IssuingCompany = stock.IssuingCompany, LastRecordedPrice = stock.LastRecordedPrice, StockCode = stock.StockCode, StockName = stock.StockName }; } #endregion #region AddStockCommand private DelegateCommand _addStockCommand; public DelegateCommand AddStockCommand { get { return _addStockCommand ?? (_addStockCommand = new DelegateCommand(() => { try { var stock = _stockService.CreateStock(SelectedStock.CurrentPrice, SelectedStock.IssuingCompany, SelectedStock.StockCode, SelectedStock.StockName); EventAggregator.GetEvent<StockAddedEvent>().Publish(stock); MessageBox.Show("Added successfuly"); SelectedStock = new Stock(); } catch (InValidStockException exception) { Container.TryResolve<ILoggerFacade>().Log(exception.Message, Category.Exception, Priority.Medium); } catch (Exception exception) { Container.TryResolve<ILoggerFacade>().Log(exception.Message, Category.Exception, Priority.High); } })); } } #endregion #region UpdateStockCommand private DelegateCommand _updateStockCommand; public DelegateCommand UpdateStockCommand { get { return _updateStockCommand ?? (_updateStockCommand = new DelegateCommand(() => { try { var stock = _stockService.UpdateStock(SelectedStock); EventAggregator.GetEvent<StockUpdatedEvent>().Publish(stock); MessageBox.Show("Updated successfuly"); SelectedStock = new Stock(); } catch (StockNotFoundException exception) { Container.TryResolve<ILoggerFacade>().Log(exception.Message, Category.Exception, Priority.Medium); } catch (Exception exception) { Container.TryResolve<ILoggerFacade>().Log(exception.Message, Category.Exception, Priority.High); } },()=>!string.IsNullOrEmpty(SelectedStock.Id))); } } #endregion } }
gpl-3.0
iLoop2/ResInsight
ApplicationCode/ProjectDataModel/RimFaultCollection.cpp
14244
///////////////////////////////////////////////////////////////////////////////// // // Copyright (C) Statoil ASA // Copyright (C) Ceetron Solutions AS // // ResInsight 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. // // ResInsight 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 at <http://www.gnu.org/licenses/gpl.html> // for more details. // ///////////////////////////////////////////////////////////////////////////////// #include "RimFaultCollection.h" #include "RiaApplication.h" #include "RiaPreferences.h" #include "RigCaseData.h" #include "RimEclipseCase.h" #include "RimNoCommonAreaNNC.h" #include "RimNoCommonAreaNncCollection.h" #include "RimReservoirView.h" #include "RiuMainWindow.h" #include "RivColorTableArray.h" #include "cafAppEnum.h" #include "cafPdmFieldCvfColor.h" #include "cafPdmFieldCvfMat4d.h" namespace caf { template<> void AppEnum< RimFaultCollection::FaultFaceCullingMode >::setUp() { addItem(RimFaultCollection::FAULT_BACK_FACE_CULLING, "FAULT_BACK_FACE_CULLING", "Cell behind fault"); addItem(RimFaultCollection::FAULT_FRONT_FACE_CULLING, "FAULT_FRONT_FACE_CULLING", "Cell in front of fault"); addItem(RimFaultCollection::FAULT_NO_FACE_CULLING, "FAULT_NO_FACE_CULLING", "Show both"); setDefault(RimFaultCollection::FAULT_NO_FACE_CULLING); } } CAF_PDM_SOURCE_INIT(RimFaultCollection, "Faults"); //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RimFaultCollection::RimFaultCollection() { CAF_PDM_InitObject("Faults", ":/draw_style_faults_24x24.png", "", ""); RiaPreferences* prefs = RiaApplication::instance()->preferences(); CAF_PDM_InitField(&showFaultCollection, "Active", true, "Active", "", "", ""); showFaultCollection.setUiHidden(true); CAF_PDM_InitField(&showFaultFaces, "ShowFaultFaces", true, "Show defined faces", "", "", ""); CAF_PDM_InitField(&showOppositeFaultFaces, "ShowOppositeFaultFaces", true, "Show opposite faces", "", "", ""); CAF_PDM_InitField(&m_showFaultsOutsideFilters,"ShowFaultsOutsideFilters", true, "Show faults outside filters", "", "", ""); CAF_PDM_InitField(&faultResult, "FaultFaceCulling", caf::AppEnum<RimFaultCollection::FaultFaceCullingMode>(RimFaultCollection::FAULT_BACK_FACE_CULLING), "Dynamic Face Selection", "", "", ""); CAF_PDM_InitField(&showFaultLabel, "ShowFaultLabel", false, "Show labels", "", "", ""); cvf::Color3f defWellLabelColor = RiaApplication::instance()->preferences()->defaultWellLabelColor(); CAF_PDM_InitField(&faultLabelColor, "FaultLabelColor", defWellLabelColor, "Label color", "", "", ""); CAF_PDM_InitField(&showNNCs, "ShowNNCs", true, "Show NNCs", "", "", ""); CAF_PDM_InitField(&hideNncsWhenNoResultIsAvailable, "HideNncsWhenNoResultIsAvailable", true, "Hide NNC geometry if no NNC result is available", "", "", ""); CAF_PDM_InitFieldNoDefault(&noCommonAreaNnncCollection, "NoCommonAreaNnncCollection", "NNCs With No Common Area", "", "", ""); noCommonAreaNnncCollection = new RimNoCommonAreaNncCollection; CAF_PDM_InitFieldNoDefault(&faults, "Faults", "Faults", "", "", ""); m_reservoirView = NULL; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RimFaultCollection::~RimFaultCollection() { faults.deleteAllChildObjects(); delete noCommonAreaNnncCollection(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue) { this->updateUiIconFromToggleField(); if (&faultLabelColor == changedField) { m_reservoirView->scheduleReservoirGridGeometryRegen(); } if (&showFaultFaces == changedField || &showOppositeFaultFaces == changedField || &showFaultCollection == changedField || &showFaultLabel == changedField || &m_showFaultsOutsideFilters == changedField || &faultLabelColor == changedField || &faultResult == changedField || &showNNCs == changedField || &hideNncsWhenNoResultIsAvailable == changedField ) { if (m_reservoirView) { m_reservoirView->scheduleCreateDisplayModelAndRedraw(); } } if (&showFaultLabel == changedField) { RiuMainWindow::instance()->refreshDrawStyleActions(); } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::setReservoirView(RimReservoirView* ownerReservoirView) { m_reservoirView = ownerReservoirView; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- caf::PdmFieldHandle* RimFaultCollection::objectToggleField() { return &showFaultCollection; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RimFault* RimFaultCollection::findFaultByName(QString name) { for (size_t i = 0; i < this->faults().size(); ++i) { if (this->faults()[i]->name() == name) { return this->faults()[i]; } } return NULL; } //-------------------------------------------------------------------------------------------------- /// A comparing function used to sort Faults in the RimFaultCollection::syncronizeFaults() method //-------------------------------------------------------------------------------------------------- bool faultComparator(const cvf::ref<RigFault>& a, const cvf::ref<RigFault>& b) { CVF_TIGHT_ASSERT(a.notNull() && b.notNull()); int compareValue = a->name().compare(b->name(), Qt::CaseInsensitive); return (compareValue < 0); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::syncronizeFaults() { if (!(m_reservoirView && m_reservoirView->eclipseCase() && m_reservoirView->eclipseCase()->reservoirData() && m_reservoirView->eclipseCase()->reservoirData()->mainGrid()) ) return; cvf::ref<cvf::Color3fArray> partColors = RivColorTableArray::colorTableArray(); const cvf::Collection<RigFault> constRigFaults = m_reservoirView->eclipseCase()->reservoirData()->mainGrid()->faults(); cvf::Collection<RigFault> rigFaults; { cvf::Collection<RigFault> sortedFaults(constRigFaults); std::sort(sortedFaults.begin(), sortedFaults.end(), faultComparator); cvf::ref<RigFault> undefinedFaults; for (size_t i = 0; i < sortedFaults.size(); i++) { if (sortedFaults[i]->name().compare(RimDefines::undefinedGridFaultName(), Qt::CaseInsensitive) == 0) { undefinedFaults = sortedFaults[i]; } } if (undefinedFaults.notNull()) { sortedFaults.erase(undefinedFaults.p()); rigFaults.push_back(undefinedFaults.p()); } for (size_t i = 0; i < sortedFaults.size(); i++) { rigFaults.push_back(sortedFaults[i].p()); } } // Find faults with std::vector<caf::PdmPointer<RimFault> > newFaults; // Find corresponding fault from data model, or create a new for (size_t fIdx = 0; fIdx < rigFaults.size(); ++fIdx) { RimFault* rimFault = this->findFaultByName(rigFaults[fIdx]->name()); if (!rimFault) { rimFault = new RimFault(); rimFault->faultColor = partColors->get(fIdx % partColors->size()); } rimFault->setFaultGeometry(rigFaults[fIdx].p()); newFaults.push_back(rimFault); } this->faults().clear(); this->faults().insert(0, newFaults); QString toolTip = QString("Fault count (%1)").arg(newFaults.size()); setUiToolTip(toolTip); // NNCs this->noCommonAreaNnncCollection()->noCommonAreaNncs().deleteAllChildObjects(); RigMainGrid* mainGrid = m_reservoirView->eclipseCase()->reservoirData()->mainGrid(); std::vector<RigConnection>& nncConnections = mainGrid->nncData()->connections(); for (size_t i = 0; i < nncConnections.size(); i++) { if (!nncConnections[i].hasCommonArea()) { RimNoCommonAreaNNC* noCommonAreaNnc = new RimNoCommonAreaNNC(); QString firstConnectionText; QString secondConnectionText; { const RigCell& cell = mainGrid->cells()[nncConnections[i].m_c1GlobIdx]; RigGridBase* hostGrid = cell.hostGrid(); size_t gridLocalCellIndex = cell.gridLocalCellIndex(); size_t i, j, k; if (hostGrid->ijkFromCellIndex(gridLocalCellIndex, &i, &j, &k)) { // Adjust to 1-based Eclipse indexing i++; j++; k++; if (!hostGrid->isMainGrid()) { QString gridName = QString::fromStdString(hostGrid->gridName()); firstConnectionText = gridName + " "; } firstConnectionText += QString("[%1 %2 %3] - ").arg(i).arg(j).arg(k); } } { const RigCell& cell = mainGrid->cells()[nncConnections[i].m_c2GlobIdx]; RigGridBase* hostGrid = cell.hostGrid(); size_t gridLocalCellIndex = cell.gridLocalCellIndex(); size_t i, j, k; if (hostGrid->ijkFromCellIndex(gridLocalCellIndex, &i, &j, &k)) { // Adjust to 1-based Eclipse indexing i++; j++; k++; if (!hostGrid->isMainGrid()) { QString gridName = QString::fromStdString(hostGrid->gridName()); secondConnectionText = gridName + " "; } secondConnectionText += QString("[%1 %2 %3]").arg(i).arg(j).arg(k); } } noCommonAreaNnc->name = firstConnectionText + secondConnectionText; this->noCommonAreaNnncCollection()->noCommonAreaNncs().push_back(noCommonAreaNnc); } this->noCommonAreaNnncCollection()->updateName(); } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RimFaultCollection::isGridVisualizationMode() const { CVF_ASSERT(m_reservoirView); return m_reservoirView->isGridVisualizationMode(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering) { bool isGridVizMode = isGridVisualizationMode(); faultResult.setUiReadOnly(isGridVizMode); showFaultFaces.setUiReadOnly(isGridVizMode); showOppositeFaultFaces.setUiReadOnly(isGridVizMode); caf::PdmUiGroup* labs = uiOrdering.addNewGroup("Fault Labels"); labs->add(&showFaultLabel); labs->add(&faultLabelColor); caf::PdmUiGroup* adv = uiOrdering.addNewGroup("Fault Options"); adv->add(&m_showFaultsOutsideFilters); caf::PdmUiGroup* ffviz = uiOrdering.addNewGroup("Fault Face Visibility"); ffviz->add(&showFaultFaces); ffviz->add(&showOppositeFaultFaces); ffviz->add(&faultResult); caf::PdmUiGroup* nncViz = uiOrdering.addNewGroup("NNC Visibility"); nncViz->add(&showNNCs); nncViz->add(&hideNncsWhenNoResultIsAvailable); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RimFaultCollection::showFaultsOutsideFilters() const { if (!showFaultCollection) return false; return m_showFaultsOutsideFilters; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::setShowFaultsOutsideFilters(bool enableState) { m_showFaultsOutsideFilters = enableState; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RimFaultCollection::addMockData() { if (!(m_reservoirView && m_reservoirView->eclipseCase() && m_reservoirView->eclipseCase()->reservoirData() && m_reservoirView->eclipseCase()->reservoirData()->mainGrid())) return; }
gpl-3.0
Imperialskull/Synthcraft
Synthcraft_common/com/Imperialskull/mods/synthcraft/ItemPlexiboat.java
5181
package com.Imperialskull.mods.synthcraft; import java.util.List; import com.Imperialskull.mods.synthcraft.client.EntityPlexiboat; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityBoat; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.EnumMovingObjectType; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; public class ItemPlexiboat extends Item { public ItemPlexiboat(int par1) { super(par1); this.maxStackSize = 1; this.setCreativeTab(CreativeTabs.tabTransport); } @Override public void updateIcons(IconRegister par1IconRegister){ this.iconIndex = par1IconRegister.registerIcon("synthcraft:Imperialskull.synthcraft.ItemPlexidoor");} /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { float f = 1.0F; float f1 = par3EntityPlayer.prevRotationPitch + (par3EntityPlayer.rotationPitch - par3EntityPlayer.prevRotationPitch) * f; float f2 = par3EntityPlayer.prevRotationYaw + (par3EntityPlayer.rotationYaw - par3EntityPlayer.prevRotationYaw) * f; double d0 = par3EntityPlayer.prevPosX + (par3EntityPlayer.posX - par3EntityPlayer.prevPosX) * (double)f; double d1 = par3EntityPlayer.prevPosY + (par3EntityPlayer.posY - par3EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par3EntityPlayer.yOffset; double d2 = par3EntityPlayer.prevPosZ + (par3EntityPlayer.posZ - par3EntityPlayer.prevPosZ) * (double)f; Vec3 vec3 = par2World.getWorldVec3Pool().getVecFromPool(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float)Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float)Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); MovingObjectPosition movingobjectposition = par2World.rayTraceBlocks_do(vec3, vec31, true); if (movingobjectposition == null) { return par1ItemStack; } else { Vec3 vec32 = par3EntityPlayer.getLook(f); boolean flag = false; float f9 = 1.0F; List list = par2World.getEntitiesWithinAABBExcludingEntity(par3EntityPlayer, par3EntityPlayer.boundingBox.addCoord(vec32.xCoord * d3, vec32.yCoord * d3, vec32.zCoord * d3).expand((double)f9, (double)f9, (double)f9)); int i; for (i = 0; i < list.size(); ++i) { Entity entity = (Entity)list.get(i); if (entity.canBeCollidedWith()) { float f10 = entity.getCollisionBorderSize(); AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f10, (double)f10, (double)f10); if (axisalignedbb.isVecInside(vec3)) { flag = true; } } } if (flag) { return par1ItemStack; } else { if (movingobjectposition.typeOfHit == EnumMovingObjectType.TILE) { i = movingobjectposition.blockX; int j = movingobjectposition.blockY; int k = movingobjectposition.blockZ; if (par2World.getBlockId(i, j, k) == Block.snow.blockID) { --j; } EntityPlexiboat entityplexiboat = new EntityPlexiboat(par2World, (double)((float)i + 0.5F), (double)((float)j + 1.0F), (double)((float)k + 0.5F)); entityplexiboat.rotationYaw = (float)(((MathHelper.floor_double((double)(par3EntityPlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3) - 1) * 90); if (!par2World.getCollidingBoundingBoxes(entityplexiboat, entityplexiboat.boundingBox.expand(-0.1D, -0.1D, -0.1D)).isEmpty()) { return par1ItemStack; } if (!par2World.isRemote) { par2World.spawnEntityInWorld(entityplexiboat); } if (!par3EntityPlayer.capabilities.isCreativeMode) { --par1ItemStack.stackSize; } } return par1ItemStack; } } } }
gpl-3.0
rudolfbono/NAIM
src/main/java/aim4/vehicle/Controller.java
485
package aim4.vehicle; public abstract class Controller { private VehicleSimView vehicle; private Sensor frontSensor; private Sensor leftSensor; private Sensor rightSensor; public Controller(VehicleSimView vehicle) { this.vehicle = vehicle; this.frontSensor = Sensor.frontSensorOn(vehicle); this.leftSensor = Sensor.leftSensorOn(vehicle); this.rightSensor = Sensor.rightSensorOn(vehicle); } abstract void control(); }
gpl-3.0
thevpc/upa
upa-impl-core/src/main/csharp/Sources/Auto/Uql/Compiler/DateAddExpressionTranslator.cs
1877
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl.Uql.Compiler { /** * * @author Taha BEN SALAH <taha.bensalah@gmail.com> */ public class DateAddExpressionTranslator : Net.TheVpc.Upa.Impl.Uql.ExpressionTranslator { public virtual Net.TheVpc.Upa.Impl.Uql.Compiledexpression.DefaultCompiledExpression TranslateExpression(object o, Net.TheVpc.Upa.Impl.Uql.ExpressionTranslationManager manager, Net.TheVpc.Upa.Impl.Uql.ExpressionDeclarationList declarations) { return CompileDateAdd((Net.TheVpc.Upa.Expressions.DateAdd) o, manager, declarations); } protected internal virtual Net.TheVpc.Upa.Impl.Uql.Compiledexpression.CompiledDateAdd CompileDateAdd(Net.TheVpc.Upa.Expressions.DateAdd v, Net.TheVpc.Upa.Impl.Uql.ExpressionTranslationManager manager, Net.TheVpc.Upa.Impl.Uql.ExpressionDeclarationList declarations) { if (v == null) { return null; } Net.TheVpc.Upa.Impl.Uql.Compiledexpression.CompiledDateAdd s = new Net.TheVpc.Upa.Impl.Uql.Compiledexpression.CompiledDateAdd(v.GetDatePartType(), manager.TranslateAny(v.GetCount(), declarations), manager.TranslateAny(v.GetDate(), declarations)); // s.setDeclarationList(declarations); return s; } } }
gpl-3.0
RDSergij/tm-real-estate
widgets/tm-real-estate-search-form-widget.php
6114
<?php /** * TM Real Estate Search form Widget * * @package TM Real Estate * @subpackage Class * @author Cherry Team <cherryframework@gmail.com>, Guriev Eugen. * @copyright Copyright (c) 2012 - 2016, Cherry Team * @link http://www.cherryframework.com/ * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ /** * Add TM_Real_Estate_Search_Form_Widget widget. */ class TM_Real_Estate_Search_Form_Widget extends Cherry_Abstract_Widget { /** * Default settings * * @var type array */ private $instance_default = array(); /** * Search_Form_Widget class constructor */ public function __construct() { $this->widget_description = __( 'TM Real Estate Search Form Widget', 'tm-real-estate' ); $this->widget_id = 'tm-real-estate-search-form-widget'; $this->widget_name = __( 'Search Form Widget', 'tm-real-estate' ); $this->settings = array( 'title' => array( 'type' => 'text', 'value' => '', 'label' => esc_html__( 'Title', 'tm-real-estate' ), ), ); // Set default settings $this->instance_default = array( 'title' => __( 'Search form & map', 'tm-real-estateß' ), 'first_block' => 'form', 'form_is' => 'true', 'form_title' => '', 'map_is' => 'true', 'map_title' => '', ); parent::__construct(); } /** * Frontend view * * @param type $args array. * @param type $instance array. */ public function form( $instance ) { $first_block_field = new UI_Select( array( 'id' => $this->get_field_id( 'first_block' ), 'name' => $this->get_field_name( 'first_block' ), 'value' => Cherry_Toolkit::get_arg( $instance, 'first_block' ), 'label' => __( 'Choose first block', 'tm-real-estate' ), 'options' => array( 'form' => 'Search From', 'map' => 'Map', ), ) ); $first_block_html = $first_block_field->render(); $form_is_field = new UI_Switcher( array( 'id' => $this->get_field_id( 'form_is' ) . ' form_is', 'label' => __( 'Show search form', 'tm-real-estate' ), 'name' => $this->get_field_name( 'form_is' ), 'value' => Cherry_Toolkit::get_arg( $instance, 'form_is', $this->instance_default['form_is'] ), ) ); $form_is_html = $form_is_field->render(); $form_title_field = new UI_Text( array( 'id' => $this->get_field_id( 'form_title' ), 'name' => $this->get_field_name( 'form_title' ), 'value' => Cherry_Toolkit::get_arg( $instance, 'form_title', $this->instance_default['form_title'] ), 'label' => __( 'Form title', 'tm-real-estate' ), ) ); $form_title_html = $form_title_field->render(); $map_is_field = new UI_Switcher( array( 'id' => $this->get_field_id( 'map_is' ) . ' map_is', 'label' => __( 'Show map', 'tm-real-estate' ), 'name' => $this->get_field_name( 'map_is' ), 'value' => Cherry_Toolkit::get_arg( $instance, 'map_is', $this->instance_default['map_is'] ), ) ); $map_is_html = $map_is_field->render(); $map_title_field = new UI_Text( array( 'id' => $this->get_field_id( 'map_title' ), 'name' => $this->get_field_name( 'map_title' ), 'value' => Cherry_Toolkit::get_arg( $instance, 'map_title', $this->instance_default['map_title'] ), 'label' => __( 'Map title', 'tm-real-estate' ), ) ); $map_title_html = $map_title_field->render(); echo Cherry_Toolkit::render_view( TM_REAL_ESTATE_DIR . 'views/widgets/search-form-and-map/admin.php', array( 'first_block_html' => $first_block_html, 'form_is_html' => $form_is_html, 'form_title_html' => $form_title_html, 'map_is_html' => $map_is_html, 'map_title_html' => $map_title_html, ) ); } /** * Frontend view * * @param type $args array. * @param type $instance array. */ public function widget( $args, $instance ) { $title = ''; if ( array_key_exists( 'title', $instance ) ) { $title = $args['before_title'] . sanitize_text_field( $instance['title'] ) . $args['after_title']; } $form = do_shortcode( '[tm-re-search-form]' ); $map = do_shortcode( '[tm-re-map]' ); $blocks = array(); if ( 'true' == Cherry_Toolkit::get_arg( $instance, 'form_is', $this->instance_default['form_is'] ) ) { $blocks['form'] = Cherry_Toolkit::render_view( TM_REAL_ESTATE_DIR . 'views/widgets/search-form-and-map/frontend-form.php', array( 'form' => $form, 'form_title' => Cherry_Toolkit::get_arg( $instance, 'form_title', $this->instance_default['form_title'] ), 'before_title' => $args['before_title'], 'after_title' => $args['after_title'], ) ); } else { $blocks['form'] = ''; } if ( 'true' == Cherry_Toolkit::get_arg( $instance, 'map_is', $this->instance_default['map_is'] ) ) { $blocks['map'] = Cherry_Toolkit::render_view( TM_REAL_ESTATE_DIR . 'views/widgets/search-form-and-map/frontend-map.php', array( 'map' => $map, 'map_title' => Cherry_Toolkit::get_arg( $instance, 'map_title', $this->instance_default['map_title'] ), 'before_title' => $args['before_title'], 'after_title' => $args['after_title'], ) ); } else { $blocks['map'] = ''; } if ( 'form' == Cherry_Toolkit::get_arg( $instance, 'first_block', $this->instance_default['first_block'] ) ) { $first_block = $blocks['form']; $second_block = $blocks['map']; } else { $first_block = $blocks['map']; $second_block = $blocks['form']; } echo Cherry_Toolkit::render_view( TM_REAL_ESTATE_DIR . 'views/widgets/search-form-and-map/frontend.php', array( 'first_block' => $first_block, 'second_block' => $second_block, 'before_widget' => $args['before_widget'], 'after_widget' => $args['after_widget'], ) ); } /** * Frontend view * * @param type $args array. * @param type $instance array. */ public function update( $new_instance, $old_instance ) { foreach ( $this->instance_default as $key => $value ) { $instance[ $key ] = ! empty( $new_instance[ $key ] ) ? $new_instance[ $key ] : $value; } return $instance; } }
gpl-3.0
veltzer/demos-python
src/examples/long/debugging_winpdb/debug_me.py
825
#!/usr/bin/env python def simple_func(x): x += 1 s = range(20) z = None w = () y = dict((i, i ** 2) for i in s) k = set(range(5, 99)) try: x.invalid except AttributeError: pass # import sys # sys.exit(1) return 2 * x def fermat(n): """Returns triplets of the form x^n+y^n=z^n. Warning! Untested with n>2. """ for x in range(100): for y in range(1, x + 1): for z in range(1, x ** n + y ** n + 1): # from pudb import set_trace; set_trace() if x ** n + y ** n == z ** n: yield x, y, z def main(): # noinspection PyTypeChecker print('SF', simple_func(10)) for i in fermat(2): print(i) print('FINISHED') if __name__ == "__main__": main()
gpl-3.0
geminorum/gtheme_03
singular-systempage.php
401
<?php defined( 'ABSPATH' ) or die( header( 'HTTP/1.0 403 Forbidden' ) ); gThemeTemplate::wrapOpen( 'systempage' ); if ( have_posts() ) { while ( have_posts() ) { the_post(); gThemeContent::post(); } // gThemeNavigation::content( 'singular' ); } else { get_template_part( 'content', '404' ); } gThemeTemplate::wrapClose( 'systempage' ); gThemeTemplate::sidebar( 'systempage' );
gpl-3.0
Samuc/Eat-with-Rango
rango/migrations/0003_remove_userprofile_website.py
386
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-16 18:50 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rango', '0002_tapa_url'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='website', ), ]
gpl-3.0
TLCFEM/suanPan
Material/Material1D/Hysteresis/Flag.cpp
6210
/******************************************************************************* * Copyright (C) 2017-2022 Theodore Chang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "Flag.h" #include <Toolbox/utility.h> Flag::Flag(const unsigned T, const double E, const double YT, const double RT, const double HT, const double YC, const double RC, const double HC, const double D) : DataFlag{fabs(E), HT, fabs(YT), RT, HC, -fabs(YC), RC} , Material1D(T, D) {} Flag::Flag(const unsigned T, const double E, const double YT, const double RT, const double HT, const double D) : DataFlag{fabs(E), HT, fabs(YT), RT, HT, -fabs(YT), -RT} , Material1D(T, D) {} void Flag::initialize(const shared_ptr<DomainBase>&) { trial_stiffness = current_stiffness = initial_stiffness = elastic_modulus; initialize_history(4); } unique_ptr<Material> Flag::get_copy() { return make_unique<Flag>(*this); } int Flag::update_trial_status(const vec& t_strain) { incre_strain = (trial_strain = t_strain) - current_strain; if(fabs(incre_strain(0)) <= datum::eps) return SUANPAN_SUCCESS; trial_status = current_status; trial_history = current_history; auto& tr_strain = trial_history(0); auto& tr_low_strain = trial_history(1); auto& cr_strain = trial_history(2); auto& cr_low_strain = trial_history(3); const auto load_direction = suanpan::sign(incre_strain(0)); switch(trial_status) { case Status::NONE: trial_status = load_direction > 0. ? Status::TLOAD : Status::CLOAD; break; case Status::TLOAD: if(load_direction < 0.) { tr_low_strain = ((current_stress(0) - t_residual_stress) / elastic_modulus + t_residual_strain * t_hardening_ratio - (tr_strain = current_strain(0))) / (t_hardening_ratio - 1.); trial_status = trial_strain(0) > tr_low_strain ? Status::TUNLOAD : trial_strain(0) > t_residual_strain ? Status::TLOW : trial_strain(0) > 0. ? Status::TLOAD : Status::CLOAD; } break; case Status::CLOAD: if(load_direction > 0.) { cr_low_strain = ((current_stress(0) - c_residual_stress) / elastic_modulus + c_residual_strain * c_hardening_ratio - (cr_strain = current_strain(0))) / (c_hardening_ratio - 1.); trial_status = trial_strain(0) < cr_low_strain ? Status::CUNLOAD : trial_strain(0) < c_residual_strain ? Status::CLOW : trial_strain(0) < 0. ? Status::CLOAD : Status::TLOAD; } break; case Status::TLOW: if(load_direction > 0.) { tr_strain = (tr_low_strain = current_strain(0)) + t_yield_strain - t_residual_strain; trial_status = trial_strain(0) < tr_strain ? Status::TUNLOAD : Status::TLOAD; } else trial_status = trial_strain(0) > t_residual_strain ? Status::TLOW : trial_strain(0) > 0. ? Status::TLOAD : Status::CLOAD; break; case Status::CLOW: if(load_direction < 0.) { cr_strain = (cr_low_strain = current_strain(0)) + c_yield_strain - c_residual_strain; trial_status = trial_strain(0) > cr_strain ? Status::CUNLOAD : Status::CLOAD; } else trial_status = trial_strain(0) < c_residual_strain ? Status::CLOW : trial_strain(0) < 0. ? Status::CLOAD : Status::TLOAD; break; case Status::TUNLOAD: trial_status = trial_strain(0) > tr_strain ? Status::TLOAD : trial_strain(0) > tr_low_strain ? Status::TUNLOAD : trial_strain(0) > t_residual_strain ? Status::TLOW : trial_strain(0) > 0. ? Status::TLOAD : Status::CLOAD; break; case Status::CUNLOAD: trial_status = trial_strain(0) < cr_strain ? Status::CLOAD : trial_strain(0) < cr_low_strain ? Status::CUNLOAD : trial_strain(0) < c_residual_strain ? Status::CLOW : trial_strain(0) < 0. ? Status::CLOAD : Status::TLOAD; break; } trial_stiffness = elastic_modulus; if(Status::TLOAD == trial_status) trial_strain(0) > t_yield_strain ? trial_stress = t_yield_stress + (trial_stiffness *= t_hardening_ratio) * (trial_strain(0) - t_yield_strain) : trial_stress = trial_stiffness * trial_strain(0); else if(Status::CLOAD == trial_status) trial_strain(0) < c_yield_strain ? trial_stress = c_yield_stress + (trial_stiffness *= c_hardening_ratio) * (trial_strain(0) - c_yield_strain) : trial_stress = trial_stiffness * trial_strain(0); else if(Status::TUNLOAD == trial_status || Status::CUNLOAD == trial_status) trial_stress = current_stress + trial_stiffness * incre_strain; else if(Status::TLOW == trial_status) trial_stress = t_residual_stress + (trial_stiffness *= t_hardening_ratio) * (trial_strain - t_residual_strain); else if(Status::CLOW == trial_status) trial_stress = c_residual_stress + (trial_stiffness *= c_hardening_ratio) * (trial_strain - c_residual_strain); return SUANPAN_SUCCESS; } int Flag::clear_status() { current_strain.zeros(); current_stress.zeros(); current_status = Status::NONE; current_history = initial_history; current_stiffness = initial_stiffness; return reset_status(); } int Flag::commit_status() { current_strain = trial_strain; current_stress = trial_stress; current_status = trial_status; current_history = trial_history; current_stiffness = trial_stiffness; return SUANPAN_SUCCESS; } int Flag::reset_status() { trial_strain = current_strain; trial_stress = current_stress; trial_status = current_status; trial_history = current_history; trial_stiffness = current_stiffness; return SUANPAN_SUCCESS; } void Flag::print() { suanpan_info("A bilinear flag material model with an elastic modulus of %.3E, a tension hardening ratio of %.2f and a compression hardening ratio of %.2f.\n", elastic_modulus, t_hardening_ratio, c_hardening_ratio); suanpan_info("current strain: %.3E\tcurrent stress: %.3E\n", current_strain(0), current_stress(0)); }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/nianticproject/ingress/l/ad.java
270
package com.nianticproject.ingress.l; import android.location.Location; public abstract interface ad { public abstract Location a(); } /* Location: classes_dex2jar.jar * Qualified Name: com.nianticproject.ingress.l.ad * JD-Core Version: 0.6.2 */
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-223.js
1174
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-223.js * @description Object.defineProperty - 'O' is an Array, 'name' is an array index property, test TypeError is thrown when the [[Value]] field of 'desc' and the [[Value]] attribute value of 'name' are two strings with different values (15.4.5.1 step 4.c) */ function testcase() { var arrObj = []; Object.defineProperty(arrObj, 0, { value: "abcd", writable: false, configurable: false }); try { Object.defineProperty(arrObj, "0", { value: "fghj" }); return false; } catch (e) { return e instanceof TypeError && dataPropertyAttributesAreCorrect(arrObj, "0", "abcd", false, false, false); } } runTestCase(testcase);
gpl-3.0
simonr89/invgen
src/logic/Sort.hpp
1740
#ifndef __Sort__ #define __Sort__ #include <map> #include <memory> #include <string> namespace logic { #pragma mark - Sort class Sort { // we need each sort to be unique. // We therefore use the Sorts-class below as a manager-class for Sort-objects friend class Sorts; private: // constructor is private to prevent accidental usage. Sort(std::string name) : name(name){}; public: const std::string name; bool operator==(Sort& o); std::string toTPTP() const; std::string toSMTLIB() const; std::string prettyString() const { return name; } std::string declareSortTPTP() const; std::string declareSortSMTLIB() const; }; std::ostream& operator<<(std::ostream& ostr, const Sort& s); #pragma mark - Sorts // we need each sort to be unique. // We therefore use Sorts as a manager-class for Sort-instances class Sorts { public: // construct various sorts static Sort* boolSort() { return fetchOrDeclare("bool"); } static Sort* intSort() { return fetchOrDeclare("int"); } static Sort* intArraySort() { return fetchOrDeclare("array_int"); } // time can either be represented by int or by a dedicated term algebra sort static Sort* timeSort(); // returns map containing all previously constructed sorts as pairs (nameOfSort, Sort) static const std::map<std::string, std::unique_ptr<Sort>>& nameToSort(){return _sorts;}; private: static Sort* fetchOrDeclare(std::string name); static std::map<std::string, std::unique_ptr<Sort>> _sorts; }; } #endif
gpl-3.0
Maximetinu/JPA-Notes
JPA Notes Project/test/com/jpanotesproject/daos/BaseDAOTest.java
1560
package com.jpanotesproject.daos; import javax.persistence.EntityManager; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.jpanotesproject.mocks.EntityManagerMock; import com.jpanotesproject.model.BaseEntity; public class BaseDAOTest { // Setting Up Mocking structure public class MockingEntity extends BaseEntity { public MockingEntity() { super(); super.id = null; } public MockingEntity(long id) { super(); super.id = id; } } public class MockingDAO extends BaseDAO<MockingEntity> { public MockingDAO(EntityManager context) { super(MockingEntity.class, context); } } MockingDAO mockDAO; EntityManagerMock em; @Before public void setUp() { em = new EntityManagerMock(); mockDAO = new MockingDAO(em); } @Test public void persistTest() { MockingEntity entityMock = new MockingEntity(); mockDAO.persist(entityMock); Assert.assertTrue(em.isPersistCalled()); Assert.assertFalse(em.isMergeCalled()); em.resetMockFlags(); entityMock = new MockingEntity(10); mockDAO.persist(entityMock); Assert.assertTrue(em.isMergeCalled()); Assert.assertFalse(em.isPersistCalled()); } @Test(expected = IllegalArgumentException.class) public void removeTest() { MockingEntity entityMock = new MockingEntity(); mockDAO.remove(entityMock); entityMock = new MockingEntity(999); mockDAO.remove(entityMock); Assert.assertTrue(em.isRemoveCalled()); } @Test public void findByIDTest() { mockDAO.findById(999); Assert.assertTrue(em.isFindCalled()); } }
gpl-3.0
waaghals/Aggressive-Swallow
old/footer.inc.php
170
</div> <!-- /.container --> <!-- JavaScript --> <script src="js/jquery-1.10.2.js"></script> <script src="js/bootstrap.js"></script> </body> </html>
gpl-3.0
YuriCat/FujiGokoroUECda
src/engine/data.hpp
8105
#pragma once // 思考用の構造体 #include "../core/record.hpp" #include "../core/field.hpp" #include "policy.hpp" // Field以外のデータ構造 // Fieldは基本盤面情報+盤面を進めたり戻したりするときに値が変化するもの // それ以外の重目のデータ構造は SharedData // スレッドごとのデータは ThreadTools struct ThreadTools { // 各スレッドの持ち物 Dice dice; // サイコロ MoveInfo mbuf[8192]; // 着手生成バッファ ThreadTools() { dice.srand(0); memset(mbuf, 0, sizeof(mbuf)); } }; struct BaseSharedData { std::array<std::array<uint32_t, N_PLAYERS>, N_PLAYERS> classDestination; // 階級到達回数 std::array<std::array<std::array<uint32_t, N_PLAYERS>, N_PLAYERS>, N_PLAYERS> classTransition; // 階級遷移回数 MatchRecord record; // 主観的な対戦棋譜 // クライアントの個人的スタッツ uint32_t playRejection, changeRejection; // リジェクト void feedPlayRejection() { playRejection += 1; } void feedChangeRejection() { changeRejection += 1; } void feedResult(int p, int cl, int ncl) { classDestination[p][ncl] += 1; classTransition[p][cl][ncl] += 1; } void initMatch(int playerNum) { // スタッツ初期化 record.init(playerNum); for (int p = 0; p < N_PLAYERS; p++) { classDestination[p].fill(0); for (int cl = 0; cl < N_PLAYERS; cl++) { classTransition[p][cl].fill(0); } } playRejection = changeRejection = 0; } void initGame() { record.initGame(); } void closeGame(const GameRecord& g) { // 試合順位の記録 for (int p = 0; p < N_PLAYERS; p++) { feedResult(p, g.classOf(p), g.newClassOf(p)); } } void closeMatch(); }; struct SharedData : public BaseSharedData { using base_t = BaseSharedData; // 全体で共通のデータ // 毎回報酬テーブルから持ってこなくてもいいようにこの試合の報酬を置いておくテーブル std::array<double, N_PLAYERS> gameReward; // 基本方策 ChangePolicy<policy_value_t> baseChangePolicy; PlayPolicy<policy_value_t> basePlayPolicy; // 1ゲーム中に保存する一次データのうち棋譜に含まれないもの int mateClass; // 初めてMATEと判定した階級の宣言 int L2Result; // L2における判定結果 // クライアントの個人的スタッツ // (勝利, 敗戦) x (勝利宣言, 判定失敗, 敗戦宣言, 無宣言) std::array<std::array<long long, 5>, 2> myL2Result; // MATEの宣言結果 std::array<std::array<long long, N_PLAYERS>, N_PLAYERS> myMateResult; void setMyMate(int bestClass) { // 詰み宣言 if (mateClass == -1) mateClass = bestClass; } void setMyL2Result(int result) { // L2詰み宣言 if (L2Result == -2) L2Result = result; } void feedMyResult(int realClass) { // ラスト2人 if (realClass >= N_PLAYERS - 2) { bool realWin = realClass == N_PLAYERS - 2; if (realWin && L2Result == -1) CERR << "L2 Lucky!" << std::endl; if (!realWin && L2Result == 1) CERR << "L2 Miss!" << std::endl; myL2Result[realClass - (N_PLAYERS - 2)][1 - L2Result] += 1; } // MATE宣言あり if (mateClass != -1) { if (mateClass != realClass) { // MATE宣言失敗 CERR << "Mate Miss! DCL:" << mateClass; CERR << " REAL:" << realClass << std::endl; } myMateResult[realClass][mateClass] += 1; } } void initMatch(int playerNum) { base_t::initMatch(playerNum); // スタッツ初期化 for (auto& a : myMateResult) a.fill(0); for (auto& a : myL2Result) a.fill(0); } void initGame() { base_t::initGame(); mateClass = -1; L2Result = -2; } void closeGame() { const auto& game = record.latestGame(); base_t::closeGame(game); int myNewClass = game.newClassOf(record.myPlayerNum); // 自己スタッツ更新 feedMyResult(myNewClass); } void closeMatch(); }; /**************************ルートの手の情報**************************/ struct RootAction { MoveInfo move; Cards changeCards; int nextDivision; // 方策関数出力 double policyScore, policyProb; // モンテカルロ結果 BetaDistribution monteCarloScore; BetaDistribution naiveScore; // モンテカルロの詳細な結果 BetaDistribution myScore, rivalScore; uint64_t simulations; std::array<std::array<int64_t, N_CLASSES>, N_PLAYERS> classDistribution; uint64_t turnSum; double mean() const { return monteCarloScore.mean(); } double size() const { return monteCarloScore.size(); } double mean_var() const { return monteCarloScore.var(); } double var() const { return monteCarloScore.var() * size(); } double naive_mean() const { return naiveScore.mean(); } void clear(); void setChange(Cards cc) { clear(); changeCards = cc; } void setPlay(MoveInfo m) { clear(); move = m; } std::string toString() const; }; /**************************ルートの全体の情報**************************/ struct RootInfo { std::array<RootAction, N_MAX_MOVES> child; int candidates; // 選択の候補とする数 bool isChange; bool policyAdded = false; // 雑多な情報 int myPlayerNum = -1, rivalPlayerNum = -1; double bestReward, worstReward; double rewardGap; // モンテカルロ用の情報 std::atomic<bool> exitFlag; uint64_t limitSimulations; BetaDistribution monteCarloAllScore; uint64_t allSimulations; // 排他処理 SpinLock<int> lock_; void lock() { lock_.lock(); } void unlock() { lock_.unlock(); } void setCommonInfo(int num, const Field& field, const SharedData& shared, int limSim); void setChange(const Cards *const a, int num, const Field& field, const SharedData& shared, int limSim = -1); void setPlay(const MoveInfo *const a, int num, const Field& field, const SharedData& shared, int limSim = -1); void addPolicyScoreToMonteCarloScore(); void feedPolicyScore(const double *const score, int num); void feedSimulationResult(int triedIndex, const Field& field, SharedData *const pshared); void sort(); template <class callback_t> int sort(int ed, const callback_t& callback) { // 数値基準を定義して候補行動をソート const int num = std::min(ed, candidates); std::stable_sort(child.begin(), child.begin() + num, [&](const RootAction& a, const RootAction& b)->bool{ return callback(a) > callback(b); }); // 最高評価なものの個数を返す for (int i = 0; i < num; i++) { if (callback(child[i]) < callback(child[0])) return i; } return num; } template <class callback_t> int binary_sort(int ed, const callback_t& callback) { // ブール値を定義して候補行動をソート const int num = std::min(ed, candidates); std::stable_sort(child.begin(), child.begin() + num, [&](const RootAction& a, const RootAction& b)->bool{ return (callback(a) ? 1 : 0) > (callback(b) ? 1 : 0); }); // 最高評価なものの個数を返す for (int i = 0; i < num; i++) { if ((callback(child[i]) ? 1 : 0) < (callback(child[0]) ? 1 : 0)) return i; } return num; } std::string toString(int num = -1) const; RootInfo() { candidates = -1; monteCarloAllScore.set(0, 0); allSimulations = 0; rivalPlayerNum = -1; exitFlag = false; unlock(); } };
gpl-3.0
rajarshig/NewsHeadline
news_headline/news_headline.py
2413
import requests from bs4 import BeautifulSoup from datetime import datetime class NewsHeadline(object): """ Class to represent newsheadline data. Usage: 1. Initialise class instance with mandatory news type (indian / international) 2. get_headlines() function provides headlines data in list [] format """ def __init__(self, news_type): self.news_type = int(news_type) def get_headlines(self): if(self.news_type == 1): return self.indian_news_data() else: return [] def indian_news_data(self): news_list = list() # get telegraphindia headlines page_telegraphindia = requests.get('https://www.telegraphindia.com/?cache=clear').content soup_telegraphindia = BeautifulSoup(page_telegraphindia, 'html.parser') result_telegraphindia_headings = soup_telegraphindia.find_all( "a", href=True, class_=["storyBold", "secondLead"] ) for news in result_telegraphindia_headings: single_news = dict() single_news['base_url'] = 'https://www.telegraphindia.com' single_news['source'] = 'Telegraph India' single_news['title'] = news.contents[0] single_news['link'] = news['href'] # single_news['created_at'] = current_date.strftime("%Y-%m-%dT%H:%M:%S.000Z") current_date = datetime.utcnow() single_news['created_at'] = current_date.strftime("%Y-%m-%d %H:%M:%S") news_list.append(single_news) # get timesofindia headlines page_toi = requests.get('http://timesofindia.indiatimes.com/?cache=clear').content soup_toi = BeautifulSoup(page_toi, 'html.parser') result_toi_ul = soup_toi.find( "ul", class_=["list8"] ) result_toi_li = [li for li in result_toi_ul.find_all("li")] for li in result_toi_li: news = li.find("a", href=True) single_news = dict() single_news['base_url'] = 'http://timesofindia.indiatimes.com' single_news['source'] = 'Times of India' single_news['title'] = news.contents[0] single_news['link'] = news['href'] current_date = datetime.utcnow() single_news['created_at'] = current_date.strftime("%Y-%m-%d %H:%M:%S") news_list.append(single_news) return news_list
gpl-3.0
nemishkor/npu-calendars
application/views/groups_index_view.php
1750
<?php if($data){ $table_class = strtolower($this->registry['controller_name']) . '-table'; ?> <h1><i class="uk-icon-users"></i> Групи</h1> <div class="uk-margin uk-form"> <?php $this->widget('toolbar', array()); ?> <div class="uk-clearfix"></div> <button class="trash-toggle uk-float-right uk-button" type="button" data-uk-button>Показати/приховати елементи в корзині</button> <div class="uk-clearfix"></div> <h3>Ваші дані</h3> <?php $this->widget('table', array( 'data'=>$data, 'hiddenRow'=>array('trashed'=>'1'), 'hiddenColumn'=>array('trashed', 'created_by'), 'columnClass'=>array('id'=>'key'), 'tableClass' => $table_class . ' uk-table uk-table-hover uk-table-striped uk-table-condensed' ) ); ?> <h3>Спільні дані з іншими користувачами</h3> <?php $shared_data = array( 'fields' => $data['shared_fields'], 'items' => $data['shared_items'] ); $this->widget('table', array( 'data' => $shared_data, 'hiddenRow' => array('trashed'=>'1'), 'hiddenColumn' => array('trashed', 'created_by'), 'columnClass' => array('id'=>'key'), 'tableClass' => $table_class . ' uk-table uk-table-hover uk-table-striped uk-table-condensed' ) ); ?> </div> <?php } ?> <script> jQuery(document).ready(function(){ jQuery('.trash-toggle').click(function(){ if(!jQuery(this).hasClass('uk-active')) jQuery('.<?php echo $table_class; ?> .trash-1').parent().add('.column-trashed').removeClass('uk-hidden') else jQuery('.<?php echo $table_class; ?> .trash-1').parent().add('.column-trashed').addClass('uk-hidden') }); }); </script> <p class="uk-text-muted">var_dump($data)</p> <pre><?php var_dump($data); ?></pre>
gpl-3.0
Belxjander/Kirito
LibBitcoin/Explorer/include/bitcoin/explorer/primitives/base58.hpp
2937
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BX_BASE58_HPP #define BX_BASE58_HPP #include <iostream> #include <string> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/define.hpp> /* NOTE: don't declare 'using namespace foo' in headers. */ namespace libbitcoin { namespace explorer { namespace primitives { /** * Serialization helper to convert between data_chunk and base58. */ class BCX_API base58 { public: /** * Default constructor. */ base58(); /** * Initialization constructor. * @param[in] base58 The value to initialize with. */ base58(const std::string& base58); /** * Initialization constructor. * @param[in] value The value to initialize with. */ base58(const data_chunk& value); /** * Copy constructor. * @param[in] other The object to copy into self on construct. */ base58(const base58& other); /** * Overload cast to internal type. * @return This object's value cast to internal type. */ operator const data_chunk&() const; /** * Overload cast to generic data reference. * @return This object's value cast to a generic data reference. */ operator data_slice() const; /** * Overload stream in. Throws if input is invalid. * @param[in] input The input stream to read the value from. * @param[out] argument The object to receive the read value. * @return The input stream reference. */ friend std::istream& operator>>(std::istream& input, base58& argument); /** * Overload stream out. * @param[in] output The output stream to write the value to. * @param[out] argument The object from which to obtain the value. * @return The output stream reference. */ friend std::ostream& operator<<(std::ostream& output, const base58& argument); private: /** * The state of this object. */ data_chunk value_; }; } // namespace explorer } // namespace primitives } // namespace libbitcoin #endif
gpl-3.0
KurodaAkira/RPG-Hud
src/main/java/net/spellcraftgaming/rpghud/gui/GuiSettingsMod.java
10924
package net.spellcraftgaming.rpghud.gui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.spellcraftgaming.rpghud.gui.TextFieldWidgetMod.ValueType; import net.spellcraftgaming.rpghud.gui.hud.element.HudElementType; import net.spellcraftgaming.rpghud.main.ModRPGHud; import net.spellcraftgaming.rpghud.settings.SettingColor; import net.spellcraftgaming.rpghud.settings.SettingDouble; import net.spellcraftgaming.rpghud.settings.SettingPosition; import net.spellcraftgaming.rpghud.settings.Settings; @OnlyIn(Dist.CLIENT) public class GuiSettingsMod extends GuiScreenTooltip { /** The ModSettings instance */ private Settings settings; /** The GuiScreen which lead to this GUI */ private Screen parent; private String subSetting; private Map<String, List<TextFieldWidget>> textFields = new HashMap<String, List<TextFieldWidget>>(); private GuiSettingsMod instance; public GuiSettingsMod(Screen parent, String subSetting, ITextComponent titleIn) { super(titleIn); this.parent = parent; this.settings = ModRPGHud.instance.settings; this.subSetting = subSetting; this.instance = this; } public GuiSettingsMod(Screen parent, ITextComponent titleIn) { super(titleIn); this.parent = parent; this.settings = ModRPGHud.instance.settings; this.subSetting = ""; this.instance = this; } @Override public void init() { FontRenderer fontRenderer = minecraft.fontRenderer; if(this.subSetting.equals("")) { GuiButtonTooltip guismallbutton = new GuiButtonTooltip(this.width / 2 - 155 + 0 % 2 * 160, this.height / 6 - 14 + 20 * (0 >> 1), "general", new TranslationTextComponent("gui.rpg.general"), button -> { GuiButtonTooltip b = (GuiButtonTooltip) button; if(b.enumOptions != null) minecraft.displayGuiScreen(new GuiSettingsMod(instance, b.enumOptions, new TranslationTextComponent("gui.settings.rpghud"))); }).setTooltip(I18n.format("tooltip.general", new Object[0])); this.addButton(guismallbutton); int count = 1; for(HudElementType type : HudElementType.values()) { List<String> settings = this.settings.getSettingsOf(type); if(!settings.isEmpty()) { guismallbutton = new GuiButtonTooltip(this.width / 2 - 155 + count % 2 * 160, this.height / 6 - 14 + 20 * (count >> 1), type.name(), new TranslationTextComponent(type.getDisplayName()), button -> { GuiButtonTooltip b = (GuiButtonTooltip) button; if(b.enumOptions != null) { this.minecraft .displayGuiScreen(new GuiSettingsMod(instance, b.enumOptions, new TranslationTextComponent("gui.settings.rpghud"))); } }).setTooltip(I18n.format("tooltip.element", new Object[0])); this.addButton(guismallbutton); count++; } } } else { List<String> settingList = this.settings.getSettingsOf(this.subSetting); for(int i = 0; i < settingList.size(); i++) { if(this.settings.getSetting(settingList.get(i)) instanceof SettingPosition) { String[] values = ((String) this.settings.getSetting(settingList.get(i)).getValue()).split("_"); List<TextFieldWidget> fields = new ArrayList<TextFieldWidget>(); GuiTextLabel settingLabel = new GuiTextLabel(this.width / 2 - 151 + i % 2 * 160, this.height / 6 - 8 + 20 * (i >> 1), this.settings.getButtonString(settingList.get(i))); labelList.add(settingLabel); TextFieldWidget xPos = new TextFieldWidgetMod(fontRenderer, ValueType.POSITION, this.width / 2 - 100 + i % 2 * 160, this.height / 6 - 12 + 20 * (i >> 1), 45, 15, new TranslationTextComponent(values[0])); xPos.setText(values[0]); xPos.setMaxStringLength(6); this.children.add(xPos); fields.add(xPos); TextFieldWidget yPos = new TextFieldWidgetMod(fontRenderer, ValueType.POSITION, this.width / 2 - 100 + i % 2 * 160 + 48, this.height / 6 - 12 + 20 * (i >> 1), 45, 15, new TranslationTextComponent(values[1])); yPos.setText(values[1]); yPos.setMaxStringLength(6); this.children.add(yPos); fields.add(yPos); textFields.put(settingList.get(i), fields); } else if(this.settings.getSetting(settingList.get(i)) instanceof SettingDouble) { List<TextFieldWidget> fields = new ArrayList<TextFieldWidget>(); GuiTextLabel scaleLabel = new GuiTextLabel(this.width / 2 - 151 + i % 2 * 160, this.height / 6 - 8 + 20 * (i >> 1), this.settings.getButtonString(settingList.get(i))); TextFieldWidget scale = new TextFieldWidgetMod(fontRenderer, ValueType.DOUBLE, this.width / 2 - 100 + i % 2 * 160 +3, this.height / 6 - 12 + 20 * (i >> 1), 90, 15, new TranslationTextComponent(String.valueOf(this.settings.getDoubleValue(settingList.get(i))))); scale.setText(String.valueOf(this.settings.getDoubleValue(settingList.get(i)))); labelList.add(scaleLabel); this.children.add(scale); fields.add(scale); textFields.put(settingList.get(i), fields); } else { GuiButtonTooltip guismallbutton = new GuiButtonTooltip(this.width / 2 - 155 + i % 2 * 160, this.height / 6 - 14 + 20 * (i >> 1), settingList.get(i), new TranslationTextComponent(this.settings.getButtonString(settingList.get(i))), button -> { GuiButtonTooltip b = (GuiButtonTooltip) button; if(b.enumOptions != null) { if(settings.getSetting(b.enumOptions) instanceof SettingColor) { minecraft.displayGuiScreen( new GuiSettingsModColor(instance, b.enumOptions, new TranslationTextComponent("gui.settings.rpghud"))); } else { settings.increment(b.enumOptions); button.setMessage(new TranslationTextComponent(settings.getButtonString(b.enumOptions))); } } }).setTooltip(this.settings.getSetting(settingList.get(i)).getTooltip()); this.addButton(guismallbutton); } } } this.addButton(new Button(this.width / 2 - 100, this.height / 6 + 168, 200, 20, new TranslationTextComponent("gui.done"), button -> { for(String settingID : textFields.keySet()) { for(TextFieldWidget t : textFields.get(settingID)) { if(t instanceof TextFieldWidgetMod) { ValueType type = ((TextFieldWidgetMod) t).getValueType(); switch(type) { case DOUBLE: double value; try { value = Double.valueOf(textFields.get(settingID).get(0).getText()); this.settings.getSetting(settingID).setValue(value); } catch(NumberFormatException e) { } break; case POSITION: this.settings.getSetting(settingID) .setValue(textFields.get(settingID).get(0).getText() + "_" + textFields.get(settingID).get(1).getText()); break; } } } } this.settings.saveSettings(); this.minecraft.displayGuiScreen(parent); })); } @Override public void render(MatrixStack ms, int mouseX, int mouseY, float partialTicks) { this.renderBackground(ms); AbstractGui.drawCenteredString(ms, minecraft.fontRenderer, I18n.format("gui.rpg.settings", new Object[0]), this.width / 2, 12, 16777215); for(List<TextFieldWidget> positionPairs : textFields.values()) { for(TextFieldWidget t : positionPairs) t.render(ms, mouseX, mouseY, partialTicks); } super.render(ms, mouseX, mouseY, partialTicks); } @Override public void tick() { super.tick(); for(String settingID : textFields.keySet()) { for(TextFieldWidget t : textFields.get(settingID)) { if(t instanceof TextFieldWidgetMod) { ValueType type = ((TextFieldWidgetMod) t).getValueType(); switch(type) { case DOUBLE: double value; try { value = Double.valueOf(textFields.get(settingID).get(0).getText()); this.settings.getSetting(settingID).setValue(value); } catch(NumberFormatException e) { } break; case POSITION: this.settings.getSetting(settingID) .setValue(textFields.get(settingID).get(0).getText() + "_" + textFields.get(settingID).get(1).getText()); break; } } t.tick(); } } } }
gpl-3.0
SciCompKL/CoDiPack
include/codi/tapes/data/blockData.hpp
10571
/* * CoDiPack, a Code Differentiation Package * * Copyright (C) 2015-2022 Chair for Scientific Computing (SciComp), TU Kaiserslautern * Homepage: http://www.scicomp.uni-kl.de * Contact: Prof. Nicolas R. Gauger (codi@scicomp.uni-kl.de) * * Lead developers: Max Sagebaum, Johannes Blühdorn (SciComp, TU Kaiserslautern) * * This file is part of CoDiPack (http://www.scicomp.uni-kl.de/software/codi). * * CoDiPack 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. * * CoDiPack 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 CoDiPack. * If not, see <http://www.gnu.org/licenses/>. * * For other licensing options please contact us. * * Authors: * - SciComp, TU Kaiserslautern: * - Max Sagebaum * - Johannes Blühdorn * - Former members: * - Tim Albring */ #pragma once #pragma once #include <vector> #include "../../misc/macros.hpp" #include "../../config.h" #include "../../traits/misc/enableIfHelpers.hpp" #include "chunk.hpp" #include "dataInterface.hpp" #include "emptyData.hpp" #include "pointerStore.hpp" #include "position.hpp" /** \copydoc codi::Namespace */ namespace codi { /** * @brief Data is stored in one contiguous block in this DataInterface implementation. * * See DataInterface documentation for details. * * This implementation does not check in #reserveItems if enough space is available. It needs to be preallocated with * #resize. * * @tparam T_Chunk Has to implement ChunkBase. The chunk defines the data stored in this implementation. * @tparam T_NestedData Nested DataInterface. * @tparam T_PointerInserter Defines how data is appended to evaluate* function calls. */ template<typename T_Chunk, typename T_NestedData = EmptyData, typename T_PointerInserter = PointerStore<T_Chunk>> struct BlockData : public DataInterface<T_NestedData> { public: using Chunk = CODI_DD(T_Chunk, CODI_T(ChunkBase<CODI_ANY>)); ///< See BlockData using NestedData = CODI_DD(T_NestedData, CODI_T(DataInterface<CODI_ANY>)); ///< See BlockData using PointerInserter = CODI_DD(T_PointerInserter, CODI_T(PointerStore<Chunk>)); ///< See BlockData using InternalPosHandle = size_t; ///< Position in the chunk using NestedPosition = typename NestedData::Position; ///< Position of NestedData using Position = ArrayPosition<NestedPosition>; ///< \copydoc DataInterface::Position private: Chunk chunk; NestedData* nested; public: /// Allocate chunkSize entries and set the nested DataInterface. BlockData(size_t const& chunkSize, NestedData* nested) : chunk(chunkSize), nested(nullptr) { setNested(nested); } /// Allocate chunkSize entries. Requires a call to #setNested. BlockData(size_t const& chunkSize) : chunk(chunkSize), nested(nullptr) {} /*******************************************************************************/ /// @name Adding items /// \copydoc DataInterface::pushData template<typename... Data> CODI_INLINE void pushData(Data const&... data) { // This method should only be called if reserveItems has been called. chunk.pushData(data...); } /// \copydoc DataInterface::reserveItems <br><br> /// Implementation: Does not check if enough space is available. CODI_INLINE InternalPosHandle reserveItems(size_t const& items) { codiAssert(chunk.getUsedSize() + items <= chunk.getSize()); return chunk.getUsedSize(); } /*******************************************************************************/ /// @name Size management /// \copydoc DataInterface::resize void resize(size_t const& totalSize) { chunk.resize(totalSize); } /// \copydoc DataInterface::reset void reset() { resetTo(getZeroPosition()); } /// \copydoc DataInterface::resetHard void resetHard() { chunk.resize(0); nested->resetHard(); } /// \copydoc DataInterface::resetTo void resetTo(Position const& pos) { codiAssert(pos.data <= chunk.getSize()); chunk.setUsedSize(pos.data); nested->resetTo(pos.inner); } /*******************************************************************************/ /// @name Position functions /// \copydoc DataInterface::getDataSize CODI_INLINE size_t getDataSize() const { return chunk.getUsedSize(); } /// \copydoc DataInterface::getPosition CODI_INLINE Position getPosition() const { return Position(chunk.getUsedSize(), nested->getPosition()); } /// \copydoc DataInterface::getPushedDataCount CODI_INLINE size_t getPushedDataCount(InternalPosHandle const& startPos) { return chunk.getUsedSize() - startPos; } /// \copydoc DataInterface::getZeroPosition CODI_INLINE Position getZeroPosition() const { return Position(0, nested->getZeroPosition()); } /*******************************************************************************/ /// @name Misc functions /// \copydoc DataInterface::addToTapeValues <br><br> /// Implementation: Adds: Total number, Memory used, Memory allocated void addToTapeValues(TapeValues& values) const { size_t allocedSize = chunk.getSize(); size_t dataEntries = getDataSize(); size_t entrySize = Chunk::EntrySize; double memoryUsed = (double)dataEntries * (double)entrySize; double memoryAlloc = (double)allocedSize * (double)entrySize; values.addUnsignedLongEntry("Total number", dataEntries); values.addDoubleEntry("Memory used", memoryUsed, true, false); values.addDoubleEntry("Memory allocated", memoryAlloc, false, true); } /// \copydoc DataInterface::extractPosition template<typename TargetPosition, typename = typename enable_if_not_same<TargetPosition, Position>::type> CODI_INLINE TargetPosition extractPosition(Position const& pos) const { return nested->template extractPosition<TargetPosition>(pos.inner); } /// \copydoc DataInterface::extractPosition template<typename TargetPosition, typename = typename enable_if_same<TargetPosition, Position>::type> CODI_INLINE Position extractPosition(Position const& pos) const { return pos; } /// \copydoc DataInterface::setNested void setNested(NestedData* v) { // Set nested is only called once during the initialization. codiAssert(nullptr == this->nested); codiAssert(v->getZeroPosition() == v->getPosition()); this->nested = v; } /// \copydoc DataInterface::swap void swap(BlockData<Chunk, NestedData>& other) { chunk.swap(other.chunk); nested->swap(*other.nested); } /*******************************************************************************/ /// @name Iterator functions /// \copydoc DataInterface::evaluateForward template<typename FunctionObject, typename... Args> CODI_INLINE void evaluateForward(Position const& start, Position const& end, FunctionObject function, Args&&... args) { PointerInserter pHandle; pHandle.setPointers(0, &chunk); size_t dataPos = start.data; pHandle.callNestedForward( /* arguments for callNestedForward */ nested, dataPos, end.data, /* arguments for nested->evaluateForward */ start.inner, end.inner, function, std::forward<Args>(args)...); codiAssert(dataPos == end.data); } /// \copydoc DataInterface::evaluateReverse template<typename FunctionObject, typename... Args> CODI_INLINE void evaluateReverse(Position const& start, Position const& end, FunctionObject function, Args&&... args) { PointerInserter pHandle; size_t dataPos = start.data; pHandle.setPointers(0, &chunk); pHandle.callNestedReverse( /* arguments for callNestedReverse */ nested, dataPos, end.data, /* arguments for nested->evaluateReverse */ start.inner, end.inner, function, std::forward<Args>(args)...); codiAssert(dataPos == end.data); } /// \copydoc DataInterface::forEachChunk template<typename FunctionObject, typename... Args> CODI_INLINE void forEachChunk(FunctionObject& function, bool recursive, Args&&... args) { function(&chunk, std::forward<Args>(args)...); if (recursive) { nested->forEachChunk(function, recursive, std::forward<Args>(args)...); } } /// \copydoc DataInterface::forEachForward template<typename FunctionObject, typename... Args> CODI_INLINE void forEachForward(Position const& start, Position const& end, FunctionObject function, Args&&... args) { codiAssert(start.data <= end.data); PointerInserter pHandle; for (size_t dataPos = start.data; dataPos < end.data; dataPos += 1) { pHandle.setPointers(dataPos, &chunk); pHandle.call(function, std::forward<Args>(args)...); } } /// \copydoc DataInterface::forEachReverse template<typename FunctionObject, typename... Args> CODI_INLINE void forEachReverse(Position const& start, Position const& end, FunctionObject function, Args&&... args) { codiAssert(start.data >= end.data); PointerInserter pHandle; // We do not initialize dataPos with start - 1 since the type can be unsigned. for (size_t dataPos = start.data; dataPos > end.data; /* decrement is done inside the loop */) { dataPos -= 1; // Decrement of loop variable. pHandle.setPointers(dataPos, &chunk); pHandle.call(function, std::forward<Args>(args)...); } } }; }
gpl-3.0
guivaloz/GenesisPHP
Demostracion/htdocs-sobreescribir/lib/Configuracion/CookieConfig.php
1613
<?php /** * GenesisPHP - CookieConfig * * Copyright (C) 2016 Guillermo Valdés Lozano * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package GenesisPHP */ namespace Configuracion; /** * Clase abstracta CookieConfig * * Configuración de la cookie */ abstract class CookieConfig { protected $nom_cookie = 'genesisphp_demostracion'; // Nombre con el que se guardara la cookie en el navegador. protected $version_actual = 1; // Número entero que sirve para obligar a renover las cookies anteriores protected $tiempo_expirar = 86400; // Tiempo en segundos para que expire la cookie, 60 x 60 x 24 = 86400 seg = 1 dia protected $tiempo_renovar = 3600; // Tiempo en segundos para que se renueve la cookie, 60 x 60 = 3600 seg = 1 hora protected $key = '1234123412341234'; // 16 caracteres o más que sean muy difíciles de adivinar para llave de cifrado } // Clase abstracta CookieConfig ?>
gpl-3.0
mmagnus/geekbook
engine/make_index.py
5052
#!/usr/bin/env python """geekbook - make index Get the list of md with sys.stdint.read() and generate html index.html. The top of the html file is defined here, see the html variable. The second part is generated in the loop, per md make a link in the index.html. """ import os import time import re from engine.conf import PATH_TO_HTML, PATH_TO_TEMPLATE, PATH_HOMEPAGE, PATH_TO_MD, PATH_TO_TEMPLATE_HTML # noqa FLASK_BASED = True class Index(object): def __init__(self): pass def update(self, list_md): """Update the index page :param list_md: is a list of your md files""" if FLASK_BASED: # flask mode head = open(PATH_TO_TEMPLATE_HTML).read() head = head.replace('{{ url_index }}', PATH_TO_HTML + '/' + 'index.html') head = head.replace('href="img/', 'href="' + '/img/') head = head.replace('="lib/', '="' + '/lib/') head = head.replace('="css/', '="' + '/css/') head = head.replace('="js/', '="' + '/js/') # remove demo content head = re.sub(r'<!-- start of demo -->.*<!-- end of demo -->', r'', head, flags=re.M | re.DOTALL) # insert dataTables "sorting":true, head += """ <style> body { background-color: black; }</style> <!-- "paging": false, --> <table id="table_id" class="display compact hover"> <thead> <tr> <th>Title</th> <th>Last update</th> <th style="text-align:center">#</th> </tr> </thead> <tbody> """ html = head else: html = open(PATH_TO_TEMPLATE + '/head.html').read() html = html.replace('{{ url_index }}', PATH_TO_HTML + '/' + 'index.html') # @todo html = html.replace('href="img/', 'href="' + PATH_TO_TEMPLATE + '/img/') html = html.replace('src="img/', 'src="' + PATH_TO_TEMPLATE + '/img/') html = html.replace('="lib/', '="' + PATH_TO_TEMPLATE + '/lib/') html = html.replace('="css/', '="' + PATH_TO_TEMPLATE + '/css/') # remove demo content html = re.sub(r'<!-- start of demo -->.*<!-- end of demo -->', r'', html, flags=re.M | re.DOTALL) ## for mdfn in list_md: if mdfn == 'imgs': pass else: if mdfn.strip(): # Insert the description in the index f = open(PATH_TO_MD + os.sep + mdfn) lines = f.readlines() f.seek(0) if lines: # if the file is empty if lines[0][0] == '#': desc = lines[0][1].strip() # if '# blelbe' -> 'bleble' else: desc = lines[0] else: desc = '' for l in f: # the tag will overwrite this before if l.strip().startswith('[desc:'): desc = l.replace('[desc:', '').replace(']', '').strip() mdfn = re.sub('.md$', '', mdfn) # replace only .md at the very end path = PATH_TO_HTML + '/' + mdfn # if l.find('::')>=0: # html += '<li class="table_of_content_h2"> # <a style="" href="' + path + '.html">' + l + '</a></li>' # else: if FLASK_BASED: html += '<tr><td style=""><a class="index_list_a" href="/view/' + mdfn + '.html">' \ + mdfn + '</a>' + '</br><span style="font-size:10px;color:gray">' + desc + '</td>' \ + '<td style="white-space: nowrap;"><small><center class="index_date">' \ + time.ctime(os.stat(os.path.join(PATH_TO_MD, mdfn + '.md')).st_mtime) \ + '</center></small></td>' \ + '<td><small><center class="index_date">' + str(len(lines)) + '</center>' \ + '</small></td></tr>' else: html += '<tr><td><a class="index_list_a" href="' + path + '.html">' \ + mdfn + '</a></td>' + '<td>' + desc + '</td>' \ + '<td><small><center class="index_date">' + \ time.ctime(os.stat(os.path.join(PATH_TO_MD, mdfn + '.md') ).st_mtime) + '</center></small></td></tr>' html += '</p>' html += "</tbody></table>" f = open(PATH_TO_HTML + 'index.html', 'w') f.write(html) f.close()
gpl-3.0
ilri/ckanext-dataportal
ckanext-ilrimetadata/ckanext/ilrimetadata/connection.py
1280
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from pylons import config def getSession(): """ Initialize the model for a Pyramid app. Activate this setup using ``config.include('wportal.models')``. """ mysqlUser = config["ilriextensions.mysql.user"] mysqlPassword = config["ilriextensions.mysql.password"] mysqlHost = config["ilriextensions.mysql.host"] mysqlPort = config["ilriextensions.mysql.port"] mysqlSchema = config["ilriextensions.mysql.schema"] engine = create_engine( "mysql+mysqlconnector://" + mysqlUser + ":" + mysqlPassword + "@" + mysqlHost + ":" + mysqlPort + "/" + mysqlSchema, pool_size=20, max_overflow=0, pool_recycle=2000, ) DBSession = scoped_session(sessionmaker()) DBSession.configure(bind=engine) return DBSession def closeSession(DBSession): try: DBSession.commit() except Exception as e: print "*************************666" print e print "*************************666" try: DBSession.rollback() except: pass DBSession.close()
gpl-3.0
mrlolethan/Buttered-Pixel-Dungeon
src/com/mrlolethan/butteredpd/actors/mobs/King.java
8853
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.mrlolethan.butteredpd.actors.mobs; import java.util.HashSet; import com.mrlolethan.butteredpd.Assets; import com.mrlolethan.butteredpd.Badges; import com.mrlolethan.butteredpd.Dungeon; import com.mrlolethan.butteredpd.actors.Actor; import com.mrlolethan.butteredpd.actors.Char; import com.mrlolethan.butteredpd.actors.blobs.ToxicGas; import com.mrlolethan.butteredpd.actors.buffs.Buff; import com.mrlolethan.butteredpd.actors.buffs.Paralysis; import com.mrlolethan.butteredpd.actors.buffs.Vertigo; import com.mrlolethan.butteredpd.effects.Flare; import com.mrlolethan.butteredpd.effects.Speck; import com.mrlolethan.butteredpd.gamemodes.GameMode; import com.mrlolethan.butteredpd.items.ArenaShopKey; import com.mrlolethan.butteredpd.items.ArmorKit; import com.mrlolethan.butteredpd.items.artifacts.LloydsBeacon; import com.mrlolethan.butteredpd.items.keys.SkeletonKey; import com.mrlolethan.butteredpd.items.scrolls.ScrollOfPsionicBlast; import com.mrlolethan.butteredpd.items.scrolls.ScrollOfTeleportation; import com.mrlolethan.butteredpd.items.wands.WandOfDisintegration; import com.mrlolethan.butteredpd.items.weapon.enchantments.Death; import com.mrlolethan.butteredpd.levels.CityBossLevel; import com.mrlolethan.butteredpd.levels.Level; import com.mrlolethan.butteredpd.scenes.GameScene; import com.mrlolethan.butteredpd.sprites.KingSprite; import com.mrlolethan.butteredpd.sprites.UndeadSprite; import com.mrlolethan.butteredpd.utils.GLog; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Bundle; import com.watabou.utils.PathFinder; import com.watabou.utils.Random; public class King extends Mob { private static final int MAX_ARMY_SIZE = 5; { name = "King of Dwarves"; spriteClass = KingSprite.class; HP = HT = 300; EXP = 40; defenseSkill = 25; Undead.count = 0; } private boolean nextPedestal = true; private static final String PEDESTAL = "pedestal"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( PEDESTAL, nextPedestal ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); nextPedestal = bundle.getBoolean( PEDESTAL ); } @Override public int damageRoll() { return Random.NormalIntRange( 20, 38 ); } @Override public int attackSkill( Char target ) { return 32; } @Override public int dr() { return 14; } @Override public String defenseVerb() { return "parried"; } @Override protected boolean getCloser( int target ) { return canTryToSummon() ? super.getCloser( CityBossLevel.pedestal( nextPedestal ) ) : super.getCloser( target ); } @Override protected boolean canAttack( Char enemy ) { return canTryToSummon() ? pos == CityBossLevel.pedestal( nextPedestal ) : Level.adjacent( pos, enemy.pos ); } private boolean canTryToSummon() { if (Undead.count < maxArmySize()) { Char ch = Actor.findChar( CityBossLevel.pedestal( nextPedestal ) ); return ch == this || ch == null; } else { return false; } } @Override public boolean attack( Char enemy ) { if (canTryToSummon() && pos == CityBossLevel.pedestal( nextPedestal )) { summon(); return true; } else { if (Actor.findChar( CityBossLevel.pedestal( nextPedestal ) ) == enemy) { nextPedestal = !nextPedestal; } return super.attack(enemy); } } @Override public void die( Object cause ) { GameScene.bossSlain(); Dungeon.level.drop( new ArmorKit(), pos ).sprite.drop(); if (Dungeon.gamemode == GameMode.REGULAR) { Dungeon.level.drop( new SkeletonKey( Dungeon.depth ), pos ).sprite.drop(); } else if (Dungeon.gamemode == GameMode.ARENA) { // Level up Dungeon.hero.earnExp(Dungeon.hero.maxExp()); ArenaShopKey key = new ArenaShopKey(); key.identify(); Dungeon.level.drop(key, pos).sprite.drop(); } super.die( cause ); Badges.validateBossSlain(); LloydsBeacon beacon = Dungeon.hero.belongings.getItem(LloydsBeacon.class); if (beacon != null) { beacon.upgrade(); GLog.p("Your beacon grows stronger!"); } yell( "You cannot kill me, " + Dungeon.hero.givenName() + "... I am... immortal..." ); } private int maxArmySize() { return 1 + MAX_ARMY_SIZE * (HT - HP) / HT; } private void summon() { nextPedestal = !nextPedestal; sprite.centerEmitter().start( Speck.factory( Speck.SCREAM ), 0.4f, 2 ); Sample.INSTANCE.play( Assets.SND_CHALLENGE ); boolean[] passable = Level.passable.clone(); for (Char c : Actor.chars()) { passable[c.pos] = false; } int undeadsToSummon = maxArmySize() - Undead.count; PathFinder.buildDistanceMap( pos, passable, undeadsToSummon ); PathFinder.distance[pos] = Integer.MAX_VALUE; int dist = 1; undeadLabel: for (int i=0; i < undeadsToSummon; i++) { do { for (int j=0; j < Level.LENGTH; j++) { if (PathFinder.distance[j] == dist) { Undead undead = new Undead(); undead.pos = j; GameScene.add( undead ); ScrollOfTeleportation.appear( undead, j ); new Flare( 3, 32 ).color( 0x000000, false ).show( undead.sprite, 2f ) ; PathFinder.distance[j] = Integer.MAX_VALUE; continue undeadLabel; } } dist++; } while (dist < undeadsToSummon); } yell( "Arise, slaves!" ); } @Override public void notice() { super.notice(); yell( "How dare you!" ); } @Override public String description() { return "The last king of dwarves was known for his deep understanding of processes of life and death. " + "He has persuaded members of his court to participate in a ritual, that should have granted them " + "eternal youthfulness. In the end he was the only one, who got it - and an army of undead " + "as a bonus."; } private static final HashSet<Class<?>> RESISTANCES = new HashSet<Class<?>>(); static { RESISTANCES.add( ToxicGas.class ); RESISTANCES.add( Death.class ); RESISTANCES.add( ScrollOfPsionicBlast.class ); RESISTANCES.add( WandOfDisintegration.class ); } @Override public HashSet<Class<?>> resistances() { return RESISTANCES; } private static final HashSet<Class<?>> IMMUNITIES = new HashSet<Class<?>>(); static { IMMUNITIES.add( Paralysis.class ); IMMUNITIES.add( Vertigo.class ); } @Override public HashSet<Class<?>> immunities() { return IMMUNITIES; } public static class Undead extends Mob { public static int count = 0; { name = "undead dwarf"; spriteClass = UndeadSprite.class; HP = HT = 28; defenseSkill = 15; EXP = 0; state = WANDERING; } @Override protected void onAdd() { count++; super.onAdd(); } @Override protected void onRemove() { count--; super.onRemove(); } @Override public int damageRoll() { return Random.NormalIntRange( 12, 16 ); } @Override public int attackSkill( Char target ) { return 16; } @Override public int attackProc( Char enemy, int damage ) { if (Random.Int( MAX_ARMY_SIZE ) == 0) { Buff.prolong( enemy, Paralysis.class, 1 ); } return damage; } @Override public void damage( int dmg, Object src ) { super.damage( dmg, src ); if (src instanceof ToxicGas) { ((ToxicGas)src).clear( pos ); } } @Override public void die( Object cause ) { super.die( cause ); if (Dungeon.visible[pos]) { Sample.INSTANCE.play( Assets.SND_BONES ); } } @Override public int dr() { return 5; } @Override public String defenseVerb() { return "blocked"; } @Override public String description() { return "These undead dwarves, risen by the will of the King of Dwarves, were members of his court. " + "They appear as skeletons with a stunning amount of facial hair."; } private static final HashSet<Class<?>> IMMUNITIES = new HashSet<Class<?>>(); static { IMMUNITIES.add( Death.class ); IMMUNITIES.add( Paralysis.class ); } @Override public HashSet<Class<?>> immunities() { return IMMUNITIES; } } }
gpl-3.0
blankaspect/onda
src/main/java/uk/blankaspect/onda/OndaDataInput.java
7591
/*====================================================================*\ OndaDataInput.java Onda lossless audio compression data input class. \*====================================================================*/ // PACKAGE package uk.blankaspect.onda; //---------------------------------------------------------------------- // IMPORTS import java.io.DataInput; import java.io.EOFException; import java.io.IOException; //---------------------------------------------------------------------- // ONDA LOSSLESS AUDIO COMPRESSION DATA INPUT CLASS /** * This class implements a data input for decompressing blocks of data that have been compressed with the * Onda lossless audio compression algorithm. Input data is assumed to be in the form of a sequence of data * blocks, as specified by the * <a href="http://onda.sourceforge.net/ondaAlgorithmAndFileFormats.html">Onda algorithm</a>. * <p> * The underlying data source for this input is an instance of {@code java.io.DataInput}. Data that is read * from the data source is buffered to improve efficiency. * </p> * <p> * The implementation of this class in the Onda application works only for integer sample values of up to 24 * bits per sample. Above 24 bits per sample, the type of the instance variable {@code bitBuffer} must be * changed from {@code int} to {@code long} to accommodate the extra bits. * </p> * * @see OndaDataOutput */ public class OndaDataInput { //////////////////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////////////////// private static final int BUFFER_SIZE = 1 << 13; // 8192 //////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////// /** * Constructs an {@code OndaDataInput} that has an instance of {@code java.io.DataInput} as its * underlying data source. * * @param dataLength the length (in bytes) of the input data. * @param numChannels the number of audio channels in the sample data. * @param sampleLength the length (in bits) of a sample value. * @param keyLength the length (in bits) of an encoding key. * @param dataInput the underlying source from which compressed data is to be read. */ public OndaDataInput(long dataLength, int numChannels, int sampleLength, int keyLength, DataInput dataInput) { this.dataLength = dataLength; this.numChannels = numChannels; this.sampleLength = sampleLength; this.keyLength = keyLength; this.dataInput = dataInput; inBuffer = new byte[BUFFER_SIZE]; inBufferIndex = inBuffer.length; encodingLengths = new int[numChannels]; excessCodes = new int[numChannels]; epsilonMasks = new int[numChannels]; } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance methods //////////////////////////////////////////////////////////////////////// /** * Reads a block of compressed data from the data source, and decompresses the data into the specified * buffer. The input data must be in the form of a data block of an Onda file (ie, a compression key * for each channel, followed by interleaved encoded data). * * @param buffer the buffer in which the decompressed data is to be stored. * @param offset the start offset at which sample data is to be stored in {@code buffer}. * @param length the number of samples that are to be read. * @throws IllegalArgumentException * <ul> * <li>{@code buffer} is {@code null}, or</li> * <li>{@code (length < 0)} or {@code (length > buffer.length - offset)}.</li> * </ul> * @throws IndexOutOfBoundsException * if {@code (offset < 0)} or {@code (offset > buffer.length)}. * @throws IOException * if an error occurs while attempting to read from the data source. */ public void readBlock(int[] buffer, int offset, int length) throws IOException { // Validate arguments if (buffer == null) throw new IllegalArgumentException(); if ((offset < 0) || (offset > buffer.length)) throw new IndexOutOfBoundsException(); if ((length < 0) || (length > buffer.length - offset)) throw new IllegalArgumentException(); // Get encoding length for each channel from key; initialise per-channel encoding variables for (int i = 0; i < numChannels; i++) { encodingLengths[i] = sampleLength - read(keyLength); excessCodes[i] = 1 << encodingLengths[i] - 1; epsilonMasks[i] = ~(excessCodes[i] - 1); } // Read sample data from source, decode them and write them to buffer int[] prevSampleValues = new int[numChannels]; int[] prevDeltas = new int[numChannels]; int sampleValue = 0; int delta = 0; boolean sampleValueExpected = false; int startOffset = offset; int endOffset = startOffset + length; while (offset < endOffset) { for (int i = 0; i < numChannels; i++) { if ((offset == startOffset) || (encodingLengths[i] == sampleLength)) sampleValue = read(sampleLength); else { while (true) { if (sampleValueExpected) { sampleValue = read(sampleLength); sampleValueExpected = false; break; } else { int epsilon = read(encodingLengths[i]); if (epsilon == excessCodes[i]) sampleValueExpected = true; else { if ((epsilon & excessCodes[i]) != 0) epsilon |= epsilonMasks[i]; delta = prevDeltas[i] + epsilon; sampleValue = prevSampleValues[i] + delta; break; } } } } prevDeltas[i] = sampleValue - prevSampleValues[i]; prevSampleValues[i] = sampleValue; buffer[offset++] = sampleValue; } } } //------------------------------------------------------------------ /** * Reads a bit string of a specified length from the data source. * * @param length the number of bits to read. * @return the bit string that was read from the data source, as an unsigned integer. * @throws IOException * if an error occurs while attempting to read from the data source. */ private int read(int length) throws IOException { while (bitDataLength < length) { if (inBufferIndex >= inBuffer.length) { if (dataLength == 0) throw new EOFException(); int readLength = (int)Math.min(dataLength, inBuffer.length); inBufferIndex = inBuffer.length - readLength; dataInput.readFully(inBuffer, inBufferIndex, readLength); dataLength -= readLength; } bitBuffer <<= 8; bitBuffer |= inBuffer[inBufferIndex++] & 0xFF; bitDataLength += 8; } bitDataLength -= length; return (bitBuffer >>> bitDataLength & ((1 << length) - 1)); } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance variables //////////////////////////////////////////////////////////////////////// private DataInput dataInput; private long dataLength; private int numChannels; private int sampleLength; private int keyLength; private int bitBuffer; private int bitDataLength; private int inBufferIndex; private byte[] inBuffer; private int[] encodingLengths; private int[] excessCodes; private int[] epsilonMasks; } //----------------------------------------------------------------------
gpl-3.0
bailey-lab/graphSourceCode
scripts/fix_pragma_once.py
1083
#!/usr/bin/python import os, glob, sys po = "#pragma once" def is_header(fn): fn = fn.lower() if fn.endswith(".h") or fn.endswith(".hpp"): return True return False def fixFile(fnp): q = open(fnp).read() with open(fnp, "w") as f: f.write(po + "\n") for line in q.split("\n"): if line.startswith("#define") or line.startswith("#ifndef"): print line continue if line.startswith("#endif"): print line continue f.write(line + "\n") d = os.path.dirname(os.path.abspath(__file__)) d = os.path.join(d, "../") src_folders = glob.glob("{d}/src".format(d=d)) for path in src_folders: for root, dirs, files in os.walk(path): for fn in files: if not is_header(fn): continue fnp = os.path.join(root, fn) fnp = os.path.abspath(fnp) firstline = open(fnp).readline().rstrip() if po != firstline: print "fixing", fnp fixFile(fnp)
gpl-3.0
241180/Oryx
framework8-demo-master/spring-demo/spring-demo-backend/src/test/java/com/vaadin/framework8/samples/backend/TestConfig.java
1137
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.framework8.samples.backend; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; /** * @author Vaadin Ltd * */ @Configuration @EnableAutoConfiguration @SpringBootConfiguration @EnableJpaRepositories @ComponentScan public class TestConfig { }
gpl-3.0
neuroanatomy/microdraw
app/controller/user/user.controller.js
5077
/* eslint-disable camelcase */ /* eslint-disable radix */ // const async = require('async'); const dateFormat = require('dateformat'); //const checkAccess = require('../checkAccess/checkAccess.js'); //const dataSlices = require('../dataSlices/dataSlices.js'); const validator = function (req, res, next) { // UserName can be an ip address (for anonymous users) /* req.checkParams('userName', 'incorrect user name').isAlphanumeric(); var errors = req.validationErrors(); console.log(errors); if (errors) { res.send(errors).status(403).end(); } else { return next(); } */ next(); }; const user = function (req, res) { const login = (req.user) ? ('<a href=\'/user/' + req.user.username + '\'>' + req.user.username + '</a> (<a href=\'/logout\'>Log Out</a>)') : ('<a href=\'/auth/github\'>Log in with GitHub</a>'); const username = req.params.userName; // Store return path in case of login req.session.returnTo = req.originalUrl; req.appConfig.db.queryUser({username}) .then((json) => { if (json) { const context = { username, // json.name, // nickname: json.nickname, joined: dateFormat(json.joined, 'dddd d mmm yyyy, HH:MM'), avatar: json.avatarURL, title: json.name, userInfo: JSON.stringify(json), tab: req.query.tab || 'data', login }; res.render('user', context); } else { res.status(404).send('User Not Found'); } }) .catch((err) => { console.log('ERROR:', err); res.status(400).send('Error'); }); }; const api_user = function (req, res) { req.appConfig.db.queryUser({username: req.params.userName, backup: {$exists: false}}) .then((json) => { if (json) { if (req.query.var) { let i; const arr = req.query.var.split('/'); for (i of arr) { json = json[arr[i]]; } } res.send(json); } else { res.send(); } }); }; const api_userAll = function (req, res) { console.log('api_userAll'); if (!req.query.page) { res.json({error: 'The \'pages\' parameter has to be specified'}); return; } const page = parseInt(req.query.page); const nItemsPerPage = 20; req.appConfig.db.queryAllUsers({backup: {$exists: false}}, {skip: page * nItemsPerPage, limit: nItemsPerPage, fields: {_id: 0}}) .then((array) => { res.send(array.map((o) => o.username)); }); }; /** * @todo Check access rights for this route */ /** * @param {object} req Request object * @param {object} res Response object * @returns {void} */ const api_userFiles = function (req, res) { const {userName} = req.params; const start = parseInt(req.query.start); const length = parseInt(req.query.length); console.log('userName:', userName, 'start:', start, 'length:', length); res.send({ success:true, message:'WARNING: THIS FUNCTION IS NOT YET IMPLEMENTED', list: [ {name: 'test1', dimensions: '3000x2000x200', included: 'yes'}, {name: 'test2', dimensions: '4000x3000x300', included: 'yes'}, {name: 'test3', dimensions: '5000x4000x400', included: 'yes'} ] }); /* dataSlices.getUserFilesSlice(req, userName, start, length) .then(result => { res.send(result); }) .catch(err => { console.log('ERROR:', err); res.send({success: false, list: []}); }); */ }; /** * @todo Check access rights for this route */ /** * @param {object} req Request object * @param {object} res Response object * @returns {void} */ const api_userAtlas = function (req, res) { const {userName} = req.params; const start = parseInt(req.query.start); const length = parseInt(req.query.length); console.log('userName:', userName, 'start:', start, 'length:', length); res.send({ successful: true, message: "WARNING: THIS FUNCTIONALITY IS NOT YET IMPLEMENTED", list: [ {parent: 'Test 1', name: 'test 1', project: 'testproject1', lastModified: (new Date()).toJSON()}, {parent: 'Test 2', name: 'test 2', project: 'testproject2', lastModified: (new Date()).toJSON()} ] }); /* dataSlices.getUserAtlasSlice(req, userName, start, length) .then(result => { res.send(result); }) .catch(err => { console.log('ERROR:', err); res.send({success: false, list: []}); }); */ }; /** * @todo Check access rights for this route */ /** * @param {object} req Request object * @param {object} res Response object * @returns {void} */ const api_userProjects = function (req, res) { const {userName} = req.params; // const start = parseInt(req.query.start); // const length = parseInt(req.query.length); req.appConfig.db.queryUserProjects(userName) .then((result) => { res.send({ successful: true, list: result }); }); }; module.exports = { validator, api_user, api_userAll, api_userFiles, api_userAtlas, api_userProjects, user };
gpl-3.0
hufsm/tu_gen2_libsigrokdecode
decoders/dcf77/pd.py
12718
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2012-2016 Uwe Hermann <uwe@hermann-uwe.de> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd import calendar from common.srdhelper import bcd2int class SamplerateError(Exception): pass class Decoder(srd.Decoder): api_version = 3 id = 'dcf77' name = 'DCF77' longname = 'DCF77 time protocol' desc = 'European longwave time signal (77.5kHz carrier signal).' license = 'gplv2+' inputs = ['logic'] outputs = ['dcf77'] channels = ( {'id': 'data', 'name': 'DATA', 'desc': 'DATA line'}, ) annotations = ( ('start-of-minute', 'Start of minute'), ('special-bits', 'Special bits (civil warnings, weather forecast)'), ('call-bit', 'Call bit'), ('summer-time', 'Summer time announcement'), ('cest', 'CEST bit'), ('cet', 'CET bit'), ('leap-second', 'Leap second bit'), ('start-of-time', 'Start of encoded time'), ('minute', 'Minute'), ('minute-parity', 'Minute parity bit'), ('hour', 'Hour'), ('hour-parity', 'Hour parity bit'), ('day', 'Day of month'), ('day-of-week', 'Day of week'), ('month', 'Month'), ('year', 'Year'), ('date-parity', 'Date parity bit'), ('raw-bits', 'Raw bits'), ('unknown-bits', 'Unknown bits'), ('warnings', 'Human-readable warnings'), ) annotation_rows = ( ('bits', 'Bits', (17, 18)), ('fields', 'Fields', tuple(range(0, 16 + 1))), ('warnings', 'Warnings', (19,)), ) def __init__(self): self.reset() def reset(self): self.samplerate = None self.state = 'WAIT FOR RISING EDGE' self.ss_bit = self.ss_bit_old = self.es_bit = self.ss_block = 0 self.datebits = [] self.bitcount = 0 # Counter for the DCF77 bits (0..58) self.dcf77_bitnumber_is_known = 0 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value def putx(self, data): # Annotation for a single DCF77 bit. self.put(self.ss_bit, self.es_bit, self.out_ann, data) def putb(self, data): # Annotation for a multi-bit DCF77 field. self.put(self.ss_block, self.samplenum, self.out_ann, data) # TODO: Which range to use? Only the 100ms/200ms or full second? def handle_dcf77_bit(self, bit): c = self.bitcount # Create one annotation for each DCF77 bit (containing the 0/1 value). # Use 'Unknown DCF77 bit x: val' if we're not sure yet which of the # 0..58 bits it is (because we haven't seen a 'new minute' marker yet). # Otherwise, use 'DCF77 bit x: val'. s = 'B' if self.dcf77_bitnumber_is_known else 'Unknown b' ann = 17 if self.dcf77_bitnumber_is_known else 18 self.putx([ann, ['%sit %d: %d' % (s, c, bit), '%d' % bit]]) # If we're not sure yet which of the 0..58 DCF77 bits we have, return. # We don't want to decode bogus data. if not self.dcf77_bitnumber_is_known: return # Collect bits 36-58, we'll need them for a parity check later. if c in range(36, 58 + 1): self.datebits.append(bit) # Output specific "decoded" annotations for the respective DCF77 bits. if c == 0: # Start of minute: DCF bit 0. if bit == 0: self.putx([0, ['Start of minute (always 0)', 'Start of minute', 'SoM']]) else: self.putx([19, ['Start of minute != 0', 'SoM != 0']]) elif c in range(1, 14 + 1): # Special bits (civil warnings, weather forecast): DCF77 bits 1-14. if c == 1: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 1)) if c == 14: s = '{:014b}'.format(self.tmp) self.putb([1, ['Special bits: %s' % s, 'SB: %s' % s]]) elif c == 15: s = '' if (bit == 1) else 'not ' self.putx([2, ['Call bit: %sset' % s, 'CB: %sset' % s]]) # TODO: Previously this bit indicated use of the backup antenna. elif c == 16: s = '' if (bit == 1) else 'not ' x = 'yes' if (bit == 1) else 'no' self.putx([3, ['Summer time announcement: %sactive' % s, 'Summer time: %sactive' % s, 'Summer time: %s' % x, 'ST: %s' % x]]) elif c == 17: s = '' if (bit == 1) else 'not ' x = 'yes' if (bit == 1) else 'no' self.putx([4, ['CEST: %sin effect' % s, 'CEST: %s' % x]]) elif c == 18: s = '' if (bit == 1) else 'not ' x = 'yes' if (bit == 1) else 'no' self.putx([5, ['CET: %sin effect' % s, 'CET: %s' % x]]) elif c == 19: s = '' if (bit == 1) else 'not ' x = 'yes' if (bit == 1) else 'no' self.putx([6, ['Leap second announcement: %sactive' % s, 'Leap second: %sactive' % s, 'Leap second: %s' % x, 'LS: %s' % x]]) elif c == 20: # Start of encoded time: DCF bit 20. if bit == 1: self.putx([7, ['Start of encoded time (always 1)', 'Start of encoded time', 'SoeT']]) else: self.putx([19, ['Start of encoded time != 1', 'SoeT != 1']]) elif c in range(21, 27 + 1): # Minutes (0-59): DCF77 bits 21-27 (BCD format). if c == 21: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 21)) if c == 27: m = bcd2int(self.tmp) self.putb([8, ['Minutes: %d' % m, 'Min: %d' % m]]) elif c == 28: # Even parity over minute bits (21-28): DCF77 bit 28. self.tmp |= (bit << (c - 21)) parity = bin(self.tmp).count('1') s = 'OK' if ((parity % 2) == 0) else 'INVALID!' self.putx([9, ['Minute parity: %s' % s, 'Min parity: %s' % s]]) elif c in range(29, 34 + 1): # Hours (0-23): DCF77 bits 29-34 (BCD format). if c == 29: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 29)) if c == 34: self.putb([10, ['Hours: %d' % bcd2int(self.tmp)]]) elif c == 35: # Even parity over hour bits (29-35): DCF77 bit 35. self.tmp |= (bit << (c - 29)) parity = bin(self.tmp).count('1') s = 'OK' if ((parity % 2) == 0) else 'INVALID!' self.putx([11, ['Hour parity: %s' % s]]) elif c in range(36, 41 + 1): # Day of month (1-31): DCF77 bits 36-41 (BCD format). if c == 36: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 36)) if c == 41: self.putb([12, ['Day: %d' % bcd2int(self.tmp)]]) elif c in range(42, 44 + 1): # Day of week (1-7): DCF77 bits 42-44 (BCD format). # A value of 1 means Monday, 7 means Sunday. if c == 42: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 42)) if c == 44: d = bcd2int(self.tmp) try: dn = calendar.day_name[d - 1] # day_name[0] == Monday self.putb([13, ['Day of week: %d (%s)' % (d, dn), 'DoW: %d (%s)' % (d, dn)]]) except IndexError: self.putb([19, ['Day of week: %d (%s)' % (d, 'invalid'), 'DoW: %d (%s)' % (d, 'inv')]]) elif c in range(45, 49 + 1): # Month (1-12): DCF77 bits 45-49 (BCD format). if c == 45: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 45)) if c == 49: m = bcd2int(self.tmp) try: mn = calendar.month_name[m] # month_name[1] == January self.putb([14, ['Month: %d (%s)' % (m, mn), 'Mon: %d (%s)' % (m, mn)]]) except IndexError: self.putb([19, ['Month: %d (%s)' % (m, 'invalid'), 'Mon: %d (%s)' % (m, 'inv')]]) elif c in range(50, 57 + 1): # Year (0-99): DCF77 bits 50-57 (BCD format). if c == 50: self.tmp = bit self.ss_block = self.ss_bit else: self.tmp |= (bit << (c - 50)) if c == 57: self.putb([15, ['Year: %d' % bcd2int(self.tmp)]]) elif c == 58: # Even parity over date bits (36-58): DCF77 bit 58. parity = self.datebits.count(1) s = 'OK' if ((parity % 2) == 0) else 'INVALID!' self.putx([16, ['Date parity: %s' % s, 'DP: %s' % s]]) self.datebits = [] else: self.putx([19, ['Invalid DCF77 bit: %d' % c, 'Invalid bit: %d' % c, 'Inv: %d' % c]]) def decode(self): if not self.samplerate: raise SamplerateError('Cannot decode without samplerate.') while True: if self.state == 'WAIT FOR RISING EDGE': # Wait until the next rising edge occurs. self.wait({0: 'r'}) # Save the sample number where the DCF77 bit begins. self.ss_bit = self.samplenum # Calculate the length (in ms) between two rising edges. len_edges = self.ss_bit - self.ss_bit_old len_edges_ms = int((len_edges / self.samplerate) * 1000) # The time between two rising edges is usually around 1000ms. # For DCF77 bit 59, there is no rising edge at all, i.e. the # time between DCF77 bit 59 and DCF77 bit 0 (of the next # minute) is around 2000ms. Thus, if we see an edge with a # 2000ms distance to the last one, this edge marks the # beginning of a new minute (and DCF77 bit 0 of that minute). if len_edges_ms in range(1600, 2400 + 1): self.bitcount = 0 self.ss_bit_old = self.ss_bit self.dcf77_bitnumber_is_known = 1 self.ss_bit_old = self.ss_bit self.state = 'GET BIT' elif self.state == 'GET BIT': # Wait until the next falling edge occurs. self.wait({0: 'f'}) # Save the sample number where the DCF77 bit ends. self.es_bit = self.samplenum # Calculate the length (in ms) of the current high period. len_high = self.samplenum - self.ss_bit len_high_ms = int((len_high / self.samplerate) * 1000) # If the high signal was 100ms long, that encodes a 0 bit. # If it was 200ms long, that encodes a 1 bit. if len_high_ms in range(40, 160 + 1): bit = 0 elif len_high_ms in range(161, 260 + 1): bit = 1 else: bit = -1 if bit in (0, 1): self.handle_dcf77_bit(bit) self.bitcount += 1 else: self.putx([19, ['Invalid bit timing', 'Inv timing', 'Inv']]) self.state = 'WAIT FOR RISING EDGE'
gpl-3.0
forio/julia-studio
share/julia-studio/qml/qmljsdebugger/qdeclarativeviewinspector.cpp
26003
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qdeclarativeviewinspector.h" #include "qdeclarativeviewinspector_p.h" #include "qdeclarativeinspectorservice.h" #include "editor/liveselectiontool.h" #include "editor/zoomtool.h" #include "editor/colorpickertool.h" #include "editor/livelayeritem.h" #include "editor/boundingrecthighlighter.h" #include "qt_private/qdeclarativedebughelper_p.h" #include <QDeclarativeItem> #include <QDeclarativeEngine> #include <QDeclarativeContext> #include <QDeclarativeExpression> #include <QWidget> #include <QVBoxLayout> #include <QMouseEvent> #include <QGraphicsObject> #include <QApplication> #include "qt_private/qdeclarativestate_p.h" namespace QmlJSDebugger { QDeclarativeViewInspectorPrivate::QDeclarativeViewInspectorPrivate(QDeclarativeViewInspector *q) : q(q), designModeBehavior(false), showAppOnTop(false), animationPaused(false), slowDownFactor(1.0f) { } QDeclarativeViewInspectorPrivate::~QDeclarativeViewInspectorPrivate() { } QDeclarativeViewInspector::QDeclarativeViewInspector(QDeclarativeView *view, QObject *parent) : QObject(parent), data(new QDeclarativeViewInspectorPrivate(this)) { data->view = view; data->manipulatorLayer = new LiveLayerItem(view->scene()); data->selectionTool = new LiveSelectionTool(this); data->zoomTool = new ZoomTool(this); data->colorPickerTool = new ColorPickerTool(this); data->boundingRectHighlighter = new BoundingRectHighlighter(this); data->currentTool = data->selectionTool; // to capture ChildRemoved event when viewport changes data->view->installEventFilter(this); data->setViewport(data->view->viewport()); data->debugService = QDeclarativeInspectorService::instance(); connect(data->debugService, SIGNAL(designModeBehaviorChanged(bool)), SLOT(setDesignModeBehavior(bool))); connect(data->debugService, SIGNAL(showAppOnTopChanged(bool)), SLOT(setShowAppOnTop(bool))); connect(data->debugService, SIGNAL(reloadRequested()), data.data(), SLOT(_q_reloadView())); connect(data->debugService, SIGNAL(currentObjectsChanged(QList<QObject*>)), data.data(), SLOT(_q_onCurrentObjectsChanged(QList<QObject*>))); connect(data->debugService, SIGNAL(animationSpeedChangeRequested(qreal)), SLOT(animationSpeedChangeRequested(qreal))); connect(data->debugService, SIGNAL(executionPauseChangeRequested(bool)), SLOT(animationPausedChangeRequested(bool))); connect(data->debugService, SIGNAL(colorPickerToolRequested()), data.data(), SLOT(_q_changeToColorPickerTool())); connect(data->debugService, SIGNAL(selectMarqueeToolRequested()), data.data(), SLOT(_q_changeToMarqueeSelectTool())); connect(data->debugService, SIGNAL(selectToolRequested()), data.data(), SLOT(_q_changeToSingleSelectTool())); connect(data->debugService, SIGNAL(zoomToolRequested()), data.data(), SLOT(_q_changeToZoomTool())); connect(data->debugService, SIGNAL(objectCreationRequested(QString,QObject*,QStringList,QString,int)), data.data(), SLOT(_q_createQmlObject(QString,QObject*,QStringList,QString,int))); connect(data->debugService, SIGNAL(objectDeletionRequested(QObject*)), data.data(), SLOT(_q_deleteQmlObject(QObject*))); connect(data->debugService, SIGNAL(objectReparentRequested(QObject*,QObject*)), data.data(), SLOT(_q_reparentQmlObject(QObject*,QObject*))); connect(data->debugService, SIGNAL(clearComponentCacheRequested()), data.data(), SLOT(_q_clearComponentCache())); connect(data->view, SIGNAL(statusChanged(QDeclarativeView::Status)), data.data(), SLOT(_q_onStatusChanged(QDeclarativeView::Status))); connect(data->colorPickerTool, SIGNAL(selectedColorChanged(QColor)), SIGNAL(selectedColorChanged(QColor))); connect(data->colorPickerTool, SIGNAL(selectedColorChanged(QColor)), data->debugService, SLOT(selectedColorChanged(QColor))); data->_q_changeToSingleSelectTool(); } QDeclarativeViewInspector::~QDeclarativeViewInspector() { } void QDeclarativeViewInspectorPrivate::_q_reloadView() { clearHighlight(); emit q->reloadRequested(); } void QDeclarativeViewInspectorPrivate::setViewport(QWidget *widget) { if (viewport.data() == widget) return; if (viewport) viewport.data()->removeEventFilter(q); viewport = widget; if (viewport) { // make sure we get mouse move events viewport.data()->setMouseTracking(true); viewport.data()->installEventFilter(q); } } void QDeclarativeViewInspectorPrivate::clearEditorItems() { clearHighlight(); setSelectedItems(QList<QGraphicsItem*>()); } bool QDeclarativeViewInspector::eventFilter(QObject *obj, QEvent *event) { if (obj == data->view) { // Event from view if (event->type() == QEvent::ChildRemoved) { // Might mean that viewport has changed if (data->view->viewport() != data->viewport.data()) data->setViewport(data->view->viewport()); } return QObject::eventFilter(obj, event); } // Event from viewport switch (event->type()) { case QEvent::Leave: { if (leaveEvent(event)) return true; break; } case QEvent::MouseButtonPress: { if (mousePressEvent(static_cast<QMouseEvent*>(event))) return true; break; } case QEvent::MouseMove: { if (mouseMoveEvent(static_cast<QMouseEvent*>(event))) return true; break; } case QEvent::MouseButtonRelease: { if (mouseReleaseEvent(static_cast<QMouseEvent*>(event))) return true; break; } case QEvent::KeyPress: { if (keyPressEvent(static_cast<QKeyEvent*>(event))) return true; break; } case QEvent::KeyRelease: { if (keyReleaseEvent(static_cast<QKeyEvent*>(event))) return true; break; } case QEvent::MouseButtonDblClick: { if (mouseDoubleClickEvent(static_cast<QMouseEvent*>(event))) return true; break; } case QEvent::Wheel: { if (wheelEvent(static_cast<QWheelEvent*>(event))) return true; break; } default: { break; } } //switch // standard event processing return QObject::eventFilter(obj, event); } bool QDeclarativeViewInspector::leaveEvent(QEvent * /*event*/) { if (!data->designModeBehavior) return false; data->clearHighlight(); return true; } bool QDeclarativeViewInspector::mousePressEvent(QMouseEvent *event) { if (!data->designModeBehavior) return false; data->cursorPos = event->pos(); data->currentTool->mousePressEvent(event); return true; } bool QDeclarativeViewInspector::mouseMoveEvent(QMouseEvent *event) { if (!data->designModeBehavior) { data->clearEditorItems(); return false; } data->cursorPos = event->pos(); QList<QGraphicsItem*> selItems = data->selectableItems(event->pos()); if (!selItems.isEmpty()) { declarativeView()->setToolTip(AbstractLiveEditTool::titleForItem(selItems.first())); } else { declarativeView()->setToolTip(QString()); } if (event->buttons()) { data->currentTool->mouseMoveEvent(event); } else { data->currentTool->hoverMoveEvent(event); } return true; } bool QDeclarativeViewInspector::mouseReleaseEvent(QMouseEvent *event) { if (!data->designModeBehavior) return false; data->cursorPos = event->pos(); data->currentTool->mouseReleaseEvent(event); return true; } bool QDeclarativeViewInspector::keyPressEvent(QKeyEvent *event) { if (!data->designModeBehavior) return false; data->currentTool->keyPressEvent(event); return true; } bool QDeclarativeViewInspector::keyReleaseEvent(QKeyEvent *event) { if (!data->designModeBehavior) return false; switch(event->key()) { case Qt::Key_V: data->_q_changeToSingleSelectTool(); break; // disabled because multiselection does not do anything useful without design mode // case Qt::Key_M: // data->_q_changeToMarqueeSelectTool(); // break; case Qt::Key_I: data->_q_changeToColorPickerTool(); break; case Qt::Key_Z: data->_q_changeToZoomTool(); break; case Qt::Key_Space: setAnimationPaused(!data->animationPaused); break; default: break; } data->currentTool->keyReleaseEvent(event); return true; } bool insertObjectInListProperty(QDeclarativeListReference &fromList, int position, QObject *object) { QList<QObject *> tmpList; int i; if (!(fromList.canCount() && fromList.canAt() && fromList.canAppend() && fromList.canClear())) return false; if (position == fromList.count()) { fromList.append(object); return true; } for (i=0; i<fromList.count(); ++i) tmpList << fromList.at(i); fromList.clear(); for (i=0; i<position; ++i) fromList.append(tmpList.at(i)); fromList.append(object); for (; i<tmpList.count(); ++i) fromList.append(tmpList.at(i)); return true; } bool removeObjectFromListProperty(QDeclarativeListReference &fromList, QObject *object) { QList<QObject *> tmpList; int i; if (!(fromList.canCount() && fromList.canAt() && fromList.canAppend() && fromList.canClear())) return false; for (i=0; i<fromList.count(); ++i) if (object != fromList.at(i)) tmpList << fromList.at(i); fromList.clear(); foreach (QObject *item, tmpList) fromList.append(item); return true; } void QDeclarativeViewInspectorPrivate::_q_createQmlObject(const QString &qml, QObject *parent, const QStringList &importList, const QString &filename, int order) { if (!parent) return; QString imports; foreach (const QString &s, importList) { imports += s; imports += QLatin1Char('\n'); } QDeclarativeContext *parentContext = view->engine()->contextForObject(parent); QDeclarativeComponent component(view->engine(), q); QByteArray constructedQml = QString(imports + qml).toLatin1(); component.setData(constructedQml, filename); QObject *newObject = component.create(parentContext); if (newObject) { newObject->setParent(parent); do { // add child item QDeclarativeItem *parentItem = qobject_cast<QDeclarativeItem*>(parent); QDeclarativeItem *newItem = qobject_cast<QDeclarativeItem*>(newObject); if (parentItem && newItem) { newItem->setParentItem(parentItem); break; } // add property change QDeclarativeState *parentState = qobject_cast<QDeclarativeState*>(parent); QDeclarativeStateOperation *newPropertyChanges = qobject_cast<QDeclarativeStateOperation *>(newObject); if (parentState && newPropertyChanges) { (*parentState) << newPropertyChanges; break; } // add states QDeclarativeState *newState = qobject_cast<QDeclarativeState*>(newObject); if (parentItem && newState) { QDeclarativeListReference statesList(parentItem, "states"); statesList.append(newObject); break; } // add animation to transition if (parent->inherits("QDeclarativeTransition") && newObject->inherits("QDeclarativeAbstractAnimation")) { QDeclarativeListReference animationsList(parent, "animations"); animationsList.append(newObject); break; } // add animation to animation if (parent->inherits("QDeclarativeAnimationGroup") && newObject->inherits("QDeclarativeAbstractAnimation")) { QDeclarativeListReference animationsList(parent, "animations"); if (order==-1) { animationsList.append(newObject); } else { if (!insertObjectInListProperty(animationsList, order, newObject)) { animationsList.append(newObject); } } break; } // add transition if (parentItem && newObject->inherits("QDeclarativeTransition")) { QDeclarativeListReference transitionsList(parentItem,"transitions"); if (transitionsList.count() == 1 && transitionsList.at(0) == 0) { transitionsList.clear(); } transitionsList.append(newObject); break; } } while (false); } } void QDeclarativeViewInspectorPrivate::_q_reparentQmlObject(QObject *object, QObject *newParent) { if (!newParent) return; object->setParent(newParent); QDeclarativeItem *newParentItem = qobject_cast<QDeclarativeItem*>(newParent); QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(object); if (newParentItem && item) item->setParentItem(newParentItem); } void QDeclarativeViewInspectorPrivate::_q_deleteQmlObject(QObject *object) { // special cases for transitions/animations if (object->inherits("QDeclarativeAbstractAnimation")) { if (object->parent()) { QDeclarativeListReference animationsList(object->parent(), "animations"); if (removeObjectFromListProperty(animationsList, object)) object->deleteLater(); return; } } if (object->inherits("QDeclarativeTransition")) { QDeclarativeListReference transitionsList(object->parent(), "transitions"); if (removeObjectFromListProperty(transitionsList, object)) object->deleteLater(); return; } } void QDeclarativeViewInspectorPrivate::_q_clearComponentCache() { view->engine()->clearComponentCache(); } void QDeclarativeViewInspectorPrivate::_q_removeFromSelection(QObject *obj) { QList<QGraphicsItem*> items = selectedItems(); if (QGraphicsItem *item = qobject_cast<QGraphicsObject*>(obj)) items.removeOne(item); setSelectedItems(items); } bool QDeclarativeViewInspector::mouseDoubleClickEvent(QMouseEvent * /*event*/) { if (!data->designModeBehavior) return false; return true; } bool QDeclarativeViewInspector::wheelEvent(QWheelEvent *event) { if (!data->designModeBehavior) return false; data->currentTool->wheelEvent(event); return true; } void QDeclarativeViewInspector::setDesignModeBehavior(bool value) { emit designModeBehaviorChanged(value); data->debugService->setDesignModeBehavior(value); data->designModeBehavior = value; if (!data->designModeBehavior) data->clearEditorItems(); } bool QDeclarativeViewInspector::designModeBehavior() { return data->designModeBehavior; } bool QDeclarativeViewInspector::showAppOnTop() const { return data->showAppOnTop; } void QDeclarativeViewInspector::setShowAppOnTop(bool appOnTop) { if (data->view) { QWidget *window = data->view->window(); Qt::WindowFlags flags = window->windowFlags(); if (appOnTop) flags |= Qt::WindowStaysOnTopHint; else flags &= ~Qt::WindowStaysOnTopHint; window->setWindowFlags(flags); window->show(); } data->showAppOnTop = appOnTop; data->debugService->setShowAppOnTop(appOnTop); emit showAppOnTopChanged(appOnTop); } void QDeclarativeViewInspectorPrivate::changeTool(Constants::DesignTool tool, Constants::ToolFlags /*flags*/) { switch(tool) { case Constants::SelectionToolMode: _q_changeToSingleSelectTool(); break; case Constants::NoTool: default: currentTool = 0; break; } } void QDeclarativeViewInspectorPrivate::setSelectedItemsForTools(QList<QGraphicsItem *> items) { foreach (const QWeakPointer<QGraphicsObject> &obj, currentSelection) { if (QGraphicsItem *item = obj.data()) { if (!items.contains(item)) { QObject::disconnect(obj.data(), SIGNAL(destroyed(QObject*)), this, SLOT(_q_removeFromSelection(QObject*))); currentSelection.removeOne(obj); } } } foreach (QGraphicsItem *item, items) { if (QGraphicsObject *obj = item->toGraphicsObject()) { if (!currentSelection.contains(obj)) { QObject::connect(obj, SIGNAL(destroyed(QObject*)), this, SLOT(_q_removeFromSelection(QObject*))); currentSelection.append(obj); } } } currentTool->updateSelectedItems(); } void QDeclarativeViewInspectorPrivate::setSelectedItems(QList<QGraphicsItem *> items) { QList<QWeakPointer<QGraphicsObject> > oldList = currentSelection; setSelectedItemsForTools(items); if (oldList != currentSelection) { QList<QObject*> objectList; foreach (const QWeakPointer<QGraphicsObject> &graphicsObject, currentSelection) { if (graphicsObject) objectList << graphicsObject.data(); } debugService->setCurrentObjects(objectList); } } QList<QGraphicsItem *> QDeclarativeViewInspectorPrivate::selectedItems() { QList<QGraphicsItem *> selection; foreach (const QWeakPointer<QGraphicsObject> &selectedObject, currentSelection) { if (selectedObject.data()) selection << selectedObject.data(); } return selection; } void QDeclarativeViewInspector::setSelectedItems(QList<QGraphicsItem *> items) { data->setSelectedItems(items); } QList<QGraphicsItem *> QDeclarativeViewInspector::selectedItems() { return data->selectedItems(); } QDeclarativeView *QDeclarativeViewInspector::declarativeView() { return data->view; } void QDeclarativeViewInspectorPrivate::clearHighlight() { boundingRectHighlighter->clear(); } void QDeclarativeViewInspectorPrivate::highlight(const QList<QGraphicsObject *> &items) { if (items.isEmpty()) return; QList<QGraphicsObject*> objectList; foreach (QGraphicsItem *item, items) { QGraphicsItem *child = item; if (child) { QGraphicsObject *childObject = child->toGraphicsObject(); if (childObject) objectList << childObject; } } boundingRectHighlighter->highlight(objectList); } QList<QGraphicsItem*> QDeclarativeViewInspectorPrivate::selectableItems( const QPointF &scenePos) const { QList<QGraphicsItem*> itemlist = view->scene()->items(scenePos); return filterForSelection(itemlist); } QList<QGraphicsItem*> QDeclarativeViewInspectorPrivate::selectableItems(const QPoint &pos) const { QList<QGraphicsItem*> itemlist = view->items(pos); return filterForSelection(itemlist); } QList<QGraphicsItem*> QDeclarativeViewInspectorPrivate::selectableItems( const QRectF &sceneRect, Qt::ItemSelectionMode selectionMode) const { QList<QGraphicsItem*> itemlist = view->scene()->items(sceneRect, selectionMode); return filterForSelection(itemlist); } void QDeclarativeViewInspectorPrivate::_q_changeToSingleSelectTool() { currentToolMode = Constants::SelectionToolMode; selectionTool->setRubberbandSelectionMode(false); changeToSelectTool(); emit q->selectToolActivated(); debugService->setCurrentTool(Constants::SelectionToolMode); } void QDeclarativeViewInspectorPrivate::changeToSelectTool() { if (currentTool == selectionTool) return; currentTool->clear(); currentTool = selectionTool; currentTool->clear(); currentTool->updateSelectedItems(); } void QDeclarativeViewInspectorPrivate::_q_changeToMarqueeSelectTool() { changeToSelectTool(); currentToolMode = Constants::MarqueeSelectionToolMode; selectionTool->setRubberbandSelectionMode(true); emit q->marqueeSelectToolActivated(); debugService->setCurrentTool(Constants::MarqueeSelectionToolMode); } void QDeclarativeViewInspectorPrivate::_q_changeToZoomTool() { currentToolMode = Constants::ZoomMode; currentTool->clear(); currentTool = zoomTool; currentTool->clear(); emit q->zoomToolActivated(); debugService->setCurrentTool(Constants::ZoomMode); } void QDeclarativeViewInspectorPrivate::_q_changeToColorPickerTool() { if (currentTool == colorPickerTool) return; currentToolMode = Constants::ColorPickerMode; currentTool->clear(); currentTool = colorPickerTool; currentTool->clear(); emit q->colorPickerActivated(); debugService->setCurrentTool(Constants::ColorPickerMode); } void QDeclarativeViewInspector::setAnimationSpeed(qreal slowDownFactor) { Q_ASSERT(slowDownFactor > 0); if (data->slowDownFactor == slowDownFactor) return; animationSpeedChangeRequested(slowDownFactor); data->debugService->setAnimationSpeed(slowDownFactor); } void QDeclarativeViewInspector::setAnimationPaused(bool paused) { if (data->animationPaused == paused) return; animationPausedChangeRequested(paused); data->debugService->setAnimationPaused(paused); } void QDeclarativeViewInspector::animationSpeedChangeRequested(qreal factor) { if (data->slowDownFactor != factor) { data->slowDownFactor = factor; emit animationSpeedChanged(factor); } const float effectiveFactor = data->animationPaused ? 0 : factor; QDeclarativeDebugHelper::setAnimationSlowDownFactor(effectiveFactor); } void QDeclarativeViewInspector::animationPausedChangeRequested(bool paused) { if (data->animationPaused != paused) { data->animationPaused = paused; emit animationPausedChanged(paused); } const float effectiveFactor = paused ? 0 : data->slowDownFactor; QDeclarativeDebugHelper::setAnimationSlowDownFactor(effectiveFactor); } void QDeclarativeViewInspectorPrivate::_q_applyChangesFromClient() { } QList<QGraphicsItem*> QDeclarativeViewInspectorPrivate::filterForSelection( QList<QGraphicsItem*> &itemlist) const { foreach (QGraphicsItem *item, itemlist) { if (isEditorItem(item)) itemlist.removeOne(item); } return itemlist; } bool QDeclarativeViewInspectorPrivate::isEditorItem(QGraphicsItem *item) const { return (item->type() == Constants::EditorItemType || item->type() == Constants::ResizeHandleItemType || item->data(Constants::EditorItemDataKey).toBool()); } void QDeclarativeViewInspectorPrivate::_q_onStatusChanged(QDeclarativeView::Status status) { if (status == QDeclarativeView::Ready) debugService->reloaded(); } void QDeclarativeViewInspectorPrivate::_q_onCurrentObjectsChanged(QList<QObject*> objects) { QList<QGraphicsItem*> items; QList<QGraphicsObject*> gfxObjects; foreach (QObject *obj, objects) { if (QDeclarativeItem *declarativeItem = qobject_cast<QDeclarativeItem*>(obj)) { items << declarativeItem; gfxObjects << declarativeItem; } } if (designModeBehavior) { setSelectedItemsForTools(items); clearHighlight(); highlight(gfxObjects); } } QString QDeclarativeViewInspector::idStringForObject(QObject *obj) { return QDeclarativeInspectorService::instance()->idStringForObject(obj); } // adjusts bounding boxes on edges of screen to be visible QRectF QDeclarativeViewInspector::adjustToScreenBoundaries(const QRectF &boundingRectInSceneSpace) { int marginFromEdge = 1; QRectF boundingRect(boundingRectInSceneSpace); if (qAbs(boundingRect.left()) - 1 < 2) boundingRect.setLeft(marginFromEdge); QRect rect = data->view->rect(); if (boundingRect.right() >= rect.right()) boundingRect.setRight(rect.right() - marginFromEdge); if (qAbs(boundingRect.top()) - 1 < 2) boundingRect.setTop(marginFromEdge); if (boundingRect.bottom() >= rect.bottom()) boundingRect.setBottom(rect.bottom() - marginFromEdge); return boundingRect; } } // namespace QmlJSDebugger
gpl-3.0
Maxzilla60/AC-Lister
.eslintrc.js
4875
/* 👋 Hi! This file was autogenerated by tslint-to-eslint-config. https://github.com/typescript-eslint/tslint-to-eslint-config It represents the closest reasonable ESLint configuration to this project's original TSLint configuration. We recommend eventually switching this configuration to extend from the recommended rulesets in typescript-eslint. https://github.com/typescript-eslint/tslint-to-eslint-config/blob/master/docs/FAQs.md Happy linting! 💖 */ module.exports = { "env": { "browser": true, "es6": true, "node": true }, "extends": [ "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking" ], "parser": "@typescript-eslint/parser", "parserOptions": { "project": "tsconfig.json", "sourceType": "module" }, "plugins": [ "eslint-plugin-import", "eslint-plugin-jsdoc", "eslint-plugin-prefer-arrow", "@typescript-eslint", ], "rules": { "@typescript-eslint/adjacent-overload-signatures": "error", "@typescript-eslint/array-type": "off", "@typescript-eslint/ban-types": [ "error", { "types": { "Object": { "message": "Avoid using the `Object` type. Did you mean `object`?" }, "Function": { "message": "Avoid using the `Function` type. Prefer a specific function type, like `() => void`." }, "Boolean": { "message": "Avoid using the `Boolean` type. Did you mean `boolean`?" }, "Number": { "message": "Avoid using the `Number` type. Did you mean `number`?" }, "String": { "message": "Avoid using the `String` type. Did you mean `string`?" }, "Symbol": { "message": "Avoid using the `Symbol` type. Did you mean `symbol`?" } } } ], "@typescript-eslint/consistent-type-assertions": "error", "@typescript-eslint/dot-notation": "error", "@typescript-eslint/explicit-member-accessibility": [ "error", { "accessibility": "explicit" } ], "@typescript-eslint/indent": [ "error", "tab" ], "@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-empty-interface": "error", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-inferrable-types": [ "error", { "ignoreParameters": true } ], "@typescript-eslint/no-misused-new": "error", "@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-non-null-assertion": "error", "@typescript-eslint/no-parameter-properties": "off", "@typescript-eslint/no-shadow": [ "error", { "hoist": "all" } ], "@typescript-eslint/no-unused-expressions": "error", "@typescript-eslint/no-use-before-define": "error", "@typescript-eslint/no-var-requires": "off", "@typescript-eslint/prefer-for-of": "error", "@typescript-eslint/prefer-function-type": "error", "@typescript-eslint/prefer-namespace-keyword": "error", "@typescript-eslint/quotes": [ "error", "single" ], "@typescript-eslint/triple-slash-reference": [ "error", { "path": "always", "types": "prefer-import", "lib": "always" } ], "@typescript-eslint/unified-signatures": "error", "arrow-parens": [ "off", "always" ], "comma-dangle": "off", "complexity": "off", "constructor-super": "error", "curly": "error", "eol-last": "error", "eqeqeq": [ "error", "smart" ], "guard-for-in": "error", "id-blacklist": "error", "id-match": "error", "import/no-deprecated": "warn", "import/order": "off", "jsdoc/check-alignment": "error", "jsdoc/check-indentation": "error", "jsdoc/newline-after-description": "error", "jsdoc/no-types": "error", "max-classes-per-file": "off", "new-parens": "error", "no-bitwise": "error", "no-caller": "error", "no-cond-assign": "error", "no-console": [ "error", { "allow": [ "log", "warn", "dir", "timeLog", "assert", "clear", "count", "countReset", "group", "groupEnd", "table", "dirxml", "error", "groupCollapsed", "Console", "profile", "profileEnd", "timeStamp", "context" ] } ], "no-debugger": "error", "no-empty": "off", "no-eval": "error", "no-fallthrough": "error", "no-invalid-this": "off", "no-multiple-empty-lines": "off", "no-new-wrappers": "error", "no-restricted-imports": [ "error", "rxjs/Rx" ], "no-throw-literal": "error", "no-trailing-spaces": "error", "no-undef-init": "error", "no-unsafe-finally": "error", "no-unused-labels": "error", "no-var": "error", "object-shorthand": "error", "one-var": [ "error", "never" ], "prefer-const": "error", "quote-props": [ "error", "as-needed" ], "radix": "error", "spaced-comment": [ "error", "always", { "markers": [ "/" ] } ], "use-isnan": "error", "valid-typeof": "off", } };
gpl-3.0
Ozi94/opencart
upload/admin/language/ro-ro/extension/payment/psigate.php
1026
<?php // Heading $_['heading_title'] = 'PSIGate'; // Text $_['text_payment'] = 'Plată'; $_['text_success'] = 'Succes: Ai modificat detaliile contului PSIGate!'; // Entry $_['entry_merchant'] = 'Merchant ID-ul Comerciantului:'; $_['entry_password'] = 'Fraza de Trecere:'; $_['entry_gateway'] = 'Gateway URL:'; $_['entry_test'] = 'Modul Test:'; $_['entry_total'] = 'Total:<br /><span class="help">Totalul de plată trebuie să fie atins înainte ca această metodă de plată să devină activă.</span>'; $_['entry_order_status'] = 'Statusul Comenzii:'; $_['entry_geo_zone'] = 'Zona Geografică:'; $_['entry_status'] = 'Status:'; $_['entry_sort_order'] = 'Selectează Ordinea:'; // Error $_['error_permission'] = 'Atenție: Nu aveți permisiunea să modificați plata prin PSIGate!'; $_['error_merchant'] = 'Comerciantul este necesar!'; $_['error_password'] = 'Fraza de trecere este necesară!'; $_['error_gateway'] = 'Gateway URL este necesar!'; ?>
gpl-3.0
manojdjoshi/dnSpy
dnSpy/dnSpy.Contracts.Debugger/Evaluation/PredefinedFormatSpecifiers.cs
10096
/* Copyright (C) 2014-2019 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System.Collections.ObjectModel; using System.Diagnostics; namespace dnSpy.Contracts.Debugger.Evaluation { /// <summary> /// Format specifiers used by variables windows /// /// https://docs.microsoft.com/en-us/visualstudio/debugger/format-specifiers-in-csharp /// </summary> public static class PredefinedFormatSpecifiers { /// <summary> /// Use decimal /// </summary> public const string Decimal = "d"; /// <summary> /// Use hexadecimal /// </summary> public const string Hexadecimal = "h"; /// <summary> /// No quotes, just show the raw string /// </summary> public const string NoQuotes = "nq"; /// <summary> /// Raw view only /// </summary> public const string RawView = "raw"; /// <summary> /// Results view only /// </summary> public const string ResultsView = "results"; /// <summary> /// Dynamic view only /// </summary> public const string DynamicView = "dynamic"; /// <summary> /// Show all members, even non-public ones /// </summary> public const string ShowAllMembers = "hidden"; /// <summary> /// Emulate the code without real func-eval /// </summary> public const string Emulator = "emulator"; /// <summary> /// No side effects, it implies <see cref="Emulator"/> /// </summary> public const string NoSideEffects = "nse"; /// <summary> /// Allow func-eval even if <see cref="NoSideEffects"/> is used and expression causes side effects /// (ac = always calculate) /// </summary> public const string AllowFuncEval = "ac"; // The following are dnSpy extensions /// <summary> /// Digit separators /// </summary> public const string DigitSeparators = "ds"; /// <summary> /// No digit seaparators /// </summary> public const string NoDigitSeparators = "nds"; /// <summary> /// Use the same expression that's shown in the edit text box /// </summary> public const string EditExpression = "edit"; /// <summary> /// Use ToString() if available to format the value /// </summary> public new const string ToString = "ts"; /// <summary> /// Don't use ToString() to format the value /// </summary> public const string NoToString = "nts"; /// <summary> /// Use <see cref="DebuggerDisplayAttribute"/> if available /// </summary> public const string DebuggerDisplay = "dda"; /// <summary> /// Don't use <see cref="DebuggerDisplayAttribute"/> /// </summary> public const string NoDebuggerDisplay = "ndda"; /// <summary> /// Show the full string value even if it's a very long string /// </summary> public const string FullString = "fs"; /// <summary> /// Don't show the full string value if it's a very long string /// </summary> public const string NoFullString = "nfs"; /// <summary> /// Show namespaces /// </summary> public const string Namespaces = "ns"; /// <summary> /// Don't show namespaces /// </summary> public const string NoNamespaces = "nns"; /// <summary> /// Show intrinsic type keywords (eg. int instead of Int32) /// </summary> public const string Intrinsics = "intrinsics"; /// <summary> /// Don't show intrinsic type keywords (eg. int instead of Int32) /// </summary> public const string NoIntrinsics = "nointrinsics"; /// <summary> /// Show tokens /// </summary> public const string Tokens = "tokens"; /// <summary> /// Don't show tokens /// </summary> public const string NoTokens = "notokens"; /// <summary> /// Show compiler generated members /// </summary> public const string ShowCompilerGeneratedMembers = "cgm"; /// <summary> /// Don't show compiler generated members /// </summary> public const string NoShowCompilerGeneratedMembers = "ncgm"; /// <summary> /// Respect attributes that can hide a member, eg. <see cref="DebuggerBrowsableAttribute"/> and <see cref="DebuggerBrowsableState.Never"/> /// </summary> public const string RespectHideMemberAttributes = "hma"; /// <summary> /// Don't respect attributes that can hide a member, eg. <see cref="DebuggerBrowsableAttribute"/> and <see cref="DebuggerBrowsableState.Never"/> /// </summary> public const string NoRespectHideMemberAttributes = "nhma"; /// <summary> /// Gets value formatter options /// </summary> /// <param name="formatSpecifiers">Format specifiers or null</param> /// <param name="options">Default options</param> /// <returns></returns> public static DbgValueFormatterOptions GetValueFormatterOptions(ReadOnlyCollection<string>? formatSpecifiers, DbgValueFormatterOptions options) { if (!(formatSpecifiers is null)) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case Decimal: options |= DbgValueFormatterOptions.Decimal; break; case Hexadecimal: options &= ~DbgValueFormatterOptions.Decimal; break; case NoQuotes: options |= DbgValueFormatterOptions.NoStringQuotes; break; case DigitSeparators: options |= DbgValueFormatterOptions.DigitSeparators; break; case NoDigitSeparators: options &= ~DbgValueFormatterOptions.DigitSeparators; break; case EditExpression: options |= DbgValueFormatterOptions.Edit; break; case ToString: options |= DbgValueFormatterOptions.ToString; break; case NoToString: options &= ~DbgValueFormatterOptions.ToString; break; case DebuggerDisplay: options &= ~DbgValueFormatterOptions.NoDebuggerDisplay; break; case NoDebuggerDisplay: options |= DbgValueFormatterOptions.NoDebuggerDisplay; break; case FullString: options |= DbgValueFormatterOptions.FullString; break; case NoFullString: options &= ~DbgValueFormatterOptions.FullString; break; case Namespaces: options |= DbgValueFormatterOptions.Namespaces; break; case NoNamespaces: options &= ~DbgValueFormatterOptions.Namespaces; break; case Intrinsics: options |= DbgValueFormatterOptions.IntrinsicTypeKeywords; break; case NoIntrinsics: options &= ~DbgValueFormatterOptions.IntrinsicTypeKeywords; break; case Tokens: options |= DbgValueFormatterOptions.Tokens; break; case NoTokens: options &= ~DbgValueFormatterOptions.Tokens; break; } } } return options; } /// <summary> /// Gets value formatter type options /// </summary> /// <param name="formatSpecifiers">Format specifiers or null</param> /// <param name="options">Default options</param> /// <returns></returns> public static DbgValueFormatterTypeOptions GetValueFormatterTypeOptions(ReadOnlyCollection<string>? formatSpecifiers, DbgValueFormatterTypeOptions options) { if (!(formatSpecifiers is null)) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case Decimal: options |= DbgValueFormatterTypeOptions.Decimal; break; case Hexadecimal: options &= ~DbgValueFormatterTypeOptions.Decimal; break; case DigitSeparators: options |= DbgValueFormatterTypeOptions.DigitSeparators; break; case NoDigitSeparators: options &= ~DbgValueFormatterTypeOptions.DigitSeparators; break; case Namespaces: options |= DbgValueFormatterTypeOptions.Namespaces; break; case NoNamespaces: options &= ~DbgValueFormatterTypeOptions.Namespaces; break; case Intrinsics: options |= DbgValueFormatterTypeOptions.IntrinsicTypeKeywords; break; case NoIntrinsics: options &= ~DbgValueFormatterTypeOptions.IntrinsicTypeKeywords; break; case Tokens: options |= DbgValueFormatterTypeOptions.Tokens; break; case NoTokens: options &= ~DbgValueFormatterTypeOptions.Tokens; break; } } } return options; } /// <summary> /// Gets value node evaluation options /// </summary> /// <param name="formatSpecifiers">Format specifiers or null</param> /// <param name="options">Default options</param> /// <returns></returns> public static DbgValueNodeEvaluationOptions GetValueNodeEvaluationOptions(ReadOnlyCollection<string>? formatSpecifiers, DbgValueNodeEvaluationOptions options) { if (!(formatSpecifiers is null)) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case DynamicView: options |= DbgValueNodeEvaluationOptions.DynamicView; break; case ResultsView: options |= DbgValueNodeEvaluationOptions.ResultsView; break; case RawView: options |= DbgValueNodeEvaluationOptions.RawView; break; case ShowAllMembers: options &= ~DbgValueNodeEvaluationOptions.PublicMembers; break; case ShowCompilerGeneratedMembers: options &= ~DbgValueNodeEvaluationOptions.HideCompilerGeneratedMembers; break; case NoShowCompilerGeneratedMembers: options |= DbgValueNodeEvaluationOptions.HideCompilerGeneratedMembers; break; case RespectHideMemberAttributes: options |= DbgValueNodeEvaluationOptions.RespectHideMemberAttributes; break; case NoRespectHideMemberAttributes: options &= ~DbgValueNodeEvaluationOptions.RespectHideMemberAttributes; break; } } } return options; } } }
gpl-3.0
FHICT-Software/P3P4
PTS/AirHockeyJeroen/AirHockey_Server_Jeroen/src/threads/WelcomeThread.java
2154
//<editor-fold defaultstate="collapsed" desc="Jibberish"> package threads; import interfaces.IThread; import java.net.Socket; //</editor-fold> /** * In this class you can find all properties and operations for WelcomeThread. //CHECK * * @organization: Moridrin * @author J.B.A.J. Berkvens * @date 2014/05/26 */ public class WelcomeThread extends ClientConnector implements IThread { //<editor-fold defaultstate="collapsed" desc="Declarations"> private static int nextID = 1000; //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Constructor()"> /** * This is the constructor for OpenThread. * * @param clientSocket is the open socket to the client. */ public WelcomeThread(Socket clientSocket) { super(clientSocket, 111); } //</editor-fold> //<editor-fold desc="run()"> @Override public void run() { boolean loginCorrect = false; String message = null; int loginTry = 0; message = "Welcome to the MP-AirHockey Server."; sendObject(message); message = readMessage(); if (message.equals("Setup Login")) { message = "You're ID is:" + nextID; sendObject(message); new LoginThread(clientSocket, nextID).start(); nextID++; System.out.println("Listening to: " + clientSocket.getRemoteSocketAddress().toString().split(":")[0]); } else if (message.contains("Setup Listener:")) { ClientListenerThread listener = new ClientListenerThread(clientSocket, Integer.parseInt(message.split(":")[1])); listener.start(); airhockey_server_jeroen.AirHockey_Server_Jeroen.addListener(listener); System.out.println("Open Connection to: " + clientSocket.getRemoteSocketAddress().toString().split(":")[0]); } else if (message.contains("Setup Chat:")) { new ChatThread(clientSocket, Integer.parseInt(message.split(":")[1])).start(); } else if (message.contains("Setup IngameConnection")) { new InGameThread(clientSocket, id).start(); } } //</editor-fold> }
gpl-3.0
PM2M2016-A-B/FM-tuner
client-example/src/service-client.js
3528
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import eventToPromise from 'event-to-promise' import { Socket } from 'net' const EVENT_VOLUME = 0x01 const EVENT_CHANNEL = 0x02 const EVENT_RADIO_NAME = 0x05 const EVENT_RADIO_TEXT = 0x06 // =================================================================== export default class ServiceClient { constructor ({ actions } = {}) { this._socket = new Socket() this._buf = new Buffer(128) this._off = 0 for (const attr of [ 'volume', 'channel', 'radioName', 'radioText' ]) { if (actions[attr] === undefined) { actions[attr] = val => { console.log(`${attr}: '${val}'`) } } } this._actions = actions } _parseMsg (buf) { let i = 0 const { _actions: actions } = this while (i < buf.length) { const event = buf.readUInt8(i++) if (event === EVENT_VOLUME) { actions.volume(buf.readUInt8(i)) i++ continue } if (event === EVENT_CHANNEL) { actions.channel(buf.readUInt16BE(i)) i += 2 continue } if (event !== EVENT_RADIO_NAME && event !== EVENT_RADIO_TEXT) { throw Error('Unknown event.') } const len = buf.readUInt8(i) const start = i + 1 const radioData = buf.slice(start, start + len) if (event === EVENT_RADIO_NAME) { actions.radioName(radioData) } else { actions.radioText(radioData) } i += len + 1 } } _onData (data) { const { _buf: buf } = this data.copy(buf, this._off) this._off += data.length if (this._off >= buf.length) { throw new Error('The buffer is full.') } while (this._off > 0) { const len = buf.readUInt8(0) if (this._off >= len) { this._parseMsg(buf.slice(1, len)) buf.copy(buf, 0, len) this._off -= len } else { break } } } async _send (buf) { return new Promise((resolve, reject) => { const { _socket: socket } = this socket.on('end', reject) socket.write(buf, () => { socket.removeListener('end', reject) resolve() }) }) } async connect (host, port) { const { _socket: socket } = this socket.connect({ host, port }) socket.on('data', data => { try { this._onData(data) } catch (error) { console.error(error) process.exit(1) } }) this.endConnection = eventToPromise(socket, 'end') await eventToPromise(socket, 'connect') } async setVolume (volume) { return this._send( new Buffer([ 0x03, EVENT_VOLUME, volume & 0xFF ]) ) } async setChannel (channel) { const buf = new Buffer(4) buf.writeUInt8(0x04, 0) buf.writeUInt8(EVENT_CHANNEL, 1) buf.writeUInt16BE(channel & 0xFFFF, 2) return this._send(buf) } async waitEndConnection () { return this.endConnection } }
gpl-3.0
flaght/starsvc
plugins/circle/schduler_engine.cc
16034
// Copyright (c) 2016-2017 The star Authors. All rights reserved. // Created on: 2017年1月7日 Author: kerry #include "schduler_engine.h" #include "basic/template.h" #include "net/comm_head.h" #include "net/packet_processing.h" #include "logic/logic_unit.h" #include "errno.h" #include "operator_code.h" namespace circle_logic { CircleManager* CircleEngine::schduler_mgr_ = NULL; CircleEngine* CircleEngine::schduler_engine_ = NULL; int64 CircleManager::current_max_circle_id = 0; CircleManager::CircleManager() { InitThreadrw(&lock_); Init(); } CircleManager::~CircleManager() { DeinitThreadrw(lock_); } void CircleManager::InitDB(circle_logic::CircleDB* circle_db) { circle_db_ = circle_db; } void CircleManager::Init() { } void CircleManager::InitManagerSchduler(manager_schduler::SchdulerEngine* schduler_engine) { manager_schduler_engine_ = schduler_engine; } void CircleManager::InitData() { bool r = false; base_logic::ListValue *listvalue; if(!circle_db_->OnFetchAllCircleInfo(listvalue)) return; while (listvalue->GetSize()) { circle_logic::Circle* circle = new circle_logic::Circle(); base_logic::Value *result_value; listvalue->Remove(0, &result_value); base_logic::DictionaryValue *dict_result_value = (base_logic::DictionaryValue *) (result_value); circle->ValueSerialization(dict_result_value); CIRCLE_MAP t_circle_map; Circle* t_circle; r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, circle->GetSymbol(), t_circle_map); if(r) { r = base::MapGet<CIRCLE_MAP,CIRCLE_MAP::iterator, int64, Circle*> (t_circle_map, circle->GetCircleId(), t_circle); } if(!r){ t_circle_map[circle->GetCircleId()] = circle; star_circle_map_[circle->GetSymbol()] = t_circle_map; circle_list_.push_back(circle); if(current_max_circle_id < circle->GetCircleId()) current_max_circle_id = circle->GetCircleId(); } delete dict_result_value; dict_result_value = NULL; } LOG_MSG2("circle list size %ld", circle_list_.size()); } //发表动态 bool CircleManager::CreateCircle(const int socket, const int64 session, const int32 reserved, const std::string& symbol, const std::string content, const std::string picurl){ circle_logic::Circle* circle = new circle_logic::Circle(); if(circle == NULL){ send_error(socket, ERROR_TYPE, NO_HAVE_MEMMORY, session); return false; } ++current_max_circle_id; circle->SetCircleId(current_max_circle_id); circle->SetSymbol(symbol); circle->SetCreateTime(time(NULL)); circle->SetContent(content); circle->SetPicUrl(picurl); circle->SetStatus(CIRCLE_NORMAL_STATUS); base_logic::RLockGd lk(lock_); CIRCLE_MAP t_circle_map; bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, circle->GetSymbol(), t_circle_map); circle_list_.push_back(circle); t_circle_map[current_max_circle_id] = circle; star_circle_map_[symbol] = t_circle_map; if(circle_db_->OnCreateCircleOrder(*circle)){ //可优化 send_error(socket, ERROR_TYPE, NO_DATABASE_ERR, session); return false; } base_logic::DictionaryValue* dic = new base_logic::DictionaryValue(); base_logic::FundamentalValue* ret = new base_logic::FundamentalValue(current_max_circle_id); dic->Set("circle_id", ret); struct PacketControl packet_control; MAKE_HEAD(packet_control, S_STAR_ADD_CIRCLE, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = dic; send_message(socket, &packet_control); } //删除动态 bool CircleManager::DeleteCircle(const int socket, const int64 session, const int32 reserved, const std::string& symbol, const int64 circleid){ CIRCLE_MAP t_circle_map; Circle* t_circle; base_logic::RLockGd lk(lock_); bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, symbol, t_circle_map); if(r) { r = base::MapGet<CIRCLE_MAP,CIRCLE_MAP::iterator, int64, Circle*> (t_circle_map, circleid, t_circle); } if(!r){ send_error(socket, ERROR_TYPE, NO_CIRCLE_NO_ERR, session); return false; } t_circle->SetStatus(CIRCLE_DEL_STATUS); if(circle_db_->OnDeleteCircle(circleid)){ //可优化 send_error(socket, ERROR_TYPE, NO_DATABASE_ERR, session); return false; } base_logic::DictionaryValue* dic = new base_logic::DictionaryValue(); base_logic::FundamentalValue* ret = new base_logic::FundamentalValue(1); dic->Set("result", ret); struct PacketControl packet_control; MAKE_HEAD(packet_control, S_STAR_DEL_CIRCLE, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = dic; send_message(socket, &packet_control); } //点赞 bool CircleManager::ApprovalCircle(const int socket, const int64 session, const int32 reserved, const int64 uid, const std::string& symbol, const int64 circleid){ CIRCLE_MAP t_circle_map; Circle* t_circle; base_logic::RLockGd lk(lock_); bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, symbol, t_circle_map); if(r) { r = base::MapGet<CIRCLE_MAP,CIRCLE_MAP::iterator, int64, Circle*> (t_circle_map, circleid, t_circle); } if(!r){ send_error(socket, ERROR_TYPE, NO_CIRCLE_NO_ERR, session); return false; } t_circle->AddApproveId(uid); int64 result = 1; if(!circle_db_->OnUpdateCircle(uid, *t_circle, result)){ //可优化 send_error(socket, ERROR_TYPE, NO_DATABASE_ERR, session); t_circle->DelApprovId(); return false; } if( result < 0 ) { send_error(socket, ERROR_TYPE, result, session); t_circle->DelApprovId(); return false; } base_logic::DictionaryValue* dic = new base_logic::DictionaryValue(); base_logic::FundamentalValue* ret = new base_logic::FundamentalValue(result); dic->Set("result", ret); struct PacketControl packet_control; MAKE_HEAD(packet_control, S_USER_APPROVE_CIRCLE, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = dic; send_message(socket, &packet_control); } //用户发表评论/回复 bool CircleManager::UserCommentCircle(const int socket, const int64 session, const int32 reserved, const int64 uid, const std::string& symbol,const int64 circleid,const int64 direction,const std::string& content){ CIRCLE_MAP t_circle_map; Circle* t_circle; base_logic::RLockGd lk(lock_); bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, symbol, t_circle_map); if(r) { r = base::MapGet<CIRCLE_MAP,CIRCLE_MAP::iterator, int64, Circle*> (t_circle_map, circleid, t_circle); } if(!r){ send_error(socket, ERROR_TYPE, NO_CIRCLE_NO_ERR, session); return false; } int64 lastpriority = 1 + t_circle->GetLastPriority(); circle_logic::Scomment scomment; scomment.uid = uid; scomment.direction = direction; scomment.content = content; scomment.priority = lastpriority; t_circle->AddComment(scomment); int64 result = 1; if(!circle_db_->OnUpdateCircle(uid, *t_circle, result)){ //可优化 send_error(socket, ERROR_TYPE, NO_DATABASE_ERR, session); t_circle->DelComment(); return false; } if( result < 0 ) { send_error(socket, ERROR_TYPE, result, session); t_circle->DelComment(); return false; } base_logic::DictionaryValue* dic = new base_logic::DictionaryValue(); base_logic::FundamentalValue* ret = new base_logic::FundamentalValue(result); dic->Set("result", ret); struct PacketControl packet_control; MAKE_HEAD(packet_control, S_USER_COMMENT_CIRCLE, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = dic; send_message(socket, &packet_control); } //明星回复评论 bool CircleManager::StarReplyCircle(const int socket, const int64 session, const int32 reserved, const int64 uid, const std::string& symbol,const int64 circleid,const int64 direction,const std::string& content){ CIRCLE_MAP t_circle_map; Circle* t_circle; base_logic::RLockGd lk(lock_); bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, symbol, t_circle_map); if(r) { r = base::MapGet<CIRCLE_MAP,CIRCLE_MAP::iterator, int64, Circle*> (t_circle_map, circleid, t_circle); } if(!r){ send_error(socket, ERROR_TYPE, NO_CIRCLE_NO_ERR, session); return false; } /* if(t_circle->m_commentList.empty()) { send_error(socket, ERROR_TYPE, NO_STAR_REPLY_ERR, session); return false; }*/ int64 lastpriority = 1 + t_circle->GetLastPriority(); circle_logic::Scomment scomment; scomment.uid = uid; scomment.direction = direction; scomment.content = content; scomment.priority = lastpriority; t_circle->AddComment(scomment); int64 result = 1; if(!circle_db_->OnUpdateCircle(uid, *t_circle, result)){ //可优化 send_error(socket, ERROR_TYPE, NO_DATABASE_ERR, session); t_circle->DelComment(); return false; } if( result < 0 ) { send_error(socket, ERROR_TYPE, result, session); t_circle->DelComment(); return false; } base_logic::DictionaryValue* dic = new base_logic::DictionaryValue(); base_logic::FundamentalValue* ret = new base_logic::FundamentalValue(result); dic->Set("result", ret); struct PacketControl packet_control; MAKE_HEAD(packet_control, S_STAR_REPLY_COMMENT, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = dic; send_message(socket, &packet_control); } //明星动态列表 bool CircleManager::GetSymbolAllCircle(const int socket, const int64 session, const int32 reserved, const std::string& symbol, const int64 pos, const int64 count){ circle_reply::CircleListReply circlereplylist; base_logic::RLockGd lk(lock_); CIRCLE_MAP t_circle_map; bool r = base::MapGet<STAR_CIRCLE_MAP,STAR_CIRCLE_MAP::iterator, std::string, CIRCLE_MAP> (star_circle_map_, symbol, t_circle_map); if(!r){ send_error(socket, ERROR_TYPE, NO_CIRCLE_NO_ERR, session); return false; } int32 posnum = 0; int32 startnum = 0; CIRCLE_MAP::reverse_iterator it = t_circle_map.rbegin(); for(; it != t_circle_map.rend() && startnum<count; ++it){ Circle*& circle = it->second; if(circle->GetStatus() == CIRCLE_DEL_STATUS) continue; ++posnum; if(posnum > pos){ ++startnum; circle_reply::CircleReply* circlereply = new circle_reply::CircleReply(); circlereply->SetCircle(circle); circlereply->SetApproveList(GetCircleApproveList(circle)); circlereply->SetCommentList(GetCircleCommentList(circle)); star_logic::StarInfo star; r = manager_schduler_engine_->GetStarInfoSchduler(symbol, &star); if (!r) { circlereply->SetName(""); circlereply->SetHeadUrl(""); } else{ circlereply->SetName(star.name()); circlereply->SetHeadUrl(star.pic()); } circlereplylist.set_unit(circlereply->get()); } } LOG_DEBUG2("Get symbol[%s] circle list size:%d, pos[%ld], count[%ld]", symbol.c_str(), circlereplylist.Size(), pos, count); if (circlereplylist.Size() != 0) { struct PacketControl packet_control; MAKE_HEAD(packet_control, S_GET_STAR_CIRCLE_INFO, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = circlereplylist.get(); send_message(socket, &packet_control); }else { send_error(socket, ERROR_TYPE, NO_HAVE_STAR_CIRCLE_ERR,session); } } //获取全量明星动态列表 bool CircleManager::GetAllCircle(const int socket, const int64 session, const int32 reserved, const int64 pos, const int64 count){ circle_reply::CircleListReply circlereplylist; bool r = false; int32 posnum = 0; int32 startnum = 0; base_logic::RLockGd lk(lock_); CIRCLE_LIST::reverse_iterator iter = circle_list_.rbegin(); for(; iter != circle_list_.rend() && startnum<count; ++iter){ if((*iter)->GetStatus() == CIRCLE_DEL_STATUS) continue; ++posnum; if(posnum > pos){ ++startnum; circle_reply::CircleReply* circlereply = new circle_reply::CircleReply(); circlereply->SetCircle(*iter); circlereply->SetApproveList(GetCircleApproveList(*iter)); circlereply->SetCommentList(GetCircleCommentList(*iter)); star_logic::StarInfo star; r = manager_schduler_engine_->GetStarInfoSchduler((*iter)->GetSymbol(), &star); if (!r) { circlereply->SetName(""); circlereply->SetHeadUrl(""); } else{ circlereply->SetName(star.name()); circlereply->SetHeadUrl(star.pic()); } circlereplylist.set_unit(circlereply->get()); } } LOG_DEBUG2("Get all symbols circle list size:%d", circlereplylist.Size()); if (circlereplylist.Size() != 0) { std::string tempstring; { base_logic::ValueSerializer* engine = base_logic::ValueSerializer::Create( 0, &tempstring); engine->Serialize(*((base_logic::Value*) circlereplylist.get())); } struct PacketControl packet_control; MAKE_HEAD(packet_control, S_GET_ALL_CIRCLE_INFO, CIRCLE_TYPE, 0, session, reserved); packet_control.body_ = circlereplylist.get(); send_message(socket, &packet_control); }else { send_error(socket, ERROR_TYPE, NO_HAVE_STAR_CIRCLE_ERR, session); } } /* return // {{"uid":123,"user_name":"abc123"}{"uid":456,"user_name":"abc456"}...} */ base_logic::ListValue* CircleManager::GetCircleApproveList(Circle*& circle){ base_logic::ListValue* approvelist = new base_logic::ListValue(); std::list<int64>::iterator it = circle->m_approveList.begin(); for(; it!= circle->m_approveList.end(); ++it){ base_logic::DictionaryValue* t_dir = new base_logic::DictionaryValue(); base_logic::FundamentalValue* t_uid = new base_logic::FundamentalValue(*it); t_dir->Set(L"uid", t_uid); base_logic::StringValue* t_username = new base_logic::StringValue(GetUserName(*it)); t_dir->Set(L"user_name", t_username); approvelist->Append((base_logic::Value*) (t_dir)); } return approvelist; } /* return // {{"uid":123,"user_name":"abc123","direction":0,"content":"abc123","priority":0} // {"uid":456,"user_name":"abc456","direction":1,"content":"321cba","priority":1}... } */ base_logic::ListValue* CircleManager::GetCircleCommentList(Circle*& circle) { base_logic::ListValue* commentlist = new base_logic::ListValue(); circle_logic::COMMENTLIST::iterator it = circle->m_commentList.begin(); for(; it!= circle->m_commentList.end(); ++it){ base_logic::DictionaryValue* t_dir = new base_logic::DictionaryValue(); base_logic::FundamentalValue* t_uid = new base_logic::FundamentalValue(it->uid); t_dir->Set(L"uid", t_uid); base_logic::StringValue* t_username = new base_logic::StringValue(GetUserName(it->uid)); t_dir->Set(L"user_name", t_username); base_logic::FundamentalValue* t_direction = new base_logic::FundamentalValue(it->direction); t_dir->Set(L"direction", t_direction); base_logic::StringValue* t_content = new base_logic::StringValue(it->content); t_dir->Set(L"content", t_content); base_logic::FundamentalValue* t_priority = new base_logic::FundamentalValue(it->priority); t_dir->Set(L"priority", t_priority); commentlist->Append((base_logic::Value*) (t_dir)); } return commentlist; } std::string CircleManager::GetUserName(int64 uid){ star_logic::UserInfo tuserinfo; if(manager_schduler_engine_->GetUserInfoSchduler(uid, &tuserinfo)){ return tuserinfo.nickname(); } base_logic::DictionaryValue* dict = new base_logic::DictionaryValue(); circle_db_->OnGetUserName(uid, dict); std::string username(""); dict->GetString(L"user_name", &username); if(dict){ delete dict; dict = NULL; } return username; } }
gpl-3.0
Doap/The-Convectek-CRM
wp-content/plugins/widget-or-sidebar-per-shortcode/widget-or-sidebar-per-shortcode.php
1301
<?php /* Plugin Name: Widget or Sidebar Shortcode Plugin URI: http://staude.net/wordpress/plugins/WidgetSidebarShortcode Description: Use widgets and sidebars via shortcode in pages or posts Author: Frank Staude Version: 0.6.1 Author URI: http://www.staude.net/ Compatibility: WordPress 4.0 */ /* Copyright 2012-2013 Frank Staude (email : frank@staude.net) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if (! class_exists( 'widget_or_sidebar_per_shortcode' ) ) { include_once dirname( __FILE__ ) .'/class-widget-or-sidebar-per-shortcode.php'; $widget_or_sidebar_per_shortcode = new widget_or_sidebar_per_shortcode(); }
gpl-3.0
Mouarius/Made-With-Experience
src/main/java/fr/mouarius/mwe/proxy/CommonProxy.java
156
package fr.mouarius.mwe.proxy; public class CommonProxy{ public void registerTileEntities(){ } public void registerRenderingThings(){ } }
gpl-3.0
FthrNature/unleashed-pixel-dungeon
src/main/java/com/shatteredpixel/pixeldungeonunleashed/effects/particles/ShaftParticle.java
1812
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.pixeldungeonunleashed.effects.particles; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.PixelParticle; import com.watabou.noosa.particles.Emitter.Factory; import com.watabou.utils.Random; public class ShaftParticle extends PixelParticle { public static final Emitter.Factory FACTORY = new Factory() { @Override public void emit( Emitter emitter, int index, float x, float y ) { ((ShaftParticle)emitter.recycle( ShaftParticle.class )).reset( x, y ); } @Override public boolean lightMode() { return true; } }; public ShaftParticle() { super(); lifespan = 1.2f; speed.set( 0, -6 ); } private float offs; public void reset( float x, float y ) { revive(); this.x = x; this.y = y; offs = -Random.Float( lifespan ); left = lifespan - offs; } @Override public void update() { super.update(); float p = left / lifespan; am = p < 0.5f ? p : 1 - p; scale.x = (1 - p) * 4; scale.y = 16 + (1 - p) * 16; } }
gpl-3.0
Emergen/zivios-panel
application/library/Zend/Filter/File/Rename.php
8647
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Filter * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: $ */ /** * @see Zend_Filter_Interface */ // require_once 'Zend/Filter/Interface.php'; /** * @category Zend * @package Zend_Filter * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Filter_File_Rename implements Zend_Filter_Interface { /** * Internal array of array(source, target, overwrite) */ protected $_files = array(); /** * Class constructor * * Options argument may be either a string, a Zend_Config object, or an array. * If an array or Zend_Config object, it accepts the following keys: * 'source' => Source filename or directory which will be renamed * 'target' => Target filename or directory, the new name of the sourcefile * 'overwrite' => Shall existing files be overwritten ? * * @param string|array $options Target file or directory to be renamed * @param string $target Source filename or directory (deprecated) * @param bool $overwrite Should existing files be overwritten (deprecated) * @return void */ public function __construct($options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); } elseif (is_string($options)) { $options = array('target' => $options); } elseif (!is_array($options)) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Invalid options argument provided to filter'); } if (1 < func_num_args()) { trigger_error('Support for multiple arguments is deprecated in favor of a single options array', E_USER_NOTICE); $argv = func_get_args(); array_shift($argv); $source = array_shift($argv); $overwrite = false; if (!empty($argv)) { $overwrite = array_shift($argv); } $options['source'] = $source; $options['overwrite'] = $overwrite; } $this->setFile($options); } /** * Returns the files to rename and their new name and location * * @return array */ public function getFile() { return $this->_files; } /** * Sets a new file or directory as target, deleting existing ones * * Array accepts the following keys: * 'source' => Source filename or directory which will be renamed * 'target' => Target filename or directory, the new name of the sourcefile * 'overwrite' => Shall existing files be overwritten ? * * @param string|array $options Old file or directory to be rewritten * @return Zend_Filter_File_Rename */ public function setFile($options) { $this->_files = array(); $this->addFile($options); return $this; } /** * Adds a new file or directory as target to the existing ones * * Array accepts the following keys: * 'source' => Source filename or directory which will be renamed * 'target' => Target filename or directory, the new name of the sourcefile * 'overwrite' => Shall existing files be overwritten ? * * @param string|array $options Old file or directory to be rewritten * @return Zend_Filter_File_Rename */ public function addFile($options) { if (is_string($options)) { $options = array('target' => $options); } elseif (!is_array($options)) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception ('Invalid options to rename filter provided'); } $this->_convertOptions($options); return $this; } /** * Defined by Zend_Filter_Interface * * Renames the file $value to the new name set before * Returns the file $value, removing all but digit characters * * @param string $value Full path of file to change * @return string The new filename which has been set, or false when there were errors */ public function filter($value) { $file = $this->_getFileName($value); if ($file['source'] == $file['target']) { return $value; } if (!file_exists($file['source'])) { return $value; } if (($file['overwrite'] == true) and (file_exists($file['target']))) { unlink($file['target']); } if (file_exists($file['target'])) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception(sprintf("File '%s' could not be renamed. It already exists.", $value)); } $result = rename($file['source'], $file['target']); if ($result === true) { return $file['target']; } // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception(sprintf("File '%s' could not be renamed. An error occured while processing the file.", $value)); } /** * Internal method for creating the file array * Supports single and nested arrays * * @param array $options * @return array */ protected function _convertOptions($options) { $files = array(); foreach ($options as $key => $value) { if (is_array($value)) { $this->_convertOptions($value); continue; } switch ($key) { case "source": $files['source'] = (string) $value; break; case 'target' : $files['target'] = (string) $value; break; case 'overwrite' : $files['overwrite'] = (boolean) $value; break; default: break; } } if (empty($files)) { return $this; } if (empty($files['source'])) { $files['source'] = '*'; } if (empty($files['target'])) { $files['target'] = '*'; } if (empty($files['overwrite'])) { $files['overwrite'] = false; } $found = false; foreach ($this->_files as $key => $value) { if ($value['source'] == $files['source']) { $this->_files[$key] = $files; $found = true; } } if (!$found) { $count = count($this->_files); $this->_files[$count] = $files; } return $this; } /** * Internal method to resolve the requested source * and return all other related parameters * * @param string $file Filename to get the informations for * @return array */ protected function _getFileName($file) { $rename = array(); foreach ($this->_files as $value) { if ($value['source'] == '*') { if (!isset($rename['source'])) { $rename = $value; $rename['source'] = $file; } } if ($value['source'] == $file) { $rename = $value; } } if (!isset($rename['source'])) { return $file; } if (!isset($rename['target']) or ($rename['target'] == '*')) { $rename['target'] = $rename['source']; } if (is_dir($rename['target'])) { $name = basename($rename['source']); $last = $rename['target'][strlen($rename['target']) - 1]; if (($last != '/') and ($last != '\\')) { $rename['target'] .= DIRECTORY_SEPARATOR; } $rename['target'] .= $name; } return $rename; } }
gpl-3.0
KamranMackey/Aurora
plugins/minecraft/mcstatus.py
2455
# # Copyright (C) 2016-2017 Kamran Mackey and contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. """Minecraft Status Minecraft Status is a plugin that retrieves the current Minecraft server status, and then displays it once a user sends the /mcstatus command. """ import json import requests from telegram import ParseMode from telegram.ext.dispatcher import run_async @run_async def mc_status(_, update): """ This plugin fetches the status of the Minecraft/Mojang servers and then posts the retrieved status information as a Telegram message. """ mcstatus_baseurl = "https://status.mojang.com/check" mcstatus_request = requests.get(mcstatus_baseurl).text try: mcstatus_request except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as error: update.message.reply_text( text="Unable to get Minecraft server status: {}".format(error)) # Take the JSON Mojang's status site gives me # and turn it into a nice format. mc_req = mcstatus_request.replace("}", "").replace( "{", "").replace("]", "}").replace("[", "{") data = json.loads(mc_req) out = [] # Use a fancy loop so I don't have to update # this when Mojang adds new servers. green = [] yellow = [] red = [] for server, status in list(data.items()): if status == "green": checkmark = "✅ " green.append(checkmark + server) elif status == "yellow": yellow.append(server) else: red_circle = "🔴 " red.append(red_circle + server) if green: green.sort() out.append("*The following Mojang services are up and running*:\n" + "\n".join(green)) if yellow: yellow.sort() out.append("*The following Mojang services are currently having issues*:\n" + ",\n".join(yellow)) if red: red.sort() out.append("*The following Mojang services are currently offline*:" + ",\n".join(red)) update.message.reply_text(parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, text=" ".join(out))
gpl-3.0
e-biz/arpi-gl
core/src/rendering/BoundingSphere.cpp
1519
/* * Copyright (C) 2015 eBusiness Information * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rendering/BoundingSphere.hpp" namespace dma { //------------------------------------------------------------------------------- BoundingSphere::BoundingSphere() : BoundingSphere(0.0f, 0.0f, 0.0f, 0.0f) {} //------------------------------------------------------------------------------- BoundingSphere::BoundingSphere(float x, float y, float z, float r) : mCenter(x, y, z), mRadius(r) {} //------------------------------------------------------------------------------- BoundingSphere::BoundingSphere(const glm::vec3 &center, float radius) : BoundingSphere(center.x, center.y, center.z, radius) {} //------------------------------------------------------------------------------- BoundingSphere::~BoundingSphere() { } }
gpl-3.0
BerntA/QCScript
QScript/Filesystem/SMDParser.cs
3535
//========= Copyright © Bernt Andreas Eide! ============// // // Purpose: Parses a Valve Studio Model Data file. // //==================================================================// using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace QScript.Filesystem { public sealed class SMDParser { public int GetNumberOfFrames { get { return _animationData.Count(); } } private List<string> _animationData; private string _smdPath; private string _smdContent; private int _startFrameNum; private bool _bHasParsedSuccessfully; public SMDParser(string path) { _smdPath = path; _animationData = new List<string>(); } public bool ParseSMDFile() { _bHasParsedSuccessfully = false; _startFrameNum = -1; _smdContent = null; _animationData.Clear(); if (!File.Exists(_smdPath)) return false; FileInfo info = new FileInfo(_smdPath); if (info.Extension != ".smd") return false; _smdContent = File.ReadAllText(_smdPath); using (StreamReader reader = new StreamReader(_smdPath)) { while(!reader.EndOfStream) { string line = reader.ReadLine(); // Add this animation block to the anim data list. if (line.Contains("time ")) { int indexOfBlock = _smdContent.IndexOf(line) + line.Length; int indexOfTime = line.IndexOf("time "); string nextFrame = string.Format("time {0}", ((int.Parse(line.Substring(indexOfTime + 5))) + 1)); int indexOfNextBlock = _smdContent.IndexOf(nextFrame); if (indexOfNextBlock == -1) indexOfNextBlock = _smdContent.IndexOf("end", indexOfBlock); if (indexOfNextBlock != -1) { string animData = _smdContent.Substring(indexOfBlock, (indexOfNextBlock - indexOfBlock)); _animationData.Add(animData); } if (_startFrameNum == -1) _startFrameNum = int.Parse(line.Substring(indexOfTime + 5)); } } } _bHasParsedSuccessfully = true; return true; } public void ReverseAnimation(string outputFile) { if (!_bHasParsedSuccessfully) return; string content = _smdContent.Substring(0, (_smdContent.IndexOf("time ", StringComparison.CurrentCulture))); int frame = _startFrameNum; for (int i = (_animationData.Count() - 1); i >= 0; i--) { content += GetAnimationBlockForData(_animationData[i], frame); frame++; } content += "end" + Environment.NewLine; Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); File.WriteAllText(outputFile, content, Encoding.ASCII); } private string GetAnimationBlockForData(string data, int frame) { return string.Format( "time {0}{1}", frame, data ); } } }
gpl-3.0
crisis-economics/CRISIS
CRISIS/src/eu/crisis_economics/abm/dashboard/CheckListModel.java
2150
/* * This file is part of CRISIS, an economics simulator. * * Copyright (C) 2015 AITIA International, Inc. * * CRISIS 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. * * CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>. */ package eu.crisis_economics.abm.dashboard; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.ListModel; /** * This class represents a list model that maintans the extra information about each element whether it is checked or not. * * @author Tamás Máhr * */ @SuppressWarnings("serial") public class CheckListModel extends AbstractListModel implements ListModel { List<?> elements = new ArrayList<Object>(); List<Boolean> checkedState = new ArrayList<Boolean>(); /** * Creates a new list model containing the specified elements. The checked state of all elements are initialized to false. * * @param elements the elements this list model should contain */ public CheckListModel(final List<?> elements) { this.elements = new ArrayList<Object>(elements); for (int i = 0; i < elements.size(); i++) { checkedState.add(false); } } /** {@inheritDoc} */ @Override public int getSize() { return elements.size(); } /** {@inheritDoc} */ @Override public Object getElementAt(int index) { return elements.get(index); } public void setCheckedState(final int index, final boolean state){ checkedState.set(index, state); fireContentsChanged(this, index, index); } public boolean getCheckedState(final int index){ if (index < 0) return false; return checkedState.get(index); } }
gpl-3.0
deremix/darmixcore
src/scripts/EasternKingdoms/Deadmines/deadmines.cpp
1198
/* * Darmix-Core Copyright (C) 2013 Deremix * Integrated Files: CREDITS.md and LICENSE.md */ /* ScriptData Name: Deadmines Complete(%): 0 Comment: Placeholder Category: Deadmines EndScriptData */ #include "ScriptPCH.h" #include "deadmines.h" #include "Spell.h" /*##### # item_Defias_Gunpowder #####*/ bool ItemUse_item_defias_gunpowder(Player* pPlayer, Item* pItem, SpellCastTargets const& targets) { ScriptedInstance *pInstance = pPlayer->GetInstanceData(); if (!pInstance) { pPlayer->GetSession()->SendNotification("Instance script not initialized"); return true; } if (pInstance->GetData(EVENT_CANNON) != CANNON_NOT_USED) return false; if (targets.getGOTarget() && targets.getGOTarget()->GetTypeId() == TYPEID_GAMEOBJECT && targets.getGOTarget()->GetEntry() == GO_DEFIAS_CANNON) pInstance->SetData(EVENT_CANNON, CANNON_GUNPOWDER_USED); pPlayer->DestroyItemCount(pItem->GetEntry(), 1, true); return true; } void AddSC_deadmines() { Script *newscript; newscript = new Script; newscript->Name = "item_defias_gunpowder"; newscript->pItemUse = &ItemUse_item_defias_gunpowder; newscript->RegisterSelf(); }
gpl-3.0
aykutalparslan/Telegram-Server
src/main/java/org/telegram/tl/L57/contacts/Blocked.java
2226
/* * This file is part of Telegram Server * Copyright (C) 2015 Aykut Alparslan KOÇ * * Telegram Server 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. * * Telegram Server is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.telegram.tl.L57.contacts; import org.telegram.mtproto.ProtocolBuffer; import org.telegram.tl.TLObject; import org.telegram.tl.TLVector; import org.telegram.tl.APIContext; import org.telegram.tl.L57.*; public class Blocked extends org.telegram.tl.contacts.TLBlocked { public static final int ID = 0x1c138d15; public TLVector<org.telegram.tl.TLContactBlocked> blocked; public TLVector<org.telegram.tl.TLUser> users; public Blocked() { this.blocked = new TLVector<>(); this.users = new TLVector<>(); } public Blocked(TLVector<org.telegram.tl.TLContactBlocked> blocked, TLVector<org.telegram.tl.TLUser> users) { this.blocked = blocked; this.users = users; } @Override public void deserialize(ProtocolBuffer buffer) { blocked = (TLVector<org.telegram.tl.TLContactBlocked>) buffer.readTLObject(APIContext.getInstance()); users = (TLVector<org.telegram.tl.TLUser>) buffer.readTLObject(APIContext.getInstance()); } @Override public ProtocolBuffer serialize() { ProtocolBuffer buffer = new ProtocolBuffer(20); serializeTo(buffer); return buffer; } @Override public void serializeTo(ProtocolBuffer buff) { buff.writeInt(getConstructor()); buff.writeTLObject(blocked); buff.writeTLObject(users); } public int getConstructor() { return ID; } }
gpl-3.0
ankitpati/jwt
main/ButtonApplet.java
1009
/* ButtonApplet.java */ /* Date : 05 April 2016 * Author: Ankit Pati */ import java.applet.Applet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonApplet extends Applet implements ActionListener{ final static long serialVersionUID = 0l; public void init() { Button r, g, b; add(r = new Button("Red")); add(g = new Button("Green")); add(b = new Button("Blue")); r.addActionListener(this); g.addActionListener(this); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { String str; str = e.getActionCommand(); if(str.equals("Red")) setBackground(Color.red); else if(str.equals("Green")) setBackground(Color.green); else setBackground(Color.blue); } }; /* <object code="ButtonApplet" width="200" height="200"></object> */ /* end of ButtonApplet.java */
gpl-3.0
generalelectrix/pyenttec
pyenttec/test.py
1622
"""Tests for offline DMX port.""" from nose.tools import assert_equal, assert_is, assert_raises, raises from . import DMXConnectionOffline def test_offline_port(): univ_size = 24 port = DMXConnectionOffline(univ_size=univ_size) assert_equal(univ_size, len(port.dmx_frame)) assert all(chan == 0 for chan in port.dmx_frame) port.set_channel(0, 1) assert_equal(1, port.dmx_frame[0]) assert_raises(IndexError, port.set_channel, univ_size, 0) def test_port_item_accessors(): univ_size = 24 port = DMXConnectionOffline(univ_size=univ_size) for i in range(univ_size): port[i] = i assert_equal(i, port.dmx_frame[i]) assert_equal(i, port[i]) def test_port_setitem_max_address(): univ_size = 24 port = DMXConnectionOffline(univ_size=univ_size) def assert_fail_set_index(i): with assert_raises(IndexError): port[i] = 0 # assert_fail_set_index(-1) assert_fail_set_index(univ_size) assert_fail_set_index(univ_size + 1) def test_dmx_value_range(): univ_size = 24 port = DMXConnectionOffline(univ_size=univ_size) assert_raises(ValueError, port.set_channel, 1, -1) def set_and_check(chan, val): port.set_channel(chan, val) assert_equal(val, port[chan]) set_and_check(0, 0) set_and_check(0, 128) set_and_check(0, 255) assert_raises(ValueError, port.set_channel, 5, 256) def test_blackout_keeps_array(): univ_size = 24 port = DMXConnectionOffline(univ_size=univ_size) old_frame = port.dmx_frame port.blackout() assert_is(port.dmx_frame, old_frame)
gpl-3.0
ramsodev/DitaManagement
dita/dita.topic/src/net/ramso/dita/topic/SlClass.java
14186
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.02 at 08:00:15 PM CEST // package net.ramso.dita.topic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for sl.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="sl.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}sl.content"/> * &lt;/sequence> * &lt;attGroup ref="{}sl.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sl.class", propOrder = { "sli" }) @XmlSeeAlso({ Sl.class }) public class SlClass { protected List<Sli> sli; @XmlAttribute(name = "spectitle") protected String spectitle; @XmlAttribute(name = "compact") protected YesnoAttClass compact; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; /** * Gets the value of the sli property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sli property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSli().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Sli } * * */ public List<Sli> getSli() { if (sli == null) { sli = new ArrayList<Sli>(); } return this.sli; } /** * Gets the value of the spectitle property. * * @return * possible object is * {@link String } * */ public String getSpectitle() { return spectitle; } /** * Sets the value of the spectitle property. * * @param value * allowed object is * {@link String } * */ public void setSpectitle(String value) { this.spectitle = value; } /** * Gets the value of the compact property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getCompact() { return compact; } /** * Sets the value of the compact property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setCompact(YesnoAttClass value) { this.compact = value; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } }
gpl-3.0
bozhbo12/demo-spring-server
spring-game/src/main/java/org/epilot/ccf/common/Filters.java
451
package org.epilot.ccf.common; public class Filters { String name; String className; String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }
gpl-3.0
DidiMilikina/SoftUni
Programming Basics - C#/Exams/Programming Basics Exam - 20 November 2016 - Evening/03. Bike Race/Program.cs
1547
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.Bike_Race { class Program { static void Main(string[] args) { var juniors = int.Parse(Console.ReadLine()); var seniors = int.Parse(Console.ReadLine()); var typeOfRaice = Console.ReadLine(); var juniorsPrice = 0.00; var seniorsPrice = 0.00; if (typeOfRaice == "trail") { juniorsPrice = 5.50; seniorsPrice = 7.00; } else if (typeOfRaice == "cross-country") { if (juniors + seniors >= 50) { juniorsPrice = 8.00 * 0.75; seniorsPrice = 9.5 * 0.75; } else { juniorsPrice = 8.00; seniorsPrice = 9.50; } } else if (typeOfRaice == "downhill") { juniorsPrice = 12.25; seniorsPrice = 13.75; } else { juniorsPrice = 20.00; seniorsPrice = 21.50; } var collectSum = juniors * juniorsPrice + seniors * seniorsPrice; var expense = collectSum * 0.05; var collectSumWithoutExpenses = collectSum - expense; Console.WriteLine("{0:f2}", collectSumWithoutExpenses); } } }
gpl-3.0
akshatamohanty/vidamo
mobius/ui-components/viewport/text_directive.js
3580
// text editor viewport example mobius.directive('textViewport', function() { return { restrict: 'A', scope: { viewModel: "=" }, template: "<div style='width: 100%; top:32px; left:0; bottom: 0; position: absolute;'>\ <textarea\ style='width: 100%; height: 100%;'\ text-viewport\ view-model='currentTextVersionGeom'>\ </textarea>\ </div>", controller: 'textCtrl', link: function (scope, elem, attr) { // Serialize the data model as json and update the textarea. var updateJson = function () { if (scope.viewModel && scope.viewModel.geom) { var json = scope.viewModel.geom; //var json = JSON.stringify(scope.viewModel.geom); $(elem).val(JSON.stringify(json)); } }; // First up, set the initial value of the textarea. updateJson(); // Watch for changes in the data model and update the textarea whenever necessary. scope.$watch("viewModel.geom", updateJson); } } }); mobius.controller('textCtrl', ['$scope','$rootScope', 'generateCode', function($scope,$rootScope,generateCode) { // geometry list for visualising after node selection $scope.outputGeom =[]; $scope.currentTextVersionGeom = {geom:"Hi, No node is selected."}; $scope.nodeIndex = ''; $scope.$watch(function () { return generateCode.getOutputGeom(); }, function () { $scope.outputGeom = generateCode.getOutputGeom(); }); $scope.chartViewModel = generateCode.getChartViewModel(); $scope.$watch(function(){return generateCode.getChartViewModel()},function(){ $scope.chartViewModel = generateCode.getChartViewModel(); }); // listen to the graph, when a node is clicked, update text accordingly $rootScope.$on("nodeIndex", function(event, message) { if($scope.nodeIndex !== message && message !== undefined && message !== "port"){ $scope.nodeIndex = message; displayText(); }else if(message === undefined){ $scope.nodeIndex = message; } function displayText(){ var selectedNodes = $scope.chartViewModel.getSelectedNodes(); for(var i = 0; i < $scope.outputGeom.length; i++){ for(var j =0; j < selectedNodes.length; j++){ if($scope.outputGeom[i].name === selectedNodes[j].data.name){ for(var i = 0; i < $scope.outputGeom.length; i++){ for(var j =0; j < selectedNodes.length; j++){ if($scope.outputGeom[i].name === selectedNodes[j].data.name){ $scope.currentTextVersionGeom.geom = $scope.outputGeom[i].geom; } } } } } } } }); }]);
gpl-3.0
tmccormi/openemr-homehealth
interface/forms/hha_visit/view.php
29845
<?php include_once("../../globals.php"); include_once ("functions.php"); include_once("../../calendar.inc"); require_once("$srcdir/ESign.class.php"); include_once("$srcdir/sha1.js"); include_once("$srcdir/api.inc"); $obj = formFetch("forms_hha_visit", $_GET["id"]); $hha_visit_activities = explode("#",$obj{"hha_visit_activities"}); // get the formDir $formDir = null; $pathSep = "/"; if(strtolower(php_uname("s")) == "windows"|| strtolower(php_uname("s")) == "windows nt") $pathSep = "\\"; $formDirParts = explode($pathSep, __dir__); $formDir = $formDirParts[count($formDirParts) - 1]; //get the form table -- currently manually set for each form - should be automated. $formTable = "forms_hha_visit"; if($formDir) $registryRow = sqlQuery("select * from registry where directory = '$formDir'"); $esign = new ESign(); $esign->init($id, $formTable); $sigId = $esign->getNewestUnsignedSignature(); ?> <html><head> <?php html_header_show();?> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> <style type="text/css">@import url(<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.css);</style> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar_en.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar_setup.js"></script> <script src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-1.7.2.min.js" type="text/javascript"></script> <script type="text/javascript" src="../../../library/js/fancybox-1.3.4/jquery.fancybox-1.3.4.pack.js"></script> <script type='text/javascript' src='../../../library/dialog.js'></script> <link rel="stylesheet" href="../../../library/js/fancybox-1.3.4/jquery.fancybox-1.3.4.css" type="text/css" media="screen" /> <script> $(document).ready(function() { var status = ""; $("#signoff").fancybox({ 'scrolling' : 'no', 'titleShow' : false, 'onClosed' : function() { $("#login_prompt").hide(); } }); $("#login_form").bind("submit", function() { document.getElementById("login_pass").value = SHA1(document.getElementById("login_pass").value); if ($("#login_pass").val().length < 1) { $("#login_prompt").show(); $.fancybox.resize(); return false; } $.fancybox.showActivity(); $.ajax({ type : "POST", cache : false, url : "<?php echo $GLOBALS['rootdir'] . "/forms/$formDir/sign.php";?>", data : $(this).serializeArray(), success: function(data) { $.fancybox(data); } }); return false; }); }); </script> <script> function requiredCheck(){ var time_in = document.getElementById('hha_visit_time_in').value; var time_out = document.getElementById('hha_visit_time_out').value; if(time_in != "" && time_out != "") { return true; } else { alert("Please select a time in and time out before submitting."); return false; } } </script> </head> <body class="body_top"> <?php include_once("$srcdir/api.inc"); $obj = formFetch("forms_hha_visit", $_GET["id"]); foreach($obj as $key => $value) { $obj[$key] = htmlspecialchars($value); } ?> <form method="post" action="<?php echo $rootdir;?>/forms/hha_visit/save.php?mode=update&&id=<?php echo $_GET['id']; ?>" name="hha_visit"> <h3 align="center"><?php xl('HHA VISIT NOTE','e') ?></h3> <table class="formtable" width="100%" border="0"> <TR valign="top"> <TD> <b><?php xl('Patient:','e') ?></b> <input type="text" name="hha_visit_patient_name" size="30" value="<?php patientName(); ?>" readonly /><br /> </TD> <TD align="right"> <b><?php xl('Caregiver:','e') ?></b> <input type="text" name="hha_visit_caregiver_name" size="30" value="<?php echo $obj{"hha_visit_caregiver_name"}; ?>" /> <strong><?php xl('Start of Care Date:','e') ?></strong> <input type="text" name="hha_visit_date" id="hha_visit_date" size="12" value="<?php echo $obj{"hha_visit_date"}; ?>" readonly/><br /> <?php if($date_is_blank == 0) { ?> <img src='../../pic/show_calendar.gif' align='absbottom' width='24' height='22' id='img_curr_date1' border='0' alt='[?]' style='cursor: pointer; cursor: hand' title='<?php xl('Click here to choose a date','e'); ?>' /> <script LANGUAGE="JavaScript"> Calendar.setup({inputField:"hha_visit_date", ifFormat:"%Y-%m-%d", button:"img_curr_date1"}); </script> <?php } else {echo '';} ?> <b><?php xl('Time In:','e') ?></b> <select name="hha_visit_time_in" id="hha_visit_time_in"> <?php timeDropDown(stripslashes($obj{"hha_visit_time_in"}))?> </select> <b><?php xl('Time Out:','e') ?></b> <select name="hha_visit_time_out" id="hha_visit_time_out"> <?php timeDropDown(stripslashes($obj{"hha_visit_time_out"}))?> </select> </TD> </TR> </TABLE> <table class="formtable" width="100%" border="1" cellpadding="5px" cellspacing="0px"> <tr><TD> <table class="formtable" width="100%" border="0"> <tr border="0"> <td width="70%" align="right" style="border-right-style:none;"> <b><?php xl('When completing, be sure to follow the Aide Assignment Sheet (form 3574/3) codes.','e') ?></b> </td> <td align="right" width="30%" style="border-left-style:none;"> <label><b><?php xl('EMPLOYEE NAME:','e')?></b> <input type="text" name="hha_visit_employee_name" size="10" value="<?php echo $obj{"hha_visit_employee_name"}; ?>" /> </label><br /> <label><b><?php xl('EMPLOYEE NO:','e')?></b> <input type="text" name="hha_visit_employee_no" size="10" value="<?php echo $obj{"hha_visit_employee_no"}; ?>" /> </label> </td> </tr> </table> </TD></tr> <tr> <TD colspan="2"> <table width="95%" border="0" align="center" class="formtable"> <tr align="center"> <TD> <b><?php xl('ACTIVITIES','e')?></b> </td> <TD> <b><?php xl('COMMENTS(All comments must be dated)','e')?></b> </td> </tr> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Bath - Tub/Shower','e')?>" <?php if(in_array("Bath - Tub/Shower",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Bath - Tub/Shower','e')?> </label></TD> <TD> <input type="text" name="hha_visit_bath" size="50%" value="<?php echo $obj{"hha_visit_bath"}; ?>" /> <?php echo goals_date('hha_visit_bath_date',$obj{"hha_visit_bath_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Bed Bath - Partial/Complete','e')?>" <?php if(in_array("Bed Bath - Partial/Complete",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Bed Bath - Partial/Complete','e')?> </label></TD> <TD> <input type="text" name="hha_visit_bed_bath" size="50%" value="<?php echo $obj{"hha_visit_bed_bath"}; ?>" /> <?php echo goals_date('hha_visit_bed_bath_date',$obj{"hha_visit_bed_bath_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Assist Bath - Chair','e')?>" <?php if(in_array("Assist Bath - Chair",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Assist Bath - Chair','e')?> </label></TD> <TD> <input type="text" name="hha_visit_assist_bath" size="50%" value="<?php echo $obj{"hha_visit_assist_bath"}; ?>" /> <?php echo goals_date('hha_visit_assist_bath_date',$obj{"hha_visit_assist_bath_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Personal Care','e')?>" <?php if(in_array("Personal Care",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Personal Care','e')?> </label></TD> <TD> <input type="text" name="hha_visit_personal_care" size="50%" value="<?php echo $obj{"hha_visit_personal_care"}; ?>" /> <?php echo goals_date('hha_visit_personal_care_date',$obj{"hha_visit_personal_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Assist with dressing','e')?>" <?php if(in_array("Assist with dressing",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Assist with dressing','e')?> </label></TD> <TD> <input type="text" name="hha_visit_assist_with_dressing" size="50%" value="<?php echo $obj{"hha_visit_assist_with_dressing"}; ?>" /> <?php echo goals_date('hha_visit_assist_with_dressing_date',$obj{"hha_visit_assist_with_dressing_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Hair care - brush/shampoo/other','e')?>" <?php if(in_array("Hair care - brush/shampoo/other",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Hair care - brush/shampoo/other','e')?> </label></TD> <TD> <input type="text" name="hha_visit_hair_care" size="50%" value="<?php echo $obj{"hha_visit_hair_care"}; ?>" /> <?php echo goals_date('hha_visit_hair_care_date',$obj{"hha_visit_hair_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Skin Care/Foot Care (Hygiene)','e')?>" <?php if(in_array("Skin Care/Foot Care (Hygiene)",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Skin Care/Foot Care (Hygiene)','e')?> </label></TD> <TD> <input type="text" name="hha_visit_skin_care" size="50%" value="<?php echo $obj{"hha_visit_skin_care"}; ?>" /> <?php echo goals_date('hha_visit_skin_care_date',$obj{"hha_visit_skin_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Check pressure areas','e')?>" <?php if(in_array("Skin Care/Foot Care (Hygiene)",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Check pressure areas','e')?> </label></TD> <TD> <input type="text" name="hha_visit_check_pressure_areas" size="50%" value="<?php echo $obj{"hha_visit_check_pressure_areas"}; ?>" /> <?php echo goals_date('hha_visit_check_pressure_areas_date',$obj{"hha_visit_check_pressure_areas_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Shave/Groom/Deodorant','e')?>" <?php if(in_array("Shave/Groom/Deodorant",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Shave/Groom/Deodorant','e')?> </label></TD> <TD> <input type="text" name="hha_visit_shave_groom" size="50%" value="<?php echo $obj{"hha_visit_shave_groom"}; ?>" /> <?php echo goals_date('hha_visit_shave_groom_date',$obj{"hha_visit_shave_groom_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Nail Hygiene - clean/file/report','e')?>" <?php if(in_array("Nail Hygiene - clean/file/report",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Nail Hygiene - clean/file/report','e')?> </label></TD> <TD> <input type="text" name="hha_visit_nail_hygiene" size="50%" value="<?php echo $obj{"hha_visit_nail_hygiene"}; ?>" /> <?php echo goals_date('hha_visit_nail_hygiene_date',$obj{"hha_visit_nail_hygiene_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Oral Care - brush/swab/dentures','e')?>" <?php if(in_array("Oral Care - brush/swab/dentures",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Oral Care - brush/swab/dentures','e')?> </label></TD> <TD> <input type="text" name="hha_visit_oral_care" size="50%" value="<?php echo $obj{"hha_visit_oral_care"}; ?>" /> <?php echo goals_date('hha_visit_oral_care_date',$obj{"hha_visit_oral_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Elimination Assist','e')?>" <?php if(in_array("Elimination Assist",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Elimination Assist','e')?> </label></TD> <TD> <input type="text" name="hha_visit_elimination_assist" size="50%" value="<?php echo $obj{"hha_visit_elimination_assist"}; ?>" /> <?php echo goals_date('hha_visit_elimination_assist_date',$obj{"hha_visit_elimination_assist_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Catheter Care','e')?>" <?php if(in_array("Catheter Care",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Catheter Care','e')?> </label></TD> <TD> <input type="text" name="hha_visit_catheter_care" size="50%" value="<?php echo $obj{"hha_visit_catheter_care"}; ?>" /> <?php echo goals_date('hha_visit_catheter_care_date',$obj{"hha_visit_catheter_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Ostomy Care','e')?>" <?php if(in_array("Ostomy Care",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Ostomy Care','e')?> </label></TD> <TD> <input type="text" name="hha_visit_ostomy_care" size="50%" value="<?php echo $obj{"hha_visit_ostomy_care"}; ?>" /> <?php echo goals_date('hha_visit_ostomy_care_date',$obj{"hha_visit_ostomy_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Record Output/Input','e')?>" <?php if(in_array("Record Output/Input",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Record Output/Input','e')?> </label></TD> <TD> <input type="text" name="hha_visit_record" size="50%" value="<?php echo $obj{"hha_visit_record"}; ?>" /> <?php echo goals_date('hha_visit_record_date',$obj{"hha_visit_record_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Inspect/Reinforce Dressing','e')?>" <?php if(in_array("Inspect/Reinforce Dressing",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Inspect/Reinforce Dressing','e')?> </label></TD> <TD> <input type="text" name="hha_visit_inspect_reinforce" size="50%" value="<?php echo $obj{"hha_visit_inspect_reinforce"}; ?>" /> <?php echo goals_date('hha_visit_inspect_reinforce_date',$obj{"hha_visit_inspect_reinforce_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Assist with Medications','e')?>" <?php if(in_array("Assist with Medications",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Assist with Medications','e')?> </label></TD> <TD> <input type="text" name="hha_visit_assist_with_medications" size="50%" value="<?php echo $obj{"hha_visit_assist_with_medications"}; ?>" /> <?php echo goals_date('hha_visit_assist_with_medications_date',$obj{"hha_visit_assist_with_medications_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('T - Oral/Axillary/Rectal','e')?>" <?php if(in_array("T - Oral/Axillary/Rectal",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('T - Oral/Axillary/Rectal','e')?> </label></TD> <TD> <input type="text" name="hha_visit_T" size="50%" value="<?php echo $obj{"hha_visit_T"}; ?>" /> <?php echo goals_date('hha_visit_T_date',$obj{"hha_visit_T_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Pulse - Site and Result','e')?>" <?php if(in_array("Pulse - Site and Result",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Pulse - Site and Result','e')?> </label></TD> <TD> <input type="text" name="hha_visit_pulse" size="50%" value="<?php echo $obj{"hha_visit_pulse"}; ?>" /> <?php echo goals_date('hha_visit_pulse_date',$obj{"hha_visit_pulse_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Respirations - Results','e')?>" <?php if(in_array("Respirations - Results",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Respirations - Results','e')?> </label></TD> <TD> <input type="text" name="hha_visit_respirations" size="50%" value="<?php echo $obj{"hha_visit_respirations"}; ?>" /> <?php echo goals_date('hha_visit_respirations_date',$obj{"hha_visit_respirations_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('BP - Site and Results','e')?>" <?php if(in_array("BP - Site and Results",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('BP - Site and Results','e')?> </label></TD> <TD> <input type="text" name="hha_visit_BP" size="50%" value="<?php echo $obj{"hha_visit_BP"}; ?>" /> <?php echo goals_date('hha_visit_BP_date',$obj{"hha_visit_BP_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Weight - Results','e')?>" <?php if(in_array("Weight - Results",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Weight - Results','e')?> </label></TD> <TD> <input type="text" name="hha_visit_weight" size="50%" value="<?php echo $obj{"hha_visit_weight"}; ?>" /> <?php echo goals_date('hha_visit_weight_date',$obj{"hha_visit_weight_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Ambulation Assist - WC/Walker/Cane','e')?>" <?php if(in_array("Ambulation Assist - WC/Walker/Cane",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Ambulation Assist - WC/Walker/Cane','e')?> </label></TD> <TD> <input type="text" name="hha_visit_ambulation_assist" size="50%" value="<?php echo $obj{"hha_visit_ambulation_assist"}; ?>" /> <?php echo goals_date('hha_visit_ambulation_assist_date',$obj{"hha_visit_ambulation_assist_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Mobility Assist','e')?>" <?php if(in_array("Mobility Assist",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Mobility Assist','e')?> </label></TD> <TD> <input type="text" name="hha_visit_mobility_assist" size="50%" value="<?php echo $obj{"hha_visit_mobility_assist"}; ?>" /> <?php echo goals_date('hha_visit_mobility_assist_date',$obj{"hha_visit_mobility_assist_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('ROM - Active/Passive','e')?>" <?php if(in_array("ROM - Active/Passive",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('ROM - Active/Passive','e')?> </label></TD> <TD> <input type="text" name="hha_visit_ROM" size="50%" value="<?php echo $obj{"hha_visit_ROM"}; ?>" /> <?php echo goals_date('hha_visit_ROM_date',$obj{"hha_visit_ROM_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Positioning - Encourage/Assist to turn q hrs','e')?>" <?php if(in_array("Positioning - Encourage/Assist to turn q hrs",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Positioning - Encourage/Assist to turn q hrs','e')?> </label></TD> <TD> <input type="text" name="hha_visit_positioning" size="50%" value="<?php echo $obj{"hha_visit_positioning"}; ?>" /> <?php echo goals_date('hha_visit_positioning_date',$obj{"hha_visit_positioning_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Exercise - per PT/OT/SLP Care Plan','e')?>" <?php if(in_array("Exercise - per PT/OT/SLP Care Plan",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Exercise - per PT/OT/SLP Care Plan','e')?> </label></TD> <TD> <input type="text" name="hha_visit_exercise" size="50%" value="<?php echo $obj{"hha_visit_exercise"}; ?>" /> <?php echo goals_date('hha_visit_exercise_date',$obj{"hha_visit_exercise_date"}); ?> </TD> </TR> <tr> <TD width="30"><label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Diet Order','e')?>" <?php if(in_array("Diet Order",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Diet Order:','e')?> </label> <input type="text" name="hha_visit_diet_order1" size="30%" value="<?php echo $obj{"hha_visit_diet_order1"}; ?>" /> </TD> <TD> <input type="text" name="hha_visit_diet_order" size="50%" value="<?php echo $obj{"hha_visit_diet_order"}; ?>" /> <?php echo goals_date('hha_visit_diet_order_date',$obj{"hha_visit_diet_order_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Meal Preparation','e')?>" <?php if(in_array("Meal Preparation",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Meal Preparation','e')?> </label></TD> <TD> <input type="text" name="hha_visit_meal_preparation" size="50%" value="<?php echo $obj{"hha_visit_meal_preparation"}; ?>" /> <?php echo goals_date('hha_visit_meal_preparation_date',$obj{"hha_visit_meal_preparation_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Assist with Feeding','e')?>" <?php if(in_array("Assist with Feeding",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Assist with Feeding','e')?> </label></TD> <TD> <input type="text" name="hha_visit_assist_with_feeding" size="50%" value="<?php echo $obj{"hha_visit_assist_with_feeding"}; ?>" /> <?php echo goals_date('hha_visit_assist_with_feeding_date',$obj{"hha_visit_assist_with_feeding_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Limit/Encourage Fluids','e')?>" <?php if(in_array("Limit/Encourage Fluids",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Limit/Encourage Fluids','e')?> </label></TD> <TD> <input type="text" name="hha_visit_limit_encourage_fluids" size="50%" value="<?php echo $obj{"hha_visit_limit_encourage_fluids"}; ?>" /> <?php echo goals_date('hha_visit_limit_encourage_fluids_date',$obj{"hha_visit_limit_encourage_fluids_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Grocery Shopping','e')?>" <?php if(in_array("Grocery Shopping",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Grocery Shopping','e')?> </label></TD> <TD> <input type="text" name="hha_visit_grocery_shopping" size="50%" value="<?php echo $obj{"hha_visit_grocery_shopping"}; ?>" /> <?php echo goals_date('hha_visit_grocery_shopping_date',$obj{"hha_visit_grocery_shopping_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Wash Clothes','e')?>" <?php if(in_array("Wash Clothes",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Wash Clothes','e')?> </label></TD> <TD> <input type="text" name="hha_visit_wash_clothes" size="50%" value="<?php echo $obj{"hha_visit_wash_clothes"}; ?>" /> <?php echo goals_date('hha_visit_wash_clothes_date',$obj{"hha_visit_wash_clothes_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Light HouseKeeping - Bedroom/Bathroom/Kitchen - Change bed linen','e')?>" <?php if(in_array("Light HouseKeeping - Bedroom/Bathroom/Kitchen - Change bed linen",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Light HouseKeeping - Bedroom/Bathroom/Kitchen - Change bed linen','e')?> </label></TD> <TD> <input type="text" name="hha_visit_light_housekeeping" size="50%" value="<?php echo $obj{"hha_visit_light_housekeeping"}; ?>" /> <?php echo goals_date('hha_visit_light_housekeeping_date',$obj{"hha_visit_light_housekeeping_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Observe Universal Precautions','e')?>" <?php if(in_array("Observe Universal Precautions",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Observe Universal Precautions','e')?> </label></TD> <TD> <input type="text" name="hha_visit_observe_universal_precaution" size="50%" value="<?php echo $obj{"hha_visit_observe_universal_precaution"}; ?>" /> <?php echo goals_date('hha_visit_observe_universal_precaution_date',$obj{"hha_visit_observe_universal_precaution_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Equipment Care','e')?>" <?php if(in_array("Equipment Care",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Equipment Care','e')?> </label></TD> <TD> <input type="text" name="hha_visit_equipment_care" size="50%" value="<?php echo $obj{"hha_visit_equipment_care"}; ?>" /> <?php echo goals_date('hha_visit_equipment_care_date',$obj{"hha_visit_equipment_care_date"}); ?> </TD> </TR> <tr> <TD width="30"> <label> <input type="checkbox" name="hha_visit_activities[]" value="<?php xl('Washing hands before and after services','e')?>" <?php if(in_array("Washing hands before and after services",$hha_visit_activities)) echo "checked"; ?> /> <?php xl('Washing hands before and after services','e')?> </label></TD> <TD> <input type="text" name="hha_visit_washing_hands" size="50%" value="<?php echo $obj{"hha_visit_washing_hands"}; ?>" /> <?php echo goals_date('hha_visit_washing_hands_date',$obj{"hha_visit_washing_hands_date"}); ?> </TD> </TR> </table> <table width="100%" class="formtable" border="0"> <TR> <TD> <b><?php xl('SIGNATURE/DATES','e')?></b> </TD> </TR> <TR><TD> <b><?php xl('Patient/ Client','e')?></b> <input type="text" name="hha_visit_patient_client_sign" size="50%" value="<?php echo $obj{"hha_visit_patient_client_sign"}; ?>" /> </TD> <td rowspan="2"> <b><?php xl('Date','e')?></b> <input type='text' size='10' name='hha_visit_patient_client_sign_date' id='hha_visit_patient_client_sign_date' title='<?php xl('Date','e'); ?>' onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc);' value="<?php echo $obj{"hha_visit_patient_client_sign_date"}; ?>" readonly/> <img src='../../pic/show_calendar.gif' align='absbottom' width='24' height='22' id='img_curr_date7' border='0' alt='[?]' style='cursor: pointer; cursor: hand' title='<?php xl('Click here to choose a date','e'); ?>'> <script LANGUAGE="JavaScript"> Calendar.setup({inputField:"hha_visit_patient_client_sign_date", ifFormat:"%Y-%m-%d", button:"img_curr_date7"}); </script> </td> </TR> </table> </TD> </tr> <tr><TD colspan="2"> <?php xl('Supplies Used','e')?> <label><input type="radio" name="hha_visit_supplies_used" value="Yes" id="hha_visit_supplies_used" <?php if($obj{"hha_visit_supplies_used"}=="Yes") echo "checked"; ?> /> <?php xl('Yes','e')?></label> <label><input type="radio" name="hha_visit_supplies_used" value="No" id="hha_visit_supplies_used" <?php if($obj{"hha_visit_supplies_used"}=="No") echo "checked"; ?> /> <?php xl('No','e')?></label> <br /> <textarea name="hha_visit_supplies_used_data" rows="4" cols="98"> <?php echo $obj{"hha_visit_supplies_used_data"}; ?> </textarea> </TD> </tr> <tr><TD> <b><?php xl('This form has been electronically signed by:','e')?></b> </TD></tr> </table> <br /> <a href="javascript:top.restoreSession();document.hha_visit.submit();" class="link_submit" onClick="return requiredCheck()"><?php xl(' [Save]','e')?></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="<?php echo $GLOBALS['form_exit_url']; ?>" class="link" style="color: #483D8B" onclick="top.restoreSession()">[<?php xl('Don\'t Save','e'); ?>]</a> </form> <center> <table> <tr> <td align="center"> <?php if($action == "edit") { ?> <input type="submit" name="Submit" value="Save Form" > &nbsp;&nbsp; <? } ?> </form> <input type="button" value="Back" onClick="top.restoreSession();window.location='<?php echo $GLOBALS['webroot'] ?>/interface/patient_file/encounter/encounter_top.php';"/>&nbsp;&nbsp; <?php if($action == "review") { ?> <input type="button" value="Sign" id="signoff" href="#login_form" <?php echo $signDisabled;?> /> <? } ?> </td> </tr> <tr><td> <div id="signature_log" name="signature_log"> <?php $esign->getDefaultSignatureLog(true);?> </div> </td></tr> </table> </center> </body> <div style="display:none"> <form id="login_form" method="post" action=""> <p><center><span style="font-size:small;"> <p id="login_prompt" style="font-size:small;">Enter your password to sign:</p> <input type="hidden" name="sig_status" value="approved" /> <input type="hidden" id="tid" name="tid" value="<?php echo $id;?>"/> <input type="hidden" id="table_name" name="table_name" value="<?php echo $formTable;?>"/> <input type="hidden" id="signature_uid" name="signature_uid" value="<?php echo $_SESSION['authUserID'];?>"/> <input type="hidden" id="signature_id" name="signature_id" value="<?php echo $sigId->getId();?>" /> <input type="hidden" id="exam_name" name="exam_name" value="<?php echo $registryRow['nickname'];?>" /> <input type="hidden" id="exam_pid" name="exam_pid" value="<?php echo $obj['pid'];?>" /> <input type="hidden" id="exam_date" name="exam_date" value="<?php echo $obj['date'];?>" /> <label for="login_pass">Password: </label> <input type="password" id="login_pass" name="login_pass" size="10" /> </span> </center></p> <p> <input type="submit" value="Sign" /> </p> </form> </div> </body> </html>
gpl-3.0
interspiresource/interspire
install/language/es-MX/default.php
4276
<?php /** * @package Arastta eCommerce * @copyright Copyright (C) 2015 Arastta Association. All rights reserved. (arastta.org) * @credits See CREDITS.txt for credits and other copyright notices. * @license GNU General Public License version 3; see LICENSE.txt */ // Heading $_['heading_main'] = 'Instalador Arastta'; // Button $_['button_back'] = 'Atrás'; $_['button_next'] = 'Siguiente'; $_['button_refresh'] = 'Actualizar'; $_['button_store'] = 'Tienda'; $_['button_admin'] = 'Administrador'; // Text $_['text_database'] = 'Base de datos'; $_['text_settings'] = 'Ajustes'; $_['text_finish'] = 'Finalizar'; $_['text_database_header'] = 'Introduzca los detalles de la base de datos.'; $_['text_settings_header'] = 'Introduzca las configuraciones de la Tienda.'; $_['text_advanced'] = 'Avanzado'; $_['text_finish_header'] = '¡Felicidades! Arastta ya está instalado.'; // Entry $_['entry_db_hostname'] = 'Nombre del Host'; $_['entry_db_username'] = 'Nombre de Usuario'; $_['entry_db_password'] = 'Contraseña'; $_['entry_db_database'] = 'Nombre Base de datos'; $_['entry_db_prefix'] = 'Prefijo Tablas'; $_['entry_db_driver'] = 'Conductor'; $_['entry_store_name'] = 'Nombre de Tienda'; $_['entry_store_email'] = 'Correo electrónico de la Tienda'; $_['entry_admin_username'] = 'Usuario Administrador'; $_['entry_admin_email'] = 'Correo electrónico del Administrador'; $_['entry_admin_password'] = 'Contraseña Administrador'; $_['entry_admin_first_name'] = 'Administrador, primer Nombre'; $_['entry_admin_last_name'] = 'Administrador, Apellidos'; $_['entry_install_demo_data'] = 'Instalar datos demostrativos'; // Help $_['help_db_hostname'] = 'Normalmente: localhost'; $_['help_db_username'] = 'Tu usuario de MySQL'; $_['help_db_password'] = 'Tu contraseña de MySQL'; $_['help_db_database'] = 'La Base de Datos que desea ejecutar en Arastta'; $_['help_db_prefix'] = 'Prefijo para múltiples instalaciones en una base de datos'; $_['help_store_name'] = 'Nombre de tu tienda, utilizado en todas partes'; $_['help_store_email'] = 'E-mail de tu tienda, que se utiliza en todas partes'; $_['help_admin_username'] = 'Nombre de usuario de la cuenta de administrador'; $_['help_admin_email'] = 'E-mail de la cuenta de administrador'; $_['help_admin_password'] = 'Contraseña de la cuenta de administrador'; $_['help_admin_first_name'] = 'Administrador, Primer Nombre'; $_['help_admin_last_name'] = 'Administrador, Apellidos'; // Error $_['error_db_hostname'] = '¡Se requiere un Nombre de Host!'; $_['error_db_username'] = '¡Nombre Usuario requerido!'; $_['error_db_database'] = '¡Se requiere un Nombre de Base de Datos!'; $_['error_db_prefix'] = 'El prefijo de la Tabla solo puede contener caracteres en minúsculas en un rango a-z, 0-9 o guiones bajos'; $_['error_db_connect'] = '<br/>Error: ¡No es posible conectar con la base de datos!, Por favor, revise si los datos introducidos son correctos.'; $_['error_config'] = 'Error: ¡No se pudo escribir en el archivo config.php. Por favor, comprueba que has configurado los permisos CHMOD correctos!'; $_['error_store_name'] = '¡Nombre de la Tienda requerido!'; $_['error_store_email'] = '¡Correo electrónico de la Tienda requerido!'; $_['error_admin_username'] = '¡Nombre Usuario requerido!'; $_['error_admin_email'] = '¡Correo electrónico no válido!'; $_['error_admin_password'] = '¡Se requiere Contraseña!'; $_['error_admin_first_name'] = '¡El Primer Nombre del Administrador es necesario!'; $_['error_admin_last_name'] = '¡El Apellido del Administrador es necesario!'; $_['error_remove_install'] = 'No se pudo eliminar el directorio de instalación. Por favor, elimínelo manualmente por motivos de seguridad.'; $_['error_lang_code'] = 'Es necesario seleccionar un idioma, por favor, seleccione uno.'; $_['error_lang_download'] = '¿No es capaz de descargar el idioma seleccionado?, por favor, elija otro.';
gpl-3.0
Benjimoro/DnrFiles
ausgsMultiTS.py
3017
# -*- coding: utf-8 -*- """ Created on Fri Jul 08 14:13:23 2016 @author: bbwarne """ from azure.storage.blob import BlockBlobService from azure.storage.blob import ContentSettings import requests import datetime today = datetime.date.today() lastmonth = today.month-1 rTS = requests.get('http://waterservices.usgs.gov/nwis/iv/?format=json,1.1&indent=on&stateCd=sc&startDT={0}-{2}-{1}&endDT={0}-{3}-{1}&parameterCd=00060,00065'.format(today.year,today.day,lastmonth,today.month)) tsdata = rTS.json()['value']['timeSeries'] import json with open('usgsDatTS.json', 'w') as outfile: json.dump(tsdata, outfile, sort_keys=True, indent=2, separators=(',',': ')) block_blob_service = BlockBlobService(account_name='usgsstorage', account_key='KASxRSxKQscbwVvd/zFtln+9wspqq/gae4+8V57xPLodmZvg9Wx29rAOa8a2a/TBgNy2/69MiWoaGpzaCH+MWQ==') block_blob_service.create_blob_from_path( 'usgspulled', 'blockblobJSONts', 'usgsDatTS.json', content_settings=ContentSettings(content_type='text/json') ) testTS = tsdata tsFlowValList = [] tsHeightValList = [] for i in range(0,len(testTS)): for j in range(0,len(testTS[i]['values'][0]['value'])): if(testTS[i]['variable']['unit']['unitCode']== u'ft'): tsHeightValList.append({u'sitename': testTS[i]['sourceInfo']['siteName'], u'value': float(testTS[i]['values'][0]['value'][j]['value']), u'units': testTS[i]['variable']['unit']['unitCode'], u'description': testTS[i]['variable']['variableDescription'], u'dateTime':testTS[i]['values'][0]['value'][j]['dateTime'] }) if(testTS[i]['variable']['unit']['unitCode']== u'ft3/s'): tsFlowValList.append({u'sitename': testTS[i]['sourceInfo']['siteName'], u'value': float(testTS[i]['values'][0]['value'][j]['value']), u'units': testTS[i]['variable']['unit']['unitCode'], u'description': testTS[i]['variable']['variableDescription'], u'dateTime':testTS[i]['values'][0]['value'][j]['dateTime'] }) import csv fieldNamTS = [u'sitename',u'value',u'units',u'description',u'dateTime'] with open('usgsTSFvalues.csv', 'w') as tsFfile: wr = csv.DictWriter(tsFfile,fieldnames=fieldNamTS) wr.writerows(tsFlowValList) with open('usgsTSHvalues.csv', 'w') as tsHfile: wr = csv.DictWriter(tsHfile,fieldnames=fieldNamTS) wr.writerows(tsHeightValList) block_blob_service.create_blob_from_path( 'usgspulled', 'tsfblobCSV', 'usgsTSFvalues.csv', content_settings=ContentSettings(content_type='text/csv') ) block_blob_service.create_blob_from_path( 'usgspulled', 'tsHblobCSV', 'usgsTSHvalues.csv', content_settings=ContentSettings(content_type='text/csv') )
gpl-3.0
AdeebNqo/Thula
Thula/src/main/java/com/adeebnqo/Thula/ui/messagelist/MessageItemCache.java
1863
package com.adeebnqo.Thula.ui.messagelist; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.util.LruCache; import com.google.android.mms.MmsException; import com.adeebnqo.Thula.common.utils.CursorUtils; import java.util.regex.Pattern; public class MessageItemCache extends LruCache<Long, MessageItem> { private final String TAG = "MessageItemCache"; private Context mContext; private MessageColumns.ColumnsMap mColumnsMap; private Pattern mSearchHighlighter; public MessageItemCache(Context context, MessageColumns.ColumnsMap columnsMap, Pattern searchHighlighter, int maxSize) { super(maxSize); mContext = context; mColumnsMap = columnsMap; mSearchHighlighter = searchHighlighter; } @Override protected void entryRemoved(boolean evicted, Long key, MessageItem oldValue, MessageItem newValue) { oldValue.cancelPduLoading(); } /** * Generates a unique key for this message item given its type and message ID. * * @param type * @param msgId */ public long getKey(String type, long msgId) { if (type.equals("mms")) { return -msgId; } else { return msgId; } } public MessageItem get(String type, long msgId, Cursor c) { long key = getKey(type, msgId); MessageItem item = get(key); if (item == null && CursorUtils.isValid(c)) { try { item = new MessageItem(mContext, type, c, mColumnsMap, mSearchHighlighter, false); key = getKey(item.mType, item.mMsgId); put(key, item); } catch (MmsException e) { Log.e(TAG, "getCachedMessageItem: ", e); } } return item; } }
gpl-3.0
uwafsl/ardupilot
libraries/OrbitControl/InnerLoopController.cpp
7951
// InnerLoopController.cpp: implementation of the InnerLoopController class. // // Christopher Lum // lum@u.washington.edu // // Dai Tsukada // dat6@uw.edu // ////////////////////////////////////////////////////////////////////// //Version History // 03/31/15: Created // standard headers //#include <iostream> //cout, endl, cerr //#include <string> //string //#include <vector> //vector #include <math.h> //min, max // local header files #include "InnerLoopController.h" //InnerLoopController class #include "ControlSurfaceDeflections.h" //ControlSurfaceDeflections class // using declaration ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- //// /// Default constructor. /// /// Input: -none /// /// Output: -none /// /// Side-effects: -none //// InnerLoopController::InnerLoopController() { kPhi = 3; // roll loop forward gain kP = 0.5; // roll loop damping gain kR = 1; // yaw damper gain kTheta = 3; // pitch loop forward gain kQ = 0.5; // pitch loop damping gain kAlt = 0.5; // altitude loop forward gain // initialize integrators intYawDamper = 0; intAltitude = 0; // initialize previous values for input last_psiDotErr = 0; last_p = 0; last_q = 0; last_r = 0; last_phi = 0; last_theta = 0; last_uB = 0; last_vB = 0; last_wB = 0; //last_rad_ref = 0; last_rad_act = 0; //Ryan Grimes added rad_act information last_alt_ref = 0; last_alt = 0; last_dt = 0; } //------------------------------------------------------------------------- //// /// Destructor //// InnerLoopController::~InnerLoopController() { } ////////////////////////////////////////////////////////////////////// // Overloaded operators ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Public interface methods ////////////////////////////////////////////////////////////////////// /// Compute control input /// /// Input: - psiDotErr = heading rate error computed in outer loop controller (rad/s) /// - p = roll rate (rad/s) /// - q = pitch rate (rad/s) /// - r = yaw rate (rad/s) /// - phi = bank angle (rad) /// - theta = pitch angle (rad) /// - uB = velocity in x-direction (m/s) /// - vB = velocity in y-direction (m/s) /// - wB = velocity in z-direction (m/s) /// - rad_ref = reference radius (m) /// - rad_act = actual radius (m) /// - alt_ref = reference altitude (m) /// - alt = actual altitude (m) /// - dt = sample time (s) /// /// Output: - dA = Aileron deflection (rad) /// - dE = Elevator deflection (rad) /// - dR = Rudder deflection (rad) /// /// Side-effects: - none //// ControlSurfaceDeflections InnerLoopController::computeControl(double psiDotErr, double p, double q, double r, double phi, double theta, double uB, double vB, double wB, double rad_act, double alt_ref, double alt, double dt) { //// /// Check input data range (subject to change depending on aircraft specification) //// if (psiDotErr>1 || psiDotErr<-1) { // invalid signal from outer loop controller //throw std::runtime_error("InnerLoopController Error: Invalid outer loop signal"); //ControlSurfaceDeflections U = ControlSurfaceDeflections(); //return(U); psiDotErr = last_psiDotErr; } //if(p>0.9 || p<-0.9 || q>0.9 || q<-0.9|| r>0.5 || r<-0.5 // || phi>1 || phi<-1 || theta>1.2 || theta<-1.2 // || uB>100 || uB<-100 || vB>100 || vB<-100 || wB>30 || wB<-30 // || alt>6000 || alt<-100) //{ // // invalid state (inertial measurement) input // //throw std::runtime_error("InnerLoopController Error: Invalid state input"); // //ControlSurfaceDeflections U = ControlSurfaceDeflections(); // //return(U); //} // invalid state (inertial measurement) input if (p>0.9 || p<-0.9) { p = last_p; } if (q>0.9 || q<-0.9) { q = last_q; } if (r>0.5 || r<-0.5) { r = last_r; } if (phi>1 || phi<-1) { phi = last_phi; } if (theta>1.2 || theta<-1.2) { theta = last_theta; } if (uB>100 || uB<-100) { uB = last_uB; } if (vB>100 || vB<-100) { vB = last_vB; } if (wB>30 || wB<-30) { wB = last_wB; } if (alt>6000 || alt<-100) { alt = last_alt; } //if (rad_ref>10000 || rad_ref<0) { // invalid reference radius input //rad_ref = last_rad_ref; //} if (rad_act>10000 || rad_act<0) { // invalid actual radius input rad_act = last_rad_act; } if (alt_ref>5000 || alt_ref<0) { // invalid altitude reference input alt_ref = last_alt_ref; } if (dt == 0) { // invalid time step dt = last_dt; } //// /// Define Constants //// const double g = 9.80665; const double pi = 3.14159; //// /// Inner Loop Interface //// //Ryan Grimes reference heading rate to be (vA/rad_act) instead of (vA/rad_ref) //Ryan Grimes updated r_ref equation to multiply by cos(phi) instead of dividing by cos(phi) double vA = sqrt(uB*uB + vB*vB + wB*wB); double psiDot = psiDotErr + (vA/rad_act); //Ryan Grimes added rad_act information double r_ref = (vA/rad_act)*cos(phi); //Reference yaw //// /// Roll Inner Loop //// double phi_cmd = atan((psiDot*vA) * (1/g)); //Ryan Grimes implemented limitations on desired bank angle if (phi_cmd < -60*(pi/180)) { phi_cmd = -60*(pi/180); } else if (phi_cmd > 60*(pi/180)) { phi_cmd = 60*(pi/180); } double phi_e = phi_cmd - phi; double dA = -(phi_e*kPhi - p*kP); //// /// Yaw Damper //// double r_e = r_ref - r; //intYawDamper += (kR/5)*r_e*dt; // signal saturation //if (intYawDamper < -0.7) { //intYawDamper = -0.7; //} else if (intYawDamper > 0.7) { //intYawDamper = 0.7; //} //double dR = -(r_e*kR + intYawDamper); double dR = -(r_e*kR); //// /// Altitude Loop //// double alt_e = alt_ref - alt; intAltitude += (kAlt/15)*alt_e*dt; // signal saturation if (intAltitude < -60) { intAltitude = -60; } else if (intAltitude > 60) { intAltitude = 60; } double theta_cmd = (alt_e*kAlt + intAltitude) * (pi/180); // Ryan Grimes implemented limitations on desired pitch if (theta_cmd < -45*(pi/180)) { theta_cmd = -45*(pi/180); } else if (theta_cmd > 45*(pi/180)) { theta_cmd = 45*(pi/180); } //// /// Pitch Inner Loop //// double theta_e = theta_cmd - theta; double dE = -(theta_e*kTheta - q*kQ); // save input information last_psiDotErr = psiDotErr; last_p = p; last_q = q; last_r = r; last_phi = phi; last_theta = theta; last_uB = uB; last_vB = vB; last_wB = wB; //last_rad_ref = rad_ref; last_rad_act = rad_act; // Ryan Grimes added rad_act information last_alt_ref = alt_ref; last_alt = alt; last_dt = dt; // instantiate control surface deflection object (data type to store control inputs) ControlSurfaceDeflections U = ControlSurfaceDeflections(); U.SetAileron(dA); U.SetRudder(dR); U.SetElevator(dE); return(U); } ////////////////////////////////////////////////////////////////////// // Get/Set Functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Global functions ////////////////////////////////////////////////////////////////////// //==================== End of File =================================
gpl-3.0
jindrapetrik/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/abc/avm2/instructions/other/InitPropertyIns.java
2413
/* * Copyright (C) 2010-2021 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.abc.avm2.instructions.other; import com.jpexs.decompiler.flash.abc.ABC; import com.jpexs.decompiler.flash.abc.AVM2LocalData; import com.jpexs.decompiler.flash.abc.avm2.AVM2Code; import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction; import com.jpexs.decompiler.flash.abc.avm2.instructions.InstructionDefinition; import com.jpexs.decompiler.flash.abc.avm2.model.FullMultinameAVM2Item; import com.jpexs.decompiler.flash.abc.avm2.model.InitPropertyAVM2Item; import com.jpexs.decompiler.graph.GraphTargetItem; import com.jpexs.decompiler.graph.TranslateStack; import java.util.List; /** * * @author JPEXS */ public class InitPropertyIns extends InstructionDefinition { public InitPropertyIns() { super(0x68, "initproperty", new int[]{AVM2Code.DAT_MULTINAME_INDEX}, true); } @Override public void translate(AVM2LocalData localData, TranslateStack stack, AVM2Instruction ins, List<GraphTargetItem> output, String path) { int multinameIndex = ins.operands[0]; GraphTargetItem val = stack.pop(); FullMultinameAVM2Item multiname = resolveMultiname(localData, true, stack, localData.getConstants(), multinameIndex, ins); GraphTargetItem obj = stack.pop(); InitPropertyAVM2Item result = new InitPropertyAVM2Item(ins, localData.lineStartInstruction, obj, multiname, val); SetPropertyIns.handleCompound(localData, obj, multiname, val, output, result); output.add(result); } @Override public int getStackPopCount(AVM2Instruction ins, ABC abc) { int multinameIndex = ins.operands[0]; return 2 + getMultinameRequiredStackSize(abc.constants, multinameIndex); } }
gpl-3.0
cstrouse/chromebrew
packages/ledger.rb
763
require 'package' class Ledger < Package description 'A double-entry accounting system with a command-line reporting interface' homepage 'https://www.ledger-cli.org/' version '3.1.3' compatibility 'all' source_url 'https://github.com/ledger/ledger/archive/v3.1.3.tar.gz' source_sha256 'b248c91d65c7a101b9d6226025f2b4bf3dabe94c0c49ab6d51ce84a22a39622b' binary_url ({ aarch64: '', armv7l: '', i686: '', x86_64: '', }) binary_sha256 ({ aarch64: '', armv7l: '', i686: '', x86_64: '', }) depends_on 'boost' => :build def self.build system './acprep', "--prefix=#{CREW_PREFIX}" system 'make' end def self.install system 'make', "DESTDIR=#{CREW_DEST_DIR}", 'install/strip' end end
gpl-3.0
szwedoman/SzUM
src/main/java/pl/szwedoman/szum/item/armor/ArmorSzum.java
1469
package pl.szwedoman.szum.item.armor; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import pl.szwedoman.szum.creativetab.CreativeTabSzUM; import pl.szwedoman.szum.reference.Reference; public class ArmorSzum extends ItemArmor { public ArmorSzum(ArmorMaterial p_i45325_1_, int p_i45325_2_, int p_i45325_3_) { super(p_i45325_1_, p_i45325_2_, p_i45325_3_); this.setCreativeTab(CreativeTabSzUM.SzUM_TAB); } @Override public String getUnlocalizedName() { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName(ItemStack itemStack) { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); }; }
gpl-3.0
frostasm/qt-creator
src/plugins/coreplugin/coreplugin.cpp
11810
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "coreplugin.h" #include "designmode.h" #include "editmode.h" #include "idocument.h" #include "helpmanager.h" #include "mainwindow.h" #include "modemanager.h" #include "infobar.h" #include "iwizardfactory.h" #include "themesettings.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/documentmanager.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/find/findplugin.h> #include <coreplugin/locator/locator.h> #include <coreplugin/coreconstants.h> #include <coreplugin/fileutils.h> #include <extensionsystem/pluginerroroverview.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/pathchooser.h> #include <utils/macroexpander.h> #include <utils/savefile.h> #include <utils/stringutils.h> #include <utils/theme/theme.h> #include <utils/theme/theme_p.h> #include <QtPlugin> #include <QDebug> #include <QDateTime> #include <QMenu> #include <QUuid> using namespace Core; using namespace Core::Internal; using namespace Utils; CorePlugin::CorePlugin() : m_mainWindow(0) , m_editMode(0) , m_designMode(0) , m_findPlugin(0) , m_locator(0) { qRegisterMetaType<Id>(); } CorePlugin::~CorePlugin() { IWizardFactory::destroyFeatureProvider(); delete m_findPlugin; delete m_locator; if (m_editMode) { removeObject(m_editMode); delete m_editMode; } if (m_designMode) { if (m_designMode->designModeIsRequired()) removeObject(m_designMode); delete m_designMode; } delete m_mainWindow; setCreatorTheme(0); } void CorePlugin::parseArguments(const QStringList &arguments) { const Id settingsThemeId = Id::fromSetting(ICore::settings()->value( QLatin1String(Constants::SETTINGS_THEME), QLatin1String("default"))); Id themeId = settingsThemeId; QColor overrideColor; bool presentationMode = false; for (int i = 0; i < arguments.size(); ++i) { if (arguments.at(i) == QLatin1String("-color")) { const QString colorcode(arguments.at(i + 1)); overrideColor = QColor(colorcode); i++; // skip the argument } if (arguments.at(i) == QLatin1String("-presentationMode")) presentationMode = true; if (arguments.at(i) == QLatin1String("-theme")) { themeId = Id::fromString(arguments.at(i + 1)); i++; } } const QList<ThemeEntry> availableThemes = ThemeSettings::availableThemes(); int themeIndex = Utils::indexOf(availableThemes, Utils::equal(&ThemeEntry::id, themeId)); if (themeIndex < 0) { themeIndex = Utils::indexOf(availableThemes, Utils::equal(&ThemeEntry::id, settingsThemeId)); } if (themeIndex < 0) themeIndex = 0; if (themeIndex < availableThemes.size()) { const ThemeEntry themeEntry = availableThemes.at(themeIndex); QSettings themeSettings(themeEntry.filePath(), QSettings::IniFormat); Theme *theme = new Theme(themeEntry.id().toString(), qApp); theme->readSettings(themeSettings); if (theme->flag(Theme::ApplyThemePaletteGlobally)) QApplication::setPalette(theme->palette()); setCreatorTheme(theme); } // defer creation of these widgets until here, // because they need a valid theme set m_mainWindow = new MainWindow; ActionManager::setPresentationModeEnabled(presentationMode); m_findPlugin = new FindPlugin; m_locator = new Locator; if (overrideColor.isValid()) m_mainWindow->setOverrideColor(overrideColor); } bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage) { if (ThemeSettings::availableThemes().isEmpty()) { *errorMessage = tr("No themes found in installation."); return false; } new ActionManager(this); Theme::initialPalette(); // Initialize palette before setting it qsrand(QDateTime::currentDateTime().toTime_t()); parseArguments(arguments); const bool success = m_mainWindow->init(errorMessage); if (success) { m_editMode = new EditMode; addObject(m_editMode); ModeManager::activateMode(m_editMode->id()); m_designMode = new DesignMode; InfoBar::initializeGloballySuppressed(); } IWizardFactory::initialize(); // Make sure we respect the process's umask when creating new files SaveFile::initializeUmask(); m_findPlugin->initialize(arguments, errorMessage); m_locator->initialize(this, arguments, errorMessage); MacroExpander *expander = Utils::globalMacroExpander(); expander->registerVariable("CurrentDate:ISO", tr("The current date (ISO)."), []() { return QDate::currentDate().toString(Qt::ISODate); }); expander->registerVariable("CurrentTime:ISO", tr("The current time (ISO)."), []() { return QTime::currentTime().toString(Qt::ISODate); }); expander->registerVariable("CurrentDate:RFC", tr("The current date (RFC2822)."), []() { return QDate::currentDate().toString(Qt::RFC2822Date); }); expander->registerVariable("CurrentTime:RFC", tr("The current time (RFC2822)."), []() { return QTime::currentTime().toString(Qt::RFC2822Date); }); expander->registerVariable("CurrentDate:Locale", tr("The current date (Locale)."), []() { return QDate::currentDate().toString(Qt::DefaultLocaleShortDate); }); expander->registerVariable("CurrentTime:Locale", tr("The current time (Locale)."), []() { return QTime::currentTime().toString(Qt::DefaultLocaleShortDate); }); expander->registerVariable("Config:DefaultProjectDirectory", tr("The configured default directory for projects."), []() { return DocumentManager::projectsDirectory(); }); expander->registerVariable("Config:LastFileDialogDirectory", tr("The directory last visited in a file dialog."), []() { return DocumentManager::fileDialogLastVisitedDirectory(); }); expander->registerVariable("HostOs:isWindows", tr("Is Qt Creator running on Windows?"), []() { return QVariant(Utils::HostOsInfo::isWindowsHost()).toString(); }); expander->registerVariable("HostOs:isOSX", tr("Is Qt Creator running on OS X?"), []() { return QVariant(Utils::HostOsInfo::isMacHost()).toString(); }); expander->registerVariable("HostOs:isLinux", tr("Is Qt Creator running on Linux?"), []() { return QVariant(Utils::HostOsInfo::isLinuxHost()).toString(); }); expander->registerVariable("HostOs:isUnix", tr("Is Qt Creator running on any unix-based platform?"), []() { return QVariant(Utils::HostOsInfo::isAnyUnixHost()).toString(); }); expander->registerPrefix("CurrentDate:", tr("The current date (QDate formatstring)."), [](const QString &fmt) { return QDate::currentDate().toString(fmt); }); expander->registerPrefix("CurrentTime:", tr("The current time (QTime formatstring)."), [](const QString &fmt) { return QTime::currentTime().toString(fmt); }); expander->registerVariable("UUID", tr("Generate a new UUID."), []() { return QUuid::createUuid().toString(); }); expander->registerPrefix("#:", tr("A comment."), [](const QString &) { return QStringLiteral(""); }); // Make sure all wizards are there when the user might access the keyboard shortcuts: connect(ICore::instance(), &ICore::optionsDialogRequested, []() { IWizardFactory::allWizardFactories(); }); Utils::PathChooser::setAboutToShowContextMenuHandler(&CorePlugin::addToPathChooserContextMenu); return success; } void CorePlugin::extensionsInitialized() { if (m_designMode->designModeIsRequired()) addObject(m_designMode); m_findPlugin->extensionsInitialized(); m_locator->extensionsInitialized(); m_mainWindow->extensionsInitialized(); if (ExtensionSystem::PluginManager::hasError()) { auto errorOverview = new ExtensionSystem::PluginErrorOverview(m_mainWindow); errorOverview->setAttribute(Qt::WA_DeleteOnClose); errorOverview->setModal(true); errorOverview->show(); } } bool CorePlugin::delayedInitialize() { HelpManager::setupHelpManager(); m_locator->delayedInitialize(); IWizardFactory::allWizardFactories(); // scan for all wizard factories return true; } QObject *CorePlugin::remoteCommand(const QStringList & /* options */, const QString &workingDirectory, const QStringList &args) { IDocument *res = m_mainWindow->openFiles( args, ICore::OpenFilesFlags(ICore::SwitchMode | ICore::CanContainLineAndColumnNumbers), workingDirectory); m_mainWindow->raiseWindow(); return res; } void CorePlugin::fileOpenRequest(const QString &f) { remoteCommand(QStringList(), QString(), QStringList(f)); } void CorePlugin::addToPathChooserContextMenu(Utils::PathChooser *pathChooser, QMenu *menu) { QList<QAction*> actions = menu->actions(); QAction *firstAction = actions.isEmpty() ? nullptr : actions.first(); auto *showInGraphicalShell = new QAction(Core::FileUtils::msgGraphicalShellAction(), menu); connect(showInGraphicalShell, &QAction::triggered, pathChooser, [pathChooser]() { Core::FileUtils::showInGraphicalShell(pathChooser, pathChooser->path()); }); menu->insertAction(firstAction, showInGraphicalShell); auto *showInTerminal = new QAction(Core::FileUtils::msgTerminalAction(), menu); connect(showInTerminal, &QAction::triggered, pathChooser, [pathChooser]() { Core::FileUtils::openTerminal(pathChooser->path()); }); menu->insertAction(firstAction, showInTerminal); if (firstAction) menu->insertSeparator(firstAction); } ExtensionSystem::IPlugin::ShutdownFlag CorePlugin::aboutToShutdown() { m_findPlugin->aboutToShutdown(); m_mainWindow->aboutToShutdown(); return SynchronousShutdown; }
gpl-3.0
SiLeBAT/FSK-Lab
de.bund.bfr.knime.foodprocess.pcml/lib/src/de/bund/bfr/pcml10/ProcessChainDocument.java
12370
/* * An XML document type. * Localname: ProcessChain * Namespace: http://www.bfr.bund.de/PCML-1_0 * Java type: de.bund.bfr.pcml10.ProcessChainDocument * * Automatically generated - do not modify. */ package de.bund.bfr.pcml10; /** * A document containing one ProcessChain(@http://www.bfr.bund.de/PCML-1_0) element. * * This is a complex type. */ public interface ProcessChainDocument extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ProcessChainDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s121DA543B1FCBC764F9DFAF30A6E9DAF").resolveHandle("processchainbc84doctype"); /** * Gets the "ProcessChain" element */ de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain getProcessChain(); /** * Sets the "ProcessChain" element */ void setProcessChain(de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain processChain); /** * Appends and returns a new empty "ProcessChain" element */ de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain addNewProcessChain(); /** * An XML ProcessChain(@http://www.bfr.bund.de/PCML-1_0). * * This is a complex type. */ public interface ProcessChain extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ProcessChain.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s121DA543B1FCBC764F9DFAF30A6E9DAF").resolveHandle("processchaina076elemtype"); /** * Gets array of all "ProcessNode" elements */ de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode[] getProcessNodeArray(); /** * Gets ith "ProcessNode" element */ de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode getProcessNodeArray(int i); /** * Returns number of "ProcessNode" element */ int sizeOfProcessNodeArray(); /** * Sets array of all "ProcessNode" element */ void setProcessNodeArray(de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode[] processNodeArray); /** * Sets ith "ProcessNode" element */ void setProcessNodeArray(int i, de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode processNode); /** * Inserts and returns a new empty value (as xml) as the ith "ProcessNode" element */ de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode insertNewProcessNode(int i); /** * Appends and returns a new empty value (as xml) as the last "ProcessNode" element */ de.bund.bfr.pcml10.ProcessNodeDocument.ProcessNode addNewProcessNode(); /** * Removes the ith "ProcessNode" element */ void removeProcessNode(int i); /** * Gets array of all "Extension" elements */ de.bund.bfr.pcml10.ExtensionDocument.Extension[] getExtensionArray(); /** * Gets ith "Extension" element */ de.bund.bfr.pcml10.ExtensionDocument.Extension getExtensionArray(int i); /** * Returns number of "Extension" element */ int sizeOfExtensionArray(); /** * Sets array of all "Extension" element */ void setExtensionArray(de.bund.bfr.pcml10.ExtensionDocument.Extension[] extensionArray); /** * Sets ith "Extension" element */ void setExtensionArray(int i, de.bund.bfr.pcml10.ExtensionDocument.Extension extension); /** * Inserts and returns a new empty value (as xml) as the ith "Extension" element */ de.bund.bfr.pcml10.ExtensionDocument.Extension insertNewExtension(int i); /** * Appends and returns a new empty value (as xml) as the last "Extension" element */ de.bund.bfr.pcml10.ExtensionDocument.Extension addNewExtension(); /** * Removes the ith "Extension" element */ void removeExtension(int i); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain newInstance() { return (de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain newInstance(org.apache.xmlbeans.XmlOptions options) { return (de.bund.bfr.pcml10.ProcessChainDocument.ProcessChain) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static de.bund.bfr.pcml10.ProcessChainDocument newInstance() { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument newInstance(org.apache.xmlbeans.XmlOptions options) { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static de.bund.bfr.pcml10.ProcessChainDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static de.bund.bfr.pcml10.ProcessChainDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static de.bund.bfr.pcml10.ProcessChainDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (de.bund.bfr.pcml10.ProcessChainDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
gpl-3.0
dazorni/9tac
app/component/user-list.js
559
import React from 'react'; class UserList extends React.Component { constructor() { super(); let userData = [ {"id": 1, "username": "dazorni"}, {"id": 2, "username": "nino"}, ]; this.state = { data: userData }; } render() { let userNodes = this.state.data.map(user => <User key={user.id} username={user.username} avatar={this._getAvatarUrl(user.username)}/>); return ( <div>UserList</div> {userNodes} ) } _getAvatarUrl(username) { return "https://api.adorable.io/avatar/" + username; } }; export default UserList
gpl-3.0
GMIG/Gumuc
src/gumuc1/RelayDecoder.java
2756
package gumuc1; import java.nio.charset.Charset; import java.util.LinkedList; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.filterchain.IoFilter.NextFilter; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.textline.LineDelimiter; import org.apache.mina.filter.codec.textline.TextLineDecoder; public class RelayDecoder extends TextLineDecoder{ class CountReply{ public static final String prefixReply = "!COUNT"; private int time; CountReply(int in_time){ time = in_time; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } } class SwitchReply{ public SwitchReply(int ledID, boolean cmdID) { this.ledID = ledID; this.statusID = cmdID; } public static final String prefixReply = "!LED"; public static final String onReply = "ON"; public static final String offReply = "OFF"; private int ledID; private boolean statusID; public int getLedID() { return ledID; } public void setLedID(int ledID) { this.ledID = ledID; } public boolean getCmdID() { return statusID; } public void setCmdID(boolean cmdID) { this.statusID = cmdID; } public boolean answers(RelaySwitchCommand command){ return (command.getCmdID() == getCmdID() && command.getLedID() == getLedID() ); } } public RelayDecoder() { super(Charset.forName("UTF-8"), LineDelimiter.MAC); } private Object parseCommand(String line) { if(line.contains(CountReply.prefixReply)) return new CountReply(Integer.parseInt(line.substring(6))); if(line.contains(RelayDecoder.SwitchReply.prefixReply)){ if(line.contains(RelayDecoder.SwitchReply.onReply)) return new RelayDecoder.SwitchReply(Integer.parseInt(line.substring(6)),true); if(line.contains(RelayDecoder.SwitchReply.offReply)) return new RelayDecoder.SwitchReply(Integer.parseInt(line.substring(7)),false); } return null; } @Override public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out) throws Exception { final LinkedList<String> lines = new LinkedList<String>(); super.decode(session, in, new ProtocolDecoderOutput() { public void write(Object message) { lines.add((String) message); } public void flush(NextFilter nextFilter, IoSession session) {} }); for (String s: lines) { out.write(parseCommand(s)); } } }
gpl-3.0
fiendishly/rsbot
src/org/rsbot/script/Store.java
5874
package org.rsbot.script; import java.awt.Point; import org.rsbot.bot.Bot; import org.rsbot.script.wrappers.RSInterface; import org.rsbot.script.wrappers.RSInterfaceComponent; /** * This class is for all the Store operations. */ public class Store { private final Methods methods; private int stock = 24; Store(final Methods methods) { this.methods = methods; } /** * Performs a given action on the specified item id. Returns atMenu. * * @param itemID * the id of the item * @param txt * the action to perform (see {@link Methods#atMenu}) * @return true on success */ public boolean atItem(final int itemID, final String txt) { if (!methods.isLoggedIn() || !isOpen()) return false; // final int[] itemArray = getItemArray(); // for (int off = 0; off < itemArray.length; off++) { // if (itemArray[off] == itemID) { // methods.clickMouse(getItemPoint(off), 5, 5, false); // return methods.atMenu(txt); // } // } final RSInterfaceComponent item = getItemByID(itemID); if ((item != null) && item.isValid()) return methods.atInterface(item, txt); return false; } /** * Tries to buy an item. * * 0 is All. 1,5,10 use buy 1,5,10 while other numbers buy X. * * @param itemID * The id of the item. * @param count * The number to buy. * @return true on success */ public boolean buy(final int itemID, final int count) { if (count < 0) throw new IllegalArgumentException("count < 0 " + count); if (!isOpen()) return false; final int inventoryCount = methods.getInventoryCount(true); for (int tries = 0; tries < 5; tries++) { switch (count) { case 0: // Withdraw All atItem(itemID, "Buy All"); break; case 1: // Withdraw 1 atItem(itemID, "Buy 1"); break; case 5: // Withdraw 5 atItem(itemID, "Buy 5"); break; case 10: // Withdraw 10 atItem(itemID, "Buy 10"); break; case 50: // Withdraw 50 atItem(itemID, "Buy 50"); default: // Withdraw x atItem(itemID, "Buy X"); methods.wait(methods.random(900, 1100)); Bot.getInputManager().sendKeys("" + count, true); } methods.wait(methods.random(500, 700)); if (methods.getInventoryCount(true) > inventoryCount) return true; } return false; } /** * Closes the Store interface. Temp Fix until interfaces are fixed * * @return true if the interface is no longer open */ public boolean close() { if (!isOpen()) return true; // methods.clickMouse(new Point(methods.random(481, 496), // methods.random( // 27, 42)), true); methods.atInterface(620, 18); methods.wait(methods.random(500, 600)); return !isOpen(); } /** * Gets the store interface. * * @return the store interface */ public RSInterface getInterface() { return RSInterface.getInterface(620); } public RSInterfaceComponent getItem(final int index) { final RSInterfaceComponent[] items = getItems(); if (items != null) { for (final RSInterfaceComponent item : items) { if (item.getComponentIndex() == index) return item; } } return null; } /** * Makes it easier to get Items in the store Written by Fusion89k * * @param id * ID of the item to get * @return the component of the item */ public RSInterfaceComponent getItemByID(final int id) { final RSInterfaceComponent[] items = getItems(); if (items != null) { for (final RSInterfaceComponent item : items) { if (item.getComponentID() == id) return item; } } return null; } public String[] getItemNames() { final RSInterfaceComponent[] items = getInterface().getChild(stock).getComponents(); if (items != null) { final String[] value = new String[items.length]; for (int i = 0; i < items.length; i++) { value[items[i].getComponentIndex()] = items[i].getComponentName(); } return value; } return new String[0]; } /** * Gets the point on the screen for a given item. Numbered left to right * then top to bottom. Written by Qauters. * * @param slot * the index of the item * @return the point of the item */ public Point getItemPoint(final int slot) { // And I will strike down upon thee with great vengeance and furious // anger those who attempt to replace the following code with fixed // constants! if (slot < 0) throw new IllegalArgumentException("slot < 0 " + slot); final RSInterfaceComponent item = getItem(slot); if (item != null) return item.getPosition(); return new Point(-1, -1); } public RSInterfaceComponent[] getItems() { if ((getInterface() == null) || (getInterface().getChild(stock) == null)) return new RSInterfaceComponent[0]; return getInterface().getChild(stock).getComponents(); } /** * Gets the array of item stack sizes in the store * * @return the stack sizes */ public int[] getStackSizes() { final RSInterfaceComponent[] items = getInterface().getChild(stock).getComponents(); if (items != null) { final int[] value = new int[items.length]; for (int i = 0; i < items.length; i++) { value[i] = items[i].getComponentStackSize(); } return value; } return new int[0]; } /** * @return true if the store interface is open, false otherwise */ public boolean isOpen() { return getInterface().isValid(); } /** * Allows switching between main stock and player stock Written by Fusion89k * * @param mainStock * <tt>true</tt> for MainStock; <tt>false</tt> for PlayerStock */ public void switchStock(final boolean mainStock) { stock = mainStock ? 24 : 26; } }
gpl-3.0
chrisplough/otmfaq
otmfaq.com/htdocs/forums/impex/systems/bac/000.php
9537
<?php /*======================================================================*\ || #################################################################### || || # vBulletin - Licence Number VBF98A5CB5 || # ---------------------------------------------------------------- # || || # All PHP code in this file is ©2000-2006 Jelsoft Enterprises Ltd. # || || # This file may not be redistributed in whole or significant part. # || || # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # || || # http://www.vbulletin.com | http://www.vbulletin.com/license.html # || || #################################################################### || \*======================================================================*/ /** * bac API module * * @package ImpEx.bac * @version $Revision: 1.1 $ * @author Jerry Hutchings <jerry.hutchings@vbulletin.com> * @checkedout $Name: $ * @date $Date: 2006/10/17 01:58:19 $ * @copyright http://www.vbulletin.com/license.html * */ class bac_000 extends ImpExModule { /** * Class version * * This is the version of the source system that is supported * * @var string */ var $_version = '0.0'; /** * Module string * * @var array */ var $_modulestring = 'BuildACommunity'; var $_homepage = 'http://buildacommunity.com/index.html'; /** * Valid Database Tables * * @var array */ var $_valid_tables = array ( 'CFACTIVITYLOG', 'CFATTACHMENTS', 'CFBOARDTYPES', 'CFCATEGORY', 'CFCATEGORYDESCRIPTION', 'CFCATEGORYTEASER', 'CFCATEGORYvsFORUM', 'CFFILTEREDUSERS', 'CFFILTEREDWORDS', 'CFFORUMS', 'CFFORUMSPREFERENCES', 'CFFORUMSvsMODERATORS', 'CFFORUMSvsPRIVILEGEGROUPS', 'CFFORUMSvsUSERGROUPS', 'CFFORUMSvsUSERS', 'CFHIGHLIGHTEDPOSTS', 'CFMETADATA', 'CFMODS', 'CFPOLLLOGS', 'CFPOLLOPTIONS', 'CFPOSTERS', 'CFPOSTREVISIONS', 'CFPOSTS', 'CFPOSTTYPES', 'CFRECOMMENDATIONLOG', 'CFREPLACEMENTS', 'CFSUBSCRIPTIONS', 'CFTHREADS', 'CFTHREADTRACKER', 'CFUSERvsFORUM', 'USERUSERS' ); function bac_000() { } /** * Parses and custom HTML for bac * * @param string mixed The text to be parse * * @return array */ function bac_html($text) { return $text; } /** * Returns the user_id => username array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_members_list(&$Db_object, &$databasetype, &$tableprefix, &$start, &$per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $user_list = $Db_object->query("SELECT UserID, UserName FROM {$tableprefix}USERUSERS ORDER BY UserID LIMIT {$start}, {$per_page}"); while ($user = $Db_object->fetch_array($user_list)) { $return_array["$user[UserID]"] = $user['UserName']; } return $return_array; } else { return false; } } /** * Returns the attachment_id => attachment array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_attachment_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}CFATTACHMENTS ORDER BY AttachmentID LIMIT {$start_at}, {$per_page}"); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[AttachmentID]"] = $detail; } } else { return false; } return $return_array; } /** * Returns the forum_id => forum array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_forum_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}CFFORUMS ORDER BY ForumID LIMIT {$start_at}, {$per_page}"); while ($detail = $Db_object->fetch_array($details_list)) { $cat_id = $Db_object->query_first("SELECT CategoryID FROM {$tableprefix}CFCATEGORYvsFORUM WHERE ForumID=" . $detail['ForumID']); $return_array["$detail[ForumID]"] = $detail; $return_array["$detail[ForumID]"]['catid'] = $cat_id['CategoryID']; } } else { return false; } return $return_array; } function get_bac_cat_details(&$Db_object, &$databasetype, &$tableprefix) { $return_array = array(); if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}CFCATEGORY ORDER BY CategoryID"); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[CategoryID]"] = $detail; } } else { return false; } return $return_array; } /** * Returns the poll_id => poll array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_poll_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // No source data return $return_array; // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query($sql); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[poll_id]"] = $detail; } } else { return false; } return $return_array; } /** * Returns the post_id => post array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_post_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}CFPOSTS ORDER BY PostID LIMIT {$start_at}, {$per_page}"); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[PostID]"] = $detail; } } else { return false; } return $return_array; } /** * Returns the thread_id => thread array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_thread_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}CFTHREADS ORDER BY ThreadID LIMIT {$start_at}, {$per_page}"); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[ThreadID]"] = $detail; } } else { return false; } return $return_array; } /** * Returns the user_id => user array * * @param object databaseobject The database object to run the query against * @param string mixed Table database type * @param string mixed The prefix to the table name i.e. 'vb3_' * @param int mixed Start point * @param int mixed End point * * @return array */ function get_bac_user_details(&$Db_object, &$databasetype, &$tableprefix, $start_at, $per_page) { $return_array = array(); // Check that there is not a empty value if(empty($per_page)) { return $return_array; } if ($databasetype == 'mysql') { $details_list = $Db_object->query("SELECT * FROM {$tableprefix}USERUSERS ORDER BY UserID LIMIT {$start_at}, {$per_page}"); while ($detail = $Db_object->fetch_array($details_list)) { $return_array["$detail[UserID]"] = $detail; } } else { return false; } return $return_array; } } // Class end # Autogenerated on : October 15, 2006, 7:40 am # By ImpEx-generator 2.1. /*======================================================================*\ || #################################################################### || # Downloaded: 03:45, Mon Nov 13th 2006 || # CVS: $RCSfile: 000.php,v $ - $Revision: 1.1 $ || #################################################################### \*======================================================================*/ ?>
gpl-3.0
unix4you2/pcoder
mod/pcoder/inc/configuracion.php
2053
<?php /* ===================================================================== PBROWSER (Practico Browser) Sistema Simple de Navegacion por Proxy basado en PHP Copyright (C) 2013 John F. Arroyave Gutiérrez unix4you2@gmail.com www.practico.org This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ /* Define si PCoder se ejecuta en modo StandAlone (Independiente) para cualquier proyecto o servidor o como un modulo de Practico Posibles Valores: 1=StandAlone 0=Modulo de Practico */ $PCO_PCODER_StandAlone=1; /* Define el Path inicial sobre el cual el usuario puede navegar por el sistema de archivos del servidor para editarlos. A mayor numero de carpetas a leer sera mas lenta la apertura del editor. Posibles valores: / -> Todo su disco!!! . -> Directorio Actual de PCoder (generalmente sobre mod/pcoder) ../ -> Raiz de PCoder (generalmente sobre mod/pcoder/mod) ../../ -> Raiz de PCoder (Donde reside LICENSE, AUTHORS, Etc) ../../../ -> Raiz Instalacion PCoder cuando es independiente o Raiz de Practico si esta como modulo Otros -> Agregue aqui tantos niveles superiores como desee segun su ruta de instalacion $_SERVER['DOCUMENT_ROOT'] -> Raiz de Todo el servidor web */ $PCO_PCODER_RaizExploracionArchivos=$_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR; $ZonaHoraria='America/Bogota'; $IdiomaPredeterminado='es';
gpl-3.0
MailCleaner/MailCleaner
www/framework/Zend/XmlRpc/Server/Fault.php
5541
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_XmlRpc * @subpackage Server * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Fault.php,v 1.1.2.4 2011-05-30 08:30:54 root Exp $ */ /** * Zend_XmlRpc_Fault */ require_once 'Zend/XmlRpc/Fault.php'; /** * XMLRPC Server Faults * * Encapsulates an exception for use as an XMLRPC fault response. Valid * exception classes that may be used for generating the fault code and fault * string can be attached using {@link attachFaultException()}; all others use a * generic '404 Unknown error' response. * * You may also attach fault observers, which would allow you to monitor * particular fault cases; this is done via {@link attachObserver()}. Observers * need only implement a static 'observe' method. * * To allow method chaining, you may use the {@link getInstance()} factory * to instantiate a Zend_XmlRpc_Server_Fault. * * @category Zend * @package Zend_XmlRpc * @subpackage Server * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_XmlRpc_Server_Fault extends Zend_XmlRpc_Fault { /** * @var Exception */ protected $_exception; /** * @var array Array of exception classes that may define xmlrpc faults */ protected static $_faultExceptionClasses = array('Zend_XmlRpc_Server_Exception' => true); /** * @var array Array of fault observers */ protected static $_observers = array(); /** * Constructor * * @param Exception $e * @return Zend_XmlRpc_Server_Fault */ public function __construct(Exception $e) { $this->_exception = $e; $code = 404; $message = 'Unknown error'; $exceptionClass = get_class($e); foreach (array_keys(self::$_faultExceptionClasses) as $class) { if ($e instanceof $class) { $code = $e->getCode(); $message = $e->getMessage(); break; } } parent::__construct($code, $message); // Notify exception observers, if present if (!empty(self::$_observers)) { foreach (array_keys(self::$_observers) as $observer) { call_user_func(array($observer, 'observe'), $this); } } } /** * Return Zend_XmlRpc_Server_Fault instance * * @param Exception $e * @return Zend_XmlRpc_Server_Fault */ public static function getInstance(Exception $e) { return new self($e); } /** * Attach valid exceptions that can be used to define xmlrpc faults * * @param string|array $classes Class name or array of class names * @return void */ public static function attachFaultException($classes) { if (!is_array($classes)) { $classes = (array) $classes; } foreach ($classes as $class) { if (is_string($class) && class_exists($class)) { self::$_faultExceptionClasses[$class] = true; } } } /** * Detach fault exception classes * * @param string|array $classes Class name or array of class names * @return void */ public static function detachFaultException($classes) { if (!is_array($classes)) { $classes = (array) $classes; } foreach ($classes as $class) { if (is_string($class) && isset(self::$_faultExceptionClasses[$class])) { unset(self::$_faultExceptionClasses[$class]); } } } /** * Attach an observer class * * Allows observation of xmlrpc server faults, thus allowing logging or mail * notification of fault responses on the xmlrpc server. * * Expects a valid class name; that class must have a public static method * 'observe' that accepts an exception as its sole argument. * * @param string $class * @return boolean */ public static function attachObserver($class) { if (!is_string($class) || !class_exists($class) || !is_callable(array($class, 'observe'))) { return false; } if (!isset(self::$_observers[$class])) { self::$_observers[$class] = true; } return true; } /** * Detach an observer * * @param string $class * @return boolean */ public static function detachObserver($class) { if (!isset(self::$_observers[$class])) { return false; } unset(self::$_observers[$class]); return true; } /** * Retrieve the exception * * @access public * @return Exception */ public function getException() { return $this->_exception; } }
gpl-3.0
seranfuen/contalibre
ContaLibre/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs
19083
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ContaLibre.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
gpl-3.0
Exygy/sf-dahlia-web-production
spec/controllers/overrides/registrations_controller_spec.rb
1196
require 'rails_helper' describe Overrides::RegistrationsController do before(:each) do @request.env['devise.mapping'] = Devise.mappings[:user] end describe 'create' do let(:valid_user_params) do { user: { email: 'jane@doe.com', password: 'somepassword', password_confirmation: 'somepassword', }, contact: { firstName: 'Jane', lastName: 'Doe', DOB: '1985-07-23', email: 'jane@doe.com', }, confirm_success_url: 'http://localhost/my-account', } end let(:salesforce_response) do { firstName: 'Test', lastName: 'lastName', email: 'test@test.com', DOB: '1989-03-29', contactId: '003f000000r2oseAAA', }.as_json end it 'saves a salesforce contact id on user' do allow(SalesforceService::AccountService) .to receive(:create_or_update) .and_return(salesforce_response) VCR.use_cassette('account/register') do post :create, valid_user_params end expect(assigns(:resource).salesforce_contact_id) .to eq('003f000000r2oseAAA') end end end
gpl-3.0
maker56/UltimateSurvivalGames
UltimateSurvivalGames/src/me/maker56/survivalgames/game/phases/DeathmatchPhase.java
3373
package me.maker56.survivalgames.game.phases; import java.util.Collections; import java.util.List; import me.maker56.survivalgames.SurvivalGames; import me.maker56.survivalgames.Util; import me.maker56.survivalgames.arena.Arena; import me.maker56.survivalgames.commands.messages.MessageHandler; import me.maker56.survivalgames.game.Game; import me.maker56.survivalgames.game.GameState; import me.maker56.survivalgames.user.SpectatorUser; import me.maker56.survivalgames.user.User; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; public class DeathmatchPhase { private int time = 600, starttime = time; private BukkitTask task; private Game game; public DeathmatchPhase(Game game) { this.game = game; } public void load() { game.setScoreboardPhase(SurvivalGames.getScoreboardManager().getNewScoreboardPhase(GameState.DEATHMATCH)); start(); } public void start() { game.sendMessage(MessageHandler.getMessage("game-deathmatch-start")); game.setState(GameState.DEATHMATCH); List<Location> spawns = game.getCurrentArena().getDeathmatchSpawns(); int i = 0; for(User user : game.getUsers()) { if(i >= spawns.size()) i = 0; user.getPlayer().teleport(spawns.get(i)); i++; } Location suloc = spawns.get(0); for(SpectatorUser su : game.getSpecators()) { su.getPlayer().teleport(suloc); Vector v = new Vector(0, 2, 0); v.multiply(1.25); su.getPlayer().getLocation().setDirection(v); } task = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() { public void run() { if(time == 60) { game.sendMessage(MessageHandler.getMessage("game-deathmatch-timeout-warning")); } if(time % 60 == 0 && time != 0) { game.sendMessage(MessageHandler.getMessage("game-deathmatch-timeout").replace("%0%", Util.getFormatedTime(time))); } else if(time % 10 == 0 && time < 60 && time > 10) { game.sendMessage(MessageHandler.getMessage("game-deathmatch-timeout").replace("%0%", Util.getFormatedTime(time))); } else if(time <= 10 && time > 0) { game.sendMessage(MessageHandler.getMessage("game-deathmatch-timeout").replace("%0%", Util.getFormatedTime(time))); } else if(time == 0) { Arena a = game.getCurrentArena(); User user = null; if(a.isDomeEnabled()) { double nearest = a.getDomeRadius() + 50; for(User u : game.getUsers()) { double distance = a.domeDistance(u.getPlayer().getLocation()); if(distance <= nearest) { nearest = distance; user = u; } } } else { Collections.shuffle(game.getUsers()); user = game.getUsers().get(0); } for(User u : game.getUsers()) { if(!u.equals(user)) { u.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 10000000, 3)); } } } game.updateScoreboard(); time--; } }, 0L, 20L); } public int getTime() { return time; } public void cancelTask() { if(task != null) task.cancel(); } public int getStartTime() { return starttime; } }
gpl-3.0
skulia15/Web-Services
D2/CoursesAPIv0.2/Models/EntityModels/CourseTemplate.cs
367
/// <summary> /// A template for the courses /// </summary> namespace CoursesAPI.Models.EntityModels { public class CourseTemplate { public int ID { get; set; } // Example: "Vefþjónustur" public string Name { get; set; } // Example: "T-514-VEFT" public string CourseID { get; set; } // Example: 2016-08-17 } }
gpl-3.0
GRIS-UdeM/spatServerGRIS
Source/sg_VuMeterComponent.cpp
6116
/* This file is part of SpatGRIS. Developers: Samuel Béland, Olivier Bélanger, Nicolas Masson SpatGRIS 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. SpatGRIS 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 SpatGRIS. If not, see <http://www.gnu.org/licenses/>. */ #include "sg_VuMeterComponent.hpp" #include "sg_GrisLookAndFeel.hpp" #include "sg_Narrow.hpp" #include "sg_constants.hpp" namespace { constexpr auto VU_METER_MIN_HEIGHT = 140; } //============================================================================== void VuMeterComponent::resized() { JUCE_ASSERT_MESSAGE_THREAD; auto const width{ getWidth() }; auto const height{ getHeight() }; mColorGrad = juce::ColourGradient{ juce::Colour::fromRGB(255, 94, 69), 0.f, 0.f, juce::Colour::fromRGB(17, 255, 159), 0.f, narrow<float>(height), false }; mColorGrad.addColour(0.1, juce::Colours::yellow); // Create vu-meter foreground image. mVuMeterBit = juce::Image{ juce::Image::RGB, width, height, true }; // used to be width - 1 juce::Graphics gf{ mVuMeterBit }; gf.setGradientFill(mColorGrad); gf.fillRect(0, 0, getWidth(), getHeight()); gf.setColour(mLookAndFeel.getDarkColour()); gf.setFont(10.0f); // Create vu-meter background image. mVuMeterBackBit = juce::Image{ juce::Image::RGB, width, height, true }; // used to be width - 1 juce::Graphics gb{ mVuMeterBackBit }; gb.setColour(mLookAndFeel.getDarkColour()); gb.fillRect(0, 0, getWidth(), getHeight()); gb.setColour(mLookAndFeel.getScrollBarColour()); gb.setFont(10.0f); // Create vu-meter muted image. mVuMeterMutedBit = juce::Image(juce::Image::RGB, width, height, true); // used to be width - 1 juce::Graphics gm{ mVuMeterMutedBit }; gm.setColour(mLookAndFeel.getWinBackgroundColour()); gm.fillRect(0, 0, getWidth(), getHeight()); gm.setColour(mLookAndFeel.getScrollBarColour()); gm.setFont(10.0f); // Draw ticks on images. auto const start = getWidth() - 3; static constexpr auto NUM_TICKS = 10; for (auto i{ 1 }; i < NUM_TICKS; ++i) { auto const y = i * height / NUM_TICKS; auto const y_f{ narrow<float>(y) }; auto const start_f{ narrow<float>(start) }; auto const with_f{ narrow<float>(getWidth()) }; gf.drawLine(start_f, y_f, with_f, y_f, 1.0f); gb.drawLine(start_f, y_f, with_f, y_f, 1.0f); gm.drawLine(start_f, y_f, with_f, y_f, 1.0f); if (i % 2 == 1) { gf.drawText(juce::String(i * -6), start - 15, y - 5, 15, 10, juce::Justification::centred, false); gb.drawText(juce::String(i * -6), start - 15, y - 5, 15, 10, juce::Justification::centred, false); gm.drawText(juce::String(i * -6), start - 15, y - 5, 15, 10, juce::Justification::centred, false); } } } //============================================================================== void VuMeterComponent::paint(juce::Graphics & g) { JUCE_ASSERT_MESSAGE_THREAD; auto const width{ getWidth() }; auto const height{ getHeight() }; if (mIsMuted) { g.drawImage(mVuMeterMutedBit, 0, 0, width, height, 0, 0, width, height); return; } if (mLevel <= MIN_LEVEL_COMP && !mIsClipping) { g.drawImage(mVuMeterBackBit, 0, 0, width, height, 0, 0, width, height); return; } auto const magnitude{ 1.0f - std::clamp(mLevel, MIN_LEVEL_COMP, MAX_LEVEL_COMP) / MIN_LEVEL_COMP }; auto const rel = narrow<int>(std::round(magnitude * narrow<float>(height))); auto const h = height - rel; g.drawImage(mVuMeterBit, 0, h, width, rel, 0, h, width, rel); g.drawImage(mVuMeterBackBit, 0, 0, width, h, 0, 0, width, h); if (mIsClipping) { g.setColour(juce::Colour::fromHSV(0.0, 1, 0.75, 1)); juce::Rectangle<float> const clipRect{ 0.5, 0.5, narrow<float>(height - 1), 5 }; g.fillRect(clipRect); } } //============================================================================== void VuMeterComponent::mouseDown(juce::MouseEvent const & e) { JUCE_ASSERT_MESSAGE_THREAD; juce::Rectangle<int> const hitBox{ 0, 0, getWidth(), 20 }; if (hitBox.contains(e.getPosition())) { resetClipping(); } } //============================================================================== int VuMeterComponent::getMinWidth() const noexcept { return SLICES_WIDTH; } //============================================================================== int VuMeterComponent::getMinHeight() const noexcept { return VU_METER_MIN_HEIGHT; } //============================================================================== void VuMeterComponent::resetClipping() { JUCE_ASSERT_MESSAGE_THREAD; mIsClipping = false; repaint(); } //============================================================================== void VuMeterComponent::setLevel(dbfs_t const level) { JUCE_ASSERT_MESSAGE_THREAD; auto const & clippedLevel{ std::clamp(level, MIN_LEVEL_COMP, MAX_LEVEL_COMP) }; if (clippedLevel == mLevel) { return; } if (level > MAX_LEVEL_COMP) { mIsClipping = true; } mLevel = clippedLevel; repaint(); } //============================================================================== void VuMeterComponent::setMuted(bool const muted) { JUCE_ASSERT_MESSAGE_THREAD; if (muted == mIsMuted) { return; } mIsMuted = muted; repaint(); }
gpl-3.0
alcheagle/jgeom2d
src/com/alcheagle/jgeom2d/MoveableObject2D.java
1012
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.alcheagle.jgeom2d; /** * * @author Andrea Gilardoni * <a href="mailto:andrea.gilardoni96@gmail.com">andrea.gilardoni96@gmail.com</a> */ public abstract class MoveableObject2D extends Object2D implements Moveable { protected Vector2D speed; protected Vector2D acceleration; public MoveableObject2D() { super(); speed = new Vector2D(); acceleration = new Vector2D(); } public Vector2D getSpeed() { return speed; } public void setSpeed(Vector2D speed) { this.speed = speed; } public Vector2D getAcceleration() { return acceleration; } public void setAcceleration(Vector2D acceleration) { this.acceleration = acceleration; } @Override public void move() { speed.selfSum(acceleration); position.selfSum(speed); if (boundary != null) { boundary.translate(speed); } } }
gpl-3.0
AdrienJarretier/MathGame
extlibs/sfgui-0.3.2-vs2017-64/doc/html/search/files_1.js
252
var searchData= [ ['bin_2ehpp',['Bin.hpp',['../Bin_8hpp.html',1,'']]], ['box_2ehpp',['Box.hpp',['../Box_8hpp.html',1,'']]], ['brew_2ehpp',['BREW.hpp',['../BREW_8hpp.html',1,'']]], ['button_2ehpp',['Button.hpp',['../Button_8hpp.html',1,'']]] ];
gpl-3.0
Shurgent/TFCTech
src/main/java/ua/pp/shurgent/tfctech/core/ModSounds.java
713
package ua.pp.shurgent.tfctech.core; public class ModSounds { private static final String PATH = ModDetails.ModID + ":"; public static final String GROOVEFIT = PATH + "rubbertapping.groove.fit"; public static final String MOUNTFIT = PATH + "rubbertapping.mount.fit"; public static final String BOWLFIT = PATH + "rubbertapping.bowl.fit"; public static final String BOWLGRAB = PATH + "rubbertapping.bowl.grab"; public static final String SCRATCH = PATH + "rubbertapping.trunk.scratch"; public static final String TONGSFALL = PATH + "wiredrawbench.tongs_fall"; public static final String DRAWING = PATH + "wiredrawbench.drawing"; public static final String INDUCTOR = PATH + "induction_smelter.work"; }
gpl-3.0
gwx/ZeldaClassic
src/zq_subscr.cpp
262070
//-------------------------------------------------------- // Zelda Classic // by Jeremy Craner, 1999-2000 // // subscr.cc // // Subscreen code for zelda.cc // //-------------------------------------------------------- #ifndef __GTHREAD_HIDE_WIN32API #define __GTHREAD_HIDE_WIN32API 1 #endif //prevent indirectly including windows.h #include "precompiled.h" //always first #include "gui.h" #include "subscr.h" #include "zq_subscr.h" #include "jwin.h" #include "zquest.h" #include "zsys.h" #include "zq_misc.h" #include "tiles.h" #include "qst.h" #include "init.h" #include <assert.h> #include "mem_debug.h" #include "backend/AllBackends.h" #ifndef _MSC_VER #include <strings.h> #endif #include <string.h> #ifdef _MSC_VER #define stricmp _stricmp #endif int curr_subscreen_object; char *str_oname; subscreen_group *css; bool sso_selection[MAXSUBSCREENITEMS]; static int ss_propCopySrc=-1; void replacedp(DIALOG &d, const char *newdp, size_t size=256); gamedata *game; //extern char *itemlist(int index, int *list_size) extern int bii_cnt; void delete_subscreen(int subscreenidx); const char *colortype_str[14] = { "Misc. Color", "Sys. Color", "CSet 0", "CSet 1", "CSet 2", "CSet 3", "CSet 4", "CSet 5", "CSet 6", "CSet 7", "CSet 8", "CSet 9", "CSet 10", "CSet 11" }; const char *colortypelist(int index, int *list_size) { if(index<0) { *list_size = 14; return NULL; } return colortype_str[index]; } int d_cs_color_proc(int msg,DIALOG *d,int c) { //these are here to bypass compiler warnings about unused arguments c=c; int w=(d->w-4)/16; switch(msg) { case MSG_DRAW: //rectfill(screen, d->x+2, d->y+2, d->x+d->w-3, d->y+d->h-3, jwin_pal[jcBOX]); //top blank part rectfill(screen, d->x, d->y, d->x+(w*16)+3, d->y+1, jwin_pal[jcBOX]); jwin_draw_frame(screen,d->x,d->y+2,w*16+4, d->h-4, FR_DEEP); for(int i=0; i<16; ++i) { rectfill(screen, d->x+2+(w*i), d->y+4, d->x+2+(w*(i+1))-1, d->y+d->h-5, ((d-2)->d1-2)*16+i); } // right end rectfill(screen, d->x+(w*16)+4, d->y, d->x+d->w-1, d->y+d->h-1, jwin_pal[jcBOX]); // bottom part rectfill(screen, d->x, d->y+d->h-2, d->x+(w*16)+3, d->y+d->h-1, jwin_pal[jcBOX]); //indicator lines hline(screen, d->x+2+(w*d->d1), d->y, d->x+2+(w*(d->d1+1))-1, jwin_pal[jcBOXFG]); hline(screen, d->x+2+(w*d->d1), d->y+d->h-1, d->x+2+(w*(d->d1+1))-1, jwin_pal[jcBOXFG]); break; case MSG_CLICK: d->d1=vbound((Backend::mouse->getVirtualScreenX()-d->x-2)/w,0,15); d->flags|=D_DIRTY; break; } return D_O_K; } int d_sys_color_proc(int msg,DIALOG *d,int c) { //these are here to bypass compiler warnings about unused arguments c=c; int w=(d->w-4)/17; switch(msg) { case MSG_DRAW: //rectfill(screen, d->x+2, d->y+2, d->x+d->w-3, d->y+d->h-3, jwin_pal[jcBOX]); //top blank part rectfill(screen, d->x, d->y, d->x+(w*17)+3, d->y+1, jwin_pal[jcBOX]); jwin_draw_frame(screen,d->x,d->y+2,w*17+4, d->h-4, FR_DEEP); for(int i=0; i<17; ++i) { rectfill(screen, d->x+2+(w*i), d->y+4, d->x+2+(w*(i+1))-1, d->y+d->h-5, vc(zc_max(0,i-1))); } line(screen, d->x+2, d->y+4, d->x+2+w-1, d->y+d->h-5, vc(15)); line(screen, d->x+2, d->y+d->h-5, d->x+2+w-1, d->y+4, vc(15)); // right end rectfill(screen, d->x+(w*17)+4, d->y, d->x+d->w-1, d->y+d->h-1, jwin_pal[jcBOX]); // bottom part rectfill(screen, d->x, d->y+d->h-2, d->x+(w*17)+3, d->y+d->h-1, jwin_pal[jcBOX]); //indicator lines hline(screen, d->x+2+(w*(d->d1+1)), d->y, d->x+2+(w*(d->d1+2))-1, jwin_pal[jcBOXFG]); hline(screen, d->x+2+(w*(d->d1+1)), d->y+d->h-1, d->x+2+(w*(d->d1+2))-1, jwin_pal[jcBOXFG]); break; case MSG_CLICK: d->d1=vbound((Backend::mouse->getVirtualScreenX()-d->x-2)/w,0,16)-1; d->flags|=D_DIRTY; break; } return D_O_K; } void update_ctl_proc(DIALOG *d, int ct) { switch(ct) { case 0: d->proc=jwin_droplist_proc; break; case 1: d->proc=d_sys_color_proc; break; default: d->proc=d_cs_color_proc; break; } d->flags|=D_DIRTY; } int d_ctl_proc(int msg,DIALOG *d,int c) { int old_d1=d->d1; int ret=jwin_droplist_proc(msg, d, c); if(d->d1!=old_d1) { update_ctl_proc(d+2, d->d1); } return ret; } int d_csl2_proc(int msg,DIALOG *d,int c); void update_csl_proc(DIALOG *d, int cs) { switch(cs) { case 0: d->proc=jwin_text_proc; d->fg=jwin_pal[jcBOXFG]; d->bg=jwin_pal[jcBOX]; (d+1)->proc=d_csl2_proc; (d+1)->fg=0; (d+1)->bg=0; //(d+59)->fg=subscreen_cset(&misc,(d-1)->d1?(d-1)->d1-1:ssctMISC, (d+1)->d1); break; default: d->proc=d_box_proc; d->fg=jwin_pal[jcBOX]; d->bg=jwin_pal[jcBOX]; (d+1)->proc=d_box_proc; (d+1)->fg=jwin_pal[jcBOX]; (d+1)->bg=jwin_pal[jcBOX]; break; } d->flags|=D_DIRTY; (d+1)->flags|=D_DIRTY; } int d_csl_proc(int msg,DIALOG *d,int c) { int old_d1=d->d1; int ret=jwin_droplist_proc(msg, d, c); if(d->d1!=old_d1) { update_csl_proc(d+1, d->d1); (d+60)->fg=subscreen_cset(&misc,d->d1?d->d1-1:ssctMISC, (d+2)->d1); } return ret; } int d_csl2_proc(int msg,DIALOG *d,int c) { int old_d1=d->d1; int ret=jwin_droplist_proc(msg, d, c); if(d->d1!=old_d1) { (d+58)->fg=subscreen_cset(&misc,(d-2)->d1?(d-2)->d1-1:ssctMISC, d->d1); } return ret; } int jwin_fontdrop_proc(int msg,DIALOG *d,int c) { int old_d1=d->d1; int ret=jwin_droplist_proc(msg, d, c); if(d->d1!=old_d1) { (d+3)->dp2=ss_font(d->d1); (d+3)->flags|=D_DIRTY; if((d+3)->proc!=d_dummy_proc) { rectfill(screen, (d+3)->x, (d+3)->y, (d+3)->x+(d+3)->w-1, (d+3)->y+(d+3)->h-1, jwin_pal[jcBOX]); } (d+3)->h=text_height(ss_font(d->d1))+8; (d+49)->dp2=ss_font(d->d1); (d+49)->flags|=D_DIRTY; if((d+49)->proc!=d_dummy_proc) { rectfill(screen, (d+49)->x, (d+49)->y, (d+49)->x+(d+49)->w-1, (d+49)->y+(d+49)->h-1, jwin_pal[jcBOX]); } (d+49)->h=text_height(ss_font(d->d1))+8; } return ret; } const char *misccolor_str[ssctMAX] = { "Text", "Caption", "Overworld BG", "Dungeon BG", "Dungeon FG", "Cave FG", "BS Dark", "BS Goal", "Compass (Lt)", "Compass (Dk)", "SS BG", "SS Shadow", "Tri. Frame", "Big Map BG", "Big Map FG", "Link's Pos", "Message Text" }; const char *misccolorlist(int index, int *list_size) { if(index<0) { *list_size = ssctMAX; return NULL; } return misccolor_str[index]; } const char *csettype_str[13] = { "Misc. CSet", "CSet 0", "CSet 1", "CSet 2", "CSet 3", "CSet 4", "CSet 5", "CSet 6", "CSet 7", "CSet 8", "CSet 9", "CSet 10", "CSet 11" }; const char *csettypelist(int index, int *list_size) { if(index<0) { *list_size = 13; return NULL; } return csettype_str[index]; } const char *misccset_str[sscsMAX] = { "Triforce", "Tri. Frame", "Overworld Map", "Dungeon Map", "Blue Frame", "HC Piece", "SS Vine" }; const char *misccsetlist(int index, int *list_size) { if(index<0) { *list_size = sscsMAX; return NULL; } return misccset_str[index]; } const char *spectile_str[ssmstMAX+1] = { "None", "SS Vine", "Magic Meter" }; const char *spectilelist(int index, int *list_size) { if(index<0) { *list_size = ssmstMAX+1; return NULL; } return spectile_str[index]; } const char *ssfont_str[ssfMAX] = { "Zelda NES", "SS 1", "SS 2", "SS 3", "SS 4", "BS Time", "Small", "Small Prop.", "LttP Small", "Link's Awakening", "Link to the Past", "Goron", "Zoran", "Hylian 1", "Hylian 2", "Hylian 3", "Hylian 4", "Proportional", "Oracle", "Oracle Proportional", "Phantom", "Phantom Proportional" }; const char *ssfontlist(int index, int *list_size) { if(index<0) { *list_size = ssfMAX; return NULL; } return ssfont_str[index]; } const char *shadowstyle_str[sstsMAX] = { "None", "Shadow", "Shadow (U)", "Shadow (O)", "Shadow (+)", "Shadow (X)", "Shadowed", "Shadowed (U)", "Shadowed (O)", "Shadowed (+)", "Shadowed (X)" }; const char *shadowstylelist(int index, int *list_size) { if(index<0) { *list_size = sstsMAX; return NULL; } return shadowstyle_str[index]; } const char *alignment_str[3] = { "Left", "Center", "Right" }; const char *alignmentlist(int index, int *list_size) { if(index<0) { *list_size = 3; return NULL; } return alignment_str[index]; } const char *wrapping_str[2] = { "Character", "Word" }; const char *wrappinglist(int index, int *list_size) { if(index<0) { *list_size = 2; return NULL; } return wrapping_str[index]; } const char *gaugeshow_str[3] = { "Always", "1/2", "Normal" }; const char *rows_str[2] = { "Two", "Three" }; const char *gaugeshowlist(int index, int *list_size) { if(index<0) { *list_size = 3; return NULL; } return gaugeshow_str[index]; } const char *rowslist(int index, int *list_size) { if(index<0) { *list_size = 2; return NULL; } return rows_str[index]; } const char *button_str[2] = { "A", "B" }; const char *buttonlist(int index, int *list_size) { if(index<0) { *list_size = 2; return NULL; } return button_str[index]; } const char *icounter_str[sscMAX] = { "Rupees", "Bombs", "Super Bombs", "Arrows", "Gen. Keys w/Magic", "Gen. Keys w/o Magic", "Level Keys w/Magic", "Level Keys w/o Magic", "Any Keys w/Magic", "Any Keys w/o Magic", "Script 1", "Script 2", "Script 3", "Script 4", "Script 5", "Script 6", "Script 7", "Script 8", "Script 9", "Script 10", "Script 11", "Script 12", "Script 13", "Script 14", "Script 15", "Script 16", "Script 17", "Script 18", "Script 19", "Script 20", "Script 21", "Script 22", "Script 23", "Script 24", "Script 25" }; const char *icounterlist(int index, int *list_size) { if(index<0) { *list_size = sscMAX; return NULL; } return icounter_str[index]; } int d_stilelist_proc(int msg,DIALOG *d,int c) { int old_d1=d->d1; int ret=jwin_droplist_proc(msg, d, c); if(d->d1!=old_d1) { (d-14)->h= is_large() ?32:16; (d-15)->h=(d-14)->h+4; switch(d->d1-1) { case ssmstSSVINETILE: (d-15)->w=52; (d-14)->w=48; (d-14)->d1=wpnsbuf[iwSubscreenVine].tile; break; case ssmstMAGICMETER: (d-15)->w=148; (d-14)->w=144; (d-14)->d1=wpnsbuf[iwMMeter].tile; break; case -1: default: (d-15)->w=20; (d-14)->w=16; break; } (d-14)->w*= is_large() ?2:1; (d-15)->w=(d-14)->w+4; (d-14)->bg=vbound((d-14)->bg,0,((d-14)->w-1)>>2); (d-17)->flags|=D_DIRTY; (d-15)->flags|=D_DIRTY; (d-14)->flags|=D_DIRTY; (d-1)->flags|=D_DIRTY; d->flags|=D_DIRTY; } return ret; } static int ssop_location_list[] = { // dialog control number 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,212,213, -1 }; static int ssop_color_list[] = { // dialog control number 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, -1 }; static int ssop_attributes_list[] = { // dialog control number 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, -1 }; static TABPANEL sso_properties_tabs[] = { // (text) { (char *)"Location", D_SELECTED, ssop_location_list, 0, NULL }, { (char *)"Color", 0, ssop_color_list, 0, NULL }, { (char *)"Attributes", 0, ssop_attributes_list, 0, NULL }, { NULL, 0, NULL, 0, NULL } }; DIALOG *sso_properties_dlg; int jwin_tflpcheck_proc(int msg,DIALOG *d,int c) { bool selected=(d->flags&D_SELECTED)!=0; int ret= is_large() ? jwin_checkfont_proc(msg,d,c) : jwin_check_proc(msg, d, c); bool new_selected=(d->flags&D_SELECTED)!=0; if(new_selected!=selected) { (d-3)->w=(new_selected?32:16)*(is_large() +1); (d-3)->h=(new_selected?48:16)*(is_large() +1); (d-4)->w=(d-3)->w+4; (d-4)->h=(d-3)->h+4; // (d-5)->x=((d-4)->x)+(((d-4)->w)/2); (d-6)->w=(new_selected?112:96)*(is_large() +1); (d-6)->h=(new_selected?112:48)*(is_large() +1); (d-7)->w=(d-6)->w+4; (d-7)->h=(d-6)->h+4; // (d-8)->x=((d-7)->x)+(((d-7)->w)/2); (d-3)->flags|=D_DIRTY; (d-4)->flags|=D_DIRTY; (d-5)->flags|=D_DIRTY; (d-6)->flags|=D_DIRTY; (d-7)->flags|=D_DIRTY; (d-8)->flags|=D_DIRTY; (d-9)->flags|=D_DIRTY; } return ret; } int jwin_lscheck_proc(int msg,DIALOG *d,int c) { bool selected=(d->flags&D_SELECTED)!=0; int ret=is_large() ? jwin_checkfont_proc(msg,d,c) : jwin_check_proc(msg, d, c); bool new_selected=(d->flags&D_SELECTED)!=0; if(new_selected!=selected || msg==MSG_START) { (d-6)->w=(new_selected?32:16)*(is_large() ? 2 : 1); (d-6)->h=(new_selected?48:16)*(is_large() ? 2 : 1); (d-7)->w=(d-6)->w+4; (d-7)->h=(d-6)->h+4; (d-6)->flags|=D_DIRTY; (d-7)->flags|=D_DIRTY; (d-8)->flags|=D_DIRTY; (d-9)->flags|=D_DIRTY; } return ret; } int d_qtile_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_DRAW: { int dw = d->w; int dh = d->h; if(is_large()) { dw /= 2; dh /= 2; } BITMAP *buf = create_bitmap_ex(8,dw,dh); if(buf) { clear_bitmap(buf); for(int y=0; y<dh; y+=16) { for(int x=0; x<dw; x+=16) { puttile16(buf,d->d1+(y>>4)*20+(x>>4),x,y,d->fg,d->d2); } } int t=d->bg>>2; int t2=d->bg-(t<<2); rect(buf, (t<<4)+((t2&1)<<3) , ((t2&2)<<2), (t<<4)+((t2&1)<<3)+7, ((t2&2)<<2)+7, jwin_pal[jcTITLER]); stretch_blit(buf,screen,0,0,dw,dh,d->x-(is_large() ? 1 : 0),d->y- (is_large() ? 1 : 0),dw*(is_large()?2:1),dh*(is_large()?2:1)); destroy_bitmap(buf); } //textprintf_ex(screen, pfont, d->x,d->y, vc(15), -1, "%d", d->bg); return D_O_K; } break; case MSG_CLICK: { int old_fg=d->fg; if(Backend::mouse->rightButtonClicked()) //right mouse button { int old_bg=d->bg; int mx=vbound(Backend::mouse->getVirtualScreenX()-d->x,0,d->w-1); int my=vbound(Backend::mouse->getVirtualScreenY()-d->y,0,d->h-1); if(is_large()) { mx/=2; my/=2; } int t=mx>>4; d->bg=(t<<2)+((my>>3)<<1)+((mx-(t<<4))>>3); if(d->bg!=old_bg) { d->flags|=D_DIRTY; } return D_O_K; } int ret=d_maptile_proc(msg, d, c); if(d->fg!=old_fg) { (d-60)->d1=d->fg+1; (d-60)->d2=(d-60)->d1; update_csl_proc(d-59, d->fg+1); } d->flags|=D_DIRTY; return ret; } break; } return d_maptile_proc(msg, d, c); } int d_spectile_proc(int msg,DIALOG *d,int c) { int d1=d->d1; int ret=d_qtile_proc(msg,d,c); if (d1 != d->d1) { (d + 14)->d1 = 0; (d + 14)->d2 = 0; (d + 14)->flags |= D_DIRTY; d->w = 16 * (is_large() ? 2 : 1); (d-1)->w=d->w+4; d->flags|=D_DIRTY; (d-1)->flags|=D_DIRTY; (d-3)->flags|=D_DIRTY; } return ret; } int d_tileblock_proc(int msg,DIALOG *d,int c) { int old_fg=d->fg; int ret=d_maptile_proc(msg, d, c); switch(msg) { case MSG_CLICK: if(d->fg!=old_fg) { (d-60)->d1=d->fg+1; (d-60)->d2=(d-60)->d1; update_csl_proc(d-59, d->fg+1); } d->flags|=D_DIRTY; break; } return ret; } extern int d_alltriggerbutton_proc(int msg,DIALOG *d,int c); extern int d_comboa_radio_proc(int msg,DIALOG *d,int c); extern int d_comboabutton_proc(int msg,DIALOG *d,int c); extern int d_jbutton_proc(int msg,DIALOG *d,int c); extern int d_kbutton_proc(int msg,DIALOG *d,int c); extern int d_listen_proc(int msg,DIALOG *d,int c); extern int d_savemidi_proc(int msg,DIALOG *d,int c); extern int d_ssdn_btn_proc(int msg,DIALOG *d,int c); extern int d_ssdn_btn2_proc(int msg,DIALOG *d,int c); extern int d_ssdn_btn3_proc(int msg,DIALOG *d,int c); extern int d_ssdn_btn4_proc(int msg,DIALOG *d,int c); extern int d_sslt_btn_proc(int msg,DIALOG *d,int c); extern int d_sslt_btn2_proc(int msg,DIALOG *d,int c); extern int d_sslt_btn3_proc(int msg,DIALOG *d,int c); extern int d_sslt_btn4_proc(int msg,DIALOG *d,int c); extern int d_ssrt_btn_proc(int msg,DIALOG *d,int c); extern int d_ssrt_btn2_proc(int msg,DIALOG *d,int c); extern int d_ssrt_btn3_proc(int msg,DIALOG *d,int c); extern int d_ssrt_btn4_proc(int msg,DIALOG *d,int c); extern int d_ssup_btn_proc(int msg,DIALOG *d,int c); extern int d_ssup_btn2_proc(int msg,DIALOG *d,int c); extern int d_ssup_btn3_proc(int msg,DIALOG *d,int c); extern int d_ssup_btn4_proc(int msg,DIALOG *d,int c); extern int d_triggerbutton_proc(int msg,DIALOG *d,int c); void dummy_dialog_proc(DIALOG *d) { replacedp(*d,NULL); d->proc=d_dummy_proc; d->x=-1; d->y=-1; d->w=0; d->h=0; } void extract_colortype(DIALOG *d, subscreen_object *tempsso, int ct) { switch(ct) { case 3: switch(tempsso->colortype3) { case ssctMISC: d->d1=0; break; case ssctSYSTEM: d->d1=1; break; default: d->d1=tempsso->colortype3+2; break; } break; case 2: switch(tempsso->colortype2) { case ssctMISC: d->d1=0; break; case ssctSYSTEM: d->d1=1; break; default: d->d1=tempsso->colortype2+2; break; } break; case 1: default: switch(tempsso->colortype1) { case ssctMISC: d->d1=0; break; case ssctSYSTEM: d->d1=1; break; default: d->d1=tempsso->colortype1+2; break; } break; } } void insert_colortype(DIALOG *d, subscreen_object *tempsso, int ct) { switch(ct) { case 3: switch(d->d1) { case 0: tempsso->colortype3=ssctMISC; break; case 1: tempsso->colortype3=ssctSYSTEM; break; default: tempsso->colortype3=d->d1-2; break; } break; case 2: switch(d->d1) { case 0: tempsso->colortype2=ssctMISC; break; case 1: tempsso->colortype2=ssctSYSTEM; break; default: tempsso->colortype2=d->d1-2; break; } break; case 1: default: switch(d->d1) { case 0: tempsso->colortype1=ssctMISC; break; case 1: tempsso->colortype1=ssctSYSTEM; break; default: tempsso->colortype1=d->d1-2; break; } break; } } void extract_cset(DIALOG *d, subscreen_object *tempsso, int ct) { switch(ct) { case 3: switch(tempsso->colortype3) { case ssctMISC: d->d1=0; break; default: d->d1=tempsso->colortype3+1; break; } break; case 2: switch(tempsso->colortype2) { case ssctMISC: d->d1=0; break; default: d->d1=tempsso->colortype2+1; break; } break; case 1: default: switch(tempsso->colortype1) { case ssctMISC: d->d1=0; break; default: d->d1=tempsso->colortype1+1; break; } break; } } void insert_cset(DIALOG *d, subscreen_object *tempsso, int ct) { switch(ct) { case 3: switch(d->d1) { case 0: tempsso->colortype3=ssctMISC; break; default: tempsso->colortype3=d->d1-1; break; } break; case 2: switch(d->d1) { case 0: tempsso->colortype2=ssctMISC; break; default: tempsso->colortype2=d->d1-1; break; } break; case 1: default: switch(d->d1) { case 0: tempsso->colortype1=ssctMISC; break; default: tempsso->colortype1=d->d1-1; break; } break; } } static DIALOG sso_raw_data_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 60-12, 40, 200+24, 148, vc(14), vc(1), 0, D_EXIT, 0, 0, (void *) "Raw Data", NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_textbox_proc, 72-12, 60+4, 176+24+1, 92+4, jwin_pal[jcTEXTFG], jwin_pal[jcTEXTBG], 0, D_EXIT, 0, 0, NULL, NULL, NULL }, { jwin_button_proc, 130, 163, 61, 21, vc(14), vc(1), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; static ListData gaugeshow_list(gaugeshowlist, &font); static ListData rows_list(rowslist, &font); static ListData itemclass_list(item_class_list, &font); int sso_raw_data(subscreen_object *tempsso) { char raw_text[65535]; char title[80]; sprintf(title, "Raw Data for Object #%d", curr_subscreen_object); sprintf(raw_text, "Type: %d\nPosition: %d\nX: %d\nY: %d\nW: %d\nH: %d\nColor Type 1: %d\nColor 1: %d\nColor Type 2: %d\nColor 2: %d\nColor Type 3: %d\nColor 3: %d\nD1: %d\nD2: %d\nD3: %d\nD4: %d\nD5: %d\nD6: %d\nD7: %d\nD8: %d\nD9: %d\nD10: %d\nFrames: %d\nSpeed: %d\nDelay: %d\nFrame: %d\nDp1: %s", tempsso->type, tempsso->pos, tempsso->x, tempsso->y, tempsso->w, tempsso->h, tempsso->colortype1, tempsso->color1, tempsso->colortype2, tempsso->color2, tempsso->colortype3, tempsso->color3, tempsso->d1, tempsso->d2, tempsso->d3, tempsso->d4, tempsso->d5, tempsso->d6, tempsso->d7, tempsso->d8, tempsso->d9, tempsso->d10, tempsso->frames, tempsso->speed, tempsso->delay, tempsso->frame, tempsso->dp1!=NULL?(char *)tempsso->dp1:"NULL"); sso_raw_data_dlg[0].dp2=lfont; sso_raw_data_dlg[2].dp=raw_text; sso_raw_data_dlg[2].d2=0; DIALOG *sso_raw_data_cpy = resizeDialog(sso_raw_data_dlg, 1.5); zc_popup_dialog(sso_raw_data_cpy,2); delete[] sso_raw_data_cpy; return D_O_K; } static ListData wrapping_list(wrappinglist, &font); static ListData alignment_list(alignmentlist, &font); static ListData shadowstyle_list(shadowstylelist, &font); static ListData misccolor_list(misccolorlist, &font); static ListData spectile_list(spectilelist, &font); static ListData ssfont_list(ssfontlist, &font); static ListData colortype_list(colortypelist, &font); static ListData item_list(itemlist, &font); static DIALOG sso_master_properties_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 320, 240, vc(0), vc(11), 0, D_EXIT, 0, 0, (void *) "Invalid Object Properties", NULL, NULL }, { jwin_button_proc, 90, 215, 61, 21, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 170, 215, 61, 21, vc(0), vc(11), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { jwin_tab_proc, 4, 25, 312, 185, 0, 0, 0, 0, 0, 0, (void *) sso_properties_tabs, NULL, (void *)sso_properties_dlg }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 5 { jwin_text_proc, 8, 49, 42, 16, 0, 0, 0, 0, 0, 0, (void *) "Display:", NULL, NULL }, //{ jwin_droplist_proc, 45, 45, 150, 16, 0, 0, 0, 0, 0, 0, (void *) displaylist, NULL, NULL }, { jwin_check_proc, 50, 48, 60, 9, 0, 0, 0, 0, 0, 0, (void *) "Active Up", NULL, NULL }, { jwin_text_proc, 8, 67, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "X:", NULL, NULL }, { jwin_edit_proc, 23, 63, 31, 16, 0, 0, 0, 0, 4, 0, NULL, NULL, NULL }, { jwin_text_proc, 8, 85, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Y:", NULL, NULL }, // 10 { jwin_edit_proc, 23, 81, 31, 16, 0, 0, 0, 0, 4, 0, NULL, NULL, NULL }, { jwin_text_proc, 68, 67, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "W:", NULL, NULL }, { jwin_edit_proc, 83, 63, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_text_proc, 68, 85, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "H:", NULL, NULL }, { jwin_edit_proc, 83, 81, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, // 15 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 20 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 25 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 30 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 35 { jwin_frame_proc, 8, 48, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 12, 45, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Foreground Color ", NULL, NULL }, { jwin_text_proc, 16, 59, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { d_ctl_proc, 46, 55, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, { jwin_text_proc, 16, 77, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, // 40 { jwin_droplist_proc, 46, 73, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, { jwin_frame_proc, 8, 103, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 12, 100, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Background Color ", NULL, NULL }, { jwin_text_proc, 16, 114, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { d_ctl_proc, 46, 110, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, // 45 { jwin_text_proc, 16, 132, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, { jwin_droplist_proc, 46, 128, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, { jwin_frame_proc, 8, 158, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 12, 155, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Shadow Color ", NULL, NULL }, { jwin_text_proc, 16, 169, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, // 50 { d_ctl_proc, 46, 165, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, { jwin_text_proc, 16, 187, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, { jwin_droplist_proc, 46, 183, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, { jwin_frame_proc, 168, 48, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 172, 45, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Foreground Color ", NULL, NULL }, // 55 { jwin_text_proc, 176, 59, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { d_ctl_proc, 206, 55, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, { jwin_text_proc, 176, 77, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, { jwin_droplist_proc, 206, 73, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, { jwin_frame_proc, 168, 103, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, // 60 { jwin_text_proc, 172, 100, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Background Color ", NULL, NULL }, { jwin_text_proc, 176, 114, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { d_ctl_proc, 206, 110, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, { jwin_text_proc, 176, 132, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, { jwin_droplist_proc, 206, 128, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, // 65 { jwin_frame_proc, 168, 158, 144, 48, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 172, 155, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Shadow Color ", NULL, NULL }, { jwin_text_proc, 176, 169, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { d_ctl_proc, 206, 165, 88, 16, 0, 0, 0, 0, 0, 0, (void *) &colortype_list, NULL, NULL }, { jwin_text_proc, 176, 187, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, // 70 { jwin_droplist_proc, 206, 183, 98, 16, 0, 0, 0, 0, 0, 0, (void *) &misccolor_list, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 75 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 80 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 85 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 90 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_ctext_proc, 160, 122, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, D_DISABLED, 0, 0, (void *) "Part of Attributes", NULL, NULL }, // 95 { d_box_proc, 8, 45, 156, 122, vc(4), vc(4), 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_text_proc, 8, 45, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "TILE", NULL, NULL }, { jwin_frame_proc, 8, 51, 20, 20, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_maptile_proc, 10, 53, 16, 16, 0, 0, 0, 0, 0, 0, NULL, (void*)1, NULL }, { jwin_text_proc, 128, 45, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "TILE", NULL, NULL }, // 100 { jwin_frame_proc, 128, 51, 36, 52, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_maptile_proc, 130, 53, 32, 48, 0, 0, 0, 0, 0, 0, NULL, (void*)1, NULL }, { jwin_check_proc, 166, 109, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Overlay", NULL, NULL }, { jwin_check_proc, 166, 119, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Transparent", NULL, NULL }, { jwin_tflpcheck_proc, 166, 129, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Large Pieces", NULL, NULL }, // 105 { jwin_text_proc, 166, 55, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Frames:", NULL, NULL }, { jwin_text_proc, 166, 73, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Speed:", NULL, NULL }, { jwin_text_proc, 166, 91, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Delay:", NULL, NULL }, { jwin_edit_proc, 215, 51, 35, 16, vc(12), vc(1), 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_edit_proc, 215, 69, 35, 16, vc(12), vc(1), 0, 0, 3, 0, NULL, NULL, NULL }, // 110 { jwin_edit_proc, 215, 87, 35, 16, vc(12), vc(1), 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_text_proc, 8, 79, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Special Tile:", NULL, NULL }, { d_stilelist_proc, 65, 75, 92, 16, 0, 0, 0, 0, 0, 0, (void *) &spectile_list, NULL, NULL }, { jwin_text_proc, 8, 97, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Offset:", NULL, NULL }, { jwin_edit_proc, 65, 93, 69, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 115 { jwin_text_proc, 8, 55, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Font:", NULL, NULL }, { jwin_text_proc, 8, 73, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Style:", NULL, NULL }, { jwin_text_proc, 8, 91, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Alignment:", NULL, NULL }, { jwin_text_proc, 8, 105, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Text:", NULL, NULL }, { jwin_fontdrop_proc, 55, 51, 110, 16, 0, 0, 0, 0, 0, 0, (void *) &ssfont_list, NULL, NULL }, // 120 { jwin_droplist_proc, 55, 69, 110, 16, 0, 0, 0, 0, 0, 0, (void *) &shadowstyle_list, NULL, NULL }, { jwin_droplist_proc, 55, 87, 110, 16, 0, 0, 0, 0, 0, 0, (void *) &alignment_list, NULL, NULL }, { jwin_edit_proc, 8, 115, 146, 16, 0, 0, 0, 0, 255, 0, NULL, NULL, NULL }, { jwin_text_proc, 166, 55, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Wrapping:", NULL, NULL }, { jwin_text_proc, 166, 73, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Tab Size:", NULL, NULL }, // 125 { jwin_droplist_proc, 212, 51, 83, 16, 0, 0, 0, 0, 0, 0, (void *) &wrapping_list, NULL, NULL }, { jwin_edit_proc, 212, 69, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_text_proc, 8, 55, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Item Class:", NULL, NULL }, { jwin_text_proc, 8, 73, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Position:", NULL, NULL }, { jwin_text_proc, 8, 91, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Up Select:", NULL, NULL }, // 130 { jwin_text_proc, 8, 109, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Down Select:", NULL, NULL }, { jwin_text_proc, 8, 127, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Left Select:", NULL, NULL }, { jwin_text_proc, 8, 145, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Right Select:", NULL, NULL }, { jwin_droplist_proc, 68, 51, 101, 16, 0, 0, 0, 0, 0, 0, (void *) &itemclass_list, NULL, NULL }, { jwin_edit_proc, 68, 69, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, // 135 { jwin_edit_proc, 68, 87, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_edit_proc, 68, 105, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_edit_proc, 68, 123, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_edit_proc, 68, 141, 83, 16, 0, 0, 0, 0, 2, 0, NULL, NULL, NULL }, { jwin_check_proc, 68, 177, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Invisible", NULL, NULL }, // 140 { jwin_check_proc, 166, 139, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Show Compass", NULL, NULL }, { jwin_check_proc, 166, 149, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Large", NULL, NULL }, { jwin_ctext_proc, 18, 45, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "NOT", NULL, NULL }, { jwin_ctext_proc, 18, 51, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "LAST", NULL, NULL }, { jwin_frame_proc, 8, 57, 20, 20, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, // 145 { d_qtile_proc, 10, 59, 16, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_ctext_proc, 56, 51, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "LAST", NULL, NULL }, { jwin_frame_proc, 46, 57, 20, 20, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_qtile_proc, 48, 59, 16, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 150 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_ctext_proc, 18, 101, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "CAP", NULL, NULL }, { jwin_frame_proc, 8, 107, 20, 20, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_qtile_proc, 10, 109, 16, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_ctext_proc, 56, 95, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "AFTER", NULL, NULL }, // 155 { jwin_ctext_proc, 56, 101, 70, 36, 0, 0, 0, D_DISABLED, 0, 0, (void *) "CAP", NULL, NULL }, { jwin_frame_proc, 46, 107, 20, 20, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_qtile_proc, 48, 109, 16, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_check_proc, 8, 78, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Mod", NULL, NULL }, { jwin_check_proc, 46, 78, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Mod", NULL, NULL }, // 160 { jwin_check_proc, 8, 128, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Mod", NULL, NULL }, { jwin_check_proc, 46, 128, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Mod", NULL, NULL }, { jwin_text_proc, 166, 109, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Show:", NULL, NULL }, { jwin_droplist_proc, 215, 105, 68, 16, 0, 0, 0, 0, 0, 0, (void *) &gaugeshow_list, NULL, NULL }, { jwin_text_proc, 166, 133, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Container:", NULL, NULL }, // 165 { jwin_edit_proc, 215, 129, 35, 16, vc(12), vc(1), 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_check_proc, 166, 147, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Unique Last", NULL, NULL }, { jwin_text_proc, 166, 91, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Infinite Character:", NULL, NULL }, { jwin_edit_proc, 253, 87, 58, 16, 0, 0, 0, 0, 1, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 170 { jwin_ctext_proc, 160, 122, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, D_DISABLED, 0, 0, (void *) "Part of Attributes", NULL, NULL }, { jwin_check_proc, 8, 51, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Show 1", NULL, NULL }, { jwin_check_proc, 8, 63, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Show 2", NULL, NULL }, { jwin_check_proc, 8, 75, 128, 9, vc(14), vc(1), 0, 0, 1, 0, (void *) "Show 3", NULL, NULL }, { jwin_text_proc, 8, 51, 96, 8, vc(14), vc(1), 0, 0, 0, 0, (void *) "Rows:", NULL, NULL }, // 175 { jwin_droplist_proc, 57, 47, 68, 16, 0, 0, 0, 0, 0, 0, (void *) &rows_list, NULL, NULL }, { jwin_droplist_proc, 68, 159, 128, 16, 0, 0, 0, 0, 3, 0, (void *) &item_list, NULL, NULL }, { jwin_text_proc, 8, 163, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) "Item Override:", NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 180 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 185 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 190 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 195 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 200 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 205 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 210 { d_dummy_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_check_proc, 115, 48, 70, 9, 0, 0, 0, 0, 0, 0, (void *) "Active Down", NULL, NULL }, { jwin_check_proc, 190, 48, 70, 9, 0, 0, 0, 0, 0, 0, (void *) "Active Scrolling", NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; void replacedp(DIALOG &d, const char *newdp, size_t size) { if((d.proc==d_alltriggerbutton_proc)|| (d.proc==d_button_proc)|| (d.proc==d_check_proc)|| (d.proc==d_comboa_radio_proc)|| (d.proc==d_comboabutton_proc)|| (d.proc==d_ctext_proc)|| (d.proc==d_edit_proc)|| (d.proc==d_jbutton_proc)|| (d.proc==d_kbutton_proc)|| (d.proc==d_listen_proc)|| (d.proc==d_savemidi_proc)|| (d.proc==d_ssdn_btn_proc)|| (d.proc==d_ssdn_btn2_proc)|| (d.proc==d_ssdn_btn3_proc)|| (d.proc==d_ssdn_btn4_proc)|| (d.proc==d_sslt_btn_proc)|| (d.proc==d_sslt_btn2_proc)|| (d.proc==d_sslt_btn3_proc)|| (d.proc==d_sslt_btn4_proc)|| (d.proc==d_ssrt_btn_proc)|| (d.proc==d_ssrt_btn2_proc)|| (d.proc==d_ssrt_btn3_proc)|| (d.proc==d_ssrt_btn4_proc)|| (d.proc==d_ssup_btn_proc)|| (d.proc==d_ssup_btn2_proc)|| (d.proc==d_ssup_btn3_proc)|| (d.proc==d_ssup_btn4_proc)|| (d.proc==d_text_proc)|| (d.proc==d_tri_edit_proc)|| (d.proc==d_triggerbutton_proc)|| (d.proc==jwin_button_proc)|| (d.proc==jwin_check_proc)|| (d.proc==jwin_ctext_proc)|| (d.proc==jwin_radio_proc)|| (d.proc==jwin_rtext_proc)|| (d.proc==jwin_text_proc)|| (d.proc==jwin_win_proc) || (d.proc==jwin_edit_proc)) { if(d.dp != NULL) zc_free(d.dp); if(newdp != NULL) { size = zc_max(size, strlen((char *)newdp)+1); d.dp = zc_malloc(size); strcpy((char*)d.dp, newdp); } else d.dp = NULL; } else { d.dp = (void *)newdp; } } int sso_properties(subscreen_object *tempsso) { copy_dialog(&sso_properties_dlg, sso_master_properties_dlg); char title[256], x_str[256],y_str[256],w_str[256],h_str[256],f_str[256],s_str[256],d_str[256]; int x_stri=0, y_stri=0, w_stri=0, h_stri=0,f_stri=0,s_stri=0,d_stri=0; char buf[256], buf2[256], buf3[256], buf4[256], buf5[256]; int bufi=0, buf2i=0, buf3i=0,buf4i=0,buf5i=0; memset(title, 0, 256); memset(x_str, 0, 256); memset(y_str, 0, 256); memset(w_str, 0, 256); memset(h_str, 0, 256); memset(f_str, 0, 256); memset(s_str, 0, 256); memset(d_str, 0, 256); memset(buf, 0, 256); memset(buf2, 0, 256); memset(buf3, 0, 256); memset(buf4, 0, 256); memset(buf5, 0, 256); sprintf(title, "%s Properties (Object #%d)", sso_name(tempsso->type), curr_subscreen_object); sprintf(x_str, "invalid"); sprintf(y_str, "invalid"); sprintf(w_str, "invalid"); sprintf(h_str, "invalid"); int ret=-1; replacedp(sso_properties_dlg[0],title); sso_properties_dlg[0].dp2=lfont; //for everything sso_properties_dlg[6].flags = (tempsso->pos & sspUP) != 0 ? D_SELECTED : 0; sso_properties_dlg[212].flags = (tempsso->pos & sspDOWN) != 0 ? D_SELECTED : 0; sso_properties_dlg[213].flags = (tempsso->pos & sspSCROLLING) != 0 ? D_SELECTED : 0; sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_dlg[8],x_str); x_stri=8; replacedp(sso_properties_dlg[10],y_str); y_stri=10; replacedp(sso_properties_dlg[12],w_str); w_stri=12; replacedp(sso_properties_dlg[14],h_str); h_stri=14; sso_properties_dlg[95].bg=jwin_pal[jcBOX]; sso_properties_dlg[95].fg=jwin_pal[jcBOX]; sso_properties_dlg[96].dp2=spfont; sso_properties_dlg[99].dp2=spfont; replacedp(sso_properties_dlg[108],x_str); x_stri=108; replacedp(sso_properties_dlg[109],x_str); x_stri=109; replacedp(sso_properties_dlg[110],x_str); x_stri=110; replacedp(sso_properties_dlg[114],x_str); x_stri=114; replacedp(sso_properties_dlg[122],x_str); x_stri=112; sso_properties_dlg[122].dp2=ss_font(ssfZELDA); sso_properties_dlg[122].h=text_height(ss_font(ssfZELDA))+8; replacedp(sso_properties_dlg[126],x_str); x_stri=126; replacedp(sso_properties_dlg[134],x_str); x_stri=134; replacedp(sso_properties_dlg[135],x_str); x_stri=134; replacedp(sso_properties_dlg[136],x_str); x_stri=136; replacedp(sso_properties_dlg[137],x_str); x_stri=137; replacedp(sso_properties_dlg[138],x_str); x_stri=138; sso_properties_dlg[142].dp2=spfont; sso_properties_dlg[143].dp2=spfont; sso_properties_dlg[147].dp2=spfont; sso_properties_dlg[151].dp2=spfont; sso_properties_dlg[154].dp2=spfont; sso_properties_dlg[155].dp2=spfont; replacedp(sso_properties_dlg[165],x_str); x_stri=165; sso_properties_dlg[168].dp2=ss_font(ssfZELDA); sso_properties_dlg[168].h=text_height(ss_font(ssfZELDA))+8; replacedp(sso_properties_dlg[168],x_str); x_stri=168; if(biic_cnt==-1) build_biic_list(); DIALOG *sso_properties_cpy = resizeDialog(sso_properties_dlg, 1.5); if(is_large()) { sso_properties_cpy[126].proc = sso_properties_cpy[136].proc = sso_properties_cpy[137].proc = sso_properties_cpy[138].proc = jwin_droplist_proc; // jwin_edit_proc, but sometimes jwin_droplist_proc sso_properties_cpy[126].proc = sso_properties_cpy[136].proc = sso_properties_cpy[137].proc = sso_properties_cpy[138].proc = jwin_edit_proc; sso_properties_cpy[95].w=(156*2)+1; // d_box_proc sso_properties_cpy[95].h=(122*2)+1; sso_properties_cpy[97].x = sso_properties_cpy[98].x-2; // d_frame_proc sso_properties_cpy[97].y = sso_properties_cpy[98].y-2; for(int i = 99; i <= 104; i++) sso_properties_cpy[i].x += (i >=102 ? 80:64); for(int i = 158; i <= 162; i++) sso_properties_cpy[i].y += 8; sso_properties_cpy[100].x = sso_properties_cpy[101].x-2; // d_frame_proc sso_properties_cpy[100].y = sso_properties_cpy[101].y-2; } //item specific switch(tempsso->type) { case ssoNONE: { // I'd just disable it entirely if I knew how... dummy_dialog_proc(sso_properties_cpy +6); for(int i=11; i<=213; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } } break; case sso2X2FRAME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=99; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } // draw_block_flip(dest,x,y,css->objects[i].d1,subscreen_cset(misc, css->objects[i].colortype1, css->objects[i].color1),css->objects[i].w,css->objects[i].h,css->objects[i].d2,css->objects[i].d3,css->objects[i].d4); char cset_caption1[80]; char cset_caption2[80]; char scset_caption[80]; sprintf(cset_caption1, " CSet "); sprintf(cset_caption2, "CSet:"); sprintf(scset_caption, "Type:"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],cset_caption1); replacedp(sso_properties_cpy[37],cset_caption2); ListData csettype_list(csettypelist, is_large() ? &lfont_l : &font); sso_properties_cpy[38].proc=d_csl_proc; //A dubious cast, but I think correct -DD replacedp(sso_properties_cpy[38],(char *)&csettype_list); replacedp(sso_properties_cpy[39],scset_caption); extract_cset(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].proc=d_csl2_proc; ListData misccset_list(misccsetlist, is_large()? &lfont_l : &font); replacedp(sso_properties_cpy[40],(char *)&misccset_list); sso_properties_cpy[40].d1=tempsso->color1; update_csl_proc(sso_properties_cpy +39, sso_properties_cpy[38].d1); //sso_properties_dlg[98].fg=sso_properties_dlg[38].d1?sso_properties_dlg[38].d1-1:sso_properties_dlg[40].d1; sso_properties_cpy[98].fg=subscreen_cset(&misc, sso_properties_cpy[38].d1? sso_properties_cpy[38].d1-1:ssctMISC, sso_properties_cpy[40].d1); sso_properties_cpy[98].d1=tempsso->d1; sso_properties_cpy[98].d2=tempsso->d2; sso_properties_cpy[98].proc=d_tileblock_proc; sso_properties_cpy[98].w=is_large()?64:32; sso_properties_cpy[98].h=is_large()?64:32; sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[102].flags=tempsso->d3?D_SELECTED:0; sso_properties_cpy[103].flags=tempsso->d4?D_SELECTED:0; } break; case ssoTEXT: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=123; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); buf[0]=0; if(tempsso->dp1!=NULL) { strcpy(buf, (char *)tempsso->dp1); } sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; replacedp(sso_properties_cpy[122],buf); bufi=122; sso_properties_cpy[122].dp2=ss_font(tempsso->d1); sso_properties_cpy[122].h=text_height(ss_font(tempsso->d1))+8; } break; case ssoLINE: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char lc_color_caption[80]; sprintf(lc_color_caption, " Line Color "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],lc_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); sso_properties_cpy[102].flags|=(tempsso->d3)?D_SELECTED:0; sso_properties_cpy[103].flags|=(tempsso->d4)?D_SELECTED:0; } break; case ssoRECT: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=47; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char ol_color_caption[80]; char f_color_caption[80]; char filled_caption[80]; sprintf(ol_color_caption, " Outline Color "); sprintf(f_color_caption, " Fill Color "); sprintf(filled_caption, "Filled"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],ol_color_caption); replacedp(sso_properties_cpy[42],f_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); sso_properties_cpy[102].flags|=(tempsso->d1)?D_SELECTED:0; replacedp(sso_properties_cpy[102],filled_caption); sso_properties_cpy[103].flags|=(tempsso->d2)?D_SELECTED:0; } break; case ssoBSTIME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +118); for(int i=122; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; } break; case ssoTIME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +118); for(int i=122; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; } break; case ssoSSTIME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +118); for(int i=122; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; } break; case ssoMAGICMETER: { for(int i=11; i<=93; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=95; i<=169; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=171; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char no_prop[80]; sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(no_prop, "No Properties Available"); //Bad! You must use replacedp or you will run into major pointer problems... -DD //sso_properties_dlg[8].dp=x_str; //sso_properties_dlg[10].dp=y_str; //sso_properties_dlg[94].dp=no_prop; //sso_properties_dlg[170].dp=no_prop; replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[94],no_prop); replacedp(sso_properties_cpy[170],no_prop); } break; case ssoLIFEMETER: { for(int i=11; i<=93; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=95; i<=138; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=140; i<=173; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=176; i<=210; i++) { dummy_dialog_proc(sso_properties_cpy +i); } char bs_style[80]; sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(bs_style, "BS-Zelda Style"); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[139],bs_style); sso_properties_cpy[139].flags=tempsso->d2?D_SELECTED:0; sso_properties_cpy[175].d1 = tempsso->d3; } break; case ssoBUTTONITEM: { for(int i=15; i<=102; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=116; i<=118; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=120; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char button_caption[80]; sprintf(button_caption, "Button:"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; sso_properties_cpy[103].flags|=(tempsso->d2)?D_SELECTED:0; replacedp(sso_properties_cpy[115],button_caption); ListData button_list(buttonlist, is_large()? &lfont_l : &font); replacedp(sso_properties_cpy[119],(char *)&button_list); sso_properties_cpy[119].d1=tempsso->d1; } break; case ssoICON: { } break; case ssoCOUNTER: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +118); dummy_dialog_proc(sso_properties_cpy +122); for(int i=127; i<=129; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=133; i<=135; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +139); for(int i=142; i<=166; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=169; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; char item_1_caption[80]; char item_2_caption[80]; char item_3_caption[80]; char digits_caption[80]; char zero_caption[80]; char selected_caption[80]; char infinite_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(item_1_caption, "Item 1:"); sprintf(item_2_caption, "Item 2:"); sprintf(item_3_caption, "Item 3:"); sprintf(infinite_caption, "Infinite:"); sprintf(digits_caption, "Digits:"); sprintf(zero_caption, "Show Zero"); sprintf(selected_caption, "Only Selected"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); sprintf(buf, "%d", tempsso->d4); sprintf(buf2, "%c", tempsso->d5); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; replacedp(sso_properties_cpy[123],digits_caption); replacedp(sso_properties_cpy[124],infinite_caption); //why, guys, why?!?? :( sso_properties_cpy[125].dp = NULL; sso_properties_cpy[125].proc=jwin_edit_proc; replacedp(sso_properties_cpy[125],buf); bufi = 125; sso_properties_cpy[125].d1 = 255; sso_properties_cpy[125].x-=8; sso_properties_cpy[125].w+=24; //Infinite Item if(bii_cnt==-1) { build_bii_list(true); } int index=tempsso->d10; int itemid = 0; for(int i=0; i<bii_cnt; i++) { if(bii[i].i == index) { itemid = i; break; } } sso_properties_cpy[126].proc=jwin_droplist_proc; replacedp(sso_properties_cpy[126],(char *)&item_list); sso_properties_cpy[126].d1=itemid; sso_properties_cpy[126].x-=8; sso_properties_cpy[126].w+=24; replacedp(sso_properties_cpy[130],item_1_caption); replacedp(sso_properties_cpy[131],item_2_caption); replacedp(sso_properties_cpy[132],item_3_caption); sso_properties_cpy[136].proc=jwin_droplist_proc; ListData icounter_list(icounterlist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[136],(char *)&icounter_list); sso_properties_cpy[136].d1=tempsso->d7; sso_properties_cpy[136].x-=13; sso_properties_cpy[136].w+=56; sso_properties_cpy[137].proc=jwin_droplist_proc; replacedp(sso_properties_cpy[137],(char *)&icounter_list); sso_properties_cpy[137].d1=tempsso->d8; sso_properties_cpy[137].x-=13; sso_properties_cpy[137].w+=56; sso_properties_cpy[138].proc=jwin_droplist_proc; replacedp(sso_properties_cpy[138],(char *)&icounter_list); sso_properties_cpy[138].d1=tempsso->d9; sso_properties_cpy[138].x-=13; sso_properties_cpy[138].w+=56; replacedp(sso_properties_cpy[168],buf2); buf2i=168; sso_properties_cpy[168].dp2=ss_font(tempsso->d1); sso_properties_cpy[168].h=text_height(ss_font(tempsso->d1))+8; replacedp(sso_properties_cpy[140],zero_caption); sso_properties_cpy[140].flags=tempsso->d6&1?D_SELECTED:0; sso_properties_cpy[140].x += 40; replacedp(sso_properties_cpy[141],selected_caption); sso_properties_cpy[141].flags=tempsso->d6&2?D_SELECTED:0; sso_properties_cpy[141].x += 40; } break; case ssoCOUNTERS: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +117); dummy_dialog_proc(sso_properties_cpy +118); dummy_dialog_proc(sso_properties_cpy +121); dummy_dialog_proc(sso_properties_cpy +122); dummy_dialog_proc(sso_properties_cpy +123); dummy_dialog_proc(sso_properties_cpy +125); for(int i=127; i<=139; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=141; i<=166; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=169; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; char item_caption[80]; char digits_caption[80]; char x_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(item_caption, "Item:"); sprintf(digits_caption, "Digits:"); sprintf(x_caption, "Use X"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); sprintf(buf, "%d", tempsso->d4); sprintf(buf2, "%c", tempsso->d5); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; replacedp(sso_properties_cpy[124],digits_caption); replacedp(sso_properties_cpy[126],buf); bufi=126; sso_properties_cpy[126].x-=8; sso_properties_cpy[126].w+=24; replacedp(sso_properties_cpy[168],buf2); buf2i=168; sso_properties_cpy[168].dp2=ss_font(tempsso->d1); sso_properties_cpy[168].h=text_height(ss_font(tempsso->d1))+8; replacedp(sso_properties_cpy[140],x_caption); sso_properties_cpy[140].flags=tempsso->d2?D_SELECTED:0; } break; case ssoMINIMAPTITLE: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } dummy_dialog_proc(sso_properties_cpy +118); for(int i=122; i<=210; ++i) { if(i!=139) dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; char map_rule_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); sprintf(map_rule_caption, "Invisible w/o Dungeon Map"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); replacedp(sso_properties_cpy[139],map_rule_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; sso_properties_cpy[139].flags=tempsso->d4?D_SELECTED:0; } break; case ssoMINIMAP: { for(int i=11; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=170; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=174; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; char show1[80]; char show2[80]; char show3[80]; sprintf(t_color_caption, " Link Color "); sprintf(s_color_caption, " C. Blink Color "); sprintf(b_color_caption, " C. Const Color "); sprintf(show1, " Show Map "); sprintf(show2, " Show Link "); sprintf(show3, " Show Compass "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); replacedp(sso_properties_cpy[171],show1); replacedp(sso_properties_cpy[172],show2); replacedp(sso_properties_cpy[173],show3); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[171].flags=tempsso->d1?D_SELECTED:0; sso_properties_cpy[172].flags=tempsso->d2?D_SELECTED:0; sso_properties_cpy[173].flags=tempsso->d3?D_SELECTED:0; } break; case ssoLARGEMAP: { for(int i=11; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=47; i<=138; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=140; i<=170; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=174; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char show1[80]; char show2[80]; char show3[80]; char bs_style[80]; sprintf(t_color_caption, " Room Color "); sprintf(s_color_caption, " Link Color "); sprintf(show1, " Show Map "); sprintf(show2, " Show Rooms "); sprintf(show3, " Show Link "); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(bs_style, "Large"); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[139],bs_style); replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[171],show1); replacedp(sso_properties_cpy[172],show2); replacedp(sso_properties_cpy[173],show3); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); sso_properties_cpy[171].flags=tempsso->d1?D_SELECTED:0; sso_properties_cpy[172].flags=tempsso->d2?D_SELECTED:0; sso_properties_cpy[173].flags=tempsso->d3?D_SELECTED:0; sso_properties_cpy[139].flags=tempsso->d10?D_SELECTED:0; } break; case ssoCLEAR: { for(int i=7; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char ss_color_caption[80]; sprintf(ss_color_caption, " Subscreen Color "); replacedp(sso_properties_cpy[36],ss_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); } break; case ssoCURRENTITEM: { for(int i=15; i<=93; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=95; i<=126; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=140; i<=175; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=178; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); sprintf(buf, "%d", tempsso->d3); sprintf(buf2, "%d", tempsso->d4); sprintf(buf3, "%d", tempsso->d5); sprintf(buf4, "%d", tempsso->d6); sprintf(buf5, "%d", tempsso->d7); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[134],buf); bufi=134; replacedp(sso_properties_cpy[135],buf2); buf2i=135; replacedp(sso_properties_cpy[136],buf3); buf3i=136; replacedp(sso_properties_cpy[137],buf4); buf4i=137; replacedp(sso_properties_cpy[138],buf5); buf5i=138; // Item Override droplist build_bii_list(true); int index=tempsso->d8-1; int itemid = 0; for(int i=0; i<bii_cnt; i++) { if(bii[i].i == index) { itemid = i; break; } } sso_properties_cpy[176].proc=jwin_droplist_proc; replacedp(sso_properties_cpy[176],(char *)&item_list); sso_properties_cpy[176].d1 = itemid; for(int j=0; j<biic_cnt; j++) { if(biic[j].i == tempsso->d1) sso_properties_cpy[133].d1 = j; } sso_properties_cpy[139].flags=tempsso->d2?0:D_SELECTED; } break; case ssoITEM: { } break; case ssoTRIFRAME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=47; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=105; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char fo_color_caption[80]; char n_color_caption[80]; char show_frame_caption[80]; char show_pieces_caption[80]; sprintf(fo_color_caption, " Frame Outline Color "); sprintf(n_color_caption, " Number Color "); sprintf(show_frame_caption, "Show Frame"); sprintf(show_pieces_caption, "Show Pieces"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],fo_color_caption); replacedp(sso_properties_cpy[42],n_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); sso_properties_cpy[98].w=(tempsso->d7?112:96)*(is_large() ? 2 : 1); sso_properties_cpy[98].h=(tempsso->d7?112:48)*(is_large() ? 2 : 1); sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[98].d1=tempsso->d1; sso_properties_cpy[98].fg=tempsso->d2; sso_properties_cpy[101].w=(tempsso->d7?32:16)*(is_large() ? 2 : 1); sso_properties_cpy[101].h=(tempsso->d7?48:16)*(is_large() ? 2 : 1); sso_properties_cpy[100].w= sso_properties_cpy[101].w+4; sso_properties_cpy[100].h= sso_properties_cpy[101].h+4; sso_properties_cpy[101].d1=tempsso->d3; sso_properties_cpy[101].fg=tempsso->d4; replacedp(sso_properties_cpy[102],show_frame_caption); sso_properties_cpy[102].flags=tempsso->d5?D_SELECTED:0; replacedp(sso_properties_cpy[103],show_pieces_caption); sso_properties_cpy[103].flags=tempsso->d6?D_SELECTED:0; sso_properties_cpy[104].flags=tempsso->d7?D_SELECTED:0; } break; case ssoTRIFORCE: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=99; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=163; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=166; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char cset_caption1[80]; char cset_caption2[80]; char scset_caption[80]; char piece_caption[80]; sprintf(cset_caption1, " CSet "); sprintf(cset_caption2, "CSet:"); sprintf(scset_caption, "Type:"); sprintf(piece_caption, "Piece #:"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); sprintf(buf, "%d", tempsso->d5); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],cset_caption1); replacedp(sso_properties_cpy[37],cset_caption2); sso_properties_cpy[38].proc=d_csl_proc; ListData csettype_list(csettypelist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[38],(char *)&csettype_list); replacedp(sso_properties_cpy[39],scset_caption); extract_cset(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].proc=d_csl2_proc; ListData misccset_list(misccsetlist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[40],(char *)&misccset_list); sso_properties_cpy[40].d1=tempsso->color1; update_csl_proc(sso_properties_cpy +39, sso_properties_cpy[38].d1); //sso_properties_dlg[98].fg=sso_properties_dlg[38].d1?sso_properties_dlg[38].d1-1:sso_properties_dlg[40].d1; sso_properties_cpy[98].fg=subscreen_cset(&misc, sso_properties_cpy[38].d1? sso_properties_cpy[38].d1-1:ssctMISC, sso_properties_cpy[40].d1); sso_properties_cpy[98].d1=tempsso->d1; sso_properties_cpy[98].d2=tempsso->d2; sso_properties_cpy[98].w=is_large()?32:16; sso_properties_cpy[98].h=is_large()?32:16; sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[98].proc=d_tileblock_proc; sso_properties_cpy[102].flags=tempsso->d3?D_SELECTED:0; sso_properties_cpy[103].flags=tempsso->d4?D_SELECTED:0; replacedp(sso_properties_cpy[164],piece_caption); replacedp(sso_properties_cpy[165],buf); bufi=165; } break; case ssoTILEBLOCK: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=99; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } // draw_block_flip(dest,x,y,css->objects[i].d1,subscreen_cset(misc, css->objects[i].colortype1, css->objects[i].color1),css->objects[i].w,css->objects[i].h,css->objects[i].d2,css->objects[i].d3,css->objects[i].d4); char cset_caption1[80]; char cset_caption2[80]; char scset_caption[80]; sprintf(cset_caption1, " CSet "); sprintf(cset_caption2, "CSet:"); sprintf(scset_caption, "Type:"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; sso_properties_cpy[38].proc=d_csl_proc; ListData csettype_list(csettypelist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[36],cset_caption1); replacedp(sso_properties_cpy[37],cset_caption2); replacedp(sso_properties_cpy[38],(char *)&csettype_list); replacedp(sso_properties_cpy[39],scset_caption); extract_cset(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].proc=d_csl2_proc; ListData misccset_list(misccsetlist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[40],(char *)&misccset_list); sso_properties_cpy[40].d1=tempsso->color1; update_csl_proc(sso_properties_cpy +39, sso_properties_cpy[38].d1); sso_properties_cpy[98].fg=subscreen_cset(&misc, sso_properties_cpy[38].d1? sso_properties_cpy[38].d1-1:ssctMISC, sso_properties_cpy[40].d1); sso_properties_cpy[98].d1=tempsso->d1; sso_properties_cpy[98].d2=tempsso->d2; sso_properties_cpy[98].w=is_large()?32:16; sso_properties_cpy[98].h=is_large()?32:16; sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[98].proc=d_tileblock_proc; sso_properties_cpy[102].flags=tempsso->d3?D_SELECTED:0; sso_properties_cpy[103].flags=tempsso->d4?D_SELECTED:0; } break; case ssoMINITILE: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=99; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=104; i<=110; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=113; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } // draw_block_flip(dest,x,y,css->objects[i].d1,subscreen_cset(misc, css->objects[i].colortype1, css->objects[i].color1),css->objects[i].w,css->objects[i].h,css->objects[i].d2,css->objects[i].d3,css->objects[i].d4); char cset_caption1[80]; char cset_caption2[80]; char scset_caption[80]; sprintf(cset_caption1, " CSet "); sprintf(cset_caption2, "CSet:"); sprintf(scset_caption, "Type:"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; sso_properties_cpy[38].proc=d_csl_proc; ListData csettype_list(csettypelist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[36],cset_caption1); replacedp(sso_properties_cpy[37],cset_caption2); replacedp(sso_properties_cpy[38],(char *)&csettype_list); replacedp(sso_properties_cpy[39],scset_caption); extract_cset(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].proc=d_csl2_proc; ListData misccset_list(misccsetlist, is_large() ? &lfont_l : &font); replacedp(sso_properties_cpy[40],(char *)&misccset_list); sso_properties_cpy[40].d1=tempsso->color1; update_csl_proc(sso_properties_cpy +39, sso_properties_cpy[38].d1); //sso_properties_dlg[98].fg=sso_properties_dlg[38].d1?sso_properties_dlg[38].d1-1:sso_properties_dlg[40].d1; sso_properties_cpy[98].fg=subscreen_cset(&misc, sso_properties_cpy[38].d1? sso_properties_cpy[38].d1-1:ssctMISC, sso_properties_cpy[40].d1); if(tempsso->d1!=-1) { sso_properties_cpy[98].d1=tempsso->d1>>2; sso_properties_cpy[98].bg=vbound(tempsso->d1-(sso_properties_cpy[98].d1<<2)+tempsso->d3,0,3); sso_properties_cpy[112].d1=0; sso_properties_cpy[112].d2=0; sso_properties_cpy[97].w=20; sso_properties_cpy[98].w=16; } else { switch(tempsso->d2) { case ssmstSSVINETILE: sso_properties_cpy[98].d1=wpnsbuf[iwSubscreenVine].tile; sso_properties_cpy[97].w=52; sso_properties_cpy[98].w=48; break; case ssmstMAGICMETER: sso_properties_cpy[98].d1=wpnsbuf[iwMMeter].tile; sso_properties_cpy[97].w=148; sso_properties_cpy[98].w=144; break; default: sso_properties_cpy[97].w=20; sso_properties_cpy[98].w=16; } sso_properties_cpy[98].bg=tempsso->d3; sso_properties_cpy[112].d1=tempsso->d2+1; sso_properties_cpy[112].d2= sso_properties_cpy[112].d1; } sso_properties_cpy[98].w*=(is_large()?2:1); sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[98].h=is_large()?32:16; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[98].d2=tempsso->d4; sso_properties_cpy[98].proc=d_spectile_proc; sso_properties_cpy[102].flags=tempsso->d5?D_SELECTED:0; sso_properties_cpy[103].flags=tempsso->d6?D_SELECTED:0; } break; case ssoSELECTOR1: case ssoSELECTOR2: { for(int i=11; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=41; i<=94; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=99; i<=101; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=105; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } // draw_block_flip(dest,x,y,css->objects[i].d1,subscreen_cset(misc, css->objects[i].colortype1, css->objects[i].color1),css->objects[i].w,css->objects[i].h,css->objects[i].d2,css->objects[i].d3,css->objects[i].d4); char cset_caption1[80]; char cset_caption2[80]; char scset_caption[80]; char large_caption[80]; sprintf(cset_caption1, " CSet "); sprintf(cset_caption2, "CSet:"); sprintf(scset_caption, "Type:"); sprintf(large_caption, "Large"); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; ListData csettype_list(csettypelist, is_large() ? &lfont_l : &font); sso_properties_cpy[38].proc=d_csl_proc; replacedp(sso_properties_cpy[36],cset_caption1); replacedp(sso_properties_cpy[37],cset_caption2); replacedp(sso_properties_cpy[38],(char *)&csettype_list); replacedp(sso_properties_cpy[39],scset_caption); extract_cset(sso_properties_cpy +38, tempsso, 1); ListData misccset_list(misccsetlist,is_large() ? &lfont_l : &font); sso_properties_cpy[40].proc=d_csl2_proc; replacedp(sso_properties_cpy[40],(char *)&misccset_list); sso_properties_cpy[40].d1=tempsso->color1; update_csl_proc(sso_properties_cpy +39, sso_properties_cpy[38].d1); //sso_properties_dlg[98].fg=sso_properties_dlg[38].d1?sso_properties_dlg[38].d1-1:sso_properties_dlg[40].d1; sso_properties_cpy[98].fg=subscreen_cset(&misc, sso_properties_cpy[38].d1? sso_properties_cpy[38].d1-1:ssctMISC, sso_properties_cpy[40].d1); sso_properties_cpy[98].d1=tempsso->d1; sso_properties_cpy[98].d2=tempsso->d2; sso_properties_cpy[98].proc=d_tileblock_proc; sso_properties_cpy[98].w=is_large()?64:32; sso_properties_cpy[98].h=is_large()?64:32; sso_properties_cpy[97].w= sso_properties_cpy[98].w+4; sso_properties_cpy[97].h= sso_properties_cpy[98].h+4; sso_properties_cpy[102].flags=tempsso->d3?D_SELECTED:0; sso_properties_cpy[103].flags=tempsso->d4?D_SELECTED:0; replacedp(sso_properties_cpy[104],large_caption); sso_properties_cpy[104].proc=jwin_lscheck_proc; sso_properties_cpy[104].flags=tempsso->d5?D_SELECTED:0; } break; case ssoMAGICGAUGE: { for(int i=15; i<=93; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=95; i<=104; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=111; i<=141; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=167; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); sprintf(f_str, "%d", tempsso->d6); sprintf(s_str, "%d", tempsso->d7); sprintf(d_str, "%d", tempsso->d8); // container sprintf(buf, "%d", tempsso->d1); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[108],f_str); f_stri=108; replacedp(sso_properties_cpy[109],s_str); s_stri=109; replacedp(sso_properties_cpy[110],d_str); d_stri=110; sso_properties_cpy[145].d1=(tempsso->d2)>>2; sso_properties_cpy[145].d2=0; sso_properties_cpy[145].fg=tempsso->colortype1; sso_properties_cpy[145].bg=(tempsso->d2)%4; sso_properties_cpy[144].w = sso_properties_cpy[145].w+4; sso_properties_cpy[144].h = sso_properties_cpy[145].h+4; sso_properties_cpy[144].x = sso_properties_cpy[145].x-3; sso_properties_cpy[144].y = sso_properties_cpy[145].y-3; sso_properties_cpy[149].d1=(tempsso->d3)>>2; sso_properties_cpy[149].d2=0; sso_properties_cpy[149].fg=tempsso->color1; sso_properties_cpy[149].bg=(tempsso->d3)%4; sso_properties_cpy[148].w = sso_properties_cpy[149].w+4; sso_properties_cpy[148].h = sso_properties_cpy[149].h+4; sso_properties_cpy[148].x = sso_properties_cpy[149].x-3; sso_properties_cpy[148].y = sso_properties_cpy[149].y-3; sso_properties_cpy[153].d1=(tempsso->d4)>>2; sso_properties_cpy[153].d2=0; sso_properties_cpy[153].fg=tempsso->colortype2; sso_properties_cpy[153].bg=(tempsso->d4)%4; sso_properties_cpy[152].w = sso_properties_cpy[153].w+4; sso_properties_cpy[152].h = sso_properties_cpy[153].h+4; sso_properties_cpy[152].x = sso_properties_cpy[153].x-3; sso_properties_cpy[152].y = sso_properties_cpy[153].y-3; sso_properties_cpy[157].d1=(tempsso->d5)>>2; sso_properties_cpy[157].d2=0; sso_properties_cpy[157].fg=tempsso->color2; sso_properties_cpy[157].bg=(tempsso->d5)%4; sso_properties_cpy[156].w = sso_properties_cpy[157].w+4; sso_properties_cpy[156].h = sso_properties_cpy[157].h+4; sso_properties_cpy[156].x = sso_properties_cpy[157].x-3; sso_properties_cpy[156].y = sso_properties_cpy[157].y-3; sso_properties_cpy[158].flags=((tempsso->d10)&1)?D_SELECTED:0; sso_properties_cpy[159].flags=((tempsso->d10)&2)?D_SELECTED:0; sso_properties_cpy[160].flags=((tempsso->d10)&4)?D_SELECTED:0; sso_properties_cpy[161].flags=((tempsso->d10)&8)?D_SELECTED:0; sso_properties_cpy[163].d1=tempsso->d9; replacedp(sso_properties_cpy[165],buf); bufi=165; sso_properties_cpy[166].flags=((tempsso->d10)&16)?D_SELECTED:0; } break; case ssoLIFEGAUGE: { for(int i=15; i<=93; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=95; i<=104; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=111; i<=141; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=167; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); sprintf(f_str, "%d", tempsso->d6); sprintf(s_str, "%d", tempsso->d7); sprintf(d_str, "%d", tempsso->d8); // container sprintf(buf, "%d", tempsso->d1); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[108],f_str); f_stri=108; replacedp(sso_properties_cpy[109],s_str); s_stri=109; replacedp(sso_properties_cpy[110],d_str); d_stri=110; sso_properties_cpy[145].d1=(tempsso->d2)>>2; sso_properties_cpy[145].d2=0; sso_properties_cpy[145].fg=tempsso->colortype1; sso_properties_cpy[145].bg=(tempsso->d2)%4; sso_properties_cpy[144].w = sso_properties_cpy[145].w+4; sso_properties_cpy[144].h = sso_properties_cpy[145].h+4; sso_properties_cpy[144].x = sso_properties_cpy[145].x-3; sso_properties_cpy[144].y = sso_properties_cpy[145].y-3; sso_properties_cpy[149].d1=(tempsso->d3)>>2; sso_properties_cpy[149].d2=0; sso_properties_cpy[149].fg=tempsso->color1; sso_properties_cpy[149].bg=(tempsso->d3)%4; sso_properties_cpy[148].w = sso_properties_cpy[149].w+4; sso_properties_cpy[148].h = sso_properties_cpy[149].h+4; sso_properties_cpy[148].x = sso_properties_cpy[149].x-3; sso_properties_cpy[148].y = sso_properties_cpy[149].y-3; sso_properties_cpy[153].d1=(tempsso->d4)>>2; sso_properties_cpy[153].d2=0; sso_properties_cpy[153].fg=tempsso->colortype2; sso_properties_cpy[153].bg=(tempsso->d4)%4; sso_properties_cpy[152].w = sso_properties_cpy[153].w+4; sso_properties_cpy[152].h = sso_properties_cpy[153].h+4; sso_properties_cpy[152].x = sso_properties_cpy[153].x-3; sso_properties_cpy[152].y = sso_properties_cpy[153].y-3; sso_properties_cpy[157].d1=(tempsso->d5)>>2; sso_properties_cpy[157].d2=0; sso_properties_cpy[157].fg=tempsso->color2; sso_properties_cpy[157].bg=(tempsso->d5)%4; sso_properties_cpy[156].w = sso_properties_cpy[157].w+4; sso_properties_cpy[156].h = sso_properties_cpy[157].h+4; sso_properties_cpy[156].x = sso_properties_cpy[157].x-3; sso_properties_cpy[156].y = sso_properties_cpy[157].y-3; sso_properties_cpy[158].flags=((tempsso->d10)&1)?D_SELECTED:0; sso_properties_cpy[159].flags=((tempsso->d10)&2)?D_SELECTED:0; sso_properties_cpy[160].flags=((tempsso->d10)&4)?D_SELECTED:0; sso_properties_cpy[161].flags=((tempsso->d10)&8)?D_SELECTED:0; sso_properties_cpy[163].d1=tempsso->d9; replacedp(sso_properties_cpy[165],buf); bufi=165; sso_properties_cpy[166].flags=((tempsso->d10)&16)?D_SELECTED:0; } break; case ssoTEXTBOX: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=127; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); strcpy(buf, (char *)tempsso->dp1); sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", tempsso->w); sprintf(h_str, "%d", tempsso->h); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; replacedp(sso_properties_cpy[122],buf); bufi=122; sso_properties_cpy[122].dp2=ss_font(tempsso->d1); sso_properties_cpy[122].h=text_height(ss_font(tempsso->d1))+8; sso_properties_cpy[125].d1=tempsso->d4; sprintf(buf2, "%d", tempsso->d5); replacedp(sso_properties_cpy[126],buf2); buf2i=126; } break; case ssoCURRENTITEMTILE: { } break; case ssoSELECTEDITEMTILE: { } break; case ssoCURRENTITEMTEXT: { } break; case ssoCURRENTITEMNAME: { } break; case ssoSELECTEDITEMNAME: { for(int i=15; i<=34; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=53; i<=114; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } for(int i=127; i<=210; ++i) { dummy_dialog_proc(sso_properties_cpy +i); } char t_color_caption[80]; char s_color_caption[80]; char b_color_caption[80]; sprintf(t_color_caption, " Text Color "); sprintf(s_color_caption, " Shadow Color "); sprintf(b_color_caption, " Background Color "); buf[0]=0; sprintf(x_str, "%d", tempsso->x); sprintf(y_str, "%d", tempsso->y); sprintf(w_str, "%d", sso_w(tempsso)); sprintf(h_str, "%d", sso_h(tempsso)); replacedp(sso_properties_cpy[8],x_str); x_stri=8; replacedp(sso_properties_cpy[10],y_str); y_stri=10; replacedp(sso_properties_cpy[12],w_str); w_stri=12; replacedp(sso_properties_cpy[14],h_str); h_stri=14; replacedp(sso_properties_cpy[36],t_color_caption); replacedp(sso_properties_cpy[42],s_color_caption); replacedp(sso_properties_cpy[48],b_color_caption); extract_colortype(sso_properties_cpy +38, tempsso, 1); sso_properties_cpy[40].d1=tempsso->color1; update_ctl_proc(sso_properties_cpy +40, sso_properties_cpy[38].d1); extract_colortype(sso_properties_cpy +44, tempsso, 2); sso_properties_cpy[46].d1=tempsso->color2; update_ctl_proc(sso_properties_cpy +46, sso_properties_cpy[44].d1); extract_colortype(sso_properties_cpy +50, tempsso, 3); sso_properties_cpy[52].d1=tempsso->color3; update_ctl_proc(sso_properties_cpy +52, sso_properties_cpy[50].d1); sso_properties_cpy[119].d1=tempsso->d1; sso_properties_cpy[120].d1=tempsso->d3; sso_properties_cpy[121].d1=tempsso->d2; replacedp(sso_properties_cpy[122],buf); bufi=122; sso_properties_cpy[122].dp2=ss_font(tempsso->d1); sso_properties_cpy[122].h=text_height(ss_font(tempsso->d1))+8; sso_properties_cpy[125].d1=tempsso->d4; sprintf(buf2, "%d", tempsso->d5); replacedp(sso_properties_cpy[126],buf2); buf2i=126; } break; case ssoCURRENTITEMCLASSTEXT: { } break; case ssoCURRENTITEMCLASSNAME: { } break; case ssoSELECTEDITEMCLASSNAME: { } break; default: { } break; } ret=zc_popup_dialog(sso_properties_cpy,2); //Bad idea //leaks memory -DD /*if (ret==2) { return -1; }*/ if(ret != 2) { //for everything tempsso->pos = 0; if((sso_properties_cpy[6].flags & D_SELECTED) != 0) tempsso->pos |= sspUP; if((sso_properties_cpy[212].flags & D_SELECTED) != 0) tempsso->pos |= sspDOWN; if((sso_properties_cpy[213].flags & D_SELECTED) != 0) tempsso->pos |= sspSCROLLING; //item specific switch(tempsso->type) { case ssoNONE: { } break; case sso2X2FRAME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_cset(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; tempsso->d1= sso_properties_cpy[98].d1; tempsso->d2= sso_properties_cpy[98].d2; tempsso->d3= sso_properties_cpy[102].flags&D_SELECTED?1:0; tempsso->d4= sso_properties_cpy[103].flags&D_SELECTED?1:0; } break; case ssoTEXT: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; if(tempsso->dp1!=NULL) { //zc_free((char *)(tempsso->dp1)); delete[]((char *)(tempsso->dp1)); } //(tempsso->dp1)=(char *)zc_malloc(strlen((char *)sso_properties_dlg[bufi].dp)+1); tempsso->dp1 = new char[strlen((char *)sso_properties_cpy[bufi].dp)+1]; strcpy((char *)tempsso->dp1, (char *)sso_properties_cpy[bufi].dp); } break; case ssoLINE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; tempsso->d1=(sso_properties_cpy[102].flags&D_SELECTED)?1:0; tempsso->d2=(sso_properties_cpy[103].flags&D_SELECTED)?1:0; } break; case ssoRECT: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; tempsso->d1=(sso_properties_cpy[102].flags&D_SELECTED)?1:0; tempsso->d2=(sso_properties_cpy[103].flags&D_SELECTED)?1:0; } break; case ssoBSTIME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; } break; case ssoTIME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; } break; case ssoSSTIME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; } break; case ssoMAGICMETER: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); } break; case ssoLIFEMETER: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->d2=(sso_properties_cpy[139].flags&D_SELECTED)?1:0; tempsso->d3= sso_properties_cpy[175].d1; } break; case ssoBUTTONITEM: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); tempsso->d2=(sso_properties_cpy[103].flags&D_SELECTED)?1:0; tempsso->d1= sso_properties_cpy[119].d1; } break; case ssoICON: { } break; case ssoCOUNTER: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; tempsso->d4=atoi((char *)sso_properties_cpy[bufi].dp); tempsso->d5=((char *)sso_properties_cpy[buf2i].dp)[0]; tempsso->d6=(sso_properties_cpy[140].flags&D_SELECTED?1:0)+(sso_properties_cpy[141].flags&D_SELECTED?2:0); tempsso->d7= sso_properties_cpy[136].d1; tempsso->d8= sso_properties_cpy[137].d1; tempsso->d9= sso_properties_cpy[138].d1; tempsso->d10=bii[sso_properties_cpy[126].d1].i; } break; case ssoCOUNTERS: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d4=atoi((char *)sso_properties_cpy[bufi].dp); tempsso->d5=((char *)sso_properties_cpy[buf2i].dp)[0]; tempsso->d2= sso_properties_cpy[140].flags&D_SELECTED?1:0; } break; case ssoMINIMAPTITLE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; tempsso->d4=(sso_properties_cpy[139].flags&D_SELECTED)?1:0; } break; case ssoMINIMAP: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1=(sso_properties_cpy[171].flags&D_SELECTED)?1:0; tempsso->d2=(sso_properties_cpy[172].flags&D_SELECTED)?1:0; tempsso->d3=(sso_properties_cpy[173].flags&D_SELECTED)?1:0; } break; case ssoLARGEMAP: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; tempsso->d1=(sso_properties_cpy[171].flags&D_SELECTED)?1:0; tempsso->d2=(sso_properties_cpy[172].flags&D_SELECTED)?1:0; tempsso->d3=(sso_properties_cpy[173].flags&D_SELECTED)?1:0; tempsso->d10=(sso_properties_cpy[139].flags&D_SELECTED)?1:0; } break; case ssoCLEAR: { insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; } break; case ssoCURRENTITEM: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); tempsso->d3=atoi((char *)sso_properties_cpy[bufi].dp); tempsso->d4=atoi((char *)sso_properties_cpy[buf2i].dp); tempsso->d5=atoi((char *)sso_properties_cpy[buf3i].dp); tempsso->d6=atoi((char *)sso_properties_cpy[buf4i].dp); tempsso->d7=atoi((char *)sso_properties_cpy[buf5i].dp); tempsso->d8=vbound(bii[sso_properties_cpy[176].d1].i+1, 0, 255); tempsso->d1=vbound(biic[sso_properties_cpy[133].d1].i, 0, 255); tempsso->d2= sso_properties_cpy[139].flags&D_SELECTED?0:1; tempsso->d8=vbound(tempsso->d8,0,256); } break; case ssoITEM: { } break; case ssoTRIFRAME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; tempsso->d1= sso_properties_cpy[98].d1; tempsso->d2= sso_properties_cpy[98].fg; tempsso->d3= sso_properties_cpy[101].d1; tempsso->d4= sso_properties_cpy[101].fg; tempsso->d5=(sso_properties_cpy[102].flags&D_SELECTED)?1:0; tempsso->d6=(sso_properties_cpy[103].flags&D_SELECTED)?1:0; tempsso->d7=(sso_properties_cpy[104].flags&D_SELECTED)?1:0; } break; case ssoTRIFORCE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_cset(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; tempsso->d1= sso_properties_cpy[98].d1; tempsso->d2= sso_properties_cpy[98].d2; tempsso->d3= sso_properties_cpy[102].flags&D_SELECTED?1:0; tempsso->d4= sso_properties_cpy[103].flags&D_SELECTED?1:0; tempsso->d5=atoi((char *)sso_properties_cpy[bufi].dp); } break; case ssoTILEBLOCK: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_cset(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; tempsso->d1= sso_properties_cpy[98].d1; tempsso->d2= sso_properties_cpy[98].d2; tempsso->d3= sso_properties_cpy[102].flags&D_SELECTED?1:0; tempsso->d4= sso_properties_cpy[103].flags&D_SELECTED?1:0; } break; case ssoMINITILE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_cset(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; switch(sso_properties_cpy[112].d1-1) { case ssmstSSVINETILE: case ssmstMAGICMETER: tempsso->d1=-1; tempsso->d2= sso_properties_cpy[112].d1-1; tempsso->d3= sso_properties_cpy[98].bg; break; case -1: default: tempsso->d1=(sso_properties_cpy[98].d1<<2)+ sso_properties_cpy[98].bg; tempsso->d2=0; tempsso->d3=0; break; } tempsso->d4= sso_properties_cpy[98].d2; tempsso->d5= sso_properties_cpy[102].flags&D_SELECTED?1:0; tempsso->d6= sso_properties_cpy[103].flags&D_SELECTED?1:0; } break; case ssoSELECTOR1: case ssoSELECTOR2: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); //tempsso->w=atoi((char *)sso_properties_dlg[w_stri].dp); //tempsso->h=atoi((char *)sso_properties_dlg[h_stri].dp); insert_cset(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; tempsso->d1= sso_properties_cpy[98].d1; tempsso->d2= sso_properties_cpy[98].d2; tempsso->d3= sso_properties_cpy[102].flags&D_SELECTED?1:0; tempsso->d4= sso_properties_cpy[103].flags&D_SELECTED?1:0; tempsso->d5= sso_properties_cpy[104].flags&D_SELECTED?1:0; } break; case ssoMAGICGAUGE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); tempsso->d6=atoi((char *)sso_properties_cpy[f_stri].dp); tempsso->d7=atoi((char *)sso_properties_cpy[s_stri].dp); tempsso->d8=atoi((char *)sso_properties_cpy[d_stri].dp); tempsso->d2=(sso_properties_cpy[145].d1<<2)+ sso_properties_cpy[145].bg; tempsso->colortype1= sso_properties_cpy[145].fg; tempsso->d3=(sso_properties_cpy[149].d1<<2)+ sso_properties_cpy[149].bg; tempsso->color1= sso_properties_cpy[149].fg; tempsso->d4=(sso_properties_cpy[153].d1<<2)+ sso_properties_cpy[153].bg; tempsso->colortype2= sso_properties_cpy[153].fg; tempsso->d5=(sso_properties_cpy[157].d1<<2)+ sso_properties_cpy[157].bg; tempsso->color2= sso_properties_cpy[157].fg; tempsso->d10=((sso_properties_cpy[158].flags&D_SELECTED)?1:0)+ ((sso_properties_cpy[159].flags&D_SELECTED)?2:0)+ ((sso_properties_cpy[160].flags&D_SELECTED)?4:0)+ ((sso_properties_cpy[161].flags&D_SELECTED)?8:0)+ ((sso_properties_cpy[166].flags&D_SELECTED)?16:0); tempsso->d9= sso_properties_cpy[163].d1; tempsso->d1=atoi((char *)sso_properties_cpy[bufi].dp); } break; case ssoLIFEGAUGE: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); tempsso->d6=atoi((char *)sso_properties_cpy[f_stri].dp); tempsso->d7=atoi((char *)sso_properties_cpy[s_stri].dp); tempsso->d8=atoi((char *)sso_properties_cpy[d_stri].dp); tempsso->d2=(sso_properties_cpy[145].d1<<2)+ sso_properties_cpy[145].bg; tempsso->colortype1= sso_properties_cpy[145].fg; tempsso->d3=(sso_properties_cpy[149].d1<<2)+ sso_properties_cpy[149].bg; tempsso->color1= sso_properties_cpy[149].fg; tempsso->d4=(sso_properties_cpy[153].d1<<2)+ sso_properties_cpy[153].bg; tempsso->colortype2= sso_properties_cpy[153].fg; tempsso->d5=(sso_properties_cpy[157].d1<<2)+ sso_properties_cpy[157].bg; tempsso->color2= sso_properties_cpy[157].fg; tempsso->d10=((sso_properties_cpy[158].flags&D_SELECTED)?1:0)+ ((sso_properties_cpy[159].flags&D_SELECTED)?2:0)+ ((sso_properties_cpy[160].flags&D_SELECTED)?4:0)+ ((sso_properties_cpy[161].flags&D_SELECTED)?8:0)+ ((sso_properties_cpy[166].flags&D_SELECTED)?16:0); tempsso->d9= sso_properties_cpy[163].d1; tempsso->d1=atoi((char *)sso_properties_cpy[bufi].dp); } break; case ssoTEXTBOX: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; if(tempsso->dp1!=NULL) { //zc_free((char *)(tempsso->dp1)); delete[]((char *)(tempsso->dp1)); } //(tempsso->dp1)=(char *)zc_malloc(strlen((char *)sso_properties_dlg[bufi].dp)+1); tempsso->dp1 = new char[strlen((char *)sso_properties_cpy[bufi].dp)+1]; strcpy((char *)tempsso->dp1, (char *)sso_properties_cpy[bufi].dp); tempsso->d4= sso_properties_cpy[125].d1; tempsso->d5=atoi((char *)sso_properties_cpy[buf2i].dp); } break; case ssoCURRENTITEMTILE: { } break; case ssoSELECTEDITEMTILE: { } break; case ssoCURRENTITEMTEXT: { } break; case ssoCURRENTITEMNAME: { } break; case ssoSELECTEDITEMNAME: { tempsso->x=atoi((char *)sso_properties_cpy[x_stri].dp); tempsso->y=atoi((char *)sso_properties_cpy[y_stri].dp); tempsso->w=atoi((char *)sso_properties_cpy[w_stri].dp); tempsso->h=atoi((char *)sso_properties_cpy[h_stri].dp); insert_colortype(sso_properties_cpy +38, tempsso, 1); tempsso->color1= sso_properties_cpy[40].d1; insert_colortype(sso_properties_cpy +44, tempsso, 2); tempsso->color2= sso_properties_cpy[46].d1; insert_colortype(sso_properties_cpy +50, tempsso, 3); tempsso->color3= sso_properties_cpy[52].d1; tempsso->d1= sso_properties_cpy[119].d1; tempsso->d3= sso_properties_cpy[120].d1; tempsso->d2= sso_properties_cpy[121].d1; tempsso->d4= sso_properties_cpy[125].d1; tempsso->d5=atoi((char *)sso_properties_cpy[buf2i].dp); } break; case ssoCURRENTITEMCLASSTEXT: { } break; case ssoCURRENTITEMCLASSNAME: { } break; case ssoSELECTEDITEMCLASSNAME: { } break; default: { } break; } } delete[] sso_properties_cpy; free_dialog(&sso_properties_dlg); //for(map<int, char *>::iterator it = itemclassnames.begin(); it != itemclassnames.end(); it++) // delete[] it->second; //itemclassnames.clear(); return (ret==2) ? -1 : 0; } int onBringToFront(); int onBringForward(); int onSendBackward(); int onSendToBack(); int onReverseArrangement(); int onAlignLeft(); int onAlignCenter(); int onAlignRight(); int onAlignTop(); int onAlignMiddle(); int onAlignBottom(); int onDistributeLeft(); int onDistributeCenter(); int onDistributeRight(); int onDistributeTop(); int onDistributeMiddle(); int onDistributeBottom(); int onGridSnapLeft(); int onGridSnapCenter(); int onGridSnapRight(); int onGridSnapTop(); int onGridSnapMiddle(); int onGridSnapBottom(); void copySSOProperties(subscreen_object& src, subscreen_object& dest); int onSubscreenObjectProperties() { if(curr_subscreen_object >= 0) { if(sso_properties(&(css->objects[curr_subscreen_object]))!=-1) { for(int i=0; i<MAXSUBSCREENITEMS; i++) { if(!sso_selection[i]) continue; copySSOProperties(css->objects[curr_subscreen_object], css->objects[i]); } } } return D_O_K; } int onSubscreenObjectRawProperties() { if(curr_subscreen_object >= 0) { sso_raw_data(&(css->objects[curr_subscreen_object])); } return D_O_K; } int onNewSubscreenObject(); int onDeleteSubscreenObject() { int objs=ss_objects(css); if(objs==0) { return D_O_K; } for(int i=curr_subscreen_object; i<objs-1; ++i) { css->objects[i]=css->objects[i+1]; sso_selection[i]=sso_selection[i+1]; } if(css->objects[objs-1].dp1!=NULL) { //No, don't do this. css->objects[objs-2] is pointing at this. Leave it be. //delete [] (char *)css->objects[objs-1].dp1; css->objects[objs-1].dp1=NULL; } css->objects[objs-1].type=ssoNULL; sso_selection[objs-1]=false; if(ss_propCopySrc==curr_subscreen_object) ss_propCopySrc=-1; else if(ss_propCopySrc>curr_subscreen_object) ss_propCopySrc--; if(curr_subscreen_object==objs-1) { --curr_subscreen_object; } update_sso_name(); update_up_dn_btns(); return D_O_K; } int onAddToSelection() { if(curr_subscreen_object >= 0) { sso_selection[curr_subscreen_object]=true; } return D_O_K; } int onRemoveFromSelection() { if(curr_subscreen_object >= 0) { sso_selection[curr_subscreen_object]=false; } return D_O_K; } int onInvertSelection() { for(int i=0; i<ss_objects(css); ++i) { sso_selection[i]=!sso_selection[i]; } return D_O_K; } int onClearSelection() { for(int i=0; i<MAXSUBSCREENITEMS; ++i) { sso_selection[i]=false; } return D_O_K; } int onDuplicateSubscreenObject() { int objs=ss_objects(css); if(objs==0) { return D_O_K; } int counter=0; for(int i=0; i<objs; ++i) { int c=objs+counter; if(sso_selection[i]||i==curr_subscreen_object) { if(css->objects[c].dp1!=NULL) { delete [](char *)css->objects[c].dp1; } css->objects[c]=css->objects[i]; if(css->objects[c].dp1!=NULL) { //No, don't do this. css->objects[i] is pointing at this. Leave it be. //delete [] (char *)css->objects[c].dp1; css->objects[c].dp1=NULL; } if(css->objects[i].dp1!=NULL) { //css->objects[c].dp1=zc_malloc(strlen((char *)css->objects[i].dp1)+1); css->objects[c].dp1= new char[strlen((char *)css->objects[i].dp1)+1]; strcpy((char *)css->objects[c].dp1,(char *)css->objects[i].dp1); } else { //css->objects[c].dp1=zc_malloc(2); css->objects[c].dp1 = new char[2]; ((char *)css->objects[c].dp1)[0]=0; } css->objects[c].x+=zc_max(zinit.ss_grid_x>>1,4); css->objects[c].y+=zc_max(zinit.ss_grid_y>>1,4); ++counter; } } update_sso_name(); update_up_dn_btns(); return D_O_K; } static int onToggleInvis(); static int onEditGrid(); static int onSelectionOptions(); static int onShowHideGrid(); static MENU subscreen_rc_menu[] = { { (char *)"Properties ", NULL, NULL, 0, NULL }, { (char *)"Inspect ", NULL, NULL, 0, NULL }, { (char *)"Copy Properties ", NULL, NULL, 0, NULL }, { (char *)"Paste Properties ", NULL, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; int d_subscreen_proc(int msg,DIALOG *d,int) { switch(msg) { case MSG_CLICK: { for(int i=ss_objects(css)-1; i>=0; --i) { int x = sso_x(&css->objects[i])*(is_large() ? 2 : 1); int y=sso_y(&css->objects[i])*(is_large() ? 2 : 1); int w=sso_w(&css->objects[i])*(is_large() ? 2 : 1); int h=sso_h(&css->objects[i])*(is_large() ? 2 : 1); switch(get_alignment(&css->objects[i])) { case sstaCENTER: x-=(w/2); break; case sstaRIGHT: x-=w; break; case sstaLEFT: default: break; } if(isinRect(Backend::mouse->getVirtualScreenX(), Backend::mouse->getVirtualScreenY(),d->x+x, d->y+y, d->x+x+w-1, d->y+y+h-1)) { if(key[KEY_LSHIFT]||key[KEY_RSHIFT]) { if(sso_selection[i]==true) { sso_selection[i]=false; } else { sso_selection[curr_subscreen_object]=true; curr_subscreen_object=i; update_sso_name(); update_up_dn_btns(); } } else { onClearSelection(); curr_subscreen_object=i; update_sso_name(); update_up_dn_btns(); } break; } } if(Backend::mouse->rightButtonClicked()) //right mouse button { object_message(d,MSG_DRAW,0); // Disable "Paste Properties" if the copy source is invalid if(ss_propCopySrc<0 || css->objects[ss_propCopySrc].type==ssoNULL) subscreen_rc_menu[3].flags|=D_DISABLED; else subscreen_rc_menu[3].flags&=~D_DISABLED; int m = popup_menu(subscreen_rc_menu, Backend::mouse->getVirtualScreenX(), Backend::mouse->getVirtualScreenY()); switch(m) { case 0: // Properties onSubscreenObjectProperties(); break; case 1: // Inspect onSubscreenObjectRawProperties(); break; case 2: // Copy Properties ss_propCopySrc=curr_subscreen_object; break; case 3: // Paste Properties if(ss_propCopySrc>=0) // Hopefully unnecessary) { copySSOProperties(css->objects[ss_propCopySrc], css->objects[curr_subscreen_object]); for(int i=0; i<MAXSUBSCREENITEMS; i++) { if(!sso_selection[i]) continue; copySSOProperties(css->objects[ss_propCopySrc], css->objects[i]); } } break; } } return D_O_K; } break; case MSG_VSYNC: d->flags|=D_DIRTY; break; case MSG_DRAW: { Sitems.animate(); BITMAP *buf = create_bitmap_ex(8,d->w,d->h);//In Large Mode, this is actually 2x as large as needed, but whatever. if(buf) { clear_bitmap(buf); show_custom_subscreen(buf, &misc, (subscreen_group *)(d->dp), 0, 0, true, sspUP | sspDOWN | sspSCROLLING); for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]) { sso_bounding_box(buf, css, i, vc(zinit.ss_bbox_2_color)); } } sso_bounding_box(buf, css, curr_subscreen_object, vc(zinit.ss_bbox_1_color)); if(zinit.ss_flags&ssflagSHOWGRID) { for(int x=zinit.ss_grid_xofs; x<d->w; x+=zinit.ss_grid_x) { for(int y=zinit.ss_grid_yofs; y<d->h; y+=zinit.ss_grid_y) { buf->line[y][x]=vc(zinit.ss_grid_color); } } } if(is_large()) { stretch_blit(buf,screen,0,0,d->w/(is_large() ? 2 : 1),d->h/(is_large() ? 2 : 1),d->x,d->y,d->w,d->h); } else { blit(buf,screen,0,0,d->x,d->y,d->w,d->h); } destroy_bitmap(buf); } } break; case MSG_WANTFOCUS: return D_WANTFOCUS; break; } return D_O_K; } int onSSUp(); int onSSDown(); int onSSLeft(); int onSSRight(); int onSSPgDn(); int onSSPgUp(); int d_ssup_btn_proc(int msg,DIALOG *d,int c); int d_ssdn_btn_proc(int msg,DIALOG *d,int c); int d_sslt_btn_proc(int msg,DIALOG *d,int c); int d_ssrt_btn_proc(int msg,DIALOG *d,int c); int onSSUp() { int delta=(key[KEY_LSHIFT]||key[KEY_RSHIFT])?-zinit.ss_grid_y:-1; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[i].h+=delta; } else { css->objects[i].y+=delta; } } } if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[curr_subscreen_object].h+=delta; } else { css->objects[curr_subscreen_object].y+=delta; } return D_O_K; } int onSSDown() { int delta=(key[KEY_LSHIFT]||key[KEY_RSHIFT])?zinit.ss_grid_y:1; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[i].h+=delta; } else { css->objects[i].y+=delta; } } } if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[curr_subscreen_object].h+=delta; } else { css->objects[curr_subscreen_object].y+=delta; } return D_O_K; } int onSSLeft() { int delta=(key[KEY_LSHIFT]||key[KEY_RSHIFT])?-zinit.ss_grid_x:-1; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[i].w+=delta; } else { css->objects[i].x+=delta; } } } if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[curr_subscreen_object].w+=delta; } else { css->objects[curr_subscreen_object].x+=delta; } return D_O_K; } int onSSRight() { int delta=(key[KEY_LSHIFT]||key[KEY_RSHIFT])?zinit.ss_grid_x:1; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[i].w+=delta; } else { css->objects[i].x+=delta; } } } if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { css->objects[curr_subscreen_object].w+=delta; } else { css->objects[curr_subscreen_object].x+=delta; } return D_O_K; } int d_ssup_btn2_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSUp(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssdn_btn2_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSDown(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_sslt_btn2_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSLeft(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssrt_btn2_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSRight(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssup_btn3_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { --css->objects[i].h; } } --css->objects[curr_subscreen_object].h; return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssdn_btn3_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { ++css->objects[i].h; } } ++css->objects[curr_subscreen_object].h; return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_sslt_btn3_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { --css->objects[i].w; } } --css->objects[curr_subscreen_object].w; return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssrt_btn3_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]&&i!=curr_subscreen_object) { ++css->objects[i].w; } } ++css->objects[curr_subscreen_object].w; return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int Bweapon(int pos) { int p=-1; for(int i=0; css->objects[i].type!=ssoNULL; ++i) { if(css->objects[i].type==ssoCURRENTITEM && css->objects[i].d3==pos) { p=i; break; } } if(p==-1) { return 0; } int family = 0; bool bow = false; switch(css->objects[p].d1) { case itype_arrow: case itype_bowandarrow: if(current_item(itype_bow) && current_item(itype_arrow)) { bow=(css->objects[p].d1==itype_bowandarrow); family=itype_arrow; } break; case itype_letterpotion: if(current_item(itype_potion)) family=itype_potion; else if(current_item(itype_letter)) family=itype_letter; break; case itype_sword: { if(!get_bit(quest_rules,qr_SELECTAWPN)) break; family=itype_sword; } break; default: family=css->objects[p].d1; } for(int i=0; i<MAXITEMS; i++) { if(itemsbuf[i].family==family) return i+(bow ? 0xF000 : 0); } return 0; } void selectBwpn(int xstep, int ystep) { if((xstep==0)&&(ystep==0)) { Bwpn=Bweapon(Bpos); update_subscr_items(); if(Bwpn) { return; } xstep=1; } if((xstep==8)&&(ystep==8)) { Bwpn=Bweapon(Bpos); update_subscr_items(); if(Bwpn) { return; } xstep=-1; } int pos = Bpos; int tries=0; do { int p=-1; for(int i=0; css->objects[i].type!=ssoNULL; ++i) { if(css->objects[i].type==ssoCURRENTITEM) { if(css->objects[i].d3==Bpos) { p=i; break; } } } if(p!=-1) { if(xstep!=0) { Bpos=xstep<0?css->objects[p].d6:css->objects[p].d7; } else { Bpos=ystep<0?css->objects[p].d4:css->objects[p].d5; } } Bwpn = Bweapon(Bpos); update_subscr_items(); if(Bwpn) { return; } } while(Bpos!=pos && ++tries<0x100); if(!Bwpn) Bpos=0; } int d_ssup_btn4_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); selectBwpn(0, -1); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssdn_btn4_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); selectBwpn(0, 1); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_sslt_btn4_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); selectBwpn(-1, 0); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssrt_btn4_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); selectBwpn(1, 0); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } const char *sso_type[ssoMAX]= { "ssoNULL", "ssoNONE", "sso2X2FRAME", "ssoTEXT", "ssoLINE", "ssoRECT", "ssoBSTIME", "ssoTIME", "ssoSSTIME", "ssoMAGICMETER", "ssoLIFEMETER", "ssoBUTTONITEM", "ssoICON", "ssoCOUNTER", "ssoCOUNTERS", "ssoMINIMAPTITLE", "ssoMINIMAP", "ssoLARGEMAP", "ssoCLEAR", "ssoCURRENTITEM", "ssoITEM", "ssoTRIFRAME", "ssoTRIFORCE", "ssoTILEBLOCK", "ssoMINITILE", "ssoSELECTOR1", "ssoSELECTOR2", "ssoMAGICGAUGE", "ssoLIFEGAUGE", "ssoTEXTBOX", "ssoCURRENTITEMTILE", "ssoSELECTEDITEMTILE", "ssoCURRENTITEMTEXT", "ssoCURRENTITEMNAME", "ssoSELECTEDITEMNAME", "ssoCURRENTITEMCLASSTEXT", "ssoCURRENTITEMCLASSNAME", "ssoSELECTEDITEMCLASSNAME" }; const char *sso_textstyle[sstsMAX]= { "sstsNORMAL", "sstsSHADOW", "sstsSHADOWU", "sstsOUTLINE8", "sstsOUTLINEPLUS", "sstsOUTLINEX", "sstsSHADOWED", "sstsSHADOWEDU", "sstsOUTLINED8", "sstsOUTLINEDPLUS", "sstsOUTLINEDX" }; const char *sso_fontname[ssfMAX]= { "ssfZELDA", "ssfSS1", "ssfSS2", "ssfSS3", "ssfSS4", "ssfZTIME", "ssfSMALL", "ssfSMALLPROP", "ssfZ3SMALL", "ssfGBLA", "ssfZ3", "ssfGORON", "ssfZORAN", "ssfHYLIAN1", "ssfHYLIAN2", "ssfHYLIAN3", "ssfHYLIAN4", "ssfPROP", "ssfGBORACLE", "ssfGBORACLEP", "ssfDSPHANTOM", "ssfDSPHANTOMP" }; const char *sso_colortype[2]= { "ssctSYSTEM", "ssctMISC" }; const char *sso_specialcolor[ssctMAX]= { "ssctTEXT", "ssctCAPTION", "ssctOVERWBG", "ssctDNGNBG", "ssctDNGNFG", "ssctCAVEFG", "ssctBSDK", "ssctBSGOAL", "ssctCOMPASSLT", "ssctCOMPASSDK", "ssctSUBSCRBG", "ssctSUBSCRSHADOW", "ssctTRIFRAMECOLOR", "ssctBMAPBG", "ssctBMAPFG", "ssctLINKDOT", "ssctMSGTEXT" }; const char *sso_specialcset[sscsMAX]= { "sscsTRIFORCECSET", "sscsTRIFRAMECSET", "sscsOVERWORLDMAPCSET", "sscsDUNGEONMAPCSET", "sscsBLUEFRAMECSET", "sscsHCPIECESCSET", "sscsSSVINECSET" }; const char *sso_specialtile[ssmstMAX]= { "ssmstSSVINETILE", "ssmstMAGICMETER" }; const char *sso_counterobject[sscMAX]= { "sscRUPEES", "sscBOMBS", "sscSBOMBS", "sscARROWS", "sscGENKEYMAGIC", "sscGENKEYNOMAGIC", "sscLEVKEYMAGIC", "sscLEVKEYNOMAGIC", "sscANYKEYMAGIC", "sscANYKEYNOMAGIC", "sscSCRIPT1", "sscSCRIPT2", "sscSCRIPT3", "sscSCRIPT4", "sscSCRIPT5", "sscSCRIPT6", "sscSCRIPT7", "sscSCRIPT8", "sscSCRIPT9", "sscSCRIPT10" }; const char *sso_alignment[3]= { "sstaLEFT", "sstaCENTER", "sstaRIGHT" }; bool save_subscreen_code(char *path) { PACKFILE *f = pack_fopen_password(path,F_WRITE,""); if(!f) { return false; } int ssobjs=ss_objects(css); char buf[512]; memset(buf,0,512); sprintf(buf, "subscreen_object exported_subscreen[%d]=\n", ssobjs); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } pack_fputs("{\n", f); if(pack_ferror(f)) { pack_fclose(f); return false; } for(int i=0; i<ssobjs; ++i) { // pack_fputs("{\n", f); sprintf(buf, " { %s, %d, %d, %d, %d, %d, ", sso_type[css->objects[i].type], css->objects[i].pos, css->objects[i].x, css->objects[i].y, css->objects[i].w, css->objects[i].h); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } if(css->objects[i].colortype1>=ssctSYSTEM) { sprintf(buf, "%s, ", sso_colortype[css->objects[i].colortype1==ssctSYSTEM?0:1]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } if(css->objects[i].colortype1==ssctMISC) { int t=css->objects[i].type; if(t==sso2X2FRAME||t==ssoCURRENTITEMTILE||t==ssoICON||t==ssoMINITILE||t==ssoSELECTEDITEMTILE||t==ssoSELECTOR1||t==ssoSELECTOR2||t==ssoTRIFORCE||t==ssoTILEBLOCK) { sprintf(buf, "%s, ", sso_specialcset[css->objects[i].color1]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } else { sprintf(buf, "%s, ", sso_specialcolor[css->objects[i].color1]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, ", css->objects[i].color1); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, %d, ", css->objects[i].colortype1, css->objects[i].color1); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } if(css->objects[i].colortype2>=ssctSYSTEM) { sprintf(buf, "%s, ", sso_colortype[css->objects[i].colortype2==ssctSYSTEM?0:1]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } if(css->objects[i].colortype2==ssctMISC) { int t=css->objects[i].type; if(t==sso2X2FRAME||t==ssoCURRENTITEMTILE||t==ssoICON||t==ssoMINITILE||t==ssoSELECTEDITEMTILE||t==ssoSELECTOR1||t==ssoSELECTOR2||t==ssoTRIFORCE||t==ssoTILEBLOCK) { sprintf(buf, "%s, ", sso_specialcset[css->objects[i].color2]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } else { sprintf(buf, "%s, ", sso_specialcolor[css->objects[i].color2]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, ", css->objects[i].color2); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, %d, ", css->objects[i].colortype2, css->objects[i].color2); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } if(css->objects[i].colortype3>=ssctSYSTEM) { sprintf(buf, "%s, ", sso_colortype[css->objects[i].colortype3==ssctSYSTEM?0:1]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } if(css->objects[i].colortype3==ssctMISC) { int t=css->objects[i].type; if(t==sso2X2FRAME||t==ssoCURRENTITEMTILE||t==ssoICON||t==ssoMINITILE||t==ssoSELECTEDITEMTILE||t==ssoSELECTOR1||t==ssoSELECTOR2||t==ssoTRIFORCE||t==ssoTILEBLOCK) { sprintf(buf, "%s, ", sso_specialcset[css->objects[i].color3]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } else { sprintf(buf, "%s, ", sso_specialcolor[css->objects[i].color3]); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, ", css->objects[i].color3); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } } else { sprintf(buf, "%d, %d, ", css->objects[i].colortype3, css->objects[i].color3); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } } switch(css->objects[i].type) { case ssoCURRENTITEM: sprintf(buf, "%s, ", itype_names[css->objects[i].d1]); break; case ssoCOUNTER: case ssoCOUNTERS: case ssoTEXT: case ssoTEXTBOX: case ssoMINIMAPTITLE: case ssoSELECTEDITEMNAME: case ssoTIME: case ssoSSTIME: case ssoBSTIME: sprintf(buf, "%s, ", sso_fontname[css->objects[i].d1]); break; default: sprintf(buf, "%d, ", css->objects[i].d1); break; } pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } switch(css->objects[i].type) { case ssoCOUNTER: case ssoTEXT: case ssoTEXTBOX: case ssoMINIMAPTITLE: case ssoSELECTEDITEMNAME: case ssoTIME: case ssoSSTIME: case ssoBSTIME: sprintf(buf, "%s, ", sso_alignment[css->objects[i].d2]); break; case ssoMINITILE: if(css->objects[i].d1==-1) { sprintf(buf, "%s, ", sso_specialtile[css->objects[i].d2]); } else { sprintf(buf, "%d, ", css->objects[i].d2); } break; default: sprintf(buf, "%d, ", css->objects[i].d2); break; } pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } switch(css->objects[i].type) { case ssoCOUNTER: case ssoCOUNTERS: case ssoTEXT: case ssoTEXTBOX: case ssoMINIMAPTITLE: case ssoSELECTEDITEMNAME: case ssoTIME: case ssoSSTIME: case ssoBSTIME: sprintf(buf, "%s, ", (char *)sso_textstyle[css->objects[i].d3]); break; default: sprintf(buf, "%d, ", css->objects[i].d3); break; } pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].d4); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } switch(css->objects[i].type) { case ssoCOUNTER: case ssoCOUNTERS: sprintf(buf, "\'%c\', ", css->objects[i].d5); break; default: sprintf(buf, "%d, ", css->objects[i].d5); break; } pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].d6); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } switch(css->objects[i].type) { case ssoCOUNTER: sprintf(buf, "%s, ", sso_counterobject[css->objects[i].d7]); break; default: sprintf(buf, "%d, ", css->objects[i].d7); break; } pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].d8); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].d9); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].d10); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].frames); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].speed); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].delay); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } sprintf(buf, "%d, ", css->objects[i].frame); pack_fputs(buf, f); if(pack_ferror(f)) { pack_fclose(f); return false; } if(!css->objects[i].dp1) { pack_fputs("NULL", f); if(pack_ferror(f)) { pack_fclose(f); return false; } } else { pack_fputs("(void *)\"", f); if(pack_ferror(f)) { pack_fclose(f); return false; } pack_fputs((char *)css->objects[i].dp1, f); if(pack_ferror(f)) { pack_fclose(f); return false; } pack_fputs("\"", f); if(pack_ferror(f)) { pack_fclose(f); return false; } } pack_fputs(" },\n", f); if(pack_ferror(f)) { pack_fclose(f); return false; } } pack_fputs(" { ssoNULL }\n", f); if(pack_ferror(f)) { pack_fclose(f); return false; } pack_fputs("};\n", f); if(pack_ferror(f)) { pack_fclose(f); return false; } pack_fclose(f); return true; } int onExport_Subscreen_Code() { if(!getname("Export Subscreen Code (.zss)","zss",NULL,datapath,false)) return D_O_K; char buf[80],buf2[80],name[13]; extract_name(temppath,name,FILENAME8_3); if(save_subscreen_code(temppath)) { sprintf(buf,"ZQuest"); sprintf(buf2,"Saved %s",name); } else { sprintf(buf,"Error"); sprintf(buf2,"Error saving %s",name); } jwin_alert(buf,buf2,NULL,NULL,"O&K",NULL,'k',0,lfont); return D_O_K; } int onActivePassive(); static MENU ss_arrange_menu[] = { { (char *)"Bring to Front", onBringToFront, NULL, 0, NULL }, { (char *)"Bring Forward", onBringForward, NULL, 0, NULL }, { (char *)"Send Backward", onSendBackward, NULL, 0, NULL }, { (char *)"Send to Back", onSendToBack, NULL, 0, NULL }, { (char *)"Reverse", onReverseArrangement, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_grid_snap_menu[] = { { (char *)"Left Edges", onGridSnapLeft, NULL, 0, NULL }, { (char *)"Horizontal Centers", onGridSnapCenter, NULL, 0, NULL }, { (char *)"Right Edges", onGridSnapRight, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"Top Edges", onGridSnapTop, NULL, 0, NULL }, { (char *)"Vertical Centers", onGridSnapMiddle, NULL, 0, NULL }, { (char *)"Bottom Edges", onGridSnapBottom, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_align_menu[] = { { (char *)"Left Edges", onAlignLeft, NULL, 0, NULL }, { (char *)"Horizontal Centers", onAlignCenter, NULL, 0, NULL }, { (char *)"Right Edges", onAlignRight, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"Top Edges", onAlignTop, NULL, 0, NULL }, { (char *)"Vertical Centers", onAlignMiddle, NULL, 0, NULL }, { (char *)"Bottom Edges", onAlignBottom, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"To Grid", NULL, ss_grid_snap_menu, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_distribute_menu[] = { { (char *)"Left Edges", onDistributeLeft, NULL, 0, NULL }, { (char *)"Horizontal Centers", onDistributeCenter, NULL, 0, NULL }, { (char *)"Right Edges", onDistributeRight, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"Top Edges", onDistributeTop, NULL, 0, NULL }, { (char *)"Vertical Centers", onDistributeMiddle, NULL, 0, NULL }, { (char *)"Bottom Edges", onDistributeBottom, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_edit_menu[] = { { (char *)"&New\tIns", onNewSubscreenObject, NULL, 0, NULL }, { (char *)"&Delete\tDel", onDeleteSubscreenObject, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"&Duplicate", onDuplicateSubscreenObject, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"&Properties", onSubscreenObjectProperties, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"&Arrange", NULL, ss_arrange_menu, 0, NULL }, { (char *)"Al&ign", NULL, ss_align_menu, 0, NULL }, { (char *)"Dis&tribute", NULL, ss_distribute_menu, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"Switch Active/Passive", onActivePassive, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"&Take Snapshot\tZ", onSnapshot, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"E&xport as Code\tX", onExport_Subscreen_Code, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_view_menu[] = { { (char *)"Show in&visible items", onToggleInvis, NULL, 0, NULL }, { (char *)"&Edit grid", onEditGrid, NULL, 0, NULL }, { (char *)"&Show grid", onShowHideGrid, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU ss_selection_menu[] = { { (char *)"&Add to Selection\tA", onAddToSelection, NULL, 0, NULL }, { (char *)"&Remove from Selection\tR", onRemoveFromSelection, NULL, 0, NULL }, { (char *)"&Invert Selection\tI", onInvertSelection, NULL, 0, NULL }, { (char *)"&Clear Selection\tC", onClearSelection, NULL, 0, NULL }, { (char *)"", NULL, NULL, 0, NULL }, { (char *)"&Options", onSelectionOptions, NULL, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static MENU subscreen_menu[] = { { (char *)"&Edit", NULL, ss_edit_menu, 0, NULL }, { (char *)"&View", NULL, ss_view_menu, 0, NULL }, { (char *)"&Selection", NULL, ss_selection_menu, 0, NULL }, { NULL, NULL, NULL, 0, NULL } }; static DIALOG subscreen_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 320, 240, vc(0), vc(11), 0, D_EXIT, 0, 0, (void *) "Subscreen Editor", NULL, NULL }, { jwin_button_proc, 192, 215, 61, 21, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 255, 215, 61, 21, vc(0), vc(11), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { jwin_frame_proc, 4, 37, 260, 172, 0, 0, 0, 0, FR_DEEP, 0, NULL, NULL, NULL }, { d_subscreen_proc, 6, 39, 256, 168, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, // 5 { d_box_proc, 11, 211, 181, 8, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_text_proc, 11, 211, 181, 16, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_text_proc, 4, 225, 30, 16, 0, 0, 0, 0, 0, 0, (void *) "Name:", NULL, NULL }, { jwin_edit_proc, 34, 221, 155, 16, 0, 0, 0, 0, 64, 0, NULL, NULL, NULL }, { d_ssup_btn_proc, 284, 23, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x88", NULL, NULL }, { d_ssdn_btn_proc, 284, 53, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x89", NULL, NULL }, { d_sslt_btn_proc, 269, 38, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8A", NULL, NULL }, { d_ssrt_btn_proc, 299, 38, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8B", NULL, NULL }, { d_ssup_btn2_proc, 284, 70, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x88", NULL, NULL }, { d_ssdn_btn2_proc, 284, 100, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x89", NULL, NULL }, { d_sslt_btn2_proc, 269, 85, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8A", NULL, NULL }, { d_ssrt_btn2_proc, 299, 85, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8B", NULL, NULL }, { d_ssup_btn3_proc, 284, 117, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x98", NULL, NULL }, { d_ssdn_btn3_proc, 284, 147, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x99", NULL, NULL }, { d_sslt_btn3_proc, 269, 132, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x9A", NULL, NULL }, { d_ssrt_btn3_proc, 299, 132, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x9B", NULL, NULL }, { d_ssup_btn4_proc, 284, 164, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x88", NULL, NULL }, { d_ssdn_btn4_proc, 284, 194, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x89", NULL, NULL }, { d_sslt_btn4_proc, 269, 179, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8A", NULL, NULL }, { d_ssrt_btn4_proc, 299, 179, 15, 15, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "\x8B", NULL, NULL }, { jwin_menu_proc, 4, 23, 0, 13, 0, 0, 0, 0, 0, 0, (void *) subscreen_menu, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_UP, 0, (void *) onSSUp, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_DOWN, 0, (void *) onSSDown, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_LEFT, 0, (void *) onSSLeft, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_RIGHT, 0, (void *) onSSRight, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_PGUP, 0, (void *) onSSPgUp, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_PGDN, 0, (void *) onSSPgDn, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'a', 0, 0, 0, (void *) onAddToSelection, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'r', 0, 0, 0, (void *) onRemoveFromSelection, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'i', 0, 0, 0, (void *) onInvertSelection, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'c', 0, 0, 0, (void *) onClearSelection, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_INSERT, 0, (void *) onNewSubscreenObject, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_DEL, 0, (void *) onDeleteSubscreenObject, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'd', 0, 0, 0, (void *) onDuplicateSubscreenObject, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'e', 0, 0, 0, (void *) onSubscreenObjectProperties, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'z', 0, 0, 0, (void *) onSnapshot, NULL, NULL }, { d_keyboard_proc, 0, 0, 0, 0, 0, 0, 'x', 0, 0, 0, (void *) onExport_Subscreen_Code, NULL, NULL }, { d_vsync_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; int onActivePassive() { if(css->ss_type == sstACTIVE) { css->ss_type = sstPASSIVE; subscreen_dlg[3].h=60*(is_large() ? 2 : 1)-(is_large()?4:0); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } else if(css->ss_type == sstPASSIVE) { css->ss_type = sstACTIVE; subscreen_dlg[3].h=172*(is_large() ? 2 : 1)-(is_large()?4:0); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } return D_REDRAW; } const char *color_str[16] = { "Black", "Blue", "Green", "Cyan", "Red", "Magenta", "Brown", "Light Gray", "Dark Gray", "Light Blue", "Light Green", "Light Cyan", "Light Red", "Light Magenta", "Yellow", "White" }; const char *colorlist(int index, int *list_size) { if(index<0) { *list_size = 16; return NULL; } return color_str[index]; } static ListData color_list(colorlist, &font); static DIALOG grid_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 158, 120, vc(0), vc(11), 0, D_EXIT, 0, 0, (void *) "Edit Grid Properties", NULL, NULL }, { jwin_button_proc, 18, 95, 61, 21, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 81, 95, 61, 21, vc(0), vc(11), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { jwin_text_proc, 6, 29, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "X Size:", NULL, NULL }, { jwin_edit_proc, 42, 25, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, // 5 { jwin_text_proc, 6, 49, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Y Size:", NULL, NULL }, { jwin_edit_proc, 42, 45, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_text_proc, 78, 29, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "X Offset:", NULL, NULL }, { jwin_edit_proc, 126, 25, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_text_proc, 78, 49, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Y Offset:", NULL, NULL }, // 10 { jwin_edit_proc, 126, 45, 26, 16, 0, 0, 0, 0, 3, 0, NULL, NULL, NULL }, { jwin_text_proc, 6, 69, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Color:", NULL, NULL }, { jwin_droplist_proc, 36, 65, 116, 16, 0, 0, 0, 0, 0, 0, (void *) &color_list, NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; static DIALOG sel_options_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 225, 120, vc(0), vc(11), 0, D_EXIT, 0, 0, (void *) "Selection Options", NULL, NULL }, { jwin_button_proc, 51, 95, 61, 21, vc(0), vc(11), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 114, 95, 61, 21, vc(0), vc(11), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { jwin_frame_proc, 6, 28, 213, 51, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, FR_ETCHED, 0, NULL, NULL, NULL }, { jwin_text_proc, 10, 25, 48, 8, jwin_pal[jcBOXFG], jwin_pal[jcBOX], 0, 0, 0, 0, (void *) " Selection Outlines ", NULL, NULL }, // 5 { jwin_text_proc, 14, 41, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Primary Color:", NULL, NULL }, { jwin_droplist_proc, 94, 37, 116, 16, 0, 0, 0, 0, 0, 0, (void *) &color_list, NULL, NULL }, { jwin_text_proc, 14, 61, 186, 16, 0, 0, 0, 0, 0, 0, (void *) "Secondary Color:", NULL, NULL }, { jwin_droplist_proc, 94, 57, 116, 16, 0, 0, 0, 0, 0, 0, (void *) &color_list, NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; const char *sso_str[ssoMAX]= { "NULL", "(None)", "2x2 Frame", "Text", "Line", "Rectangle", "BS-Zelda Time", "Game Time", "Game Time (Quest Rule)", "Magic Meter", "Life Meter", "Button Item", "-Icon (Not Implemented)", "Counter", "Counter Block", "Minimap Title", "Minimap", "Large Map", "Erase Subscreen", "Current Item", "-Item (Not Implemented)", "Triforce Frame", "Triforce Piece", "Tile Block", "Minitile", "Selector 1", "Selector 2", "Magic Gauge Piece", "Life Gauge Piece", "Text Box", "-Current Item -> Tile (Not Implemented)", "-Selected Item -> Tile (Not Implemented)", "-Current Item -> Text (Not Implemented)", "-Current Item Name (Not Implemented)", "Selected Item Name", "-Current Item Class -> Text (Not Implemented)", "-Current Item Class Name (Not Implemented)", "-Selected Item Class Name (Not Implemented)" }; char *sso_name(int type) { char *tempname; tempname=(char*)zc_malloc(255); if(type>=0 && type <ssoMAX) { sprintf(tempname, "%s", sso_str[type]); } else { sprintf(tempname, "INVALID OBJECT! type=%d", type); } return tempname; } char *sso_name(subscreen_object *tempss, int id) { return sso_name(tempss[id].type); } sso_struct bisso[ssoMAX]; int bisso_cnt=-1; void build_bisso_list() { int start=1; bisso_cnt=0; for(int i=start; i<ssoMAX; i++) { if(sso_str[i][0]!='-') { bisso[bisso_cnt].s = (char *)sso_str[i]; bisso[bisso_cnt].i = i; ++bisso_cnt; } } for(int i=start; i<bisso_cnt-1; i++) { for(int j=i+1; j<bisso_cnt; j++) { if(stricmp(bisso[i].s,bisso[j].s)>0) { std::swap(bisso[i],bisso[j]); } } } } const char *ssolist(int index, int *list_size) { if(index<0) { *list_size = bisso_cnt; return NULL; } return bisso[index].s; } static ListData sso_list(ssolist, &font); static DIALOG ssolist_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 255, 148, vc(14), vc(1), 0, D_EXIT, 0, 0, (void *) "Select Object Type", NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_abclist_proc, 4, 24, 247, 95, jwin_pal[jcTEXTFG], jwin_pal[jcTEXTBG], 0, D_EXIT, 0, 0, (void *) &sso_list, NULL, NULL }, { jwin_button_proc, 65, 123, 61, 21, vc(14), vc(1), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 128, 123, 61, 21, vc(14), vc(1), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; int onNewSubscreenObject() { subscreen_object tempsso; int ret=-1; ssolist_dlg[0].dp2=lfont; build_bisso_list(); DIALOG *ssolist_cpy = resizeDialog(ssolist_dlg, 1.5); ret=zc_popup_dialog(ssolist_cpy,2); if(ret!=0&&ret!=4) { memset(&tempsso,0,sizeof(subscreen_object)); //tempsso.dp1=(char *)zc_malloc(2); tempsso.dp1 = new char[2]; ((char *)tempsso.dp1)[0]=0; tempsso.type=bisso[ssolist_cpy[2].d1].i; tempsso.pos = sspUP | sspDOWN | sspSCROLLING; tempsso.w=1; tempsso.h=1; if(tempsso.type==ssoCURRENTITEM) // Should not be invisible! tempsso.d2 = 1; int temp_cso=curr_subscreen_object; curr_subscreen_object=ss_objects(css); if(sso_properties(&tempsso)!=-1) { if(css->objects[curr_subscreen_object].dp1!=NULL) { delete [](char *)css->objects[curr_subscreen_object].dp1; css->objects[curr_subscreen_object].dp1=NULL; } css->objects[curr_subscreen_object]=tempsso; update_sso_name(); update_up_dn_btns(); } else { curr_subscreen_object=temp_cso; } } delete[] ssolist_cpy; return D_O_K; } void align_objects(subscreen_group *tempss, bool *selection, int align_type) { int l=sso_x(&tempss->objects[curr_subscreen_object]); int t=sso_y(&tempss->objects[curr_subscreen_object]); int w=sso_w(&tempss->objects[curr_subscreen_object]); int h=sso_h(&tempss->objects[curr_subscreen_object]); switch(get_alignment(&tempss->objects[curr_subscreen_object])) { case sstaCENTER: l-=(w/2); break; case sstaRIGHT: l-=w; break; case sstaLEFT: default: break; } int r=l+w-1; int b=t+h-1; int c=l+w/2; int m=t+h/2; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(selection[i]&&i!=curr_subscreen_object) { int tl=sso_x(&tempss->objects[i]); int tt=sso_y(&tempss->objects[i]); int tw=sso_w(&tempss->objects[i]); int th=sso_h(&tempss->objects[i]); switch(get_alignment(&tempss->objects[i])) { case sstaCENTER: tl-=(tw/2); break; case sstaRIGHT: tl-=tw; break; case sstaLEFT: default: break; } int tr=tl+tw-1; int tb=tt+th-1; int tc=tl+tw/2; int tm=tt+th/2; switch(align_type) { case ssoaBOTTOM: tempss->objects[i].y+=b-tb; break; case ssoaMIDDLE: tempss->objects[i].y+=m-tm; break; case ssoaTOP: tempss->objects[i].y+=t-tt; break; case ssoaRIGHT: tempss->objects[i].x+=r-tr; break; case ssoaCENTER: tempss->objects[i].x+=c-tc; break; case ssoaLEFT: default: tempss->objects[i].x+=l-tl; break; } } } } void grid_snap_objects(subscreen_group *tempss, bool *selection, int snap_type) { for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(selection[i]||i==curr_subscreen_object) { int tl=sso_x(&tempss->objects[i]); int tt=sso_y(&tempss->objects[i]); int tw=sso_w(&tempss->objects[i]); int th=sso_h(&tempss->objects[i]); switch(get_alignment(&tempss->objects[i])) { case sstaCENTER: tl-=(tw/2); break; case sstaRIGHT: tl-=tw; break; case sstaLEFT: default: break; } int tr=tl+tw-1; int tb=tt+th-1; int tc=tl+tw/2; int tm=tt+th/2; int l1=(tl-zinit.ss_grid_xofs)/zinit.ss_grid_x*zinit.ss_grid_x+zinit.ss_grid_xofs; int l2=l1+zinit.ss_grid_x; int c1=(tc-zinit.ss_grid_xofs)/zinit.ss_grid_x*zinit.ss_grid_x+zinit.ss_grid_xofs; int c2=c1+zinit.ss_grid_x; int r1=(tr-zinit.ss_grid_xofs)/zinit.ss_grid_x*zinit.ss_grid_x+zinit.ss_grid_xofs; int r2=r1+zinit.ss_grid_x; int t1=(tt-zinit.ss_grid_yofs)/zinit.ss_grid_y*zinit.ss_grid_y+zinit.ss_grid_yofs; int t2=t1+zinit.ss_grid_y; int m1=(tm-zinit.ss_grid_yofs)/zinit.ss_grid_y*zinit.ss_grid_y+zinit.ss_grid_yofs; int m2=m1+zinit.ss_grid_y; int b1=(tb-zinit.ss_grid_yofs)/zinit.ss_grid_y*zinit.ss_grid_y+zinit.ss_grid_yofs; int b2=b1+zinit.ss_grid_y; switch(snap_type) { case ssosBOTTOM: tempss->objects[i].y+=(abs(b1-tb)>abs(b2-tb))?(b2-tb):(b1-tb); break; case ssosMIDDLE: tempss->objects[i].y+=(abs(m1-tm)>abs(m2-tm))?(m2-tm):(m1-tm); break; case ssosTOP: tempss->objects[i].y+=(abs(t1-tt)>abs(t2-tt))?(t2-tt):(t1-tt); break; case ssosRIGHT: tempss->objects[i].x+=(abs(r1-tr)>abs(r2-tr))?(r2-tr):(r1-tr); break; case ssosCENTER: tempss->objects[i].x+=(abs(c1-tc)>abs(c2-tc))?(c2-tc):(c1-tc); break; case ssosLEFT: default: tempss->objects[i].x+=(abs(l1-tl)>abs(l2-tl))?(l2-tl):(l1-tl); break; } } } } typedef struct dist_obj { int index; int l; int t; int w; int h; int r; int b; int c; int m; } dist_obj; void distribute_objects(subscreen_group *tempss, bool *selection, int distribute_type) { //these are here to bypass compiler warnings about unused arguments selection=selection; int count=0; dist_obj temp_do[MAXSUBSCREENITEMS]; for(int i=0; i<MAXSUBSCREENITEMS; ++i) { if(sso_selection[i]==true||i==curr_subscreen_object) { temp_do[count].index=i; temp_do[count].l=sso_x(&tempss->objects[i]); temp_do[count].t=sso_y(&tempss->objects[i]); temp_do[count].w=sso_w(&tempss->objects[i]); temp_do[count].h=sso_h(&tempss->objects[i]); switch(get_alignment(&tempss->objects[i])) { case sstaCENTER: temp_do[count].l-=(temp_do[count].w/2); break; case sstaRIGHT: temp_do[count].l-=temp_do[count].w; break; case sstaLEFT: default: break; } temp_do[count].r=temp_do[count].l+temp_do[count].w-1; temp_do[count].b=temp_do[count].t+temp_do[count].h-1; temp_do[count].c=temp_do[count].l+temp_do[count].w/2; temp_do[count].m=temp_do[count].t+temp_do[count].h/2; ++count; } } if(count<3) { return; } //sort all objects in order of position, then index (yeah, bubble sort; sue me) dist_obj tempdo2; for(int j=0; j<count-1; j++) { for(int k=0; k<count-1-j; k++) { switch(distribute_type) { case ssodBOTTOM: if(temp_do[k+1].b<temp_do[k].b||((temp_do[k+1].b==temp_do[k].b)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; case ssodMIDDLE: if(temp_do[k+1].m<temp_do[k].m||((temp_do[k+1].m==temp_do[k].m)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; case ssodTOP: if(temp_do[k+1].t<temp_do[k].t||((temp_do[k+1].t==temp_do[k].t)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; case ssodRIGHT: if(temp_do[k+1].r<temp_do[k].r||((temp_do[k+1].r==temp_do[k].r)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; case ssodCENTER: if(temp_do[k+1].c<temp_do[k].c||((temp_do[k+1].c==temp_do[k].c)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; case ssodLEFT: default: if(temp_do[k+1].l<temp_do[k].l||((temp_do[k+1].l==temp_do[k].l)&&(temp_do[k+1].index<temp_do[k].index))) { tempdo2=temp_do[k]; temp_do[k]=temp_do[k+1]; temp_do[k+1]=tempdo2; } break; } } } int ld=temp_do[count-1].l-temp_do[0].l; int td=temp_do[count-1].t-temp_do[0].t; int rd=temp_do[count-1].r-temp_do[0].r; int bd=temp_do[count-1].b-temp_do[0].b; int cd=temp_do[count-1].c-temp_do[0].c; int md=temp_do[count-1].m-temp_do[0].m; for(int i=1; i<count-1; ++i) { switch(distribute_type) { case ssodBOTTOM: tempss->objects[temp_do[i].index].y+=bd*i/(count-1)-temp_do[i].b+temp_do[0].b; break; case ssodMIDDLE: tempss->objects[temp_do[i].index].y+=md*i/(count-1)-temp_do[i].m+temp_do[0].m; break; case ssodTOP: tempss->objects[temp_do[i].index].y+=td*i/(count-1)-temp_do[i].t+temp_do[0].t; break; case ssodRIGHT: tempss->objects[temp_do[i].index].x+=rd*i/(count-1)-temp_do[i].r+temp_do[0].r; break; case ssodCENTER: tempss->objects[temp_do[i].index].x+=cd*i/(count-1)-temp_do[i].c+temp_do[0].c; break; case ssodLEFT: default: tempss->objects[temp_do[i].index].x+=ld*i/(count-1)-temp_do[i].l+temp_do[0].l; break; } } } int onBringToFront() { while(curr_subscreen_object<ss_objects(css)-1) { onBringForward(); } return D_O_K; } int onSendToBack() { while(curr_subscreen_object>0) { onSendBackward(); } return D_O_K; } int onReverseArrangement() { int i=0; int j=MAXSUBSCREENITEMS-1; subscreen_object tempsso; sso_selection[curr_subscreen_object]=true; while(true) { while(i<MAXSUBSCREENITEMS && !sso_selection[i]) i++; while(j>=0 && !sso_selection[j]) j--; if(i>=j) { sso_selection[curr_subscreen_object]=false; return D_O_K; } if(curr_subscreen_object==i) curr_subscreen_object=j; else if(curr_subscreen_object==j) curr_subscreen_object=i; tempsso=css->objects[i]; css->objects[i]=css->objects[j]; css->objects[j]=tempsso; i++; j--; } } int onAlignLeft() { align_objects(css, sso_selection, ssoaLEFT); return D_O_K; } int onAlignCenter() { align_objects(css, sso_selection, ssoaCENTER); return D_O_K; } int onAlignRight() { align_objects(css, sso_selection, ssoaRIGHT); return D_O_K; } int onAlignTop() { align_objects(css, sso_selection, ssoaTOP); return D_O_K; } int onAlignMiddle() { align_objects(css, sso_selection, ssoaMIDDLE); return D_O_K; } int onAlignBottom() { align_objects(css, sso_selection, ssoaBOTTOM); return D_O_K; } int onDistributeLeft() { distribute_objects(css, sso_selection, ssodLEFT); return D_O_K; } int onDistributeCenter() { distribute_objects(css, sso_selection, ssodCENTER); return D_O_K; } int onDistributeRight() { distribute_objects(css, sso_selection, ssodRIGHT); return D_O_K; } int onDistributeTop() { distribute_objects(css, sso_selection, ssodTOP); return D_O_K; } int onDistributeMiddle() { distribute_objects(css, sso_selection, ssodMIDDLE); return D_O_K; } int onDistributeBottom() { distribute_objects(css, sso_selection, ssodBOTTOM); return D_O_K; } int onGridSnapLeft() { grid_snap_objects(css, sso_selection, ssosLEFT); return D_O_K; } int onGridSnapCenter() { grid_snap_objects(css, sso_selection, ssosCENTER); return D_O_K; } int onGridSnapRight() { grid_snap_objects(css, sso_selection, ssosRIGHT); return D_O_K; } int onGridSnapTop() { grid_snap_objects(css, sso_selection, ssosTOP); return D_O_K; } int onGridSnapMiddle() { grid_snap_objects(css, sso_selection, ssosMIDDLE); return D_O_K; } int onGridSnapBottom() { grid_snap_objects(css, sso_selection, ssosBOTTOM); return D_O_K; } static int onToggleInvis() { bool show=!(zinit.ss_flags&ssflagSHOWINVIS); zinit.ss_flags&=~ssflagSHOWINVIS; zinit.ss_flags|=(show?ssflagSHOWINVIS:0); ss_view_menu[0].flags=zinit.ss_flags&ssflagSHOWINVIS?D_SELECTED:0; return D_O_K; } static int onEditGrid() { grid_dlg[0].dp2=lfont; char xsize[4]; char ysize[4]; char xoffset[4]; char yoffset[4]; sprintf(xsize, "%d", zc_max(zinit.ss_grid_x,1)); sprintf(ysize, "%d", zc_max(zinit.ss_grid_y,1)); sprintf(xoffset, "%d", zinit.ss_grid_xofs); sprintf(yoffset, "%d", zinit.ss_grid_yofs); grid_dlg[4].dp=xsize; grid_dlg[6].dp=ysize; grid_dlg[8].dp=xoffset; grid_dlg[10].dp=yoffset; grid_dlg[12].d1=zinit.ss_grid_color; DIALOG *grid_cpy = resizeDialog(grid_dlg, 1.5); int ret = zc_popup_dialog(grid_cpy,2); if(ret==1) { zinit.ss_grid_x=zc_max(atoi(xsize),1); zinit.ss_grid_xofs=atoi(xoffset); zinit.ss_grid_y=zc_max(atoi(ysize),1); zinit.ss_grid_yofs=atoi(yoffset); zinit.ss_grid_color= grid_cpy[12].d1; } delete[] grid_cpy; return D_O_K; } static int onShowHideGrid() { bool show=!(zinit.ss_flags&ssflagSHOWGRID); zinit.ss_flags&=~ssflagSHOWGRID; zinit.ss_flags|=(show?ssflagSHOWGRID:0); ss_view_menu[2].flags=zinit.ss_flags&ssflagSHOWGRID?D_SELECTED:0; return D_O_K; } int onSelectionOptions() { sel_options_dlg[0].dp2=lfont; sel_options_dlg[6].d1=zinit.ss_bbox_1_color; sel_options_dlg[8].d1=zinit.ss_bbox_2_color; DIALOG *sel_options_cpy = resizeDialog(sel_options_dlg, 1.5); int ret = zc_popup_dialog(sel_options_cpy,2); if(ret==1) { zinit.ss_bbox_1_color= sel_options_cpy[6].d1; zinit.ss_bbox_2_color= sel_options_cpy[8].d1; } delete[] sel_options_cpy; return D_O_K; } void update_up_dn_btns() { if(curr_subscreen_object<1) { subscreen_dlg[10].flags|=D_DISABLED; } else { subscreen_dlg[10].flags&=~D_DISABLED; } if(curr_subscreen_object>=ss_objects(css)-1) { subscreen_dlg[9].flags|=D_DISABLED; } else { subscreen_dlg[9].flags&=~D_DISABLED; } subscreen_dlg[9].flags|=D_DIRTY; subscreen_dlg[10].flags|=D_DIRTY; } int onSSCtrlPgUp() { return onBringForward(); } int onSSCtrlPgDn() { return onSendBackward(); } int onSendBackward() { subscreen_object tempsso; bool tempsel; if(curr_subscreen_object>0) { tempsso=css->objects[curr_subscreen_object]; tempsel=sso_selection[curr_subscreen_object]; css->objects[curr_subscreen_object]=css->objects[curr_subscreen_object-1]; sso_selection[curr_subscreen_object]=sso_selection[curr_subscreen_object-1]; css->objects[curr_subscreen_object-1]=tempsso; sso_selection[curr_subscreen_object-1]=tempsel; --curr_subscreen_object; update_sso_name(); } update_up_dn_btns(); return D_O_K; } int onSSPgDn() { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { return onSSCtrlPgDn(); } else { --curr_subscreen_object; if(curr_subscreen_object<0) { curr_subscreen_object=ss_objects(css)-1; } update_sso_name(); update_up_dn_btns(); } return D_O_K; } // Send forward int onBringForward() { subscreen_object tempsso; bool tempsel; if(curr_subscreen_object<ss_objects(css)-1) { tempsso=css->objects[curr_subscreen_object]; tempsel=sso_selection[curr_subscreen_object]; css->objects[curr_subscreen_object]=css->objects[curr_subscreen_object+1]; sso_selection[curr_subscreen_object]=sso_selection[curr_subscreen_object+1]; css->objects[curr_subscreen_object+1]=tempsso; sso_selection[curr_subscreen_object+1]=tempsel; ++curr_subscreen_object; update_sso_name(); } update_up_dn_btns(); return D_O_K; } int onSSPgUp() { if(key[KEY_ZC_LCONTROL] || key[KEY_ZC_RCONTROL]) { return onSSCtrlPgUp(); } else { if(ss_objects(css)>0) { ++curr_subscreen_object; if(curr_subscreen_object>=ss_objects(css)) { curr_subscreen_object=0; } } update_sso_name(); update_up_dn_btns(); } return D_O_K; } int d_ssup_btn_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); return onSSCtrlPgUp(); } break; } return jwin_button_proc(msg, d, c); } int d_ssdn_btn_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); return onSSCtrlPgDn(); } break; } return jwin_button_proc(msg, d, c); } int d_sslt_btn_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSPgDn(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } int d_ssrt_btn_proc(int msg,DIALOG *d,int c) { switch(msg) { case MSG_CLICK: { jwin_button_proc(msg, d, c); onSSPgUp(); return D_O_K; } break; } return jwin_button_proc(msg, d, c); } void edit_subscreen() { game = new gamedata; game->Clear(); game->set_time(0); resetItems(game,&zinit,true); //so that these will show up on the subscreen -DD if(game->get_bombs() == 0) game->set_bombs(1); if(game->get_sbombs() == 0) game->set_sbombs(1); if(game->get_arrows() == 0) game->set_arrows(1); subscreen_dlg[0].dp2=lfont; load_Sitems(&misc); curr_subscreen_object=0; ss_propCopySrc=-1; subscreen_group tempss; memset(&tempss, 0, sizeof(subscreen_group)); int i; for(i=0; i<MAXSUBSCREENITEMS; i++) { memcpy(&tempss.objects[i],&css->objects[i],sizeof(subscreen_object)); switch(css->objects[i].type) { case ssoTEXT: case ssoTEXTBOX: case ssoCURRENTITEMTEXT: case ssoCURRENTITEMCLASSTEXT: tempss.objects[i].dp1 = NULL; tempss.objects[i].dp1 = new char[strlen((char*)css->objects[i].dp1)+1]; strcpy((char*)tempss.objects[i].dp1,(char*)css->objects[i].dp1); break; default: break; } } tempss.ss_type=css->ss_type; sprintf(tempss.name, css->name); if(ss_objects(css)==0) { curr_subscreen_object=-1; } onClearSelection(); ss_view_menu[0].flags=zinit.ss_flags&ssflagSHOWINVIS?D_SELECTED:0; ss_view_menu[2].flags=zinit.ss_flags&ssflagSHOWGRID?D_SELECTED:0; if(css->objects[0].type==ssoNULL) { css->objects[0].type=ssoNONE; } subscreen_dlg[4].dp=(void *)css; subscreen_dlg[5].fg=jwin_pal[jcBOX]; subscreen_dlg[5].bg=jwin_pal[jcBOX]; str_oname=(char *)zc_malloc(255); subscreen_dlg[6].dp=(void *)str_oname; subscreen_dlg[8].dp=(void *)(css->name); update_sso_name(); subscreen_dlg[10].flags|=D_DISABLED; if(css->ss_type==sstPASSIVE) { subscreen_dlg[21].flags|=D_DISABLED; subscreen_dlg[22].flags|=D_DISABLED; subscreen_dlg[23].flags|=D_DISABLED; subscreen_dlg[24].flags|=D_DISABLED; } else { subscreen_dlg[21].flags&=~D_DISABLED; subscreen_dlg[22].flags&=~D_DISABLED; subscreen_dlg[23].flags&=~D_DISABLED; subscreen_dlg[24].flags&=~D_DISABLED; } selectBwpn(0, 0); DIALOG *subscreen_cpy = resizeDialog(subscreen_dlg, 2.0); if(is_large()) { subscreen_cpy[4].y-=32; subscreen_cpy[3].y-=31; subscreen_cpy[3].x+=1; if(css->ss_type == sstPASSIVE) subscreen_cpy[3].h=60*(is_large() ? 2 : 1)-(is_large() ?4:0); else if(css->ss_type == sstACTIVE) subscreen_cpy[3].h=172*(is_large() ? 2 : 1)-(is_large() ?4:0); subscreen_cpy[4].h= subscreen_cpy[3].h-4; } int ret = zc_popup_dialog(subscreen_cpy,2); if(ret==1) { saved=false; zinit.subscreen=ssdtMAX; } else { reset_subscreen(css); int j; for(j=0; j<MAXSUBSCREENITEMS; j++) { memcpy(&css->objects[j],&tempss.objects[j],sizeof(subscreen_object)); switch(tempss.objects[j].type) { case ssoTEXT: case ssoTEXTBOX: case ssoCURRENTITEMTEXT: case ssoCURRENTITEMCLASSTEXT: css->objects[j].dp1 = NULL; css->objects[j].dp1 = new char[strlen((char*)tempss.objects[j].dp1)+1]; strcpy((char*)css->objects[j].dp1,(char*)tempss.objects[j].dp1); break; default: break; } } css->ss_type=tempss.ss_type; sprintf(css->name, tempss.name); reset_subscreen(&tempss); } delete[] subscreen_cpy; delete game; game=NULL; } const char *allsubscrtype_str[30] = { "Original (Top, Triforce)", "Original (Top, Map)", "New Subscreen (Top, Triforce)", "New Subscreen (Top, Map)", "Revision 2 (Top, Triforce)", "Revision 2 (Top, Map)", "BS Zelda Original (Top, Triforce)", "BS Zelda Original (Top, Map)", "BS Zelda Modified (Top, Triforce)", "BS Zelda Modified (Top, Map)", "BS Zelda Enhanced (Top, Triforce)", "BS Zelda Enhanced (Top, Map)", "BS Zelda Complete (Top, Triforce)", "BS Zelda Complete (Top, Map)", "Zelda 3 (Top)", "Original (Bottom, Magic)", "Original (Bottom, No Magic)", "New Subscreen (Bottom, Magic)", "New Subscreen (Bottom, No Magic)", "Revision 2 (Bottom, Magic)", "Revision 2 (Bottom, No Magic)", "BS Zelda Original (Bottom, Magic)", "BS Zelda Original (Bottom, No Magic)", "BS Zelda Modified (Bottom, Magic)", "BS Zelda Modified (Bottom, No Magic)", "BS Zelda Enhanced (Bottom, Magic)", "BS Zelda Enhanced (Bottom, No Magic)", "BS Zelda Complete (Bottom, Magic)", "BS Zelda Complete (Bottom, No Magic)", "Zelda 3 (Bottom)" }; const char *activesubscrtype_str[16] = { "Blank", "Original (Top, Triforce)", "Original (Top, Map)", "New Subscreen (Top, Triforce)", "New Subscreen (Top, Map)", "Revision 2 (Top, Triforce)", "Revision 2 (Top, Map)", "BS Zelda Original (Top, Triforce)", "BS Zelda Original (Top, Map)", "BS Zelda Modified (Top, Triforce)", "BS Zelda Modified (Top, Map)", "BS Zelda Enhanced (Top, Triforce)", "BS Zelda Enhanced (Top, Map)", "BS Zelda Complete (Top, Triforce)", "BS Zelda Complete (Top, Map)", "Zelda 3 (Top)" }; const char *activelist(int index, int *list_size) { if(index<0) { *list_size = 16; return NULL; } return activesubscrtype_str[index]; } const char *passivesubscrtype_str[16] = { "Blank", "Original (Bottom, Magic)", "Original (Bottom, No Magic)", "New Subscreen (Bottom, Magic)", "New Subscreen (Bottom, No Magic)", "Revision 2 (Bottom, Magic)", "Revision 2 (Bottom, No Magic)", "BS Zelda Original (Bottom, Magic)", "BS Zelda Original (Bottom, No Magic)", "BS Zelda Modified (Bottom, Magic)", "BS Zelda Modified (Bottom, No Magic)", "BS Zelda Enhanced (Bottom, Magic)", "BS Zelda Enhanced (Bottom, No Magic)", "BS Zelda Complete (Bottom, Magic)", "BS Zelda Complete (Bottom, No Magic)", "Zelda 3 (Bottom)" }; const char *passivelist(int index, int *list_size) { if(index<0) { *list_size = 16; return NULL; } return passivesubscrtype_str[index]; } const char *activepassive_str[sstMAX] = { "Active", "Passive" }; const char *activepassivelist(int index, int *list_size) { if(index<0) { *list_size = sstMAX; return NULL; } return activepassive_str[index]; } static ListData passive_list(passivelist, &font); static ListData active_list(activelist, &font); int sstype_drop_proc(int msg,DIALOG *d,int c) { int tempd1=d->d1; int ret=jwin_droplist_proc(msg,d,c); if(tempd1!=d->d1) { (d+1)->dp=(d->d1)?(void*)&passive_list:(void*)&active_list; object_message(d+1,MSG_START,0); (d+1)->flags|=D_DIRTY; } return ret; } static ListData activepassive_list(activepassivelist, &font); static DIALOG sstemplatelist_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 265, 87, vc(14), vc(1), 0, D_EXIT, 0, 0, (void *) "New Subscreen", NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_text_proc, 4, 28, 8, 8, 0, 0, 0, 0, 0, 0, (void *) "Type:", NULL, NULL }, { jwin_text_proc, 4, 46, 8, 8, 0, 0, 0, 0, 0, 0, (void *) "Template:", NULL, NULL }, { sstype_drop_proc, 33, 24, 72, 16, jwin_pal[jcTEXTFG], jwin_pal[jcTEXTBG], 0, 0, 0, 0, (void *) &activepassive_list, NULL, NULL }, { jwin_droplist_proc, 50, 42, 211, 16, jwin_pal[jcTEXTFG], jwin_pal[jcTEXTBG], 0, 0, 0, 0, (void *) &active_list, NULL, NULL }, { jwin_button_proc, 61, 62, 61, 21, vc(14), vc(1), 13, D_EXIT, 0, 0, (void *) "OK", NULL, NULL }, { jwin_button_proc, 142, 62, 61, 21, vc(14), vc(1), 27, D_EXIT, 0, 0, (void *) "Cancel", NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; bool show_new_ss=true; const char *subscreenlist(int index, int *list_size) { if(index<0) { int j=0; while(custom_subscreen[j].objects[0].type!=ssoNULL) { ++j; } *list_size = j+(show_new_ss?1:0); sprintf(custom_subscreen[j].name, "<New>"); return NULL; } return custom_subscreen[index].name; } const char *subscreenlist_a(int index, int *list_size) { if(index<0) { int i=0, j=0; while(custom_subscreen[j].objects[0].type!=ssoNULL) { if(custom_subscreen[j].ss_type==sstACTIVE) { ++i; } ++j; } *list_size = i; return NULL; } // return custsubscrtype_str[index]; int i=-1, j=0; while(custom_subscreen[j].objects[0].type!=ssoNULL&&i!=index) { if(custom_subscreen[j].ss_type==sstACTIVE) { ++i; } ++j; } return custom_subscreen[j-1].name; } const char *subscreenlist_b(int index, int *list_size) { if(index<0) { int i=0, j=0; while(custom_subscreen[j].objects[0].type!=ssoNULL) { if(custom_subscreen[j].ss_type==sstPASSIVE) { ++i; } ++j; } *list_size = i; return NULL; } // return custsubscrtype_str[index]; int i=-1, j=0; while(custom_subscreen[j].name[0]&&i!=index) { if(custom_subscreen[j].ss_type==sstPASSIVE) { ++i; } ++j; } return custom_subscreen[j-1].name; } static ListData subscreen_list(subscreenlist, &font); DIALOG sslist_dlg[] = { // (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) { jwin_win_proc, 0, 0, 234, 148, vc(14), vc(1), 0, D_EXIT, 0, 0, (void *) "Select Subscreen", NULL, NULL }, { d_timer_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { jwin_abclist_proc, 12, 24, 211, 95, jwin_pal[jcTEXTFG], jwin_pal[jcTEXTBG], 0, D_EXIT, 0, 0, (void *) &subscreen_list, NULL, NULL }, { jwin_button_proc, 12, 123, 61, 21, vc(14), vc(1), 13, D_EXIT, 0, 0, (void *) "Edit", NULL, NULL }, { jwin_button_proc, 85, 123, 61, 21, vc(14), vc(1), KEY_DEL, D_EXIT, 0, 0, (void *) "Delete", NULL, NULL }, { jwin_button_proc, 158, 123, 61, 21, vc(14), vc(1), 27, D_EXIT, 0, 0, (void *) "Done", NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; int onEditSubscreens() { int ret=-1; sslist_dlg[0].dp2=lfont; sstemplatelist_dlg[0].dp2=lfont; DIALOG *sslist_cpy = resizeDialog(sslist_dlg, 1.5); while(ret!=0&&ret!=5) { ret=zc_popup_dialog(sslist_cpy,2); if(ret==4) { int confirm = jwin_alert("Confirm Delete", "You are about to delete the selected subscreen!", "Are you sure?", NULL, "OK", "Cancel", KEY_ENTER, KEY_ESC, lfont); if(confirm==1) { delete_subscreen(sslist_cpy[2].d1); saved=false; } } else if(ret==2 || ret ==3) { if(custom_subscreen[sslist_cpy[2].d1].ss_type==sstACTIVE) { subscreen_dlg[3].h=172*(is_large() ? 2 :1)-(is_large() ?4:0); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } else if(custom_subscreen[sslist_cpy[2].d1].ss_type==sstPASSIVE) { subscreen_dlg[3].h=60*(is_large() ? 2 : 1)-(is_large() ?4:0); subscreen_dlg[4].h=subscreen_dlg[3].h-4; //iu;hukl;kh; } else { subscreen_dlg[3].h=20*(is_large() ? 2 : 1); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } css = &custom_subscreen[sslist_cpy[2].d1]; bool edit_it=true; if(css->objects[0].type==ssoNULL) { DIALOG *sstemplatelist_cpy = resizeDialog(sstemplatelist_dlg, 1.5); ret=zc_popup_dialog(sstemplatelist_cpy,4); if(ret==6) { if(sstemplatelist_cpy[5].d1<15) { if(sstemplatelist_cpy[5].d1 != 0) { subscreen_object *tempsub; if(sstemplatelist_cpy[4].d1==0) { tempsub = default_subscreen_active[(sstemplatelist_cpy[5].d1-1)/2][(sstemplatelist_cpy[5].d1-1)&1]; } else { tempsub = default_subscreen_passive[(sstemplatelist_cpy[5].d1-1)/2][(sstemplatelist_cpy[5].d1-1)&1]; } int i; for(i=0; (i<MAXSUBSCREENITEMS&&tempsub[i].type!=ssoNULL); i++) { switch(tempsub[i].type) { case ssoTEXT: case ssoTEXTBOX: case ssoCURRENTITEMTEXT: case ssoCURRENTITEMCLASSTEXT: if(css->objects[i].dp1 != NULL) delete [](char *)css->objects[i].dp1; memcpy(&css->objects[i],&tempsub[i],sizeof(subscreen_object)); css->objects[i].dp1 = NULL; css->objects[i].dp1 = new char[strlen((char*)tempsub[i].dp1)+1]; strcpy((char*)css->objects[i].dp1,(char*)tempsub[i].dp1); break; default: memcpy(&css->objects[i],&tempsub[i],sizeof(subscreen_object)); break; } } } if(sstemplatelist_cpy[4].d1==0) { css->ss_type=sstACTIVE; sprintf(css->name, activesubscrtype_str[sstemplatelist_cpy[5].d1]); subscreen_dlg[3].h=172*(is_large() ? 2 : 1); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } else { css->ss_type=sstPASSIVE; sprintf(css->name, passivesubscrtype_str[sstemplatelist_cpy[5].d1]); subscreen_dlg[3].h=60*(is_large() ? 2 : 1); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } } else //Z3 { subscreen_object *tempsub; if(sstemplatelist_cpy[4].d1==0) { tempsub = z3_active_a; } else { tempsub = z3_passive_a; } int i; for(i=0; (i<MAXSUBSCREENITEMS&&tempsub[i].type!=ssoNULL); i++) { switch(tempsub[i].type) { case ssoTEXT: case ssoTEXTBOX: case ssoCURRENTITEMTEXT: case ssoCURRENTITEMCLASSTEXT: if(css->objects[i].dp1 != NULL) delete [](char *)css->objects[i].dp1; memcpy(&css->objects[i],&tempsub[i],sizeof(subscreen_object)); css->objects[i].dp1 = NULL; css->objects[i].dp1 = new char[strlen((char*)tempsub[i].dp1)+1]; strcpy((char*)css->objects[i].dp1,(char*)tempsub[i].dp1); break; default: memcpy(&css->objects[i],&tempsub[i],sizeof(subscreen_object)); break; } } if(sstemplatelist_cpy[4].d1==0) { css->ss_type=sstACTIVE; sprintf(css->name, activesubscrtype_str[sstemplatelist_cpy[5].d1]); subscreen_dlg[3].h=172*(is_large() ? 2 : 1); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } else { css->ss_type=sstPASSIVE; sprintf(css->name, passivesubscrtype_str[sstemplatelist_cpy[5].d1]); subscreen_dlg[3].h=60*(is_large() ? 2 : 1); subscreen_dlg[4].h=subscreen_dlg[3].h-4; } } } else { edit_it=false; } delete[] sstemplatelist_cpy; } if(edit_it) { edit_subscreen(); } } } delete[] sslist_cpy; Backend::mouse->setWheelPosition(0); return D_O_K; } void update_sso_name() { if(curr_subscreen_object<0) { sprintf(str_oname, "No object selected"); } else { sprintf(str_oname, "%3d: %s", curr_subscreen_object, sso_name(css->objects, curr_subscreen_object)); } subscreen_dlg[5].flags|=D_DIRTY; subscreen_dlg[6].flags|=D_DIRTY; } void center_zq_subscreen_dialogs() { jwin_center_dialog(grid_dlg); jwin_center_dialog(sel_options_dlg); jwin_center_dialog(sslist_dlg); jwin_center_dialog(ssolist_dlg); jwin_center_dialog(sso_master_properties_dlg); jwin_center_dialog(sstemplatelist_dlg); jwin_center_dialog(subscreen_dlg); } void delete_subscreen(int subscreenidx) { if(custom_subscreen[subscreenidx].objects[0].type == ssoNULL) return; //delete reset_subscreen(&custom_subscreen[subscreenidx]); //and move all other subscreens up for(int i=subscreenidx+1; i<MAXCUSTOMSUBSCREENS; i++) { memcpy(&custom_subscreen[i-1], &custom_subscreen[i], sizeof(subscreen_group)); } //fix dmaps int dmap_count=count_dmaps(); for(int i=0; i<dmap_count; i++) { //decrement if(DMaps[i].active_subscreen > subscreenidx) DMaps[i].active_subscreen--; if(DMaps[i].passive_subscreen > subscreenidx) DMaps[i].passive_subscreen--; } } // These were defined in ffscript.h; no need for them here #undef DELAY #undef WIDTH #undef HEIGHT #define D1 0x00000001 #define D2 0x00000002 #define D3 0x00000004 #define D4 0x00000008 #define D5 0x00000010 #define D6 0x00000020 #define D7 0x00000040 #define D8 0x00000080 #define D9 0x00000100 #define D10 0x00000200 #define D1_TO_D10 0x000003FF #define COLOR1 0x00000400 #define COLOR2 0x00000800 #define COLOR3 0x00001000 #define FRAMES 0x00002000 #define FRAME 0x00004000 #define SPEED 0x00008000 #define DELAY 0x00010000 #define WIDTH 0x00020000 #define HEIGHT 0x00040000 // This function does the actual copying. Name sucks, but whatever. // what controls which properties are copied. Type, x, y, and dp1 // are never copied. The active up/down/scrolling flags from pos // are always copied, but the rest of it is not. void doCopySSOProperties(subscreen_object& src, subscreen_object& dest, int what) { dest.pos&=~(sspUP|sspDOWN|sspSCROLLING); dest.pos|=src.pos&(sspUP|sspDOWN|sspSCROLLING); // Actually, I think pos is nothing but those three flags... if(what&WIDTH) dest.w=src.w; if(what&HEIGHT) dest.h=src.h; if(what&D1) dest.d1=src.d1; if(what&D2) dest.d2=src.d2; if(what&D3) dest.d3=src.d3; if(what&D4) dest.d4=src.d4; if(what&D5) dest.d5=src.d5; if(what&D6) dest.d6=src.d6; if(what&D7) dest.d7=src.d7; if(what&D8) dest.d8=src.d8; if(what&D9) dest.d9=src.d9; if(what&D10) dest.d10=src.d10; if(what&COLOR1) { dest.colortype1=src.colortype1; dest.color1=src.color1; } if(what&COLOR2) { dest.colortype2=src.colortype2; dest.color2=src.color2; } if(what&COLOR3) { dest.colortype3=src.colortype3; dest.color3=src.color3; } if(what&FRAMES) dest.frames=src.frames; if(what&FRAME) dest.frame=src.frame; if(what&SPEED) dest.speed=src.speed; if(what&DELAY) dest.delay=src.delay; } // Copies one object's properties to another. Selects properties depending on // the object type; some things are deliberately skipped, like which heart // container a life gauge piece corresponds to. void copySSOProperties(subscreen_object& src, subscreen_object& dest) { if(src.type!=dest.type || &src==&dest) return; switch(src.type) { case sso2X2FRAME: doCopySSOProperties(src, dest, D1|D2|D3|D4|COLOR1); break; case ssoTEXT: doCopySSOProperties(src, dest, D1|D2|D3|COLOR1|COLOR2|COLOR3); break; case ssoLINE: doCopySSOProperties(src, dest, D1|D2|COLOR1|WIDTH|HEIGHT); break; case ssoRECT: doCopySSOProperties(src, dest, D1|D2|COLOR1|COLOR2|WIDTH|HEIGHT); break; case ssoBSTIME: case ssoTIME: case ssoSSTIME: doCopySSOProperties(src, dest, D1|D2|D3|COLOR1|COLOR2|COLOR3); break; case ssoMAGICMETER: // Full meter // No properties but pos doCopySSOProperties(src, dest, 0); break; case ssoLIFEMETER: doCopySSOProperties(src, dest, D2|D3); break; case ssoBUTTONITEM: doCopySSOProperties(src, dest, D2); break; case ssoCOUNTER: // Single counter doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|D6|COLOR1|COLOR2|COLOR3); break; case ssoCOUNTERS: // Counter block doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|COLOR1|COLOR2|COLOR3); break; case ssoMINIMAPTITLE: doCopySSOProperties(src, dest, D1|D2|D3|D4|COLOR1|COLOR2|COLOR3); break; case ssoMINIMAP: doCopySSOProperties(src, dest, D1|D2|D3|COLOR1|COLOR2|COLOR3); break; case ssoLARGEMAP: doCopySSOProperties(src, dest, D1|D2|D3|D10|COLOR1|COLOR2); break; case ssoCLEAR: doCopySSOProperties(src, dest, COLOR1); break; case ssoCURRENTITEM: // Only the invisible flag doCopySSOProperties(src, dest, D2); break; case ssoTRIFRAME: doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|D6|D7|COLOR1|COLOR2); break; case ssoTRIFORCE: // Single piece doCopySSOProperties(src, dest, D1|D2|D3|D4|COLOR1); break; case ssoTILEBLOCK: doCopySSOProperties(src, dest, D1|D2|D3|D4|COLOR1|WIDTH|HEIGHT); break; case ssoMINITILE: // Does this one work at all? doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|D6|COLOR1|WIDTH|HEIGHT); break; case ssoSELECTOR1: case ssoSELECTOR2: doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|COLOR1); break; case ssoMAGICGAUGE: // Single piece // Skip magic container (d1) doCopySSOProperties(src, dest, (D1_TO_D10&~D1)|COLOR1|COLOR2|WIDTH|HEIGHT); break; case ssoLIFEGAUGE: // Single piece // Skip heart container (d1) doCopySSOProperties(src, dest, (D1_TO_D10&~D1)|COLOR1|COLOR2|WIDTH|HEIGHT); break; case ssoTEXTBOX: case ssoSELECTEDITEMNAME: doCopySSOProperties(src, dest, D1|D2|D3|D4|D5|COLOR1|COLOR2|COLOR3|WIDTH|HEIGHT); break; } } /*** end of subscr.cc ***/
gpl-3.0
gianitobia/ippocrate-j2ee
Ippocrate-war/src/java/utils/QuickPopulate.java
29601
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package utils; import Controller.GestoreInserimentoDatiLocal; import Entity.CartellaClinicaFacadeLocal; import Entity.MedicoEsternoFacadeLocal; import Entity.MedicoOspedalieroFacadeLocal; import Entity.OspedaleFacadeLocal; import Entity.PazienteFacadeLocal; import Entity.PrestazioneSala; import Entity.RepartoFacadeLocal; import Entity.SalaFacadeLocal; import Entity.StudioMedicoFacadeLocal; import static Utility.Gestore_Date.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author toby */ @WebServlet(name = "QuickPopulate", urlPatterns = {"/QuickPopulate"}) public class QuickPopulate extends HttpServlet { @EJB private GestoreInserimentoDatiLocal insert; @EJB private MedicoOspedalieroFacadeLocal medicoOspedalieroFacade; @EJB private MedicoEsternoFacadeLocal medicoEsternoFacade1; @EJB private OspedaleFacadeLocal ospedaleFacade; @EJB private PazienteFacadeLocal pazienteFacade; @EJB private RepartoFacadeLocal repartoFacade; @EJB private MedicoEsternoFacadeLocal medicoEsternoFacade; @EJB private CartellaClinicaFacadeLocal cartellaClinicaFacade; @EJB private StudioMedicoFacadeLocal studioMedicoFacade; @EJB private SalaFacadeLocal salaFacade; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] prestazioniSala = {"Amniocentesi", "Biopsia cervicovaginale ", "Ecocolordoppler del seno", "Ecocolordoppler ostetrico-ginecologico ", "Ecografia del seno", "Ecografia ginecologica", "Ecografia ostetrica", "Ecografia strutturale", "Pap-test", "Implantologia", "Otturazione carie 3 pareti", "Elettrocardiogramma", "Infiltrazione articolare", "Doppler vascolare", "Terapia sclerosante", "Trattamento delle ulcere varicose", "Correnti di Kotz", "Correnti interferenziali", "Elettrostimolazioni", "Elettroterapia antalgica", "Ionoforesi", "Linfodrenaggio manuale", "Magnetoterapia a placche", "Massoterapia terapeutica", "Rieducazione motoria", "Ultrasuonoterapia", "Ecografia addome superiore", "Rettoscopia – Proctoscopia", "Chirurgia dermatologica", "Crioterapia", "Dermatoscopia", "Elettrocoagulazione", "Mesoterapia", "Peeling cutaneo", "Ricerca microscopica infezioni della pelle", "Terapie dermatologiche topiche", "Trattamento anticellulite", "Trattamento antietà con crio-resurfacing", "Trattamento laser dei capillari", "Trattamento rughe con acido ialuronico", "Trattamento smagliature", "Tricogramma", "Cura del piede", "Massaggio circolatorio del piede", "Esame audiometrico", "Esame impedenzometrico", "Esame vestibolare", "Impedenzometria ", "Laringoscopia", "Otoscopia", "Rinoscopia", "Fondo oculare", "Fonometria", "Risonanza magnetica", "Ago aspirato ecoguidato del seno", "Agobiopsia del seno", "Dermatoscopia del seno", "Ecocolordoppler del seno", "Ecografia del seno", "Analisi del sangue", "Analisi delle feci", "Test antidroga", "Ingessatura di un arto superiore", "Ingessatura di un arto inferiore", "Sostituzione del gesso", "Rimozione del gesso" }; String[] prestazioniMedico = { "Visita ginecologica", "Visita ostetrica", "Visita senologica", "Visita internistica", "Ablazione tartaro", "Tampone vaginale", "Capsula in oro-ceramica", "Estrazione dente permanente", "Visita diabetologica ", "Visita endocrinologica", "Visita odontoiatrica", "Visita ortodontica", "Visita cardiologia", "Visita ortopedica", "Visita neonatologica", "Visita pediatrica", "Visita angiologia", "Visita dermatologica", "Visita chirurgica vascolare ", "Visita epatologica", "Visita gastroenterologica", "Visite dietologiche ", "Colloquio psicodiagnostico", "Colloquio psicologico", "Misurazione dello stress", "Psicoterapia individuale", "Visita otorino", "Test psicodiagnostico", "Visita oculistica", "Visita senologica", "Visita senologica con ecografia", "Visita dermatologica"}; //creazione dio Long medico_dio = insert.addMedicoOspedaliero("Gregory", "House", "Patologo", generateDate(), "house", "sonodio", "666", "1C"); Long medico_pippa = insert.addMedicoEsterno("Hershel", "Greene", "Ginecologo", generateDate(), "hershel", "sonopippa", "666"); //creazione ospedali Long id_o_1 = insert.addOspedale("Maria Vittoria", "Via Cibrario, 72, Torino"); Long id_o_2 = insert.addOspedale("CTO", "Via Gianfranco Zuretti, 29, 10126 Torino"); Long id_o_3 = insert.addOspedale("Amedeo di Savoia", "Corso Svizzera, 164, 10149 Torino"); Long id_o_4 = insert.addOspedale("Molinette", "Corso Bramante, 88, 10126 Torino"); //creazione studi medici Long id_sm_1 = insert.addStudioMedico("R.I.B.A.", "Corso Regina Margherita, 10, 10133 Torino"); Long id_sm_2 = insert.addStudioMedico("Corba", "Via Roma, 1, 10012 Torino"); Long id_sm_3 = insert.addStudioMedico("C.D.C", "Piazza Bernini, 5, 10136 Torino"); //creazione reparti Long id_r_1 = insert.addReparto(id_o_1, "Cardiologia", medico_dio); //Long id_r_2 = insert.addReparto(id_o_1, "Chirurgia generale", medico_dio); //Long id_r_3 = insert.addReparto(id_o_1, "Dialisi", medico_dio); //Long id_r_4 = insert.addReparto(id_o_1, "Gastroenterologia", medico_dio); //Long id_r_5 = insert.addReparto(id_o_1, "Geriatria", medico_dio); //Long id_r_6 = insert.addReparto(id_o_1, "Radiologia", medico_dio); Long id_r_7 = insert.addReparto(id_o_1, "Ortopedia", medico_dio); Long id_r_8 = insert.addReparto(id_o_1, "Laboratorio analisi", medico_dio); Long id_r_9 = insert.addReparto(id_o_1, "Medicina fisica e riabilitazione", medico_dio); //Long id_r_10 = insert.addReparto(id_o_1, "Ortopedia e Traumatologia", medico_dio); //Long id_r_11 = insert.addReparto(id_o_2, "Cardiologia", medico_dio); //Long id_r_12 = insert.addReparto(id_o_2, "Chirurgia generale", medico_dio); //Long id_r_13 = insert.addReparto(id_o_2, "Dialisi", medico_dio); //Long id_r_14 = insert.addReparto(id_o_2, "Gastroenterologia", medico_dio); //Long id_r_15 = insert.addReparto(id_o_2, "Geriatria", medico_dio); Long id_r_16 = insert.addReparto(id_o_2, "Radiologia", medico_dio); Long id_r_17 = insert.addReparto(id_o_2, "Ortopedia", medico_dio); Long id_r_18 = insert.addReparto(id_o_2, "Laboratorio analisi", medico_dio); Long id_r_19 = insert.addReparto(id_o_2, "Medicina fisica e riabilitazione", medico_dio); //Long id_r_20 = insert.addReparto(id_o_2, "Ortopedia e Traumatologia", medico_dio); Long id_r_21 = insert.addReparto(id_o_3, "Cardiologia", medico_dio); //Long id_r_22 = insert.addReparto(id_o_3, "Chirurgia generale", medico_dio); //Long id_r_23 = insert.addReparto(id_o_3, "Dialisi", medico_dio); //Long id_r_24 = insert.addReparto(id_o_3, "Gastroenterologia", medico_dio); //Long id_r_25 = insert.addReparto(id_o_3, "Geriatria", medico_dio); Long id_r_26 = insert.addReparto(id_o_3, "Radiologia", medico_dio); //Long id_r_27 = insert.addReparto(id_o_3, "Ortopedia", medico_dio); //Long id_r_28 = insert.addReparto(id_o_3, "Laboratorio analisi", medico_dio); Long id_r_29 = insert.addReparto(id_o_3, "Medicina fisica e riabilitazione", medico_dio); //Long id_r_30 = insert.addReparto(id_o_3, "Ortopedia e Traumatologia", medico_dio); Long id_r_31 = insert.addReparto(id_o_4, "Cardiologia", medico_dio); //Long id_r_32 = insert.addReparto(id_o_4, "Chirurgia generale", medico_dio); //Long id_r_33 = insert.addReparto(id_o_4, "Dialisi", medico_dio); //Long id_r_34 = insert.addReparto(id_o_4, "Gastroenterologia", medico_dio); //Long id_r_35 = insert.addReparto(id_o_4, "Geriatria", medico_dio); Long id_r_36 = insert.addReparto(id_o_4, "Radiologia", medico_dio); Long id_r_37 = insert.addReparto(id_o_4, "Ortopedia", medico_dio); //Long id_r_38 = insert.addReparto(id_o_4, "Laboratorio analisi", medico_dio); //Long id_r_39 = insert.addReparto(id_o_4, "Medicina fisica e riabilitazione", medico_dio); //Long id_r_40 = insert.addReparto(id_o_4, "Ortopedia e Traumatologia", medico_dio); //inserimento sale ospedale //Long id_s_1 = insert.addSalaOspedale(id_r_6, "Radiografia", medico_dio); Long id_s_2 = insert.addSalaOspedale(id_r_16, "Radiografia", medico_dio); Long id_s_3 = insert.addSalaOspedale(id_r_26, "Radiografia", medico_dio); Long id_s_4 = insert.addSalaOspedale(id_r_36, "Radiografia", medico_dio); //Long id_s_5 = insert.addSalaOspedale(id_r_6, "RMN", medico_dio); Long id_s_6 = insert.addSalaOspedale(id_r_16, "RMN", medico_dio); Long id_s_7 = insert.addSalaOspedale(id_r_26, "RMN", medico_dio); Long id_s_8 = insert.addSalaOspedale(id_r_36, "RMN", medico_dio); Long id_s_9 = insert.addSalaOspedale(id_r_8, "Analisi", medico_dio); Long id_s_10 = insert.addSalaOspedale(id_r_18, "Analisi", medico_dio); //Long id_s_11 = insert.addSalaOspedale(id_r_28, "Analisi", medico_dio); //Long id_s_12 = insert.addSalaOspedale(id_r_38, "Analisi", medico_dio); Long id_s_13 = insert.addSalaOspedale(id_r_7, "Sala gessi", medico_dio); Long id_s_14 = insert.addSalaOspedale(id_r_17, "Sala gessi", medico_dio); //Long id_s_15 = insert.addSalaOspedale(id_r_27, "Sala gessi", medico_dio); Long id_s_16 = insert.addSalaOspedale(id_r_37, "Sala gessi", medico_dio); Long id_s_17 = insert.addSalaOspedale(id_r_9, "Palestra per riabilitazione", medico_dio); Long id_s_18 = insert.addSalaOspedale(id_r_19, "Palestra per riabilitazione", medico_dio); Long id_s_19 = insert.addSalaOspedale(id_r_29, "Palestra per riabilitazione", medico_dio); //Long id_s_20 = insert.addSalaOspedale(id_r_39, "Palestra per riabilitazione", medico_dio); Long id_s_21 = insert.addSalaOspedale(id_r_1, "Elettrocardiografia", medico_dio); //Long id_s_22 = insert.addSalaOspedale(id_r_11, "Elettrocardiografia", medico_dio); Long id_s_23 = insert.addSalaOspedale(id_r_21, "Elettrocardiografia", medico_dio); Long id_s_24 = insert.addSalaOspedale(id_r_31, "Elettrocardiografia", medico_dio); //inserimento sale studi medici Long id_s_25 = insert.addSalaStudio(id_sm_1, "Radiografia", medico_pippa); Long id_s_26 = insert.addSalaStudio(id_sm_1, "RMN", medico_pippa); Long id_s_27 = insert.addSalaStudio(id_sm_2, "Radiografia", medico_pippa); Long id_s_28 = insert.addSalaStudio(id_sm_2, "RMN", medico_pippa); Long id_s_29 = insert.addSalaStudio(id_sm_3, "RMN", medico_pippa); Long id_s_30 = insert.addSalaStudio(id_sm_1, "Analisi", medico_pippa); Long id_s_31 = insert.addSalaStudio(id_sm_2, "Analisi", medico_pippa); Long id_s_32 = insert.addSalaStudio(id_sm_3, "Analisi", medico_pippa); Long id_s_33 = insert.addSalaStudio(id_sm_1, "Palestra per riabilitazione", medico_pippa); Long id_s_34 = insert.addSalaStudio(id_sm_2, "Palestra per riabilitazione", medico_pippa); Long id_s_35 = insert.addSalaStudio(id_sm_3, "Palestra per riabilitazione", medico_pippa); Long id_s_36 = insert.addSalaStudio(id_sm_1, "Elettrocardiografia", medico_pippa); Long id_s_37 = insert.addSalaStudio(id_sm_2, "Elettrocardiografia", medico_pippa); Long id_s_38 = insert.addSalaStudio(id_sm_3, "Elettrocardiografia", medico_pippa); //inserimento pazienti insert.addPaziente("Arrigo", "Toscano", "10000", "10000", "M", "via Cocci, 7", generateDate(), "Torino"); insert.addPaziente("Raffaele", "Udinese", "11000", "11000", "M", "Via Acrone, 109", generateDate(), "Sarezzano"); insert.addPaziente("Francesco", "Arcuri", "11100", "11100", "M", "Corso Alcide De Gasperi, 32", generateDate(), "Candide"); insert.addPaziente("Macario", "Napolitano", "11110", "11110", "M", "Via Galvani, 74", generateDate(), "Roma"); insert.addPaziente("Teodata", "Lombardo", "11111", "11111", "F", "Via Nazionale, 131", generateDate(), "Trafoi"); insert.addPaziente("Maia", "Gallo", "10111", "10111", "F", "Via Venezia, 43", generateDate(), "Trento"); insert.addPaziente("Aldo", "Siciliano", "10011", "10011", "M", "Piazza Bovio, 71", generateDate(), "Bologna"); insert.addPaziente("Damiana", "Lorenzo", "20000", "20000", "F", "Vico Giganti, 68", generateDate(), "Milano"); insert.addPaziente("Simonetta", "Fiorentino", "20002", "20002", "F", "Via Agostino Depretis, 98", generateDate(), "Prato"); insert.addPaziente("Rosita", "Buccho", "20022", "20022", "F", "Piazza Trieste e Trento, 70", generateDate(), "Prunetto"); insert.addPaziente("Gaetana", "Panicucci", "20222", "20222", "F", "Viale Augusto, 10", generateDate(), "Messina"); insert.addPaziente("Siro", "Greco", "22222", "22222", "M", "Corso Vittorio Emanuele, 95", generateDate(), "Roma"); insert.addPaziente("Adelfina", "Pirozzi", "22000", "22000", "F", "Via Francesco Del Giudice, 109", generateDate(), "Napoli"); insert.addPaziente("Eligio", "Beneventi", "22200", "22200", "M", "Via Valpantena, 17", generateDate(), "Genova"); insert.addPaziente("Mara", "Rossi", "22220", "22220", "F", "Via Sergente Maggiore, 124", generateDate(), "Cuneo"); insert.addPaziente("Irmina", "Pagnotto", "30000", "30000", "F", "Via Nizza, 148", generateDate(), "Torino"); insert.addPaziente("Alina", "Mazzi", "33000", "33000", "F", "Via Volto San Luca, 30", generateDate(), "Torino"); insert.addPaziente("Clotilde", "Beneventi", "33300", "33300", "F", "Via Loreto, 81", generateDate(), "Livorno"); insert.addPaziente("Marco", "Onio", "33120", "33120", "M", "Via degli Aldobrandeschi, 77", generateDate(), "Genova"); insert.addPaziente("Santo", "Castiglione", "33333", "33333", "M", "Piazza Trieste e Trento, 127", generateDate(), "Torino"); insert.addPaziente("Luisa", "Pisano", "12303", "12303", "F", "Via Carlo Alberto, 18", generateDate(), "Avellino"); insert.addPaziente("Livio", "Piccio", "33133", "33033", "M", "Corso Vittorio Emanuele, 15", generateDate(), "Bari"); insert.addPaziente("Quinto", "Fallaci", "30133", "30133", "M", "Via San Pietro Ad Aram, 57", generateDate(), "Modena"); insert.addPaziente("Anselmo", "Mancini", "40000", "40000", "M", "Via Antonio Cecchi, 94", generateDate(), "Brindisi"); insert.addPaziente("Tolomeo", "Trevisano", "40004", "40004", "M", "Via di Santa Melania, 44", generateDate(), "Venezia"); insert.addPaziente("Giorgio", "Toscani", "100001", "10000", "M", "via Noci, 7", generateDate(), "Torino"); insert.addPaziente("Roberto", "Marche", "110001", "11000", "M", "Via Acrone, 109", generateDate(), "Sarezzano"); insert.addPaziente("Ugo", "Arcuri", "111001", "11100", "M", "Corso Alcide De Gasperi, 32", generateDate(), "Candide"); insert.addPaziente("Marika", "Napoli", "111101", "11110", "F", "Via Galvani, 74", generateDate(), "Roma"); insert.addPaziente("Olmo", "Lordo", "111111", "11111", "M", "Via Nazionale, 131", generateDate(), "Trafoi"); insert.addPaziente("Maria", "Galli", "101111", "10111", "F", "Via Venezia, 43", generateDate(), "Roma"); insert.addPaziente("Aldo", "Siciliano", "100111", "10011", "M", "Piazza Bovio, 71", generateDate(), "Bologna"); insert.addPaziente("Damiano", "Tarantino", "2030001", "20000", "M", "Vico Giganti, 68", generateDate(), "Milano"); insert.addPaziente("Simonetta", "Scenna", "2400012", "20002", "F", "Via Agostino Depretis, 98", generateDate(), "Prato"); insert.addPaziente("Rosa", "Bucco", "200222", "200122", "F", "Piazza Trieste e Trento, 70", generateDate(), "Prunetto"); insert.addPaziente("Gaetano", "Panucci", "201222", "210222", "M", "Viale Augusto, 10", generateDate(), "Avellino"); insert.addPaziente("Matteo", "Greco", "2222124", "222212", "M", "Corso Vittorio Emanuele, 95", generateDate(), "Roma"); insert.addPaziente("Adelfina", "Pirozzi", "220400", "22000", "F", "Via Francesco Del Giudice, 109", generateDate(), "Napoli"); insert.addPaziente("Elisa", "Struzzo", "222300", "22200", "F", "Via Valpadana, 17", generateDate(), "Genova"); insert.addPaziente("Armanda", "Papa", "222230", "22220", "F", "Via Sergente Maggiore, 124", generateDate(), "Cuneo"); insert.addPaziente("Gelmina", "Patto", "300030", "30000", "F", "Via Nizza, 148", generateDate(), "Torino"); insert.addPaziente("Adelina", "Mazzi", "330006", "33000", "F", "Via Volto San Luca, 30", generateDate(), "Torino"); insert.addPaziente("Cloe", "Benvenuti", "333050", "33300", "F", "Via Loreto, 81", generateDate(), "Livorno"); insert.addPaziente("Garco", "Orio", "33330", "533330", "M", "Via degli Aldobrandeschi, 77", generateDate(), "Genova"); insert.addPaziente("Santino", "Castiglione", "332333", "33333", "M", "Piazza Trieste e Trento, 127", generateDate(), "Torino"); insert.addPaziente("Luca", "Pisano", "33303", "334303", "M", "Via Carlo Alberto, 18", generateDate(), "Venezia"); insert.addPaziente("Livio", "Piccolo", "33033", "333033", "M", "Corso Vittorio Emanuele, 15", generateDate(), "Bari"); insert.addPaziente("Mara", "Fellaci", "30333", "303433", "F", "Via San Pietro Ad Aram, 57", generateDate(), "Modena"); insert.addPaziente("Gianna", "Mancini", "40000", "406000", "F", "Via Antonio Cecchi, 94", generateDate(), "Brindisi"); insert.addPaziente("Arturo", "Treviso", "40004", "4000774", "M", "Via di Santa Melania, 44", generateDate(), "Avellino"); //inserimento medici //medici ospedalieri insert.addMedicoOspedaliero("Cassandra", "Trentini", "Ginecologia", generateDate(), "1000", "1000", "1000", "28", id_r_1); insert.addMedicoOspedaliero("Irma", "Folliero", "Immunologia", generateDate(), "2000", "2000", "2000", "T4", id_r_1); insert.addMedicoOspedaliero("Neera", "Li Fonti", "Cardiochirurgia", generateDate(), "3000", "3000", "3000", "F6", id_r_26); insert.addMedicoOspedaliero("Salomone", "Cocci", "Ematologia", generateDate(), "4000", "4000", "4000", "C3", id_r_31); insert.addMedicoOspedaliero("Alfio", "Panicucci", "Nefrologia", generateDate(), "5000", "5000", "5000", "4A", id_r_29); insert.addMedicoOspedaliero("Camilla", "Genovese", "Urologia", generateDate(), "6000", "6000", "6000", "7V", id_r_1); insert.addMedicoOspedaliero("Jacopo", "Zetticci", "Cardiologia", generateDate(), "7000", "7000", "7000", "7S", id_r_21); insert.addMedicoOspedaliero("Imelda", "Fanucci", "Endocrinologia", generateDate(), "8000", "8000", "8000", "2R", id_r_1); insert.addMedicoOspedaliero("Guglielma", "Bergamaschi", "Neurooncologia", generateDate(), "9000", "9000", "9000", "2R", id_r_18); insert.addMedicoOspedaliero("Luigina", "Longo", "Ginecologia", generateDate(), "1001", "1001", "1001", "2T", id_r_37); insert.addMedicoOspedaliero("Natale", "Milanesi", "Chirurgia generale", generateDate(), "2002", "2002", "2002", "4E", id_r_17); insert.addMedicoOspedaliero("Albertino", "Cremonesi", "Medicina generale", generateDate(), "3003", "3003", "3003", "3R", id_r_1); insert.addMedicoOspedaliero("Muzio", "Padovesi", "Radiologia", generateDate(), "4004", "4004", "4004", "9R", id_r_17); insert.addMedicoOspedaliero("Tolomeo", "Colombo", "Radiologia", generateDate(), "5005", "5005", "5005", "4R", id_r_1); insert.addMedicoOspedaliero("Immacolata", "Zetticci", "Neurologia", generateDate(), "6006", "6006", "6006", "9N", id_r_21); insert.addMedicoOspedaliero("Urania", "Sal", "Patologia orale", generateDate(), "7007", "7007", "7007", "4O", id_r_7); insert.addMedicoOspedaliero("Saverio", "Greco", "Ortopedia", generateDate(), "8008", "8008", "8008", "O9", id_r_37); insert.addMedicoOspedaliero("Quintilio", "Marcelo", "Medicina dello sport", generateDate(), "9009", "9009", "9009", "S4", id_r_36); insert.addMedicoOspedaliero("Imelda", "Bianchi", "Medicina interna", generateDate(), "1101", "1101", "1101", "I2", id_r_19); insert.addMedicoOspedaliero("Ubalda", "Bergamaschi", "Neurologia", generateDate(), "2202", "2202", "2202", "N4", id_r_8); insert.addMedicoOspedaliero("Stella", "De Luca", "Allergologia", generateDate(), "3303", "3303", "3303", "A9", id_r_1); insert.addMedicoOspedaliero("Tranquilla", "Nucci", "Anestesia", generateDate(), "4404", "4404", "4404", "AN7", id_r_31); insert.addMedicoOspedaliero("Silvio", "Lombardi", "Radiologia", generateDate(), "5505", "5505", "5505", "R12", id_r_29); insert.addMedicoOspedaliero("Jacopo", "Manfrin", "Cardiochirurgia", generateDate(), "6606", "6606", "6606", "F7", id_r_1); //medici esterni insert.addMedicoEsterno("Arcangela", "Greece", "Cardiochirurgia", generateDate(), "7707", "7707", "7707", id_sm_2); insert.addMedicoEsterno("Consuelo", "Longo", "Nefrologia", generateDate(), "8808", "8808", "8808", id_sm_1); insert.addMedicoEsterno("Armando", "Sal", "Endocrinologia", generateDate(), "9909", "9909", "9909", id_sm_2); insert.addMedicoEsterno("Immacolata", "Mazzanti", "Radiologia", generateDate(), "1111", "1111", "1111", id_sm_1); insert.addMedicoEsterno("Frediana", "Iadanza", "Chirurgia generale", generateDate(), "2222", "2222", "2222", id_sm_1); insert.addMedicoEsterno("Massimo", "Padovano", "Patologia orale", generateDate(), "3333", "3333", "3333", id_sm_1); insert.addMedicoEsterno("Germana", "Ferri", "Medicina del lavoro", generateDate(), "4444", "4444", "4444", id_sm_3); insert.addMedicoEsterno("Landolfo", "Lettiere", "Radiologia", generateDate(), "5555", "5555", "5555", id_sm_1); insert.addMedicoEsterno("Amerigo", "Marcelo", "Radiologia", generateDate(), "6666", "6666", "6666", id_sm_1); insert.addMedicoEsterno("Petronio", "Dellucci", "Chirurgia generale", generateDate(), "7777", "7777", "7777", id_sm_1); insert.addPrestazioniMedico(prestazioniMedico); List<PrestazioneSala> listPrestazioniSala = insert.addPrestazioniSala(prestazioniSala); List<PrestazioneSala> prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(7)); prest.add(listPrestazioniSala.get(57)); //insert.addPrestazioniToSala(id_s_1, prest); insert.addPrestazioniToSala(id_s_2, prest); insert.addPrestazioniToSala(id_s_3, prest); insert.addPrestazioniToSala(id_s_4, prest); insert.addPrestazioniToSala(id_s_27, prest); insert.addPrestazioniToSala(id_s_25, prest); prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(53)); //insert.addPrestazioniToSala(id_s_5, prest); insert.addPrestazioniToSala(id_s_6, prest); insert.addPrestazioniToSala(id_s_7, prest); insert.addPrestazioniToSala(id_s_8, prest); insert.addPrestazioniToSala(id_s_26, prest); insert.addPrestazioniToSala(id_s_28, prest); insert.addPrestazioniToSala(id_s_29, prest); prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(60)); prest.add(listPrestazioniSala.get(61)); prest.add(listPrestazioniSala.get(59)); insert.addPrestazioniToSala(id_s_9, prest); insert.addPrestazioniToSala(id_s_10, prest); //insert.addPrestazioniToSala(id_s_11, prest); //insert.addPrestazioniToSala(id_s_12, prest); insert.addPrestazioniToSala(id_s_30, prest); insert.addPrestazioniToSala(id_s_31, prest); insert.addPrestazioniToSala(id_s_32, prest); prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(64)); prest.add(listPrestazioniSala.get(65)); prest.add(listPrestazioniSala.get(62)); prest.add(listPrestazioniSala.get(63)); insert.addPrestazioniToSala(id_s_13, prest); insert.addPrestazioniToSala(id_s_14, prest); //insert.addPrestazioniToSala(id_s_15, prest); insert.addPrestazioniToSala(id_s_16, prest); prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(24)); prest.add(listPrestazioniSala.get(46)); insert.addPrestazioniToSala(id_s_17, prest); insert.addPrestazioniToSala(id_s_18, prest); insert.addPrestazioniToSala(id_s_19, prest); //insert.addPrestazioniToSala(id_s_20, prest); insert.addPrestazioniToSala(id_s_33, prest); insert.addPrestazioniToSala(id_s_34, prest); insert.addPrestazioniToSala(id_s_35, prest); prest = new ArrayList<>(); prest.add(listPrestazioniSala.get(11)); prest.add(listPrestazioniSala.get(31)); insert.addPrestazioniToSala(id_s_21, prest); //insert.addPrestazioniToSala(id_s_22, prest); insert.addPrestazioniToSala(id_s_23, prest); insert.addPrestazioniToSala(id_s_24, prest); insert.addPrestazioniToSala(id_s_36, prest); insert.addPrestazioniToSala(id_s_37, prest); insert.addPrestazioniToSala(id_s_38, prest); insert.linkRepartoMedico(medico_dio, id_r_16); insert.linkStudioMedico(medico_pippa, id_sm_3); insert.linkRepartiPazienti(); insert.linkMediciPazienti(); insert.addCartelleCliniche(); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* String nome, String cognome, String cf, String password, String sesso, String indirizzo, Date data_nascita, String luogo_nascita */ /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet QuickPopulate</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet QuickPopulate at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
gpl-3.0
HampsterEater/FusionGameEngine
Source/Fusion/Windows/Games Explorer Window.cs
71213
/* * File: Game Explorer Window.cs * * Contains all the functional partial code declaration for the GameExplorer form. * * Copyright (c) Binary Phoenix. All rights reserved. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Xml; using System.IO; using System.IO.Compression; using System.Threading; using System.Diagnostics; using System.Windows.Forms; using BinaryPhoenix.Fusion.Runtime; using BinaryPhoenix.Fusion.Runtime.Resources; namespace BinaryPhoenix.Fusion.Engine.Windows { /// <summary> /// This is the main games explorer class. It deals with created and processing the games explorer window. /// </summary> public partial class GamesExplorerWindow : Form { #region Members #region Variables private ArrayList _myGames = new ArrayList(); private ImageList _myGamesImageList = new ImageList(); private ArrayList _downloads = new ArrayList(); private ArrayList _gamesLibrary = new ArrayList(); private ImageList _gamesLibraryImageList = new ImageList(); private ArrayList _newsItems = new ArrayList(); private bool _connectedToNet = true; #endregion #endregion #region Methods /// <summary> /// Initializes a new instance of this class. /// </summary> public GamesExplorerWindow() { InitializeComponent(); } /// <summary> /// Syncronizes the data displayed on this window. /// </summary> private void SyncronizeWindow() { if (Fusion.GlobalInstance.CurrentUsername != "" && _connectedToNet == true) { registerAccountToolStripMenuItem.Enabled = false; lostPasswordToolStripMenuItem.Enabled = false; loginToolStripMenuItem.Text = "Logout Of Account"; loginToolStripMenuItem.Enabled = true; gameLibraryStatusLabel.Visible = !(_gamesLibrary.Count != 0); gameLibraryContainer.Visible = (_gamesLibrary.Count != 0); if (_gamesLibrary.Count == 0) gameLibraryStatusLabel.Text = "No games available."; Text = "Fusion Game Explorer - (Logged in as " + Fusion.GlobalInstance.CurrentUsername+")"; refreshGamesLibraryToolStripMenuItem.Enabled = true; } else { loginToolStripMenuItem.Text = "Login To Account"; loginToolStripMenuItem.Enabled = true; registerAccountToolStripMenuItem.Enabled = true; lostPasswordToolStripMenuItem.Enabled = true; gameLibraryStatusLabel.Visible = true; gameLibraryContainer.Visible = false; gameLibraryStatusLabel.Text = "Please login to view Binary Phoenix's game library."; refreshGamesLibraryToolStripMenuItem.Enabled = false; } myGamesStatusLabel.Visible = (_myGames.Count == 0); myGamesContainer.Visible = (_myGames.Count != 0); myGamesContainer.Panel2Collapsed = (myGamesListView.SelectedItems.Count == 0); gameLibraryContainer.Panel2Collapsed = (gameLibraryListView.SelectedItems.Count == 0); if (myGamesListView.SelectedItems.Count != 0) { GameDescription selectedGame = _myGames[myGamesListView.SelectedIndices[0]] as GameDescription; myGamesDescriptionTextBox.Text = selectedGame.Description; myGamesLanguageLabel.Text = "Language: " + selectedGame.Language; myGamesPlayButton.Visible = true; myGamesEditorButton.Visible = File.Exists("editor.exe"); myGamesPlayersLabel.Text = "Players: " + selectedGame.Players; myGamesRatingLabel.Text = selectedGame.Rating; myGamesRequirementsLabel.Text = selectedGame.Requirements; myGamesTitleLabel.Text = selectedGame.Name; myGamesPublisherLabel.Text = selectedGame.Publisher; myGamesUpdateButton.Visible = false; // Is there an update available? foreach (GameDescription gamesLibraryDescription in _gamesLibrary) { if (gamesLibraryDescription.Name == selectedGame.Name && float.Parse(gamesLibraryDescription.Version) > float.Parse(selectedGame.Version)) { // Check we are not already being downloaded. bool found = false; foreach (DownloadItem download in _downloads) { if (download.GameDescription == selectedGame) { found = true; break; } } myGamesUpdateButton.Visible = (found == false); break; } } } if (gameLibraryListView.SelectedItems.Count != 0) { GameDescription selectedGame = _gamesLibrary[gameLibraryListView.SelectedIndices[0]] as GameDescription; gameLibraryDescriptionTextBox.Text = selectedGame.Description; gameLibraryLanguageLabel.Text = "Language: " + selectedGame.Language; gameLibraryPlayersLabel.Text = "Players: " + selectedGame.Players; gameLibraryRatingLabel.Text = selectedGame.Rating; gameLibraryRequirementsLabel.Text = selectedGame.Requirements; gameLibraryNameLabel.Text = selectedGame.Name; gameLibraryPublisherLabel.Text = selectedGame.Publisher; gameLibraryDownloadButton.Enabled = (selectedGame.Downloading != true); gameLibraryDownloadButton.Text = (selectedGame.Downloading ? "Downloading..." : "Download"); // Do we already own the current game? foreach (GameDescription myGameDescription in _myGames) if (myGameDescription.Name == selectedGame.Name && float.Parse(myGameDescription.Version) >= float.Parse(selectedGame.Version)) { gameLibraryDownloadButton.Text = "Downloaded"; gameLibraryDownloadButton.Enabled = false; break; } } if (_downloads.Count != 0) { downloadsStatusLabel.Visible = false; downloadsContainer.Visible = true; } else { downloadsStatusLabel.Visible = true; downloadsStatusLabel.Text = "You are not currently downloading anything."; downloadsContainer.Visible = false; } if (_connectedToNet == false) { statusToolStripProgressBar.Style = ProgressBarStyle.Continuous; Text = "Fusion Games Explorer (Offline)"; statusToolStripStatusLabel.BackColor = Color.Red; statusToolStripStatusLabel.Text = "Fusion was unable to connect to the internet."; newDownloadLabel.Text = "Unable to connect to the internet."; gameLibraryStatusLabel.Text = "Unable to connect to the internet."; registerAccountToolStripMenuItem.Enabled = false; loginToolStripMenuItem.Enabled = false; } } /// <summary> /// Invoked when the window is first shown. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void GamesExplorerWindow_Shown(object sender, EventArgs e) { //this.Enabled = false; // Create a splash screen. // SplashScreenWindow splashScreen = new SplashScreenWindow(); // splashScreen.Show(); // Refresh the my game's panel. //splashScreen.LoadingMessage = "Loading games ... "; LoadMyGames(); // Refresh the news //splashScreen.LoadingMessage = "Loading news ... "; if (Fusion.GlobalInstance.CurrentUsername != "") ValidateLogin(); if (_connectedToNet == true) { // Check password is correct. //splashScreen.LoadingMessage = "Validating login ... "; RefreshNews(); // Check for any updates and notify the user. //splashScreen.LoadingMessage = "Checking for updates ... "; CheckForUpdates(); } // Refresh the games library panel. if (_connectedToNet) { //splashScreen.LoadingMessage = "Loading game library ... "; LoadGamesLibrary(); } // Syncronize window. SyncronizeWindow(); //splashScreen.Close(); //this.Enabled = true; //this.Focus(); } /// <summary> /// Validates the current username and password. /// </summary> /// <returns>True if login is valid, else false.</returns> private bool ValidateLogin() { // See if we can connect to the internet. FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionverifylogin&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword)); try { downloader.Start(); statusToolStripStatusLabel.Text = "Validating login."; statusToolStripProgressBar.Style = ProgressBarStyle.Marquee; while (downloader.Complete == false) { if (downloader.Error != "") throw new Exception("An error occured while connecting to the server."); Application.DoEvents(); } statusToolStripProgressBar.Style = ProgressBarStyle.Continuous; statusToolStripStatusLabel.Text = "Validating login."; // Get the data. ASCIIEncoding encoding = new ASCIIEncoding(); string response = encoding.GetString(downloader.FileData); if (response.ToLower() == "invalid") { Fusion.GlobalInstance.CurrentPassword = ""; Fusion.GlobalInstance.CurrentUsername = ""; return false; } else if (response.ToLower() == "valid") return true; else MessageBox.Show("Unexpected value returned from server. Please login manually.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); statusToolStripStatusLabel.Text = "Idle."; } catch (Exception) { _connectedToNet = false; } return false; } /// <summary> /// Refreshs the new tab by downloading news ite from the /// central server. /// </summary> private void RefreshNews() { // See if we can connect to the internet. FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionnews"); try { downloader.Start(); statusToolStripStatusLabel.Text = "Downloading news."; statusToolStripProgressBar.Style = ProgressBarStyle.Marquee; while (downloader.Complete == false) { if (downloader.Error != "") throw new Exception("An error occured while connecting to the server."); Application.DoEvents(); } statusToolStripProgressBar.Style = ProgressBarStyle.Continuous; statusToolStripStatusLabel.Text = "Downloaded news."; // Get the data. ASCIIEncoding encoding = new ASCIIEncoding(); string data = encoding.GetString(downloader.FileData); // Ok now parse the data. if (data.Length != 4 && data.ToLower() != "none") { XmlDocument document = new XmlDocument(); document.LoadXml(data); if (document["news"] != null) { int y = 15; for (int i = 0; i < document["news"].ChildNodes.Count; i++) { string title = document["news"].ChildNodes[i]["title"].InnerText; string author = document["news"].ChildNodes[i]["author"].InnerText; string date = document["news"].ChildNodes[i]["date"].InnerText; string body = document["news"].ChildNodes[i]["body"].InnerText; NewsItem item = new NewsItem(title, "written by " + author + " on " + date, body, recentNewsTabPage); item.NewsPanel.Location = new Point(15, y); _newsItems.Add(item); y += item.NewsPanel.Height + 15; } statusToolStripStatusLabel.Text = "Idle."; newDownloadLabel.Visible = false; } else { BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse news XML, the root node dosen't exist."); statusToolStripStatusLabel.Text = "An error occured while parsing news XML."; newDownloadLabel.Text = "Unable to download."; } } } catch (Exception) { _connectedToNet = false; } } /// <summary> /// Checks for new updates with the central server. /// </summary> private void CheckForUpdates() { // Wrok out the major / minor versions. string version = Engine.GlobalInstance.EngineConfigFile["version", "1.0"]; int radixIndex = version.IndexOf('.'); string majorVersion = radixIndex == -1 ? "1" : version.Substring(0, radixIndex); string minorVersion = radixIndex == -1 ? "0" : version.Substring(radixIndex + 1); // See if we can connect to the internet. FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionupdates&mjrver="+majorVersion+"&minver="+minorVersion); try { downloader.Start(); statusToolStripStatusLabel.Text = "Checking for updates."; statusToolStripProgressBar.Style = ProgressBarStyle.Marquee; while (downloader.Complete == false) { if (downloader.Error != "") throw new Exception("An error occured while connecting to the server."); Application.DoEvents(); } statusToolStripProgressBar.Style = ProgressBarStyle.Continuous; statusToolStripStatusLabel.Text = "Downloaded updates."; // Get the data. ASCIIEncoding encoding = new ASCIIEncoding(); string data = encoding.GetString(downloader.FileData); // Ok now parse the data. if (data.Length != 4 && data.ToLower() != "none") { try { XmlDocument document = new XmlDocument(); document.LoadXml(data); if (document["updates"] != null) { if (MessageBox.Show("There are updates available for the Fusion Game Engine, would you like to download the updates now?", "Updates Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { for (int i = 0; i < document["updates"].ChildNodes.Count; i++) { string name = document["updates"].ChildNodes[i]["name"].InnerText; string file = document["updates"].ChildNodes[i]["file"].InnerText; AddDownload(name, file, DownloadType.FusionUpdate, null); } SyncronizeWindow(); } } } catch (Exception) { BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse updates XML, the root node dosen't exist."); statusToolStripStatusLabel.Text = "An error occured while parsing updates XML."; } } statusToolStripStatusLabel.Text = "Idle."; } catch (Exception) { _connectedToNet = false; } } /// <summary> /// Downloads the games library from the central server. /// </summary> private void LoadGamesLibrary() { // Make sure we are logged in. if (Fusion.GlobalInstance.CurrentUsername == "" || Fusion.GlobalInstance.CurrentPassword == "") return; // See if we can connect to the internet. FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusiongameslist&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword)); #if RELEASE || PROFILE try { #endif downloader.Start(); gameLibraryStatusLabel.Text = "Downloading Games Library ..."; statusToolStripStatusLabel.Text = "Downloading Games Library ..."; statusToolStripProgressBar.Style = ProgressBarStyle.Marquee; while (downloader.Complete == false) { if (downloader.Error != "") throw new Exception("An error occured while connecting to the server."); Application.DoEvents(); } statusToolStripProgressBar.Style = ProgressBarStyle.Continuous; statusToolStripStatusLabel.Text = "Downloaded Games Library."; // Get the data. ASCIIEncoding encoding = new ASCIIEncoding(); string data = encoding.GetString(downloader.FileData); // Clear up. _gamesLibrary.Clear(); _gamesLibraryImageList.Images.Clear(); _gamesLibraryImageList.ColorDepth = ColorDepth.Depth32Bit; _gamesLibraryImageList.ImageSize = new Size(48, 48); // Ok now parse the data. if (data.Length != 4 && data.ToLower() != "none") { #if RELEASE || PROFILE try { #endif XmlDocument document = new XmlDocument(); document.LoadXml(data); if (document["games"] != null) { for (int i = 0; i < document["games"].ChildNodes.Count; i++) { string title = document["games"].ChildNodes[i]["title"].InnerText; string version = document["games"].ChildNodes[i]["version"].InnerText; string language = document["games"].ChildNodes[i]["language"].InnerText; string shortdescription = document["games"].ChildNodes[i]["shortdescription"].InnerText; string description = document["games"].ChildNodes[i]["description"].InnerText; string rating = document["games"].ChildNodes[i]["rating"].InnerText; string players = document["games"].ChildNodes[i]["players"].InnerText; string requirements = document["games"].ChildNodes[i]["requirements"].InnerText; string publisher = document["games"].ChildNodes[i]["publisher"].InnerText; // Download the icon. FileDownloader iconDownloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword) + "&game=" + System.Web.HttpUtility.UrlEncode(title) + "&file=0"); try { iconDownloader.Start(); while (iconDownloader.Complete == false) { if (iconDownloader.Error != "") break; // Not important enough for an error message. Application.DoEvents(); } } catch {} Stream iconDataStream = new MemoryStream(iconDownloader.FileData); Image iconImage = Image.FromStream(iconDataStream); //iconDataStream.Close(); GameDescription gameDescription = new GameDescription("", title, description, shortdescription, rating, language, requirements, players, version, publisher); gameDescription.Icon = iconImage; _gamesLibrary.Add(gameDescription); _gamesLibraryImageList.Images.Add(iconImage); } SyncronizeWindow(); statusToolStripStatusLabel.Text = "Idle."; } #if RELEASE || PROFILE } catch (Exception) { BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse game library XML, the root node dosen't exist."); statusToolStripStatusLabel.Text = "An error occured while parsing game library XML."; } #endif } #if RELEASE || PROFILE } catch (Exception) { _connectedToNet = false; } #endif // Is there an update available for any of our games? foreach (GameDescription myGameDescription in _myGames) foreach (GameDescription gamesLibraryDescription in _gamesLibrary) if (gamesLibraryDescription.Name == myGameDescription.Name && float.Parse(gamesLibraryDescription.Version) > float.Parse(myGameDescription.Version)) if (MessageBox.Show("There are updates available for "+myGameDescription.Name+", would you like to download the updates now?", "Updates Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { gamesLibraryDescription.Downloading = true; AddDownload(gamesLibraryDescription.Name + " (Version " + gamesLibraryDescription.Version + ")", "http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword) + "&game=" + System.Web.HttpUtility.UrlEncode(gamesLibraryDescription.Name) + "&file=1", DownloadType.Game, gamesLibraryDescription); } } /// <summary> /// Refreshs the games library tab. /// </summary> private void RefreshGamesLibrary() { // gameLibraryListView.Clear(); gameLibraryListView.SmallImageList = _gamesLibraryImageList; gameLibraryListView.Items.Clear(); int iconIndex = 0; foreach (GameDescription description in _gamesLibrary) { gameLibraryListView.Items.Add(new ListViewItem(new string[] { "", description.Name, description.Publisher, description.Version, description.Rating, description.ShortDescription }, iconIndex)); if (description.Icon != null) iconIndex++; } SyncronizeWindow(); } /// <summary> /// Loads in details on all games that are on the local drive. /// </summary> private void LoadMyGames() { _myGames.Clear(); _myGamesImageList.Images.Clear(); _myGamesImageList.ColorDepth = ColorDepth.Depth32Bit; _myGamesImageList.ImageSize = new Size(48, 48); string[] directories = Directory.GetDirectories(Fusion.GlobalInstance.BasePath); for (int i = 0; i < directories.Length; i++) { string gameDir = directories[i]; string gameName = gameDir.Substring(gameDir.LastIndexOf('\\') + 1); if (File.Exists(gameDir + "\\" + gameName + ".xml") == false) continue; // Grab data out of the config file. XmlConfigFile configFile = new XmlConfigFile(gameDir + "\\" + gameName + ".xml"); GameDescription description = new GameDescription(gameName, configFile["title", "Unknown"], configFile["description", "Unknown"], configFile["shortDescription", "Unknown"], configFile["rating", "Unknown"], configFile["language", "Unknown"], configFile["requirements", "Unknown"], configFile["players", "Unknown"], configFile["version", "Unknown"], configFile["publisher", "Unknown"]); // Load an icon? string icon = configFile["icon", ""]; if (icon != "" && File.Exists(gameDir + "\\" + icon)) { byte[] data = File.ReadAllBytes(gameDir + "\\" + icon); Stream iconStream = new MemoryStream(data); description.Icon = Image.FromStream(iconStream); //iconStream.Close(); _myGamesImageList.Images.Add(description.Icon); } _myGames.Add(description); } myGamesStatusLabel.Text = "You currently don't own any games."; RefreshMyGames(); } /// <summary> /// Refreshs the my games tab. /// </summary> private void RefreshMyGames() { myGamesListView.Items.Clear(); myGamesListView.SmallImageList = _myGamesImageList; int iconIndex = 0; foreach (GameDescription description in _myGames) { myGamesListView.Items.Add(new ListViewItem(new string[] {"", description.Name, description.Publisher, description.Version, description.Rating, description.ShortDescription }, iconIndex)); if (description.Icon != null) iconIndex++; } SyncronizeWindow(); } /// <summary> /// Called when the exit menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } /// <summary> /// Called when the contents menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void contentsToolStripMenuItem_Click(object sender, EventArgs e) { if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\help.chm") == false) { MessageBox.Show("Unable to locate help file, please make sure that the file \"Help.chm\" is inside the same directory as this executable.", "Unable to locate file"); return; } // Boot up the help page. Process process = new Process(); process.StartInfo.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory; process.StartInfo.FileName = "help.chm"; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); } /// <summary> /// Called when the visit website menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void visitWebsiteToolStripMenuItem_Click(object sender, EventArgs e) { // Boot up internet explorer to the binary phoenix page. Process process = new Process(); process.StartInfo.FileName = @"iexplore"; process.StartInfo.Arguments = "www.binaryphoenix.com"; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); } /// <summary> /// Called when the about menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutWindow aboutWindow = new AboutWindow(); aboutWindow.ShowDialog(this); } /// <summary> /// Called when the register account menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void registerAccountToolStripMenuItem_Click(object sender, EventArgs e) { RegisterWindow registerWindow = new RegisterWindow(); registerWindow.ShowDialog(this); SyncronizeWindow(); } /// <summary> /// Called when the lost password menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void lostPasswordToolStripMenuItem_Click(object sender, EventArgs e) { ResetPasswordWindow registerWindow = new ResetPasswordWindow(); registerWindow.ShowDialog(this); } /// <summary> /// Called when the login account menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void loginToolStripMenuItem_Click(object sender, EventArgs e) { if (Fusion.GlobalInstance.CurrentUsername == "") { LoginWindow loginWindow = new LoginWindow(); loginWindow.ShowDialog(this); LoadGamesLibrary(); RefreshGamesLibrary(); } else { Fusion.GlobalInstance.CurrentPassword = ""; Fusion.GlobalInstance.CurrentUsername = ""; } SyncronizeWindow(); } /// <summary> /// Called when the selected item in the my games list view is changed. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void myGamesListView_SelectedIndexChanged(object sender, EventArgs e) { SyncronizeWindow(); } /// <summary> /// Called when the selected item in the games library list view is changed. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void gameLibraryListView_SelectedIndexChanged(object sender, EventArgs e) { SyncronizeWindow(); } /// <summary> /// Called when the update button in the my games tab is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void myGamesUpdateButton_Click(object sender, EventArgs e) { GameDescription selectedGame = _myGames[myGamesListView.SelectedIndices[0]] as GameDescription; foreach (GameDescription game in _gamesLibrary) { if (game.Name.ToLower() == selectedGame.Name.ToLower()) { AddDownload(game.Name + " (Version " + game.Version + ")", "http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword) + "&game=" + System.Web.HttpUtility.UrlEncode(game.Name) + "&file=1", DownloadType.Game, game); return; } } SyncronizeWindow(); } /// <summary> /// Called when the play button in the my games tab is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void myGamesPlayButton_Click(object sender, EventArgs e) { if (myGamesListView.SelectedItems.Count != 0) { GameDescription selectedGame = _myGames[myGamesListView.SelectedIndices[0]] as GameDescription; Process process = new Process(); process.StartInfo.FileName = Application.ExecutablePath; process.StartInfo.Arguments = "-game:\"" + selectedGame.FolderName + "\""; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); this.WindowState = FormWindowState.Minimized; while (process.HasExited == false) { if (this.WindowState != FormWindowState.Minimized) break; Application.DoEvents(); } this.WindowState = FormWindowState.Normal; } } /// <summary> /// Called when the run editor button in the my games tab is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void myGamesEditorButton_Click(object sender, EventArgs e) { if (myGamesListView.SelectedItems.Count != 0 && File.Exists("editor.exe")) { GameDescription selectedGame = _myGames[myGamesListView.SelectedIndices[0]] as GameDescription; Process process = new Process(); process.StartInfo.FileName = "editor.exe"; process.StartInfo.Arguments = "-game:\"" + selectedGame.FolderName + "\""; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); this.WindowState = FormWindowState.Minimized; while (process.HasExited == false) { if (this.WindowState != FormWindowState.Minimized) break; Application.DoEvents(); } this.WindowState = FormWindowState.Normal; } } /// <summary> /// Called when the download button in the games library tab is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void gameLibraryDownloadButton_Click(object sender, EventArgs e) { GameDescription selectedGame = _gamesLibrary[gameLibraryListView.SelectedIndices[0]] as GameDescription; selectedGame.Downloading = true; AddDownload(selectedGame.Name + " (Version " + selectedGame.Version + ")", "http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentUsername) + "&password=" + System.Web.HttpUtility.UrlEncode(Fusion.GlobalInstance.CurrentPassword) + "&game=" + System.Web.HttpUtility.UrlEncode(selectedGame.Name) + "&file=1", DownloadType.Game, selectedGame); } /// <summary> /// Called when the download timer ticks. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void downloadTimer_Tick(object sender, EventArgs e) { downloadTimer.Enabled = false; // Disable it so that we don't recieve notifications while we are trying to proess this one. int totalTimeRemaining = 0; int totalSpeed = 0; int workingDownloads = 0; foreach (DownloadItem download in _downloads) { if (download.Downloader.Error != "") { MessageBox.Show("An error occured while downloading " + download.Downloader.URL + "\n\n\t '" + download.Downloader.Error + "'.", "Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error); download.ListViewItem.StateImageIndex = 3; download.ListViewItem.SubItems[2].Text = "Error"; download.ListViewItem.SubItems[3].Text = "Error"; download.ListViewItem.SubItems[4].Text = "Error"; continue; } else if (download.Downloader.Complete == true) { if (download.ListViewItem.StateImageIndex != 1 && download.DownloadType == DownloadType.FusionUpdate && MessageBox.Show("Updates have been downloaded, would you like to install them now?\n\nThis will require this application to restart.", "Updates Downloaded", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) download.Install(); else if (download.ListViewItem.StateImageIndex != 1 && download.ListViewItem.StateImageIndex != 3 && download.DownloadType == DownloadType.Game) { download.ListViewItem.StateImageIndex = 3; download.ListViewItem.SubItems[2].Text = "Installing"; download.ListViewItem.SubItems[3].Text = "Installing"; download.ListViewItem.SubItems[4].Text = "Installing"; download.Install(); while (download.Installing == true) Application.DoEvents(); LoadMyGames(); RefreshMyGames(); } download.ListViewItem.StateImageIndex = 1; download.ListViewItem.SubItems[2].Text = "Complete"; download.ListViewItem.SubItems[3].Text = "Complete"; download.ListViewItem.SubItems[4].Text = "Complete"; continue; } totalTimeRemaining += download.Downloader.TimeRemaining; totalSpeed += download.Downloader.AverageSpeed; workingDownloads++; int time = download.Downloader.TimeRemaining; download.ListViewItem.SubItems[2].Text = download.Downloader.AverageSpeed+"kb/s"; download.ListViewItem.SubItems[3].Text = StringMethods.SizeFromBytes(download.Downloader.Size) + " / " + StringMethods.SizeFromBytes(download.Downloader.TotalSize) + " (" + download.Downloader.Progress + "%)"; if (time > 60 * 60) download.ListViewItem.SubItems[4].Text = (time / (60 * 60)) + " hours"; else if (time > 60) download.ListViewItem.SubItems[4].Text = (time / 60) + " minutes"; else download.ListViewItem.SubItems[4].Text = time + " seconds"; } // Set the status text labels. if (workingDownloads > 0) { downloadSpeedLabel.Text = "Downloading " + workingDownloads + " files at " + (totalSpeed / workingDownloads) + " kb/s"; int approxTime = totalTimeRemaining / workingDownloads; if (approxTime > 60 * 60) downloadTimeLabel.Text = "Approximatly " + (approxTime / (60 * 60)) + " hours remaining"; else if (approxTime > 60) downloadTimeLabel.Text = "Approximatly " + (approxTime / 60) + " minutes remaining"; else downloadTimeLabel.Text = "Approximatly " + approxTime + " seconds remaining"; } else { downloadSpeedLabel.Text = ""; downloadTimeLabel.Text = ""; } downloadTimer.Enabled = true; // Allow notifications again. } /// <summary> /// Starts a new download item and adds it to the downloads page. /// </summary> /// <param name="name">Name of the download.</param> /// <param name="url">URL of file to download.</param> /// <param name="type">Type of download.</param> /// <param name="description">Game description, used in the case of game downloads.</param> private void AddDownload(string name, string url, DownloadType type, GameDescription description) { DownloadItem download = new DownloadItem(name, url, type, description); download.ListViewItem = new ListViewItem(new string[] { "", download.Name, "Unknown", "Unknown", "Unknown" }); download.ListViewItem.StateImageIndex = 0; downloadsListView.Items.Add(download.ListViewItem); _downloads.Add(download); SyncronizeWindow(); } /// <summary> /// Called when a sub item of the downloads list view needs drawing. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void downloadsListView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) { DownloadItem itemDownload = null; foreach (DownloadItem download in _downloads) if (download.ListViewItem == e.Item) { itemDownload = download; break; } if (e.ColumnIndex == 3) { int width = (int)(((e.Bounds.Width - 4) / 100.0f) * (float)itemDownload.Downloader.Progress); // Draw selection backround if necessary. if ((e.ItemState & ListViewItemStates.Selected) != 0) e.Graphics.FillRectangle(SystemBrushes.Highlight, new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)); e.Graphics.DrawRectangle(new Pen(Color.Gray), new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 3, e.Bounds.Height - 3)); e.Graphics.FillRectangle(Brushes.LightGray, new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, e.Bounds.Width - 4, e.Bounds.Height - 4)); e.Graphics.FillRectangle(Brushes.LightGreen, new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, width, e.Bounds.Height - 4)); StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Center; format.Alignment = StringAlignment.Center; e.Graphics.DrawString(e.SubItem.Text, SystemFonts.MessageBoxFont, Brushes.Black, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), format); } else e.DrawDefault = true; } /// <summary> /// Called when a header of the downloads list view needs drawing. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void downloadsListView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) { e.DrawDefault = true; } /// <summary> /// Retrieves the currently selected download item on the downloads tab. /// </summary> /// <returns>Currently selected download item.</returns> private DownloadItem GetSelectedDownload() { if (downloadsListView.SelectedItems.Count > 0) foreach (DownloadItem download in _downloads) if (download.ListViewItem == downloadsListView.SelectedItems[0]) return download; return null; } /// <summary> /// Called when the selected item of the downloads list view is changed. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void downloadsListView_SelectedIndexChanged(object sender, EventArgs e) { DownloadItem selectedDownload = GetSelectedDownload(); stopDownloadsButton.Enabled = (selectedDownload != null && selectedDownload.Downloader.Complete == false); if (selectedDownload != null) { if (selectedDownload.Downloader.Complete == false) { if (selectedDownload.Downloader.Paused == true) { pauseDownloadsButton.Enabled = true; pauseDownloadsButton.Text = "Resume"; pauseDownloadsButton.ImageIndex = 3; } else { pauseDownloadsButton.Enabled = true; pauseDownloadsButton.Text = "Pause"; pauseDownloadsButton.ImageIndex = 2; } } else { pauseDownloadsButton.Enabled = false; } if (selectedDownload.DownloadType == DownloadType.FusionUpdate && selectedDownload.Downloader.Complete == true) installDownloadsButton.Enabled = true; } else { pauseDownloadsButton.Enabled = false; installDownloadsButton.Enabled = false; } } /// <summary> /// Called when the stop download button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void stopDownloadsButton_Click(object sender, EventArgs e) { DownloadItem downloadItem = GetSelectedDownload(); if (downloadItem != null && MessageBox.Show("Are you sure you wish to stop this download? This action is irreversible and any downloaded data will be lost.", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { downloadItem.Downloader.Abort(); downloadItem.Downloader = null; downloadsListView.Items.Remove(downloadItem.ListViewItem); downloadItem.ListViewItem = null; _downloads.Remove(downloadItem); } } /// <summary> /// Called when the pause download button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void pauseDownloadsButton_Click(object sender, EventArgs e) { DownloadItem downloadItem = GetSelectedDownload(); if (downloadItem != null) { downloadItem.Downloader.Paused = !downloadItem.Downloader.Paused; if (downloadItem.Downloader.Paused == true) { pauseDownloadsButton.Enabled = true; pauseDownloadsButton.Text = "Resume"; pauseDownloadsButton.ImageIndex = 3; } else { pauseDownloadsButton.Enabled = true; pauseDownloadsButton.Text = "Pause"; pauseDownloadsButton.ImageIndex = 2; } } } /// <summary> /// Called when the install download button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void installDownloadsButton_Click(object sender, EventArgs e) { DownloadItem download = GetSelectedDownload(); download.Install(); } /// <summary> /// Called when the check for updates menu ite is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e) { _connectedToNet = true; CheckForUpdates(); } /// <summary> /// Called wehn the visit website menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void visitToolStripStatusLabel_Click(object sender, EventArgs e) { // Boot up internet explorer to the binary phoenix page. Process process = new Process(); process.StartInfo.FileName = @"iexplore"; process.StartInfo.Arguments = "www.binaryphoenix.com"; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); } /// <summary> /// Called when the refresh news menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void refreshNewsToolStripMenuItem_Click(object sender, EventArgs e) { _connectedToNet = true; RefreshNews(); } /// <summary> /// Called when the refresh games library menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void refreshGamesLibraryToolStripMenuItem_Click(object sender, EventArgs e) { _connectedToNet = true; LoadGamesLibrary(); RefreshGamesLibrary(); } /// <summary> /// Called wehn the refresh my gaes menu item is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void refreshMyGamesToolStripMenuItem_Click(object sender, EventArgs e) { _connectedToNet = true; LoadMyGames(); RefreshMyGames(); } /// <summary> /// Called when the user attempts to close the window. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void GamesExplorerWindow_FormClosing(object sender, FormClosingEventArgs e) { foreach (DownloadItem download in _downloads) { if (download.Downloader.Complete == false && download.Downloader.Error == "") { if (MessageBox.Show("You are currently downloading one or more files. If you quit now those downloads will be canceled.\n\nAre you sure you wish to quit?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { return; } else { e.Cancel = true; return; } } } } #endregion } /// <summary> /// This enum describes what a download item is downloading. /// </summary> public enum DownloadType { Game, FusionUpdate } /// <summary> /// This class describes a currently downloading file. /// </summary> public class DownloadItem { #region Members #region Variables private string _name; private FileDownloader _downloader; private ListViewItem _listViewItem; private DownloadType _downloadType; private Thread _installGameThread = null; private GameDescription _gameDescription = null; #endregion #region Properties /// <summary> /// Gets or sets the name of this download. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets or sets the file downloader instance associated with this download. /// </summary> public FileDownloader Downloader { get { return _downloader; } set { _downloader = value; } } /// <summary> /// Gets or sets the list view item that this download is being displayed with. /// </summary> public ListViewItem ListViewItem { get { return _listViewItem; } set { _listViewItem = value; } } /// <summary> /// Gets or sets the type of item that is being downloaded. /// </summary> public DownloadType DownloadType { get { return _downloadType; } set { _downloadType = value; } } /// <summary> /// Returns if this download is being installed. /// </summary> public bool Installing { get { return _installGameThread != null; } } /// <summary> /// Gets or sets the description of the game being downloaded. /// </summary> public GameDescription GameDescription { get { return _gameDescription; } set { _gameDescription = value; } } #endregion #endregion #region Methods /// <summary> /// Installs this download. /// </summary> public void Install() { Runtime.Debug.DebugLogger.WriteLog("Installing \"" + _name + "\"..."); if (_downloadType == DownloadType.FusionUpdate) { // DO update here! Stream stream = StreamFactory.RequestStream(Fusion.GlobalInstance.DownloadPath + "\\" + Path.GetFileName(_downloader.URL), StreamMode.Truncate); stream.Write(_downloader.FileData, 0, _downloader.FileData.Length); stream.Close(); if (File.Exists("Updater.exe") == false) { MessageBox.Show("Unable to locate updater file, please make sure that the file \"Updater.exe\" is inside the same directory as this executable.", "Unable to locate file"); return; } else { Process process = new Process(); process.StartInfo.FileName = "Updater.exe"; process.StartInfo.Arguments = "-file:\"" + Fusion.GlobalInstance.DownloadPath + "\\" + Path.GetFileName(_downloader.URL) + "\" -finishfile:\"Fusion.exe\""; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; process.Start(); Application.Exit(); } } else if (_downloadType == DownloadType.Game) { _installGameThread = new Thread(InstallGameThread); _installGameThread.IsBackground = true; _installGameThread.Start(); } } /// <summary> /// Used as the entry point for the installation thread. /// </summary> private void InstallGameThread() { // Dump it to a file. Stream stream = StreamFactory.RequestStream(Fusion.GlobalInstance.DownloadPath + "\\" + _gameDescription.Name + ".pk", StreamMode.Truncate); stream.Write(_downloader.FileData, 0, _downloader.FileData.Length); stream.Close(); // Load the pak file. PakFile pakFile = new PakFile(Fusion.GlobalInstance.DownloadPath + "\\" + _gameDescription.Name + ".pk"); // Create a folder to dump the files into. string gameFolder = Fusion.GlobalInstance.BasePath + "\\" + _gameDescription.Name; if (!Directory.Exists(gameFolder)) Directory.CreateDirectory(Fusion.GlobalInstance.BasePath + "\\" + _gameDescription.Name); // Output to the correct folder. foreach (PakResource resource in pakFile.Resources) { if (!Directory.Exists(gameFolder + "\\" + Path.GetDirectoryName(resource.URL as string))) Directory.CreateDirectory(gameFolder + "\\" + Path.GetDirectoryName(resource.URL as string)); Runtime.Debug.DebugLogger.WriteLog("Unpacking \""+(resource.URL as string)+"\"..."); Stream resourceStream = resource.RequestResourceStream(); Stream resourceFileStream = StreamFactory.RequestStream(gameFolder + "\\" + resource.URL, StreamMode.Truncate); byte[] data = new byte[resourceStream.Length]; resourceStream.Read(data, 0, (int)resourceStream.Length); resourceFileStream.Write(data, 0, data.Length); resourceFileStream.Close(); resourceStream.Close(); } _installGameThread = null; } /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="name">Name of file to download.</param> /// <param name="url">URL of file to download.</param> /// <param name="type">Type of file being downloaded.</param> /// <param name="description">Description of game being downloaded.</param> public DownloadItem(string name, string url, DownloadType type, GameDescription description) { _name = name; _gameDescription = description; _downloadType = type; _downloader = new FileDownloader(url); _downloader.Start(); } #endregion } /// <summary> /// This class describes a game that is shown in either the games library or /// my games tab. /// </summary> public class GameDescription { #region Members #region Variables private string _name; private string _description, _shortDescription; private string _rating; private string _language; private string _requirements; private string _players; private string _version; private string _publisher; private string _folderName; private Image _icon; private bool _downloading; #endregion #region Properties /// <summary> /// Gets or sets the icon associated with this game. /// </summary> public Image Icon { get { return _icon; } set { _icon = value; } } /// <summary> /// Gets or sets if this game is being downloaded. /// </summary> public bool Downloading { get { return _downloading; } set { _downloading = value; } } /// <summary> /// Gets or sets the name of this game. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets or sets the name of the folder this game is stored in. /// </summary> public string FolderName { get { return _folderName; } set { _folderName = value; } } /// <summary> /// Gets or sets the description of this game. /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Gets or sets the short description of this game. /// </summary> public string ShortDescription { get { return _shortDescription; } set { _shortDescription = value; } } /// <summary> /// Gets or sets the publisher of this game. /// </summary> public string Publisher { get { return _publisher; } set { _publisher = value; } } /// <summary> /// Gets or sets the age rating of this game. /// </summary> public string Rating { get { return _rating; } set { _rating = value; } } /// <summary> /// Gets or sets the language of this game. /// </summary> public string Language { get { return _language; } set { _language = value; } } /// <summary> /// Gets or sets the requirements of this game. /// </summary> public string Requirements { get { return _requirements; } set { _requirements = value; } } /// <summary> /// Gets or sets the player count of this game. /// </summary> public string Players { get { return _players; } set { _players = value; } } /// <summary> /// Gets or sets the current version of this game. /// </summary> public string Version { get { return _version; } set { _version = value; } } #endregion #endregion #region Methods /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="folderName">Name of folder this game is stored in.</param> /// <param name="name">Nae of this game.</param> /// <param name="description">Description of this game.</param> /// <param name="shortDescription">Short description of this game.</param> /// <param name="rating">Age rating of this game.</param> /// <param name="language">Language of this game.</param> /// <param name="requirements">Requirements of this game.</param> /// <param name="players">Player count for this game.</param> /// <param name="version">Version of this game.</param> /// <param name="publisher">Publisher of this game.</param> public GameDescription(string folderName, string name, string description, string shortDescription, string rating, string language, string requirements, string players, string version, string publisher) { _folderName = folderName; _name = name; _description = description; _shortDescription = shortDescription; _rating = rating; _language = language; _requirements = requirements; _players = players; _version = version; _publisher = publisher; } #endregion } /// <summary> /// This class describes a news item that has been downloaded from the central /// server and is being displayed in the recent news tab. /// </summary> public class NewsItem { #region Members #region Variables private Control _parent = null; private Panel _newsPanel; private Label _titleLabel, _nameLabel; private RichTextBox _bodyBox = null; private string _title, _name, _body; #endregion #region Properties /// <summary> /// Gets or sets the panel this news item is being displayed on. /// </summary> public Panel NewsPanel { get { return _newsPanel; } } #endregion #endregion #region Methods /// <summary> /// Sets up the panel this news item is being displayed on. /// </summary> private void SetupPanel() { _titleLabel = new Label(); _titleLabel.Parent = _newsPanel; _titleLabel.Text = _title; _titleLabel.AutoSize = false; _titleLabel.Location = new Point(22, 22); _titleLabel.Size = new Size(_parent.ClientRectangle.Width - 30 - 44, 25); _titleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); _nameLabel = new Label(); _nameLabel.Parent = _newsPanel; _nameLabel.Text = _name; _nameLabel.AutoSize = false; _nameLabel.Location = new Point(24, 47); _nameLabel.Size = new Size(_parent.ClientRectangle.Width - 30 - 44, 25); _nameLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); _bodyBox = new RichTextBox(); _bodyBox.ReadOnly = true; _bodyBox.Parent = _newsPanel; _bodyBox.Text = _body; _bodyBox.BackColor = Color.White; _bodyBox.BorderStyle = BorderStyle.None; _bodyBox.Location = new Point(22, 76); _bodyBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); _bodyBox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom; _bodyBox.Size = new Size(_parent.ClientRectangle.Width - 30 - 44, 100); int height = 44 + _titleLabel.Font.Height + _nameLabel.Font.Height + 110; _newsPanel = new Panel(); _newsPanel.Parent = _parent; _parent.Controls.Add(_newsPanel); _newsPanel.Location = new Point(15, 25); _newsPanel.Size = new Size(_parent.ClientRectangle.Width - 30, height); _newsPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); _newsPanel.BackColor = System.Drawing.SystemColors.ControlLightLight; _newsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; _newsPanel.Controls.Add(_titleLabel); _newsPanel.Controls.Add(_nameLabel); _newsPanel.Controls.Add(_bodyBox); } /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="title">Title of this news item,</param> /// <param name="name">Name of this news item.</param> /// <param name="body">Body of this news item.</param> /// <param name="parent">Parent control of this news item.</param> public NewsItem(string title, string name, string body, Control parent) { _title = title; _parent = parent; _name = name; _body = body; SetupPanel(); } #endregion } }
gpl-3.0
julianwachholz/wmask
vendor/whammy.js
15978
/** * https://github.com/antimatter15/whammy/blob/a1c8e861a3269387ffac519fe6e96c645efb6686/whammy.js * * modified to have a progress callback */ /* var vid = new Whammy.Video(); vid.add(canvas or data url) vid.compile() */ window.Whammy = (function(){ // in this case, frames has a very specific meaning, which will be // detailed once i finish writing the code function toWebM(frames, outputAsArray){ var info = checkFrames(frames); //max duration by cluster in milliseconds var CLUSTER_MAX_DURATION = 30000; var EBML = [ { "id": 0x1a45dfa3, // EBML "data": [ { "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion } ] }, { "id": 0x18538067, // Segment "data": [ { "id": 0x1549a966, // Info "data": [ { "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration } ] }, { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x73c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [ { "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight } ] } ] } ] }, { "id": 0x1c53bb6b, // Cues "data": [ //cue insertion point ] } //cluster insertion point ] } ]; var segment = EBML[1]; var cues = segment.data[2]; //Generate clusters (max duration) var frameNumber = 0; var clusterTimecode = 0; while(frameNumber < frames.length){ var cuePoint = { "id": 0xbb, // CuePoint "data": [ { "data": Math.round(clusterTimecode), "id": 0xb3 // CueTime }, { "id": 0xb7, // CueTrackPositions "data": [ { "data": 1, "id": 0xf7 // CueTrack }, { "data": 0, // to be filled in when we know it "size": 8, "id": 0xf1 // CueClusterPosition } ] } ] }; cues.data.push(cuePoint); var clusterFrames = []; var clusterDuration = 0; do { clusterFrames.push(frames[frameNumber]); clusterDuration += frames[frameNumber].duration; frameNumber++; }while(frameNumber < frames.length && clusterDuration < CLUSTER_MAX_DURATION); var clusterCounter = 0; var cluster = { "id": 0x1f43b675, // Cluster "data": [ { "data": Math.round(clusterTimecode), "id": 0xe7 // Timecode } ].concat(clusterFrames.map(function(webp){ var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(clusterCounter) }); clusterCounter += webp.duration; return { data: block, id: 0xa3 }; })) } //Add cluster to segment segment.data.push(cluster); clusterTimecode += clusterDuration; } //First pass to compute cluster positions var position = 0; for(var i = 0; i < segment.data.length; i++){ if (i >= 3) { cues.data[i-3].data[1].data[1].data = position; } var data = generateEBML([segment.data[i]], outputAsArray); position += data.size || data.byteLength || data.length; if (i != 2) { // not cues //Save results to avoid having to encode everything twice segment.data[i] = data; } } return generateEBML(EBML, outputAsArray) } // sums the lengths of all the frames and gets the duration, woo function checkFrames(frames){ var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for(var i = 1; i < frames.length; i++){ if(frames[i].width != width) throw "Frame " + (i + 1) + " has a different width"; if(frames[i].height != height) throw "Frame " + (i + 1) + " has a different height"; if(frames[i].duration < 0 || frames[i].duration > 0x7fff) throw "Frame " + (i + 1) + " has a weird duration (must be between 0 and 32767)"; duration += frames[i].duration; } return { duration: duration, width: width, height: height }; } function numToBuffer(num){ var parts = []; while(num > 0){ parts.push(num & 0xff) num = num >> 8 } return new Uint8Array(parts.reverse()); } function numToFixedBuffer(num, size){ var parts = new Uint8Array(size); for(var i = size - 1; i >= 0; i--){ parts[i] = num & 0xff; num = num >> 8; } return parts; } function strToBuffer(str){ // return new Blob([str]); var arr = new Uint8Array(str.length); for(var i = 0; i < str.length; i++){ arr[i] = str.charCodeAt(i) } return arr; // this is slower // return new Uint8Array(str.split('').map(function(e){ // return e.charCodeAt(0) // })) } //sorry this is ugly, and sort of hard to understand exactly why this was done // at all really, but the reason is that there's some code below that i dont really // feel like understanding, and this is easier than using my brain. function bitsToBuffer(bits){ var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for(var i = 0; i < bits.length; i+= 8){ data.push(parseInt(bits.substr(i,8),2)) } return new Uint8Array(data); } function generateEBML(json, outputAsArray){ var ebml = []; for(var i = 0; i < json.length; i++){ if (!('id' in json[i])){ //already encoded blob or byteArray ebml.push(json[i]); continue; } var data = json[i].data; if(typeof data == 'object') data = generateEBML(data, outputAsArray); if(typeof data == 'number') data = ('size' in json[i]) ? numToFixedBuffer(data, json[i].size) : bitsToBuffer(data.toString(2)); if(typeof data == 'string') data = strToBuffer(data); if(data.length){ var z = z; } var len = data.size || data.byteLength || data.length; var zeroes = Math.ceil(Math.ceil(Math.log(len)/Math.log(2))/8); var size_str = len.toString(2); var padded = (new Array((zeroes * 7 + 7 + 1) - size_str.length)).join('0') + size_str; var size = (new Array(zeroes)).join('0') + '1' + padded; //i actually dont quite understand what went on up there, so I'm not really //going to fix this, i'm probably just going to write some hacky thing which //converts that string into a buffer-esque thing ebml.push(numToBuffer(json[i].id)); ebml.push(bitsToBuffer(size)); ebml.push(data) } //output as blob or byteArray if(outputAsArray){ //convert ebml to an array var buffer = toFlatArray(ebml) return new Uint8Array(buffer); }else{ return new Blob(ebml, {type: "video/webm"}); } } function toFlatArray(arr, outBuffer){ if(outBuffer == null){ outBuffer = []; } for(var i = 0; i < arr.length; i++){ if(typeof arr[i] == 'object'){ //an array toFlatArray(arr[i], outBuffer) }else{ //a simple element outBuffer.push(arr[i]); } } return outBuffer; } //OKAY, so the following two functions are the string-based old stuff, the reason they're //still sort of in here, is that they're actually faster than the new blob stuff because //getAsFile isn't widely implemented, or at least, it doesn't work in chrome, which is the // only browser which supports get as webp //Converting between a string of 0010101001's and binary back and forth is probably inefficient //TODO: get rid of this function function toBinStr_old(bits){ var data = ''; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for(var i = 0; i < bits.length; i+= 8){ data += String.fromCharCode(parseInt(bits.substr(i,8),2)) } return data; } function generateEBML_old(json){ var ebml = ''; for(var i = 0; i < json.length; i++){ var data = json[i].data; if(typeof data == 'object') data = generateEBML_old(data); if(typeof data == 'number') data = toBinStr_old(data.toString(2)); var len = data.length; var zeroes = Math.ceil(Math.ceil(Math.log(len)/Math.log(2))/8); var size_str = len.toString(2); var padded = (new Array((zeroes * 7 + 7 + 1) - size_str.length)).join('0') + size_str; var size = (new Array(zeroes)).join('0') + '1' + padded; ebml += toBinStr_old(json[i].id.toString(2)) + toBinStr_old(size) + data; } return ebml; } //woot, a function that's actually written for this project! //this parses some json markup and makes it into that binary magic //which can then get shoved into the matroska comtainer (peaceably) function makeSimpleBlock(data){ var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e){ return String.fromCharCode(e) }).join('') + data.frame; return out; } // here's something else taken verbatim from weppy, awesome rite? function parseWebP(riff){ var VP8 = riff.RIFF[0].WEBP[0]; var frame_start = VP8.indexOf('\x9d\x01\x2a'); //A VP8 keyframe starts with the 0x9d012a header for(var i = 0, c = []; i < 4; i++) c[i] = VP8.charCodeAt(frame_start + 3 + i); var width, horizontal_scale, height, vertical_scale, tmp; //the code below is literally copied verbatim from the bitstream spec tmp = (c[1] << 8) | c[0]; width = tmp & 0x3FFF; horizontal_scale = tmp >> 14; tmp = (c[3] << 8) | c[2]; height = tmp & 0x3FFF; vertical_scale = tmp >> 14; return { width: width, height: height, data: VP8, riff: riff } } // i think i'm going off on a riff by pretending this is some known // idiom which i'm making a casual and brilliant pun about, but since // i can't find anything on google which conforms to this idiomatic // usage, I'm assuming this is just a consequence of some psychotic // break which makes me make up puns. well, enough riff-raff (aha a // rescue of sorts), this function was ripped wholesale from weppy function parseRIFF(string){ var offset = 0; var chunks = {}; while (offset < string.length) { var id = string.substr(offset, 4); chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i){ var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded }).join(''),2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id].push(parseRIFF(data)); } else if (id == 'WEBP') { // Use (offset + 8) to skip past "VP8 "/"VP8L"/"VP8X" field after "WEBP" chunks[id].push(string.substr(offset + 8)); offset = string.length; } else { // Unknown chunk type; push entire payload chunks[id].push(string.substr(offset + 4)); offset = string.length; } } return chunks; } // here's a little utility function that acts as a utility for other functions // basically, the only purpose is for encoding "Duration", which is encoded as // a double (considerably more difficult to encode than an integer) function doubleToString(num){ return [].slice.call( new Uint8Array( ( new Float64Array([num]) //create a float64 array ).buffer) //extract the array buffer , 0) // convert the Uint8Array into a regular array .map(function(e){ //since it's a regular array, we can now use map return String.fromCharCode(e) // encode all the bytes individually }) .reverse() //correct the byte endianness (assume it's little endian for now) .join('') // join the bytes in holy matrimony as a string } function WhammyVideo(speed, quality){ // a more abstract-ish API this.frames = []; this.duration = 1000 / speed; this.quality = quality || 0.8; } WhammyVideo.prototype.add = function(frame, duration){ if(typeof duration != 'undefined' && this.duration) throw "you can't pass a duration if the fps is set"; if(typeof duration == 'undefined' && !this.duration) throw "if you don't have the fps set, you need to have durations here."; if(frame.canvas){ //CanvasRenderingContext2D frame = frame.canvas; } if(frame.toDataURL){ // frame = frame.toDataURL('image/webp', this.quality); // quickly store image data so we don't block cpu. encode in compile method. frame = frame.getContext('2d').getImageData(0, 0, frame.width, frame.height); }else if(typeof frame != "string"){ throw "frame must be a a HTMLCanvasElement, a CanvasRenderingContext2D or a DataURI formatted string" } if (typeof frame === "string" && !(/^data:image\/webp;base64,/ig).test(frame)) { throw "Input must be formatted properly as a base64 encoded DataURI of type image/webp"; } this.frames.push({ image: frame, duration: duration || this.duration }); }; // deferred webp encoding. Draws image data to canvas, then encodes as dataUrl WhammyVideo.prototype.encodeFrames = function(callback, progress){ if(this.frames[0].image instanceof ImageData){ var frames = this.frames; var tmpCanvas = document.createElement('canvas'); var tmpContext = tmpCanvas.getContext('2d'); tmpCanvas.width = this.frames[0].image.width; tmpCanvas.height = this.frames[0].image.height; var encodeFrame = function(index){ console.log('encodeFrame', index); if (progress !== undefined) { setTimeout(function () { progress(index); }, 1); } var frame = frames[index]; tmpContext.putImageData(frame.image, 0, 0); frame.image = tmpCanvas.toDataURL('image/webp', this.quality); if(index < frames.length-1){ setTimeout(function(){ encodeFrame(index + 1); }, 1); }else{ callback(); } }.bind(this); encodeFrame(0); }else{ callback(); } }; WhammyVideo.prototype.compile = function(outputAsArray, callback, progress){ this.encodeFrames(function(){ var webm = new toWebM(this.frames.map(function(frame){ var webp = parseWebP(parseRIFF(atob(frame.image.slice(23)))); webp.duration = frame.duration; return webp; }), outputAsArray); callback(webm); }.bind(this), progress); }; return { Video: WhammyVideo, fromImageArray: function(images, fps, outputAsArray){ return toWebM(images.map(function(image){ var webp = parseWebP(parseRIFF(atob(image.slice(23)))) webp.duration = 1000 / fps; return webp; }), outputAsArray) }, toWebM: toWebM // expose methods of madness } })()
gpl-3.0
ryanl/go-ai
src/interface_gtp/go_callbacks/callbacks.cpp
5373
#include "../go_gtp_interface.hpp" /* boardsize */ GTPResponse GTPCallbackBoardsize::callback(const std::vector<std::string>& args) { if (args.size() != 1 || !isInt(args[0])) { return GTPResponse(GTP_FAILURE, "syntax error # board_size takes one integer argument"); } else { int i = stringToInt(args[0].c_str()); return parent->boardsize(i); } } /* clear_board */ GTPResponse GTPCallbackClearBoard::callback(const std::vector<std::string>& args) { if (args.size() != 0) { return GTPResponse(GTP_FAILURE, "syntax error # clear_board takes no arguments"); } else { return parent->clear_board(); } } /* showboard */ GTPResponse GTPCallbackShowboard::callback(const std::vector<std::string>& args) { if (args.size() != 0) { return GTPResponse(GTP_FAILURE, "syntax error # showboard takes no arguments"); } else { return parent->showboard(); } } /* komi */ GTPResponse GTPCallbackKomi::callback(const std::vector<std::string>& args) { if (args.size() != 1 || !isFloat(args[0])) { return GTPResponse(GTP_FAILURE, "invalid syntax # komi takes one float argument"); } else { double f = stringToFloat(args[0].c_str()); return parent->komi(f); } } /* play */ GTPResponse GTPCallbackPlay::callback(const std::vector<std::string>& args) { if (args.size() != 2) { return GTPResponse(GTP_FAILURE, "invalid syntax # play takes colour and position as arguments"); } else { int colour = stringToBlackWhite(args[0]); if (colour == EMPTY) { return GTPResponse(GTP_FAILURE, "invalid syntax # colour argument should be 'black' or 'white' (or 'b' or 'w')"); } GoMove move = stringToMove(args[1]); if (move.isNone()) { return GTPResponse(GTP_FAILURE, "invalid syntax # bad position format"); } return parent->play(colour, move); } } /* genmove */ GTPResponse GTPCallbackGenmove::callback(const std::vector<std::string>& args) { if (args.size() == 1 || args.size() == 2) { int colour = stringToBlackWhite(args[0]); if (colour == EMPTY) { return GTPResponse(GTP_FAILURE, "invalid syntax # colour argument should be 'black' or 'white' (or 'b' or 'w')"); } else { if (args.size() == 2) { if (args[1] == "verbose") { return parent->genmove(colour, true); } else { return GTPResponse(GTP_FAILURE, "invalid syntax # genmove takes a colour as its argument"); } } else { return parent->genmove(colour); } } } else { return GTPResponse(GTP_FAILURE, "invalid syntax # genmove takes a colour as its argument"); } } /* final_score */ GTPResponse GTPCallbackFinalScore::callback(const std::vector<std::string>& args) { if (args.size() != 0) { return GTPResponse(GTP_FAILURE, "invalid syntax # final_score takes no arguments"); } else { return parent->final_score(); } } /* time_left */ GTPResponse GTPCallbackTimeLeft::callback(const std::vector<std::string>& args) { if (args.size() != 3) { return GTPResponse(GTP_FAILURE, "invalid syntax # time_left takes three arguments"); } else { int colour = stringToBlackWhite(args[0]); if (colour == EMPTY) { return GTPResponse(GTP_FAILURE, "invalid syntax # colour argument should be 'black' or 'white' (or 'b' or 'w')"); } if (!isInt(args[1]) || !isInt(args[2])) { return GTPResponse(GTP_FAILURE, "invalid syntax # second and third arguments should be integers"); } int time = stringToInt(args[1]); int stones = stringToInt(args[2]); return parent->time_left(colour, time, stones); } } /* time_settings */ GTPResponse GTPCallbackTimeSettings::callback(const std::vector<std::string>& args) { if (args.size() != 3 || !isInt(args[0]) || !isInt(args[1]) || !isInt(args[2])) { return GTPResponse(GTP_FAILURE, "invalid syntax # time_settings takes three integer arguments"); } else { int main_time = stringToInt(args[0]); int byo_yomi_time = stringToInt(args[1]); int byo_yomi_stones = stringToInt(args[2]); return parent->time_settings(main_time, byo_yomi_time, byo_yomi_stones); } } /* quit */ GTPResponse GTPCallbackQuit::callback(const std::vector<std::string>& args) { if (args.size() != 0) { return GTPResponse(GTP_FAILURE, "invalid syntax # quit takes no arguments"); } else { return parent->quit(); } } /* cputime */ // the only program I know of that uses this is gogui-regress GTPResponse GTPCallbackCputime::callback(const std::vector<std::string>& args) { if (args.size() != 0) { return GTPResponse(GTP_FAILURE, "invalid syntax # quit takes no arguments"); } else { return parent->cputime(); } } /* loadsgf */ /* GTPResponse GTPCallbackLoadSGF::callback(const std::vector<std::string>& args) { if (args.size() != 2 || !isInt(args[1])) { return GTPResponse(GTP_FAILURE, "invalid syntax # loadsgf takes two arguments: file name and move number"); } else { return parent->loadsgf(args[0], stringToInt(args[1])); } } */
gpl-3.0
BizarreCake/Arane
src/linker/executable.cpp
806
/* * Arane - A Perl 6 interpreter. * Copyright (C) 2014 Jacob Zhitomirsky * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "linker/executable.hpp" #include <cstring> namespace arane { }
gpl-3.0
V8CH/rice-paper
parts/loop-archive.php
1407
<article id="post-<?php the_ID(); ?>" <?php post_class(''); ?> role="article"> <header class="article-header"> <h5 class="kicker"> <span class="badge"><span class="fa fa-star"></span></span> <span class="kicker-title">Featured</span> </h5> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <?php get_template_part( 'parts/content', 'byline' ); ?> </header> <!-- end article header --> <section class="entry-content" itemprop="articleBody"> <a href="<?php the_permalink() ?>"><?php the_post_thumbnail(); ?></a> <?php the_content('<span class="badge"><span class="fa fa-chevron-right"></span><span class="fa fa-chevron-right"></span></span>' . __( 'Read more', 'jointswp' )); ?> </section> <!-- end article section --> <footer class="article-footer"> <span class="categories">Posted in: <?php the_category( ', ' ); ?></span> <?php $link = get_comments_link(); $zero = '<a href="' . $link . '"><span class="badge">0</span> Comments</a>'; $one = '<a href="' . $link . '"><span class="badge">1</span> Comment</a>'; $multiple = '<a href="' . $link . '"><span class="badge">%</span> Comments</a>'; ?> <span class="comment-stats"><?php comments_number( $zero, $one, $multiple );?></span></p> </footer> <!-- end article footer --> </article> <!-- end article -->
gpl-3.0
dsalazarr/pfc_ii
pfc/pfc/applications/apps.py
331
from __future__ import unicode_literals from django.apps import AppConfig class ApplicationsConfig(AppConfig): name = 'pfc.applications' verbose_name = 'Applications' def ready(self): """Override this to put in: Users system checks Users signal registration """ pass
gpl-3.0
wfjm/w11
tools/src/librlink/RlinkChannel.cpp
2022
// $Id: RlinkChannel.cpp 1186 2019-07-12 17:49:59Z mueller $ // SPDX-License-Identifier: GPL-3.0-or-later // Copyright 2013-2018 by Walter F.J. Mueller <W.F.J.Mueller@gsi.de> // // Revision History: // Date Rev Version Comment // 2018-12-07 1078 1.0.2 use std::shared_ptr instead of boost // 2017-04-07 868 1.0.1 Dump(): add detail arg // 2013-02-23 492 1.0 Initial version // --------------------------------------------------------------------------- /*! \brief Implemenation of class RlinkChannel. */ #include "librtools/RosFill.hpp" #include "librtools/RosPrintf.hpp" #include "librtools/RosPrintBvi.hpp" #include "librtools/Rexception.hpp" #include "RlinkChannel.hpp" using namespace std; /*! \class Retro::RlinkChannel \brief FIXME_docs */ // all method definitions in namespace Retro namespace Retro { //------------------------------------------+----------------------------------- //! Default constructor RlinkChannel::RlinkChannel(const std::shared_ptr<RlinkConnect>& spconn) : fContext(), fspConn(spconn) {} //------------------------------------------+----------------------------------- //! Destructor RlinkChannel::~RlinkChannel() {} //------------------------------------------+----------------------------------- //! FIXME_docs bool RlinkChannel::Exec(RlinkCommandList& clist, RerrMsg& emsg) { if (!fspConn) throw Rexception("RlinkChannel::Exec", "Bad state: fspConn == 0"); return fspConn->Exec(clist, emsg); } //------------------------------------------+----------------------------------- //! FIXME_docs void RlinkChannel::Dump(std::ostream& os, int ind, const char* text, int /*detail*/) const { RosFill bl(ind); os << bl << (text?text:"--") << "RlinkChannel @ " << this << endl; fContext.Dump(os, ind+2, "fContext: "); if (fspConn) { fspConn->Dump(os, ind+2, "fspConn: "); } else { os << bl << " fspConn: " << fspConn.get() << endl; } return; } } // end namespace Retro
gpl-3.0
WhisperSystems/TextSecure
app/src/main/java/org/thoughtcrime/securesms/service/webrtc/WebRtcActionProcessor.java
43101
package org.thoughtcrime.securesms.service.webrtc; import android.content.Context; import android.content.Intent; import android.os.ResultReceiver; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.signal.ringrtc.CallException; import org.signal.ringrtc.CallId; import org.signal.ringrtc.GroupCall; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.events.CallParticipant; import org.thoughtcrime.securesms.events.WebRtcViewModel; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.recipients.RecipientUtil; import org.thoughtcrime.securesms.ringrtc.CallState; import org.thoughtcrime.securesms.ringrtc.CameraState; import org.thoughtcrime.securesms.ringrtc.IceCandidateParcel; import org.thoughtcrime.securesms.ringrtc.RemotePeer; import org.thoughtcrime.securesms.service.webrtc.WebRtcData.CallMetadata; import org.thoughtcrime.securesms.service.webrtc.WebRtcData.GroupCallUpdateMetadata; import org.thoughtcrime.securesms.service.webrtc.WebRtcData.HttpData; import org.thoughtcrime.securesms.service.webrtc.WebRtcData.OfferMetadata; import org.thoughtcrime.securesms.service.webrtc.WebRtcData.ReceivedOfferMetadata; import org.thoughtcrime.securesms.service.webrtc.state.WebRtcServiceState; import org.thoughtcrime.securesms.service.webrtc.state.WebRtcServiceStateBuilder; import org.thoughtcrime.securesms.util.TelephonyUtil; import org.thoughtcrime.securesms.webrtc.locks.LockManager; import org.webrtc.PeerConnection; import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.InvalidKeyException; import org.whispersystems.libsignal.util.guava.Optional; import org.whispersystems.signalservice.api.messages.calls.BusyMessage; import org.whispersystems.signalservice.api.messages.calls.HangupMessage; import org.whispersystems.signalservice.api.messages.calls.OfferMessage; import org.whispersystems.signalservice.api.messages.calls.SignalServiceCallMessage; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ACCEPT_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_BLUETOOTH_CHANGE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_CALL_CONCLUDED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_CALL_CONNECTED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_CAMERA_SWITCH_COMPLETED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_CANCEL_PRE_JOIN_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_DENY_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_CONNECTION_FAILURE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_INTERNAL_FAILURE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_BUSY; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_GLARE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_HANGUP; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_HANGUP_ACCEPTED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_HANGUP_BUSY; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_HANGUP_DECLINED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_REMOTE_HANGUP_NEED_PERMISSION; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_SIGNALING_FAILURE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_ENDED_TIMEOUT; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_FLIP_CAMERA; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_CALL_ENDED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_CALL_UPDATE_MESSAGE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_JOINED_MEMBERSHIP_CHANGED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_LOCAL_DEVICE_STATE_CHANGED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_REMOTE_DEVICE_STATE_CHANGED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_REQUEST_MEMBERSHIP_PROOF; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_REQUEST_UPDATE_MEMBERS; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_GROUP_UPDATE_RENDERED_RESOLUTIONS; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_HTTP_FAILURE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_HTTP_SUCCESS; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_IS_IN_CALL_QUERY; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_LOCAL_HANGUP; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_LOCAL_RINGING; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_MESSAGE_SENT_ERROR; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_MESSAGE_SENT_SUCCESS; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_OUTGOING_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_PRE_JOIN_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVED_OFFER_EXPIRED; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVED_OFFER_WHILE_ACTIVE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_ANSWER; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_BUSY; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_HANGUP; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_ICE_CANDIDATES; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_OFFER; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_RECEIVE_OPAQUE_MESSAGE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_REMOTE_RINGING; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_REMOTE_VIDEO_ENABLE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SCREEN_OFF; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_ANSWER; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_BUSY; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_HANGUP; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_ICE_CANDIDATES; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_OFFER; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SEND_OPAQUE_MESSAGE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SETUP_FAILURE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SET_AUDIO_BLUETOOTH; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SET_AUDIO_SPEAKER; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SET_ENABLE_VIDEO; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_SET_MUTE_AUDIO; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_START_INCOMING_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_START_OUTGOING_CALL; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_TURN_SERVER_UPDATE; import static org.thoughtcrime.securesms.service.WebRtcCallService.ACTION_WIRED_HEADSET_CHANGE; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_ANSWER_WITH_VIDEO; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_BLUETOOTH; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_IS_ALWAYS_TURN; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_MUTE; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_RESULT_RECEIVER; import static org.thoughtcrime.securesms.service.WebRtcCallService.EXTRA_SPEAKER; import static org.thoughtcrime.securesms.service.webrtc.WebRtcData.AnswerMetadata; import static org.thoughtcrime.securesms.service.webrtc.WebRtcData.HangupMetadata; import static org.thoughtcrime.securesms.service.webrtc.WebRtcData.OpaqueMessageMetadata; import static org.thoughtcrime.securesms.service.webrtc.WebRtcData.ReceivedAnswerMetadata; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getAvailable; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getBroadcastFlag; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getCallId; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getCameraState; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getEnable; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getErrorCallState; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getErrorIdentityKey; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getGroupCallEndReason; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getGroupCallHash; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getGroupMembershipToken; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getIceCandidates; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getIceServers; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getNullableRemotePeerFromMap; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getOfferMessageType; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getRemotePeer; import static org.thoughtcrime.securesms.service.webrtc.WebRtcIntentParser.getRemotePeerFromMap; /** * Base WebRTC action processor and core of the calling state machine. As actions (as intents) * are sent to the service, they are passed to an instance of the current state's action processor. * Based on the state of the system, the action processor will either handle the event or do nothing. * * For example, the {@link OutgoingCallActionProcessor} responds to the the * {@link #handleReceivedBusy(WebRtcServiceState, CallMetadata)} event but no others do. * * Processing of the actions occur in {@link #processAction(String, Intent, WebRtcServiceState)} and * result in atomic state updates that are returned to the caller. Part of the state change can be * the replacement of the current action processor. */ public abstract class WebRtcActionProcessor { protected final Context context; protected final WebRtcInteractor webRtcInteractor; protected final String tag; public WebRtcActionProcessor(@NonNull WebRtcInteractor webRtcInteractor, @NonNull String tag) { this.context = webRtcInteractor.getWebRtcCallService(); this.webRtcInteractor = webRtcInteractor; this.tag = tag; } public @NonNull String getTag() { return tag; } public @NonNull WebRtcServiceState processAction(@NonNull String action, @NonNull Intent intent, @NonNull WebRtcServiceState currentState) { switch (action) { case ACTION_IS_IN_CALL_QUERY: return handleIsInCallQuery(currentState, intent.getParcelableExtra(EXTRA_RESULT_RECEIVER)); // Pre-Join Actions case ACTION_PRE_JOIN_CALL: return handlePreJoinCall(currentState, getRemotePeer(intent)); case ACTION_CANCEL_PRE_JOIN_CALL: return handleCancelPreJoinCall(currentState); // Outgoing Call Actions case ACTION_OUTGOING_CALL: return handleOutgoingCall(currentState, getRemotePeer(intent), getOfferMessageType(intent)); case ACTION_START_OUTGOING_CALL: return handleStartOutgoingCall(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_SEND_OFFER: return handleSendOffer(currentState, CallMetadata.fromIntent(intent), OfferMetadata.fromIntent(intent), getBroadcastFlag(intent)); case ACTION_REMOTE_RINGING: return handleRemoteRinging(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_RECEIVE_ANSWER: return handleReceivedAnswer(currentState, CallMetadata.fromIntent(intent), AnswerMetadata.fromIntent(intent), ReceivedAnswerMetadata.fromIntent(intent)); case ACTION_RECEIVE_BUSY: return handleReceivedBusy(currentState, CallMetadata.fromIntent(intent)); // Incoming Call Actions case ACTION_RECEIVE_OFFER: return handleReceivedOffer(currentState, CallMetadata.fromIntent(intent), OfferMetadata.fromIntent(intent), ReceivedOfferMetadata.fromIntent(intent)); case ACTION_RECEIVED_OFFER_EXPIRED: return handleReceivedOfferExpired(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_START_INCOMING_CALL: return handleStartIncomingCall(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_ACCEPT_CALL: return handleAcceptCall(currentState, intent.getBooleanExtra(EXTRA_ANSWER_WITH_VIDEO, false)); case ACTION_LOCAL_RINGING: return handleLocalRinging(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_DENY_CALL: return handleDenyCall(currentState); case ACTION_SEND_ANSWER: return handleSendAnswer(currentState, CallMetadata.fromIntent(intent), AnswerMetadata.fromIntent(intent), getBroadcastFlag(intent)); // Active Call Actions case ACTION_CALL_CONNECTED: return handleCallConnected(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_RECEIVED_OFFER_WHILE_ACTIVE: return handleReceivedOfferWhileActive(currentState, getRemotePeerFromMap(intent, currentState)); case ACTION_SEND_BUSY: return handleSendBusy(currentState, CallMetadata.fromIntent(intent), getBroadcastFlag(intent)); case ACTION_CALL_CONCLUDED: return handleCallConcluded(currentState, getNullableRemotePeerFromMap(intent, currentState)); case ACTION_REMOTE_VIDEO_ENABLE: return handleRemoteVideoEnable(currentState, getEnable(intent)); case ACTION_RECEIVE_HANGUP: return handleReceivedHangup(currentState, CallMetadata.fromIntent(intent), HangupMetadata.fromIntent(intent)); case ACTION_LOCAL_HANGUP: return handleLocalHangup(currentState); case ACTION_SEND_HANGUP: return handleSendHangup(currentState, CallMetadata.fromIntent(intent), HangupMetadata.fromIntent(intent), getBroadcastFlag(intent)); case ACTION_MESSAGE_SENT_SUCCESS: return handleMessageSentSuccess(currentState, getCallId(intent)); case ACTION_MESSAGE_SENT_ERROR: return handleMessageSentError(currentState, getCallId(intent), getErrorCallState(intent), getErrorIdentityKey(intent)); // Call Setup Actions case ACTION_RECEIVE_ICE_CANDIDATES: return handleReceivedIceCandidates(currentState, CallMetadata.fromIntent(intent), getIceCandidates(intent)); case ACTION_SEND_ICE_CANDIDATES: return handleSendIceCandidates(currentState, CallMetadata.fromIntent(intent), getBroadcastFlag(intent), getIceCandidates(intent)); case ACTION_TURN_SERVER_UPDATE: return handleTurnServerUpdate(currentState, getIceServers(intent), intent.getBooleanExtra(EXTRA_IS_ALWAYS_TURN, false)); // Local Device Actions case ACTION_SET_ENABLE_VIDEO: return handleSetEnableVideo(currentState, getEnable(intent)); case ACTION_SET_MUTE_AUDIO: return handleSetMuteAudio(currentState, intent.getBooleanExtra(EXTRA_MUTE, false)); case ACTION_FLIP_CAMERA: return handleSetCameraFlip(currentState); case ACTION_SCREEN_OFF: return handleScreenOffChange(currentState); case ACTION_WIRED_HEADSET_CHANGE: return handleWiredHeadsetChange(currentState, getAvailable(intent)); case ACTION_SET_AUDIO_SPEAKER: return handleSetSpeakerAudio(currentState, intent.getBooleanExtra(EXTRA_SPEAKER, false)); case ACTION_SET_AUDIO_BLUETOOTH: return handleSetBluetoothAudio(currentState, intent.getBooleanExtra(EXTRA_BLUETOOTH, false)); case ACTION_BLUETOOTH_CHANGE: return handleBluetoothChange(currentState, getAvailable(intent)); case ACTION_CAMERA_SWITCH_COMPLETED: return handleCameraSwitchCompleted(currentState, getCameraState(intent)); // End Call Actions case ACTION_ENDED_REMOTE_HANGUP: case ACTION_ENDED_REMOTE_HANGUP_ACCEPTED: case ACTION_ENDED_REMOTE_HANGUP_BUSY: case ACTION_ENDED_REMOTE_HANGUP_DECLINED: case ACTION_ENDED_REMOTE_BUSY: case ACTION_ENDED_REMOTE_HANGUP_NEED_PERMISSION: case ACTION_ENDED_REMOTE_GLARE: return handleEndedRemote(currentState, action, getRemotePeerFromMap(intent, currentState)); // End Call Failure Actions case ACTION_ENDED_TIMEOUT: case ACTION_ENDED_INTERNAL_FAILURE: case ACTION_ENDED_SIGNALING_FAILURE: case ACTION_ENDED_CONNECTION_FAILURE: return handleEnded(currentState, action, getRemotePeerFromMap(intent, currentState)); // Local Call Failure Actions case ACTION_SETUP_FAILURE: return handleSetupFailure(currentState, getCallId(intent)); // Group Calling case ACTION_GROUP_LOCAL_DEVICE_STATE_CHANGED: return handleGroupLocalDeviceStateChanged(currentState); case ACTION_GROUP_REMOTE_DEVICE_STATE_CHANGED: return handleGroupRemoteDeviceStateChanged(currentState); case ACTION_GROUP_JOINED_MEMBERSHIP_CHANGED: return handleGroupJoinedMembershipChanged(currentState); case ACTION_GROUP_REQUEST_MEMBERSHIP_PROOF: return handleGroupRequestMembershipProof(currentState, getGroupCallHash(intent), getGroupMembershipToken(intent)); case ACTION_GROUP_REQUEST_UPDATE_MEMBERS: return handleGroupRequestUpdateMembers(currentState); case ACTION_GROUP_UPDATE_RENDERED_RESOLUTIONS: return handleUpdateRenderedResolutions(currentState); case ACTION_GROUP_CALL_ENDED: return handleGroupCallEnded(currentState, getGroupCallHash(intent), getGroupCallEndReason(intent)); case ACTION_GROUP_CALL_UPDATE_MESSAGE: return handleGroupCallUpdateMessage(currentState, GroupCallUpdateMetadata.fromIntent(intent)); case ACTION_HTTP_SUCCESS: return handleHttpSuccess(currentState, HttpData.fromIntent(intent)); case ACTION_HTTP_FAILURE: return handleHttpFailure(currentState, HttpData.fromIntent(intent)); case ACTION_SEND_OPAQUE_MESSAGE: return handleSendOpaqueMessage(currentState, OpaqueMessageMetadata.fromIntent(intent)); case ACTION_RECEIVE_OPAQUE_MESSAGE: return handleReceivedOpaqueMessage(currentState, OpaqueMessageMetadata.fromIntent(intent)); } return currentState; } protected @NonNull WebRtcServiceState handleIsInCallQuery(@NonNull WebRtcServiceState currentState, @Nullable ResultReceiver resultReceiver) { if (resultReceiver != null) { resultReceiver.send(0, null); } return currentState; } //region Pre-Join protected @NonNull WebRtcServiceState handlePreJoinCall(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handlePreJoinCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleCancelPreJoinCall(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleCancelPreJoinCall not processed"); return currentState; } //endregion Pre-Join //region Outgoing Call protected @NonNull WebRtcServiceState handleOutgoingCall(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer, @NonNull OfferMessage.Type offerType) { Log.i(tag, "handleOutgoingCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleStartOutgoingCall(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleStartOutgoingCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSendOffer(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull OfferMetadata offerMetadata, boolean broadcast) { Log.i(tag, "handleSendOffer not processed"); return currentState; } protected @NonNull WebRtcServiceState handleRemoteRinging(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleRemoteRinging not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedAnswer(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull AnswerMetadata answerMetadata, @NonNull ReceivedAnswerMetadata receivedAnswerMetadata) { Log.i(tag, "handleReceivedAnswer not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedBusy(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata) { Log.i(tag, "handleReceivedBusy not processed"); return currentState; } //endregion Outgoing call //region Incoming call protected @NonNull WebRtcServiceState handleReceivedOffer(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull OfferMetadata offerMetadata, @NonNull ReceivedOfferMetadata receivedOfferMetadata) { Log.i(tag, "handleReceivedOffer(): id: " + callMetadata.getCallId().format(callMetadata.getRemoteDevice())); if (TelephonyUtil.isAnyPstnLineBusy(context)) { Log.i(tag, "PSTN line is busy."); currentState = currentState.getActionProcessor().handleSendBusy(currentState, callMetadata, true); webRtcInteractor.insertMissedCall(callMetadata.getRemotePeer(), true, receivedOfferMetadata.getServerReceivedTimestamp(), offerMetadata.getOfferType() == OfferMessage.Type.VIDEO_CALL); return currentState; } if (!RecipientUtil.isCallRequestAccepted(context.getApplicationContext(), callMetadata.getRemotePeer().getRecipient())) { Log.w(tag, "Caller is untrusted."); currentState = currentState.getActionProcessor().handleSendHangup(currentState, callMetadata, WebRtcData.HangupMetadata.fromType(HangupMessage.Type.NEED_PERMISSION), true); webRtcInteractor.insertMissedCall(callMetadata.getRemotePeer(), true, receivedOfferMetadata.getServerReceivedTimestamp(), offerMetadata.getOfferType() == OfferMessage.Type.VIDEO_CALL); return currentState; } Log.i(tag, "add remotePeer callId: " + callMetadata.getRemotePeer().getCallId() + " key: " + callMetadata.getRemotePeer().hashCode()); callMetadata.getRemotePeer().setCallStartTimestamp(receivedOfferMetadata.getServerReceivedTimestamp()); currentState = currentState.builder() .changeCallSetupState() .isRemoteVideoOffer(offerMetadata.getOfferType() == OfferMessage.Type.VIDEO_CALL) .commit() .changeCallInfoState() .putRemotePeer(callMetadata.getRemotePeer()) .build(); long messageAgeSec = Math.max(receivedOfferMetadata.getServerDeliveredTimestamp() - receivedOfferMetadata.getServerReceivedTimestamp(), 0) / 1000; Log.i(tag, "messageAgeSec: " + messageAgeSec + ", serverReceivedTimestamp: " + receivedOfferMetadata.getServerReceivedTimestamp() + ", serverDeliveredTimestamp: " + receivedOfferMetadata.getServerDeliveredTimestamp()); try { byte[] remoteIdentityKey = WebRtcUtil.getPublicKeyBytes(receivedOfferMetadata.getRemoteIdentityKey()); byte[] localIdentityKey = WebRtcUtil.getPublicKeyBytes(IdentityKeyUtil.getIdentityKey(context).serialize()); webRtcInteractor.getCallManager().receivedOffer(callMetadata.getCallId(), callMetadata.getRemotePeer(), callMetadata.getRemoteDevice(), offerMetadata.getOpaque(), offerMetadata.getSdp(), messageAgeSec, WebRtcUtil.getCallMediaTypeFromOfferType(offerMetadata.getOfferType()), 1, receivedOfferMetadata.isMultiRing(), true, remoteIdentityKey, localIdentityKey); } catch (CallException | InvalidKeyException e) { return callFailure(currentState, "Unable to process received offer: ", e); } return currentState; } protected @NonNull WebRtcServiceState handleReceivedOfferExpired(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleReceivedOfferExpired(): call_id: " + remotePeer.getCallId()); webRtcInteractor.insertMissedCall(remotePeer, true, remotePeer.getCallStartTimestamp(), currentState.getCallSetupState().isRemoteVideoOffer()); return terminate(currentState, remotePeer); } protected @NonNull WebRtcServiceState handleStartIncomingCall(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleStartIncomingCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleAcceptCall(@NonNull WebRtcServiceState currentState, boolean answerWithVideo) { Log.i(tag, "handleAcceptCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleLocalRinging(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleLocalRinging not processed"); return currentState; } protected @NonNull WebRtcServiceState handleDenyCall(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleDenyCall not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSendAnswer(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull AnswerMetadata answerMetadata, boolean broadcast) { Log.i(tag, "handleSendAnswer not processed"); return currentState; } //endregion Incoming call //region Active call protected @NonNull WebRtcServiceState handleCallConnected(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleCallConnected not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedOfferWhileActive(@NonNull WebRtcServiceState currentState, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleReceivedOfferWhileActive not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSendBusy(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, boolean broadcast) { Log.i(tag, "handleSendBusy(): id: " + callMetadata.getCallId().format(callMetadata.getRemoteDevice())); BusyMessage busyMessage = new BusyMessage(callMetadata.getCallId().longValue()); Integer destinationDeviceId = broadcast ? null : callMetadata.getRemoteDevice(); SignalServiceCallMessage callMessage = SignalServiceCallMessage.forBusy(busyMessage, true, destinationDeviceId); webRtcInteractor.sendCallMessage(callMetadata.getRemotePeer(), callMessage); return currentState; } protected @NonNull WebRtcServiceState handleCallConcluded(@NonNull WebRtcServiceState currentState, @Nullable RemotePeer remotePeer) { Log.i(tag, "handleCallConcluded not processed"); return currentState; } protected @NonNull WebRtcServiceState handleRemoteVideoEnable(@NonNull WebRtcServiceState currentState, boolean enable) { Log.i(tag, "handleRemoteVideoEnable not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedHangup(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull HangupMetadata hangupMetadata) { Log.i(tag, "handleReceivedHangup(): id: " + callMetadata.getCallId().format(callMetadata.getRemoteDevice())); try { webRtcInteractor.getCallManager().receivedHangup(callMetadata.getCallId(), callMetadata.getRemoteDevice(), hangupMetadata.getCallHangupType(), hangupMetadata.getDeviceId()); } catch (CallException e) { return callFailure(currentState, "receivedHangup() failed: ", e); } return currentState; } protected @NonNull WebRtcServiceState handleLocalHangup(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleLocalHangup not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSendHangup(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull HangupMetadata hangupMetadata, boolean broadcast) { Log.i(tag, "handleSendHangup(): id: " + callMetadata.getCallId().format(callMetadata.getRemoteDevice())); HangupMessage hangupMessage = new HangupMessage(callMetadata.getCallId().longValue(), hangupMetadata.getType(), hangupMetadata.getDeviceId(), hangupMetadata.isLegacy()); Integer destinationDeviceId = broadcast ? null : callMetadata.getRemoteDevice(); SignalServiceCallMessage callMessage = SignalServiceCallMessage.forHangup(hangupMessage, true, destinationDeviceId); webRtcInteractor.sendCallMessage(callMetadata.getRemotePeer(), callMessage); return currentState; } protected @NonNull WebRtcServiceState handleMessageSentSuccess(@NonNull WebRtcServiceState currentState, @NonNull CallId callId) { try { webRtcInteractor.getCallManager().messageSent(callId); } catch (CallException e) { return callFailure(currentState, "callManager.messageSent() failed: ", e); } return currentState; } protected @NonNull WebRtcServiceState handleMessageSentError(@NonNull WebRtcServiceState currentState, @NonNull CallId callId, @NonNull WebRtcViewModel.State errorCallState, @NonNull Optional<IdentityKey> identityKey) { Log.w(tag, "handleMessageSentError():"); try { webRtcInteractor.getCallManager().messageSendFailure(callId); } catch (CallException e) { currentState = callFailure(currentState, "callManager.messageSendFailure() failed: ", e); } RemotePeer activePeer = currentState.getCallInfoState().getActivePeer(); if (activePeer == null) { return currentState; } WebRtcServiceStateBuilder builder = currentState.builder(); if (errorCallState == WebRtcViewModel.State.UNTRUSTED_IDENTITY) { CallParticipant participant = Objects.requireNonNull(currentState.getCallInfoState().getRemoteCallParticipant(activePeer.getRecipient())); CallParticipant untrusted = participant.withIdentityKey(identityKey.get()); builder.changeCallInfoState() .callState(WebRtcViewModel.State.UNTRUSTED_IDENTITY) .putParticipant(activePeer.getRecipient(), untrusted) .commit(); } else { builder.changeCallInfoState() .callState(errorCallState) .commit(); } return builder.build(); } //endregion Active call //region Call setup protected @NonNull WebRtcServiceState handleSendIceCandidates(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, boolean broadcast, @NonNull ArrayList<IceCandidateParcel> iceCandidates) { Log.i(tag, "handleSendIceCandidates not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedIceCandidates(@NonNull WebRtcServiceState currentState, @NonNull CallMetadata callMetadata, @NonNull ArrayList<IceCandidateParcel> iceCandidateParcels) { Log.i(tag, "handleReceivedIceCandidates not processed"); return currentState; } public @NonNull WebRtcServiceState handleTurnServerUpdate(@NonNull WebRtcServiceState currentState, @NonNull List<PeerConnection.IceServer> iceServers, boolean isAlwaysTurn) { Log.i(tag, "handleTurnServerUpdate not processed"); return currentState; } //endregion Call setup //region Local device protected @NonNull WebRtcServiceState handleSetEnableVideo(@NonNull WebRtcServiceState currentState, boolean enable) { Log.i(tag, "handleSetEnableVideo not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSetMuteAudio(@NonNull WebRtcServiceState currentState, boolean muted) { Log.i(tag, "handleSetMuteAudio not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSetSpeakerAudio(@NonNull WebRtcServiceState currentState, boolean isSpeaker) { Log.i(tag, "handleSetSpeakerAudio not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSetBluetoothAudio(@NonNull WebRtcServiceState currentState, boolean isBluetooth) { Log.i(tag, "handleSetBluetoothAudio not processed"); return currentState; } protected @NonNull WebRtcServiceState handleSetCameraFlip(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleSetCameraFlip not processed"); return currentState; } protected @NonNull WebRtcServiceState handleScreenOffChange(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleScreenOffChange not processed"); return currentState; } protected @NonNull WebRtcServiceState handleBluetoothChange(@NonNull WebRtcServiceState currentState, boolean available) { Log.i(tag, "handleBluetoothChange not processed"); return currentState; } protected @NonNull WebRtcServiceState handleWiredHeadsetChange(@NonNull WebRtcServiceState currentState, boolean present) { Log.i(tag, "handleWiredHeadsetChange not processed"); return currentState; } public @NonNull WebRtcServiceState handleCameraSwitchCompleted(@NonNull WebRtcServiceState currentState, @NonNull CameraState newCameraState) { Log.i(tag, "handleCameraSwitchCompleted not processed"); return currentState; } //endregion Local device //region End call protected @NonNull WebRtcServiceState handleEndedRemote(@NonNull WebRtcServiceState currentState, @NonNull String action, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleEndedRemote not processed"); return currentState; } //endregion End call //region End call failure protected @NonNull WebRtcServiceState handleEnded(@NonNull WebRtcServiceState currentState, @NonNull String action, @NonNull RemotePeer remotePeer) { Log.i(tag, "handleEnded not processed"); return currentState; } //endregion //region Local call failure protected @NonNull WebRtcServiceState handleSetupFailure(@NonNull WebRtcServiceState currentState, @NonNull CallId callId) { Log.i(tag, "handleSetupFailure not processed"); return currentState; } //endregion //region Global call operations public @NonNull WebRtcServiceState callFailure(@NonNull WebRtcServiceState currentState, @Nullable String message, @Nullable Throwable error) { Log.w(tag, "callFailure(): " + message, error); WebRtcServiceStateBuilder builder = currentState.builder(); if (currentState.getCallInfoState().getActivePeer() != null) { builder.changeCallInfoState() .callState(WebRtcViewModel.State.CALL_DISCONNECTED); } try { webRtcInteractor.getCallManager().reset(); } catch (CallException e) { Log.w(tag, "Unable to reset call manager: ", e); } currentState = builder.changeCallInfoState().clearPeerMap().build(); return terminate(currentState, currentState.getCallInfoState().getActivePeer()); } public synchronized @NonNull WebRtcServiceState terminate(@NonNull WebRtcServiceState currentState, @Nullable RemotePeer remotePeer) { Log.i(tag, "terminate():"); RemotePeer activePeer = currentState.getCallInfoState().getActivePeer(); if (activePeer == null) { Log.i(tag, "skipping with no active peer"); return currentState; } if (!activePeer.callIdEquals(remotePeer)) { Log.i(tag, "skipping remotePeer is not active peer"); return currentState; } webRtcInteractor.updatePhoneState(LockManager.PhoneState.PROCESSING); webRtcInteractor.stopForegroundService(); boolean playDisconnectSound = (activePeer.getState() == CallState.DIALING) || (activePeer.getState() == CallState.REMOTE_RINGING) || (activePeer.getState() == CallState.RECEIVED_BUSY) || (activePeer.getState() == CallState.CONNECTED); webRtcInteractor.stopAudio(playDisconnectSound); webRtcInteractor.setWantsBluetoothConnection(false); webRtcInteractor.updatePhoneState(LockManager.PhoneState.IDLE); return WebRtcVideoUtil.deinitializeVideo(currentState) .builder() .changeCallInfoState() .activePeer(null) .commit() .actionProcessor(currentState.getCallInfoState().getCallState() == WebRtcViewModel.State.CALL_DISCONNECTED ? new DisconnectingCallActionProcessor(webRtcInteractor) : new IdleActionProcessor(webRtcInteractor)) .terminate() .build(); } //endregion //region Group Calling protected @NonNull WebRtcServiceState handleGroupLocalDeviceStateChanged(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleGroupLocalDeviceStateChanged not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupRemoteDeviceStateChanged(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleGroupRemoteDeviceStateChanged not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupJoinedMembershipChanged(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleGroupJoinedMembershipChanged not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupRequestMembershipProof(@NonNull WebRtcServiceState currentState, int groupCallHash, @NonNull byte[] groupMembershipToken) { Log.i(tag, "handleGroupRequestMembershipProof not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupRequestUpdateMembers(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleGroupRequestUpdateMembers not processed"); return currentState; } protected @NonNull WebRtcServiceState handleUpdateRenderedResolutions(@NonNull WebRtcServiceState currentState) { Log.i(tag, "handleUpdateRenderedResolutions not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupCallEnded(@NonNull WebRtcServiceState currentState, int groupCallHash, @NonNull GroupCall.GroupCallEndReason groupCallEndReason) { Log.i(tag, "handleGroupCallEnded not processed"); return currentState; } protected @NonNull WebRtcServiceState handleGroupCallUpdateMessage(@NonNull WebRtcServiceState currentState, @NonNull GroupCallUpdateMetadata groupCallUpdateMetadata) { webRtcInteractor.peekGroupCall(groupCallUpdateMetadata); return currentState; } //endregion protected @NonNull WebRtcServiceState handleHttpSuccess(@NonNull WebRtcServiceState currentState, @NonNull HttpData httpData) { try { webRtcInteractor.getCallManager().receivedHttpResponse(httpData.getRequestId(), httpData.getStatus(), httpData.getBody() != null ? httpData.getBody() : new byte[0]); } catch (CallException e) { return callFailure(currentState, "Unable to process received http response", e); } return currentState; } protected @NonNull WebRtcServiceState handleHttpFailure(@NonNull WebRtcServiceState currentState, @NonNull HttpData httpData) { try { webRtcInteractor.getCallManager().httpRequestFailed(httpData.getRequestId()); } catch (CallException e) { return callFailure(currentState, "Unable to process received http response", e); } return currentState; } protected @NonNull WebRtcServiceState handleSendOpaqueMessage(@NonNull WebRtcServiceState currentState, @NonNull OpaqueMessageMetadata opaqueMessageMetadata) { Log.i(tag, "handleSendOpaqueMessage not processed"); return currentState; } protected @NonNull WebRtcServiceState handleReceivedOpaqueMessage(@NonNull WebRtcServiceState currentState, @NonNull OpaqueMessageMetadata opaqueMessageMetadata) { Log.i(tag, "handleReceivedOpaqueMessage not processed"); return currentState; } }
gpl-3.0
enghen10/todo-application-frontend-angular
e2e/app.po.ts
235
import { browser, element, by } from 'protractor'; export class TodoApplicationFrontendAngularPage { navigateTo() { return browser.get('/'); } getParagraphText() { return element(by.css('app-root h1')).getText(); } }
gpl-3.0
wmwolf/MESATestHub
MESATestHub/test/system/test_data_test.rb
208
require "application_system_test_case" class TestDataTest < ApplicationSystemTestCase # test "visiting the index" do # visit test_data_url # # assert_selector "h1", text: "TestDatum" # end end
gpl-3.0
jukiewiczm/renjin
tools/packager/src/main/java/org/renjin/packaging/DatasetsBuilder2.java
12223
package org.renjin.packaging; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.renjin.eval.EvalException; import org.renjin.eval.Session; import org.renjin.eval.SessionBuilder; import org.renjin.parser.RParser; import org.renjin.primitives.io.connections.GzFileConnection; import org.renjin.primitives.io.serialization.RDataReader; import org.renjin.primitives.io.serialization.RDataWriter; import org.renjin.primitives.packaging.PackageLoader; import org.renjin.repackaged.guava.annotations.VisibleForTesting; import org.renjin.repackaged.guava.base.Joiner; import org.renjin.repackaged.guava.collect.HashMultimap; import org.renjin.repackaged.guava.collect.Multimap; import org.renjin.repackaged.guava.io.Files; import org.renjin.sexp.*; import org.tukaani.xz.XZInputStream; import java.io.*; import java.util.Properties; import java.util.zip.GZIPInputStream; /** * Prepares datasets, writes an index, and copies them into target/classes * as a resource. * * <p>GNU R supports several types of data formats and compression; we want to * simplify everything at compile time into an uncompressed, serialized objects * we don't have to muck around with it at runtime. The data files will be compressed * in a jar in any case.</p> * * <p>To complicate things, a single "dataset" can contain multiple R objects. Again, * to simplify things at runtime, we'll write out each element to a seperate resource * file, and then write a "datasets" index file that maps logical datasets to the * named R objects. */ public class DatasetsBuilder2 { private final PackageSource source; private final BuildContext buildContext; private final File dataObjectDirectory; /** * Maps logical datasets to R object names */ private final Multimap<String, String> indexMap = HashMultimap.create(); public DatasetsBuilder2(PackageSource source, BuildContext buildContext) { this.source = source; this.buildContext = buildContext; this.dataObjectDirectory = new File(buildContext.getPackageOutputDir(), "data"); } public void build() throws IOException { if(!source.getDataDir().exists()) { buildContext.getLogger().info(source.getDataDir() + " does not exist; no datasets will be built."); return; } buildContext.getLogger().info("Building datasets in " + source.getDataDir()); if(!dataObjectDirectory.exists()) { boolean created = this.dataObjectDirectory.mkdirs(); if (!created) { throw new IOException("Failed to create data output directory: " + this.dataObjectDirectory.getAbsolutePath()); } } File[] files = source.getDataDir().listFiles(); if(files != null) { for(File dataFile : files) { try { processDataset(dataFile); } catch(EvalException e) { System.err.println("ERROR processing data file " + dataFile.getName() + ": " + e.getMessage()); e.printRStackTrace(System.err); throw e; } catch(Exception e) { System.err.println("Exception processing data file " + dataFile); e.printStackTrace(); throw new RuntimeException(e); } } } if(!indexMap.isEmpty()) { writeIndex(); } } private void writeIndex() throws FileNotFoundException { Properties index = new Properties(); for(String logicalDatasetName : indexMap.keySet()) { index.put(logicalDatasetName, Joiner.on(",").join(indexMap.get(logicalDatasetName))); } File indexFile = new File(buildContext.getPackageOutputDir(), "datasets"); FileOutputStream out = new FileOutputStream(indexFile); try { index.store(out, "Datasets index"); out.close(); } catch (IOException e) { throw new RuntimeException("Failed to write dataset index to " + indexFile.getAbsolutePath(), e); } } @VisibleForTesting void processDataset(File dataFile) throws IOException { if(dataFile.getName().endsWith("datalist")) { return; } else if(dataFile.getName().toLowerCase().endsWith(".rda") || dataFile.getName().toLowerCase().endsWith(".rdata")) { processRDataFile(dataFile); } else if(dataFile.getName().endsWith(".txt")) { processTextFile(dataFile, stripExtension(dataFile), ""); } else if(dataFile.getName().endsWith(".txt.gz")) { processTextFile(dataFile, stripExtension(dataFile, ".txt.gz"), ""); } else if(dataFile.getName().endsWith(".tab")) { processTextFile(dataFile, stripExtension(dataFile), ""); } else if(dataFile.getName().endsWith(".tab.gz")) { processTextFile(dataFile, stripExtension(dataFile, ".tab.gz"), ""); } else if(dataFile.getName().toLowerCase().endsWith(".csv")) { processTextFile(dataFile, stripExtension(dataFile), ";"); } else if(dataFile.getName().toLowerCase().endsWith(".csv.gz")) { processTextFile(dataFile, stripExtension(dataFile, ".csv.gz"), ";"); } else if(dataFile.getName().toUpperCase().endsWith(".R")) { processRScript(dataFile, stripExtension(dataFile)); } else { buildContext.getLogger().debug(dataFile.getName() + ": ignored."); } } /** * Copy and decompress the saved PairList in rda format. * @param dataFile the source data format * @throws IOException */ private void processRDataFile(File dataFile) throws IOException { SEXP exp; try(RDataReader reader = new RDataReader(DatasetsBuilder2.decompress(dataFile))) { exp = reader.readFile(); } if(!(exp instanceof PairList)) { throw new UnsupportedOperationException("Expected to find a pairlist in " + dataFile + ", found a " + exp.getTypeName()); } String logicalDatasetName = stripExtension(dataFile.getName()); Session session = new SessionBuilder().withoutBasePackage().build(); writePairList(logicalDatasetName, session, (PairList)exp); } private String stripExtension(String name) { int lastDot = name.lastIndexOf('.'); return name.substring(0, lastDot); } private String stripExtension(File dataFile) { return stripExtension(dataFile.getName()); } private static String stripExtension(File file, String ext) { return stripExtension(file.getName(), ext); } private static String stripExtension(String name, String ext) { return name.substring(0, name.length() - ext.length()); } /** * Text files (*.tab, *.csv, *.txt) are processed with utils::read.table() and the * resulting data.frame is stored as the single object of the logical dataset. */ private void processTextFile(File dataFile, String logicalDatasetName, String sep) throws IOException { if (scriptFileExists(logicalDatasetName) || dataFileAlreadyExists(logicalDatasetName)) { debug(dataFile, "skipping, script or data file exists."); return; } debug(dataFile, "processing as text file."); // Read into a data frame using read.table() PairList.Builder args = new PairList.Builder(); args.add(StringVector.valueOf(dataFile.getAbsolutePath())); args.add("header", LogicalVector.TRUE); args.add("sep", StringVector.valueOf(sep)); FunctionCall readTable = FunctionCall.newCall(Symbol.get("::"), Symbol.get("utils"), Symbol.get("read.table")); FunctionCall call = new FunctionCall(readTable, args.build()); Session session = new SessionBuilder() .bind(PackageLoader.class, buildContext.getPackageLoader()) .build(); SEXP dataFrame = session.getTopLevelContext().evaluate(call); PairList.Builder pairList = new PairList.Builder(); pairList.add(logicalDatasetName, dataFrame); writePairList(logicalDatasetName, session, pairList.build()); } private void debug(File dataFile, String message) { buildContext.getLogger().debug(dataFile.getName() + ": " + message); } private boolean dataFileAlreadyExists(String logicalDatasetName) { for (File file : source.getDataDir().listFiles()) { String name = Files.getNameWithoutExtension(file.getName()); String ext = Files.getFileExtension(file.getName()); if(logicalDatasetName.equals(name) && (ext.equalsIgnoreCase("RData") || ext.equalsIgnoreCase("rda"))) { return true; } } return false; } private boolean scriptFileExists(String logicalDatasetName) { for (File file : source.getDataDir().listFiles()) { String name = Files.getNameWithoutExtension(file.getName()); String ext = Files.getFileExtension(file.getName()); if (logicalDatasetName.equals(name) && ext.equalsIgnoreCase("R")) { return true; } } return false; } /** * R Scripts are evaluated, and any resulting objects in the global * namespace are considered part of the dataset. * */ private void processRScript(File scriptFile, String logicalDatasetName) throws IOException { if(dataFileAlreadyExists(logicalDatasetName)) { debug(scriptFile, "skipping, datafile exists."); return; } debug(scriptFile, "evaluating as script."); Session session = new SessionBuilder() .bind(PackageLoader.class, buildContext.getPackageLoader()) .build(); FileReader reader = new FileReader(scriptFile); ExpressionVector source = RParser.parseAllSource(reader); reader.close(); // The utils package needs to be on the search path // For read.table, etc session.getTopLevelContext().evaluate(FunctionCall.newCall(Symbol.get("library"), Symbol.get("utils"))); // The working directory needs to be the data dir session.setWorkingDirectory(scriptFile.getParentFile()); session.getTopLevelContext().evaluate(source); PairList.Builder pairList = new PairList.Builder(); for(Symbol symbol : session.getGlobalEnvironment().getSymbolNames()) { if(!symbol.getPrintName().startsWith(".")) { pairList.add(symbol, session.getGlobalEnvironment().getVariable(symbol)); } } writePairList(logicalDatasetName, session, pairList.build()); } /** * Write each element of the pairlist out to a separate resource * file so that it can be loaded on demand, rather than en mass * when a package is loaded. */ private void writePairList(String logicalDatasetName, Session session, PairList pairList) throws IOException { File datasetDir = new File(dataObjectDirectory, logicalDatasetName); if(!datasetDir.exists()) { boolean created = datasetDir.mkdirs(); if(!created) { throw new IOException("Failed to create directory for dataset " + logicalDatasetName); } } for(PairList.Node node : pairList.nodes()) { indexMap.put(logicalDatasetName, logicalDatasetName + "/" + node.getName()); File targetFile = new File(datasetDir, node.getName()); FileOutputStream out = new FileOutputStream(targetFile); RDataWriter writer = new RDataWriter(session.getTopLevelContext(), out); writer.save(node.getValue()); out.close(); } } /** * Check the input stream for a compression header and wrap in a decompressing * stream (gzip or xz) if necessary */ public static InputStream decompress(File file) throws IOException { FileInputStream in = new FileInputStream(file); int b1 = in.read(); int b2 = in.read(); int b3 = in.read(); in.close(); if(b1 == GzFileConnection.GZIP_MAGIC_BYTE1 && b2 == GzFileConnection.GZIP_MAGIC_BYTE2) { return new GZIPInputStream(new FileInputStream(file)); } else if(b1 == 0xFD && b2 == '7') { // See http://tukaani.org/xz/xz-javadoc/org/tukaani/xz/XZInputStream.html // Set a memory limit of 64mb, if this is not sufficient, it will throw // an exception rather than an OutOfMemoryError, which will terminate the JVM return new XZInputStream(new FileInputStream(file), 64 * 1024 * 1024); } else if (b1 == 'B' && b2 == 'Z' && b3 == 'h' ) { return new BZip2CompressorInputStream(new FileInputStream(file)); } else { return new FileInputStream(file); } } }
gpl-3.0
yamstudio/leetcode
csharp/722.remove-comments.cs
1416
/* * @lc app=leetcode id=722 lang=csharp * * [722] Remove Comments */ using System.Collections.Generic; using System.Text; // @lc code=start public class Solution { public IList<string> RemoveComments(string[] source) { IList<string> ret = new List<string>(); StringBuilder sb = new StringBuilder(); bool isBlock = false; foreach (var line in source) { int len = line.Length; for (int i = 0; i < len; ++i) { char c = line[i]; if (isBlock) { if (i < len - 1 && c == '*' && line[i + 1] == '/') { isBlock = false; ++i; } continue; } if (i == len - 1) { sb.Append(c); continue; } if (c == '/') { if (line[i + 1] == '/') { break; } if (line[i + 1] == '*') { isBlock = true; ++i; continue; } } sb.Append(c); } if (!isBlock && sb.Length > 0) { ret.Add(sb.ToString()); sb.Clear(); } } return ret; } } // @lc code=end
gpl-3.0
missingdaysqxy/MVCiHealth
MVCiHealth/App_Start/BundleConfig.cs
1721
using System.Web; using System.Web.Optimization; namespace MVCiHealth { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js", "~/Scripts/jquery.unobtrusive-ajax.min.js", "~/Scripts/star-rating*")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); //添加自定义的javascripts代码 bundles.Add(new ScriptBundle("~/JavaScripts/global").Include( "~/JavaScripts/global.js")); // 使用要用于开发和学习的 Modernizr 的开发版本。然后,当你做好 // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js", "~/Scripts/respond.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/normalize.css", "~/Content/bootstrap.min.css", "~/Content/bootstrap-theme.min.css", "~/Content/site.css", "~/Content/star-rating.min.css")); } } }
gpl-3.0
acostasg/upload
upload/tests/shared/test_open_file.py
642
import unittest import upload.injectionContainer as injectionContainer from upload.strategy.dummys.injectedContainerDummy import ContainerMock class TestRequestParams(unittest.TestCase): """ Class test for request params class """ def test_open_file_error(self): """ test case secured upload """ injectionContainer.Container.update( ContainerMock().container() ) from upload.shared \ import open_file with self.assertRaises(FileNotFoundError): open_file.execute('FailedTest', 'r') if __name__ == '__main__': unittest.main()
gpl-3.0
hlin09/renjin
core/src/main/java/org/renjin/stats/internals/FFT.java
1762
package org.renjin.stats.internals; import edu.emory.mathcs.jtransforms.fft.DoubleFFT_1D; import org.apache.commons.math.complex.Complex; import org.renjin.invoke.annotations.Internal; import org.renjin.sexp.*; public class FFT { @Internal public static ComplexVector fft(IntVector x, boolean inverse) { return realFFT(x, inverse); } @Internal public static ComplexVector fft(DoubleVector x, boolean inverse) { return realFFT(x, inverse); } @Internal public static ComplexVector fft(ComplexVector x, boolean inverse) { DoubleFFT_1D fft = new DoubleFFT_1D(x.length()); double array[] = new double[x.length() * 2]; for(int i=0;i!=x.length();++i) { array[i*2] = x.getElementAsComplex(i).getReal(); array[i*2+1] = x.getElementAsComplex(i).getImaginary(); } if(inverse) { fft.complexInverse(array, false); } else { fft.complexForward(array); } return toComplex(array); } private static ComplexVector realFFT(Vector x, boolean inverse) { DoubleFFT_1D fft = new DoubleFFT_1D(x.length()); double array[] = new double[x.length() * 2]; for(int i=0;i!=x.length();++i) { array[i] = x.getElementAsDouble(i); } if(inverse) { fft.realInverse(array, false); } else { fft.realForwardFull(array); } return toComplex(array); } private static ComplexVector toComplex(double[] array) { int n = array.length / 2; ComplexArrayVector.Builder result = new ComplexArrayVector.Builder(0, n); for(int i=0;i!=n;++i) { result.add(new Complex(array[i*2], array[i*2+1])); } return result.build(); } private static boolean isPowerOfTwo(int n) { return ((n!=0) && (n&(n-1))==0); } }
gpl-3.0
calexil/sandwich
sandwich.py
186
#!/usr/bin/env python import webbrowser import pyautogui print ("Here is a sandwich,") print ("You are welcome") pyautogui.time.sleep(2) webbrowser.open("https://u.teknik.io/UOCVi.jpg")
gpl-3.0
STEMLab/geoserver-3d-extension
gs-wfs-iso/src/main/java/org/geoserver/wfs/kvp/SrsNameKvpParser.java
712
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved * (c) 2001 - 2013 OpenPlans * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.wfs.kvp; import java.net.URI; import org.geoserver.ows.FlatKvpParser; import org.geoserver.ows.KvpParser; /** * Kvp Parser which parses srsName strings like "epsg:4326" into a URI. * * @author Justin Deoliveira, The Open Planning Project * */ public class SrsNameKvpParser extends KvpParser { public SrsNameKvpParser() { super("srsName", URI.class); } public Object parse(String token) throws Exception { return new URI(token); } }
gpl-3.0
htdebeer/paru
lib/paru/filter/header.rb
1981
#-- # Copyright 2015, 2016, 2017 Huub de Beer <Huub@heerdebeer.org> # # This file is part of Paru # # Paru 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. # # Paru 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 Paru. If not, see <http://www.gnu.org/licenses/>. #++ require_relative "./block.rb" require_relative "./attr.rb" require_relative "./inner_markdown.rb" module Paru module PandocFilter # A Header node has a level, an attribute object and the contents of # the header as a list on Inline nodes. # # @!attribute level # @return [Integer] # # @!attribute attr # @return [Attr] class Header < Block include InnerMarkdown attr_accessor :level, :attr # Create a new Header node # # @param contents [Array] an array with the level, attribute, and # the header contents def initialize(contents) @level = contents[0] @attr = Attr.new contents[1] super contents[2], true end # Create an AST representation of this Header node def ast_contents() [ @level, @attr.to_ast, super ] end # Has this Header node inline contents? # # @return [Boolean] true def has_inline? true end end end end
gpl-3.0
nickbattle/vdmj
vdmj/src/main/java/com/fujitsu/vdmj/tc/definitions/TCTypeDefinition.java
16031
/******************************************************************************* * * Copyright (c) 2016 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ 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. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * SPDX-License-Identifier: GPL-3.0-or-later * ******************************************************************************/ package com.fujitsu.vdmj.tc.definitions; import com.fujitsu.vdmj.ast.expressions.ASTExpression; import com.fujitsu.vdmj.lex.Dialect; import com.fujitsu.vdmj.lex.LexLocation; import com.fujitsu.vdmj.lex.LexTokenReader; import com.fujitsu.vdmj.mapper.ClassMapper; import com.fujitsu.vdmj.syntax.ExpressionReader; import com.fujitsu.vdmj.tc.TCNode; import com.fujitsu.vdmj.tc.annotations.TCAnnotationList; import com.fujitsu.vdmj.tc.definitions.visitors.TCDefinitionVisitor; import com.fujitsu.vdmj.tc.expressions.TCExpression; import com.fujitsu.vdmj.tc.lex.TCNameToken; import com.fujitsu.vdmj.tc.patterns.TCIdentifierPattern; import com.fujitsu.vdmj.tc.patterns.TCPattern; import com.fujitsu.vdmj.tc.patterns.TCPatternList; import com.fujitsu.vdmj.tc.patterns.TCPatternListList; import com.fujitsu.vdmj.tc.types.TCBooleanType; import com.fujitsu.vdmj.tc.types.TCField; import com.fujitsu.vdmj.tc.types.TCFunctionType; import com.fujitsu.vdmj.tc.types.TCInvariantType; import com.fujitsu.vdmj.tc.types.TCNamedType; import com.fujitsu.vdmj.tc.types.TCRecordType; import com.fujitsu.vdmj.tc.types.TCType; import com.fujitsu.vdmj.tc.types.TCTypeList; import com.fujitsu.vdmj.tc.types.TCUnionType; import com.fujitsu.vdmj.tc.types.TCUnresolvedType; import com.fujitsu.vdmj.typechecker.Environment; import com.fujitsu.vdmj.typechecker.NameScope; import com.fujitsu.vdmj.typechecker.Pass; import com.fujitsu.vdmj.typechecker.TypeCheckException; import com.fujitsu.vdmj.typechecker.TypeChecker; import com.fujitsu.vdmj.typechecker.TypeComparator; /** * A class to hold a type definition. */ public class TCTypeDefinition extends TCDefinition { private static final long serialVersionUID = 1L; public TCInvariantType type; public final TCTypeList unresolved; public final TCPattern invPattern; public final TCExpression invExpression; public final TCPattern eqPattern1; public final TCPattern eqPattern2; public final TCExpression eqExpression; public final TCPattern ordPattern1; public final TCPattern ordPattern2; public final TCExpression ordExpression; public TCExplicitFunctionDefinition invdef; public TCExplicitFunctionDefinition eqdef; public TCExplicitFunctionDefinition orddef; public TCExplicitFunctionDefinition mindef; public TCExplicitFunctionDefinition maxdef; public boolean infinite = false; private TCDefinitionList composeDefinitions; public TCTypeDefinition(TCAnnotationList annotations, TCAccessSpecifier accessSpecifier, TCNameToken name, TCInvariantType type, TCPattern invPattern, TCExpression invExpression, TCPattern eqPattern1, TCPattern eqPattern2, TCExpression eqExpression, TCPattern ordPattern1, TCPattern ordPattern2, TCExpression ordExpression) { super(Pass.TYPES, name.getLocation(), name, NameScope.TYPENAME); this.annotations = annotations; this.accessSpecifier = accessSpecifier; this.type = type; this.unresolved = type.unresolvedTypes(); this.invPattern = invPattern; this.invExpression = invExpression; this.eqPattern1 = eqPattern1; this.eqPattern2 = eqPattern2; this.eqExpression = eqExpression; this.ordPattern1 = ordPattern1; this.ordPattern2 = ordPattern2; this.ordExpression = ordExpression; type.definitions = new TCDefinitionList(this); composeDefinitions = new TCDefinitionList(); } @Override public String toString() { return accessSpecifier.ifSet(" ") + name.getName() + " = " + type.toDetailedString() + (invPattern == null ? "" : "\n\tinv " + invPattern + " == " + invExpression) + (eqPattern1 == null ? "" : "\n\teq " + eqPattern1 + " = " + eqPattern2 + " == " + eqExpression) + (ordPattern1 == null ? "" : "\n\tord " + ordPattern1 + " < " + ordPattern2 + " == " + ordExpression); } @Override public String kind() { return "type"; } @Override public void implicitDefinitions(Environment base) { if (invPattern != null) { invdef = getInvDefinition(); type.setInvariant(invdef); } else { invdef = null; } if (eqPattern1 != null) { eqdef = getEqOrdDefinition(eqPattern1, eqPattern2, eqExpression, name.getEqName(eqPattern1.location)); type.setEquality(eqdef); } else { eqdef = null; } if (ordPattern1 != null) { orddef = getEqOrdDefinition(ordPattern1, ordPattern2, ordExpression, name.getOrdName(ordPattern1.location)); type.setOrder(orddef); mindef = getMinMaxDefinition(true, name.getMinName(ordPattern1.location)); maxdef = getMinMaxDefinition(false, name.getMaxName(ordPattern1.location)); } else { orddef = null; mindef = null; maxdef = null; } // TCType definitions of the form "A = compose B of ... end" also define the type // B, which can be used globally. Here, we assume all compose types are legal // but in the typeCheck we check whether they match any existing definitions. if (type instanceof TCNamedType) { composeDefinitions.clear(); TCNamedType nt = (TCNamedType)type; for (TCType compose: nt.type.getComposeTypes()) { TCRecordType rtype = (TCRecordType)compose; composeDefinitions.add(new TCTypeDefinition(null, TCAccessSpecifier.DEFAULT, rtype.name, rtype, null, null, null, null, null, null, null, null)); } } } @Override public void typeResolve(Environment base) { try { infinite = false; type = (TCInvariantType)type.typeResolve(base, this); if (infinite) { report(3050, "Type '" + name + "' is infinite"); } if (invdef != null) { invdef.typeResolve(base); invPattern.typeResolve(base); } if (eqdef != null) { eqdef.typeResolve(base); eqPattern1.typeResolve(base); eqPattern2.typeResolve(base); } if (orddef != null) { orddef.typeResolve(base); ordPattern1.typeResolve(base); ordPattern2.typeResolve(base); } if (mindef != null) { mindef.typeResolve(base); } if (maxdef != null) { maxdef.typeResolve(base); } composeDefinitions.typeResolve(base); } catch (TypeCheckException e) { type.unResolve(); throw e; } } @Override public void typeCheck(Environment base, NameScope scope) { if (annotations != null) annotations.tcBefore(this, base, scope); // We have to perform the type check in two passes because the invariants can depend on // the types of "values" that have not been set yet. Initially, pass == TYPES. if (pass == Pass.DEFS) // Set below { if (invdef != null) { invdef.typeCheck(base, NameScope.NAMES); } if (eqdef != null) { eqdef.typeCheck(base, NameScope.NAMES); } if (orddef != null) { orddef.typeCheck(base, NameScope.NAMES); } // Suppress any TC errors around min/max as they can only add confusion TypeChecker.suspend(true); if (mindef != null) { mindef.typeCheck(base, NameScope.NAMES); } if (maxdef != null) { maxdef.typeCheck(base, NameScope.NAMES); } TypeChecker.suspend(false); } else { pass = Pass.DEFS; // Come back later for the invariant functions if (type.isUnion(location)) { TCUnionType ut = type.getUnion(); for (TCType t: ut.types) { if (orddef != null && t instanceof TCInvariantType) { TCInvariantType it = (TCInvariantType) t; if (it.orddef != null) { warning(5019, "Order of union member " + t + " will be overridden"); } } if (eqdef != null && t.isEq(location)) { warning(5020, "Equality of union member " + t + " will be overridden"); } } } TypeComparator.checkImports(base, unresolved, location.module); if (type instanceof TCNamedType) { // Rebuild the compose definitions, after we check whether they already exist composeDefinitions.clear(); TCNamedType nt = (TCNamedType)type; for (TCType compose: TypeComparator.checkComposeTypes(nt.type, base, true)) { TCRecordType rtype = (TCRecordType)compose; TCDefinition cdef = new TCTypeDefinition(null, accessSpecifier, rtype.name, rtype, null, null, null, null, null, null, null, null); composeDefinitions.add(cdef); } } // We have to do the "top level" here, rather than delegating to the types // because the definition pointer from these top level types just refers // to the definition we are checking, which is never "narrower" than itself. // See the narrowerThan method in TCNamedType and TCRecordType. if (type instanceof TCNamedType) { TCNamedType ntype = (TCNamedType)type; if (ntype.type.narrowerThan(accessSpecifier)) { report(3321, "Type component visibility less than type's definition"); } } else if (type instanceof TCRecordType) { TCRecordType rtype = (TCRecordType)type; for (TCField field: rtype.fields) { if (field.type.narrowerThan(accessSpecifier)) { field.tagname.report(3321, "Field type visibility less than type's definition"); } if (field.equalityAbstraction && eqdef != null) { field.tagname.warning(5018, "Field has ':-' for type with eq definition"); } } } } if (annotations != null) annotations.tcAfter(this, type, base, scope); } @Override public TCType getType() { return type; } @Override public TCDefinition findName(TCNameToken sought, NameScope incState) { if (invdef != null && invdef.findName(sought, incState) != null) { return invdef; } if (eqdef != null && eqdef.findName(sought, incState) != null) { return eqdef; } if (orddef != null && orddef.findName(sought, incState) != null) { return orddef; } if (mindef != null && mindef.findName(sought, incState) != null) { return mindef; } if (maxdef != null && maxdef.findName(sought, incState) != null) { return maxdef; } return null; } @Override public TCDefinition findType(TCNameToken sought, String fromModule) { if (composeDefinitions != null) { TCDefinition d = composeDefinitions.findType(sought, fromModule); if (d != null) { return d; } } return super.findName(sought, NameScope.TYPENAME); } @Override public TCDefinitionList getDefinitions() { TCDefinitionList defs = new TCDefinitionList(this); defs.addAll(composeDefinitions); if (invdef != null) { defs.add(invdef); } if (eqdef != null) { defs.add(eqdef); } if (orddef != null) { defs.add(orddef); } if (mindef != null) { defs.add(mindef); } if (maxdef != null) { defs.add(maxdef); } return defs; } private TCExplicitFunctionDefinition getInvDefinition() { LexLocation loc = invPattern.location; TCPatternList params = new TCPatternList(); params.add(invPattern); TCPatternListList parameters = new TCPatternListList(); parameters.add(params); TCTypeList ptypes = new TCTypeList(); if (type instanceof TCRecordType) { // Records are inv_R: R +> bool ptypes.add(new TCUnresolvedType(name)); } else { // Named types are inv_T: x +> bool, for T = x TCNamedType nt = (TCNamedType)type; ptypes.add(nt.type); } TCFunctionType ftype = new TCFunctionType(loc, ptypes, false, new TCBooleanType(loc)); TCExplicitFunctionDefinition def = new TCExplicitFunctionDefinition(null, accessSpecifier, name.getInvName(loc), null, ftype, parameters, invExpression, null, null, true, null); def.classDefinition = classDefinition; ftype.definitions = new TCDefinitionList(def); return def; } private TCExplicitFunctionDefinition getEqOrdDefinition(TCPattern p1, TCPattern p2, TCExpression exp, TCNameToken fname) { LexLocation loc = p1.location; TCPatternList params = new TCPatternList(); params.add(p1); params.add(p2); TCPatternListList parameters = new TCPatternListList(); parameters.add(params); TCTypeList ptypes = new TCTypeList(); if (type instanceof TCRecordType) { // Records are xxx_R: R * R +> bool ptypes.add(new TCUnresolvedType(name)); ptypes.add(new TCUnresolvedType(name)); } else { // Named types are xxx_T: X * X +> bool, for T = X TCNamedType nt = (TCNamedType)type; ptypes.add(nt.type); ptypes.add(nt.type); } TCFunctionType ftype = new TCFunctionType(loc, ptypes, false, new TCBooleanType(loc)); TCExplicitFunctionDefinition def = new TCExplicitFunctionDefinition(null, accessSpecifier, fname, null, ftype, parameters, exp, null, null, false, null); def.classDefinition = classDefinition; ftype.definitions = new TCDefinitionList(def); return def; } private TCExplicitFunctionDefinition getMinMaxDefinition(boolean isMin, TCNameToken fname) { LexLocation loc = fname.getLocation(); TCPatternList params = new TCPatternList(); params.add(new TCIdentifierPattern(new TCNameToken(loc, loc.module, "a"))); params.add(new TCIdentifierPattern(new TCNameToken(loc, loc.module, "b"))); TCPatternListList parameters = new TCPatternListList(); parameters.add(params); TCTypeList ptypes = new TCTypeList(); ptypes.add(new TCUnresolvedType(name)); ptypes.add(new TCUnresolvedType(name)); // min_T: T * T +> T, max_T: T * T +> T TCFunctionType ftype = new TCFunctionType(loc, ptypes, false, new TCUnresolvedType(name)); TCExpression body = null; try { if (isMin) { body = parse(String.format("if a < b or a = b then a else b")); } else { body = parse(String.format("if a < b or a = b then b else a")); } } catch (Exception e) { // Never reached } TCExplicitFunctionDefinition def = new TCExplicitFunctionDefinition(null, accessSpecifier, fname, null, ftype, parameters, body, null, null, false, null); def.classDefinition = classDefinition; ftype.definitions = new TCDefinitionList(def); return def; } private TCExpression parse(String body) throws Exception { LexTokenReader ltr = new LexTokenReader(body, Dialect.VDM_SL); ExpressionReader er = new ExpressionReader(ltr); er.setCurrentModule(name.getModule()); ASTExpression ast = er.readExpression(); return ClassMapper.getInstance(TCNode.MAPPINGS).convert(ast); } @Override public boolean isRuntime() { return false; // Though the inv definition is, of course } @Override public boolean isTypeDefinition() { return true; } @Override public <R, S> R apply(TCDefinitionVisitor<R, S> visitor, S arg) { return visitor.caseTypeDefinition(this, arg); } }
gpl-3.0
memphis518/RecipeApplication
RecipeApplicationUnitTests/src/com/recipeapplication/tests/models/RecipeTest.java
6331
package com.recipeapplication.tests.models; import java.util.ArrayList; import javax.jdo.PersistenceManager; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Text; import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit; import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalBlobstoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.recipeapplication.tests.utils.FileReader; import com.recipewebservice.models.Ingredient; import com.recipewebservice.models.Recipe; import com.recipewebservice.models.RecipeImage; import com.recipewebservice.utils.PMF; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class RecipeTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig(), new LocalBlobstoreServiceTestConfig()); private Entity recipeTestEntity; private ArrayList<RecipeImage> images; private ArrayList<Ingredient> ingredients; @Before public void setUp() throws Exception { helper.setUp(); recipeTestEntity = new Entity("Recipe"); recipeTestEntity.setProperty("title", "Test Recipe"); recipeTestEntity.setProperty("directions", "These are the directions"); recipeTestEntity.setProperty("preptime", "45"); recipeTestEntity.setProperty("preptimeunit", "minutes"); recipeTestEntity.setProperty("cookingtime", "1"); recipeTestEntity.setProperty("cookingtimeunit", "hour"); recipeTestEntity.setProperty("servings", "4"); images = new ArrayList<RecipeImage>(); FileReader fr = new FileReader(); Text testImageString = new Text(fr.readImageFile("/resources/hamburger.jpeg")); RecipeImage recipeImage1 = new RecipeImage(); recipeImage1.setImage(testImageString); images.add(recipeImage1); FileReader fr2 = new FileReader(); Text testImageString2 = new Text(fr2.readImageFile("/resources/steak.jpeg")); RecipeImage recipeImage2 = new RecipeImage(); recipeImage2.setImage(testImageString2); images.add(recipeImage2); ingredients = new ArrayList<Ingredient>(); Ingredient ingredient = new Ingredient(); ingredient.setName("Pork Chops"); ingredient.setAmount(1.5); ingredient.setUnit("lbs"); ingredients.add(ingredient); Ingredient ingredient2 = new Ingredient(); ingredient2.setName("Rosemary"); ingredient2.setAmount(1); ingredient2.setUnit("twig"); ingredients.add(ingredient2); } @After public void tearDown() throws Exception { helper.tearDown(); } @Test public void testGets() { Recipe recipe = new Recipe(recipeTestEntity); assertEquals(recipe.getTitle(), recipeTestEntity.getProperty("title")); assertEquals(recipe.getDirections(), recipeTestEntity.getProperty("directions")); assertEquals(recipe.getPreptime(), recipeTestEntity.getProperty("preptime")); assertEquals(recipe.getPreptimeunit(), recipeTestEntity.getProperty("preptimeunit")); assertEquals(recipe.getCookingtime(), recipeTestEntity.getProperty("cookingtime")); assertEquals(recipe.getCookingtimeunit(), recipeTestEntity.getProperty("cookingtimeunit")); assertEquals(recipe.getServings(), recipeTestEntity.getProperty("servings")); } @Test public void testSets(){ Recipe recipe = new Recipe(); recipe.setTitle((String) recipeTestEntity.getProperty("title")); recipe.setDirections((String) recipeTestEntity.getProperty("directions")); recipe.setPreptime((String) recipeTestEntity.getProperty("preptime")); recipe.setPreptimeunit((String) recipeTestEntity.getProperty("preptimeunit")); recipe.setCookingtime((String) recipeTestEntity.getProperty("cookingtime")); recipe.setCookingtimeunit((String) recipeTestEntity.getProperty("cookingtimeunit")); recipe.setServings((String) recipeTestEntity.getProperty("servings")); Recipe recipeControl = new Recipe(recipeTestEntity); assertEquals(recipeControl, recipe); } @Test public void testImages(){ Recipe recipe = new Recipe(); recipe.setRecipeImages(images); assertEquals(images, recipe.getRecipeImages()); recipe.clearRecipeImages(); assertEquals(0, recipe.getRecipeImages().size()); recipe.addRecipeImage(images.get(0)); recipe.addRecipeImage(images.get(1)); assertEquals(images, recipe.getRecipeImages()); recipe.removeRecipeImage(1); assertEquals(1, recipe.getRecipeImages().size()); assertEquals(images.get(0), recipe.getRecipeImages().get(0)); } @Test public void testIngredients(){ Recipe recipe = new Recipe(); recipe.setIngredients(ingredients); assertEquals(ingredients, recipe.getIngredients()); recipe.clearIngredients(); assertEquals(0, recipe.getIngredients().size()); recipe.addIngredient(ingredients.get(0)); recipe.addIngredient(ingredients.get(1)); assertEquals(ingredients, recipe.getIngredients()); recipe.removeIngredient(1); assertEquals(1, recipe.getIngredients().size()); assertEquals(ingredients.get(0), recipe.getIngredients().get(0)); } @Test public void testSave1() { doSave(); } @Test public void testSave2() { doSave(); } private void doSave(){ DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("Recipe"); PreparedQuery pq = datastore.prepare(q); assertEquals(0, pq.countEntities(withLimit(10))); Query q2 = new Query("RecipeImage"); pq = datastore.prepare(q2); assertEquals(0, pq.countEntities(withLimit(10))); PersistenceManager pm = PMF.get().getPersistenceManager(); Recipe recipe = new Recipe(recipeTestEntity); recipe.setRecipeImages(images); recipe.setIngredients(ingredients); pm.makePersistent(recipe); pm.close(); PreparedQuery pq2 = datastore.prepare(q); assertEquals(1, pq2.countEntities(withLimit(10))); pq2 = datastore.prepare(q2); assertEquals(2, pq.countEntities(withLimit(10))); } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qt3d/src/quick3d/quick3drender/items/quick3dtechniquefilter.cpp
5635
/**************************************************************************** ** ** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <Qt3DQuickRender/private/quick3dtechniquefilter_p.h> QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { namespace Quick { Quick3DTechniqueFilter::Quick3DTechniqueFilter(QObject *parent) : QObject(parent) { } QQmlListProperty<QFilterKey> Quick3DTechniqueFilter::matchList() { return QQmlListProperty<QFilterKey>(this, 0, &Quick3DTechniqueFilter::appendRequire, &Quick3DTechniqueFilter::requiresCount, &Quick3DTechniqueFilter::requireAt, &Quick3DTechniqueFilter::clearRequires); } QQmlListProperty<QParameter> Quick3DTechniqueFilter::parameterList() { return QQmlListProperty<QParameter>(this, 0, &Quick3DTechniqueFilter::appendParameter, &Quick3DTechniqueFilter::parametersCount, &Quick3DTechniqueFilter::parameterAt, &Quick3DTechniqueFilter::clearParameterList); } void Quick3DTechniqueFilter::appendRequire(QQmlListProperty<QFilterKey> *list, QFilterKey *criterion) { Quick3DTechniqueFilter *filter = qobject_cast<Quick3DTechniqueFilter *>(list->object); if (filter) { criterion->setParent(filter->parentTechniqueFilter()); filter->parentTechniqueFilter()->addMatch(criterion); } } QFilterKey *Quick3DTechniqueFilter::requireAt(QQmlListProperty<QFilterKey> *list, int index) { Quick3DTechniqueFilter *filter = qobject_cast<Quick3DTechniqueFilter *>(list->object); if (filter) return filter->parentTechniqueFilter()->matchAll().at(index); return 0; } int Quick3DTechniqueFilter::requiresCount(QQmlListProperty<QFilterKey> *list) { Quick3DTechniqueFilter *filter = qobject_cast<Quick3DTechniqueFilter *>(list->object); if (filter) return filter->parentTechniqueFilter()->matchAll().size(); return 0; } void Quick3DTechniqueFilter::clearRequires(QQmlListProperty<QFilterKey> *list) { Quick3DTechniqueFilter *filter = qobject_cast<Quick3DTechniqueFilter *>(list->object); if (filter) { const auto criteria = filter->parentTechniqueFilter()->matchAll(); for (QFilterKey *criterion : criteria) filter->parentTechniqueFilter()->removeMatch(criterion); } } void Quick3DTechniqueFilter::appendParameter(QQmlListProperty<QParameter> *list, QParameter *param) { Quick3DTechniqueFilter *techniqueFilter = qobject_cast<Quick3DTechniqueFilter *>(list->object); techniqueFilter->parentTechniqueFilter()->addParameter(param); } QParameter *Quick3DTechniqueFilter::parameterAt(QQmlListProperty<QParameter> *list, int index) { Quick3DTechniqueFilter *techniqueFilter = qobject_cast<Quick3DTechniqueFilter *>(list->object); return techniqueFilter->parentTechniqueFilter()->parameters().at(index); } int Quick3DTechniqueFilter::parametersCount(QQmlListProperty<QParameter> *list) { Quick3DTechniqueFilter *techniqueFilter = qobject_cast<Quick3DTechniqueFilter *>(list->object); return techniqueFilter->parentTechniqueFilter()->parameters().count(); } void Quick3DTechniqueFilter::clearParameterList(QQmlListProperty<QParameter> *list) { Quick3DTechniqueFilter *techniqueFilter = qobject_cast<Quick3DTechniqueFilter *>(list->object); const auto parameters = techniqueFilter->parentTechniqueFilter()->parameters(); for (QParameter *p : parameters) techniqueFilter->parentTechniqueFilter()->removeParameter(p); } } // namespace Quick } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE
gpl-3.0